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