2 # $Id: robot.tcl,v 1.34 2002/06/18 19:57:53 adam Exp $
4 proc RobotFileNext1 {area lead} {
5 # puts "RobotFileNext1 area=$area lead=$lead"
6 if {[catch {set ns [glob ${area}/*]}]} {
10 if {[file isfile $n]} {
11 set off [string last / $n]
13 return $lead/[string range $n $off end]
17 if {[file isdirectory $n]} {
18 set off [string last / $n]
20 set sb [RobotFileNext1 $n $lead/[string range $n $off end]]
21 if {[string length $sb]} {
29 proc RobotWriteRecord {outf fromurl distance} {
31 puts $outf "<distance>"
33 puts $outf "</distance>"
34 puts $outf "<fromurl>"
36 puts $outf "</fromurl>"
40 proc RobotReadRecord {inf fromurlx distancex} {
41 upvar $fromurlx fromurl
42 upvar $distancex distance
45 set distance [string trim [gets $inf]]
46 # puts "got distance = $distance"
49 set fromurl [string trim [gets $inf]]
52 proc RobotFileNext {area} {
57 # puts "RobotFileNext robotSeq=$robotSeq"
62 if {[catch {set ns [glob ${area}/*]}]} {
66 set off [string length $area]
68 set n [lindex $ns $robotSeq]
69 if {![string length $n]} {
72 set statusfile [open status w]
73 puts $statusfile "$status(unvisited) $status(bad) $status(visited)"
78 if {[file isfile $n/frobots.txt]} {
79 puts "ok returning http://[string range $n $off end]/robots.txt"
80 return http://[string range $n $off end]/robots.txt
81 } elseif {[file isdirectory $n]} {
82 set sb [RobotFileNext1 $n http://[string range $n $off end]]
83 if {[string length $sb]} {
87 puts "no more work at end of RobotFileNext n=$n"
93 proc RobotFileExist {area host path} {
96 if {$debuglevel > 3} {
97 puts "RobotFileExist begin area=$area host=$host path=$path"
99 set lpath [split $path /]
100 set l [llength $lpath]
102 set t [lindex $lpath $l]
104 set npath $area/$host[join [lrange $lpath 0 $l] /d]/f$t
105 if {$debuglevel > 3} {
106 puts "RobotFileExist end npath=$npath"
108 return [file exists $npath]
111 proc RobotFileUnlink {area host path} {
113 # puts "RobotFileUnlink begin"
114 # puts "area=$area host=$host path=$path"
115 set lpath [split $path /]
116 set l [llength $lpath]
118 set t [lindex $lpath $l]
120 set npath $area/$host[join [lrange $lpath 0 $l] /d]/f$t
121 # puts "npath=$npath"
122 set comp [split $npath /]
123 if {[catch {exec rm [join $comp /]}]} return
125 set l [llength $comp]
128 incr status($area) -1
129 for {set i $l} {$i > 0} {incr i -1} {
130 set path [join [lrange $comp 0 $i] /]
131 if {![catch {glob $path/*}]} return
134 # puts "RobotFileUnlink end"
137 proc RobotFileClose {out} {
138 if [string compare $out stdout] {
143 proc RobotFileOpen {area host path {mode w}} {
149 if {![info exists workdir]} {
152 if {$debuglevel > 3} {
153 puts "RobotFileOpen orgPwd=$orgPwd area=$area host=$host path=$path mode=$mode"
155 if {[string compare $orgPwd $workdir]} {
156 puts "ooops. RobotFileOpen failed"
157 puts "workdir = $workdir"
161 set comp [split $area/$host$path /]
162 set len [llength $comp]
164 for {set i 0} {$i < $len} {incr i} {
166 set d "d[lindex $comp $i]"
168 set d [lindex $comp $i]
170 if {[catch {cd ./$d}]} {
173 if {![string compare $area unvisited] && $i == 1 && $mode == "w"} {
174 if {[string compare $path /robots.txt]} {
175 set out [open frobots.txt w]
176 puts "creating robots.txt in $d"
178 incr status(unvisited)
183 set d [lindex $comp $len]
184 if {[string length $d]} {
185 set out [open f$d $mode]
187 set out [open f $mode]
197 global robotSeq robotsRunning
199 incr robotsRunning -1
200 while {$robotsRunning} {
207 proc RobotRestart {url sock} {
208 global URL robotsRunning
211 after cancel $URL($sock,cancel)
213 foreach v [array names URL $url,*] {
217 incr robotsRunning -1
223 global robotsRunning robotsMax idletime
227 set url [RobotFileNext unvisited]
228 if {![string length $url]} {
232 if {[string compare $url wait] == 0} {
233 after $idletime RobotRR
236 set r [RobotGetUrl $url {}]
238 if {$robotsRunning >= $robotsMax} return
240 incr robotsRunning -1
241 if {![RobotFileExist bad $URL($url,hostport) $URL($url,path)]} {
242 set outf [RobotFileOpen bad $URL($url,hostport) $URL($url,path)]
245 RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)
250 proc headSave {url out} {
253 if {[info exists URL($url,head,last-modified)]} {
254 puts $out "<lastmodified>$URL($url,head,last-modified)</lastmodified>"
257 if {[info exists URL($url,head,date)]} {
258 puts $out " <date>$URL($url,head,date)</date>"
260 if {[info exists URL($url,head,content-length)]} {
261 puts $out " <by>$URL($url,head,content-length)</by>"
263 if {[info exists URL($url,head,server)]} {
264 puts $out " <format>$URL($url,head,server)</format>"
267 puts $out {<publisher>}
268 puts $out " <identifier>$url</identifier>"
269 if {[info exists URL($url,head,content-type)]} {
270 puts $out " <type>$URL($url,head,content-type)</type>"
272 puts $out {</publisher>}
275 proc RobotHref {url hrefx hostx pathx} {
276 global URL domains debuglevel
281 if {$debuglevel > 1} {
282 puts "Ref input url = $url href=$href"
285 if {[string first { } $href] >= 0} {
288 if {[string length $href] > 256} {
292 # Skip pages that have ? in them
293 # if {[string first {?} $url] >= 0 && [string first {?} $href] >= 0} {
296 # get method (if any)
297 if {![regexp {^([^/:]+):(.*)} $href x method hpath]} {
301 if {[string compare $method http]} {
306 if {[regexp {^//([^/]+)([^\#]*)} $hpath x host surl]} {
307 if {![string length $surl]} {
310 if {[info exist domains]} {
312 foreach domain $domains {
313 if {[string match $domain $host]} {
323 regexp {^([^\#]*)} $hpath x surl
324 set host $URL($url,hostport)
326 if {![string length $surl]} {
329 if {[string first / $surl]} {
331 set curpath $URL($url,path)
332 if {[info exists URL($url,bpath)]} {
333 set curpath $URL($url,bpath)
335 regexp {^([^\#?]*)} $curpath x dpart
336 set l [string last / $dpart]
337 if {[expr $l >= 0]} {
338 set surl [string range $dpart 0 $l]$surl
340 set surl $dpart/$surl
343 set surllist [split $surl /]
346 foreach c $surllist {
351 set path [lrange $path 0 $pathl]
364 if {$debuglevel > 4} {
365 puts "pathl=$pathl output path=$path"
367 set path [join $path /]
368 if {![string length $path]} {
371 regsub -all {~} $path {%7E} path
372 set href "$method://$host$path"
374 if {$debuglevel > 1} {
375 puts "Ref result = $href"
377 return [checkrule url $href]
380 proc RobotError {url code} {
383 puts "Bad URL $url (code $code)"
386 if {[RobotFileExist unvisited $URL($url,hostport) $URL($url,path)]} {
387 set inf [RobotFileOpen unvisited $URL($url,hostport) $URL($url,path) r]
388 RobotReadRecord $inf fromurl distance
391 RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)
392 if {![RobotFileExist bad $URL($url,hostport) $URL($url,path)]} {
393 set outf [RobotFileOpen bad $URL($url,hostport) $URL($url,path)]
394 RobotWriteRecord $outf $fromurl $distance
399 proc RobotRedirect {url tourl code} {
402 puts "Redirecting from $url to $tourl"
406 if {[RobotFileExist unvisited $URL($url,hostport) $URL($url,path)]} {
407 set inf [RobotFileOpen unvisited $URL($url,hostport) $URL($url,path) r]
408 RobotReadRecord $inf fromurl distance
411 if {![RobotFileExist bad $URL($url,hostport) $URL($url,path)]} {
412 set outf [RobotFileOpen bad $URL($url,hostport) $URL($url,path)]
413 RobotWriteRecord $outf $fromurl $distance
416 if {[RobotHref $url tourl host path]} {
417 if {![RobotFileExist visited $host $path]} {
418 if {![RobotFileExist unvisited $host $path]} {
419 set outf [RobotFileOpen unvisited $host $path]
420 RobotWriteRecord $outf $fromurl $distance
425 set inf [RobotFileOpen visited $host $path r]
426 RobotReadRecord $inf oldurl olddistance
428 if {[string length $olddistance] == 0} {
431 if {[string length $distance] == 0} {
434 puts "distance=$distance olddistance=$olddistance"
435 if {[expr $distance < $olddistance]} {
436 set outf [RobotFileOpen unvisited $host $path]
437 RobotWriteRecord $outf $tourl $distance
442 if {[catch {RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)}]} {
448 proc link {url out href body distance} {
449 global URL maxdistance
450 if {[expr $distance > $maxdistance]} return
452 if {![RobotHref $url href host path]} return
455 puts $out "<identifier>$href</identifier>"
456 puts $out "<description>$body</description>"
459 if {![RobotFileExist visited $host $path]} {
461 if {![RobotFileExist bad $host $path]} {
462 if {[RobotFileExist unvisited $host $path]} {
463 set inf [RobotFileOpen unvisited $host $path r]
464 RobotReadRecord $inf oldurl olddistance
470 if {[string length $olddistance] == 0} {
473 if {[expr $distance < $olddistance]} {
474 set outf [RobotFileOpen unvisited $host $path]
475 RobotWriteRecord $outf $url $distance
478 } elseif {[string compare $href $url]} {
479 set inf [RobotFileOpen visited $host $path r]
480 RobotReadRecord $inf xurl olddistance
482 if {[string length $olddistance] == 0} {
485 if {[expr $distance < $olddistance]} {
486 puts "OK remarking url=$url href=$href"
487 puts "olddistance = $olddistance"
488 puts "newdistance = $distance"
489 set outf [RobotFileOpen unvisited $host $path]
490 RobotWriteRecord $outf $url $distance
496 proc RobotTextHtml {url out} {
497 global URL maxdistance
499 # set title so we can emit it for the body
501 # if true, nothing will be indexed
503 # if true, nothing will be followed
508 if {$maxdistance < 1000 && [info exists URL($url,dist)]} {
509 set fdistance $URL($url,dist)
510 set distance [expr $fdistance + 1]
512 htmlSwitch $URL($url,buf) \
516 # collect metadata and save NAME= CONTENT=..
519 puts -nonewline $out "<meta"
520 set al [array names parm]
522 set al [string tolower $a]
523 puts -nonewline $out " $al"
524 puts -nonewline $out {="}
525 puts -nonewline $out $parm($a)
526 puts -nonewline $out {"}
529 set metaname [string tolower $parm($a)]
532 set metacontent $parm($a)
538 # go through robots directives (af any)
539 if {![string compare $metaname robots]} {
540 set direcs [split [string tolower $metacontent] ,]
541 if {[lsearch $direcs noindex] >= 0} {
544 if {[lsearch $direcs nofollow] >= 0} {
549 # don't print title of document content if noindex is used
551 puts $out "<title>$title</title>"
552 regsub -all {<!--[^-]*-->} $body { } abody
553 regsub -all -nocase {<script[^<]*</script>} $abody {} bbody
554 regsub -all {<[^\>]+>} $bbody {} nbody
555 puts $out "<documentcontent>"
557 puts $out "</documentcontent>"
561 if {![info exists parm(href)]} {
564 set href [string trim $parm(href)]
565 if {![RobotHref $url href host path]} continue
566 set URL($url,bpath) $path
568 # <a href="...."> .. </a>
569 # we're not using nonest - otherwise body isn't set
570 if {$nofollow} continue
571 if {![info exists parm(href)]} {
574 link $url $out [string trim $parm(href)] $body $distance
576 if {$nofollow} continue
577 if {![info exists parm(href)]} {
580 link $url $out [string trim $parm(href)] $body $distance
582 if {![info exists parm(src)]} {
585 link $url $out [string trim $parm(src)] $body $fdistance
589 proc RobotsTxt {url} {
592 RobotsTxt0 URL(URL($url,hostport),robots) $URL($url,buf)
595 proc RobotsTxt0 {v buf} {
598 foreach l [split $buf \n] {
599 if {[regexp {([-A-Za-z]+):[ ]*([^\# ]+)} $l match cmd arg]} {
600 puts "cmd=$cmd arg=$arg"
601 switch -- [string tolower $cmd] {
604 set pat [string tolower $arg]*
605 set section [string match $pat $agent]
609 puts "rule [list 0 $arg]"
610 lappend $v [list 0 $arg]
615 puts "rule [list 1 $arg]"
616 lappend $v [list 1 $arg]
624 proc RobotTextPlain {url out} {
627 puts $out "<documentcontent>"
628 regsub -all {<} $URL($url,buf) {\<} content
630 puts $out "</documentcontent>"
632 if {![string compare $URL($url,path) /robots.txt]} {
637 proc RobotWriteMetadata {url out} {
643 if {[RobotFileExist unvisited $URL($url,hostport) $URL($url,path)]} {
644 set inf [RobotFileOpen unvisited $URL($url,hostport) $URL($url,path) r]
645 RobotReadRecord $inf fromurl distance
648 set URL($url,dist) $distance
649 puts $out "<distance>"
650 puts $out " $distance"
651 puts $out "</distance>"
653 puts "Parsing $url distance=$distance"
654 switch $URL($url,head,content-type) {
656 if {[string length $distance]} {
657 RobotTextHtml $url $out
661 RobotTextPlain $url $out
667 proc Robot200 {url} {
670 set out [RobotFileOpen raw $URL($url,hostport) $URL($url,path)]
671 puts -nonewline $out $URL($url,buf)
674 set out [RobotFileOpen visited $URL($url,hostport) $URL($url,path)]
675 RobotWriteMetadata $url $out
678 RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)
681 proc RobotReadContent {url sock binary} {
684 set buffer [read $sock 16384]
685 set readCount [string length $buffer]
687 if {$readCount <= 0} {
689 RobotRestart $url $sock
690 } elseif {!$binary && [string first \0 $buffer] >= 0} {
692 RobotRestart $url $sock
694 # puts "Got $readCount bytes"
695 set URL($url,buf) $URL($url,buf)$buffer
699 proc RobotReadHeader {url sock} {
700 global URL debuglevel
702 if {$debuglevel > 1} {
703 puts "HTTP head $url"
705 if {[catch {set buffer [read $sock 2148]}]} {
707 RobotRestart $url $sock
710 set readCount [string length $buffer]
712 if {$readCount <= 0} {
714 RobotRestart $url $sock
716 # puts "Got $readCount bytes"
717 set URL($url,buf) $URL($url,buf)$buffer
719 set n [string first \r\n\r\n $URL($url,buf)]
723 set headbuf [string range $URL($url,buf) 0 $n]
725 set URL($url,buf) [string range $URL($url,buf) $n end]
727 regexp {^HTTP/([0-9.]+)[ ]+([0-9]+)} $headbuf x version code
728 set lines [split $headbuf \n]
729 foreach line $lines {
730 if {[regexp {^([^:]+):[ ]+([^;]*)} $line x name value]} {
731 set URL($url,head,[string tolower $name]) [string trim $value]
734 puts "HTTP CODE $code"
735 set URL($url,state) skip
738 RobotRedirect $url $URL($url,head,location) 301
739 RobotRestart $url $sock
742 RobotRedirect $url $URL($url,head,location) 302
743 RobotRestart $url $sock
746 if {![info exists URL($url,head,content-type)]} {
747 set URL($url,head,content-type) {}
750 switch -glob -- $URL($url,head,content-type) {
755 if {![regexp {/robots.txt$} $url]} {
756 if {![checkrule mime $URL($url,head,content-type)]} {
757 RobotError $url mimedeny
758 RobotRestart $url $sock
762 fileevent $sock readable [list RobotReadContent $url $sock $binary]
765 RobotError $url $code
766 RobotRestart $url $sock
773 proc RobotSockCancel {url sock} {
775 puts "RobotSockCancel sock=$sock url=$url"
777 RobotRestart $url $sock
780 proc RobotConnect {url sock} {
781 global URL agent acceptLanguage
783 fconfigure $sock -translation {lf crlf} -blocking 0
784 fileevent $sock readable [list RobotReadHeader $url $sock]
785 puts $sock "GET $URL($url,path) HTTP/1.0"
786 puts $sock "Host: $URL($url,host)"
787 puts $sock "User-Agent: $agent"
788 if {[string length $acceptLanguage]} {
789 puts $sock "Accept-Language: $acceptLanguage"
793 set URL($sock,cancel) [after 30000 [list RobotSockCancel $url $sock]]
800 proc RobotGetUrl {url phost} {
801 global URL robotsRunning
803 puts "Retrieve $robotsRunning url=$url"
804 if {![regexp {([^:]+)://([^/]+)(.*)} $url x method hostport path]} {
807 if {![regexp {([^:]+):([0-9]+)} $hostport x host port]} {
811 set URL($url,method) $method
812 set URL($url,host) $host
813 set URL($url,hostport) $hostport
814 set URL($url,path) $path
815 set URL($url,state) head
818 if {[string compare $path /robots.txt]} {
820 if {![info exists URL($hostport,robots)]} {
821 puts "READING robots.txt for host $hostport"
822 if {[RobotFileExist visited $hostport /robots.txt]} {
823 set inf [RobotFileOpen visited $hostport /robots.txt r]
824 set buf [read $inf 32768]
827 set buf "User-agent: *\nAllow: /\n"
829 RobotsTxt0 URL($hostport,robots) $buf
831 if {[info exists URL($hostport,robots)]} {
832 foreach l $URL($hostport,robots) {
833 if {[string first [lindex $l 1] $path] == 0} {
840 puts "skipped due to robots.txt"
844 if [catch {set sock [socket -async $host $port]}] {
847 RobotConnect $url $sock
852 if {![llength [info commands htmlSwitch]]} {
853 set e [info sharedlibextension]
854 if {[catch {load ./tclrobot$e}]} {
859 set agent "zmbot/0.1"
860 if {![catch {set os [exec uname -s -r]}]} {
861 set agent "$agent ($os)"
876 set acceptLanguage {}
878 set status(unvisited) 0
879 set status(visited) 0
884 # Rules: allow, deny, url
886 proc checkrule {type this} {
890 if {$debuglevel > 3} {
891 puts "CHECKRULE $type $this"
893 if {[info exist alrules]} {
895 if {$debuglevel > 3} {
899 if {[lindex $l 1] != $type} continue
900 # consider mask (! negates)
901 set masks [lindex $l 2]
903 foreach mask $masks {
904 if {$debuglevel > 4} {
905 puts "consider single mask $mask"
907 if {[string index $mask 0] == "!"} {
908 set mask [string range $mask 1 end]
909 if {[string match $mask $this]} continue
911 if {![string match $mask $this]} continue
915 if {$debuglevel > 4} {
919 # OK, we have a match
920 if {[lindex $l 0] == "allow"} {
921 if {$debuglevel > 3} {
922 puts "CHECKRULE MATCH OK"
926 if {$debuglevel > 3} {
927 puts "CHECKFULE MATCH FAIL"
933 if {$debuglevel > 3} {
934 puts "CHECKRULE MATCH OK"
943 if {[RobotHref http://www.indexdata.dk/ href host path]} {
944 if {![RobotFileExist visited $host $path]} {
945 set outf [RobotFileOpen unvisited $host $path]
946 RobotWriteRecord $outf href 0
952 proc deny {type stuff} {
955 lappend alrules [list deny $type $stuff]
958 proc allow {type stuff} {
961 lappend alrules [list allow $type $stuff]
967 set debuglevel $level
973 set l [llength $argv]
976 puts {tclrobot: usage:}
977 puts {tclrobot [-j jobs] [-i idle] [-c count] [-d domain] [-r rules] [url ..]}
978 puts " Example: -c 3 -d '*.dk' http://www.indexdata.dk/"
983 set arg [lindex $argv $i]
984 switch -glob -- $arg {
986 set robotsMax [string range $arg 2 end]
987 if {![string length $robotsMax]} {
988 set robotsMax [lindex $argv [incr i]]
992 set maxdistance [string range $arg 2 end]
993 if {![string length $maxdistance]} {
994 set maxdistance [lindex $argv [incr i]]
998 set dom [string range $arg 2 end]
999 if {![string length $dom]} {
1000 set dom [lindex $argv [incr i]]
1002 lappend domains $dom
1005 set idletime [string range $arg 2 end]
1006 if {![string length $idletime]} {
1007 set idletime [lindex $argv [incr i]]
1011 set acceptLanguage [string range $arg 2 end]
1012 if {![string length $acceptLanguage]} {
1013 set acceptLanguage [lindex $argv [incr i]]
1017 set rfile [string range $arg 2 end]
1018 if {![string length $rfile]} {
1019 set rfile [lindex $argv [incr i]]
1025 if {[RobotHref http://www.indexdata.dk/ href host path]} {
1026 if {![RobotFileExist visited $host $path]} {
1027 set outf [RobotFileOpen unvisited $host $path]
1028 RobotWriteRecord $outf href 0
1029 RobotFileClose $outf
1037 if {![info exist domains]} {
1040 if {![info exist maxdistance]} {
1043 if {![info exist robotsMax]} {
1047 puts "domains=$domains"
1048 puts "max distance=$maxdistance"
1049 puts "max jobs=$robotsMax"
1055 while {$robotsRunning} {
1059 set statusfile [open status w]
1060 puts $statusfile "$status(unvisited) $status(bad) $status(visited)"