chiark / gitweb /
Format
[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     global nick_onchans
546     foreach luser [array names nick_onchans] {
547         upvar #0 nick_onchans($luser) oc
548         set oc [grep tc {"$tc" != "$lchan"} $oc]
549     }
550     upvar #0 chan_nicks($lchan) nlist
551     unset nlist
552     upvar #0 chan_lastactivity($lchan) la
553     catch { unset la }
554 }
555
556 proc doleave {lchan} {
557     sendout PART $lchan
558     leaving $lchan
559 }
560
561 proc dojoin {lchan} {
562     global chan_nicks
563     sendout JOIN $lchan
564     set chan_nicks($lchan) {}
565 }
566
567 proc check_justme {lchan} {
568     global nick
569     upvar #0 chan_nicks($lchan) nlist
570     if {[llength $nlist] != 1} return
571     if {"[lindex $nlist 0]" != "[irctolower $nick]"} return
572     if {[chandb_exists $lchan]} {
573         set mode [chandb_get $lchan mode]
574         if {"$mode" != "*"} {
575             sendout MODE $lchan $mode
576         }
577         set topic [chandb_get $lchan topicset]
578         if {[string length $topic]} {
579             sendout TOPIC $lchan $topic
580         }
581     } else {
582         doleave $lchan
583     }
584 }
585
586 proc process_kickpart {chan user} {
587     global nick
588     check_nick $user
589     set luser [irctolower $user]
590     set lchan [irctolower $chan]
591     if {![ischan $chan]} { error "not a channel" }
592     if {"$luser" == "[irctolower $nick]"} {
593         leaving $lchan
594     } else {
595         upvar #0 nick_onchans($luser) oc
596         upvar #0 chan_nicks($lchan) nlist
597         set oc [grep tc {"$tc" != "$lchan"} $oc]
598         set nlist [grep tn {"$tn" != "$luser"} $nlist]
599         nick_case $user
600         if {![llength $oc]} {
601             nick_forget $luser
602         } else {
603             check_justme $lchan
604         }
605     }
606 }
607
608 proc msg_TOPIC {p c dest topic} {
609     prefix_nick
610     if {![ischan $dest]} return
611     recordlastseen_n $n "changing the topic on $dest" 1
612     note_topic [irctolower $dest] $n $topic
613 }
614
615 proc msg_KICK {p c chans users comment} {
616     set chans [split $chans ,]
617     set users [split $users ,]
618     if {[llength $chans] > 1} {
619         foreach chan $chans user $users { process_kickpart $chan $user }
620     } else {
621         foreach user $users { process_kickpart [lindex $chans 0] $user }
622     }
623 }
624
625 proc msg_KILL {p c user why} {
626     nick_forget $user
627 }
628
629 set nick_counter 0
630 set nick_arys {onchans username unique}
631 # nick_onchans($luser) -> [list ... $lchan ...]
632 # nick_username($luser) -> <securely known local username>
633 # nick_unique($luser) -> <includes-counter>
634 # nick_case($luser) -> $user  (valid even if no longer visible)
635 # nick_markid($luser) -> <after id for marktime>
636 # nick_telling($luser) -> <unique> mentioned|passed <when>
637
638 # chan_nicks($lchan) -> [list ... $luser ...]
639 # chan_lastactivity($lchan) -> [clock seconds]
640
641 proc lnick_forget {luser} {
642     global nick_arys chan_nicks
643     lnick_marktime_cancel $luser
644     foreach ary $nick_arys {
645         upvar #0 nick_${ary}($luser) av
646         catch { unset av }
647     }
648     foreach lch [array names chan_nicks] {
649         upvar #0 chan_nicks($lch) nlist
650         set nlist [grep tn {"$tn" != "$luser"} $nlist]
651         check_justme $lch
652     }
653 }
654
655 proc nick_forget {user} {
656     global nick_arys chan_nicks
657     lnick_forget [irctolower $user]
658     nick_case $user
659 }
660
661 proc nick_case {user} {
662     global nick_case
663     set nick_case([irctolower $user]) $user
664 }
665
666 proc msg_NICK {p c newnick} {
667     global nick_arys nick_case calling_nick
668     prefix_nick
669     recordlastseen_n $n "changing nicks to $newnick" 0
670     set calling_nick $newnick
671     recordlastseen_n $newnick "changing nicks from $n" 1
672     set luser [irctolower $n]
673     lnick_marktime_cancel $luser
674     set lusernew [irctolower $newnick]
675     foreach ary $nick_arys {
676         upvar #0 nick_${ary}($luser) old
677         upvar #0 nick_${ary}($lusernew) new
678         if {[info exists new]} { error "nick collision ?! $ary $n $newnick" }
679         if {[info exists old]} { set new $old; unset old }
680     }
681     upvar #0 nick_onchans($lusernew) oc
682     foreach ch $oc {
683         upvar #0 chan_nicks($ch) nlist
684         set nlist [grep tn {"$tn" != "$luser"} $nlist]
685         lappend nlist $lusernew
686     }
687     lnick_marktime_start $lusernew "Hi." 500 1
688     nick_case $newnick
689 }
690
691 proc nick_ishere {n} {
692     global nick_counter
693     upvar #0 nick_unique([irctolower $n]) u
694     if {![info exists u]} { set u [incr nick_counter].$n.[clock seconds] }
695     nick_case $n
696 }
697
698 proc msg_JOIN {p c chan} {
699     prefix_nick
700     nick_ishere $n
701     recordlastseen_n $n "joining $chan" 1
702     set nl [irctolower $n]
703     set lchan [irctolower $chan]
704     upvar #0 nick_onchans($nl) oc
705     upvar #0 chan_nicks($lchan) nlist
706     if {![info exists oc]} {
707         global marktime_join_startdelay
708         lnick_marktime_start $nl "Welcome." $marktime_join_startdelay 1
709     }
710     lappend oc $lchan
711     lappend nlist $nl
712 }
713 proc msg_PART {p c chan args} {
714     prefix_nick
715     set msg "leaving $chan"
716     if {[llength $args]} {
717         set why [lindex $args 0]
718         if {"[irctolower $why]" != "[irctolower $n]"} { append msg " ($why)" }
719     }
720     recordlastseen_n $n $msg 1
721     process_kickpart $chan $n
722 }
723 proc msg_QUIT {p c why} {
724     prefix_nick
725     recordlastseen_n $n "leaving ($why)" 0
726     nick_forget $n
727 }
728
729 proc msg_PRIVMSG {p c dest text} {
730     global errorCode
731     
732     prefix_nick
733     if {[ischan $dest]} {
734         recordlastseen_n $n "invoking me in $dest" 1
735         set output $dest
736     } else {
737         recordlastseen_n $n "talking to me" 1
738         set output $n
739     }
740     nick_case $n
741
742     execute_usercommand $p $c $n $output $dest $text
743 }
744
745 proc msg_INVITE {p c n chan} {
746     after 1000 [list dojoin [irctolower $chan]]
747 }
748
749 proc grep {var predicate list} {
750     set o {}
751     upvar 1 $var v
752     foreach v $list {
753         if {[uplevel 1 [list expr $predicate]]} { lappend o $v }
754     }
755     return $o
756 }
757
758 proc msg_353 {p c dest type chan nicklist} {
759     global names_chans nick_onchans
760     set lchan [irctolower $chan]
761     upvar #0 chan_nicks($lchan) nlist
762     lappend names_chans $lchan
763     if {![info exists nlist]} {
764         # We don't think we're on this channel, so ignore it !
765         # Unfortunately, because we don't get a reply to PART,
766         # we have to remember ourselves whether we're on a channel,
767         # and ignore stuff if we're not, to avoid races.  Feh.
768         return
769     }
770     set nlist_new {}
771     foreach user [split $nicklist { }] {
772         regsub {^[@+]} $user {} user
773         if {![string length $user]} continue
774         check_nick $user
775         set luser [irctolower $user]
776         upvar #0 nick_onchans($luser) oc
777         lappend oc $lchan
778         lappend nlist_new $luser
779         nick_ishere $user
780     }
781     set nlist $nlist_new
782 }
783
784 proc msg_366 {p c args} {
785     global names_chans nick_onchans
786     set lchan [irctolower $c]
787     foreach luser [array names nick_onchans] {
788         upvar #0 nick_onchans($luser) oc
789         if {[llength names_chans] > 1} {
790             set oc [grep tc {[lsearch -exact $tc $names_chans] >= 0} $oc]
791         }
792         if {![llength $oc]} { lnick_forget $luser }
793     }
794     unset names_chans
795 }
796
797 proc check_username {target} {
798     if {
799         [string length $target] > 8 ||
800         [regexp {[^-0-9a-z]} $target] ||
801         ![regexp {^[a-z]} $target]
802     } { error "invalid username" }
803 }
804
805 proc somedb__head {} {
806     uplevel 1 {
807         set idl [irctolower $id]
808         upvar #0 ${nickchan}db($idl) ndbe
809         binary scan $idl H* idh
810         set idfn $fprefix$idh
811         if {![info exists iddbe] && [file exists $idfn]} {
812             set f [open $idfn r]
813             try_except_finally { set newval [read $f] } {} { close $f }
814             if {[llength $newval] % 2} { error "invalid length" }
815             set iddbe $newval
816         }
817     }
818 }
819
820 proc def_somedb {name arglist body} {
821     foreach {nickchan fprefix} {
822         nick users/n
823         chan chans/c
824         msgs users/m
825     } {
826         proc ${nickchan}db_$name $arglist \
827             "set nickchan $nickchan; set fprefix $fprefix; $body"
828     }
829 }
830
831 def_somedb list {} {
832     set list {}
833     foreach path [glob -nocomplain -path $fprefix *] {
834         binary scan $path "A[string length $fprefix]A*" afprefix thinghex
835         if {"$afprefix" != "$fprefix"} { error "wrong prefix $path $afprefix" }
836         lappend list [binary format H* $thinghex]
837     }
838     return $list
839 }
840
841 proc def_somedb_id {name arglist body} {
842     def_somedb $name [concat id $arglist] "somedb__head; $body"
843 }
844
845 def_somedb_id exists {} {
846     return [info exists iddbe]
847 }
848
849 def_somedb_id delete {} {
850     catch { unset iddbe }
851     file delete $idfn
852 }
853
854 set default_settings_nick {
855     timeformat ks
856     marktime off
857     tellsec {secure 600}
858     tellrel {remind 3600 30}
859 }
860
861 set default_settings_chan {
862     autojoin 1
863     mode *
864     userinvite pub
865     topicset {}
866     topicsee {}
867     topictell {}
868 }
869
870 set default_settings_msgs {
871     inbound {}
872     outbound {}
873 }
874 # inbound -> [<nick> <time_t> <message>] ...
875 # outbound -> [<nick> <time_t(earliest)> <count>] ...
876 #   neither are sorted particularly; only one entry per recipient in
877 #   output; both sender and recipient are cased
878
879 def_somedb_id set {args} {
880     upvar #0 default_settings_$nickchan def
881     if {![info exists iddbe]} { set iddbe $def }
882     foreach {key value} [concat $iddbe $args] { set a($key) $value }
883     set newval {}
884     foreach {key value} [array get a] { lappend newval $key $value }
885     set f [open $idfn.new w]
886     try_except_finally {
887         puts $f $newval
888         close $f
889         file rename -force $idfn.new $idfn
890     } {
891     } {
892         catch { close $f }
893     }
894     set iddbe $newval
895 }
896
897 def_somedb_id get {key} {
898     upvar #0 default_settings_$nickchan def
899     if {[info exists iddbe]} {
900         set l [concat $iddbe $def]
901     } else {
902         set l $def
903     }
904     foreach {tkey value} $l {
905         if {"$tkey" == "$key"} { return $value }
906     }
907     error "unset setting $key"
908 }
909
910 proc opt {key} {
911     global calling_nick
912     if {[info exists calling_nick]} { set n $calling_nick } { set n {} }
913     return [nickdb_get $n $key]
914 }
915
916 proc check_notonchan {} {
917     upvar 1 dest dest
918     if {[ischan $dest]} { usererror "That command must be sent privately." }
919 }
920
921 proc nick_securitycheck {strict} {
922     upvar 1 n n
923     if {![nickdb_exists $n]} {
924         usererror "You are unknown to me, use `register'."
925     }
926     set wantu [nickdb_get $n username]
927     if {![string length $wantu]} {
928         if {$strict} {
929             usererror "That feature is only available to secure users, sorry."
930         } else {
931             return
932         }
933     }
934     set luser [irctolower $n]
935     upvar #0 nick_username($luser) nu
936     if {![info exists nu]} {
937         usererror "Nick $n is secure, you must identify yourself first."
938     }
939     if {"$wantu" != "$nu"} {
940         usererror "You are the wrong user -\
941                 the nick $n belongs to $wantu, not $nu."
942     }
943 }
944
945 proc channel_ismanager {channel n} {
946     set mgrs [chandb_get $channel managers]
947     return [expr {[lsearch -exact [irctolower $mgrs] [irctolower $n]] >= 0}]
948 }
949
950 proc channel_securitycheck {channel} {
951     upvar n n
952     if {![channel_ismanager $channel $n]} {
953         usererror "You are not a manager of $channel."
954     }
955     nick_securitycheck 1
956 }
957
958 proc def_chancmd {name body} {
959     proc channel/$name {} \
960             "    upvar 1 target chan; upvar 1 n n; upvar 1 text text; $body"
961 }
962
963 proc ta_listop {findnow procvalue} {
964     # findnow and procvalue are code fragments which will be executed
965     # in the caller's level.  findnow should set ta_listop_ev to
966     # the current list, and procvalue should treat ta_listop_ev as
967     # a proposed value in the list and check and possibly modify
968     # (canonicalise?) it.  After ta_listop, ta_listop_ev will
969     # be the new value of the list.
970     upvar 1 ta_listop_ev exchg
971     upvar 1 text text
972     set opcode [ta_word]
973     switch -exact _$opcode {
974         _= { }
975         _+ - _- {
976             uplevel 1 $findnow
977             foreach item $exchg { set array($item) 1 }
978         }
979         default {
980             error "list change opcode must be one of + - ="
981         }
982     }
983     foreach exchg [split $text " "] {
984         if {![string length $exchg]} continue
985         uplevel 1 $procvalue
986         if {"$opcode" != "-"} {
987             set array($exchg) 1
988         } else {
989             catch { unset array($exchg) }
990         }
991     }
992     set exchg [lsort [array names array]]
993 }
994
995 def_chancmd manager {
996     ta_listop {
997         if {[chandb_exists $chan]} {
998             set ta_listop_ev [chandb_get $chan managers]
999         } else {
1000             set ta_listop_ev [list [irctolower $n]]
1001         }
1002     } {
1003         check_nick $ta_listop_ev
1004         set ta_listop_ev [irctolower $ta_listop_ev]
1005     }
1006     if {[llength $ta_listop_ev]} {
1007         chandb_set $chan managers $ta_listop_ev
1008         ucmdr "Managers of $chan: $ta_listop_ev" {}
1009     } else {
1010         chandb_delete $chan
1011         ucmdr {} {} "forgets about managing $chan." {}
1012     }
1013 }
1014
1015 def_chancmd autojoin {
1016     set yesno [ta_word]
1017     switch -exact [string tolower $yesno] {
1018         no { set nv 0 }
1019         yes { set nv 1 }
1020         default { error "channel autojoin must be `yes' or `no' }
1021     }
1022     chandb_set $chan autojoin $nv
1023     ucmdr [expr {$nv ? "I will join $chan when I'm restarted " : \
1024             "I won't join $chan when I'm restarted "}] {}
1025 }
1026
1027 def_chancmd userinvite {
1028     set nv [string tolower [ta_word]]
1029     switch -exact $nv {
1030         pub { set txt "!invite will work for $chan, but it won't work by /msg" }
1031         here { set txt "!invite and /msg invite will work, but only for users who are already on $chan." }
1032         all { set txt "Any user will be able to invite themselves or anyone else to $chan." }
1033         none { set txt "I will not invite anyone to $chan." }
1034         default {
1035             error "channel userinvite must be `pub', `here', `all' or `none'
1036         }
1037     }
1038     chandb_set $chan userinvite $nv
1039     ucmdr $txt {}
1040 }
1041
1042 def_chancmd topic {
1043     set what [ta_word]
1044     switch -exact $what {
1045         leave {
1046             ta_nomore
1047             chandb_set $chan topicset {}
1048             ucmdr "I won't ever change the topic of $chan." {}
1049         }
1050         set {
1051             set t [string trim $text]
1052             if {![string length $t]} {
1053                 error "you must specific the topic to set"
1054             }
1055             chandb_set $chan topicset $t
1056             ucmdr "Whenever I'm alone on $chan, I'll set the topic to $t." {}
1057         }
1058         see - tell {
1059             ta_listop {
1060                 set ta_listop_ev [chandb_get $chan topic$what]
1061             } {
1062                 if {"$ta_listop_ev" != "*"} {
1063                     if {![ischan $ta_listop_ev]} {
1064                         error "bad channel \`$ta_listop_ev' in topic $what"
1065                     }
1066                     set ta_listop_ev [irctolower $ta_listop_ev]
1067                 }
1068             }
1069             chandb_set $chan topic$what $ta_listop_ev
1070             ucmdr "Topic $what list for $chan: $ta_listop_ev" {}
1071         }
1072         default {
1073             usererror "Unknown channel topic subcommand - see help channel."
1074         }
1075     }
1076 }
1077
1078 def_chancmd mode {
1079     set mode [ta_word]
1080     if {"$mode" != "*" && ![regexp {^(([-+][imnpst]+)+)$} $mode mode]} {
1081         error {channel mode must be * or match ([-+][imnpst]+)+}
1082     }
1083     chandb_set $chan mode $mode
1084     if {"$mode" == "*"} {
1085         ucmdr "I won't ever change the mode of $chan." {}
1086     } else {
1087         ucmdr "Whenever I'm alone on $chan, I'll set the mode to $mode." {}
1088     }
1089 }
1090
1091 def_chancmd show {
1092     if {[chandb_exists $chan]} {
1093         set l "Settings for $chan: autojoin "
1094         append l [lindex {no yes} [chandb_get $chan autojoin]]
1095         append l ", mode " [chandb_get $chan mode]
1096         append l ", userinvite " [chandb_get $chan userinvite] "."
1097         append l "\nManagers: "
1098         append l [join [chandb_get $chan managers] " "]
1099         foreach {ts sep} {see "\n" tell "  "} {
1100             set t [chandb_get $chan topic$ts]
1101             append l $sep
1102             if {[llength $t]} {
1103                 append l "Topic $ts list: $t."
1104             } else {
1105                 append l "Topic $ts list is empty."
1106             }
1107         }
1108         append l "\n"
1109         set t [chandb_get $chan topicset]
1110         if {[string length $t]} {
1111             append l "Topic to set: $t"
1112         } else {
1113             append l "I will not change the topic."
1114         }
1115         ucmdr {} $l
1116     } else {
1117         ucmdr {} "The channel $chan is not managed."
1118     }
1119 }
1120
1121 proc channelmgr_monoop {} {
1122     upvar 1 dest dest
1123     upvar 1 text text
1124     upvar 1 n n
1125     upvar 1 p p
1126     upvar 1 target target
1127     global chan_nicks
1128
1129     prefix_nick
1130
1131     if {[ischan $dest]} { set target $dest }
1132     if {[ta_anymore]} { set target [ta_word] }
1133     ta_nomore
1134     if {![info exists target]} {
1135         usererror "You must specify, or invoke me on, the relevant channel."
1136     }
1137     if {![info exists chan_nicks([irctolower $target])]} {
1138         usererror "I am not on $target."
1139     }
1140     if {![ischan $target]} { error "not a valid channel" }
1141
1142     if {![chandb_exists $target]} {
1143         usererror "$target is not a managed channel."
1144     }
1145     channel_securitycheck $target
1146 }
1147
1148 def_ucmd op {
1149     channelmgr_monoop
1150     sendout MODE $target +o $n
1151     ucmdr {} {}
1152 }
1153
1154 def_ucmd leave {
1155     channelmgr_monoop
1156     doleave $target
1157     ucmdr {} {}
1158 }
1159
1160 def_ucmd invite {
1161     global chan_nicks errorCode errorInfo
1162     prefix_nick
1163     
1164     if {[ischan $dest]} {
1165         set target $dest
1166         set onchan 1
1167     } else {
1168         set target [ta_word]
1169         set onchan 0
1170     }
1171     set ltarget [irctolower $target]
1172     if {![ischan $target]} { error "$target is not a channel" }
1173     if {![info exists chan_nicks($ltarget)]} {
1174         usererror "I am not on $target."
1175     }
1176     set ui [chandb_get $ltarget userinvite]
1177     if {[catch {
1178         if {"$ui" == "pub" && !$onchan} {
1179             usererror "Invitations to $target must be made there with !invite."
1180         }
1181         if {"$ui" != "all"} {
1182             if {[lsearch -exact $chan_nicks($ltarget) [irctolower $n]] < 0} {
1183                 usererror "Invitations to $target may only be made\
1184                         by a user on the channel."
1185             }
1186         }
1187         if {"$ui" == "none"} {
1188             usererror "Sorry, I've not been authorised\
1189                     to invite people to $target."
1190         }
1191     } emsg]} {
1192         if {"$errorCode" == "BLIGHT USER" && [channel_ismanager $target $n]} {
1193             if {[catch {
1194                 nick_securitycheck 1
1195             } emsg2]} {
1196                 if {"$errorCode" == "BLIGHT USER"} {
1197                     usererror "$emsg2  Therefore you can't use your\
1198                             channel manager privilege.  $emsg"
1199                 } else {
1200                     error $error $errorInfo $errorCode
1201                 }
1202             }
1203         } else {
1204             error $emsg $errorInfo $errorCode
1205         }
1206     }
1207     if {![ta_anymore]} {
1208         usererror "You have to say who to invite."
1209     }
1210     set invitees {}
1211     while {[ta_anymore]} {
1212         set invitee [ta_nick]
1213         lappend invitees $invitee
1214     }
1215     foreach invitee $invitees {
1216         sendout INVITE $invitee $ltarget
1217     }
1218     set who [lindex $invitees 0]
1219     switch -exact llength $invitees {
1220         0 { error "zero invitees" }
1221         1 { }
1222         2 { append who " and [lindex $invitees 1]" }
1223         * {
1224             set who [join [lreplace $invitees end end] ", "]
1225             append who " and [lindex $invitees [llength $invitees]]"
1226         }
1227     }
1228     ucmdr {} {} {} "invites $who to $target."
1229 }
1230
1231 def_ucmd channel {
1232     if {[ischan $dest]} { set target $dest }
1233     if {![ta_anymore]} {
1234         set subcmd show
1235     } else {
1236         set subcmd [ta_word]
1237     }
1238     if {[ischan $subcmd]} {
1239         set target $subcmd
1240         if {![ta_anymore]} {
1241             set subcmd show
1242         } else {
1243             set subcmd [ta_word]
1244         }
1245     }
1246     if {![info exists target]} { error "privately, you must specify a channel" }
1247     set procname channel/$subcmd
1248     if {"$subcmd" != "show"} {
1249         if {[catch { info body $procname }]} {
1250             usererror "unknown channel setting $subcmd."
1251         }
1252         prefix_nick
1253         if {[chandb_exists $target]} {
1254             channel_securitycheck $target
1255         } else {
1256             nick_securitycheck 1
1257             upvar #0 chan_initialop([irctolower $target]) io
1258             upvar #0 nick_unique([irctolower $n]) u
1259             if {![info exists io]} {
1260                 usererror "$target is not a managed channel."
1261             }
1262             if {"$io" != "$u"} {
1263                 usererror "You are not the interim manager of $target."
1264             }
1265             if {"$subcmd" != "manager"} {
1266                 usererror "Please use `channel manager' first."
1267             }
1268         }
1269     }
1270     channel/$subcmd
1271 }
1272
1273 proc nickdb_get_username {n} {
1274     if {![nickdb_exists $n]} { return "" }
1275     return [nickdb_get $n username]
1276 }
1277
1278 proc nickdb_get_sec_effective {n} {
1279     set l [nickdb_get $n tellsec]
1280     set u [nickdb_get_username $n]
1281     if {"[lindex $l 0]" == "secure" && ![string length $u]} { set l insecure }
1282     return $l
1283 }
1284
1285 proc tell_peernicks {text} {
1286     global errorInfo errorCode
1287     set text [irctolower [string trim $text]]
1288     set senders [split $text " "]
1289     foreach sender $senders {
1290         if {[catch { check_nick $sender } emsg]} {
1291             error "invalid nick `$sender': $emsg" $errorInfo $errorCode
1292         }
1293     }
1294     return $senders
1295 }
1296
1297 proc msgsdb_set_maydelete {n key l otherkey} {
1298     msgsdb_set $n $key $l
1299     if {[llength $l]} return
1300     if {[llength [msgsdb_get $n $otherkey]]} return
1301     msgsdb_delete $n
1302 }
1303
1304 proc tell_delete_msgs {lsenders lrecip} {
1305     set ninbound {}
1306     set ndel 0
1307     foreach {s t m} [msgsdb_get $lrecip inbound] {
1308         if {[llength $lsenders]} {
1309             if {[lsearch -exact $lsenders [irctolower $s]] == -1} {
1310                 lappend ninbound $s $t $m
1311                 continue
1312             }
1313         }
1314         set rsenders($s) 1
1315         incr ndel
1316     }
1317     msgsdb_set_maydelete $lrecip inbound $ninbound outbound
1318     if {![llength $ninbound]} {
1319         upvar #0 nick_telling($lrecip) telling
1320         catch { unset telling }
1321     }
1322     foreach s [array names rsenders] {
1323         set noutbound {}
1324         foreach {r t c} [msgsdb_get $s outbound] {
1325             if {"[irctolower $r]" == "$lrecip"} continue
1326             lappend noutbound $r $t $c
1327         }
1328         msgsdb_set_maydelete $s outbound $noutbound inbound
1329     }
1330     return $ndel
1331 }
1332
1333 def_ucmd untell {
1334     prefix_nick
1335     check_notonchan
1336     if {[nickdb_exists $n]} { nick_securitycheck 0 }
1337     set recipients [tell_peernicks $text]
1338     if {![llength $recipients]} {
1339         usererror "You must say which recipients' messages from you to forget."
1340     }
1341     set ndel 0
1342     foreach recip $recipients {
1343         incr ndel [tell_delete_msgs [irctolower $n] $recip]
1344     }
1345     ucmdr "Removed $ndel as yet undelivered message(s)." {}
1346 }
1347
1348 def_ucmd_alias delmsgs delmsg
1349 def_ucmd delmsg {
1350     global errorInfo errorCode
1351     prefix_nick
1352     set nl [irctolower $n]
1353     check_notonchan
1354     manyset [nickdb_get_sec_effective $n] sec secwhen
1355     switch -exact $sec {
1356         insecure { }
1357         reject - mailto {
1358             usererror \
1359  "There are no messages to delete\
1360  because your message disposition prevents them from being left."
1361         }
1362         secure {
1363             nick_securitycheck 1
1364         }
1365         default {
1366             error "delmsg sec $sec"
1367         }
1368     }
1369     if {![llength [msgsdb_get $n inbound]]} {
1370         ucmdr "No incoming messages to delete." {}
1371     }
1372     tell_getcstate
1373     if {![info exists u]} {
1374         usererror \
1375  "I can't delete your messages unless I can see you on a channel with me.\
1376   Otherwise I might delete a message I hadn't told you about yet."
1377     }
1378     if {"$stt" != "passed"} {
1379         set telling [list $u undelivered 0]
1380         usererror \
1381  "There are message(s) you may not yet have seen;\
1382  I'll deliver them to you now.\
1383   If you actually want to delete them, just tell me `delmsg' again."
1384     }
1385     set senders [tell_peernicks $text]
1386     set ndel [tell_delete_msgs [irctolower $senders] [irctolower $n]]
1387     if {!$ndel} {
1388         if {[llength $senders]} {
1389             ucmdr "No relevant incoming messages to delete." {}
1390         }
1391     }
1392     switch -exact [llength $senders] {
1393         0 { ucmdr {} {} "deletes your $ndel message(s)." }
1394         1 { ucmdr {} {} "deletes your $ndel message(s) from $senders." }
1395         default {
1396             ucmdr {} {} "deletes your $ndel message(s) from\
1397  [lreplace $senders end end] and/or [lindex $senders end]."
1398         }
1399     }
1400 }
1401
1402 def_ucmd tellme {
1403     prefix_nick
1404     ta_nomore
1405     check_notonchan
1406     manyset [nickdb_get $n tellsec] sec
1407     switch -exact $sec {
1408         reject { ucmdr "But, you asked me to reject messages for you !" {} }
1409         mailto { ucmdr "But, you asked me to mail your messages to you !" {} }
1410     }
1411     switch -exact [tell_event [irctolower $n] tellme] {
1412         ERROR - INVALID { ucmdr {} {is ill.  Help!} }
1413         nomsgs { ucmdr {You have no messages.} {} }
1414         default { }
1415     }
1416 }
1417
1418 def_ucmd tell {
1419     global nick_case ownmailaddr ownfullname
1420     
1421     prefix_nick
1422     set target [ta_nick]
1423     if {![string length $text]} { error "tell them what?" }
1424     if {[string length $text] > 400} { error "message too long" }
1425
1426     set ltarget [irctolower $target]
1427     set ctarget $target
1428     if {[info exists nick_case($ltarget)]} { set ctarget $nick_case($ltarget) }
1429
1430     manyset [nickdb_get_sec_effective $target] sec mailtoint mailwhy
1431     manyset [nickdb_get $target tellrel] rel relint relwithin
1432     switch -exact $sec {
1433         insecure - secure {
1434             set now [clock seconds]
1435             set inbound [msgsdb_get $ltarget inbound]
1436             lappend inbound $n $now $text
1437             msgsdb_set $ltarget inbound $inbound
1438
1439             set outbound [msgsdb_get $n outbound]
1440             set noutbound {}
1441             set found 0
1442             foreach {recip time count} $outbound {
1443                 if {"[irctolower $recip]" == "$ltarget"} {
1444                     incr count
1445                     set recip $ctarget
1446                     set found 1
1447                 }
1448                 lappend noutbound $recip $time $count
1449             }
1450             if {!$found} {
1451                 lappend noutbound $ctarget $now 1
1452             }
1453             msgsdb_set $n outbound $noutbound
1454             set msg "OK, I'll tell $ctarget"
1455             if {$found} { append msg " that too" }
1456             append msg ", "
1457             if {"$sec" != "secure"} {
1458                 switch -exact $rel {
1459                     unreliable { append msg "neither reliably nor securely" }
1460                     remind { append msg "pretty reliably, but not securely" }
1461                     pester { append msg "reliably but not securely" }
1462                 }
1463             } else {
1464                 switch -exact $rel {
1465                     unreliable { append msg "securely but not reliably" }
1466                     remind { append msg "securely and pretty reliably" }
1467                     pester { append msg "reliably and securely" }
1468                 }
1469             }
1470             append msg .
1471             tell_event $ltarget msgsarrive
1472             ucmdr $msg {}
1473         }
1474         mailto {
1475             set fmtmsg [exec fmt << " $text"]
1476             exec /usr/sbin/sendmail -odb -oi -t -oee -f $mailwhy \
1477                     > /dev/null << \
1478  "From: $ownmailaddr ($ownfullname)
1479 To: $mailtoint
1480 Subject: IRC tell from $n
1481
1482 $n asked me[expr {[ischan $dest] ? " on $dest" : ""}] to tell you:
1483 [exec fmt << " $text"]
1484
1485 (This message was for your nick $ctarget; your account $mailwhy
1486  arranged for it to be forwarded to $mailtoint.)
1487 "
1488             ucmdr \
1489  "I've mailed $ctarget, which is what they prefer." \
1490                 {}
1491         }
1492         reject {
1493             usererror "Sorry, $ctarget does not want me to take messages."
1494         }
1495         default {
1496             error "bad tellsec $sec"
1497         }
1498     }
1499 }
1500
1501 def_ucmd who {
1502     if {[ta_anymore]} {
1503         set target [ta_nick]; ta_nomore
1504         set myself 1
1505     } else {
1506         prefix_nick
1507         set target $n
1508         set myself [expr {"$target" != "$n"}]
1509     }
1510     set ltarget [irctolower $target]
1511     upvar #0 nick_case($ltarget) ctarget
1512     set nshow $target
1513     if {[info exists ctarget]} {
1514         upvar #0 nick_onchans($ltarget) oc
1515         upvar #0 nick_username($ltarget) nu
1516         if {[info exists oc]} { set nshow $ctarget }
1517     }
1518     if {![nickdb_exists $ltarget]} {
1519         set ol "$nshow is not a registered nick."
1520     } elseif {[string length [set username [nickdb_get $target username]]]} {
1521         set ol "The nick $nshow belongs to the user $username."
1522     } else {
1523         set ol "The nick $nshow is registered (but not to a username)."
1524     }
1525     if {![info exists ctarget] || ![info exists oc]} {
1526         if {$myself} {
1527             append ol "\nI can't see $nshow on anywhere."
1528         } else {
1529             append ol "\nYou aren't on any channels with me."
1530         }
1531     } elseif {![info exists nu]} {
1532         append ol "\n$nshow has not identified themselves."
1533     } elseif {![info exists username]} {
1534         append ol "\n$nshow has identified themselves as the user $nu."
1535     } elseif {"$nu" != "$username"} {
1536         append ol "\nHowever, $nshow is being used by the user $nu."
1537     } else {
1538         append ol "\n$nshow has identified themselves to me."
1539     }
1540     ucmdr {} $ol
1541 }
1542
1543 def_ucmd register {
1544     prefix_nick
1545     check_notonchan
1546     set old [nickdb_exists $n]
1547     if {$old} { nick_securitycheck 0 }
1548     set luser [irctolower $n]
1549     switch -exact [string tolower [string trim $text]] {
1550         {} {
1551             upvar #0 nick_username($luser) nu
1552             if {![info exists nu]} {
1553                 ucmdr {} \
1554  "You must identify yourself before using `register'.  See `help identify', or use `register insecure'."
1555             }
1556             nickdb_set $n username $nu
1557             ucmdr {} {} "makes a note of your username." {}
1558         }
1559         delete {
1560             nickdb_delete $n
1561             ucmdr {} {} "forgets your nickname." {}
1562         }
1563         insecure {
1564             nickdb_set $n username {}
1565             if {$old} {
1566                 ucmdr {} "Security is now disabled for your nickname !"
1567             } else {
1568                 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."
1569             }
1570         }
1571         default {
1572             error "you mean register / register delete / register insecure"
1573         }
1574     }
1575 }
1576
1577 proc timeformat_desc {tf} {
1578     switch -exact $tf {
1579         ks { return "Times will be displayed in seconds or kiloseconds." }
1580         hms { return "Times will be displayed in hours, minutes, etc." }
1581         beat { return "Times will be displayed in beats (1000B = 1d)." }
1582         default { error "invalid timeformat: $v" }
1583     }
1584 }
1585
1586 set settings {}
1587 proc def_setting {opt show_body set_body} {
1588     global settings
1589     lappend settings $opt
1590     proc set_show/$opt {} "
1591         upvar 1 n n
1592         set opt $opt
1593         $show_body"
1594     if {![string length $set_body]} return
1595     proc set_set/$opt {} "
1596         upvar 1 n n
1597         upvar 1 text text
1598         set opt $opt
1599         $set_body"
1600 }
1601
1602 proc tellme_sec_desc {v n} {
1603     manyset $v sec mailtoint
1604     switch -exact $sec {
1605         insecure {
1606             return "I'll tell you your messages whenever I see you."
1607         }
1608         secure {
1609             if {[string length [nickdb_get_username $n]]} {
1610                 return \
1611  "I'll keep the bodies of your messages private until you identify yourself, reminding you every [showintervalsecs $mailtoint 1]."
1612             } else {
1613                 return \
1614  "I'll tell you your messages whenever I see you.\
1615   (Secure message delivery is enabled, but your nick is not registered\
1616  securely.  See `help register'.)"
1617             }
1618         }
1619         reject {
1620             return "I shan't accept messages for you."
1621         }
1622         mailto {
1623             return "I'll forward your messages by email to $mailtoint."
1624         }
1625         default {
1626             error "bad tellsec $sec"
1627         }
1628     }
1629 }
1630
1631 proc tellme_rel_desc {v n} {
1632     manyset $v rel every within
1633     switch -exact $rel {
1634         unreliable {
1635             return "As soon as I've told you message(s), I'll forget them\
1636  - note that this means messages can get lost !"
1637         }
1638         pester {
1639             set u {}
1640         }
1641         remind {
1642             set u ", or talk on channel within [showintervalsecs $within 1] of me having told you"
1643         }
1644         default {
1645             error "bad tellrel $rel"
1646         }
1647     }
1648     return "After delivering messages, I'll remind you every\
1649  [showintervalsecs $every 1] until you say delmsg$u."
1650 }
1651
1652 def_setting timeformat {
1653     set tf [nickdb_get $n timeformat]
1654     return "$tf: [timeformat_desc $tf]"
1655 } {
1656     set tf [string tolower [ta_word]]
1657     ta_nomore
1658     set desc [timeformat_desc $tf]
1659     nickdb_set $n timeformat $tf
1660     ucmdr {} $desc
1661 }
1662
1663 proc marktime_desc {mt} {
1664     if {"$mt" == "off"} {
1665         return "I will not send you periodic messages."
1666     } elseif {"$mt" == "once"} {
1667         return "I will send you one informational message when I see you."
1668     } else {
1669         return "I'll send you a message every [showintervalsecs $mt 0]."
1670     }
1671 }
1672
1673 def_setting marktime {
1674     set mt [nickdb_get $n marktime]
1675     set p $mt
1676     if {[string match {[0-9]*} $mt]} { append p s }
1677     append p ": "
1678     append p [marktime_desc $mt]
1679     return $p
1680 } {
1681     global marktime_min
1682     set mt [string tolower [ta_word]]
1683     ta_nomore
1684
1685     if {"$mt" == "off" || "$mt" == "once"} {
1686     } else {
1687         set mt [parse_interval $mt $marktime_min]
1688     }
1689     nickdb_set $n marktime $mt
1690     lnick_marktime_start [irctolower $n] "So:" 500 0
1691     ucmdr {} [marktime_desc $mt]
1692 }
1693
1694 def_setting security {
1695     set s [nickdb_get $n username]
1696     if {[string length $s]} {
1697         return "Your nick, $n, is controlled by the user $s."
1698     } else {
1699         return "Your nick, $n, is not secure."
1700     }
1701 } {}
1702
1703 proc tellme_setting_sec_simple {} {
1704     uplevel 1 {
1705         ta_nomore
1706         set sr sec
1707         set v $setting
1708     }
1709 }
1710
1711 proc tellme_setting_neednomsgs {} {
1712     uplevel 1 {
1713         if {[llength [msgsdb_get $n inbound]]} {
1714             usererror "You must delete the incoming messages you have, first."
1715         }
1716     }
1717 }
1718
1719 def_setting tellme {
1720     set secv [nickdb_get $n tellsec]
1721     set ms [tellme_sec_desc $secv $n]
1722     manyset $secv sec
1723     switch -exact $sec {
1724         insecure - secure {
1725             set mr [tellme_rel_desc [nickdb_get $n tellrel] $n]
1726             return "$ms  $mr"
1727         }
1728         reject - mailto {
1729             return $ms
1730         }
1731     }
1732 } {
1733     set setting [string tolower [ta_word]]
1734     set nl [irctolower $n]
1735     switch -exact $setting {
1736         insecure {
1737             tellme_setting_sec_simple
1738         }
1739         secure {
1740             set every [ta_interval_optional 60 600]
1741             ta_nomore
1742             set sr sec
1743             set v [list secure $every]
1744         }
1745         reject {
1746             tellme_setting_neednomsgs
1747             tellme_setting_sec_simple
1748         }
1749         mailto {
1750             tellme_setting_neednomsgs
1751             
1752             upvar #0 nick_username($nl) nu
1753             if {!([info exists nu] && [string length $nu])} {
1754                 usererror \
1755  "Sorry, you must register securely to have your messages mailed\
1756  (to prevent the use of this feature for spamming).  See `help register'."
1757             }
1758             set sr sec
1759             set v [list mailto [ta_word] $nu]
1760         }
1761         unreliable - pester - remind {
1762             manyset [nickdb_get $n tellsec] sec
1763             switch -exact $sec {
1764                 reject - mailto {
1765                     usererror \
1766  "Sorry, I shan't change when I'll consider a message delivered, because\
1767  you've asked me not to keep messages, or to mail them to you.\
1768   You should say `set tellme secure' or some such, first."
1769                 }
1770             }
1771             set sr rel
1772             set v $setting
1773             if {"$setting" != "unreliable"} {
1774                 set every [ta_interval_optional 300 3600]
1775                 lappend v $every
1776             }
1777             if {"$setting" == "remind"} {
1778                 set within [ta_interval_optional 5 30]
1779                 if {$within > $every} {
1780                     error "remind interval must be at least time to respond"
1781                 }
1782                 lappend v $within
1783             }
1784             ta_nomore
1785         }
1786         default {
1787             error "invalid tellme setting $setting"
1788         }
1789     }
1790     nickdb_set $n tell$sr $v
1791     upvar #0 nick_telling($nl) telling
1792     catch { unset telling }
1793     ucmdr [tellme_${sr}_desc $v $n] {}
1794 }
1795
1796 proc lnick_checktold {luser} {
1797     set ml [msgsdb_get $luser outbound]
1798     if {![llength $ml]} return
1799     set is1 [expr {[llength $ml]==3}]
1800     set m1 "FYI, I haven't yet delivered your"
1801     set ol {}
1802     set now [clock seconds]
1803     while {[llength $ml]} {
1804         manyset $ml r t n
1805         set ml [lreplace $ml 0 2]
1806         set td [expr {$now-$t}]
1807         if {$n == 1} {
1808             set iv [showinterval $td]
1809             set ifo "$r, $iv"
1810             set if1 "message to $r, $iv."
1811         } else {
1812             set iv [showintervalsecs $td 0]
1813             set ifo "$r, $n messages, oldest $iv"
1814             set if1 "$n messages to $r, oldest $iv."
1815         }
1816         if {$is1} {
1817             sendprivmsg $luser "$m1 $if1"
1818             return
1819         } else {
1820             lappend ol " to $ifo[expr {[llength $ml] ? ";" : "."}]"
1821         }
1822     }
1823     sendprivmsg $luser "$m1 messages:"
1824     msendprivmsg $luser $ol
1825 }
1826
1827 def_ucmd set {
1828     global settings
1829     prefix_nick
1830     check_notonchan
1831     if {![nickdb_exists $n]} {
1832         ucmdr {} "You are unknown to me and so have no settings.  (Use `register'.)"
1833     }
1834     if {![ta_anymore]} {
1835         set ol {}
1836         foreach opt $settings {
1837             lappend ol [format "%-10s %s" $opt [set_show/$opt]]
1838         }
1839         ucmdr {} [join $ol "\n"]
1840     } else {
1841         set opt [ta_word]
1842         if {[catch { info body set_show/$opt }]} {
1843             error "no setting $opt"
1844         }
1845         if {![ta_anymore]} {
1846             ucmdr {} "$opt: [set_show/$opt]"
1847         } else {
1848             nick_securitycheck 0
1849             if {[catch { info body set_set/$opt }]} {
1850                 error "setting $opt cannot be set with `set'"
1851             }
1852             set_set/$opt
1853         }
1854     }
1855 }
1856
1857 def_ucmd identpass {
1858     prefix_nick
1859     check_notonchan
1860     set luser [irctolower $n]
1861     set username [ta_word]
1862     set passmd5 [md5sum "[ta_word]\n"]
1863     ta_nomore
1864     upvar #0 nick_onchans($luser) onchans
1865     if {![info exists onchans] || ![llength $onchans]} {
1866         ucmdr "You must be on a channel with me to identify yourself." {}
1867     }
1868     check_username $username
1869     exec userv --timeout 3 $username << "$passmd5\n" > /dev/null \
1870             irc-identpass $n
1871     upvar #0 nick_username($luser) rec_username
1872     set rec_username $username
1873     after 50 [list tell_event $luser ident]
1874     ucmdr "Pleased to see you, $username." {}
1875 }
1876
1877 def_ucmd kill {
1878     global nick
1879     prefix_nick
1880     set target [ta_nick]
1881     if {![nickdb_exists $target]} { error "$target is not a registered nick." }
1882     set wantu [nickdb_get $target username]
1883     if {![string length $wantu]} { error "$target is insecurely registred." }
1884     upvar #0 nick_username([irctolower $n]) nu
1885     if {![info exists nu]} { error "You must identify yourself first." }
1886     if {"$wantu" != "$nu"} {
1887         error "You are the wrong user, $nu - $target belongs to $wantu."
1888     }
1889     set reason "at request of user $nu"
1890     if {[ta_anymore]} { append reason "; $text" }
1891     sendout KILL $target $reason
1892     ucmdr {} {}
1893 }
1894
1895 def_ucmd summon {
1896     set target [ta_word]
1897     ta_nomore
1898     # fixme would be nice if the rest of the text was passed on instead
1899     check_username $target
1900     prefix_nick
1901
1902     upvar #0 lastsummon($target) ls
1903     set now [clock seconds]
1904     if {[info exists ls]} {
1905         set interval [expr {$now - $ls}]
1906         if {$interval < 30} {
1907             ucmdr {} \
1908  "Please be patient; $target was summoned only [showinterval $interval]."
1909         }
1910     }
1911     regsub {^[^!]*!} $p {} path
1912     if {[catch {
1913         exec userv --timeout 3 $target irc-summon $n $path \
1914                 [expr {[ischan $dest] ? "$dest" : ""}] \
1915                 < /dev/null
1916     } rv]} {
1917         regsub -all "\n" $rv { / } rv
1918         error $rv
1919     }
1920     if {[regexp {^problem (.*)} $rv dummy problem]} {
1921         ucmdr {} "The user `$target' $problem."
1922     } elseif {[regexp {^ok ([^ ]+) ([0-9]+)$} $rv dummy tty idlesince]} {
1923         set idletime [expr {$now - $idlesince}]
1924         set ls $now
1925         ucmdr {} {} {} "invites $target ($tty[expr {
1926             $idletime > 10 ? ", idle for [showintervalsecs $idletime 0]" : ""
1927         }]) to [expr {
1928             [ischan $dest] ? "join us here" : "talk to you"
1929         }]."
1930     } else {
1931         error "unexpected response from userv service: $rv"
1932     }
1933 }
1934
1935 proc md5sum {value} { exec md5sum << $value }
1936
1937 def_ucmd seen {
1938     global lastseen nick
1939     prefix_nick
1940     set ncase [ta_nick]
1941     set nlower [irctolower $ncase]
1942     ta_nomore
1943     set now [clock seconds]
1944     if {"$nlower" == "[irctolower $nick]"} {
1945         usererror "I am not self-aware."
1946     } elseif {![info exists lastseen($nlower)]} {
1947         set rstr "I've never seen $ncase."
1948     } else {
1949         manyset $lastseen($nlower) realnick time what
1950         set howlong [expr {$now - $time}]
1951         set string [showinterval $howlong]
1952         set rstr "I last saw $realnick $string, $what."
1953     }
1954     if {[ischan $dest]} {
1955         set where $dest
1956     } else {
1957         set where {}
1958     }
1959     upvar #0 lookedfor($nlower) lf
1960     if {[info exists lf]} { set oldvalue $lf } else { set oldvalue {} }
1961     set lf [list [list $now $n $where]]
1962     foreach v $oldvalue {
1963         if {"[irctolower [lindex $v 1]]" == "[irctolower $n]"} continue
1964         lappend lf $v
1965     }
1966     ucmdr {} $rstr
1967 }
1968
1969 proc lnick_marktime_cancel {luser} {
1970     upvar #0 nick_markid($luser) mi
1971     if {![info exists mi]} return
1972     catch { after cancel $mi }
1973     catch { unset mi }
1974 }
1975
1976 proc lnick_marktime_doafter {luser why ms mentiontold} {
1977     lnick_marktime_cancel $luser
1978     upvar #0 nick_markid($luser) mi
1979     set mi [after $ms [list lnick_marktime_now $luser $why 0]]
1980 }
1981
1982 proc lnick_marktime_reset {luser} {
1983     set mt [nickdb_get $luser marktime]
1984     if {"$mt" == "off" || "$mt" == "once"} return
1985     lnick_marktime_doafter $luser "Time passes." [expr {$mt*1000}] 0
1986 }
1987
1988 proc lnick_marktime_start {luser why ms mentiontold} {
1989     set mt [nickdb_get $luser marktime]
1990     if {"$mt" == "off"} {
1991         lnick_marktime_cancel $luser
1992         if {$mentiontold} { after $ms [list lnick_checktold $luser] }
1993     } else {
1994         lnick_marktime_doafter $luser $why $ms $mentiontold
1995     }
1996 }
1997
1998 proc lnick_marktime_now {luser why mentiontold} {
1999     upvar #0 nick_onchans($luser) oc
2000     global calling_nick
2001     set calling_nick $luser
2002     sendprivmsg $luser [lnick_pingstring $why $oc ""]
2003     if {$mentiontold} { after 150 [list lnick_checktold $luser] }
2004     lnick_marktime_reset $luser
2005 }    
2006
2007 proc lnick_pingstring {why oc apstring} {
2008     global nick_onchans
2009     catch { exec uptime } uptime
2010     set nnicks [llength [array names nick_onchans]]
2011     if {[regexp \
2012  {^ *([0-9:apm]+) +up.*, +(\d+) users?, +load average: +([0-9., ]+) *$} \
2013             $uptime dummy time users load]} {
2014         regsub -all , $load {} load
2015         set uptime "$time  $nnicks/$users  $load"
2016     } else {
2017         append uptime ", $nnicks nicks"
2018     }
2019     if {[llength $oc]} {
2020         set best_la 0
2021         set activity quiet
2022         foreach ch $oc {
2023             upvar #0 chan_lastactivity($ch) la
2024             if {![info exists la]} continue
2025             if {$la <= $best_la} continue
2026             set since [showintervalsecs [expr {[clock seconds]-$la}] 1]
2027             set activity "$ch $since"
2028             set best_la $la
2029         }
2030     } else {
2031         set activity unseen
2032     }
2033     set str $why
2034     append str "  " $uptime "  " $activity
2035     if {[string length $apstring]} { append str "  " $apstring }
2036     return $str
2037 }
2038
2039 def_ucmd ping {
2040     prefix_nick
2041     set ln [irctolower $n]
2042     if {[ischan $dest]} {
2043         set oc [irctolower $dest]
2044     } else {
2045         global nick_onchans
2046         if {[info exists nick_onchans($ln)]} {
2047             set oc $nick_onchans($ln)
2048         } else {
2049             set oc {}
2050         }
2051         if {[llength $oc]} { lnick_marktime_reset $ln }
2052     }
2053     after 150 [list lnick_checktold $ln]
2054     ucmdr {} [lnick_pingstring "Pong!" $oc $text]
2055 }
2056
2057 proc ensure_globalsecret {} {
2058     global globalsecret
2059     
2060     if {[info exists globalsecret]} return
2061     set gsfile [open /dev/urandom r]
2062     fconfigure $gsfile -translation binary
2063     set globalsecret [read $gsfile 32]
2064     binary scan $globalsecret H* globalsecret
2065     close $gsfile
2066     unset gsfile
2067 }
2068
2069 proc connected {} {
2070     global operuserpass
2071     if {[info exists operuserpass]} {
2072         eval sendout OPER $operuserpass
2073     }
2074     foreach chan [chandb_list] {
2075         if {[chandb_get $chan autojoin]} { dojoin $chan }
2076     }
2077 }
2078
2079 ensure_globalsecret
2080 loadhelp
2081 ensure_connecting