2 # $Id: robot.tcl,v 1.29 2001/11/14 09:15:23 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 set out [open frobots.txt w]
175 puts "creating robots.txt in $d"
177 incr status(unvisited)
181 set d [lindex $comp $len]
182 if {[string length $d]} {
183 set out [open f$d $mode]
185 if {[file isfile $d/f]} {
186 set out [open $d/f $mode]
188 set out [open f$d $mode]
192 set out [open f $mode]
202 global robotSeq robotsRunning
204 incr robotsRunning -1
205 while {$robotsRunning} {
212 proc RobotRestart {url sock} {
213 global URL robotsRunning
216 after cancel $URL($sock,cancel)
218 foreach v [array names URL $url,*] {
222 incr robotsRunning -1
228 global robotsRunning robotsMax idletime
232 set url [RobotFileNext unvisited]
233 if {![string length $url]} {
237 if {[string compare $url wait] == 0} {
238 after $idletime RobotRR
241 set r [RobotGetUrl $url {}]
243 if {$robotsRunning >= $robotsMax} return
245 incr robotsRunning -1
246 if {![RobotFileExist bad $URL($url,hostport) $URL($url,path)]} {
247 set outf [RobotFileOpen bad $URL($url,hostport) $URL($url,path)]
250 RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)
255 proc headSave {url out} {
258 if {[info exists URL($url,head,last-modified)]} {
259 puts $out "<lastmodified>$URL($url,head,last-modified)</lastmodified>"
262 if {[info exists URL($url,head,date)]} {
263 puts $out " <date>$URL($url,head,date)</date>"
265 if {[info exists URL($url,head,content-length)]} {
266 puts $out " <by>$URL($url,head,content-length)</by>"
268 if {[info exists URL($url,head,server)]} {
269 puts $out " <format>$URL($url,head,server)</format>"
272 puts $out {<publisher>}
273 puts $out " <identifier>$url</identifier>"
274 if {[info exists URL($url,head,content-type)]} {
275 puts $out " <type>$URL($url,head,content-type)</type>"
277 puts $out {</publisher>}
280 proc RobotHref {url hrefx hostx pathx} {
281 global URL domains debuglevel
286 if {$debuglevel > 1} {
287 puts "Ref input url = $url href=$href"
290 if {[string first { } $href] >= 0} {
293 if {[string length $href] > 256} {
296 if {[string first {?} $href] >= 0} {
299 if {[string first {?} $url] >= 0 && [string first {?} $href] >= 0} {
302 # get method (if any)
303 if {![regexp {^([^/:]+):(.*)} $href x method hpath]} {
307 if {[string compare $method http]} {
312 if {[regexp {^//([^/]+)([^\#]*)} $hpath x host surl]} {
313 if {![string length $surl]} {
316 if {[info exist domains]} {
318 foreach domain $domains {
319 if {[string match $domain $host]} {
329 regexp {^([^\#]*)} $hpath x surl
330 set host $URL($url,hostport)
332 if {![string length $surl]} {
335 if {[string first / $surl]} {
337 set curpath $URL($url,path)
338 if {[info exists URL($url,bpath)]} {
339 set curpath $URL($url,bpath)
341 regexp {^([^\#?]*)} $curpath x dpart
342 set l [string last / $dpart]
343 if {[expr $l >= 0]} {
344 set surl [string range $dpart 0 $l]$surl
346 set surl $dpart/$surl
349 set surllist [split $surl /]
352 foreach c $surllist {
357 set path [lrange $path 0 $pathl]
370 if {$debuglevel > 4} {
371 puts "pathl=$pathl output path=$path"
373 set path [join $path /]
374 if {![string length $path]} {
377 regsub -all {~} $path {%7E} path
378 set href "$method://$host$path"
380 if {$debuglevel > 1} {
381 puts "Ref result = $href"
383 return [checkrule url $href]
386 proc RobotError {url code} {
389 puts "Bad URL $url (code $code)"
392 if {[RobotFileExist unvisited $URL($url,hostport) $URL($url,path)]} {
393 set inf [RobotFileOpen unvisited $URL($url,hostport) $URL($url,path) r]
394 RobotReadRecord $inf fromurl distance
397 RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)
398 if {![RobotFileExist bad $URL($url,hostport) $URL($url,path)]} {
399 set outf [RobotFileOpen bad $URL($url,hostport) $URL($url,path)]
400 RobotWriteRecord $outf $fromurl $distance
405 proc RobotRedirect {url tourl code} {
408 puts "Redirecting from $url to $tourl"
412 if {[RobotFileExist unvisited $URL($url,hostport) $URL($url,path)]} {
413 set inf [RobotFileOpen unvisited $URL($url,hostport) $URL($url,path) r]
414 RobotReadRecord $inf fromurl distance
417 if {![RobotFileExist bad $URL($url,hostport) $URL($url,path)]} {
418 set outf [RobotFileOpen bad $URL($url,hostport) $URL($url,path)]
419 RobotWriteRecord $outf $fromurl $distance
422 if {[RobotHref $url tourl host path]} {
423 if {![RobotFileExist visited $host $path]} {
424 if {![RobotFileExist unvisited $host $path]} {
425 set outf [RobotFileOpen unvisited $host $path]
426 RobotWriteRecord $outf $fromurl $distance
431 set inf [RobotFileOpen visited $host $path r]
432 RobotReadRecord $inf oldurl olddistance
434 if {[string length $olddistance] == 0} {
437 if {[string length $distance] == 0} {
440 puts "distance=$distance olddistance=$olddistance"
441 if {[expr $distance < $olddistance]} {
442 set outf [RobotFileOpen unvisited $host $path]
443 RobotWriteRecord $outf $tourl $distance
448 if {[catch {RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)}]} {
454 proc link {url out href body distance} {
455 global URL maxdistance
456 if {[expr $distance > $maxdistance]} return
458 if {![RobotHref $url href host path]} return
461 puts $out "<identifier>$href</identifier>"
462 puts $out "<description>$body</description>"
465 if {![RobotFileExist visited $host $path]} {
467 if {![RobotFileExist bad $host $path]} {
468 if {[RobotFileExist unvisited $host $path]} {
469 set inf [RobotFileOpen unvisited $host $path r]
470 RobotReadRecord $inf oldurl olddistance
476 if {[string length $olddistance] == 0} {
479 if {[expr $distance < $olddistance]} {
480 set outf [RobotFileOpen unvisited $host $path]
481 RobotWriteRecord $outf $url $distance
484 } elseif {[string compare $href $url]} {
485 set inf [RobotFileOpen visited $host $path r]
486 RobotReadRecord $inf xurl olddistance
488 if {[string length $olddistance] == 0} {
491 if {[expr $distance < $olddistance]} {
492 puts "OK remarking url=$url href=$href"
493 puts "olddistance = $olddistance"
494 puts "newdistance = $distance"
495 set outf [RobotFileOpen unvisited $host $path]
496 RobotWriteRecord $outf $url $distance
502 proc RobotTextHtml {url out} {
503 global URL maxdistance
507 if {$maxdistance < 1000 && [info exists URL($url,dist)]} {
508 set fdistance $URL($url,dist)
509 set distance [expr $fdistance + 1]
511 htmlSwitch $URL($url,buf) \
513 puts $out "<title>$body</title>"
515 puts -nonewline $out "<meta"
516 foreach a [array names parm] {
517 puts -nonewline $out " $a"
518 puts -nonewline $out {="}
519 puts -nonewline $out $parm($a)
520 puts -nonewline $out {"}
524 regsub -all {<!--[^-]*->} $body { } abody
525 regsub -all -nocase {<script[^<]*</script>} $abody {} bbody
526 regsub -all {<[^\>]+>} $bbody {} nbody
527 puts $out "<documentcontent>"
529 puts $out "</documentcontent>"
531 if {![info exists parm(href)]} {
534 set href [string trim $parm(href)]
535 if {![RobotHref $url href host path]} continue
536 set URL($url,bpath) $path
538 if {![info exists parm(href)]} {
541 link $url $out [string trim $parm(href)] $body $distance
543 if {![info exists parm(href)]} {
546 link $url $out [string trim $parm(href)] $body $distance
548 if {![info exists parm(src)]} {
551 link $url $out [string trim $parm(src)] $body $fdistance
555 proc RobotsTxt {url} {
558 RobotsTxt0 URL(URL($url,hostport),robots) $URL($url,buf)
561 proc RobotsTxt0 {v buf} {
564 foreach l [split $buf \n] {
565 if {[regexp {([-A-Za-z]+):[ ]*([^\# ]+)} $l match cmd arg]} {
566 puts "cmd=$cmd arg=$arg"
567 switch -- [string tolower $cmd] {
570 set pat [string tolower $arg]*
571 set section [string match $pat $agent]
575 puts "rule [list 0 $arg]"
576 lappend $v [list 0 $arg]
581 puts "rule [list 1 $arg]"
582 lappend $v [list 1 $arg]
590 proc RobotTextPlain {url out} {
593 puts $out "<documentcontent>"
594 regsub -all {<} $URL($url,buf) {\<} content
596 puts $out "</documentcontent>"
598 if {![string compare $URL($url,path) /robots.txt]} {
603 proc RobotWriteMetadata {url out} {
609 if {[RobotFileExist unvisited $URL($url,hostport) $URL($url,path)]} {
610 set inf [RobotFileOpen unvisited $URL($url,hostport) $URL($url,path) r]
611 RobotReadRecord $inf fromurl distance
614 set URL($url,dist) $distance
615 puts $out "<distance>"
616 puts $out " $distance"
617 puts $out "</distance>"
619 puts "Parsing $url distance=$distance"
620 switch $URL($url,head,content-type) {
622 if {[string length $distance]} {
623 RobotTextHtml $url $out
627 RobotTextPlain $url $out
633 proc Robot200 {url} {
636 set out [RobotFileOpen raw $URL($url,hostport) $URL($url,path)]
637 puts -nonewline $out $URL($url,buf)
640 set out [RobotFileOpen visited $URL($url,hostport) $URL($url,path)]
641 RobotWriteMetadata $url $out
644 RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)
647 proc RobotReadContent {url sock binary} {
650 set buffer [read $sock 16384]
651 set readCount [string length $buffer]
653 if {$readCount <= 0} {
655 RobotRestart $url $sock
656 } elseif {!$binary && [string first \0 $buffer] >= 0} {
658 RobotRestart $url $sock
660 # puts "Got $readCount bytes"
661 set URL($url,buf) $URL($url,buf)$buffer
665 proc RobotReadHeader {url sock} {
666 global URL debuglevel
668 if {$debuglevel > 1} {
669 puts "HTTP head $url"
671 if {[catch {set buffer [read $sock 2148]}]} {
673 RobotRestart $url $sock
676 set readCount [string length $buffer]
678 if {$readCount <= 0} {
680 RobotRestart $url $sock
682 # puts "Got $readCount bytes"
683 set URL($url,buf) $URL($url,buf)$buffer
685 set n [string first \r\n\r\n $URL($url,buf)]
689 set headbuf [string range $URL($url,buf) 0 $n]
691 set URL($url,buf) [string range $URL($url,buf) $n end]
693 regexp {^HTTP/([0-9.]+)[ ]+([0-9]+)} $headbuf x version code
694 set lines [split $headbuf \n]
695 foreach line $lines {
696 if {[regexp {^([^:]+):[ ]+([^;]*)} $line x name value]} {
697 set URL($url,head,[string tolower $name]) [string trim $value]
700 puts "HTTP CODE $code"
701 set URL($url,state) skip
704 RobotRedirect $url $URL($url,head,location) 301
705 RobotRestart $url $sock
708 RobotRedirect $url $URL($url,head,location) 302
709 RobotRestart $url $sock
712 if {![info exists URL($url,head,content-type)]} {
713 set URL($url,head,content-type) {}
716 switch -glob -- $URL($url,head,content-type) {
721 if {![regexp {/robots.txt$} $url]} {
722 if {![checkrule mime $URL($url,head,content-type)]} {
723 RobotError $url mimedeny
724 RobotRestart $url $sock
728 fileevent $sock readable [list RobotReadContent $url $sock $binary]
731 RobotError $url $code
732 RobotRestart $url $sock
739 proc RobotSockCancel {url sock} {
741 puts "RobotSockCancel sock=$sock url=$url"
743 RobotRestart $url $sock
746 proc RobotConnect {url sock} {
747 global URL agent acceptLanguage
749 fconfigure $sock -translation {lf crlf} -blocking 0
750 fileevent $sock readable [list RobotReadHeader $url $sock]
751 puts $sock "GET $URL($url,path) HTTP/1.0"
752 puts $sock "Host: $URL($url,host)"
753 puts $sock "User-Agent: $agent"
754 if {[string length $acceptLanguage]} {
755 puts $sock "Accept-Language: $acceptLanguage"
759 set URL($sock,cancel) [after 30000 [list RobotSockCancel $url $sock]]
766 proc RobotGetUrl {url phost} {
767 global URL robotsRunning
769 puts "Retrieve $robotsRunning url=$url"
770 if {![regexp {([^:]+)://([^/]+)(.*)} $url x method hostport path]} {
773 if {![regexp {([^:]+):([0-9]+)} $hostport x host port]} {
777 set URL($url,method) $method
778 set URL($url,host) $host
779 set URL($url,hostport) $hostport
780 set URL($url,path) $path
781 set URL($url,state) head
784 if {[string compare $path /robots.txt]} {
786 if {![info exists URL($hostport,robots)]} {
787 puts "READING robots.txt for host $hostport"
788 if {[RobotFileExist visited $hostport /robots.txt]} {
789 set inf [RobotFileOpen visited $hostport /robots.txt r]
790 set buf [read $inf 32768]
793 set buf "User-agent: *\nAllow: /\n"
795 RobotsTxt0 URL($hostport,robots) $buf
797 if {[info exists URL($hostport,robots)]} {
798 foreach l $URL($hostport,robots) {
799 if {[string first [lindex $l 1] $path] == 0} {
806 puts "skipped due to robots.txt"
810 if [catch {set sock [socket -async $host $port]}] {
813 RobotConnect $url $sock
818 if {![llength [info commands htmlSwitch]]} {
819 set e [info sharedlibextension]
820 if {[catch {load ./tclrobot$e}]} {
825 set agent "zmbot/0.1"
826 if {![catch {set os [exec uname -s -r]}]} {
827 set agent "$agent ($os)"
842 set acceptLanguage {}
844 set status(unvisited) 0
845 set status(visited) 0
850 # Rules: allow, deny, url
852 proc checkrule {type this} {
856 if {$debuglevel > 3} {
857 puts "CHECKRULE $type $this"
859 if {[info exist alrules]} {
861 if {$debuglevel > 3} {
865 if {[lindex $l 1] != $type} continue
866 # consider mask (! negates)
867 set masks [lindex $l 2]
869 foreach mask $masks {
870 if {$debuglevel > 4} {
871 puts "consider single mask $mask"
873 if {[string index $mask 0] == "!"} {
874 set mask [string range $mask 1 end]
875 if {[string match $mask $this]} continue
877 if {![string match $mask $this]} continue
881 if {$debuglevel > 4} {
885 # OK, we have a match
886 if {[lindex $l 0] == "allow"} {
887 if {$debuglevel > 3} {
888 puts "CHECKRULE MATCH OK"
892 if {$debuglevel > 3} {
893 puts "CHECKFULE MATCH FAIL"
899 if {$debuglevel > 3} {
900 puts "CHECKRULE MATCH OK"
909 if {[RobotHref http://www.indexdata.dk/ href host path]} {
910 if {![RobotFileExist visited $host $path]} {
911 set outf [RobotFileOpen unvisited $host $path]
912 RobotWriteRecord $outf href 0
918 proc deny {type stuff} {
921 lappend alrules [list deny $type $stuff]
924 proc allow {type stuff} {
927 lappend alrules [list allow $type $stuff]
933 set debuglevel $level
939 set l [llength $argv]
942 puts {tclrobot: usage:}
943 puts {tclrobot [-j jobs] [-i idle] [-c count] [-d domain] [-r rules] [url ..]}
944 puts " Example: -c 3 -d '*.dk' http://www.indexdata.dk/"
949 set arg [lindex $argv $i]
950 switch -glob -- $arg {
952 set robotsMax [string range $arg 2 end]
953 if {![string length $robotsMax]} {
954 set robotsMax [lindex $argv [incr i]]
958 set maxdistance [string range $arg 2 end]
959 if {![string length $maxdistance]} {
960 set maxdistance [lindex $argv [incr i]]
964 set dom [string range $arg 2 end]
965 if {![string length $dom]} {
966 set dom [lindex $argv [incr i]]
971 set idletime [string range $arg 2 end]
972 if {![string length $idletime]} {
973 set idletime [lindex $argv [incr i]]
977 set acceptLanguage [string range $arg 2 end]
978 if {![string length $acceptLanguage]} {
979 set acceptLanguage [lindex $argv [incr i]]
983 set rfile [string range $arg 2 end]
984 if {![string length $rfile]} {
985 set rfile [lindex $argv [incr i]]
991 if {[RobotHref http://www.indexdata.dk/ href host path]} {
992 if {![RobotFileExist visited $host $path]} {
993 set outf [RobotFileOpen unvisited $host $path]
994 RobotWriteRecord $outf href 0
1003 if {![info exist domains]} {
1006 if {![info exist maxdistance]} {
1009 if {![info exist robotsMax]} {
1013 puts "domains=$domains"
1014 puts "max distance=$maxdistance"
1015 puts "max jobs=$robotsMax"
1021 while {$robotsRunning} {
1025 set statusfile [open status w]
1026 puts $statusfile "$status(unvisited) $status(bad) $status(visited)"