2 # $Id: robot.tcl,v 1.32 2002/03/25 16:11:08 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} {
291 # if {[string first {?} $href] >= 0} {
294 # if {[string first {?} $url] >= 0 && [string first {?} $href] >= 0} {
297 # get method (if any)
298 if {![regexp {^([^/:]+):(.*)} $href x method hpath]} {
302 if {[string compare $method http]} {
307 if {[regexp {^//([^/]+)([^\#]*)} $hpath x host surl]} {
308 if {![string length $surl]} {
311 if {[info exist domains]} {
313 foreach domain $domains {
314 if {[string match $domain $host]} {
324 regexp {^([^\#]*)} $hpath x surl
325 set host $URL($url,hostport)
327 if {![string length $surl]} {
330 if {[string first / $surl]} {
332 set curpath $URL($url,path)
333 if {[info exists URL($url,bpath)]} {
334 set curpath $URL($url,bpath)
336 regexp {^([^\#?]*)} $curpath x dpart
337 set l [string last / $dpart]
338 if {[expr $l >= 0]} {
339 set surl [string range $dpart 0 $l]$surl
341 set surl $dpart/$surl
344 set surllist [split $surl /]
347 foreach c $surllist {
352 set path [lrange $path 0 $pathl]
365 if {$debuglevel > 4} {
366 puts "pathl=$pathl output path=$path"
368 set path [join $path /]
369 if {![string length $path]} {
372 regsub -all {~} $path {%7E} path
373 set href "$method://$host$path"
375 if {$debuglevel > 1} {
376 puts "Ref result = $href"
378 return [checkrule url $href]
381 proc RobotError {url code} {
384 puts "Bad URL $url (code $code)"
387 if {[RobotFileExist unvisited $URL($url,hostport) $URL($url,path)]} {
388 set inf [RobotFileOpen unvisited $URL($url,hostport) $URL($url,path) r]
389 RobotReadRecord $inf fromurl distance
392 RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)
393 if {![RobotFileExist bad $URL($url,hostport) $URL($url,path)]} {
394 set outf [RobotFileOpen bad $URL($url,hostport) $URL($url,path)]
395 RobotWriteRecord $outf $fromurl $distance
400 proc RobotRedirect {url tourl code} {
403 puts "Redirecting from $url to $tourl"
407 if {[RobotFileExist unvisited $URL($url,hostport) $URL($url,path)]} {
408 set inf [RobotFileOpen unvisited $URL($url,hostport) $URL($url,path) r]
409 RobotReadRecord $inf fromurl distance
412 if {![RobotFileExist bad $URL($url,hostport) $URL($url,path)]} {
413 set outf [RobotFileOpen bad $URL($url,hostport) $URL($url,path)]
414 RobotWriteRecord $outf $fromurl $distance
417 if {[RobotHref $url tourl host path]} {
418 if {![RobotFileExist visited $host $path]} {
419 if {![RobotFileExist unvisited $host $path]} {
420 set outf [RobotFileOpen unvisited $host $path]
421 RobotWriteRecord $outf $fromurl $distance
426 set inf [RobotFileOpen visited $host $path r]
427 RobotReadRecord $inf oldurl olddistance
429 if {[string length $olddistance] == 0} {
432 if {[string length $distance] == 0} {
435 puts "distance=$distance olddistance=$olddistance"
436 if {[expr $distance < $olddistance]} {
437 set outf [RobotFileOpen unvisited $host $path]
438 RobotWriteRecord $outf $tourl $distance
443 if {[catch {RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)}]} {
449 proc link {url out href body distance} {
450 global URL maxdistance
451 if {[expr $distance > $maxdistance]} return
453 if {![RobotHref $url href host path]} return
456 puts $out "<identifier>$href</identifier>"
457 puts $out "<description>$body</description>"
460 if {![RobotFileExist visited $host $path]} {
462 if {![RobotFileExist bad $host $path]} {
463 if {[RobotFileExist unvisited $host $path]} {
464 set inf [RobotFileOpen unvisited $host $path r]
465 RobotReadRecord $inf oldurl olddistance
471 if {[string length $olddistance] == 0} {
474 if {[expr $distance < $olddistance]} {
475 set outf [RobotFileOpen unvisited $host $path]
476 RobotWriteRecord $outf $url $distance
479 } elseif {[string compare $href $url]} {
480 set inf [RobotFileOpen visited $host $path r]
481 RobotReadRecord $inf xurl olddistance
483 if {[string length $olddistance] == 0} {
486 if {[expr $distance < $olddistance]} {
487 puts "OK remarking url=$url href=$href"
488 puts "olddistance = $olddistance"
489 puts "newdistance = $distance"
490 set outf [RobotFileOpen unvisited $host $path]
491 RobotWriteRecord $outf $url $distance
497 proc RobotTextHtml {url out} {
498 global URL maxdistance
500 # set title so we can emit it for the body
502 # if true, nothing will be indexed
504 # if true, nothing will be followed
509 if {$maxdistance < 1000 && [info exists URL($url,dist)]} {
510 set fdistance $URL($url,dist)
511 set distance [expr $fdistance + 1]
513 htmlSwitch $URL($url,buf) \
517 # collect metadata and save NAME= CONTENT=..
520 puts -nonewline $out "<meta"
521 foreach a [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)
537 # go through robots directives (af any)
538 if {![string compare $metaname robots]} {
539 set direcs [split [string tolower $metacontent] ,]
540 if {[lsearch $direcs noindex] >= 0} {
543 if {[lsearch $direcs nofollow] >= 0} {
548 # don't print title of document content if noindex is used
550 puts $out "<title>$title</title>"
551 regsub -all {<!--[^-]*-->} $body { } abody
552 regsub -all -nocase {<script[^<]*</script>} $abody {} bbody
553 regsub -all {<[^\>]+>} $bbody {} nbody
554 puts $out "<documentcontent>"
556 puts $out "</documentcontent>"
560 if {![info exists parm(href)]} {
563 set href [string trim $parm(href)]
564 if {![RobotHref $url href host path]} continue
565 set URL($url,bpath) $path
567 # <a href="...."> .. </a>
568 # we're not using nonest - otherwise body isn't set
569 if {$nofollow} continue
570 if {![info exists parm(href)]} {
573 link $url $out [string trim $parm(href)] $body $distance
575 if {$nofollow} continue
576 if {![info exists parm(href)]} {
579 link $url $out [string trim $parm(href)] $body $distance
581 if {![info exists parm(src)]} {
584 link $url $out [string trim $parm(src)] $body $fdistance
588 proc RobotsTxt {url} {
591 RobotsTxt0 URL(URL($url,hostport),robots) $URL($url,buf)
594 proc RobotsTxt0 {v buf} {
597 foreach l [split $buf \n] {
598 if {[regexp {([-A-Za-z]+):[ ]*([^\# ]+)} $l match cmd arg]} {
599 puts "cmd=$cmd arg=$arg"
600 switch -- [string tolower $cmd] {
603 set pat [string tolower $arg]*
604 set section [string match $pat $agent]
608 puts "rule [list 0 $arg]"
609 lappend $v [list 0 $arg]
614 puts "rule [list 1 $arg]"
615 lappend $v [list 1 $arg]
623 proc RobotTextPlain {url out} {
626 puts $out "<documentcontent>"
627 regsub -all {<} $URL($url,buf) {\<} content
629 puts $out "</documentcontent>"
631 if {![string compare $URL($url,path) /robots.txt]} {
636 proc RobotWriteMetadata {url out} {
642 if {[RobotFileExist unvisited $URL($url,hostport) $URL($url,path)]} {
643 set inf [RobotFileOpen unvisited $URL($url,hostport) $URL($url,path) r]
644 RobotReadRecord $inf fromurl distance
647 set URL($url,dist) $distance
648 puts $out "<distance>"
649 puts $out " $distance"
650 puts $out "</distance>"
652 puts "Parsing $url distance=$distance"
653 switch $URL($url,head,content-type) {
655 if {[string length $distance]} {
656 RobotTextHtml $url $out
660 RobotTextPlain $url $out
666 proc Robot200 {url} {
669 set out [RobotFileOpen raw $URL($url,hostport) $URL($url,path)]
670 puts -nonewline $out $URL($url,buf)
673 set out [RobotFileOpen visited $URL($url,hostport) $URL($url,path)]
674 RobotWriteMetadata $url $out
677 RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)
680 proc RobotReadContent {url sock binary} {
683 set buffer [read $sock 16384]
684 set readCount [string length $buffer]
686 if {$readCount <= 0} {
688 RobotRestart $url $sock
689 } elseif {!$binary && [string first \0 $buffer] >= 0} {
691 RobotRestart $url $sock
693 # puts "Got $readCount bytes"
694 set URL($url,buf) $URL($url,buf)$buffer
698 proc RobotReadHeader {url sock} {
699 global URL debuglevel
701 if {$debuglevel > 1} {
702 puts "HTTP head $url"
704 if {[catch {set buffer [read $sock 2148]}]} {
706 RobotRestart $url $sock
709 set readCount [string length $buffer]
711 if {$readCount <= 0} {
713 RobotRestart $url $sock
715 # puts "Got $readCount bytes"
716 set URL($url,buf) $URL($url,buf)$buffer
718 set n [string first \r\n\r\n $URL($url,buf)]
722 set headbuf [string range $URL($url,buf) 0 $n]
724 set URL($url,buf) [string range $URL($url,buf) $n end]
726 regexp {^HTTP/([0-9.]+)[ ]+([0-9]+)} $headbuf x version code
727 set lines [split $headbuf \n]
728 foreach line $lines {
729 if {[regexp {^([^:]+):[ ]+([^;]*)} $line x name value]} {
730 set URL($url,head,[string tolower $name]) [string trim $value]
733 puts "HTTP CODE $code"
734 set URL($url,state) skip
737 RobotRedirect $url $URL($url,head,location) 301
738 RobotRestart $url $sock
741 RobotRedirect $url $URL($url,head,location) 302
742 RobotRestart $url $sock
745 if {![info exists URL($url,head,content-type)]} {
746 set URL($url,head,content-type) {}
749 switch -glob -- $URL($url,head,content-type) {
754 if {![regexp {/robots.txt$} $url]} {
755 if {![checkrule mime $URL($url,head,content-type)]} {
756 RobotError $url mimedeny
757 RobotRestart $url $sock
761 fileevent $sock readable [list RobotReadContent $url $sock $binary]
764 RobotError $url $code
765 RobotRestart $url $sock
772 proc RobotSockCancel {url sock} {
774 puts "RobotSockCancel sock=$sock url=$url"
776 RobotRestart $url $sock
779 proc RobotConnect {url sock} {
780 global URL agent acceptLanguage
782 fconfigure $sock -translation {lf crlf} -blocking 0
783 fileevent $sock readable [list RobotReadHeader $url $sock]
784 puts $sock "GET $URL($url,path) HTTP/1.0"
785 puts $sock "Host: $URL($url,host)"
786 puts $sock "User-Agent: $agent"
787 if {[string length $acceptLanguage]} {
788 puts $sock "Accept-Language: $acceptLanguage"
792 set URL($sock,cancel) [after 30000 [list RobotSockCancel $url $sock]]
799 proc RobotGetUrl {url phost} {
800 global URL robotsRunning
802 puts "Retrieve $robotsRunning url=$url"
803 if {![regexp {([^:]+)://([^/]+)(.*)} $url x method hostport path]} {
806 if {![regexp {([^:]+):([0-9]+)} $hostport x host port]} {
810 set URL($url,method) $method
811 set URL($url,host) $host
812 set URL($url,hostport) $hostport
813 set URL($url,path) $path
814 set URL($url,state) head
817 if {[string compare $path /robots.txt]} {
819 if {![info exists URL($hostport,robots)]} {
820 puts "READING robots.txt for host $hostport"
821 if {[RobotFileExist visited $hostport /robots.txt]} {
822 set inf [RobotFileOpen visited $hostport /robots.txt r]
823 set buf [read $inf 32768]
826 set buf "User-agent: *\nAllow: /\n"
828 RobotsTxt0 URL($hostport,robots) $buf
830 if {[info exists URL($hostport,robots)]} {
831 foreach l $URL($hostport,robots) {
832 if {[string first [lindex $l 1] $path] == 0} {
839 puts "skipped due to robots.txt"
843 if [catch {set sock [socket -async $host $port]}] {
846 RobotConnect $url $sock
851 if {![llength [info commands htmlSwitch]]} {
852 set e [info sharedlibextension]
853 if {[catch {load ./tclrobot$e}]} {
858 set agent "zmbot/0.1"
859 if {![catch {set os [exec uname -s -r]}]} {
860 set agent "$agent ($os)"
875 set acceptLanguage {}
877 set status(unvisited) 0
878 set status(visited) 0
883 # Rules: allow, deny, url
885 proc checkrule {type this} {
889 if {$debuglevel > 3} {
890 puts "CHECKRULE $type $this"
892 if {[info exist alrules]} {
894 if {$debuglevel > 3} {
898 if {[lindex $l 1] != $type} continue
899 # consider mask (! negates)
900 set masks [lindex $l 2]
902 foreach mask $masks {
903 if {$debuglevel > 4} {
904 puts "consider single mask $mask"
906 if {[string index $mask 0] == "!"} {
907 set mask [string range $mask 1 end]
908 if {[string match $mask $this]} continue
910 if {![string match $mask $this]} continue
914 if {$debuglevel > 4} {
918 # OK, we have a match
919 if {[lindex $l 0] == "allow"} {
920 if {$debuglevel > 3} {
921 puts "CHECKRULE MATCH OK"
925 if {$debuglevel > 3} {
926 puts "CHECKFULE MATCH FAIL"
932 if {$debuglevel > 3} {
933 puts "CHECKRULE MATCH OK"
942 if {[RobotHref http://www.indexdata.dk/ href host path]} {
943 if {![RobotFileExist visited $host $path]} {
944 set outf [RobotFileOpen unvisited $host $path]
945 RobotWriteRecord $outf href 0
951 proc deny {type stuff} {
954 lappend alrules [list deny $type $stuff]
957 proc allow {type stuff} {
960 lappend alrules [list allow $type $stuff]
966 set debuglevel $level
972 set l [llength $argv]
975 puts {tclrobot: usage:}
976 puts {tclrobot [-j jobs] [-i idle] [-c count] [-d domain] [-r rules] [url ..]}
977 puts " Example: -c 3 -d '*.dk' http://www.indexdata.dk/"
982 set arg [lindex $argv $i]
983 switch -glob -- $arg {
985 set robotsMax [string range $arg 2 end]
986 if {![string length $robotsMax]} {
987 set robotsMax [lindex $argv [incr i]]
991 set maxdistance [string range $arg 2 end]
992 if {![string length $maxdistance]} {
993 set maxdistance [lindex $argv [incr i]]
997 set dom [string range $arg 2 end]
998 if {![string length $dom]} {
999 set dom [lindex $argv [incr i]]
1001 lappend domains $dom
1004 set idletime [string range $arg 2 end]
1005 if {![string length $idletime]} {
1006 set idletime [lindex $argv [incr i]]
1010 set acceptLanguage [string range $arg 2 end]
1011 if {![string length $acceptLanguage]} {
1012 set acceptLanguage [lindex $argv [incr i]]
1016 set rfile [string range $arg 2 end]
1017 if {![string length $rfile]} {
1018 set rfile [lindex $argv [incr i]]
1024 if {[RobotHref http://www.indexdata.dk/ href host path]} {
1025 if {![RobotFileExist visited $host $path]} {
1026 set outf [RobotFileOpen unvisited $host $path]
1027 RobotWriteRecord $outf href 0
1028 RobotFileClose $outf
1036 if {![info exist domains]} {
1039 if {![info exist maxdistance]} {
1042 if {![info exist robotsMax]} {
1046 puts "domains=$domains"
1047 puts "max distance=$maxdistance"
1048 puts "max jobs=$robotsMax"
1054 while {$robotsRunning} {
1058 set statusfile [open status w]
1059 puts $statusfile "$status(unvisited) $status(bad) $status(visited)"