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