chiark / gitweb /
bbee0a0b86e6643117a3e9414885eea97cfd9470
[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     if {[string length $whoby]} {
419         set msg "FYI, $whoby has changed the topic on $showoff"
420     } else {
421         set msg "FYI, I have reset the topic on $showoff"
422     }
423     if {[string length $topic] < 160} {
424         append msg " to $topic"
425     } else {
426         append msg " but it is too long to reproduce here !"
427     }
428     set showoff [irctolower $showoff]
429     set tell [chandb_get $showoff topictell]
430     if {[lsearch -exact $tell *] >= 0} {
431         set tryspies [chandb_list]
432     } else {
433         set tryspies $tell
434     }
435 puts "NT>showoff $showoff|whoby $whoby|topic $topic|tell $tell|tryspies $tryspies|msg $msg<"
436     foreach spy $tryspies {
437         set see [chandb_get $spy topicsee]
438 puts "NT>spy $spy|see $see<"
439         if {[lsearch -exact $see $showoff] >= 0 || \
440                 ([lsearch -exact $see *] >= 0 && \
441                 [lsearch -exact $tell $spy] >= 0)} {
442             sendprivmsg $spy $msg
443         }
444     }
445 }
446
447 proc recordlastseen_p {p how here} {
448     prefix_nick
449     recordlastseen_n $n $how $here
450 }
451
452 proc chanmode_arg {} {
453     upvar 2 args cm_args
454     set rv [lindex $cm_args 0]
455     set cm_args [lreplace cm_args 0 0]
456     return $rv
457 }
458
459 proc chanmode_o1 {m g p chan} {
460     global nick chan_initialop
461     prefix_nick
462     set who [chanmode_arg]
463     recordlastseen_n $n "being nice to $who" 1
464     if {"[irctolower $who]" == "[irctolower $nick]"} {
465         set nlower [irctolower $n]
466         upvar #0 nick_unique($nlower) u
467         if {[chandb_exists $chan]} {
468             sendprivmsg $n Thanks.
469         } elseif {![info exists u]} {
470             sendprivmsg $n {Op me while not on the channel, why don't you ?}
471         } else {
472             set chan_initialop([irctolower $chan]) $u
473             sendprivmsg $n \
474  "Thanks. You can use `channel manager ...' to register this channel."
475             if {![nickdb_exists $n] || ![string length [nickdb_get $n username]]} {
476                 sendprivmsg $n \
477  "(But to do that you must register your nick securely first.)"
478             }
479         }
480     }
481 }
482
483 proc chanmode_o0 {m g p chan} {
484     global nick chandeop
485     prefix_nick
486     set who [chanmode_arg]
487     recordlastseen_p $p "being mean to $who" 1
488     if {"[irctolower $who]" == "[irctolower $nick]"} {
489         set chandeop($chan) [list [clock seconds] $p]
490     }
491 }
492
493 proc msg_MODE {p c dest modelist args} {
494     if {![ischan $dest]} return
495     if {[regexp {^\-(.+)$} $modelist dummy modelist]} {
496         set give 0
497     } elseif {[regexp {^\+(.+)$} $modelist dummy modelist]} {
498         set give 1
499     } else {
500         error "invalid modelist"
501     }
502     foreach m [split $modelist] {
503         set procname chanmode_$m$give
504         if {[catch { info body $procname }]} {
505             recordlastseen_p $p "fiddling with $dest" 1
506         } else {
507             $procname $m $give  $p $dest
508         }
509     }
510 }
511
512 proc leaving {lchan} {
513     foreach luser [array names nick_onchans] {
514         upvar #0 nick_onchans($luser) oc
515         set oc [grep tc {"$tc" != "$lchan"} $oc]
516     }
517     upvar #0 chan_nicks($lchan) nlist
518     unset nlist
519 }
520
521 proc dojoin {lchan} {
522     global chan_nicks
523     sendout JOIN $lchan
524     set chan_nicks($lchan) {}
525 }
526
527 proc check_justme {lchan} {
528     global nick
529     upvar #0 chan_nicks($lchan) nlist
530     if {[llength $nlist] != 1} return
531     if {"[lindex $nlist 0]" != "$nick"} return
532     if {[chandb_exists $lchan]} {
533         set mode [chandb_get $lchan mode]
534         if {"$mode" != "*"} {
535             sendout MODE $lchan $mode
536         }
537         set topic [chandb_get $lchan topicset]
538         if {[string length $topic]} {
539             sendout TOPIC $lchan $topic
540             note_topic $lchan {} $topic
541         }
542     } else {
543         sendout PART $lchan
544         leaving $lchan
545     }
546 }
547
548 proc process_kickpart {chan user} {
549     global nick
550     check_nick $user
551     set luser [irctolower $user]
552     set lchan [irctolower $chan]
553     if {![ischan $chan]} { error "not a channel" }
554     if {"$luser" == "[irctolower $nick]"} {
555         leaving $lchan
556     } else {
557         upvar #0 nick_onchans($luser) oc
558         upvar #0 chan_nicks($lchan) nlist
559         set oc [grep tc {"$tc" != "$lchan"} $oc]
560         set nlist [grep tn {"$tn" != "$luser"} $nlist]
561         nick_case $user
562         if {![llength $oc]} {
563             nick_forget $luser
564         } else {
565             check_justme $lchan
566         }
567     }
568 }
569
570 proc msg_TOPIC {p c dest topic} {
571     prefix_nick
572     if {![ischan $dest]} return
573     recordlastseen_n $n "changing the topic on $dest" 1
574     note_topic [irctolower $dest] $n $topic
575 }
576
577 proc msg_KICK {p c chans users comment} {
578     set chans [split $chans ,]
579     set users [split $users ,]
580     if {[llength $chans] > 1} {
581         foreach chan $chans user $users { process_kickpart $chan $user }
582     } else {
583         foreach user $users { process_kickpart [lindex $chans 0] $user }
584     }
585 }
586
587 proc msg_KILL {p c user why} {
588     nick_forget $user
589 }
590
591 set nick_counter 0
592 set nick_arys {onchans username unique}
593 # nick_onchans($luser) -> [list ... $lchan ...]
594 # nick_username($luser) -> <securely known local username>
595 # nick_unique($luser) -> <counter>
596 # nick_case($luser) -> $user  (valid even if no longer visible)
597
598 # chan_nicks($lchan) -> [list ... $luser ...]
599
600 proc lnick_forget {luser} {
601     global nick_arys chan_nicks
602     foreach ary $nick_arys {
603         upvar #0 nick_${ary}($luser) av
604         catch { unset av }
605     }
606     foreach lch [array names chan_nicks] {
607         upvar #0 chan_nicks($lch) nlist
608         set nlist [grep tn {"$tn" != "$luser"} $nlist]
609         check_justme $lch
610     }
611 }
612
613 proc nick_forget {user} {
614     global nick_arys chan_nicks
615     lnick_forget [irctolower $user]
616     nick_case $user
617 }
618
619 proc nick_case {user} {
620     global nick_case
621     set nick_case([irctolower $user]) $user
622 }
623
624 proc msg_NICK {p c newnick} {
625     global nick_arys nick_case
626     prefix_nick
627     recordlastseen_n $n "changing nicks to $newnick" 0
628     recordlastseen_n $newnick "changing nicks from $n" 1
629     foreach ary $nick_arys {
630         upvar #0 nick_${ary}($n) old
631         upvar #0 nick_${ary}($newnick) new
632         if {[info exists new]} { error "nick collision ?! $ary $n $newnick" }
633         if {[info exists old]} { set new $old; unset old }
634     }
635     upvar #0 nick_onchans($new)
636     set luser [irctolower $n]
637     set lusernew [irctolower $newnick]
638     foreach ch $oc {
639         upvar #0 chan_nicks($ch) nlist
640         set nlist [grep tn {"$tn" != "$luser"} $nlist]
641         lappend nlist $lusernew
642     }
643     nick_case $newnick
644 }
645
646 proc nick_ishere {n} {
647     global nick_counter
648     upvar #0 nick_unique([irctolower $n]) u
649     if {![info exists u]} { set u [incr nick_counter].$n.[clock seconds] }
650     nick_case $n
651 }
652
653 proc msg_JOIN {p c chan} {
654     prefix_nick
655     recordlastseen_n $n "joining $chan" 1
656     upvar #0 nick_onchans([irctolower $n]) oc
657     lappend oc [irctolower $chan]
658     nick_ishere $n
659 }
660 proc msg_PART {p c chan} {
661     prefix_nick
662     recordlastseen_n $n "leaving $chan" 1
663     process_kickpart $chan $n
664 }
665 proc msg_QUIT {p c why} {
666     prefix_nick
667     recordlastseen_n $n "leaving ($why)" 0
668     nick_forget $n
669 }
670
671 proc msg_PRIVMSG {p c dest text} {
672     prefix_nick
673     if {[ischan $dest]} {
674         recordlastseen_n $n "invoking me in $dest" 1
675         set output $dest
676     } else {
677         recordlastseen_n $n "talking to me" 1
678         set output $n
679     }
680     nick_case $n
681
682     if {[catch {
683         regsub {^! *} $text {} text
684         set ucmd [ta_word]
685         set procname ucmd/[string tolower $ucmd]
686         if {[catch { info body $procname }]} {
687             error "unknown command; try help for help"
688         }
689         $procname $p $dest
690     } rv]} {
691         sendprivmsg $n "error: $rv"
692     } else {
693         manyset $rv priv_msgs pub_msgs priv_acts pub_acts
694         foreach {td val} [list $n $priv_acts $output $pub_acts] {
695             foreach l [split $val "\n"] {
696                 sendaction_priority 0 $td $l
697             }
698         }
699         foreach {td val} [list $n $priv_msgs $output $pub_msgs] {
700             foreach l [split $val "\n"] {
701                 sendprivmsg $td $l
702             }
703         }
704     }
705 }
706
707 proc msg_INVITE {p c n chan} {
708     after 1000 [list dojoin [irctolower $chan]]
709 }
710
711 proc grep {var predicate list} {
712     set o {}
713     upvar 1 $var v
714     foreach v $list {
715         if {[uplevel 1 [list expr $predicate]]} { lappend o $v }
716     }
717     return $o
718 }
719
720 proc msg_353 {p c dest type chan nicklist} {
721     global names_chans nick_onchans
722     set lchan [irctolower $chan]
723     upvar #0 chan_nicks($lchan) nlist
724     lappend names_chans $lchan
725     if {![info exists nlist]} {
726         # We don't think we're on this channel, so ignore it !
727         # Unfortunately, because we don't get a reply to PART,
728         # we have to remember ourselves whether we're on a channel,
729         # and ignore stuff if we're not, to avoid races.  Feh.
730         return
731     }
732     set nlist_new {}
733     foreach user [split $nicklist { }] {
734         regsub {^[@+]} $user {} user
735         if {![string length $user]} continue
736         check_nick $user
737         set luser [irctolower $user]
738         upvar #0 nick_onchans($luser) oc
739         lappend oc $lchan
740         lappend nlist_new $luser
741         nick_ishere $user
742     }
743     set nlist $nlist_new
744 }
745
746 proc msg_366 {p c args} {
747     global names_chans nick_onchans
748     set lchan [irctolower $c]
749     foreach luser [array names nick_onchans] {
750         upvar #0 nick_onchans($luser) oc
751         if {[llength names_chans] > 1} {
752             set oc [grep tc {[lsearch -exact $tc $names_chans] >= 0} $oc]
753         }
754         if {![llength $oc]} { lnick_forget $n }
755     }
756     unset names_chans
757 }
758
759 proc ta_anymore {} {
760     upvar 1 text text
761     return [expr {!![string length $text]}]
762 }
763
764 proc ta_nomore {} {
765     upvar 1 text text
766     if {[string length $text]} { error "too many parameters" }
767 }
768
769 proc ta_word {} {
770     upvar 1 text text
771     if {![regexp {^([^  ]+) *(.*)} $text dummy firstword text]} {
772         error "too few parameters"
773     }
774     return $firstword
775 }
776
777 proc ta_nick {} {
778     upvar 1 text text
779     set v [ta_word]
780     check_nick $v
781     return $v
782 }
783
784 proc def_ucmd {cmdname body} {
785     proc ucmd/$cmdname {p dest} "    upvar 1 text text\n$body"
786 }
787
788 proc ucmdr {priv pub args} {
789     return -code return [concat [list $priv $pub] $args]
790 }
791
792 proc loadhelp {} {
793     global help_topics errorInfo
794
795     catch { unset help_topics }
796     set f [open helpinfos r]
797     try_except_finally {
798         set lno 0
799         while {[gets $f l] >= 0} {
800             incr lno
801             if {[regexp {^#.*} $l]} {
802             } elseif {[regexp {^ *$} $l]} {
803                 if {[info exists topic]} {
804                     set help_topics($topic) [join $lines "\n"]
805                     unset topic
806                     unset lines
807                 }
808             } elseif {[regexp {^\:\:} $l]} {
809             } elseif {[regexp {^\:([-+._0-9a-z]*)$} $l dummy newtopic]} {
810                 if {[info exists topic]} {
811                     error "help $newtopic while in $topic"
812                 }
813                 set topic $newtopic
814                 set lines {}
815             } elseif {[regexp {^[^:#]} $l]} {
816                 set topic
817                 regsub -all {([^\\])\!\$?} _$l {\1} l
818                 regsub -all {\\(.)} $l {\1} l
819                 regsub {^_} $l {} l
820                 lappend lines [string trimright $l]
821             } else {
822                 error "eh ? $lno: $l"
823             }
824         }
825         if {[info exists topic]} { error "unfinished topic $topic" }
826     } {
827         set errorInfo "in helpinfos line $lno\n$errorInfo"
828     } {
829         close $f
830     }
831 }
832
833 def_ucmd help {
834     if {[set lag [out_lagged]]} {
835         if {[ischan $dest]} { set replyto $dest } else { set replyto $n }
836         if {$lag > 1} {
837             sendaction_priority 1 $replyto \
838                 "is very lagged.  Please ask for help again later."
839             ucmdr {} {}
840         } else {
841             sendaction_priority 1 $replyto \
842                 "is lagged.  Your help will arrive shortly ..."
843         }
844     }
845     
846     upvar #0 help_topics([irctolower [string trim $text]]) info
847     if {![info exists info]} { ucmdr "No help on $text, sorry." {} }
848     ucmdr $info {}
849 }
850
851 def_ucmd ? {
852     global help_topics
853     ucmdr $help_topics() {}
854 }
855
856 proc check_username {target} {
857     if {
858         [string length $target] > 8 ||
859         [regexp {[^-0-9a-z]} $target] ||
860         ![regexp {^[a-z]} $target]
861     } { error "invalid username" }
862 }
863
864 proc somedb__head {} {
865     uplevel 1 {
866         set idl [irctolower $id]
867         upvar #0 ${nickchan}db($idl) ndbe
868         binary scan $idl H* idh
869         set idfn $fprefix$idh
870         if {![info exists iddbe] && [file exists $idfn]} {
871             set f [open $idfn r]
872             try_except_finally { set newval [read $f] } {} { close $f }
873             if {[llength $newval] % 2} { error "invalid length" }
874             set iddbe $newval
875         }
876     }
877 }
878
879 proc def_somedb {name arglist body} {
880     foreach {nickchan fprefix} {nick users/n chan chans/c} {
881         proc ${nickchan}db_$name $arglist \
882             "set nickchan $nickchan; set fprefix $fprefix; $body"
883     }
884 }
885
886 def_somedb list {} {
887     set list {}
888     foreach path [glob -nocomplain -path $fprefix *] {
889         binary scan $path "A[string length $fprefix]A*" afprefix thinghex
890         if {"$afprefix" != "$fprefix"} { error "wrong prefix $path $afprefix" }
891         lappend list [binary format H* $thinghex]
892     }
893     return $list
894 }
895
896 proc def_somedb_id {name arglist body} {
897     def_somedb $name [concat id $arglist] "somedb__head; $body"
898 }
899
900 def_somedb_id exists {} {
901     return [info exists iddbe]
902 }
903
904 def_somedb_id delete {} {
905     catch { unset iddbe }
906     file delete $idfn
907 }
908
909 set default_settings_nick {timeformat ks}
910 set default_settings_chan {
911     autojoin 1
912     mode *
913     userinvite pub
914     topicset {}
915     topicsee {}
916     topictell {}
917 }
918
919 def_somedb_id set {args} {
920     upvar #0 default_settings_$nickchan def
921     if {![info exists iddbe]} { set iddbe $def }
922     foreach {key value} [concat $iddbe $args] { set a($key) $value }
923     set newval {}
924     foreach {key value} [array get a] { lappend newval $key $value }
925     set f [open $idfn.new w]
926     try_except_finally {
927         puts $f $newval
928         close $f
929         file rename -force $idfn.new $idfn
930     } {
931     } {
932         catch { close $f }
933     }
934     set iddbe $newval
935 }
936
937 def_somedb_id get {key} {
938     upvar #0 default_settings_$nickchan def
939     if {[info exists iddbe]} {
940         set l [concat $iddbe $def]
941     } else {
942         set l $def
943     }
944     foreach {tkey value} $l {
945         if {"$tkey" == "$key"} { return $value }
946     }
947     error "unset setting $key"
948 }
949
950 proc opt {key} {
951     global calling_nick
952     if {[info exists calling_nick]} { set n $calling_nick } { set n {} }
953     return [nickdb_get $n $key]
954 }
955
956 proc check_notonchan {} {
957     upvar 1 dest dest
958     if {[ischan $dest]} { error "that command must be sent privately" }
959 }
960
961 proc nick_securitycheck {strict} {
962     upvar 1 n n
963     if {![nickdb_exists $n]} { error "you are unknown to me, use `register'." }
964     set wantu [nickdb_get $n username]
965     if {![string length $wantu]} {
966         if {$strict} {
967             error "that feature is only available to secure users, sorry."
968         } else {
969             return
970         }
971     }
972     set luser [irctolower $n]
973     upvar #0 nick_username($luser) nu
974     if {![info exists nu]} {
975         error "nick $n is secure, you must identify yourself first."
976     }
977     if {"$wantu" != "$nu"} {
978         error "you are the wrong user - the nick $n belongs to $wantu, not $nu"
979     }
980 }
981
982 proc channel_securitycheck {channel n} {
983     # You must also call `nick_securitycheck 1'
984     set mgrs [chandb_get $channel managers]
985     if {[lsearch -exact [irctolower $mgrs] [irctolower $n]] < 0} {
986         error "you are not a manager of $channel"
987     }
988 }
989
990 proc def_chancmd {name body} {
991     proc channel/$name {} \
992             "    upvar 1 target chan; upvar 1 n n; upvar 1 text text; $body"
993 }
994
995 proc ta_listop {findnow procvalue} {
996     # findnow and procvalue are code fragments which will be executed
997     # in the caller's level.  findnow should set ta_listop_ev to
998     # the current list, and procvalue should treat ta_listop_ev as
999     # a proposed value in the list and check and possibly modify
1000     # (canonicalise?) it.  After ta_listop, ta_listop_ev will
1001     # be the new value of the list.
1002     upvar 1 ta_listop_ev exchg
1003     upvar 1 text text
1004     set opcode [ta_word]
1005     switch -exact _$opcode {
1006         _= { }
1007         _+ - _- {
1008             uplevel 1 $findnow
1009             foreach item $exchg { set array($item) 1 }
1010         }
1011         default {
1012             error "list change opcode must be one of + - ="
1013         }
1014     }
1015     foreach exchg [split $text " "] {
1016         if {![string length $exchg]} continue
1017         uplevel 1 $procvalue
1018         if {"$opcode" != "-"} {
1019             set array($exchg) 1
1020         } else {
1021             catch { unset array($exchg) }
1022         }
1023     }
1024     set exchg [lsort [array names array]]
1025 }
1026
1027 def_chancmd manager {
1028     ta_listop {
1029         if {[chandb_exists $chan]} {
1030             set ta_listop_ev [chandb_get $chan managers]
1031         } else {
1032             set ta_listop_ev [list [irctolower $n]]
1033         }
1034     } {
1035         check_nick $ta_listop_ev
1036         set ta_listop_ev [irctolower $ta_listop_ev]
1037     }
1038     if {[llength $ta_listop_ev]} {
1039         chandb_set $chan managers $ta_listop_ev
1040         ucmdr "Managers of $chan: $ta_listop_ev" {}
1041     } else {
1042         chandb_delete $chan
1043         ucmdr {} {} "forgets about managing $chan." {}
1044     }
1045 }
1046
1047 def_chancmd autojoin {
1048     set yesno [ta_word]
1049     switch -exact [string tolower $yesno] {
1050         no { set nv 0 }
1051         yes { set nv 1 }
1052         default { error "channel autojoin must be `yes' or `no' }
1053     }
1054     chandb_set $chan autojoin $nv
1055     ucmdr [expr {$nv ? "I will join $chan when I'm restarted " : \
1056             "I won't join $chan when I'm restarted "}] {}
1057 }
1058
1059 def_chancmd userinvite {
1060     set nv [string tolower [ta_word]]
1061     switch -exact $nv {
1062         pub { set txt "!invite will work for $chan, but it won't work by /msg" }
1063         here { set txt "!invite and /msg invite will work, but only for users who are already on $chan." }
1064         all { set txt "Any user will be able to invite themselves or anyone else to $chan." }
1065         none { set txt "I will not invite anyone to $chan." }
1066         default {
1067             error "channel userinvite must be `pub', `here', `all' or `none'
1068         }
1069     }
1070     chandb_set $chan userinvite $nv
1071     ucmdr $txt {}
1072 }
1073
1074 def_chancmd topic {
1075     set what [ta_word]
1076     switch -exact $what {
1077         leave {
1078             ta_nomore
1079             chandb_set $chan topicset {}
1080             ucmdr "I won't ever change the topic of $chan." {}
1081         }
1082         set {
1083             set t [string trim $text]
1084             if {![string length $t]} {
1085                 error "you must specific the topic to set"
1086             }
1087             chandb_set $chan topicset $t
1088             ucmdr "Whenever I'm alone on $chan, I'll set the topic to $t." {}
1089         }
1090         see - tell {
1091             ta_listop {
1092                 set ta_listop_ev [chandb_get $chan topic$what]
1093             } {
1094                 if {"$ta_listop_ev" != "*"} {
1095                     if {![ischan $ta_listop_ev]} {
1096                         error "bad channel \`$ta_listop_ev' in topic $what"
1097                     }
1098                     set ta_listop_ev [irctolower $ta_listop_ev]
1099                 }
1100             }
1101             chandb_set $chan topic$what $ta_listop_ev
1102             ucmdr "Topic $what list for $chan: $ta_listop_ev" {}
1103         }
1104         default {
1105             error "unknown channel topic subcommand - see help channel"
1106         }
1107     }
1108 }
1109
1110 def_chancmd mode {
1111     set mode [ta_word]
1112     if {"$mode" != "*" && ![regexp {^(([-+][imnpst]+)+)$} $mode mode]} {
1113         error {channel mode must be * or match ([-+][imnpst]+)+}
1114     }
1115     chandb_set $chan mode $mode
1116     if {"$mode" == "*"} {
1117         ucmdr "I won't ever change the mode of $chan." {}
1118     } else {
1119         ucmdr "Whenever I'm alone on $chan, I'll set the mode to $mode." {}
1120     }
1121 }
1122
1123 def_chancmd show {
1124     if {[chandb_exists $chan]} {
1125         set l "Settings for $chan: autojoin "
1126         append l [lindex {no yes} [chandb_get $chan autojoin]]
1127         append l ", mode " [chandb_get $chan mode]
1128         append l ", userinvite " [chandb_get $chan userinvite] "."
1129         append l "\nManagers: "
1130         append l [join [chandb_get $chan managers] " "]
1131         foreach {ts sep} {see "\n" tell "  "} {
1132             set t [chandb_get $chan topic$ts]
1133             append l $sep
1134             if {[llength $t]} {
1135                 append l "Topic $ts list: $t."
1136             } else {
1137                 append l "Topic $ts list is empty."
1138             }
1139         }
1140         append l "\n"
1141         set t [chandb_get $chan topicset]
1142         if {[string length $t]} {
1143             append l "Topic to set: $t"
1144         } else {
1145             append l "I will not change the topic."
1146         }
1147         ucmdr {} $l
1148     } else {
1149         ucmdr {} "The channel $chan is not managed."
1150     }
1151 }
1152
1153 def_ucmd op {
1154     if {[ischan $dest]} { set target $dest }
1155     if {[ta_anymore]} { set target [ta_word] }
1156     ta_nomore
1157     if {![info exists target]} { error "you must specify, or !... on, the channel" }
1158     if {![ischan $target]} { error "not a valid channel" }
1159     if {![chandb_exists $target]} { error "$target is not a managed channel." }
1160     prefix_nick
1161     nick_securitycheck 1
1162     channel_securitycheck $target $n
1163     sendout MODE $target +o $n
1164 }
1165
1166 def_ucmd invite {
1167     global chan_nicks
1168     
1169     if {[ischan $dest]} {
1170         set target $dest
1171         set onchan 1
1172     } else {
1173         set target [ta_word]
1174         set onchan 0
1175     }
1176     set ltarget [irctolower $target]
1177     if {![ischan $target]} { error "$target is not a channel." }
1178     if {![info exists chan_nicks($ltarget)]} { error "I am not on $target." }
1179     set ui [chandb_get $ltarget userinvite]
1180     if {"$ui" == "pub" && !$onchan} {
1181         error "Invitations to $target must be made with !invite."
1182     }
1183     if {"$ui" != "all"} {
1184         prefix_nick
1185         if {[lsearch -exact $chan_nicks($ltarget) [irctolower $n]] < 0} {
1186  error "Invitations to $target may only be made by a user on the channel."
1187         }
1188     }
1189     if {"$ui" == "none"} {
1190         error "Sorry, I've not been authorised to invite people to $target."
1191     }
1192     if {![ta_anymore]} {
1193         error "You have to say who to invite."
1194     }
1195     set invitees {}
1196     while {[ta_anymore]} {
1197         set invitee [ta_word]
1198         check_nick $invitee
1199         lappend invitees $invitee
1200     }
1201     foreach invitee $invitees {
1202         sendout INVITE $invitee $ltarget
1203     }
1204     set who [lindex $invitees 0]
1205     switch -exact llength $invitees {
1206         0 { error "zero invitees" }
1207         1 { }
1208         2 { append who " and [lindex $invitees 1]" }
1209         * {
1210             set who [join [lreplace $invitees end end] ", "]
1211             append who " and [lindex $invitees [llength $invitees]]"
1212         }
1213     }
1214     ucmdr {} "invites $who to $target."
1215 }
1216
1217 def_ucmd channel {
1218     if {[ischan $dest]} { set target $dest }
1219     if {![ta_anymore]} {
1220         set subcmd show
1221     } else {
1222         set subcmd [ta_word]
1223     }
1224     if {[ischan $subcmd]} {
1225         set target $subcmd
1226         if {![ta_anymore]} {
1227             set subcmd show
1228         } else {
1229             set subcmd [ta_word]
1230         }
1231     }
1232     if {![info exists target]} { error "privately, you must specify a channel" }
1233     set procname channel/$subcmd
1234     if {"$subcmd" != "show"} {
1235         if {[catch { info body $procname }]} { error "unknown channel setting $subcmd" }
1236         prefix_nick
1237         nick_securitycheck 1
1238         if {[chandb_exists $target]} {
1239             channel_securitycheck $target $n
1240         } else {
1241             upvar #0 chan_initialop([irctolower $target]) io
1242             upvar #0 nick_unique([irctolower $n]) u
1243             if {![info exists io]} { error "$target is not a managed channel" }
1244             if {"$io" != "$u"} { error "you are not the interim manager of $target" }
1245             if {"$subcmd" != "manager"} { error "use `channel manager' first" }
1246         }
1247     }
1248     channel/$subcmd
1249 }
1250
1251 def_ucmd who {
1252     if {[ta_anymore]} {
1253         set target [ta_word]; ta_nomore
1254         set myself 1
1255     } else {
1256         prefix_nick
1257         set target $n
1258         set myself [expr {"$target" != "$n"}]
1259     }
1260     set ltarget [irctolower $target]
1261     upvar #0 nick_case($ltarget) ctarget
1262     set nshow $target
1263     if {[info exists ctarget]} {
1264         upvar #0 nick_onchans($ltarget) oc
1265         upvar #0 nick_username($ltarget) nu
1266         if {[info exists oc]} { set nshow $ctarget }
1267     }
1268     if {![nickdb_exists $ltarget]} {
1269         set ol "$nshow is not a registered nick."
1270     } elseif {[string length [set username [nickdb_get $target username]]]} {
1271         set ol "The nick $nshow belongs to the user $username."
1272     } else {
1273         set ol "The nick $nshow is registered (but not to a username)."
1274     }
1275     if {![info exists ctarget] || ![info exists oc]} {
1276         if {$myself} {
1277             append ol "\nI can't see $nshow on anywhere."
1278         } else {
1279             append ol "\nYou aren't on any channels with me."
1280         }
1281     } elseif {![info exists nu]} {
1282         append ol "\n$nshow has not identified themselves."
1283     } elseif {![info exists username]} {
1284         append ol "\n$nshow has identified themselves as the user $nu."
1285     } elseif {"$nu" != "$username"} {
1286         append ol "\nHowever, $nshow is being used by the user $nu."
1287     } else {
1288         append ol "\n$nshow has identified themselves to me."
1289     }
1290     ucmdr {} $ol
1291 }
1292
1293 def_ucmd register {
1294     prefix_nick
1295     check_notonchan
1296     set old [nickdb_exists $n]
1297     if {$old} { nick_securitycheck 0 }
1298     set luser [irctolower $n]
1299     switch -exact [string tolower [string trim $text]] {
1300         {} {
1301             upvar #0 nick_username($luser) nu
1302             if {![info exists nu]} {
1303                 ucmdr {} \
1304  "You must identify yourself before using `register'.  See `help identify', or use `register insecure'."
1305             }
1306             nickdb_set $n username $nu
1307             ucmdr {} {} "makes a note of your username." {}
1308         }
1309         delete {
1310             nickdb_delete $n
1311             ucmdr {} {} "forgets your nickname." {}
1312         }
1313         insecure {
1314             nickdb_set $n username {}
1315             if {$old} {
1316                 ucmdr {} "Security is now disabled for your nickname !"
1317             } else {
1318                 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."
1319             }
1320         }
1321     }
1322 }
1323
1324 proc timeformat_desc {tf} {
1325     switch -exact $tf {
1326         ks { return "Times will be displayed in seconds or kiloseconds." }
1327         hms { return "Times will be displayed in hours, minutes, etc." }
1328         default { error "invalid timeformat: $v" }
1329     }
1330 }
1331
1332 proc def_setting {opt show_body set_body} {
1333     proc set_show/$opt {} "
1334         upvar 1 n n
1335         set opt $opt
1336         $show_body"
1337     if {![string length $set_body]} return
1338     proc set_set/$opt {} "
1339         upvar 1 n n
1340         upvar 1 text text
1341         set opt $opt
1342         $set_body"
1343 }
1344
1345 def_setting timeformat {
1346     set tf [nickdb_get $n timeformat]
1347     return "$tf: [timeformat_desc $tf]"
1348 } {
1349     set tf [string tolower [ta_word]]
1350     ta_nomore
1351     set desc [timeformat_desc $tf]
1352     nickdb_set $n timeformat $tf
1353     ucmdr {} $desc
1354 }
1355
1356 def_setting security {
1357     set s [nickdb_get $n username]
1358     if {[string length $s]} {
1359         return "Your nick, $n, is controlled by the user $s."
1360     } else {
1361         return "Your nick, $n, is not secure."
1362     }
1363 } {}
1364
1365 def_ucmd set {
1366     prefix_nick
1367     check_notonchan
1368     if {![nickdb_exists $n]} {
1369         ucmdr {} "You are unknown to me and so have no settings.  (Use `register'.)"
1370     }
1371     if {![ta_anymore]} {
1372         set ol {}
1373         foreach proc [lsort [info procs]] {
1374             if {![regexp {^set_show/(.*)$} $proc dummy opt]} continue
1375             lappend ol [format "%-10s %s" $opt [set_show/$opt]]
1376         }
1377         ucmdr {} [join $ol "\n"]
1378     } else {
1379         set opt [ta_word]
1380         if {[catch { info body set_show/$opt }]} {
1381             error "no setting $opt"
1382         }
1383         if {![ta_anymore]} {
1384             ucmdr {} "$opt [set_show/$opt]"
1385         } else {
1386             nick_securitycheck 0
1387             if {[catch { info body set_set/$opt }]} {
1388                 error "setting $opt cannot be set with `set'"
1389             }
1390             set_set/$opt
1391         }
1392     }
1393 }
1394
1395 def_ucmd identpass {
1396     set username [ta_word]
1397     set passmd5 [md5sum "[ta_word]\n"]
1398     ta_nomore
1399     prefix_nick
1400     check_notonchan
1401     set luser [irctolower $n]
1402     upvar #0 nick_onchans($luser) onchans
1403     if {![info exists onchans] || ![llength $onchans]} {
1404         ucmdr "You must be on a channel with me to identify yourself." {}
1405     }
1406     check_username $username
1407     exec userv --timeout 3 $username << "$passmd5\n" > /dev/null \
1408             irc-identpass $n
1409     upvar #0 nick_username($luser) rec_username
1410     set rec_username $username
1411     ucmdr "Pleased to see you, $username." {}
1412 }
1413
1414 def_ucmd summon {
1415     set target [ta_word]
1416     ta_nomore
1417     check_username $target
1418     prefix_nick
1419
1420     upvar #0 lastsummon($target) ls
1421     set now [clock seconds]
1422     if {[info exists ls]} {
1423         set interval [expr {$now - $ls}]
1424         if {$interval < 30} {
1425             ucmdr {} \
1426  "Please be patient; $target was summoned only [showinterval $interval]."
1427         }
1428     }
1429     regsub {^[^!]*!} $p {} path
1430     if {[catch {
1431         exec userv --timeout 3 $target irc-summon $n $path \
1432                 [expr {[ischan $dest] ? "$dest" : ""}] \
1433                 < /dev/null
1434     } rv]} {
1435         regsub -all "\n" $rv { / } rv
1436         error $rv
1437     }
1438     if {[regexp {^problem (.*)} $rv dummy problem]} {
1439         ucmdr {} "The user `$target' $problem."
1440     } elseif {[regexp {^ok ([^ ]+) ([0-9]+)$} $rv dummy tty idlesince]} {
1441         set idletime [expr {$now - $idlesince}]
1442         set ls $now
1443         ucmdr {} {} {} "invites $target ($tty[expr {
1444             $idletime > 10 ? ", idle for [showintervalsecs $idletime]" : ""
1445         }]) to [expr {
1446             [ischan $dest] ? "join us here" : "talk to you"
1447         }]."
1448     } else {
1449         error "unexpected response from userv service: $rv"
1450     }
1451 }
1452
1453 proc md5sum {value} { exec md5sum << $value }
1454
1455 def_ucmd seen {
1456     global lastseen nick
1457     prefix_nick
1458     set ncase [ta_nick]
1459     set nlower [irctolower $ncase]
1460     ta_nomore
1461     set now [clock seconds]
1462     if {"$nlower" == "[irctolower $nick]"} {
1463         error "I am not self-aware."
1464     } elseif {![info exists lastseen($nlower)]} {
1465         set rstr "I've never seen $ncase."
1466     } else {
1467         manyset $lastseen($nlower) realnick time what
1468         set howlong [expr {$now - $time}]
1469         set string [showinterval $howlong]
1470         set rstr "I last saw $realnick $string, $what."
1471     }
1472     if {[ischan $dest]} {
1473         set where $dest
1474     } else {
1475         set where {}
1476     }
1477     upvar #0 lookedfor($nlower) lf
1478     if {[info exists lf]} { set oldvalue $lf } else { set oldvalue {} }
1479     set lf [list [list $now $n $where]]
1480     foreach v $oldvalue {
1481         if {"[irctolower [lindex $v 1]]" == "[irctolower $n]"} continue
1482         lappend lf $v
1483     }
1484     ucmdr {} $rstr
1485 }
1486
1487 proc ensure_globalsecret {} {
1488     global globalsecret
1489     
1490     if {[info exists globalsecret]} return
1491     set gsfile [open /dev/urandom r]
1492     fconfigure $gsfile -translation binary
1493     set globalsecret [read $gsfile 32]
1494     binary scan $globalsecret H* globalsecret
1495     close $gsfile
1496     unset gsfile
1497 }
1498
1499 proc ensure_outqueue {} {
1500     out__vars
1501     if {[info exists out_queue]} return
1502     set out_creditms 0
1503     set out_creditat [clock seconds]
1504     set out_queue {}
1505     set out_lag_reported 0
1506     set out_lag_reportwhen $out_creditat
1507 }
1508
1509 proc fail {msg} {
1510     logerror "failing: $msg"
1511     exit 1
1512 }
1513
1514 proc ensure_connecting {} {
1515     global sock ownfullname host port nick
1516     global musthaveping_ms musthaveping_after
1517     
1518     if {[info exists sock]} return
1519     set sock [socket $host $port]
1520     fconfigure $sock -buffering line
1521     fconfigure $sock -translation crlf
1522
1523     sendout USER blight 0 * $ownfullname
1524     sendout NICK $nick
1525     fileevent $sock readable onread
1526
1527     set musthaveping_after [after $musthaveping_ms \
1528             {fail "no ping within timeout"}]
1529 }
1530
1531 proc connected {} {
1532     global musthaveping_after
1533
1534     after cancel $musthaveping_after
1535     unset musthaveping_after
1536
1537     foreach chan [chandb_list] {
1538         if {[chandb_get $chan autojoin]} { dojoin $chan }
1539     }
1540 }
1541
1542 ensure_globalsecret
1543 ensure_outqueue
1544 loadhelp
1545 ensure_connecting