File status written with counts of areas: unvisited, bad, visited.
[tclrobot.git] / robot.tcl
1 #!/usr/bin/tclsh 
2 # $Id: robot.tcl,v 1.29 2001/11/14 09:15:23 adam Exp $
3 #
4 proc RobotFileNext1 {area lead} {
5     # puts "RobotFileNext1 area=$area lead=$lead"
6     if {[catch {set ns [glob ${area}/*]}]} {
7         return {}
8     }
9     foreach n $ns {
10         if {[file isfile $n]} {
11             set off [string last / $n]
12             incr off 2
13             return $lead/[string range $n $off end]
14         }
15     }
16     foreach n $ns {
17         if {[file isdirectory $n]} {
18             set off [string last / $n]
19             incr off 2
20             set sb [RobotFileNext1 $n $lead/[string range $n $off end]]
21             if {[string length $sb]} {
22                 return $sb
23             }
24         }
25     }
26     return {}
27 }
28
29 proc RobotWriteRecord {outf fromurl distance} {
30     puts $outf "<zmbot>"
31     puts $outf "<distance>"
32     puts $outf $distance
33     puts $outf "</distance>"
34     puts $outf "<fromurl>"
35     puts $outf $fromurl
36     puts $outf "</fromurl>"
37     puts $outf "</zmbot>"
38 }
39
40 proc RobotReadRecord {inf fromurlx distancex} {
41     upvar $fromurlx fromurl
42     upvar $distancex distance
43     gets $inf
44     gets $inf
45     set distance [string trim [gets $inf]]
46     # puts "got distance = $distance"
47     gets $inf
48     gets $inf
49     set fromurl [string trim [gets $inf]]
50 }
51
52 proc RobotFileNext {area} {
53     global robotSeq
54     global idletime ns
55     global status
56
57     # puts "RobotFileNext robotSeq=$robotSeq"
58     if {$robotSeq < 0} {
59         return {}
60     }
61     if {$robotSeq == 0} {
62         if {[catch {set ns [glob ${area}/*]}]} {
63             return {}
64         }
65     }
66     set off [string length $area]
67     incr off
68     set n [lindex $ns $robotSeq]
69     if {![string length $n]} {
70         set robotSeq -1
71         flush stdout
72         set statusfile [open status w]
73         puts $statusfile "$status(unvisited) $status(bad) $status(visited)"
74         close $statusfile
75         return wait
76     }
77     incr robotSeq
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]} {
84             return $sb
85         }
86     }
87     puts "no more work at end of RobotFileNext n=$n"
88     puts "ns=$ns"
89     return {}
90 }
91
92
93 proc RobotFileExist {area host path} {
94     global debuglevel
95
96     if {$debuglevel > 3} {
97         puts "RobotFileExist begin area=$area host=$host path=$path"
98     }
99     set lpath [split $path /]
100     set l [llength $lpath]
101     incr l -1
102     set t [lindex $lpath $l]
103     incr l -1
104     set npath $area/$host[join [lrange $lpath 0 $l] /d]/f$t
105     if {$debuglevel > 3} {
106         puts "RobotFileExist end npath=$npath"
107     }
108     return [file exists $npath]
109 }
110
111 proc RobotFileUnlink {area host path} {
112     global status
113     # puts "RobotFileUnlink begin"
114     # puts "area=$area host=$host path=$path"
115     set lpath [split $path /]
116     set l [llength $lpath]
117     incr l -1
118     set t [lindex $lpath $l]
119     incr l -1
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
124
125     set l [llength $comp]
126     incr l -1
127     incr l -1
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
132         exec rmdir ./$path
133     }
134     # puts "RobotFileUnlink end"
135 }
136
137 proc RobotFileClose {out} {
138     if [string compare $out stdout] {
139         close $out
140     }
141 }
142
143 proc RobotFileOpen {area host path {mode w}} {
144     set orgPwd [pwd]
145     global workdir
146     global status
147     global debuglevel
148
149     if {![info exists workdir]} {
150         return stdout
151     }
152     if {$debuglevel > 3} {
153         puts "RobotFileOpen orgPwd=$orgPwd area=$area host=$host path=$path mode=$mode"
154     }
155     if {[string compare $orgPwd $workdir]} {
156         puts "ooops. RobotFileOpen failed"
157         puts "workdir = $workdir"
158         puts "pwd = $orgPwd"
159         exit 1
160     }
161     set comp [split $area/$host$path /]
162     set len [llength $comp]
163     incr len -1
164     for {set i 0} {$i < $len} {incr i} {
165         if {$i > 1} {
166             set d "d[lindex $comp $i]" 
167         } else {
168             set d [lindex $comp $i]
169         }
170         if {[catch {cd ./$d}]} {
171             exec mkdir $d
172             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"
176                 close $out
177                 incr status(unvisited)
178             }
179         }
180     }
181     set d [lindex $comp $len]
182     if {[string length $d]} {
183         set out [open f$d $mode]
184         if {0} {
185             if {[file isfile $d/f]} {
186                 set out [open $d/f $mode]
187             } else {
188                 set out [open f$d $mode]
189             }
190         }
191     } else {
192         set out [open f $mode]
193     }
194     if {$mode == "w"} {
195         incr status($area)
196     }
197     cd $orgPwd
198     return $out
199 }
200
201 proc RobotRR {} {
202     global robotSeq robotsRunning
203
204     incr robotsRunning -1
205     while {$robotsRunning} {
206         vwait robotsRunning
207     }
208     set robotSeq 0
209     RobotStart
210 }
211
212 proc RobotRestart {url sock} {
213     global URL robotsRunning
214
215     close $sock
216     after cancel $URL($sock,cancel) 
217
218     foreach v [array names URL $url,*] {
219         unset URL($v)
220     }
221
222     incr robotsRunning -1
223     RobotStart
224 }
225
226 proc RobotStart {} {
227     global URL
228     global robotsRunning robotsMax idletime
229   
230     # puts "RobotStart"
231     while {1} {
232         set url [RobotFileNext unvisited]
233         if {![string length $url]} {
234             return
235         }
236         incr robotsRunning
237         if {[string compare $url wait] == 0} {
238             after $idletime RobotRR
239             return
240         }
241         set r [RobotGetUrl $url {}]
242         if {!$r} {
243             if {$robotsRunning >= $robotsMax} return
244         } else {
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)]
248                 RobotFileClose $outf
249             }
250             RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)
251         }
252     }
253 }
254
255 proc headSave {url out} {
256     global URL
257     
258     if {[info exists URL($url,head,last-modified)]} {
259         puts $out "<lastmodified>$URL($url,head,last-modified)</lastmodified>"
260     }
261     puts $out {<si>}
262     if {[info exists URL($url,head,date)]} {
263         puts $out " <date>$URL($url,head,date)</date>"
264     }
265     if {[info exists URL($url,head,content-length)]} {
266         puts $out " <by>$URL($url,head,content-length)</by>"
267     }
268     if {[info exists URL($url,head,server)]} {
269         puts $out " <format>$URL($url,head,server)</format>"
270     }
271     puts $out {</si>}
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>"
276     }
277     puts $out {</publisher>}
278 }
279
280 proc RobotHref {url hrefx hostx pathx} {
281     global URL domains debuglevel
282     upvar $hrefx href
283     upvar $hostx host
284     upvar $pathx path
285
286     if {$debuglevel > 1} {
287         puts "Ref input url = $url href=$href"
288     }
289
290     if {[string first { } $href] >= 0} {
291         return 0
292     }
293     if {[string length $href] > 256} {
294         return 0
295     }
296     if {[string first {?} $href] >= 0} {
297         return 0
298     }
299     if {[string first {?} $url] >= 0 && [string first {?} $href] >= 0} {
300         return 0
301     }
302     # get method (if any)
303     if {![regexp {^([^/:]+):(.*)} $href x method hpath]} {
304         set hpath $href
305         set method http
306     } else {
307         if {[string compare $method http]} {
308             return 0
309         }
310     }
311     # get host (if any)
312     if {[regexp {^//([^/]+)([^\#]*)} $hpath x host surl]} {
313         if {![string length $surl]} {
314             set surl /
315         }
316         if {[info exist domains]} {
317             set ok 0
318             foreach domain $domains {
319                 if {[string match $domain $host]} {
320                     set ok 1
321                     break
322                  }
323             }
324             if {!$ok} {
325                 return 0
326             }
327         }
328     } else {
329         regexp {^([^\#]*)} $hpath x surl
330         set host $URL($url,hostport)
331     }
332     if {![string length $surl]} {
333         return 0
334     }
335     if {[string first / $surl]} {
336         # relative path
337         set curpath $URL($url,path)
338         if {[info exists URL($url,bpath)]} {
339             set curpath $URL($url,bpath)
340         }
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
345         } else {
346             set surl $dpart/$surl
347         }
348     }
349     set surllist [split $surl /]
350     catch {unset path}
351     set pathl 0
352     foreach c $surllist {
353         switch -- $c {
354             .. {
355                 if {$pathl > 1} {
356                     incr pathl -2
357                     set path [lrange $path 0 $pathl]
358                     incr pathl
359                 }
360             }
361             . {
362
363             }
364             default {
365                 incr pathl
366                 lappend path $c
367             }
368         }
369     }
370     if {$debuglevel > 4} {
371         puts "pathl=$pathl output path=$path"
372     }
373     set path [join $path /]
374     if {![string length $path]} {
375         set path /
376     }
377     regsub -all {~} $path {%7E} path
378     set href "$method://$host$path"
379
380     if {$debuglevel > 1} {
381         puts "Ref result = $href"
382     }
383     return [checkrule url $href]
384 }
385
386 proc RobotError {url code} {
387     global URL
388
389     puts "Bad URL $url (code $code)"
390     set fromurl {}
391     set distance -1
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
395         RobotFileClose $inf
396     }
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
401         RobotFileClose $outf
402     }
403 }
404
405 proc RobotRedirect {url tourl code} {
406     global URL
407
408     puts "Redirecting from $url to $tourl"
409
410     set distance {}
411     set fromurl {}
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
415         RobotFileClose $inf
416     }
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
420         RobotFileClose $outf
421     }
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
427                 RobotFileClose $outf
428             }
429         } else {
430             set olddistance {}
431             set inf [RobotFileOpen visited $host $path r]
432             RobotReadRecord $inf oldurl olddistance
433             RobotFileClose $inf
434             if {[string length $olddistance] == 0} {
435                 set olddistance 1000
436             }
437             if {[string length $distance] == 0} {
438                 set distance 1000
439             }
440             puts "distance=$distance olddistance=$olddistance"
441             if {[expr $distance < $olddistance]} {
442                 set outf [RobotFileOpen unvisited $host $path]
443                 RobotWriteRecord $outf $tourl $distance
444                 RobotFileClose $outf
445             }
446         }
447     }
448     if {[catch {RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)}]} {
449         puts "unlink failed"
450         exit 1
451     }
452 }
453
454 proc link {url out href body distance} {
455     global URL maxdistance
456     if {[expr $distance > $maxdistance]} return
457     
458     if {![RobotHref $url href host path]} return
459     
460     puts $out "<cr>"
461     puts $out "<identifier>$href</identifier>"
462     puts $out "<description>$body</description>"
463     puts $out "</cr>"
464     
465     if {![RobotFileExist visited $host $path]} {
466         set olddistance 1000
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
471                 RobotFileClose $inf
472             }
473         } else {
474             set olddistance 0
475         }
476         if {[string length $olddistance] == 0} {
477             set olddistance 1000
478         }
479         if {[expr $distance < $olddistance]} {
480             set outf [RobotFileOpen unvisited $host $path]
481             RobotWriteRecord $outf $url $distance
482             RobotFileClose $outf
483         }
484     } elseif {[string compare $href $url]} {
485         set inf [RobotFileOpen visited $host $path r]
486         RobotReadRecord $inf xurl olddistance
487         close $inf
488         if {[string length $olddistance] == 0} {
489             set olddistance 1000
490         }
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
497             RobotFileClose $outf
498         }
499     }
500 }
501
502 proc RobotTextHtml {url out} {
503     global URL maxdistance
504
505     set distance 0
506     set fdistance 0
507     if {$maxdistance < 1000 && [info exists URL($url,dist)]} {
508         set fdistance $URL($url,dist)
509         set distance [expr $fdistance + 1]
510     }
511     htmlSwitch $URL($url,buf) \
512         title {
513             puts $out "<title>$body</title>"
514         } -nonest meta {
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 {"}
521             }
522             puts $out {></meta>}
523         } body {
524             regsub -all {<!--[^-]*->} $body { } abody
525             regsub -all -nocase {<script[^<]*</script>} $abody {} bbody
526             regsub -all {<[^\>]+>} $bbody {} nbody
527             puts $out "<documentcontent>"
528             puts $out $nbody
529             puts $out "</documentcontent>"
530         } -nonest base {
531             if {![info exists parm(href)]} {
532                 continue
533             }
534             set href [string trim $parm(href)]
535             if {![RobotHref $url href host path]} continue
536             set URL($url,bpath) $path
537         } -nonest a {
538             if {![info exists parm(href)]} {
539                 continue
540             }
541             link $url $out [string trim $parm(href)] $body $distance
542         } -nonest area {
543             if {![info exists parm(href)]} {
544                 continue
545             }
546             link $url $out [string trim $parm(href)] $body $distance
547         } -nonest frame {
548             if {![info exists parm(src)]} {
549                 continue
550             }
551             link $url $out [string trim $parm(src)] $body $fdistance
552         }
553 }
554
555 proc RobotsTxt {url} {
556     global agent URL
557
558     RobotsTxt0 URL(URL($url,hostport),robots) $URL($url,buf)
559 }
560
561 proc RobotsTxt0 {v buf} {
562     global URL agent
563     set section 0
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] {
568                 user-agent {
569                     if {$section} break
570                     set pat [string tolower $arg]*
571                     set section [string match $pat $agent]
572                 }
573                 disallow {
574                     if {$section} {
575                         puts "rule [list 0 $arg]"
576                         lappend $v [list 0 $arg]
577                     }
578                 }
579                 allow {
580                     if {$section} {
581                         puts "rule [list 1 $arg]"
582                         lappend $v [list 1 $arg]
583                     }
584                 }
585             }
586         }
587     }
588 }
589
590 proc RobotTextPlain {url out} {
591     global URL
592
593     puts $out "<documentcontent>"
594     regsub -all {<} $URL($url,buf) {\&lt;} content
595     puts $out $content
596     puts $out "</documentcontent>"
597
598     if {![string compare $URL($url,path) /robots.txt]} {
599         RobotsTxt $url
600     }
601 }
602
603 proc RobotWriteMetadata {url out} {
604     global URL domains
605
606     puts $out "<zmbot>"
607
608     set distance 1000
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
612         RobotFileClose $inf
613     }
614     set URL($url,dist) $distance
615     puts $out "<distance>"
616     puts $out "  $distance"
617     puts $out "</distance>"
618     headSave $url $out
619     puts "Parsing $url distance=$distance"
620     switch $URL($url,head,content-type) {
621         text/html {
622             if {[string length $distance]} {
623                 RobotTextHtml $url $out
624             }
625         }
626         text/plain {
627             RobotTextPlain $url $out
628         }
629     }
630     puts $out "</zmbot>"
631 }
632
633 proc Robot200 {url} {
634     global URL domains
635     
636     set out [RobotFileOpen raw $URL($url,hostport) $URL($url,path)]
637     puts -nonewline $out $URL($url,buf)
638     RobotFileClose $out
639
640     set out [RobotFileOpen visited $URL($url,hostport) $URL($url,path)]
641     RobotWriteMetadata $url $out
642     RobotFileClose $out
643
644     RobotFileUnlink unvisited $URL($url,hostport) $URL($url,path)
645 }
646
647 proc RobotReadContent {url sock binary} {
648     global URL
649
650     set buffer [read $sock 16384]
651     set readCount [string length $buffer]
652
653     if {$readCount <= 0} {
654         Robot200 $url
655         RobotRestart $url $sock
656     } elseif {!$binary && [string first \0 $buffer] >= 0} {
657         Robot200 $url
658         RobotRestart $url $sock
659     } else {
660         # puts "Got $readCount bytes"
661         set URL($url,buf) $URL($url,buf)$buffer
662     }
663 }
664
665 proc RobotReadHeader {url sock} {
666     global URL debuglevel
667
668     if {$debuglevel > 1} {
669         puts "HTTP head $url"
670     }
671     if {[catch {set buffer [read $sock 2148]}]} {
672         RobotError $url 404
673         RobotRestart $url $sock
674         return
675     }
676     set readCount [string length $buffer]
677     
678     if {$readCount <= 0} {
679         RobotError $url 404
680         RobotRestart $url $sock
681     } else {
682         # puts "Got $readCount bytes"
683         set URL($url,buf) $URL($url,buf)$buffer
684         
685         set n [string first \r\n\r\n $URL($url,buf)]
686         if {$n > 1} {
687             set code 0
688             set version {}
689             set headbuf [string range $URL($url,buf) 0 $n]
690             incr n 4
691             set URL($url,buf) [string range $URL($url,buf) $n end]
692             
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]
698                 }
699             }
700             puts "HTTP CODE $code"
701             set URL($url,state) skip
702             switch $code {
703                 301 {
704                     RobotRedirect $url $URL($url,head,location) 301
705                     RobotRestart $url $sock
706                 }
707                 302 {
708                     RobotRedirect $url $URL($url,head,location) 302
709                     RobotRestart $url $sock
710                 }
711                 200 {
712                     if {![info exists URL($url,head,content-type)]} {
713                         set URL($url,head,content-type) {}
714                     }
715                     set binary 1
716                     switch -glob -- $URL($url,head,content-type) {
717                         text/* {
718                             set binary 0
719                         }
720                     }
721                     if {![regexp {/robots.txt$} $url]} {
722                         if {![checkrule mime $URL($url,head,content-type)]} {
723                             RobotError $url mimedeny
724                             RobotRestart $url $sock
725                             return
726                         }
727                     }
728                     fileevent $sock readable [list RobotReadContent $url $sock $binary]
729                 }
730                 default {
731                     RobotError $url $code
732                     RobotRestart $url $sock
733                 }
734             }
735         }
736     }
737 }
738
739 proc RobotSockCancel {url sock} {
740
741     puts "RobotSockCancel sock=$sock url=$url"
742     RobotError $url 401
743     RobotRestart $url $sock
744 }
745
746 proc RobotConnect {url sock} {
747     global URL agent acceptLanguage
748
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"
756     }
757     puts $sock ""
758     flush $sock
759     set URL($sock,cancel) [after 30000 [list RobotSockCancel $url $sock]]
760 }
761
762 proc RobotNop {} {
763
764 }
765
766 proc RobotGetUrl {url phost} {
767     global URL robotsRunning
768     flush stdout
769     puts "Retrieve $robotsRunning url=$url"
770     if {![regexp {([^:]+)://([^/]+)(.*)} $url x method hostport path]} {
771         return -1
772     }
773     if {![regexp {([^:]+):([0-9]+)} $hostport x host port]} {
774         set port 80
775         set host $hostport
776     }
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
782     set URL($url,buf) {}
783
784     if {[string compare $path /robots.txt]} {
785         set ok 1
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]
791                 close $inf
792             } else {
793                 set buf "User-agent: *\nAllow: /\n"
794             }
795             RobotsTxt0 URL($hostport,robots) $buf
796         }
797         if {[info exists URL($hostport,robots)]} {
798             foreach l $URL($hostport,robots) {
799                 if {[string first [lindex $l 1] $path] == 0} {
800                     set ok [lindex $l 0]
801                     break
802                 }
803             }
804         }
805         if {!$ok} {
806             puts "skipped due to robots.txt"
807             return -1
808         }
809     }
810     if [catch {set sock [socket -async $host $port]}] {
811         return -1
812     }
813     RobotConnect $url $sock
814
815     return 0
816 }
817
818 if {![llength [info commands htmlSwitch]]} {
819     set e [info sharedlibextension]
820     if {[catch {load ./tclrobot$e}]} {
821         load tclrobot$e
822     }
823 }
824
825 set agent "zmbot/0.1"
826 if {![catch {set os [exec uname -s -r]}]} {
827     set agent "$agent ($os)"
828 }
829
830 puts "agent: $agent"
831
832 proc bgerror {m} {
833     global errorInfo
834     puts "BGERROR $m"
835     puts $errorInfo
836 }
837
838 set robotsRunning 0
839 set robotSeq 0
840 set workdir [pwd]
841 set idletime 60000
842 set acceptLanguage {}
843 set debuglevel 0
844 set status(unvisited) 0
845 set status(visited) 0
846 set status(bad) 0
847 set status(raw) 0
848
849
850 # Rules: allow, deny, url
851
852 proc checkrule {type this} {
853     global alrules
854     global debuglevel
855
856     if {$debuglevel > 3} {
857         puts "CHECKRULE $type $this"
858     }
859     if {[info exist alrules]} {
860         foreach l $alrules {
861             if {$debuglevel > 3} {
862                 puts "consider $l"
863             }
864             # consider type
865             if {[lindex $l 1] != $type} continue
866             # consider mask (! negates)
867             set masks [lindex $l 2]
868             set ok 0
869             foreach mask $masks {       
870                 if {$debuglevel > 4} {
871                     puts "consider single mask $mask"
872                 }
873                 if {[string index $mask 0] == "!"} {
874                     set mask [string range $mask 1 end]
875                     if {[string match $mask $this]}  continue
876                 } else {
877                     if {![string match $mask $this]} continue
878                 }
879                 set ok 1
880             }
881             if {$debuglevel > 4} {
882                 puts "ok = $ok"
883             }
884             if {!$ok} continue
885             # OK, we have a match
886             if {[lindex $l 0] == "allow"} {
887                 if {$debuglevel > 3} {
888                     puts "CHECKRULE MATCH OK"
889                 }
890                 return 1
891             } else {
892                 if {$debuglevel > 3} {
893                     puts "CHECKFULE MATCH FAIL"
894                 }
895                 return 0
896             }
897         }
898     }
899     if {$debuglevel > 3} {
900         puts "CHECKRULE MATCH OK"
901     }
902     return 1
903 }
904
905
906 proc url {href} {
907     global debuglevel
908
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
913             RobotFileClose $outf
914         }
915     }
916 }
917
918 proc deny {type stuff} {
919     global alrules
920
921     lappend alrules [list deny $type $stuff]
922 }
923
924 proc allow {type stuff} {
925     global alrules
926
927     lappend alrules [list allow $type $stuff]
928 }
929
930 proc debug {level} {
931     global debuglevel
932
933     set debuglevel $level
934 }
935
936 # Parse options
937
938 set i 0
939 set l [llength $argv]
940
941 if {$l < 2} {
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/"
945
946     exit 1
947 }
948 while  {$i < $l} {
949     set arg [lindex $argv $i]
950     switch -glob -- $arg {
951         -j* {
952             set robotsMax [string range $arg 2 end]
953             if {![string length $robotsMax]} {
954                 set robotsMax [lindex $argv [incr i]]
955             }
956         }
957         -c* {
958             set maxdistance [string range $arg 2 end]
959             if {![string length $maxdistance]} {
960                 set maxdistance [lindex $argv [incr i]]
961             }
962         }
963         -d* {
964             set dom [string range $arg 2 end]
965             if {![string length $dom]} {
966                 set dom [lindex $argv [incr i]]
967             }
968             lappend domains $dom
969         }
970         -i* {
971             set idletime [string range $arg 2 end]
972             if {![string length $idletime]} {
973                 set idletime [lindex $argv [incr i]]
974             }
975         }
976         -l* {
977             set acceptLanguage [string range $arg 2 end]
978             if {![string length $acceptLanguage]} {
979                 set acceptLanguage [lindex $argv [incr i]]
980             }
981         }
982         -r* {
983             set rfile [string range $arg 2 end]
984             if {![string length $rfile]} {
985                 set rfile [lindex $argv [incr i]]
986             }
987             source $rfile
988         }
989         default {
990             set href $arg
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
995                     RobotFileClose $outf
996                 }
997             }
998         }
999     }
1000     incr i
1001 }
1002
1003 if {![info exist domains]} {
1004     set domains {*}
1005 }
1006 if {![info exist maxdistance]} {
1007     set maxdistance 50
1008 }
1009 if {![info exist robotsMax]} {
1010     set robotsMax 5
1011 }
1012
1013 puts "domains=$domains"
1014 puts "max distance=$maxdistance"
1015 puts "max jobs=$robotsMax"
1016
1017
1018 RobotStart
1019
1020
1021 while {$robotsRunning} {
1022     vwait robotsRunning
1023 }
1024
1025 set statusfile [open status w]
1026 puts $statusfile "$status(unvisited) $status(bad) $status(visited)"
1027 close $statusfile
1028