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