chiark / gitweb /
b26d1c6f7eccb78491e9987356202bcb4961b7f7
[ircbot] / bot.tcl
1 # Core bot code
2
3 proc defset {varname val} {
4     upvar #0 $varname var
5     if {![info exists var]} { set var $val }
6 }
7
8 # must set host
9 defset port 6667
10
11 defset nick testbot
12 defset ownfullname "testing bot"
13 defset ownmailaddr test-irc-bot@example.com
14
15 defset musthaveping_ms 10000
16 defset out_maxburst 6
17 defset out_interval 2100
18 defset out_lag_lag 5000
19 defset out_lag_very 25000
20
21 proc manyset {list args} {
22     foreach val $list var $args {
23         upvar 1 $var my
24         set my $val
25     }
26 }
27
28 proc try_except_finally {try except finally} {
29     global errorInfo errorCode
30     set er [catch { uplevel 1 $try } emsg]
31     if {$er} {
32         set ei $errorInfo
33         set ec $errorCode
34         if {[catch { uplevel 1 $except } emsg3]} {
35             append ei "\nALSO ERROR HANDLING ERROR:\n$emsg3"
36         }
37     }
38     set er2 [catch { uplevel 1 $finally } emsg2]
39     if {$er} {
40         if {$er2} {
41             append ei "\nALSO ERROR CLEANING UP:\n$emsg2"
42         }
43         return -code $er -errorinfo $ei -errorcode $ec $emsg
44     } elseif {$er2} {
45         return -code $er2 -errorinfo $errorInfo -errorcode $errorCode $emsg2
46     } else {
47         return $emsg
48     }
49 }
50
51 proc out__vars {} {
52     uplevel 1 {
53         global out_queue out_creditms out_creditat out_interval out_maxburst
54         global out_lag_lag out_lag_very
55 #set pr [lindex [info level 0] 0]
56 #puts $pr>[clock seconds]|$out_creditat|$out_creditms|[llength $out_queue]<
57     }
58 }
59
60 proc out_lagged {} {
61     out__vars
62     if {[llength $out_queue]*$out_interval > $out_lag_very} {
63         return 2
64     } elseif {[llength $out_queue]*$out_interval > $out_lag_lag} {
65         return 1
66     } else {
67         return 0
68     }
69 }
70
71 proc out_restart {} {
72     out__vars
73     
74     set now [clock seconds]
75     incr out_creditms [expr {($now - $out_creditat) * 1000}]
76     set out_creditat $now
77     if {$out_creditms > $out_maxburst*$out_interval} {
78         set out_creditms [expr {$out_maxburst*$out_interval}]
79     }
80     out_runqueue $now
81 }
82
83 proc out_runqueue {now} {
84     global sock
85     out__vars
86     
87     while {[llength $out_queue] && $out_creditms >= $out_interval} {
88 #puts rq>$now|$out_creditat|$out_creditms|[llength $out_queue]<
89         manyset [lindex $out_queue 0] orgwhen msg
90         set out_queue [lrange $out_queue 1 end]
91         if {[llength $out_queue]} {
92             append orgwhen "+[expr {$now - $orgwhen}]"
93             append orgwhen "([llength $out_queue])"
94         }
95         puts "$orgwhen -> $msg"
96         puts $sock $msg
97         incr out_creditms -$out_interval
98     }
99     if {[llength $out_queue]} {
100         after $out_interval out_nextmessage
101     }
102 }
103
104 proc out_nextmessage {} {
105     out__vars
106     set now [clock seconds]
107     incr out_creditms $out_interval
108     set out_creditat $now
109     out_runqueue $now
110 }
111
112 proc sendout_priority {priority command args} {
113     global sock out_queue
114     if {[llength $args]} {
115         set la [lindex $args end]
116         set args [lreplace $args end end]
117         foreach i $args {
118             if {[regexp {[: ]} $i]} {
119                 error "bad argument in output $i ($command $args)"
120             }
121         }
122         lappend args :$la
123     }
124     set args [lreplace $args 0 -1 $command]
125     set string [join $args { }]
126     set now [clock seconds]
127     set newe [list $now $string]
128     if {$priority} {
129         set out_queue [concat [list $newe] $out_queue]
130     } else {
131         lappend out_queue $newe
132     }
133     if {[llength $out_queue] == 1} {
134         out_restart
135     }
136 }
137
138 proc sendout {command args} { eval sendout_priority [list 0 $command] $args }
139     
140 proc log {data} {
141     puts $data
142 }
143
144 proc logerror {data} {
145     log $data
146 }
147
148 proc saveeic {} {
149     global saveei saveec errorInfo errorCode
150
151     set saveei $errorInfo
152     set saveec $errorCode
153
154     puts ">$saveec|$saveei<"
155 }
156
157 proc bgerror {msg} {
158     global save
159     logerror $msg
160     saveeic
161 }
162
163 proc onread {args} {
164     global sock nick calling_nick errorInfo errorCode
165     
166     if {[gets $sock line] == -1} { fail "EOF/error on input" }
167     regsub -all "\[^ -\176\240-\376\]" $line ? line
168     set org $line
169     
170     set ei $errorInfo
171     set ec $errorCode
172     catch { unset calling_nick }
173     set errorInfo $ei
174     set errorCode $ec
175     
176     if {[regexp -nocase {^:([^ ]+) (.*)} $line dummy prefix remain]} {
177         set line $remain
178         if {[regexp {^([^!]+)!} $prefix dummy maybenick]} {
179             set calling_nick $maybenick
180             if {"[irctolower $maybenick]" == "[irctolower $nick]"} return
181         }
182     } else {
183         set prefix {}
184     }
185     if {![string length $line]} { return }
186     if {![regexp -nocase {^([0-9a-z]+) *(.*)} $line dummy command line]} {
187         log "bad command: $org"
188         return
189     }
190     set command [string toupper $command]
191     set params {}
192     while {[regexp {^([^ :]+) *(.*)} $line dummy thisword line]} {
193         lappend params $thisword
194     }
195     if {[regexp {^:(.*)} $line dummy thisword]} {
196         lappend params $thisword
197     } elseif {[string length $line]} {
198         log "junk at end: $org"
199         return
200     }
201     if {"$command" == "PRIVMSG" &&
202         [regexp {^[&#+!]} [lindex $params 0]] &&
203         ![regexp {^!} [lindex $params 1]]} {
204         # on-channel message, ignore
205         catch {
206             recordlastseen_p $prefix "talking on [lindex $params 0]" 1
207         }
208         return
209     }
210     log "[clock seconds] <- $org"
211     set procname msg_$command
212     if {[catch { info body $procname }]} { return }
213     if {[catch {
214         eval [list $procname $prefix $command] $params
215     } emsg]} {
216         logerror "error: $emsg ($prefix $command $params)"
217         saveeic
218     }
219 }
220
221 proc sendprivmsg {dest l} {
222     foreach v [split $l "\n"] {
223         sendout [expr {[ischan $dest] ? "PRIVMSG" : "NOTICE"}] $dest $v
224     }
225 }
226 proc sendaction_priority {priority dest what} {
227     sendout_priority $priority PRIVMSG $dest "\001ACTION $what\001"
228 }
229 proc msendprivmsg {dest ll} { foreach l $ll { sendprivmsg $dest $l } }
230 proc msendprivmsg_delayed {delay dest ll} { after $delay [list msendprivmsg $dest $ll] }
231
232 proc prefix_none {} {
233     upvar 1 p p
234     if {[string length $p]} { error "prefix specified" }
235 }
236
237 proc msg_PING {p c s1} {
238     global musthaveping_after
239     prefix_none
240     sendout PONG $s1
241     if {[info exists musthaveping_after]} connected
242 }
243
244 proc check_nick {n} {
245     if {[regexp -nocase {[^][\\`_^{|}a-z0-9-]} $n]} { error "bad char in nick" }
246     if {[regexp {^[-0-9]} $n]} { error "bad nick start" }
247 }
248
249 proc ischan {dest} {
250     return [regexp {^[&#+!]} $dest]
251 }
252
253 proc irctolower {v} {
254     foreach {from to} [list "\\\[" "{" \
255                           "\\\]" "}" \
256                           "\\\\" "|" \
257                           "~"    "^"] {
258         regsub -all $from $v $to v
259     }
260     return [string tolower $v]
261 }
262
263 proc prefix_nick {} {
264     global nick
265     upvar 1 p p
266     upvar 1 n n
267     if {![regexp {^([^!]+)!} $p dummy n]} { error "not from nick" }
268     check_nick $n
269     if {"[irctolower $n]" == "[irctolower $nick]"} {
270         error "from myself" {} {}
271     }
272 }
273
274 proc showintervalsecs {howlong} {
275     return [showintervalsecs/[opt timeformat] $howlong]
276 }
277
278 proc showintervalsecs/ks {howlong} {
279     if {$howlong < 1000} {
280         return "${howlong}s"
281     } else {
282         if {$howlong < 1000000} {
283             set pfx k
284             set scale 1000
285         } else {
286             set pfx M
287             set scale 1000000
288         }
289         set value [expr "$howlong.0 / $scale"]
290         foreach {min format} {100 %.0f 10 %.1f 1 %.2f} {
291             if {$value < $min} continue
292             return [format "$format${pfx}s" $value]
293         }
294     }
295 }
296
297 proc format_qty {qty unit} {
298     set o $qty
299     append o " "
300     append o $unit
301     if {$qty != 1} { append o s }
302     return $o
303 }
304
305 proc showintervalsecs/hms {qty} {
306     set ul {second 60 minute 60 hour 24 day 7 week}
307     set remainv 0
308     while {[llength $ul] > 1 && $qty >= [set uv [lindex $ul 1]]} {
309         set remainu [lindex $ul 0]
310         set remainv [expr {$qty % $uv}]
311         set qty [expr {($qty-$remainv)/$uv}]
312         set ul [lreplace $ul 0 1]
313     }
314     set o [format_qty $qty [lindex $ul 0]]
315     if {$remainv} {
316         append o " "
317         append o [format_qty $remainv $remainu]
318     }
319     return $o
320 }
321
322 proc showinterval {howlong} {
323     if {$howlong <= 0} {
324         return {just now}
325     } else {
326         return "[showintervalsecs $howlong] ago"
327     }
328 }
329
330 proc showtime {when} {
331     return [showinterval [expr {[clock seconds] - $when}]]
332 }
333
334 proc def_msgproc {name argl body} {
335     proc msg_$name "varbase $argl" "\
336     upvar #0 msg/\$varbase/dest d\n\
337     upvar #0 msg/\$varbase/str s\n\
338     upvar #0 msg/\$varbase/accum a\n\
339 $body"
340 }
341
342 def_msgproc begin {dest str} {
343     set d $dest
344     set s $str
345     set a {}
346 }
347
348 def_msgproc append {str} {
349     set ns "$s$str"
350     if {[string length $s] && [string length $ns] > 65} {
351         msg__sendout $varbase
352         set s " [string trimleft $str]"
353     } else {
354         set s $ns
355     }
356 }
357
358 def_msgproc finish {} {
359     msg__sendout $varbase
360     unset s
361     unset d
362     return $a
363 }
364
365 def_msgproc _sendout {} {
366     lappend a [string trimright $s]
367     set s {}
368 }
369
370 proc looking_whenwhere {when where} {
371     set str [showtime [expr {$when-1}]]
372     if {[string length $where]} { append str " on $where" }
373     return $str
374 }
375
376 proc recordlastseen_n {n how here} {
377     global lastseen lookedfor
378     set lastseen([irctolower $n]) [list $n [clock seconds] $how]
379     if {!$here} return
380     upvar #0 lookedfor([irctolower $n]) lf
381     if {[info exists lf]} {
382         switch -exact [llength $lf] {
383             0 {
384                 set ml {}
385             }
386             1 {
387                 manyset [lindex $lf 0] when who where
388                 set ml [list \
389  "FYI, $who was looking for you [looking_whenwhere $when $where]."]
390             }
391             default {
392                 msg_begin tosend $n "FYI, people have been looking for you:"
393                 set i 0
394                 set fin ""
395                 foreach e $lf {
396                     incr i
397                     if {$i == 1} {
398                         msg_append tosend " "
399                     } elseif {$i == [llength $lf]} {
400                         msg_append tosend " and "
401                         set fin .
402                     } else {
403                         msg_append tosend ", "
404                     }
405                     manyset $e when who where
406                     msg_append tosend \
407                             "$who ([looking_whenwhere $when $where])$fin"
408                 }
409                 set ml [msg_finish tosend]
410             }
411         }
412         unset lf
413         msendprivmsg_delayed 1000 $n $ml
414     }
415 }
416
417 proc note_topic {showoff whoby topic} {
418     set msg "FYI, $whoby has changed the topic on $showoff"
419     if {[string length $topic] < 160} {
420         append msg " to $topic"
421     } else {
422         append msg " but it is too long to reproduce here !"
423     }
424     set showoff [irctolower $showoff]
425     set tell [chandb_get $showoff topictell]
426     if {[lsearch -exact $tell *] >= 0} {
427         set tryspies [chandb_list]
428     } else {
429         set tryspies $tell
430     }
431     foreach spy $tryspies {
432         set see [chandb_get $spy topicsee]
433         if {[lsearch -exact $see $showoff] >= 0 || \
434                 ([lsearch -exact $see *] >= 0 && \
435                 [lsearch -exact $tell $spy] >= 0)} {
436             sendprivmsg $spy $msg
437         }
438     }
439 }
440
441 proc recordlastseen_p {p how here} {
442     prefix_nick
443     recordlastseen_n $n $how $here
444 }
445
446 proc chanmode_arg {} {
447     upvar 2 args cm_args
448     set rv [lindex $cm_args 0]
449     set cm_args [lreplace cm_args 0 0]
450     return $rv
451 }
452
453 proc chanmode_o1 {m g p chan} {
454     global nick chan_initialop
455     prefix_nick
456     set who [chanmode_arg]
457     recordlastseen_n $n "being nice to $who" 1
458     if {"[irctolower $who]" == "[irctolower $nick]"} {
459         set nlower [irctolower $n]
460         upvar #0 nick_unique($nlower) u
461         if {[chandb_exists $chan]} {
462             sendprivmsg $n Thanks.
463         } elseif {![info exists u]} {
464             sendprivmsg $n {Op me while not on the channel, why don't you ?}
465         } else {
466             set chan_initialop([irctolower $chan]) $u
467             sendprivmsg $n \
468  "Thanks. You can use `channel manager ...' to register this channel."
469             if {![nickdb_exists $n] || ![string length [nickdb_get $n username]]} {
470                 sendprivmsg $n \
471  "(But to do that you must register your nick securely first.)"
472             }
473         }
474     }
475 }
476
477 proc chanmode_o0 {m g p chan} {
478     global nick chandeop
479     prefix_nick
480     set who [chanmode_arg]
481     recordlastseen_p $p "being mean to $who" 1
482     if {"[irctolower $who]" == "[irctolower $nick]"} {
483         set chandeop($chan) [list [clock seconds] $p]
484     }
485 }
486
487 proc msg_MODE {p c dest modelist args} {
488     if {![ischan $dest]} return
489     if {[regexp {^\-(.+)$} $modelist dummy modelist]} {
490         set give 0
491     } elseif {[regexp {^\+(.+)$} $modelist dummy modelist]} {
492         set give 1
493     } else {
494         error "invalid modelist"
495     }
496     foreach m [split $modelist] {
497         set procname chanmode_$m$give
498         if {[catch { info body $procname }]} {
499             recordlastseen_p $p "fiddling with $dest" 1
500         } else {
501             $procname $m $give  $p $dest
502         }
503     }
504 }
505
506 proc leaving {lchan} {
507     foreach luser [array names nick_onchans] {
508         upvar #0 nick_onchans($luser) oc
509         set oc [grep tc {"$tc" != "$lchan"} $oc]
510     }
511     upvar #0 chan_nicks($lchan) nlist
512     unset nlist
513 }
514
515 proc dojoin {lchan} {
516     global chan_nicks
517     sendout JOIN $lchan
518     set chan_nicks($lchan) {}
519 }
520
521 proc check_justme {lchan} {
522     global nick
523     upvar #0 chan_nicks($lchan) nlist
524     if {[llength $nlist] != 1} return
525     if {"[lindex $nlist 0]" != "[irctolower $nick]"} return
526     if {[chandb_exists $lchan]} {
527         set mode [chandb_get $lchan mode]
528         if {"$mode" != "*"} {
529             sendout MODE $lchan $mode
530         }
531         set topic [chandb_get $lchan topicset]
532         if {[string length $topic]} {
533             sendout TOPIC $lchan $topic
534         }
535     } else {
536         sendout PART $lchan
537         leaving $lchan
538     }
539 }
540
541 proc process_kickpart {chan user} {
542     global nick
543     check_nick $user
544     set luser [irctolower $user]
545     set lchan [irctolower $chan]
546     if {![ischan $chan]} { error "not a channel" }
547     if {"$luser" == "[irctolower $nick]"} {
548         leaving $lchan
549     } else {
550         upvar #0 nick_onchans($luser) oc
551         upvar #0 chan_nicks($lchan) nlist
552         set oc [grep tc {"$tc" != "$lchan"} $oc]
553         set nlist [grep tn {"$tn" != "$luser"} $nlist]
554         nick_case $user
555         if {![llength $oc]} {
556             nick_forget $luser
557         } else {
558             check_justme $lchan
559         }
560     }
561 }
562
563 proc msg_TOPIC {p c dest topic} {
564     prefix_nick
565     if {![ischan $dest]} return
566     recordlastseen_n $n "changing the topic on $dest" 1
567     note_topic [irctolower $dest] $n $topic
568 }
569
570 proc msg_KICK {p c chans users comment} {
571     set chans [split $chans ,]
572     set users [split $users ,]
573     if {[llength $chans] > 1} {
574         foreach chan $chans user $users { process_kickpart $chan $user }
575     } else {
576         foreach user $users { process_kickpart [lindex $chans 0] $user }
577     }
578 }
579
580 proc msg_KILL {p c user why} {
581     nick_forget $user
582 }
583
584 set nick_counter 0
585 set nick_arys {onchans username unique}
586 # nick_onchans($luser) -> [list ... $lchan ...]
587 # nick_username($luser) -> <securely known local username>
588 # nick_unique($luser) -> <counter>
589 # nick_case($luser) -> $user  (valid even if no longer visible)
590
591 # chan_nicks($lchan) -> [list ... $luser ...]
592
593 proc lnick_forget {luser} {
594     global nick_arys chan_nicks
595     foreach ary $nick_arys {
596         upvar #0 nick_${ary}($luser) av
597         catch { unset av }
598     }
599     foreach lch [array names chan_nicks] {
600         upvar #0 chan_nicks($lch) nlist
601         set nlist [grep tn {"$tn" != "$luser"} $nlist]
602         check_justme $lch
603     }
604 }
605
606 proc nick_forget {user} {
607     global nick_arys chan_nicks
608     lnick_forget [irctolower $user]
609     nick_case $user
610 }
611
612 proc nick_case {user} {
613     global nick_case
614     set nick_case([irctolower $user]) $user
615 }
616
617 proc msg_NICK {p c newnick} {
618     global nick_arys nick_case
619     prefix_nick
620     recordlastseen_n $n "changing nicks to $newnick" 0
621     recordlastseen_n $newnick "changing nicks from $n" 1
622     foreach ary $nick_arys {
623         upvar #0 nick_${ary}($n) old
624         upvar #0 nick_${ary}($newnick) new
625         if {[info exists new]} { error "nick collision ?! $ary $n $newnick" }
626         if {[info exists old]} { set new $old; unset old }
627     }
628     upvar #0 nick_onchans($new) oc
629     set luser [irctolower $n]
630     set lusernew [irctolower $newnick]
631     foreach ch $oc {
632         upvar #0 chan_nicks($ch) nlist
633         set nlist [grep tn {"$tn" != "$luser"} $nlist]
634         lappend nlist $lusernew
635     }
636     nick_case $newnick
637 }
638
639 proc nick_ishere {n} {
640     global nick_counter
641     upvar #0 nick_unique([irctolower $n]) u
642     if {![info exists u]} { set u [incr nick_counter].$n.[clock seconds] }
643     nick_case $n
644 }
645
646 proc msg_JOIN {p c chan} {
647     prefix_nick
648     recordlastseen_n $n "joining $chan" 1
649     upvar #0 nick_onchans([irctolower $n]) oc
650     lappend oc [irctolower $chan]
651     nick_ishere $n
652 }
653 proc msg_PART {p c chan} {
654     prefix_nick
655     recordlastseen_n $n "leaving $chan" 1
656     process_kickpart $chan $n
657 }
658 proc msg_QUIT {p c why} {
659     prefix_nick
660     recordlastseen_n $n "leaving ($why)" 0
661     nick_forget $n
662 }
663
664 proc msg_PRIVMSG {p c dest text} {
665     prefix_nick
666     if {[ischan $dest]} {
667         recordlastseen_n $n "invoking me in $dest" 1
668         set output $dest
669     } else {
670         recordlastseen_n $n "talking to me" 1
671         set output $n
672     }
673     nick_case $n
674
675     if {[catch {
676         regsub {^! *} $text {} text
677         set ucmd [ta_word]
678         set procname ucmd/[string tolower $ucmd]
679         if {[catch { info body $procname }]} {
680             error "unknown command; try help for help"
681         }
682         $procname $p $dest
683     } rv]} {
684         sendprivmsg $n "error: $rv"
685     } else {
686         manyset $rv priv_msgs pub_msgs priv_acts pub_acts
687         foreach {td val} [list $n $priv_acts $output $pub_acts] {
688             foreach l [split $val "\n"] {
689                 sendaction_priority 0 $td $l
690             }
691         }
692         foreach {td val} [list $n $priv_msgs $output $pub_msgs] {
693             foreach l [split $val "\n"] {
694                 sendprivmsg $td $l
695             }
696         }
697     }
698 }
699
700 proc msg_INVITE {p c n chan} {
701     after 1000 [list dojoin [irctolower $chan]]
702 }
703
704 proc grep {var predicate list} {
705     set o {}
706     upvar 1 $var v
707     foreach v $list {
708         if {[uplevel 1 [list expr $predicate]]} { lappend o $v }
709     }
710     return $o
711 }
712
713 proc msg_353 {p c dest type chan nicklist} {
714     global names_chans nick_onchans
715     set lchan [irctolower $chan]
716     upvar #0 chan_nicks($lchan) nlist
717     lappend names_chans $lchan
718     if {![info exists nlist]} {
719         # We don't think we're on this channel, so ignore it !
720         # Unfortunately, because we don't get a reply to PART,
721         # we have to remember ourselves whether we're on a channel,
722         # and ignore stuff if we're not, to avoid races.  Feh.
723         return
724     }
725     set nlist_new {}
726     foreach user [split $nicklist { }] {
727         regsub {^[@+]} $user {} user
728         if {![string length $user]} continue
729         check_nick $user
730         set luser [irctolower $user]
731         upvar #0 nick_onchans($luser) oc
732         lappend oc $lchan
733         lappend nlist_new $luser
734         nick_ishere $user
735     }
736     set nlist $nlist_new
737 }
738
739 proc msg_366 {p c args} {
740     global names_chans nick_onchans
741     set lchan [irctolower $c]
742     foreach luser [array names nick_onchans] {
743         upvar #0 nick_onchans($luser) oc
744         if {[llength names_chans] > 1} {
745             set oc [grep tc {[lsearch -exact $tc $names_chans] >= 0} $oc]
746         }
747         if {![llength $oc]} { lnick_forget $n }
748     }
749     unset names_chans
750 }
751
752 proc ta_anymore {} {
753     upvar 1 text text
754     return [expr {!![string length $text]}]
755 }
756
757 proc ta_nomore {} {
758     upvar 1 text text
759     if {[string length $text]} { error "too many parameters" }
760 }
761
762 proc ta_word {} {
763     upvar 1 text text
764     if {![regexp {^([^  ]+) *(.*)} $text dummy firstword text]} {
765         error "too few parameters"
766     }
767     return $firstword
768 }
769
770 proc ta_nick {} {
771     upvar 1 text text
772     set v [ta_word]
773     check_nick $v
774     return $v
775 }
776
777 proc def_ucmd {cmdname body} {
778     proc ucmd/$cmdname {p dest} "    upvar 1 text text\n$body"
779 }
780
781 proc ucmdr {priv pub args} {
782     return -code return [concat [list $priv $pub] $args]
783 }
784
785 proc loadhelp {} {
786     global help_topics errorInfo
787
788     catch { unset help_topics }
789     set f [open helpinfos r]
790     try_except_finally {
791         set lno 0
792         while {[gets $f l] >= 0} {
793             incr lno
794             if {[regexp {^#.*} $l]} {
795             } elseif {[regexp {^ *$} $l]} {
796                 if {[info exists topic]} {
797                     set help_topics($topic) [join $lines "\n"]
798                     unset topic
799                     unset lines
800                 }
801             } elseif {[regexp {^\:\:} $l]} {
802             } elseif {[regexp {^\:([-+._0-9a-z]*)$} $l dummy newtopic]} {
803                 if {[info exists topic]} {
804                     error "help $newtopic while in $topic"
805                 }
806                 set topic $newtopic
807                 set lines {}
808             } elseif {[regexp {^[^:#]} $l]} {
809                 set topic
810                 regsub -all {([^\\])\!\$?} _$l {\1} l
811                 regsub -all {\\(.)} $l {\1} l
812                 regsub {^_} $l {} l
813                 lappend lines [string trimright $l]
814             } else {
815                 error "eh ? $lno: $l"
816             }
817         }
818         if {[info exists topic]} { error "unfinished topic $topic" }
819     } {
820         set errorInfo "in helpinfos line $lno\n$errorInfo"
821     } {
822         close $f
823     }
824 }
825
826 def_ucmd help {
827     if {[set lag [out_lagged]]} {
828         if {[ischan $dest]} { set replyto $dest } else { set replyto $n }
829         if {$lag > 1} {
830             sendaction_priority 1 $replyto \
831                 "is very lagged.  Please ask for help again later."
832             ucmdr {} {}
833         } else {
834             sendaction_priority 1 $replyto \
835                 "is lagged.  Your help will arrive shortly ..."
836         }
837     }
838     
839     upvar #0 help_topics([irctolower [string trim $text]]) info
840     if {![info exists info]} { ucmdr "No help on $text, sorry." {} }
841     ucmdr $info {}
842 }
843
844 def_ucmd ? {
845     global help_topics
846     ucmdr $help_topics() {}
847 }
848
849 proc check_username {target} {
850     if {
851         [string length $target] > 8 ||
852         [regexp {[^-0-9a-z]} $target] ||
853         ![regexp {^[a-z]} $target]
854     } { error "invalid username" }
855 }
856
857 proc somedb__head {} {
858     uplevel 1 {
859         set idl [irctolower $id]
860         upvar #0 ${nickchan}db($idl) ndbe
861         binary scan $idl H* idh
862         set idfn $fprefix$idh
863         if {![info exists iddbe] && [file exists $idfn]} {
864             set f [open $idfn r]
865             try_except_finally { set newval [read $f] } {} { close $f }
866             if {[llength $newval] % 2} { error "invalid length" }
867             set iddbe $newval
868         }
869     }
870 }
871
872 proc def_somedb {name arglist body} {
873     foreach {nickchan fprefix} {nick users/n chan chans/c} {
874         proc ${nickchan}db_$name $arglist \
875             "set nickchan $nickchan; set fprefix $fprefix; $body"
876     }
877 }
878
879 def_somedb list {} {
880     set list {}
881     foreach path [glob -nocomplain -path $fprefix *] {
882         binary scan $path "A[string length $fprefix]A*" afprefix thinghex
883         if {"$afprefix" != "$fprefix"} { error "wrong prefix $path $afprefix" }
884         lappend list [binary format H* $thinghex]
885     }
886     return $list
887 }
888
889 proc def_somedb_id {name arglist body} {
890     def_somedb $name [concat id $arglist] "somedb__head; $body"
891 }
892
893 def_somedb_id exists {} {
894     return [info exists iddbe]
895 }
896
897 def_somedb_id delete {} {
898     catch { unset iddbe }
899     file delete $idfn
900 }
901
902 set default_settings_nick {timeformat ks}
903 set default_settings_chan {
904     autojoin 1
905     mode *
906     userinvite pub
907     topicset {}
908     topicsee {}
909     topictell {}
910 }
911
912 def_somedb_id set {args} {
913     upvar #0 default_settings_$nickchan def
914     if {![info exists iddbe]} { set iddbe $def }
915     foreach {key value} [concat $iddbe $args] { set a($key) $value }
916     set newval {}
917     foreach {key value} [array get a] { lappend newval $key $value }
918     set f [open $idfn.new w]
919     try_except_finally {
920         puts $f $newval
921         close $f
922         file rename -force $idfn.new $idfn
923     } {
924     } {
925         catch { close $f }
926     }
927     set iddbe $newval
928 }
929
930 def_somedb_id get {key} {
931     upvar #0 default_settings_$nickchan def
932     if {[info exists iddbe]} {
933         set l [concat $iddbe $def]
934     } else {
935         set l $def
936     }
937     foreach {tkey value} $l {
938         if {"$tkey" == "$key"} { return $value }
939     }
940     error "unset setting $key"
941 }
942
943 proc opt {key} {
944     global calling_nick
945     if {[info exists calling_nick]} { set n $calling_nick } { set n {} }
946     return [nickdb_get $n $key]
947 }
948
949 proc check_notonchan {} {
950     upvar 1 dest dest
951     if {[ischan $dest]} { error "that command must be sent privately" }
952 }
953
954 proc nick_securitycheck {strict} {
955     upvar 1 n n
956     if {![nickdb_exists $n]} { error "you are unknown to me, use `register'." }
957     set wantu [nickdb_get $n username]
958     if {![string length $wantu]} {
959         if {$strict} {
960             error "that feature is only available to secure users, sorry."
961         } else {
962             return
963         }
964     }
965     set luser [irctolower $n]
966     upvar #0 nick_username($luser) nu
967     if {![info exists nu]} {
968         error "nick $n is secure, you must identify yourself first."
969     }
970     if {"$wantu" != "$nu"} {
971         error "you are the wrong user - the nick $n belongs to $wantu, not $nu"
972     }
973 }
974
975 proc channel_securitycheck {channel n} {
976     # You must also call `nick_securitycheck 1'
977     set mgrs [chandb_get $channel managers]
978     if {[lsearch -exact [irctolower $mgrs] [irctolower $n]] < 0} {
979         error "you are not a manager of $channel"
980     }
981 }
982
983 proc def_chancmd {name body} {
984     proc channel/$name {} \
985             "    upvar 1 target chan; upvar 1 n n; upvar 1 text text; $body"
986 }
987
988 proc ta_listop {findnow procvalue} {
989     # findnow and procvalue are code fragments which will be executed
990     # in the caller's level.  findnow should set ta_listop_ev to
991     # the current list, and procvalue should treat ta_listop_ev as
992     # a proposed value in the list and check and possibly modify
993     # (canonicalise?) it.  After ta_listop, ta_listop_ev will
994     # be the new value of the list.
995     upvar 1 ta_listop_ev exchg
996     upvar 1 text text
997     set opcode [ta_word]
998     switch -exact _$opcode {
999         _= { }
1000         _+ - _- {
1001             uplevel 1 $findnow
1002             foreach item $exchg { set array($item) 1 }
1003         }
1004         default {
1005             error "list change opcode must be one of + - ="
1006         }
1007     }
1008     foreach exchg [split $text " "] {
1009         if {![string length $exchg]} continue
1010         uplevel 1 $procvalue
1011         if {"$opcode" != "-"} {
1012             set array($exchg) 1
1013         } else {
1014             catch { unset array($exchg) }
1015         }
1016     }
1017     set exchg [lsort [array names array]]
1018 }
1019
1020 def_chancmd manager {
1021     ta_listop {
1022         if {[chandb_exists $chan]} {
1023             set ta_listop_ev [chandb_get $chan managers]
1024         } else {
1025             set ta_listop_ev [list [irctolower $n]]
1026         }
1027     } {
1028         check_nick $ta_listop_ev
1029         set ta_listop_ev [irctolower $ta_listop_ev]
1030     }
1031     if {[llength $ta_listop_ev]} {
1032         chandb_set $chan managers $ta_listop_ev
1033         ucmdr "Managers of $chan: $ta_listop_ev" {}
1034     } else {
1035         chandb_delete $chan
1036         ucmdr {} {} "forgets about managing $chan." {}
1037     }
1038 }
1039
1040 def_chancmd autojoin {
1041     set yesno [ta_word]
1042     switch -exact [string tolower $yesno] {
1043         no { set nv 0 }
1044         yes { set nv 1 }
1045         default { error "channel autojoin must be `yes' or `no' }
1046     }
1047     chandb_set $chan autojoin $nv
1048     ucmdr [expr {$nv ? "I will join $chan when I'm restarted " : \
1049             "I won't join $chan when I'm restarted "}] {}
1050 }
1051
1052 def_chancmd userinvite {
1053     set nv [string tolower [ta_word]]
1054     switch -exact $nv {
1055         pub { set txt "!invite will work for $chan, but it won't work by /msg" }
1056         here { set txt "!invite and /msg invite will work, but only for users who are already on $chan." }
1057         all { set txt "Any user will be able to invite themselves or anyone else to $chan." }
1058         none { set txt "I will not invite anyone to $chan." }
1059         default {
1060             error "channel userinvite must be `pub', `here', `all' or `none'
1061         }
1062     }
1063     chandb_set $chan userinvite $nv
1064     ucmdr $txt {}
1065 }
1066
1067 def_chancmd topic {
1068     set what [ta_word]
1069     switch -exact $what {
1070         leave {
1071             ta_nomore
1072             chandb_set $chan topicset {}
1073             ucmdr "I won't ever change the topic of $chan." {}
1074         }
1075         set {
1076             set t [string trim $text]
1077             if {![string length $t]} {
1078                 error "you must specific the topic to set"
1079             }
1080             chandb_set $chan topicset $t
1081             ucmdr "Whenever I'm alone on $chan, I'll set the topic to $t." {}
1082         }
1083         see - tell {
1084             ta_listop {
1085                 set ta_listop_ev [chandb_get $chan topic$what]
1086             } {
1087                 if {"$ta_listop_ev" != "*"} {
1088                     if {![ischan $ta_listop_ev]} {
1089                         error "bad channel \`$ta_listop_ev' in topic $what"
1090                     }
1091                     set ta_listop_ev [irctolower $ta_listop_ev]
1092                 }
1093             }
1094             chandb_set $chan topic$what $ta_listop_ev
1095             ucmdr "Topic $what list for $chan: $ta_listop_ev" {}
1096         }
1097         default {
1098             error "unknown channel topic subcommand - see help channel"
1099         }
1100     }
1101 }
1102
1103 def_chancmd mode {
1104     set mode [ta_word]
1105     if {"$mode" != "*" && ![regexp {^(([-+][imnpst]+)+)$} $mode mode]} {
1106         error {channel mode must be * or match ([-+][imnpst]+)+}
1107     }
1108     chandb_set $chan mode $mode
1109     if {"$mode" == "*"} {
1110         ucmdr "I won't ever change the mode of $chan." {}
1111     } else {
1112         ucmdr "Whenever I'm alone on $chan, I'll set the mode to $mode." {}
1113     }
1114 }
1115
1116 def_chancmd show {
1117     if {[chandb_exists $chan]} {
1118         set l "Settings for $chan: autojoin "
1119         append l [lindex {no yes} [chandb_get $chan autojoin]]
1120         append l ", mode " [chandb_get $chan mode]
1121         append l ", userinvite " [chandb_get $chan userinvite] "."
1122         append l "\nManagers: "
1123         append l [join [chandb_get $chan managers] " "]
1124         foreach {ts sep} {see "\n" tell "  "} {
1125             set t [chandb_get $chan topic$ts]
1126             append l $sep
1127             if {[llength $t]} {
1128                 append l "Topic $ts list: $t."
1129             } else {
1130                 append l "Topic $ts list is empty."
1131             }
1132         }
1133         append l "\n"
1134         set t [chandb_get $chan topicset]
1135         if {[string length $t]} {
1136             append l "Topic to set: $t"
1137         } else {
1138             append l "I will not change the topic."
1139         }
1140         ucmdr {} $l
1141     } else {
1142         ucmdr {} "The channel $chan is not managed."
1143     }
1144 }
1145
1146 def_ucmd op {
1147     if {[ischan $dest]} { set target $dest }
1148     if {[ta_anymore]} { set target [ta_word] }
1149     ta_nomore
1150     if {![info exists target]} { error "you must specify, or !... on, the channel" }
1151     if {![ischan $target]} { error "not a valid channel" }
1152     if {![chandb_exists $target]} { error "$target is not a managed channel." }
1153     prefix_nick
1154     nick_securitycheck 1
1155     channel_securitycheck $target $n
1156     sendout MODE $target +o $n
1157 }
1158
1159 def_ucmd invite {
1160     global chan_nicks
1161     
1162     if {[ischan $dest]} {
1163         set target $dest
1164         set onchan 1
1165     } else {
1166         set target [ta_word]
1167         set onchan 0
1168     }
1169     set ltarget [irctolower $target]
1170     if {![ischan $target]} { error "$target is not a channel." }
1171     if {![info exists chan_nicks($ltarget)]} { error "I am not on $target." }
1172     set ui [chandb_get $ltarget userinvite]
1173     if {"$ui" == "pub" && !$onchan} {
1174         error "Invitations to $target must be made with !invite."
1175     }
1176     if {"$ui" != "all"} {
1177         prefix_nick
1178         if {[lsearch -exact $chan_nicks($ltarget) [irctolower $n]] < 0} {
1179  error "Invitations to $target may only be made by a user on the channel."
1180         }
1181     }
1182     if {"$ui" == "none"} {
1183         error "Sorry, I've not been authorised to invite people to $target."
1184     }
1185     if {![ta_anymore]} {
1186         error "You have to say who to invite."
1187     }
1188     set invitees {}
1189     while {[ta_anymore]} {
1190         set invitee [ta_word]
1191         check_nick $invitee
1192         lappend invitees $invitee
1193     }
1194     foreach invitee $invitees {
1195         sendout INVITE $invitee $ltarget
1196     }
1197     set who [lindex $invitees 0]
1198     switch -exact llength $invitees {
1199         0 { error "zero invitees" }
1200         1 { }
1201         2 { append who " and [lindex $invitees 1]" }
1202         * {
1203             set who [join [lreplace $invitees end end] ", "]
1204             append who " and [lindex $invitees [llength $invitees]]"
1205         }
1206     }
1207     ucmdr {} "invites $who to $target."
1208 }
1209
1210 def_ucmd channel {
1211     if {[ischan $dest]} { set target $dest }
1212     if {![ta_anymore]} {
1213         set subcmd show
1214     } else {
1215         set subcmd [ta_word]
1216     }
1217     if {[ischan $subcmd]} {
1218         set target $subcmd
1219         if {![ta_anymore]} {
1220             set subcmd show
1221         } else {
1222             set subcmd [ta_word]
1223         }
1224     }
1225     if {![info exists target]} { error "privately, you must specify a channel" }
1226     set procname channel/$subcmd
1227     if {"$subcmd" != "show"} {
1228         if {[catch { info body $procname }]} { error "unknown channel setting $subcmd" }
1229         prefix_nick
1230         nick_securitycheck 1
1231         if {[chandb_exists $target]} {
1232             channel_securitycheck $target $n
1233         } else {
1234             upvar #0 chan_initialop([irctolower $target]) io
1235             upvar #0 nick_unique([irctolower $n]) u
1236             if {![info exists io]} { error "$target is not a managed channel" }
1237             if {"$io" != "$u"} { error "you are not the interim manager of $target" }
1238             if {"$subcmd" != "manager"} { error "use `channel manager' first" }
1239         }
1240     }
1241     channel/$subcmd
1242 }
1243
1244 def_ucmd who {
1245     if {[ta_anymore]} {
1246         set target [ta_word]; ta_nomore
1247         set myself 1
1248     } else {
1249         prefix_nick
1250         set target $n
1251         set myself [expr {"$target" != "$n"}]
1252     }
1253     set ltarget [irctolower $target]
1254     upvar #0 nick_case($ltarget) ctarget
1255     set nshow $target
1256     if {[info exists ctarget]} {
1257         upvar #0 nick_onchans($ltarget) oc
1258         upvar #0 nick_username($ltarget) nu
1259         if {[info exists oc]} { set nshow $ctarget }
1260     }
1261     if {![nickdb_exists $ltarget]} {
1262         set ol "$nshow is not a registered nick."
1263     } elseif {[string length [set username [nickdb_get $target username]]]} {
1264         set ol "The nick $nshow belongs to the user $username."
1265     } else {
1266         set ol "The nick $nshow is registered (but not to a username)."
1267     }
1268     if {![info exists ctarget] || ![info exists oc]} {
1269         if {$myself} {
1270             append ol "\nI can't see $nshow on anywhere."
1271         } else {
1272             append ol "\nYou aren't on any channels with me."
1273         }
1274     } elseif {![info exists nu]} {
1275         append ol "\n$nshow has not identified themselves."
1276     } elseif {![info exists username]} {
1277         append ol "\n$nshow has identified themselves as the user $nu."
1278     } elseif {"$nu" != "$username"} {
1279         append ol "\nHowever, $nshow is being used by the user $nu."
1280     } else {
1281         append ol "\n$nshow has identified themselves to me."
1282     }
1283     ucmdr {} $ol
1284 }
1285
1286 def_ucmd register {
1287     prefix_nick
1288     check_notonchan
1289     set old [nickdb_exists $n]
1290     if {$old} { nick_securitycheck 0 }
1291     set luser [irctolower $n]
1292     switch -exact [string tolower [string trim $text]] {
1293         {} {
1294             upvar #0 nick_username($luser) nu
1295             if {![info exists nu]} {
1296                 ucmdr {} \
1297  "You must identify yourself before using `register'.  See `help identify', or use `register insecure'."
1298             }
1299             nickdb_set $n username $nu
1300             ucmdr {} {} "makes a note of your username." {}
1301         }
1302         delete {
1303             nickdb_delete $n
1304             ucmdr {} {} "forgets your nickname." {}
1305         }
1306         insecure {
1307             nickdb_set $n username {}
1308             if {$old} {
1309                 ucmdr {} "Security is now disabled for your nickname !"
1310             } else {
1311                 ucmdr {} "This is fine, but bear in mind that people will be able to mess with your settings.  Channel management features need a secure registration." "makes an insecure registration for your nick."
1312             }
1313         }
1314     }
1315 }
1316
1317 proc timeformat_desc {tf} {
1318     switch -exact $tf {
1319         ks { return "Times will be displayed in seconds or kiloseconds." }
1320         hms { return "Times will be displayed in hours, minutes, etc." }
1321         default { error "invalid timeformat: $v" }
1322     }
1323 }
1324
1325 proc def_setting {opt show_body set_body} {
1326     proc set_show/$opt {} "
1327         upvar 1 n n
1328         set opt $opt
1329         $show_body"
1330     if {![string length $set_body]} return
1331     proc set_set/$opt {} "
1332         upvar 1 n n
1333         upvar 1 text text
1334         set opt $opt
1335         $set_body"
1336 }
1337
1338 def_setting timeformat {
1339     set tf [nickdb_get $n timeformat]
1340     return "$tf: [timeformat_desc $tf]"
1341 } {
1342     set tf [string tolower [ta_word]]
1343     ta_nomore
1344     set desc [timeformat_desc $tf]
1345     nickdb_set $n timeformat $tf
1346     ucmdr {} $desc
1347 }
1348
1349 def_setting security {
1350     set s [nickdb_get $n username]
1351     if {[string length $s]} {
1352         return "Your nick, $n, is controlled by the user $s."
1353     } else {
1354         return "Your nick, $n, is not secure."
1355     }
1356 } {}
1357
1358 def_ucmd set {
1359     prefix_nick
1360     check_notonchan
1361     if {![nickdb_exists $n]} {
1362         ucmdr {} "You are unknown to me and so have no settings.  (Use `register'.)"
1363     }
1364     if {![ta_anymore]} {
1365         set ol {}
1366         foreach proc [lsort [info procs]] {
1367             if {![regexp {^set_show/(.*)$} $proc dummy opt]} continue
1368             lappend ol [format "%-10s %s" $opt [set_show/$opt]]
1369         }
1370         ucmdr {} [join $ol "\n"]
1371     } else {
1372         set opt [ta_word]
1373         if {[catch { info body set_show/$opt }]} {
1374             error "no setting $opt"
1375         }
1376         if {![ta_anymore]} {
1377             ucmdr {} "$opt [set_show/$opt]"
1378         } else {
1379             nick_securitycheck 0
1380             if {[catch { info body set_set/$opt }]} {
1381                 error "setting $opt cannot be set with `set'"
1382             }
1383             set_set/$opt
1384         }
1385     }
1386 }
1387
1388 def_ucmd identpass {
1389     set username [ta_word]
1390     set passmd5 [md5sum "[ta_word]\n"]
1391     ta_nomore
1392     prefix_nick
1393     check_notonchan
1394     set luser [irctolower $n]
1395     upvar #0 nick_onchans($luser) onchans
1396     if {![info exists onchans] || ![llength $onchans]} {
1397         ucmdr "You must be on a channel with me to identify yourself." {}
1398     }
1399     check_username $username
1400     exec userv --timeout 3 $username << "$passmd5\n" > /dev/null \
1401             irc-identpass $n
1402     upvar #0 nick_username($luser) rec_username
1403     set rec_username $username
1404     ucmdr "Pleased to see you, $username." {}
1405 }
1406
1407 def_ucmd summon {
1408     set target [ta_word]
1409     ta_nomore
1410     check_username $target
1411     prefix_nick
1412
1413     upvar #0 lastsummon($target) ls
1414     set now [clock seconds]
1415     if {[info exists ls]} {
1416         set interval [expr {$now - $ls}]
1417         if {$interval < 30} {
1418             ucmdr {} \
1419  "Please be patient; $target was summoned only [showinterval $interval]."
1420         }
1421     }
1422     regsub {^[^!]*!} $p {} path
1423     if {[catch {
1424         exec userv --timeout 3 $target irc-summon $n $path \
1425                 [expr {[ischan $dest] ? "$dest" : ""}] \
1426                 < /dev/null
1427     } rv]} {
1428         regsub -all "\n" $rv { / } rv
1429         error $rv
1430     }
1431     if {[regexp {^problem (.*)} $rv dummy problem]} {
1432         ucmdr {} "The user `$target' $problem."
1433     } elseif {[regexp {^ok ([^ ]+) ([0-9]+)$} $rv dummy tty idlesince]} {
1434         set idletime [expr {$now - $idlesince}]
1435         set ls $now
1436         ucmdr {} {} {} "invites $target ($tty[expr {
1437             $idletime > 10 ? ", idle for [showintervalsecs $idletime]" : ""
1438         }]) to [expr {
1439             [ischan $dest] ? "join us here" : "talk to you"
1440         }]."
1441     } else {
1442         error "unexpected response from userv service: $rv"
1443     }
1444 }
1445
1446 proc md5sum {value} { exec md5sum << $value }
1447
1448 def_ucmd seen {
1449     global lastseen nick
1450     prefix_nick
1451     set ncase [ta_nick]
1452     set nlower [irctolower $ncase]
1453     ta_nomore
1454     set now [clock seconds]
1455     if {"$nlower" == "[irctolower $nick]"} {
1456         error "I am not self-aware."
1457     } elseif {![info exists lastseen($nlower)]} {
1458         set rstr "I've never seen $ncase."
1459     } else {
1460         manyset $lastseen($nlower) realnick time what
1461         set howlong [expr {$now - $time}]
1462         set string [showinterval $howlong]
1463         set rstr "I last saw $realnick $string, $what."
1464     }
1465     if {[ischan $dest]} {
1466         set where $dest
1467     } else {
1468         set where {}
1469     }
1470     upvar #0 lookedfor($nlower) lf
1471     if {[info exists lf]} { set oldvalue $lf } else { set oldvalue {} }
1472     set lf [list [list $now $n $where]]
1473     foreach v $oldvalue {
1474         if {"[irctolower [lindex $v 1]]" == "[irctolower $n]"} continue
1475         lappend lf $v
1476     }
1477     ucmdr {} $rstr
1478 }
1479
1480 proc ensure_globalsecret {} {
1481     global globalsecret
1482     
1483     if {[info exists globalsecret]} return
1484     set gsfile [open /dev/urandom r]
1485     fconfigure $gsfile -translation binary
1486     set globalsecret [read $gsfile 32]
1487     binary scan $globalsecret H* globalsecret
1488     close $gsfile
1489     unset gsfile
1490 }
1491
1492 proc ensure_outqueue {} {
1493     out__vars
1494     if {[info exists out_queue]} return
1495     set out_creditms 0
1496     set out_creditat [clock seconds]
1497     set out_queue {}
1498     set out_lag_reported 0
1499     set out_lag_reportwhen $out_creditat
1500 }
1501
1502 proc fail {msg} {
1503     logerror "failing: $msg"
1504     exit 1
1505 }
1506
1507 proc ensure_connecting {} {
1508     global sock ownfullname host port nick
1509     global musthaveping_ms musthaveping_after
1510     
1511     if {[info exists sock]} return
1512     set sock [socket $host $port]
1513     fconfigure $sock -buffering line
1514     fconfigure $sock -translation crlf
1515
1516     sendout USER blight 0 * $ownfullname
1517     sendout NICK $nick
1518     fileevent $sock readable onread
1519
1520     set musthaveping_after [after $musthaveping_ms \
1521             {fail "no ping within timeout"}]
1522 }
1523
1524 proc connected {} {
1525     global musthaveping_after
1526
1527     after cancel $musthaveping_after
1528     unset musthaveping_after
1529
1530     foreach chan [chandb_list] {
1531         if {[chandb_get $chan autojoin]} { dojoin $chan }
1532     }
1533 }
1534
1535 ensure_globalsecret
1536 ensure_outqueue
1537 loadhelp
1538 ensure_connecting