2 # $Id: robot.tcl,v 1.33 2002/03/25 16:13:21 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 foreach a [array names parm] {
521 set al [string tolower $a]
522 puts -nonewline $out " $al"
523 puts -nonewline $out {="}
524 puts -nonewline $out $parm($a)
525 puts -nonewline $out {"}
528 set metaname [string tolower $parm($a)]
531 set metacontent $parm($a)
536 # go through robots directives (af any)
537 if {![string compare $metaname robots]} {
538 set direcs [split [string tolower $metacontent] ,]
539 if {[lsearch $direcs noindex] >= 0} {
542 if {[lsearch $direcs nofollow] >= 0} {
547 # don't print title of document content if noindex is used
549 puts $out "<title>$title</title>"
550 regsub -all {<!--[^-]*-->} $body { } abody
551 regsub -all -nocase {<script[^<]*</script>} $abody {} bbody
552 regsub -all {<[^\>]+>} $bbody {} nbody
553 puts $out "<documentcontent>"
555 puts $out "</documentcontent>"
559 if {![info exists parm(href)]} {
562 set href [string trim $parm(href)]
563 if {![RobotHref $url href host path]} continue
564 set URL($url,bpath) $path
566 # <a href="...."> .. </a>
567 # we're not using nonest - otherwise body isn't set
568 if {$nofollow} continue
569 if {![info exists parm(href)]} {
572 link $url $out [string trim $parm(href)] $body $distance
574 if {$nofollow} continue
575 if {![info exists parm(href)]} {
578 link $url $out [string trim $parm(href)] $body $distance
580 if {![info exists parm(src)]} {
583 link $url $out [string trim $parm(src)] $body $fdistance
587 proc RobotsTxt {url} {
590 RobotsTxt0 URL(URL($url,hostport),robots) $URL($url,buf)
593 proc RobotsTxt0 {v buf} {
596 foreach l [split $buf \n] {
597 if {[regexp {([-A-Za-z]+):[ ]*([^\# ]+)} $l match cmd arg]} {
598 puts "cmd=$cmd arg=$arg"
599 switch -- [string tolower $cmd] {
602 set pat [string tolower $arg]*
603 set section [string match $pat $agent]
607 puts "rule [list 0 $arg]"
608 lappend $v [list 0 $arg]
613 puts "rule [list 1 $arg]"
614 lappend $v [list 1 $arg]
622 proc RobotTextPlain {url out} {
625 puts $out "<documentcontent>"
626 regsub -all {<} $URL($url,buf) {\<} content
628 puts $out "</documentcontent>"
630 if {![string compare $URL($url,path) /robots.txt]} {
635 proc RobotWriteMetadata {url out} {
641 if {[RobotFileExist unvisited $URL($url,hostport) $URL($url,path)]} {
642 set inf [RobotFileOpen unvisited $URL($url,hostport) $URL($url,path) r]
643 RobotReadRecord $inf fromurl distance
646 set URL($url,dist) $distance
647 puts $out "<distance>"
648 puts $out " $distance"
649 puts $out "</distance>"
651 puts "Parsing $url distance=$distance"
652 switch $URL($url,head,content-type) {
654 if {[string length $distance]} {
655 RobotTextHtml $url $out
659 RobotTextPlain $url $out
665 proc Robot200 {url} {
668 set out [RobotFileOpen raw $URL($url,hostport) $URL($url,path)]
669 puts -nonewline $out $URL($url,buf)
672 set out [RobotFileOpen visited $URL($url,hostport) $URL($url,path)]
673 RobotWriteMetadata $url $out
676 RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)
679 proc RobotReadContent {url sock binary} {
682 set buffer [read $sock 16384]
683 set readCount [string length $buffer]
685 if {$readCount <= 0} {
687 RobotRestart $url $sock
688 } elseif {!$binary && [string first \0 $buffer] >= 0} {
690 RobotRestart $url $sock
692 # puts "Got $readCount bytes"
693 set URL($url,buf) $URL($url,buf)$buffer
697 proc RobotReadHeader {url sock} {
698 global URL debuglevel
700 if {$debuglevel > 1} {
701 puts "HTTP head $url"
703 if {[catch {set buffer [read $sock 2148]}]} {
705 RobotRestart $url $sock
708 set readCount [string length $buffer]
710 if {$readCount <= 0} {
712 RobotRestart $url $sock
714 # puts "Got $readCount bytes"
715 set URL($url,buf) $URL($url,buf)$buffer
717 set n [string first \r\n\r\n $URL($url,buf)]
721 set headbuf [string range $URL($url,buf) 0 $n]
723 set URL($url,buf) [string range $URL($url,buf) $n end]
725 regexp {^HTTP/([0-9.]+)[ ]+([0-9]+)} $headbuf x version code
726 set lines [split $headbuf \n]
727 foreach line $lines {
728 if {[regexp {^([^:]+):[ ]+([^;]*)} $line x name value]} {
729 set URL($url,head,[string tolower $name]) [string trim $value]
732 puts "HTTP CODE $code"
733 set URL($url,state) skip
736 RobotRedirect $url $URL($url,head,location) 301
737 RobotRestart $url $sock
740 RobotRedirect $url $URL($url,head,location) 302
741 RobotRestart $url $sock
744 if {![info exists URL($url,head,content-type)]} {
745 set URL($url,head,content-type) {}
748 switch -glob -- $URL($url,head,content-type) {
753 if {![regexp {/robots.txt$} $url]} {
754 if {![checkrule mime $URL($url,head,content-type)]} {
755 RobotError $url mimedeny
756 RobotRestart $url $sock
760 fileevent $sock readable [list RobotReadContent $url $sock $binary]
763 RobotError $url $code
764 RobotRestart $url $sock
771 proc RobotSockCancel {url sock} {
773 puts "RobotSockCancel sock=$sock url=$url"
775 RobotRestart $url $sock
778 proc RobotConnect {url sock} {
779 global URL agent acceptLanguage
781 fconfigure $sock -translation {lf crlf} -blocking 0
782 fileevent $sock readable [list RobotReadHeader $url $sock]
783 puts $sock "GET $URL($url,path) HTTP/1.0"
784 puts $sock "Host: $URL($url,host)"
785 puts $sock "User-Agent: $agent"
786 if {[string length $acceptLanguage]} {
787 puts $sock "Accept-Language: $acceptLanguage"
791 set URL($sock,cancel) [after 30000 [list RobotSockCancel $url $sock]]
798 proc RobotGetUrl {url phost} {
799 global URL robotsRunning
801 puts "Retrieve $robotsRunning url=$url"
802 if {![regexp {([^:]+)://([^/]+)(.*)} $url x method hostport path]} {
805 if {![regexp {([^:]+):([0-9]+)} $hostport x host port]} {
809 set URL($url,method) $method
810 set URL($url,host) $host
811 set URL($url,hostport) $hostport
812 set URL($url,path) $path
813 set URL($url,state) head
816 if {[string compare $path /robots.txt]} {
818 if {![info exists URL($hostport,robots)]} {
819 puts "READING robots.txt for host $hostport"
820 if {[RobotFileExist visited $hostport /robots.txt]} {
821 set inf [RobotFileOpen visited $hostport /robots.txt r]
822 set buf [read $inf 32768]
825 set buf "User-agent: *\nAllow: /\n"
827 RobotsTxt0 URL($hostport,robots) $buf
829 if {[info exists URL($hostport,robots)]} {
830 foreach l $URL($hostport,robots) {
831 if {[string first [lindex $l 1] $path] == 0} {
838 puts "skipped due to robots.txt"
842 if [catch {set sock [socket -async $host $port]}] {
845 RobotConnect $url $sock
850 if {![llength [info commands htmlSwitch]]} {
851 set e [info sharedlibextension]
852 if {[catch {load ./tclrobot$e}]} {
857 set agent "zmbot/0.1"
858 if {![catch {set os [exec uname -s -r]}]} {
859 set agent "$agent ($os)"
874 set acceptLanguage {}
876 set status(unvisited) 0
877 set status(visited) 0
882 # Rules: allow, deny, url
884 proc checkrule {type this} {
888 if {$debuglevel > 3} {
889 puts "CHECKRULE $type $this"
891 if {[info exist alrules]} {
893 if {$debuglevel > 3} {
897 if {[lindex $l 1] != $type} continue
898 # consider mask (! negates)
899 set masks [lindex $l 2]
901 foreach mask $masks {
902 if {$debuglevel > 4} {
903 puts "consider single mask $mask"
905 if {[string index $mask 0] == "!"} {
906 set mask [string range $mask 1 end]
907 if {[string match $mask $this]} continue
909 if {![string match $mask $this]} continue
913 if {$debuglevel > 4} {
917 # OK, we have a match
918 if {[lindex $l 0] == "allow"} {
919 if {$debuglevel > 3} {
920 puts "CHECKRULE MATCH OK"
924 if {$debuglevel > 3} {
925 puts "CHECKFULE MATCH FAIL"
931 if {$debuglevel > 3} {
932 puts "CHECKRULE MATCH OK"
941 if {[RobotHref http://www.indexdata.dk/ href host path]} {
942 if {![RobotFileExist visited $host $path]} {
943 set outf [RobotFileOpen unvisited $host $path]
944 RobotWriteRecord $outf href 0
950 proc deny {type stuff} {
953 lappend alrules [list deny $type $stuff]
956 proc allow {type stuff} {
959 lappend alrules [list allow $type $stuff]
965 set debuglevel $level
971 set l [llength $argv]
974 puts {tclrobot: usage:}
975 puts {tclrobot [-j jobs] [-i idle] [-c count] [-d domain] [-r rules] [url ..]}
976 puts " Example: -c 3 -d '*.dk' http://www.indexdata.dk/"
981 set arg [lindex $argv $i]
982 switch -glob -- $arg {
984 set robotsMax [string range $arg 2 end]
985 if {![string length $robotsMax]} {
986 set robotsMax [lindex $argv [incr i]]
990 set maxdistance [string range $arg 2 end]
991 if {![string length $maxdistance]} {
992 set maxdistance [lindex $argv [incr i]]
996 set dom [string range $arg 2 end]
997 if {![string length $dom]} {
998 set dom [lindex $argv [incr i]]
1000 lappend domains $dom
1003 set idletime [string range $arg 2 end]
1004 if {![string length $idletime]} {
1005 set idletime [lindex $argv [incr i]]
1009 set acceptLanguage [string range $arg 2 end]
1010 if {![string length $acceptLanguage]} {
1011 set acceptLanguage [lindex $argv [incr i]]
1015 set rfile [string range $arg 2 end]
1016 if {![string length $rfile]} {
1017 set rfile [lindex $argv [incr i]]
1023 if {[RobotHref http://www.indexdata.dk/ href host path]} {
1024 if {![RobotFileExist visited $host $path]} {
1025 set outf [RobotFileOpen unvisited $host $path]
1026 RobotWriteRecord $outf href 0
1027 RobotFileClose $outf
1035 if {![info exist domains]} {
1038 if {![info exist maxdistance]} {
1041 if {![info exist robotsMax]} {
1045 puts "domains=$domains"
1046 puts "max distance=$maxdistance"
1047 puts "max jobs=$robotsMax"
1053 while {$robotsRunning} {
1057 set statusfile [open status w]
1058 puts $statusfile "$status(unvisited) $status(bad) $status(visited)"