chiark / gitweb /
topicedit: add a timeout; better error handling
[ircbot.git] / bot.tcl
1 # Actual IRC bot code
2
3 set helpfile helpinfos
4
5 source irccore.tcl
6 source parsecmd.tcl
7 source stdhelp.tcl
8 source userv.tcl
9
10 defset marktime_min 300
11 defset marktime_join_startdelay 5000
12
13 proc privmsg_unlogged {prefix ischan params} {
14     if {!$ischan ||
15         [regexp {^![a-z][-a-z]*[a-z]( .*)?$} [lindex $params 1]]} {
16         return 0
17     }
18     # on-channel message, ignore
19     set chan [lindex $params 0]
20     upvar #0 chan_lastactivity([irctolower $chan]) la
21     set la [clock seconds]
22     catch_logged { recordlastseen_p $prefix "talking on $chan" 2 }
23     return 1
24 }
25
26 proc showintervalsecs {howlong abbrev} {
27     return [showintervalsecs/[opt timeformat] $howlong $abbrev]
28 }
29
30 proc formatsf {pfx value} {
31    foreach {min format} { 100 %.0f 10 %.1f 0 %.2f} {
32         set fval [format $format $value]
33         if {$fval < $min} continue
34         return [format "$fval${pfx}" $value]
35    }
36 }
37
38 proc showintervalsecs/beat {howlong abbrev} {
39     # We split in two to avoid overflow problems.
40     if {$howlong < 86 } {
41         # mB's
42         set pfx mB
43         return [format "%.0fmB" [expr {round($howlong * 1.157)*10} ]]
44     } else {
45         if {$howlong < 86400 } {
46             # B's
47             set pfx B
48             set value [expr {$howlong / 86.4}]
49         } else {
50             # kB's
51             set pfx kB
52             set value [expr {$howlong / 86400.0}]
53         }
54     }
55     return [formatsf $pfx $value]
56 }
57
58 proc showintervalsecs/ks {howlong abbrev} {
59     if {$howlong < 1000} {
60         return "${howlong}s"
61     } else {
62         if {$howlong < 1000000} {
63             set pfx ks
64             set scale 1000
65         } else {
66             set pfx Ms
67             set scale 1000000
68         }
69         set value [expr "$howlong.0 / $scale"]
70         return [formatsf $pfx $value]
71     }
72 }
73
74 proc format_qty {qty unit abbrev} {
75     set o $qty
76     if {$abbrev} {
77         append o [string range $unit 0 0]
78     } else {
79         append o " "
80         append o $unit
81         if {$qty != 1} { append o s }
82     }
83     return $o
84 }
85
86 proc showintervalsecs/hms {qty abbrev} {
87     set ul {second 60 minute 60 hour 24 day 7 week}
88     set remainv 0
89     while {[llength $ul] > 1 && $qty >= [set uv [lindex $ul 1]]} {
90         set remainu [lindex $ul 0]
91         set remainv [expr {$qty % $uv}]
92         set qty [expr {($qty-$remainv)/$uv}]
93         set ul [lreplace $ul 0 1]
94     }
95     set o [format_qty $qty [lindex $ul 0] $abbrev]
96     if {$remainv} {
97         if {!$abbrev} { append o " " }
98         append o [format_qty $remainv $remainu $abbrev]
99     }
100     return $o
101 }
102
103 proc showinterval {howlong} {
104     if {$howlong <= 0} {
105         return {just now}
106     } else {
107         return "[showintervalsecs $howlong 0] ago"
108     }
109 }
110
111 proc showtime {when} {
112     return [showinterval [expr {[clock seconds] - $when}]]
113 }
114
115 proc parse_interval {specified min} {
116     if {![regexp {^([0-9]+)([a-z]+)$} $specified dummy value unit]} {
117         error "invalid syntax for interval"
118     }
119     switch -exact $unit {
120         s { set u 1 }
121         ks { set u 1000 }
122         m { set u 60 }
123         h { set u 3600 }
124         mb { set u 0.0864 }
125         b { set u 86.4 }
126         kb { set u 86400 }
127         default { error "unknown unit of time $unit" }
128     }
129     if {$value > 86400*21/$u} { error "interval too large" }
130     set result [expr {round($value*$u)}]
131     if {$result < $min} { error "interval too small (<${min}s)" }
132     return $result
133 }
134
135 proc def_msgproc {name argl body} {
136     proc msg_$name "varbase $argl" "\
137     upvar #0 msg/\$varbase/dest d\n\
138     upvar #0 msg/\$varbase/str s\n\
139     upvar #0 msg/\$varbase/accum a\n\
140 $body"
141 }
142
143 def_msgproc begin {dest str} {
144     set d $dest
145     set s $str
146     set a {}
147 }
148
149 def_msgproc append {str} {
150     set ns "$s$str"
151     if {[string length $s] && [string length $ns] > 65} {
152         msg__sendout $varbase
153         set s " [string trimleft $str]"
154     } else {
155         set s $ns
156     }
157 }
158
159 def_msgproc finish {} {
160     msg__sendout $varbase
161     unset s
162     unset d
163     return $a
164 }
165
166 def_msgproc _sendout {} {
167     lappend a [string trimright $s]
168     set s {}
169 }
170
171 proc looking_whenwhere {when where} {
172     set str [showtime [expr {$when-1}]]
173     if {[string length $where]} { append str " on $where" }
174     return $str
175 }
176
177 proc tell_getcstate {} {
178     # uses nl from caller's context
179     # imports telling (as the nick_telling) and u
180     # sets stt, telling_when
181     uplevel 1 {
182         upvar #0 nick_telling($nl) telling
183         upvar #0 nick_unique($nl) u
184
185         if {[info exists telling]} {
186             manyset $telling u_last stt telling_when
187             if {![info exists u] || "$u_last" != "$u"} {
188                 set stt undelivered
189             }
190         } else {
191             set stt undelivered
192             set telling_when 0
193         }
194     }
195 }
196
197 proc tell_event {nl event} {
198     # For `act' we *haven't* yet done the 750ms delay; we implement
199     # that here.  Also, here we turn `talk' into `talk' now and `act'
200     # later.  We also support the psuedo-event `none'.  The del msg
201     # and new msg events are handled by the command procedures, not here.
202     global calling_nick
203     if {[info exists calling_nick]} { set save $calling_nick }
204     set r DELAYED
205     switch -exact $event {
206         none { }
207         talk {
208             tell_event_core $nl talk
209             tell_event $nl act
210         }
211         act {
212             after 750 [list tell_event_core $nl $event]
213         }
214         ident - msgsarrive {
215             tell_event_core $nl $event
216         }
217         tellme {
218             set r [tell_event_core $nl TELLME]
219         }
220         default {
221             error "tell_event $nl $event"
222         }
223     }
224     if {[info exists save]} { set calling_nick $save }
225     return $r
226 }
227
228 proc tell_event_core {nl event} {
229     global tell_event_teventi errorInfo
230     set tell_event_teventi "*$event* $nl"
231     if {[catch {
232         tell_event_core1 $nl $event
233     } emsg]} {
234         log_intern "tell event error" "$emsg >$errorInfo<"
235         set emsg ERROR
236     } else {
237         if {"$emsg" != "nomsgs"} {
238             log_intern "tell event" "done $tell_event_teventi $emsg"
239         }
240     }
241     return $emsg
242 }
243
244 proc tell_event_core1 {nl event} {
245     # event is `talk', `act', `ident', `msgsarrive' or `TELLME'
246     # When user talks we actually get talk now and act later
247     global calling_nick
248     set calling_nick $nl
249     set iml [msgsdb_get $nl inbound]
250     if {![llength $iml]} { return nomsgs }
251
252     set now [clock seconds]
253     tell_getcstate
254     set ago [expr {$now - $telling_when}]
255
256     # Now we have the components of a telling state
257     #   u     - nick_unique (unset if not visible)
258     #   stt   - state: undelivered, mentioned, passede
259     #   ago   - how long ago since we did anything
260
261     # We compute an evstate to dispatch on as follows:
262
263     # evstate is string of letters
264     #   current state
265     #      u   UNDELIVERED (MESSAGES)
266     #      m   MENTIONED
267     #      p   PASSED
268     #   event
269     #      t   talk
270     #      a   act
271     #      i   ident
272     #      m   msgsarrive
273     #      T   tellme (user command)
274     #   security level and timing
275     #      ii  Insecure
276     #      ss  Secure and soon (before interval)
277     #      sl  Secure and late (after interval)
278     #   current identification
279     #      i   Identified
280     #      u   Unidentified
281     #   reliability and timing
282     #      uu  Unreliable
283     #      rv  Remind, very soon (before within-interval)
284     #      rs  Remind, soon (between)
285     #      rl  Remind, late (after every-interval)
286     #      ps  Pester, soon (before interval)
287     #      pl  Pester, late (after interval)
288
289     set evstate {}
290
291     append evstate [string range $stt 0 0]
292     append evstate [string range $event 0 0]
293
294     manyset [nickdb_get_sec_effective $nl] sec secwhen
295     switch -exact $sec {
296         insecure { append evstate ii }
297         secure { append evstate [expr {$ago<$secwhen ? "ss" : "sl"}] }
298         default { append evstate "#$sec#" }
299     }
300
301     upvar #0 nick_username($nl) nu
302     if {[info exists nu] && ![string compare $nu [nickdb_get_username $nl]]} {
303         append evstate i
304     } else {
305         append evstate u
306     }
307     
308     manyset [nickdb_get $nl tellrel] rel relint relwithin
309     switch -exact $rel {
310         unreliable { append evstate uu }
311         remind { append evstate [expr {
312             $ago<$relwithin ? "rv" : $ago<$relint ? "rs" : "rl"
313         }]}
314         pester { append evstate [expr {$ago<$relint ? "ps" : "pl"}] }
315         default { append evstate "#$rel#" }
316     }
317
318     global tell_event_teventi
319     set tell_event_teventi "$evstate $ago $nl"
320     switch -glob $evstate {
321         pt???rv {
322             # consider delivered:
323             #  (very recently passed, and the user talks)
324             set ndel [tell_delete_msgs {} $nl]
325             sendprivmsg $nl \
326  "I'm assuming you got the $ndel message(s) I just passed on."
327             return delivered
328         }
329         pm????? {
330             # oops, messages passed are now out of date
331             catch_restoreei { unset telling }
332             return reset
333         }
334         ?m????? {
335             # ignore new msgs if we haven't passed yet
336             return ignorenew
337         }
338         ut????? - mt????? -
339         pt???uu - pt???rs - pt???rl - pt???p? {
340             # ignore (any other `talk's) - act handles these
341             return ignoretalk
342         }
343         ui????? -
344         uaii?uu - uaii??l - uas?iuu - uas?i?l -
345         mi????? - pa????l -
346         ?Tii??? - ?Ts?i?? {
347             # pass and then stuff
348             if {[llength $iml] == 3} {
349                 manyset $iml sender sentwhen msg
350                 sendprivmsg $nl \
351  "$sender asked me, [showinterval [expr {$now-$sentwhen}]],\
352  to tell you: $msg"
353             } else {
354                 sendprivmsg $nl \
355  "I have [expr {[llength $iml]/3}] messages for you:"
356                 while {[llength $iml] >= 3} {
357                     manyset [lrange $iml 0 2] sender sentwhen msg
358                     set iml [lrange $iml 3 end]
359                     sendprivmsg $nl \
360  " [showintervalsecs [expr {$now-$sentwhen}] 1] <$sender> $msg"
361                 }
362             }
363             if {![string compare $rel "unreliable"]} {
364                 tell_delete_msgs {} $nl
365                 return toldunreliable
366             }
367             set stt passed
368             set re passed
369         }
370         uaslu?? {
371             sendprivmsg $nl {You have messages (so identify yourself please).}
372             set stt mentioned
373             set re mentioned
374         }
375         ?Ts?u?? {
376             sendprivmsg $nl {You must identify yourself to see your messages.}
377             return ignoreuitm
378         }
379         masl??? {
380             sendprivmsg $nl {Don't forget about your messages.}
381             set re remind
382         }
383         pi????? {
384             return ignorepi
385         }
386         mass??? - pa????v - pa????s -
387         uaii??v - uaii??s -
388         uas?i?v - uas?i?s -
389         uassu?? {
390             # too soon
391             return ignoresoon
392         }
393         * {
394             error "tell_event_core nl=$nl evstate=$evstate ?"
395         }
396     }
397     if {![info exists u]} {
398         set telling [list {} undelivered $now]
399     } else {
400         set telling [list $u $stt $now]
401     }
402     return $re
403 }
404
405 proc recordlastseen_n {n how here} {
406     # here is:
407     #   0 - nick was seen leaving (or changing to another nicks or some such)
408     #   1 - nick was seen doing something else
409     #   2 - nick was seen talking on channel
410     global lastseen lookedfor
411     set nl [irctolower $n]
412     set now [clock seconds]
413     set lastseen($nl) [list $n $now $how]
414
415     if {!$here} return
416
417     tell_event $nl [lindex {none act talk} $here]
418
419     upvar #0 lookedfor($nl) lf
420     if {[info exists lf]} {
421         switch -exact [llength $lf] {
422             0 {
423                 set ml {}
424             }
425             1 {
426                 manyset [lindex $lf 0] when who where
427                 set ml [list \
428  "FYI, $who was looking for you [looking_whenwhere $when $where]."]
429             }
430             default {
431                 msg_begin tosend $n "FYI, people have been looking for you:"
432                 set i 0
433                 set fin ""
434                 foreach e $lf {
435                     incr i
436                     if {$i == 1} {
437                         msg_append tosend " "
438                     } elseif {$i == [llength $lf]} {
439                         msg_append tosend " and "
440                         set fin .
441                     } else {
442                         msg_append tosend ", "
443                     }
444                     manyset $e when who where
445                     msg_append tosend \
446                             "$who ([looking_whenwhere $when $where])$fin"
447                 }
448                 set ml [msg_finish tosend]
449             }
450         }
451         unset lf
452         msendprivmsg_delayed 1000 $n $ml
453     }
454 }
455
456 proc note_topic {showoff whoby topic} {
457     set msg "FYI, $whoby has changed the topic on $showoff"
458     if {[string length $topic] < 160} {
459         append msg " to $topic"
460     } else {
461         append msg " but it is too long to reproduce here !"
462     }
463     set showoff [irctolower $showoff]
464     set tell [chandb_get $showoff topictell]
465     if {[lsearch -exact $tell *] >= 0} {
466         set tryspies [chandb_list]
467     } else {
468         set tryspies $tell
469     }
470     foreach spy $tryspies {
471         set see [chandb_get $spy topicsee]
472         if {[lsearch -exact $see $showoff] >= 0 || \
473                 ([lsearch -exact $see *] >= 0 && \
474                 [lsearch -exact $tell $spy] >= 0)} {
475             sendprivmsg $spy $msg
476         }
477     }
478 }
479
480 proc recordlastseen_p {p how here} {
481     prefix_nick
482     recordlastseen_n $n $how $here
483 }
484
485 proc chanmode_arg {} {
486     upvar 2 args cm_args
487     set rv [lindex $cm_args 0]
488     set cm_args [lreplace cm_args 0 0]
489     return $rv
490 }
491
492 proc chanmode_o1 {m g p chan} {
493     global nick chan_initialop
494     prefix_nick
495     set who [chanmode_arg]
496     recordlastseen_n $n "being nice to $who" 1
497     if {![ircnick_compare $who $nick]} {
498         set nlower [irctolower $n]
499         upvar #0 nick_unique($nlower) u
500         if {[chandb_exists $chan]} {
501             sendprivmsg $n Thanks.
502         } elseif {![info exists u]} {
503             sendprivmsg $n {Op me while not on the channel, why don't you ?}
504         } else {
505             set chan_initialop([irctolower $chan]) $u
506             sendprivmsg $n \
507  "Thanks.  You can use `channel manager ...' to register this channel."
508             if {![string length [nickdb_get_username $n username]]} {
509                 sendprivmsg $n \
510  "(But to do that you must register your nick securely first.)"
511             }
512         }
513     }
514 }
515
516 proc chanmode_o0 {m g p chan} {
517     global nick chandeop
518     prefix_nick
519     set who [chanmode_arg]
520     recordlastseen_p $p "being mean to $who" 1
521     if {![ircnick_compare $who $nick]} {
522         set chandeop($chan) [list [clock seconds] $p]
523     }
524 }
525
526 proc msg_MODE {p c dest modelist args} {
527     if {![ischan $dest]} return
528     if {[regexp {^\-(.+)$} $modelist dummy modelist]} {
529         set give 0
530     } elseif {[regexp {^\+(.+)$} $modelist dummy modelist]} {
531         set give 1
532     } else {
533         error "invalid modelist"
534     }
535     foreach m [split $modelist] {
536         set procname chanmode_$m$give
537         if {[catch { info body $procname }]} {
538             recordlastseen_p $p "fiddling with $dest" 1
539         } else {
540             $procname $m $give  $p $dest
541         }
542     }
543 }
544
545 proc leaving {lchan} {
546     global nick_onchans
547     foreach luser [array names nick_onchans] {
548         upvar #0 nick_onchans($luser) oc
549         set oc [grep tc {"$tc" != "$lchan"} $oc]
550     }
551     upvar #0 chan_nicks($lchan) nlist
552     unset nlist
553     upvar #0 chan_lastactivity($lchan) la
554     catch { unset la }
555 }
556
557 proc doleave {lchan} {
558     sendout PART $lchan
559     leaving $lchan
560 }
561
562 proc dojoin {lchan} {
563     global chan_nicks
564     sendout JOIN $lchan
565     set chan_nicks($lchan) {}
566 }
567
568 proc check_justme {lchan} {
569     global nick
570     upvar #0 chan_nicks($lchan) nlist
571     if {[llength $nlist] != 1} return
572     if {"[lindex $nlist 0]" != "[irctolower $nick]"} return
573     if {[chandb_exists $lchan]} {
574         set mode [chandb_get $lchan mode]
575         if {"$mode" != "*"} {
576             sendout MODE $lchan $mode
577         }
578         set topic [chandb_get $lchan topicset]
579         if {[string length $topic]} {
580             sendout TOPIC $lchan $topic
581         }
582     } else {
583         doleave $lchan
584     }
585 }
586
587 proc process_kickpart {chan user} {
588     global nick
589     check_nick $user
590     set luser [irctolower $user]
591     set lchan [irctolower $chan]
592     if {![ischan $chan]} { error "not a channel" }
593     if {![ircnick_compare $luser $nick]} {
594         leaving $lchan
595     } else {
596         upvar #0 nick_onchans($luser) oc
597         upvar #0 chan_nicks($lchan) nlist
598         set oc [grep tc {"$tc" != "$lchan"} $oc]
599         set nlist [grep tn {"$tn" != "$luser"} $nlist]
600         nick_case $user
601         if {![llength $oc]} {
602             nick_forget $luser
603         } else {
604             check_justme $lchan
605         }
606     }
607 }
608
609 proc msg_TOPIC {p c dest topic} {
610     prefix_nick
611     if {![ischan $dest]} return
612     recordlastseen_n $n "changing the topic on $dest" 1
613     note_topic [irctolower $dest] $n $topic
614 }
615
616 proc msg_KICK {p c chans users comment} {
617     set chans [split $chans ,]
618     set users [split $users ,]
619     if {[llength $chans] > 1} {
620         foreach chan $chans user $users { process_kickpart $chan $user }
621     } else {
622         foreach user $users { process_kickpart [lindex $chans 0] $user }
623     }
624 }
625
626 proc msg_KILL {p c user why} {
627     nick_forget $user
628 }
629
630 set nick_counter 0
631 set nick_arys {onchans username unique}
632 # nick_onchans($luser) -> [list ... $lchan ...]
633 # nick_username($luser) -> <securely known local username>
634 # nick_unique($luser) -> <includes-counter>
635 # nick_case($luser) -> $user  (valid even if no longer visible)
636 # nick_markid($luser) -> <after id for marktime>
637 # nick_telling($luser) -> <unique> mentioned|passed <when>
638
639 # chan_nicks($lchan) -> [list ... $luser ...]
640 # chan_lastactivity($lchan) -> [clock seconds]
641
642 proc lnick_forget {luser} {
643     global nick_arys chan_nicks
644     lnick_marktime_cancel $luser
645     foreach ary $nick_arys {
646         upvar #0 nick_${ary}($luser) av
647         catch { unset av }
648     }
649     foreach lch [array names chan_nicks] {
650         upvar #0 chan_nicks($lch) nlist
651         set nlist [grep tn {"$tn" != "$luser"} $nlist]
652         check_justme $lch
653     }
654 }
655
656 proc nick_forget {user} {
657     global nick_arys chan_nicks
658     lnick_forget [irctolower $user]
659     nick_case $user
660 }
661
662 proc nick_case {user} {
663     global nick_case
664     set nick_case([irctolower $user]) $user
665 }
666
667 proc msg_NICK {p c newnick} {
668     global nick_arys nick_case calling_nick
669     prefix_nick
670     recordlastseen_n $n "changing nicks to $newnick" 0
671     set calling_nick $newnick
672     recordlastseen_n $newnick "changing nicks from $n" 1
673     set luser [irctolower $n]
674     lnick_marktime_cancel $luser
675     set lusernew [irctolower $newnick]
676     foreach ary $nick_arys {
677         upvar #0 nick_${ary}($luser) old
678         upvar #0 nick_${ary}($lusernew) new
679         if {[info exists new]} { error "nick collision ?! $ary $n $newnick" }
680         if {[info exists old]} { set new $old; unset old }
681     }
682     upvar #0 nick_onchans($lusernew) oc
683     foreach ch $oc {
684         upvar #0 chan_nicks($ch) nlist
685         set nlist [grep tn {"$tn" != "$luser"} $nlist]
686         lappend nlist $lusernew
687     }
688     lnick_marktime_start $lusernew "Hi." 500 1
689     nick_case $newnick
690 }
691
692 proc nick_ishere {n} {
693     global nick_counter
694     upvar #0 nick_unique([irctolower $n]) u
695     if {![info exists u]} { set u [incr nick_counter].$n.[clock seconds] }
696     nick_case $n
697 }
698
699 proc msg_JOIN {p c chan} {
700     prefix_nick
701     nick_ishere $n
702     recordlastseen_n $n "joining $chan" 1
703     set nl [irctolower $n]
704     set lchan [irctolower $chan]
705     upvar #0 nick_onchans($nl) oc
706     upvar #0 chan_nicks($lchan) nlist
707     if {![info exists oc]} {
708         global marktime_join_startdelay
709         lnick_marktime_start $nl "Welcome." $marktime_join_startdelay 1
710     }
711     lappend oc $lchan
712     lappend nlist $nl
713 }
714 proc msg_PART {p c chan args} {
715     prefix_nick
716     set msg "leaving $chan"
717     if {[llength $args]} {
718         set why [lindex $args 0]
719         if {"[irctolower $why]" != "[irctolower $n]"} { append msg " ($why)" }
720     }
721     recordlastseen_n $n $msg 1
722     process_kickpart $chan $n
723 }
724 proc msg_QUIT {p c why} {
725     prefix_nick
726     recordlastseen_n $n "leaving ($why)" 0
727     nick_forget $n
728 }
729
730 proc msg_PRIVMSG {p c dest text} {
731     global errorCode
732     
733     prefix_nick
734     if {[ischan $dest]} {
735         recordlastseen_n $n "invoking me in $dest" 1
736         set output $dest
737     } else {
738         recordlastseen_n $n "talking to me" 1
739         set output $n
740     }
741     nick_case $n
742
743     execute_usercommand $p $c $n $output $dest $text
744 }
745
746 proc msg_INVITE {p c n chan} {
747     after 1000 [list dojoin [irctolower $chan]]
748 }
749
750 proc grep {var predicate list} {
751     set o {}
752     upvar 1 $var v
753     foreach v $list {
754         if {[uplevel 1 [list expr $predicate]]} { lappend o $v }
755     }
756     return $o
757 }
758
759 proc msg_353 {p c dest type chan nicklist} {
760     global names_chans nick_onchans
761     set lchan [irctolower $chan]
762     upvar #0 chan_nicks($lchan) nlist
763     lappend names_chans $lchan
764     if {![info exists nlist]} {
765         # We don't think we're on this channel, so ignore it !
766         # Unfortunately, because we don't get a reply to PART,
767         # we have to remember ourselves whether we're on a channel,
768         # and ignore stuff if we're not, to avoid races.  Feh.
769         return
770     }
771     set nlist_new {}
772     foreach user [split $nicklist { }] {
773         regsub {^[@+]} $user {} user
774         if {![string length $user]} continue
775         check_nick $user
776         set luser [irctolower $user]
777         upvar #0 nick_onchans($luser) oc
778         lappend oc $lchan
779         lappend nlist_new $luser
780         nick_ishere $user
781     }
782     set nlist $nlist_new
783 }
784
785 proc msg_366 {p c args} {
786     global names_chans nick_onchans
787     set lchan [irctolower $c]
788     foreach luser [array names nick_onchans] {
789         upvar #0 nick_onchans($luser) oc
790         if {[llength names_chans] > 1} {
791             set oc [grep tc {[lsearch -exact $tc $names_chans] >= 0} $oc]
792         }
793         if {![llength $oc]} { lnick_forget $luser }
794     }
795     unset names_chans
796 }
797
798 proc somedb__head {} {
799     uplevel 1 {
800         set idl [irctolower $id]
801         upvar #0 ${nickchan}db($idl) ndbe
802         binary scan $idl H* idh
803         set idfn $fprefix$idh
804         if {![info exists iddbe] && [file exists $idfn]} {
805             set f [open $idfn r]
806             try_except_finally { set newval [read $f] } {} { close $f }
807             if {[llength $newval] % 2} { error "invalid length" }
808             set iddbe $newval
809         }
810     }
811 }
812
813 proc def_somedb {name arglist body} {
814     foreach {nickchan fprefix} {
815         nick users/n
816         chan chans/c
817         msgs users/m
818     } {
819         proc ${nickchan}db_$name $arglist \
820             "set nickchan $nickchan; set fprefix $fprefix; $body"
821     }
822 }
823
824 def_somedb list {} {
825     set list {}
826     foreach path [glob -nocomplain -path $fprefix *] {
827         binary scan $path "A[string length $fprefix]A*" afprefix thinghex
828         if {"$afprefix" != "$fprefix"} { error "wrong prefix $path $afprefix" }
829         lappend list [binary format H* $thinghex]
830     }
831     return $list
832 }
833
834 proc def_somedb_id {name arglist body} {
835     def_somedb $name [concat id $arglist] "somedb__head; $body"
836 }
837
838 def_somedb_id exists {} {
839     return [info exists iddbe]
840 }
841
842 def_somedb_id delete {} {
843     catch { unset iddbe }
844     file delete $idfn
845 }
846
847 set default_settings_nick {
848     timeformat ks
849     marktime off
850     tellsec {secure 600}
851     tellrel {remind 3600 30}
852 }
853
854 set default_settings_chan {
855     autojoin 1
856     mode *
857     userinvite pub
858     topicset {}
859     topicsee {}
860     topictell {}
861 }
862
863 set default_settings_msgs {
864     inbound {}
865     outbound {}
866 }
867 # inbound -> [<nick> <time_t> <message>] ...
868 # outbound -> [<nick> <time_t(earliest)> <count>] ...
869 #   neither are sorted particularly; only one entry per recipient in
870 #   output; both sender and recipient are cased
871
872 def_somedb_id set {args} {
873     upvar #0 default_settings_$nickchan def
874     if {![info exists iddbe]} { set iddbe $def }
875     foreach {key value} [concat $iddbe $args] { set a($key) $value }
876     set newval {}
877     foreach {key value} [array get a] { lappend newval $key $value }
878     set f [open $idfn.new w]
879     try_except_finally {
880         puts $f $newval
881         close $f
882         file rename -force $idfn.new $idfn
883     } {
884     } {
885         catch { close $f }
886     }
887     set iddbe $newval
888 }
889
890 def_somedb_id get {key} {
891     upvar #0 default_settings_$nickchan def
892     if {[info exists iddbe]} {
893         set l [concat $iddbe $def]
894     } else {
895         set l $def
896     }
897     foreach {tkey value} $l {
898         if {![string compare $tkey $key]} { return $value }
899     }
900     error "unset setting $key"
901 }
902
903 proc opt {key} {
904     global calling_nick
905     if {[info exists calling_nick]} { set n $calling_nick } { set n {} }
906     return [nickdb_get $n $key]
907 }
908
909 proc check_notonchan {} {
910     upvar 1 dest dest
911     if {[ischan $dest]} { usererror "That command must be sent privately." }
912 }
913
914 proc nick_securitycheck {strict} {
915     upvar 1 n n
916     if {![nickdb_exists $n]} {
917         usererror "You are unknown to me, use `register'."
918     }
919     set wantu [nickdb_get $n username]
920     if {![string length $wantu]} {
921         if {$strict} {
922             usererror "That feature is only available to secure users, sorry."
923         } else {
924             return
925         }
926     }
927     set luser [irctolower $n]
928     upvar #0 nick_username($luser) nu
929     if {![info exists nu]} {
930         usererror "Nick $n is secure, you must identify yourself first."
931     }
932     if {"$wantu" != "$nu"} {
933         usererror "You are the wrong user -\
934                 the nick $n belongs to $wantu, not $nu."
935     }
936 }
937
938 proc channel_ismanager {channel n} {
939     set mgrs [chandb_get $channel managers]
940     return [expr {[lsearch -exact [irctolower $mgrs] [irctolower $n]] >= 0}]
941 }
942
943 proc channel_securitycheck {channel} {
944     upvar n n
945     if {![channel_ismanager $channel $n]} {
946         usererror "You are not a manager of $channel."
947     }
948     nick_securitycheck 1
949 }
950
951 proc def_chancmd {name body} {
952     proc channel/$name {} \
953             "    upvar 1 target chan; upvar 1 n n; upvar 1 text text; $body"
954 }
955
956 proc ta_listop {findnow procvalue} {
957     # findnow and procvalue are code fragments which will be executed
958     # in the caller's level.  findnow should set ta_listop_ev to
959     # the current list, and procvalue should treat ta_listop_ev as
960     # a proposed value in the list and check and possibly modify
961     # (canonicalise?) it.  After ta_listop, ta_listop_ev will
962     # be the new value of the list.
963     upvar 1 ta_listop_ev exchg
964     upvar 1 text text
965     set opcode [ta_word]
966     switch -exact _$opcode {
967         _= { }
968         _+ - _- {
969             uplevel 1 $findnow
970             foreach item $exchg { set array($item) 1 }
971         }
972         default {
973             error "list change opcode must be one of + - ="
974         }
975     }
976     foreach exchg [split $text " "] {
977         if {![string length $exchg]} continue
978         uplevel 1 $procvalue
979         if {"$opcode" != "-"} {
980             set array($exchg) 1
981         } else {
982             catch { unset array($exchg) }
983         }
984     }
985     set exchg [lsort [array names array]]
986 }
987
988 def_chancmd manager {
989     ta_listop {
990         if {[chandb_exists $chan]} {
991             set ta_listop_ev [chandb_get $chan managers]
992         } else {
993             set ta_listop_ev [list [irctolower $n]]
994         }
995     } {
996         check_nick $ta_listop_ev
997         set ta_listop_ev [irctolower $ta_listop_ev]
998     }
999     if {[llength $ta_listop_ev]} {
1000         chandb_set $chan managers $ta_listop_ev
1001         ucmdr "Managers of $chan: $ta_listop_ev" {}
1002     } else {
1003         chandb_delete $chan
1004         ucmdr {} {} "forgets about managing $chan." {}
1005     }
1006 }
1007
1008 def_chancmd autojoin {
1009     set yesno [ta_word]
1010     switch -exact [string tolower $yesno] {
1011         no { set nv 0 }
1012         yes { set nv 1 }
1013         default { error "channel autojoin must be `yes' or `no' }
1014     }
1015     chandb_set $chan autojoin $nv
1016     ucmdr [expr {$nv ? "I will join $chan when I'm restarted " : \
1017             "I won't join $chan when I'm restarted "}] {}
1018 }
1019
1020 def_chancmd userinvite {
1021     set nv [string tolower [ta_word]]
1022     switch -exact $nv {
1023         pub { set txt "!invite will work for $chan, but it won't work by /msg" }
1024         here { set txt "!invite and /msg invite will work, but only for users who are already on $chan." }
1025         all { set txt "Any user will be able to invite themselves or anyone else to $chan." }
1026         none { set txt "I will not invite anyone to $chan." }
1027         default {
1028             error "channel userinvite must be `pub', `here', `all' or `none'
1029         }
1030     }
1031     chandb_set $chan userinvite $nv
1032     ucmdr $txt {}
1033 }
1034
1035 def_chancmd topic {
1036     set what [ta_word]
1037     switch -exact $what {
1038         leave {
1039             ta_nomore
1040             chandb_set $chan topicset {}
1041             ucmdr "I won't ever change the topic of $chan." {}
1042         }
1043         set {
1044             set t [string trim $text]
1045             if {![string length $t]} {
1046                 error "you must specific the topic to set"
1047             }
1048             chandb_set $chan topicset $t
1049             ucmdr "Whenever I'm alone on $chan, I'll set the topic to $t." {}
1050         }
1051         see - tell {
1052             ta_listop {
1053                 set ta_listop_ev [chandb_get $chan topic$what]
1054             } {
1055                 if {"$ta_listop_ev" != "*"} {
1056                     if {![ischan $ta_listop_ev]} {
1057                         error "bad channel \`$ta_listop_ev' in topic $what"
1058                     }
1059                     set ta_listop_ev [irctolower $ta_listop_ev]
1060                 }
1061             }
1062             chandb_set $chan topic$what $ta_listop_ev
1063             ucmdr "Topic $what list for $chan: $ta_listop_ev" {}
1064         }
1065         default {
1066             usererror "Unknown channel topic subcommand - see help channel."
1067         }
1068     }
1069 }
1070
1071 def_chancmd mode {
1072     set mode [ta_word]
1073     if {"$mode" != "*" && ![regexp {^(([-+][imnpst]+)+)$} $mode mode]} {
1074         error {channel mode must be * or match ([-+][imnpst]+)+}
1075     }
1076     chandb_set $chan mode $mode
1077     if {![string compare $mode "*"]} {
1078         ucmdr "I won't ever change the mode of $chan." {}
1079     } else {
1080         ucmdr "Whenever I'm alone on $chan, I'll set the mode to $mode." {}
1081     }
1082 }
1083
1084 def_chancmd show {
1085     if {[chandb_exists $chan]} {
1086         set l "Settings for $chan: autojoin "
1087         append l [lindex {no yes} [chandb_get $chan autojoin]]
1088         append l ", mode " [chandb_get $chan mode]
1089         append l ", userinvite " [chandb_get $chan userinvite] "."
1090         append l "\nManagers: "
1091         append l [join [chandb_get $chan managers] " "]
1092         foreach {ts sep} {see "\n" tell "  "} {
1093             set t [chandb_get $chan topic$ts]
1094             append l $sep
1095             if {[llength $t]} {
1096                 append l "Topic $ts list: $t."
1097             } else {
1098                 append l "Topic $ts list is empty."
1099             }
1100         }
1101         append l "\n"
1102         set t [chandb_get $chan topicset]
1103         if {[string length $t]} {
1104             append l "Topic to set: $t"
1105         } else {
1106             append l "I will not change the topic."
1107         }
1108         ucmdr {} $l
1109     } else {
1110         ucmdr {} "The channel $chan is not managed."
1111     }
1112 }
1113
1114 proc channelmgr_monoop {} {
1115     upvar 1 dest dest
1116     upvar 1 text text
1117     upvar 1 n n
1118     upvar 1 p p
1119     upvar 1 target target
1120     global chan_nicks
1121
1122     prefix_nick
1123
1124     if {[ischan $dest]} { set target $dest }
1125     if {[ta_anymore]} { set target [ta_word] }
1126     ta_nomore
1127     if {![info exists target]} {
1128         usererror "You must specify, or invoke me on, the relevant channel."
1129     }
1130     if {![info exists chan_nicks([irctolower $target])]} {
1131         usererror "I am not on $target."
1132     }
1133     if {![ischan $target]} { error "not a valid channel" }
1134
1135     if {![chandb_exists $target]} {
1136         usererror "$target is not a managed channel."
1137     }
1138     channel_securitycheck $target
1139 }
1140
1141 def_ucmd op {
1142     channelmgr_monoop
1143     sendout MODE $target +o $n
1144     ucmdr {} {}
1145 }
1146
1147 def_ucmd leave {
1148     channelmgr_monoop
1149     doleave $target
1150     ucmdr {} {}
1151 }
1152
1153 def_ucmd invite {
1154     global chan_nicks errorCode errorInfo
1155     prefix_nick
1156     
1157     if {[ischan $dest]} {
1158         set target $dest
1159         set onchan 1
1160     } else {
1161         set target [ta_word]
1162         set onchan 0
1163     }
1164     set ltarget [irctolower $target]
1165     if {![ischan $target]} { error "$target is not a channel" }
1166     if {![info exists chan_nicks($ltarget)]} {
1167         usererror "I am not on $target."
1168     }
1169     set ui [chandb_get $ltarget userinvite]
1170     if {[catch {
1171         if {![string compare $ui "pub"] && !$onchan} {
1172             usererror "Invitations to $target must be made there with !invite."
1173         }
1174         if {"$ui" != "all"} {
1175             if {[lsearch -exact $chan_nicks($ltarget) [irctolower $n]] < 0} {
1176                 usererror "Invitations to $target may only be made\
1177                         by a user on the channel."
1178             }
1179         }
1180         if {[!string compare $ui "none"]} {
1181             usererror "Sorry, I've not been authorised\
1182                     to invite people to $target."
1183         }
1184     } emsg]} {
1185         if {![string compare $errorCode "BLIGHT USER"] &&
1186              [channel_ismanager $target $n]} {
1187             if {[catch {
1188                 nick_securitycheck 1
1189             } emsg2]} {
1190                 if {![string compare $errorCode "BLIGHT USER"]} {
1191                     usererror "$emsg2  Therefore you can't use your\
1192                             channel manager privilege.  $emsg"
1193                 } else {
1194                     error $error $errorInfo $errorCode
1195                 }
1196             }
1197         } else {
1198             error $emsg $errorInfo $errorCode
1199         }
1200     }
1201     if {![ta_anymore]} {
1202         usererror "You have to say who to invite."
1203     }
1204     set invitees {}
1205     while {[ta_anymore]} {
1206         set invitee [ta_nick]
1207         lappend invitees $invitee
1208     }
1209     foreach invitee $invitees {
1210         sendout INVITE $invitee $ltarget
1211     }
1212     set who [lindex $invitees 0]
1213     switch -exact llength $invitees {
1214         0 { error "zero invitees" }
1215         1 { }
1216         2 { append who " and [lindex $invitees 1]" }
1217         * {
1218             set who [join [lreplace $invitees end end] ", "]
1219             append who " and [lindex $invitees [llength $invitees]]"
1220         }
1221     }
1222     ucmdr {} {} {} "invites $who to $target."
1223 }
1224
1225 def_ucmd channel {
1226     if {[ischan $dest]} { set target $dest }
1227     if {![ta_anymore]} {
1228         set subcmd show
1229     } else {
1230         set subcmd [ta_word]
1231     }
1232     if {[ischan $subcmd]} {
1233         set target $subcmd
1234         if {![ta_anymore]} {
1235             set subcmd show
1236         } else {
1237             set subcmd [ta_word]
1238         }
1239     }
1240     if {![info exists target]} { error "privately, you must specify a channel" }
1241     set procname channel/$subcmd
1242     if {"$subcmd" != "show"} {
1243         if {[catch { info body $procname }]} {
1244             usererror "unknown channel setting $subcmd."
1245         }
1246         prefix_nick
1247         if {[chandb_exists $target]} {
1248             channel_securitycheck $target
1249         } else {
1250             nick_securitycheck 1
1251             upvar #0 chan_initialop([irctolower $target]) io
1252             upvar #0 nick_unique([irctolower $n]) u
1253             if {![info exists io]} {
1254                 usererror "$target is not a managed channel."
1255             }
1256             if {"$io" != "$u"} {
1257                 usererror "You are not the interim manager of $target."
1258             }
1259             if {"$subcmd" != "manager"} {
1260                 usererror "Please use `channel manager' first."
1261             }
1262         }
1263     }
1264     channel/$subcmd
1265 }
1266
1267 proc nickdb_get_username {n} {
1268     if {![nickdb_exists $n]} { return "" }
1269     return [nickdb_get $n username]
1270 }
1271
1272 proc nickdb_get_sec_effective {n} {
1273     set l [nickdb_get $n tellsec]
1274     set u [nickdb_get_username $n]
1275     if {![string compare [lindex $l 0] "secure"] &&
1276         ![string length $u]} { set l insecure }
1277     return $l
1278 }
1279
1280 proc tell_peernicks {text} {
1281     global errorInfo errorCode
1282     set text [irctolower [string trim $text]]
1283     set senders [split $text " "]
1284     foreach sender $senders {
1285         if {[catch { check_nick $sender } emsg]} {
1286             error "invalid nick `$sender': $emsg" $errorInfo $errorCode
1287         }
1288     }
1289     return $senders
1290 }
1291
1292 proc msgsdb_set_maydelete {n key l otherkey} {
1293     msgsdb_set $n $key $l
1294     if {[llength $l]} return
1295     if {[llength [msgsdb_get $n $otherkey]]} return
1296     msgsdb_delete $n
1297 }
1298
1299 proc tell_delete_msgs {lsenders lrecip} {
1300     set new_inbound {}
1301     set ndel 0
1302     foreach {s t m} [msgsdb_get $lrecip inbound] {
1303         if {[llength $lsenders]} {
1304             if {[lsearch -exact $lsenders [irctolower $s]] == -1} {
1305                 lappend new_inbound $s $t $m
1306                 continue
1307             }
1308         }
1309         set rsenders($s) 1
1310         incr ndel
1311     }
1312     msgsdb_set_maydelete $lrecip inbound $new_inbound outbound
1313     if {![llength $new_inbound]} {
1314         upvar #0 nick_telling($lrecip) telling
1315         catch { unset telling }
1316     }
1317     foreach s [array names rsenders] {
1318         set new_outbound {}
1319         foreach {r t c} [msgsdb_get $s outbound] {
1320             if {![ircnick_compare $r $lrecip]} continue
1321             lappend new_outbound $r $t $c
1322         }
1323         msgsdb_set_maydelete $s outbound $new_outbound inbound
1324     }
1325     return $ndel
1326 }
1327
1328 def_ucmd untell {
1329     prefix_nick
1330     check_notonchan
1331     if {[nickdb_exists $n]} { nick_securitycheck 0 }
1332     set recipients [tell_peernicks $text]
1333     if {![llength $recipients]} {
1334         usererror "You must say which recipients' messages from you to forget."
1335     }
1336     set ndel 0
1337     foreach recip $recipients {
1338         incr ndel [tell_delete_msgs [irctolower $n] $recip]
1339     }
1340     ucmdr "Removed $ndel as yet undelivered message(s)." {}
1341 }
1342
1343 def_ucmd_alias delmsgs delmsg
1344 def_ucmd delmsg {
1345     global errorInfo errorCode
1346     prefix_nick
1347     set nl [irctolower $n]
1348     check_notonchan
1349     manyset [nickdb_get_sec_effective $n] sec secwhen
1350     switch -exact $sec {
1351         insecure { }
1352         reject - mailto {
1353             usererror \
1354  "There are no messages to delete\
1355  because your message disposition prevents them from being left."
1356         }
1357         secure {
1358             nick_securitycheck 1
1359         }
1360         default {
1361             error "delmsg sec $sec"
1362         }
1363     }
1364     if {![llength [msgsdb_get $n inbound]]} {
1365         ucmdr "No incoming messages to delete." {}
1366     }
1367     tell_getcstate
1368     if {![info exists u]} {
1369         usererror \
1370  "I can't delete your messages unless I can see you on a channel with me.\
1371   Otherwise I might delete a message I hadn't told you about yet."
1372     }
1373     if {"$stt" != "passed"} {
1374         set telling [list $u undelivered 0]
1375         usererror \
1376  "There are message(s) you may not yet have seen;\
1377  I'll deliver them to you now.\
1378   If you actually want to delete them, just tell me `delmsg' again."
1379     }
1380     set senders [tell_peernicks $text]
1381     set ndel [tell_delete_msgs [irctolower $senders] [irctolower $n]]
1382     if {!$ndel} {
1383         if {[llength $senders]} {
1384             ucmdr "No relevant incoming messages to delete." {}
1385         }
1386     }
1387     switch -exact [llength $senders] {
1388         0 { ucmdr {} {} "deletes your $ndel message(s)." }
1389         1 { ucmdr {} {} "deletes your $ndel message(s) from $senders." }
1390         default {
1391             ucmdr {} {} "deletes your $ndel message(s) from\
1392  [lreplace $senders end end] and/or [lindex $senders end]."
1393         }
1394     }
1395 }
1396
1397 def_ucmd tellme {
1398     prefix_nick
1399     ta_nomore
1400     check_notonchan
1401     manyset [nickdb_get $n tellsec] sec
1402     switch -exact $sec {
1403         reject { ucmdr "But, you asked me to reject messages for you !" {} }
1404         mailto { ucmdr "But, you asked me to mail your messages to you !" {} }
1405     }
1406     switch -exact [tell_event [irctolower $n] tellme] {
1407         ERROR - INVALID { ucmdr {} {is ill.  Help!} }
1408         nomsgs { ucmdr {You have no messages.} {} }
1409         default { }
1410     }
1411 }
1412
1413 def_ucmd tell {
1414     global nick_case ownmailaddr ownfullname
1415     
1416     prefix_nick
1417     set target [ta_nick]
1418     if {![string length $text]} { error "tell them what?" }
1419     if {[string length $text] > 400} { error "message too long" }
1420
1421     set ltarget [irctolower $target]
1422     set ctarget $target
1423     if {[info exists nick_case($ltarget)]} { set ctarget $nick_case($ltarget) }
1424
1425     manyset [nickdb_get_sec_effective $target] sec mailtoint mailwhy
1426     manyset [nickdb_get $target tellrel] rel relint relwithin
1427     switch -exact $sec {
1428         insecure - secure {
1429             set now [clock seconds]
1430             set inbound [msgsdb_get $ltarget inbound]
1431             lappend inbound $n $now $text
1432             msgsdb_set $ltarget inbound $inbound
1433
1434             set outbound [msgsdb_get $n outbound]
1435             set noutbound {}
1436             set found 0
1437             foreach {recip time count} $outbound {
1438                 if {![ircnick_compare $recip $ltarget]} {
1439                     incr count
1440                     set recip $ctarget
1441                     set found 1
1442                 }
1443                 lappend noutbound $recip $time $count
1444             }
1445             if {!$found} {
1446                 lappend noutbound $ctarget $now 1
1447             }
1448             msgsdb_set $n outbound $noutbound
1449             set msg "OK, I'll tell $ctarget"
1450             if {$found} { append msg " that too" }
1451             append msg ", "
1452             if {"$sec" != "secure"} {
1453                 switch -exact $rel {
1454                     unreliable { append msg "neither reliably nor securely" }
1455                     remind { append msg "pretty reliably, but not securely" }
1456                     pester { append msg "reliably but not securely" }
1457                 }
1458             } else {
1459                 switch -exact $rel {
1460                     unreliable { append msg "securely but not reliably" }
1461                     remind { append msg "securely and pretty reliably" }
1462                     pester { append msg "reliably and securely" }
1463                 }
1464             }
1465             append msg .
1466             tell_event $ltarget msgsarrive
1467             ucmdr $msg {}
1468         }
1469         mailto {
1470             set fmtmsg [exec fmt << " $text"]
1471             exec /usr/sbin/sendmail -odb -oi -t -oee -f $mailwhy \
1472                     > /dev/null << \
1473  "From: $ownmailaddr ($ownfullname)
1474 To: $mailtoint
1475 Subject: IRC tell from $n
1476
1477 $n asked me[expr {[ischan $dest] ? " on $dest" : ""}] to tell you:
1478 [exec fmt << " $text"]
1479
1480 (This message was for your nick $ctarget; your account $mailwhy
1481  arranged for it to be forwarded to $mailtoint.)
1482 "
1483             ucmdr \
1484  "I've mailed $ctarget, which is what they prefer." \
1485                 {}
1486         }
1487         reject {
1488             usererror "Sorry, $ctarget does not want me to take messages."
1489         }
1490         default {
1491             error "bad tellsec $sec"
1492         }
1493     }
1494 }
1495
1496 def_ucmd who {
1497     if {[ta_anymore]} {
1498         set target [ta_nick]; ta_nomore
1499         set myself 1
1500     } else {
1501         prefix_nick
1502         set target $n
1503         set myself [expr {"$target" != "$n"}]
1504     }
1505     set ltarget [irctolower $target]
1506     upvar #0 nick_case($ltarget) ctarget
1507     set nshow $target
1508     if {[info exists ctarget]} {
1509         upvar #0 nick_onchans($ltarget) oc
1510         upvar #0 nick_username($ltarget) nu
1511         if {[info exists oc]} { set nshow $ctarget }
1512     }
1513     if {![nickdb_exists $ltarget]} {
1514         set ol "$nshow is not a registered nick."
1515     } elseif {[string length [set username [nickdb_get $target username]]]} {
1516         set ol "The nick $nshow belongs to the user $username."
1517     } else {
1518         set ol "The nick $nshow is registered (but not to a username)."
1519     }
1520     if {![info exists ctarget] || ![info exists oc]} {
1521         if {$myself} {
1522             append ol "\nI can't see $nshow on anywhere."
1523         } else {
1524             append ol "\nYou aren't on any channels with me."
1525         }
1526     } elseif {![info exists nu]} {
1527         append ol "\n$nshow has not identified themselves."
1528     } elseif {![info exists username]} {
1529         append ol "\n$nshow has identified themselves as the user $nu."
1530     } elseif {"$nu" != "$username"} {
1531         append ol "\nHowever, $nshow is being used by the user $nu."
1532     } else {
1533         append ol "\n$nshow has identified themselves to me."
1534     }
1535     ucmdr {} $ol
1536 }
1537
1538 def_ucmd register {
1539     prefix_nick
1540     check_notonchan
1541     set old [nickdb_exists $n]
1542     if {$old} { nick_securitycheck 0 }
1543     set luser [irctolower $n]
1544     switch -exact [string tolower [string trim $text]] {
1545         {} {
1546             upvar #0 nick_username($luser) nu
1547             if {![info exists nu]} {
1548                 ucmdr {} \
1549  "You must identify yourself before using `register'.  See `help identify', or use `register insecure'."
1550             }
1551             nickdb_set $n username $nu
1552             ucmdr {} {} "makes a note of your username." {}
1553         }
1554         delete {
1555             nickdb_delete $n
1556             ucmdr {} {} "forgets your nickname." {}
1557         }
1558         insecure {
1559             nickdb_set $n username {}
1560             if {$old} {
1561                 ucmdr {} "Security is now disabled for your nickname !"
1562             } else {
1563                 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."
1564             }
1565         }
1566         default {
1567             error "you mean register / register delete / register insecure"
1568         }
1569     }
1570 }
1571
1572 proc timeformat_desc {tf} {
1573     switch -exact $tf {
1574         ks { return "Times will be displayed in seconds or kiloseconds." }
1575         hms { return "Times will be displayed in hours, minutes, etc." }
1576         beat { return "Times will be displayed in beats (1000B = 1d)." }
1577         default { error "invalid timeformat: $v" }
1578     }
1579 }
1580
1581 set settings {}
1582 proc def_setting {opt show_body set_body} {
1583     global settings
1584     lappend settings $opt
1585     proc set_show/$opt {} "
1586         upvar 1 n n
1587         set opt $opt
1588         $show_body"
1589     if {![string length $set_body]} return
1590     proc set_set/$opt {} "
1591         upvar 1 n n
1592         upvar 1 text text
1593         set opt $opt
1594         $set_body"
1595 }
1596
1597 proc tellme_sec_desc {v n} {
1598     manyset $v sec mailtoint
1599     switch -exact $sec {
1600         insecure {
1601             return "I'll tell you your messages whenever I see you."
1602         }
1603         secure {
1604             if {[string length [nickdb_get_username $n]]} {
1605                 return \
1606  "I'll keep the bodies of your messages private until you identify yourself, reminding you every [showintervalsecs $mailtoint 1]."
1607             } else {
1608                 return \
1609  "I'll tell you your messages whenever I see you.\
1610   (Secure message delivery is enabled, but your nick is not registered\
1611  securely.  See `help register'.)"
1612             }
1613         }
1614         reject {
1615             return "I shan't accept messages for you."
1616         }
1617         mailto {
1618             return "I'll forward your messages by email to $mailtoint."
1619         }
1620         default {
1621             error "bad tellsec $sec"
1622         }
1623     }
1624 }
1625
1626 proc tellme_rel_desc {v n} {
1627     manyset $v rel every within
1628     switch -exact $rel {
1629         unreliable {
1630             return "As soon as I've told you message(s), I'll forget them\
1631  - note that this means messages can get lost !"
1632         }
1633         pester {
1634             set u {}
1635         }
1636         remind {
1637             set u ", or talk on channel within [showintervalsecs $within 1] of me having told you"
1638         }
1639         default {
1640             error "bad tellrel $rel"
1641         }
1642     }
1643     return "After delivering messages, I'll remind you every\
1644  [showintervalsecs $every 1] until you say delmsg$u."
1645 }
1646
1647 def_setting timeformat {
1648     set tf [nickdb_get $n timeformat]
1649     return "$tf: [timeformat_desc $tf]"
1650 } {
1651     set tf [string tolower [ta_word]]
1652     ta_nomore
1653     set desc [timeformat_desc $tf]
1654     nickdb_set $n timeformat $tf
1655     ucmdr {} $desc
1656 }
1657
1658 proc marktime_desc {mt} {
1659     switch -exact $mt {
1660         off {
1661             return "I will not send you periodic messages."
1662         }
1663         once {
1664             return "I will send you one informational message when I see you."
1665         }
1666         default {
1667             return "I'll send you a message every [showintervalsecs $mt 0]."
1668         }
1669     }
1670 }
1671
1672 def_setting marktime {
1673     set mt [nickdb_get $n marktime]
1674     set p $mt
1675     if {[string match {[0-9]*} $mt]} { append p s }
1676     append p ": "
1677     append p [marktime_desc $mt]
1678     return $p
1679 } {
1680     global marktime_min
1681     set mt [string tolower [ta_word]]
1682     ta_nomore
1683
1684     switch -exact $mt {
1685         off - once {
1686         }
1687         default {
1688             set mt [parse_interval $mt $marktime_min]
1689         }
1690     }
1691     nickdb_set $n marktime $mt
1692     lnick_marktime_start [irctolower $n] "So:" 500 0
1693     ucmdr {} [marktime_desc $mt]
1694 }
1695
1696 def_setting security {
1697     set s [nickdb_get $n username]
1698     if {[string length $s]} {
1699         return "Your nick, $n, is controlled by the user $s."
1700     } else {
1701         return "Your nick, $n, is not secure."
1702     }
1703 } {}
1704
1705 proc tellme_setting_sec_simple {} {
1706     uplevel 1 {
1707         ta_nomore
1708         set sr sec
1709         set v $setting
1710     }
1711 }
1712
1713 proc tellme_setting_neednomsgs {} {
1714     uplevel 1 {
1715         if {[llength [msgsdb_get $n inbound]]} {
1716             usererror "You must delete the incoming messages you have, first."
1717         }
1718     }
1719 }
1720
1721 def_setting tellme {
1722     set secv [nickdb_get $n tellsec]
1723     set ms [tellme_sec_desc $secv $n]
1724     manyset $secv sec
1725     switch -exact $sec {
1726         insecure - secure {
1727             set mr [tellme_rel_desc [nickdb_get $n tellrel] $n]
1728             return "$ms  $mr"
1729         }
1730         reject - mailto {
1731             return $ms
1732         }
1733     }
1734 } {
1735     set setting [string tolower [ta_word]]
1736     set nl [irctolower $n]
1737     switch -exact $setting {
1738         insecure {
1739             tellme_setting_sec_simple
1740         }
1741         secure {
1742             set every [ta_interval_optional 60 600]
1743             ta_nomore
1744             set sr sec
1745             set v [list secure $every]
1746         }
1747         reject {
1748             tellme_setting_neednomsgs
1749             tellme_setting_sec_simple
1750         }
1751         mailto {
1752             tellme_setting_neednomsgs
1753             
1754             upvar #0 nick_username($nl) nu
1755             if {!([info exists nu] && [string length $nu])} {
1756                 usererror \
1757  "Sorry, you must register securely to have your messages mailed\
1758  (to prevent the use of this feature for spamming).  See `help register'."
1759             }
1760             set sr sec
1761             set v [list mailto [ta_word] $nu]
1762         }
1763         unreliable - pester - remind {
1764             manyset [nickdb_get $n tellsec] sec
1765             switch -exact $sec {
1766                 reject - mailto {
1767                     usererror \
1768  "Sorry, I shan't change when I'll consider a message delivered, because\
1769  you've asked me not to keep messages, or to mail them to you.\
1770   You should say `set tellme secure' or some such, first."
1771                 }
1772             }
1773             set sr rel
1774             set v $setting
1775             if {"$setting" != "unreliable"} {
1776                 set every [ta_interval_optional 300 3600]
1777                 lappend v $every
1778             }
1779             if {![string compare $setting remind]} {
1780                 set within [ta_interval_optional 5 30]
1781                 if {$within > $every} {
1782                     error "remind interval must be at least time to respond"
1783                 }
1784                 lappend v $within
1785             }
1786             ta_nomore
1787         }
1788         default {
1789             error "invalid tellme setting $setting"
1790         }
1791     }
1792     nickdb_set $n tell$sr $v
1793     upvar #0 nick_telling($nl) telling
1794     catch { unset telling }
1795     ucmdr [tellme_${sr}_desc $v $n] {}
1796 }
1797
1798 proc lnick_checktold {luser} {
1799     set ml [msgsdb_get $luser outbound]
1800     if {![llength $ml]} return
1801     set is1 [expr {[llength $ml]==3}]
1802     set m1 "FYI, I haven't yet delivered your"
1803     set ol {}
1804     set now [clock seconds]
1805     while {[llength $ml]} {
1806         manyset $ml r t n
1807         set ml [lreplace $ml 0 2]
1808         set td [expr {$now-$t}]
1809         if {$n == 1} {
1810             set iv [showinterval $td]
1811             set ifo "$r, $iv"
1812             set if1 "message to $r, $iv."
1813         } else {
1814             set iv [showintervalsecs $td 0]
1815             set ifo "$r, $n messages, oldest $iv"
1816             set if1 "$n messages to $r, oldest $iv."
1817         }
1818         if {$is1} {
1819             sendprivmsg $luser "$m1 $if1"
1820             return
1821         } else {
1822             lappend ol " to $ifo[expr {[llength $ml] ? ";" : "."}]"
1823         }
1824     }
1825     sendprivmsg $luser "$m1 messages:"
1826     msendprivmsg $luser $ol
1827 }
1828
1829 def_ucmd set {
1830     global settings
1831     prefix_nick
1832     check_notonchan
1833     if {![nickdb_exists $n]} {
1834         ucmdr {} "You are unknown to me and so have no settings.  (Use `register'.)"
1835     }
1836     if {![ta_anymore]} {
1837         set ol {}
1838         foreach opt $settings {
1839             lappend ol [format "%-10s %s" $opt [set_show/$opt]]
1840         }
1841         ucmdr {} [join $ol "\n"]
1842     } else {
1843         set opt [ta_word]
1844         if {[catch { info body set_show/$opt }]} {
1845             error "no setting $opt"
1846         }
1847         if {![ta_anymore]} {
1848             ucmdr {} "$opt: [set_show/$opt]"
1849         } else {
1850             nick_securitycheck 0
1851             if {[catch { info body set_set/$opt }]} {
1852                 error "setting $opt cannot be set with `set'"
1853             }
1854             set_set/$opt
1855         }
1856     }
1857 }
1858
1859 def_ucmd identpass {
1860     prefix_nick
1861     check_notonchan
1862     set luser [irctolower $n]
1863     set username [ta_word]
1864     set passmd5 [md5sum "[ta_word]\n"]
1865     ta_nomore
1866     upvar #0 nick_onchans($luser) onchans
1867     if {![info exists onchans] || ![llength $onchans]} {
1868         ucmdr "You must be on a channel with me to identify yourself." {}
1869     }
1870     check_username $username
1871     exec userv --timeout 3 $username << "$passmd5\n" > /dev/null \
1872             irc-identpass $n
1873     upvar #0 nick_username($luser) rec_username
1874     set rec_username $username
1875     after 50 [list tell_event $luser ident]
1876     ucmdr "Pleased to see you, $username." {}
1877 }
1878
1879 def_ucmd kill {
1880     global nick
1881     prefix_nick
1882     set target [ta_nick]
1883     if {![nickdb_exists $target]} { error "$target is not a registered nick." }
1884     set wantu [nickdb_get $target username]
1885     if {![string length $wantu]} { error "$target is insecurely registred." }
1886     upvar #0 nick_username([irctolower $n]) nu
1887     if {![info exists nu]} { error "You must identify yourself first." }
1888     if {"$wantu" != "$nu"} {
1889         error "You are the wrong user, $nu - $target belongs to $wantu."
1890     }
1891     set reason "at request of user $nu"
1892     if {[ta_anymore]} { append reason "; $text" }
1893     sendout KILL $target $reason
1894     ucmdr {} {}
1895 }
1896
1897 def_ucmd summon {
1898     set target [ta_word]
1899     ta_nomore
1900     # fixme would be nice if the rest of the text was passed on instead
1901     check_username $target
1902     prefix_nick
1903
1904     upvar #0 lastsummon($target) ls
1905     set now [clock seconds]
1906     if {[info exists ls]} {
1907         set interval [expr {$now - $ls}]
1908         if {$interval < 30} {
1909             ucmdr {} \
1910  "Please be patient; $target was summoned only [showinterval $interval]."
1911         }
1912     }
1913     regsub {^[^!]*!} $p {} path
1914     if {[catch {
1915         exec userv --timeout 3 $target irc-summon $n $path \
1916                 [expr {[ischan $dest] ? "$dest" : ""}] \
1917                 < /dev/null
1918     } rv]} {
1919         regsub -all "\n" $rv { / } rv
1920         error $rv
1921     }
1922     if {[regexp {^problem (.*)} $rv dummy problem]} {
1923         ucmdr {} "The user `$target' $problem."
1924     } elseif {[regexp {^ok ([^ ]+) ([0-9]+)$} $rv dummy tty idlesince]} {
1925         set idletime [expr {$now - $idlesince}]
1926         set ls $now
1927         ucmdr {} {} {} "invites $target ($tty[expr {
1928             $idletime > 10 ? ", idle for [showintervalsecs $idletime 0]" : ""
1929         }]) to [expr {
1930             [ischan $dest] ? "join us here" : "talk to you"
1931         }]."
1932     } else {
1933         error "unexpected response from userv service: $rv"
1934     }
1935 }
1936
1937 proc md5sum {value} { exec md5sum << $value }
1938
1939 def_ucmd seen {
1940     global lastseen nick
1941     prefix_nick
1942     set ncase [ta_nick]
1943     set nlower [irctolower $ncase]
1944     ta_nomore
1945     set now [clock seconds]
1946     if {![ircnick_compare $nlower $nick]} {
1947         usererror "I am not self-aware."
1948     } elseif {![info exists lastseen($nlower)]} {
1949         set rstr "I've never seen $ncase."
1950     } else {
1951         manyset $lastseen($nlower) realnick time what
1952         set howlong [expr {$now - $time}]
1953         set string [showinterval $howlong]
1954         set rstr "I last saw $realnick $string, $what."
1955     }
1956     if {[ischan $dest]} {
1957         set where $dest
1958     } else {
1959         set where {}
1960     }
1961     upvar #0 lookedfor($nlower) lf
1962     if {[info exists lf]} { set oldvalue $lf } else { set oldvalue {} }
1963     set lf [list [list $now $n $where]]
1964     foreach v $oldvalue {
1965         if {![ircnick_compare [lindex $v 1] $n]} continue
1966         lappend lf $v
1967     }
1968     ucmdr {} $rstr
1969 }
1970
1971 proc lnick_marktime_cancel {luser} {
1972     upvar #0 nick_markid($luser) mi
1973     if {![info exists mi]} return
1974     catch { after cancel $mi }
1975     catch { unset mi }
1976 }
1977
1978 proc lnick_marktime_doafter {luser why ms mentiontold} {
1979     lnick_marktime_cancel $luser
1980     upvar #0 nick_markid($luser) mi
1981     set mi [after $ms [list lnick_marktime_now $luser $why 0]]
1982 }
1983
1984 proc lnick_marktime_reset {luser} {
1985     set mt [nickdb_get $luser marktime]
1986     switch -exact $mt {
1987         off - once { }
1988         default {
1989             lnick_marktime_doafter $luser "Time passes." [expr {$mt*1000}] 0
1990         }
1991     }
1992 }
1993
1994 proc lnick_marktime_start {luser why ms mentiontold} {
1995     set mt [nickdb_get $luser marktime]
1996     switch -exact $mt {
1997         off {
1998             lnick_marktime_cancel $luser
1999             if {$mentiontold} { after $ms [list lnick_checktold $luser] }
2000         }
2001         default {
2002             lnick_marktime_doafter $luser $why $ms $mentiontold
2003         }
2004     }
2005 }
2006
2007 proc lnick_marktime_now {luser why mentiontold} {
2008     upvar #0 nick_onchans($luser) oc
2009     global calling_nick
2010     set calling_nick $luser
2011     sendprivmsg $luser [lnick_pingstring $why $oc ""]
2012     if {$mentiontold} { after 150 [list lnick_checktold $luser] }
2013     lnick_marktime_reset $luser
2014 }    
2015
2016 proc lnick_pingstring {why oc apstring} {
2017     global nick_onchans
2018     catch { exec uptime } uptime
2019     set nnicks [llength [array names nick_onchans]]
2020     if {[regexp \
2021  {^ *([0-9:apm]+) +up.*, +(\d+) users?, +load average: +([0-9., ]+) *$} \
2022             $uptime dummy time users load]} {
2023         regsub -all , $load {} load
2024         set uptime "$time  $nnicks/$users  $load"
2025     } else {
2026         append uptime ", $nnicks nicks"
2027     }
2028     if {[llength $oc]} {
2029         set best_la 0
2030         set activity quiet
2031         foreach ch $oc {
2032             upvar #0 chan_lastactivity($ch) la
2033             if {![info exists la]} continue
2034             if {$la <= $best_la} continue
2035             set since [showintervalsecs [expr {[clock seconds]-$la}] 1]
2036             set activity "$ch $since"
2037             set best_la $la
2038         }
2039     } else {
2040         set activity unseen
2041     }
2042     set str $why
2043     append str "  " $uptime "  " $activity
2044     if {[string length $apstring]} { append str "  " $apstring }
2045     return $str
2046 }
2047
2048 def_ucmd ping {
2049     prefix_nick
2050     set ln [irctolower $n]
2051     if {[ischan $dest]} {
2052         set oc [irctolower $dest]
2053     } else {
2054         global nick_onchans
2055         if {[info exists nick_onchans($ln)]} {
2056             set oc $nick_onchans($ln)
2057         } else {
2058             set oc {}
2059         }
2060         if {[llength $oc]} { lnick_marktime_reset $ln }
2061     }
2062     after 150 [list lnick_checktold $ln]
2063     ucmdr {} [lnick_pingstring "Pong!" $oc $text]
2064 }
2065
2066 proc ensure_globalsecret {} {
2067     global globalsecret
2068     
2069     if {[info exists globalsecret]} return
2070     set gsfile [open /dev/urandom r]
2071     fconfigure $gsfile -translation binary
2072     set globalsecret [read $gsfile 32]
2073     binary scan $globalsecret H* globalsecret
2074     close $gsfile
2075     unset gsfile
2076 }
2077
2078 proc connected {} {
2079     global operuserpass
2080     if {[info exists operuserpass]} {
2081         eval sendout OPER $operuserpass
2082     }
2083     foreach chan [chandb_list] {
2084         if {[chandb_get $chan autojoin]} { dojoin $chan }
2085     }
2086 }
2087
2088 ensure_globalsecret
2089 loadhelp
2090 ensure_connecting