chiark / gitweb /
marktime and ping.
[ircbot] / bot.tcl
1 # Core bot code
2
3 proc defset {varname val} {
4     upvar #0 $varname var
5     if {![info exists var]} { set var $val }
6 }
7
8 # must set host
9 defset port 6667
10
11 defset nick testbot
12 defset ownfullname "testing bot"
13 defset ownmailaddr test-irc-bot@example.com
14
15 defset musthaveping_ms 10000
16 defset out_maxburst 6
17 defset out_interval 2100
18 defset out_lag_lag 5000
19 defset out_lag_very 25000
20
21 defset marktime_min 300
22 defset marktime_join_startdelay 5000
23
24 proc manyset {list args} {
25     foreach val $list var $args {
26         upvar 1 $var my
27         set my $val
28     }
29 }
30
31 proc try_except_finally {try except finally} {
32     global errorInfo errorCode
33     set er [catch { uplevel 1 $try } emsg]
34     if {$er} {
35         set ei $errorInfo
36         set ec $errorCode
37         if {[catch { uplevel 1 $except } emsg3]} {
38             append ei "\nALSO ERROR HANDLING ERROR:\n$emsg3"
39         }
40     }
41     set er2 [catch { uplevel 1 $finally } emsg2]
42     if {$er} {
43         if {$er2} {
44             append ei "\nALSO ERROR CLEANING UP:\n$emsg2"
45         }
46         return -code $er -errorinfo $ei -errorcode $ec $emsg
47     } elseif {$er2} {
48         return -code $er2 -errorinfo $errorInfo -errorcode $errorCode $emsg2
49     } else {
50         return $emsg
51     }
52 }
53
54 proc out__vars {} {
55     uplevel 1 {
56         global out_queue out_creditms out_creditat out_interval out_maxburst
57         global out_lag_lag out_lag_very
58 #set pr [lindex [info level 0] 0]
59 #puts $pr>[clock seconds]|$out_creditat|$out_creditms|[llength $out_queue]<
60     }
61 }
62
63 proc out_lagged {} {
64     out__vars
65     if {[llength $out_queue]*$out_interval > $out_lag_very} {
66         return 2
67     } elseif {[llength $out_queue]*$out_interval > $out_lag_lag} {
68         return 1
69     } else {
70         return 0
71     }
72 }
73
74 proc out_restart {} {
75     out__vars
76     
77     set now [clock seconds]
78     incr out_creditms [expr {($now - $out_creditat) * 1000}]
79     set out_creditat $now
80     if {$out_creditms > $out_maxburst*$out_interval} {
81         set out_creditms [expr {$out_maxburst*$out_interval}]
82     }
83     out_runqueue $now
84 }
85
86 proc out_runqueue {now} {
87     global sock
88     out__vars
89     
90     while {[llength $out_queue] && $out_creditms >= $out_interval} {
91 #puts rq>$now|$out_creditat|$out_creditms|[llength $out_queue]<
92         manyset [lindex $out_queue 0] orgwhen msg
93         set out_queue [lrange $out_queue 1 end]
94         if {[llength $out_queue]} {
95             append orgwhen "+[expr {$now - $orgwhen}]"
96             append orgwhen "([llength $out_queue])"
97         }
98         puts "$orgwhen -> $msg"
99         puts $sock $msg
100         incr out_creditms -$out_interval
101     }
102     if {[llength $out_queue]} {
103         after $out_interval out_nextmessage
104     }
105 }
106
107 proc out_nextmessage {} {
108     out__vars
109     set now [clock seconds]
110     incr out_creditms $out_interval
111     set out_creditat $now
112     out_runqueue $now
113 }
114
115 proc sendout_priority {priority command args} {
116     global sock out_queue
117     if {[llength $args]} {
118         set la [lindex $args end]
119         set args [lreplace $args end end]
120         foreach i $args {
121             if {[regexp {[: ]} $i]} {
122                 error "bad argument in output $i ($command $args)"
123             }
124         }
125         lappend args :$la
126     }
127     set args [lreplace $args 0 -1 $command]
128     set string [join $args { }]
129     set now [clock seconds]
130     set newe [list $now $string]
131     if {$priority} {
132         set out_queue [concat [list $newe] $out_queue]
133     } else {
134         lappend out_queue $newe
135     }
136     if {[llength $out_queue] == 1} {
137         out_restart
138     }
139 }
140
141 proc sendout {command args} { eval sendout_priority [list 0 $command] $args }
142     
143 proc log {data} {
144     puts $data
145 }
146
147 proc logerror {data} {
148     log $data
149 }
150
151 proc saveeic {} {
152     global saveei saveec errorInfo errorCode
153
154     set saveei $errorInfo
155     set saveec $errorCode
156
157     puts ">$saveec|$saveei<"
158 }
159
160 proc bgerror {msg} {
161     global save
162     logerror $msg
163     saveeic
164 }
165
166 proc onread {args} {
167     global sock nick calling_nick errorInfo errorCode
168     
169     if {[gets $sock line] == -1} { fail "EOF/error on input" }
170     regsub -all "\[^ -\176\240-\376\]" $line ? line
171     set org $line
172     
173     set ei $errorInfo
174     set ec $errorCode
175     catch { unset calling_nick }
176     set errorInfo $ei
177     set errorCode $ec
178     
179     if {[regexp -nocase {^:([^ ]+) (.*)} $line dummy prefix remain]} {
180         set line $remain
181         if {[regexp {^([^!]+)!} $prefix dummy maybenick]} {
182             set calling_nick $maybenick
183             if {"[irctolower $maybenick]" == "[irctolower $nick]"} return
184         }
185     } else {
186         set prefix {}
187     }
188     if {![string length $line]} { return }
189     if {![regexp -nocase {^([0-9a-z]+) *(.*)} $line dummy command line]} {
190         log "bad command: $org"
191         return
192     }
193     set command [string toupper $command]
194     set params {}
195     while {[regexp {^([^ :]+) *(.*)} $line dummy thisword line]} {
196         lappend params $thisword
197     }
198     if {[regexp {^:(.*)} $line dummy thisword]} {
199         lappend params $thisword
200     } elseif {[string length $line]} {
201         log "junk at end: $org"
202         return
203     }
204     if {"$command" == "PRIVMSG" &&
205         [regexp {^[&#+!]} [lindex $params 0]] &&
206         ![regexp {^![a-z][-a-z]*[a-z]( .*)?$} [lindex $params 1]]} {
207         # on-channel message, ignore
208         set chan [lindex $params 0]
209         upvar #0 chan_lastactivity([irctolower $chan]) la
210         set la [clock seconds]
211         catch { recordlastseen_p $prefix "talking on $chan" 1 }
212         return
213     }
214     log "[clock seconds] <- $org"
215     set procname msg_$command
216     if {[catch { info body $procname }]} { return }
217     if {[catch {
218         eval [list $procname $prefix $command] $params
219     } emsg]} {
220         logerror "error: $emsg ($prefix $command $params)"
221         saveeic
222     }
223 }
224
225 proc sendprivmsg {dest l} {
226     foreach v [split $l "\n"] {
227         sendout [expr {[ischan $dest] ? "PRIVMSG" : "NOTICE"}] $dest $v
228     }
229 }
230 proc sendaction_priority {priority dest what} {
231     sendout_priority $priority PRIVMSG $dest "\001ACTION $what\001"
232 }
233 proc msendprivmsg {dest ll} { foreach l $ll { sendprivmsg $dest $l } }
234 proc msendprivmsg_delayed {delay dest ll} { after $delay [list msendprivmsg $dest $ll] }
235
236 proc prefix_none {} {
237     upvar 1 p p
238     if {[string length $p]} { error "prefix specified" }
239 }
240
241 proc msg_PING {p c s1} {
242     global musthaveping_after
243     prefix_none
244     sendout PONG $s1
245     if {[info exists musthaveping_after]} connected
246 }
247
248 proc check_nick {n} {
249     if {[regexp -nocase {[^][\\`_^{|}a-z0-9-]} $n]} { error "bad char in nick" }
250     if {[regexp {^[-0-9]} $n]} { error "bad nick start" }
251 }
252
253 proc ischan {dest} {
254     return [regexp {^[&#+!]} $dest]
255 }
256
257 proc irctolower {v} {
258     foreach {from to} [list "\\\[" "{" \
259                           "\\\]" "}" \
260                           "\\\\" "|" \
261                           "~"    "^"] {
262         regsub -all $from $v $to v
263     }
264     return [string tolower $v]
265 }
266
267 proc prefix_nick {} {
268     global nick
269     upvar 1 p p
270     upvar 1 n n
271     if {![regexp {^([^!]+)!} $p dummy n]} { error "not from nick" }
272     check_nick $n
273     if {"[irctolower $n]" == "[irctolower $nick]"} {
274         error "from myself" {} {}
275     }
276 }
277
278 proc showintervalsecs {howlong} {
279     return [showintervalsecs/[opt timeformat] $howlong]
280 }
281
282 proc showintervalsecs/ks {howlong} {
283     if {$howlong < 1000} {
284         return "${howlong}s"
285     } else {
286         if {$howlong < 1000000} {
287             set pfx k
288             set scale 1000
289         } else {
290             set pfx M
291             set scale 1000000
292         }
293         set value [expr "$howlong.0 / $scale"]
294         foreach {min format} {100 %.0f 10 %.1f 1 %.2f} {
295             if {$value < $min} continue
296             return [format "$format${pfx}s" $value]
297         }
298     }
299 }
300
301 proc format_qty {qty unit} {
302     set o $qty
303     append o " "
304     append o $unit
305     if {$qty != 1} { append o s }
306     return $o
307 }
308
309 proc showintervalsecs/hms {qty} {
310     set ul {second 60 minute 60 hour 24 day 7 week}
311     set remainv 0
312     while {[llength $ul] > 1 && $qty >= [set uv [lindex $ul 1]]} {
313         set remainu [lindex $ul 0]
314         set remainv [expr {$qty % $uv}]
315         set qty [expr {($qty-$remainv)/$uv}]
316         set ul [lreplace $ul 0 1]
317     }
318     set o [format_qty $qty [lindex $ul 0]]
319     if {$remainv} {
320         append o " "
321         append o [format_qty $remainv $remainu]
322     }
323     return $o
324 }
325
326 proc showinterval {howlong} {
327     if {$howlong <= 0} {
328         return {just now}
329     } else {
330         return "[showintervalsecs $howlong] ago"
331     }
332 }
333
334 proc showtime {when} {
335     return [showinterval [expr {[clock seconds] - $when}]]
336 }
337
338 proc def_msgproc {name argl body} {
339     proc msg_$name "varbase $argl" "\
340     upvar #0 msg/\$varbase/dest d\n\
341     upvar #0 msg/\$varbase/str s\n\
342     upvar #0 msg/\$varbase/accum a\n\
343 $body"
344 }
345
346 def_msgproc begin {dest str} {
347     set d $dest
348     set s $str
349     set a {}
350 }
351
352 def_msgproc append {str} {
353     set ns "$s$str"
354     if {[string length $s] && [string length $ns] > 65} {
355         msg__sendout $varbase
356         set s " [string trimleft $str]"
357     } else {
358         set s $ns
359     }
360 }
361
362 def_msgproc finish {} {
363     msg__sendout $varbase
364     unset s
365     unset d
366     return $a
367 }
368
369 def_msgproc _sendout {} {
370     lappend a [string trimright $s]
371     set s {}
372 }
373
374 proc looking_whenwhere {when where} {
375     set str [showtime [expr {$when-1}]]
376     if {[string length $where]} { append str " on $where" }
377     return $str
378 }
379
380 proc recordlastseen_n {n how here} {
381     global lastseen lookedfor
382     set lastseen([irctolower $n]) [list $n [clock seconds] $how]
383     if {!$here} return
384     upvar #0 lookedfor([irctolower $n]) lf
385     if {[info exists lf]} {
386         switch -exact [llength $lf] {
387             0 {
388                 set ml {}
389             }
390             1 {
391                 manyset [lindex $lf 0] when who where
392                 set ml [list \
393  "FYI, $who was looking for you [looking_whenwhere $when $where]."]
394             }
395             default {
396                 msg_begin tosend $n "FYI, people have been looking for you:"
397                 set i 0
398                 set fin ""
399                 foreach e $lf {
400                     incr i
401                     if {$i == 1} {
402                         msg_append tosend " "
403                     } elseif {$i == [llength $lf]} {
404                         msg_append tosend " and "
405                         set fin .
406                     } else {
407                         msg_append tosend ", "
408                     }
409                     manyset $e when who where
410                     msg_append tosend \
411                             "$who ([looking_whenwhere $when $where])$fin"
412                 }
413                 set ml [msg_finish tosend]
414             }
415         }
416         unset lf
417         msendprivmsg_delayed 1000 $n $ml
418     }
419 }
420
421 proc note_topic {showoff whoby topic} {
422     set msg "FYI, $whoby has changed the topic on $showoff"
423     if {[string length $topic] < 160} {
424         append msg " to $topic"
425     } else {
426         append msg " but it is too long to reproduce here !"
427     }
428     set showoff [irctolower $showoff]
429     set tell [chandb_get $showoff topictell]
430     if {[lsearch -exact $tell *] >= 0} {
431         set tryspies [chandb_list]
432     } else {
433         set tryspies $tell
434     }
435     foreach spy $tryspies {
436         set see [chandb_get $spy topicsee]
437         if {[lsearch -exact $see $showoff] >= 0 || \
438                 ([lsearch -exact $see *] >= 0 && \
439                 [lsearch -exact $tell $spy] >= 0)} {
440             sendprivmsg $spy $msg
441         }
442     }
443 }
444
445 proc recordlastseen_p {p how here} {
446     prefix_nick
447     recordlastseen_n $n $how $here
448 }
449
450 proc chanmode_arg {} {
451     upvar 2 args cm_args
452     set rv [lindex $cm_args 0]
453     set cm_args [lreplace cm_args 0 0]
454     return $rv
455 }
456
457 proc chanmode_o1 {m g p chan} {
458     global nick chan_initialop
459     prefix_nick
460     set who [chanmode_arg]
461     recordlastseen_n $n "being nice to $who" 1
462     if {"[irctolower $who]" == "[irctolower $nick]"} {
463         set nlower [irctolower $n]
464         upvar #0 nick_unique($nlower) u
465         if {[chandb_exists $chan]} {
466             sendprivmsg $n Thanks.
467         } elseif {![info exists u]} {
468             sendprivmsg $n {Op me while not on the channel, why don't you ?}
469         } else {
470             set chan_initialop([irctolower $chan]) $u
471             sendprivmsg $n \
472  "Thanks. You can use `channel manager ...' to register this channel."
473             if {![nickdb_exists $n] || ![string length [nickdb_get $n username]]} {
474                 sendprivmsg $n \
475  "(But to do that you must register your nick securely first.)"
476             }
477         }
478     }
479 }
480
481 proc chanmode_o0 {m g p chan} {
482     global nick chandeop
483     prefix_nick
484     set who [chanmode_arg]
485     recordlastseen_p $p "being mean to $who" 1
486     if {"[irctolower $who]" == "[irctolower $nick]"} {
487         set chandeop($chan) [list [clock seconds] $p]
488     }
489 }
490
491 proc msg_MODE {p c dest modelist args} {
492     if {![ischan $dest]} return
493     if {[regexp {^\-(.+)$} $modelist dummy modelist]} {
494         set give 0
495     } elseif {[regexp {^\+(.+)$} $modelist dummy modelist]} {
496         set give 1
497     } else {
498         error "invalid modelist"
499     }
500     foreach m [split $modelist] {
501         set procname chanmode_$m$give
502         if {[catch { info body $procname }]} {
503             recordlastseen_p $p "fiddling with $dest" 1
504         } else {
505             $procname $m $give  $p $dest
506         }
507     }
508 }
509
510 proc leaving {lchan} {
511     foreach luser [array names nick_onchans] {
512         upvar #0 nick_onchans($luser) oc
513         set oc [grep tc {"$tc" != "$lchan"} $oc]
514     }
515     upvar #0 chan_nicks($lchan) nlist
516     unset nlist
517     upvar #0 chan_lastactivity($lchan) la
518     catch { unset la }
519 }
520
521 proc doleave {lchan} {
522     sendout PART $lchan
523     leaving $lchan
524 }
525
526 proc dojoin {lchan} {
527     global chan_nicks
528     sendout JOIN $lchan
529     set chan_nicks($lchan) {}
530 }
531
532 proc check_justme {lchan} {
533     global nick
534     upvar #0 chan_nicks($lchan) nlist
535     if {[llength $nlist] != 1} return
536     if {"[lindex $nlist 0]" != "[irctolower $nick]"} return
537     if {[chandb_exists $lchan]} {
538         set mode [chandb_get $lchan mode]
539         if {"$mode" != "*"} {
540             sendout MODE $lchan $mode
541         }
542         set topic [chandb_get $lchan topicset]
543         if {[string length $topic]} {
544             sendout TOPIC $lchan $topic
545         }
546     } else {
547         doleave $lchan
548     }
549 }
550
551 proc process_kickpart {chan user} {
552     global nick
553     check_nick $user
554     set luser [irctolower $user]
555     set lchan [irctolower $chan]
556     if {![ischan $chan]} { error "not a channel" }
557     if {"$luser" == "[irctolower $nick]"} {
558         leaving $lchan
559     } else {
560         upvar #0 nick_onchans($luser) oc
561         upvar #0 chan_nicks($lchan) nlist
562         set oc [grep tc {"$tc" != "$lchan"} $oc]
563         set nlist [grep tn {"$tn" != "$luser"} $nlist]
564         nick_case $user
565         if {![llength $oc]} {
566             nick_forget $luser
567         } else {
568             check_justme $lchan
569         }
570     }
571 }
572
573 proc msg_TOPIC {p c dest topic} {
574     prefix_nick
575     if {![ischan $dest]} return
576     recordlastseen_n $n "changing the topic on $dest" 1
577     note_topic [irctolower $dest] $n $topic
578 }
579
580 proc msg_KICK {p c chans users comment} {
581     set chans [split $chans ,]
582     set users [split $users ,]
583     if {[llength $chans] > 1} {
584         foreach chan $chans user $users { process_kickpart $chan $user }
585     } else {
586         foreach user $users { process_kickpart [lindex $chans 0] $user }
587     }
588 }
589
590 proc msg_KILL {p c user why} {
591     nick_forget $user
592 }
593
594 set nick_counter 0
595 set nick_arys {onchans username unique}
596 # nick_onchans($luser) -> [list ... $lchan ...]
597 # nick_username($luser) -> <securely known local username>
598 # nick_unique($luser) -> <counter>
599 # nick_case($luser) -> $user  (valid even if no longer visible)
600 # nick_markid($luser) -> <after id for marktime>
601
602 # chan_nicks($lchan) -> [list ... $luser ...]
603 # chan_lastactivity($lchan) -> [clock seconds]
604
605 proc lnick_forget {luser} {
606     global nick_arys chan_nicks
607     lnick_marktime_cancel $luser
608     foreach ary $nick_arys {
609         upvar #0 nick_${ary}($luser) av
610         catch { unset av }
611     }
612     foreach lch [array names chan_nicks] {
613         upvar #0 chan_nicks($lch) nlist
614         set nlist [grep tn {"$tn" != "$luser"} $nlist]
615         check_justme $lch
616     }
617 }
618
619 proc nick_forget {user} {
620     global nick_arys chan_nicks
621     lnick_forget [irctolower $user]
622     nick_case $user
623 }
624
625 proc nick_case {user} {
626     global nick_case
627     set nick_case([irctolower $user]) $user
628 }
629
630 proc msg_NICK {p c newnick} {
631     global nick_arys nick_case
632     prefix_nick
633     recordlastseen_n $n "changing nicks to $newnick" 0
634     recordlastseen_n $newnick "changing nicks from $n" 1
635     set luser [irctolower $n]
636     lnick_marktime_cancel $luser
637     set lusernew [irctolower $newnick]
638     foreach ary $nick_arys {
639         upvar #0 nick_${ary}($luser) old
640         upvar #0 nick_${ary}($lusernew) new
641         if {[info exists new]} { error "nick collision ?! $ary $n $newnick" }
642         if {[info exists old]} { set new $old; unset old }
643     }
644     upvar #0 nick_onchans($lusernew) oc
645     foreach ch $oc {
646         upvar #0 chan_nicks($ch) nlist
647         set nlist [grep tn {"$tn" != "$luser"} $nlist]
648         lappend nlist $lusernew
649     }
650     lnick_marktime_start $lusernew "Hi." 500
651     nick_case $newnick
652 }
653
654 proc nick_ishere {n} {
655     global nick_counter
656     upvar #0 nick_unique([irctolower $n]) u
657     if {![info exists u]} { set u [incr nick_counter].$n.[clock seconds] }
658     nick_case $n
659 }
660
661 proc msg_JOIN {p c chan} {
662     prefix_nick
663     recordlastseen_n $n "joining $chan" 1
664     set nl [irctolower $n]
665     set lchan [irctolower $chan]
666     upvar #0 nick_onchans($nl) oc
667     upvar #0 chan_nicks($lchan) nlist
668     if {![info exists oc]} {
669         global marktime_join_startdelay
670         lnick_marktime_start $nl "Welcome." $marktime_join_startdelay
671     }
672     lappend oc $lchan
673     lappend nlist $nl
674     nick_ishere $n
675 }
676 proc msg_PART {p c chan} {
677     prefix_nick
678     recordlastseen_n $n "leaving $chan" 1
679     process_kickpart $chan $n
680 }
681 proc msg_QUIT {p c why} {
682     prefix_nick
683     recordlastseen_n $n "leaving ($why)" 0
684     nick_forget $n
685 }
686
687 proc msg_PRIVMSG {p c dest text} {
688     prefix_nick
689     if {[ischan $dest]} {
690         recordlastseen_n $n "invoking me in $dest" 1
691         set output $dest
692     } else {
693         recordlastseen_n $n "talking to me" 1
694         set output $n
695     }
696     nick_case $n
697
698     if {[catch {
699         regsub {^! *} $text {} text
700         set ucmd [ta_word]
701         set procname ucmd/[string tolower $ucmd]
702         if {[catch { info body $procname }]} {
703             error "unknown command; try help for help"
704         }
705         $procname $p $dest
706     } rv]} {
707         sendprivmsg $n "error: $rv"
708     } else {
709         manyset $rv priv_msgs pub_msgs priv_acts pub_acts
710         foreach {td val} [list $n $priv_acts $output $pub_acts] {
711             foreach l [split $val "\n"] {
712                 sendaction_priority 0 $td $l
713             }
714         }
715         foreach {td val} [list $n $priv_msgs $output $pub_msgs] {
716             foreach l [split $val "\n"] {
717                 sendprivmsg $td $l
718             }
719         }
720     }
721 }
722
723 proc msg_INVITE {p c n chan} {
724     after 1000 [list dojoin [irctolower $chan]]
725 }
726
727 proc grep {var predicate list} {
728     set o {}
729     upvar 1 $var v
730     foreach v $list {
731         if {[uplevel 1 [list expr $predicate]]} { lappend o $v }
732     }
733     return $o
734 }
735
736 proc msg_353 {p c dest type chan nicklist} {
737     global names_chans nick_onchans
738     set lchan [irctolower $chan]
739     upvar #0 chan_nicks($lchan) nlist
740     lappend names_chans $lchan
741     if {![info exists nlist]} {
742         # We don't think we're on this channel, so ignore it !
743         # Unfortunately, because we don't get a reply to PART,
744         # we have to remember ourselves whether we're on a channel,
745         # and ignore stuff if we're not, to avoid races.  Feh.
746         return
747     }
748     set nlist_new {}
749     foreach user [split $nicklist { }] {
750         regsub {^[@+]} $user {} user
751         if {![string length $user]} continue
752         check_nick $user
753         set luser [irctolower $user]
754         upvar #0 nick_onchans($luser) oc
755         lappend oc $lchan
756         lappend nlist_new $luser
757         nick_ishere $user
758     }
759     set nlist $nlist_new
760 }
761
762 proc msg_366 {p c args} {
763     global names_chans nick_onchans
764     set lchan [irctolower $c]
765     foreach luser [array names nick_onchans] {
766         upvar #0 nick_onchans($luser) oc
767         if {[llength names_chans] > 1} {
768             set oc [grep tc {[lsearch -exact $tc $names_chans] >= 0} $oc]
769         }
770         if {![llength $oc]} { lnick_forget $n }
771     }
772     unset names_chans
773 }
774
775 proc ta_anymore {} {
776     upvar 1 text text
777     return [expr {!![string length $text]}]
778 }
779
780 proc ta_nomore {} {
781     upvar 1 text text
782     if {[string length $text]} { error "too many parameters" }
783 }
784
785 proc ta_word {} {
786     upvar 1 text text
787     if {![regexp {^([^  ]+) *(.*)} $text dummy firstword text]} {
788         error "too few parameters"
789     }
790     return $firstword
791 }
792
793 proc ta_nick {} {
794     upvar 1 text text
795     set v [ta_word]
796     check_nick $v
797     return $v
798 }
799
800 proc def_ucmd {cmdname body} {
801     proc ucmd/$cmdname {p dest} "    upvar 1 text text\n$body"
802 }
803
804 proc ucmdr {priv pub args} {
805     return -code return [concat [list $priv $pub] $args]
806 }
807
808 proc loadhelp {} {
809     global help_topics errorInfo
810
811     catch { unset help_topics }
812     set f [open helpinfos r]
813     try_except_finally {
814         set lno 0
815         while {[gets $f l] >= 0} {
816             incr lno
817             if {[regexp {^#.*} $l]} {
818             } elseif {[regexp {^ *$} $l]} {
819                 if {[info exists topic]} {
820                     set help_topics($topic) [join $lines "\n"]
821                     unset topic
822                     unset lines
823                 }
824             } elseif {[regexp {^\:\:} $l]} {
825             } elseif {[regexp {^\:([-+._0-9a-z]*)$} $l dummy newtopic]} {
826                 if {[info exists topic]} {
827                     error "help $newtopic while in $topic"
828                 }
829                 set topic $newtopic
830                 set lines {}
831             } elseif {[regexp {^[^:#]} $l]} {
832                 set topic
833                 regsub -all {([^\\])\!\$?} _$l {\1} l
834                 regsub -all {\\(.)} $l {\1} l
835                 regsub {^_} $l {} l
836                 lappend lines [string trimright $l]
837             } else {
838                 error "eh ? $lno: $l"
839             }
840         }
841         if {[info exists topic]} { error "unfinished topic $topic" }
842     } {
843         set errorInfo "in helpinfos line $lno\n$errorInfo"
844     } {
845         close $f
846     }
847 }
848
849 def_ucmd help {
850     upvar 1 n n
851
852     set topic [irctolower [string trim $text]]
853     if {[string length $topic]} {
854         set ontopic " on `$topic'"
855     } else {
856         set ontopic ""
857     }
858     if {[set lag [out_lagged]]} {
859         if {[ischan $dest]} { set replyto $dest } else { set replyto $n }
860         if {$lag > 1} {
861             sendaction_priority 1 $replyto \
862                 "is very lagged.  Please ask for help$ontopic again later."
863             ucmdr {} {}
864         } else {
865             sendaction_priority 1 $replyto \
866                 "is lagged.  Your help$ontopic will arrive shortly ..."
867         }
868     }
869     
870     upvar #0 help_topics($topic) info
871     if {![info exists info]} { ucmdr "No help on $topic, sorry." {} }
872     ucmdr $info {}
873 }
874
875 def_ucmd ? {
876     global help_topics
877     ucmdr $help_topics() {}
878 }
879
880 proc check_username {target} {
881     if {
882         [string length $target] > 8 ||
883         [regexp {[^-0-9a-z]} $target] ||
884         ![regexp {^[a-z]} $target]
885     } { error "invalid username" }
886 }
887
888 proc somedb__head {} {
889     uplevel 1 {
890         set idl [irctolower $id]
891         upvar #0 ${nickchan}db($idl) ndbe
892         binary scan $idl H* idh
893         set idfn $fprefix$idh
894         if {![info exists iddbe] && [file exists $idfn]} {
895             set f [open $idfn r]
896             try_except_finally { set newval [read $f] } {} { close $f }
897             if {[llength $newval] % 2} { error "invalid length" }
898             set iddbe $newval
899         }
900     }
901 }
902
903 proc def_somedb {name arglist body} {
904     foreach {nickchan fprefix} {nick users/n chan chans/c} {
905         proc ${nickchan}db_$name $arglist \
906             "set nickchan $nickchan; set fprefix $fprefix; $body"
907     }
908 }
909
910 def_somedb list {} {
911     set list {}
912     foreach path [glob -nocomplain -path $fprefix *] {
913         binary scan $path "A[string length $fprefix]A*" afprefix thinghex
914         if {"$afprefix" != "$fprefix"} { error "wrong prefix $path $afprefix" }
915         lappend list [binary format H* $thinghex]
916     }
917     return $list
918 }
919
920 proc def_somedb_id {name arglist body} {
921     def_somedb $name [concat id $arglist] "somedb__head; $body"
922 }
923
924 def_somedb_id exists {} {
925     return [info exists iddbe]
926 }
927
928 def_somedb_id delete {} {
929     catch { unset iddbe }
930     file delete $idfn
931 }
932
933 set default_settings_nick {timeformat ks  marktime off}
934 set default_settings_chan {
935     autojoin 1
936     mode *
937     userinvite pub
938     topicset {}
939     topicsee {}
940     topictell {}
941 }
942
943 def_somedb_id set {args} {
944     upvar #0 default_settings_$nickchan def
945     if {![info exists iddbe]} { set iddbe $def }
946     foreach {key value} [concat $iddbe $args] { set a($key) $value }
947     set newval {}
948     foreach {key value} [array get a] { lappend newval $key $value }
949     set f [open $idfn.new w]
950     try_except_finally {
951         puts $f $newval
952         close $f
953         file rename -force $idfn.new $idfn
954     } {
955     } {
956         catch { close $f }
957     }
958     set iddbe $newval
959 }
960
961 def_somedb_id get {key} {
962     upvar #0 default_settings_$nickchan def
963     if {[info exists iddbe]} {
964         set l [concat $iddbe $def]
965     } else {
966         set l $def
967     }
968     foreach {tkey value} $l {
969         if {"$tkey" == "$key"} { return $value }
970     }
971     error "unset setting $key"
972 }
973
974 proc opt {key} {
975     global calling_nick
976     if {[info exists calling_nick]} { set n $calling_nick } { set n {} }
977     return [nickdb_get $n $key]
978 }
979
980 proc check_notonchan {} {
981     upvar 1 dest dest
982     if {[ischan $dest]} { error "that command must be sent privately" }
983 }
984
985 proc nick_securitycheck {strict} {
986     upvar 1 n n
987     if {![nickdb_exists $n]} { error "you are unknown to me, use `register'." }
988     set wantu [nickdb_get $n username]
989     if {![string length $wantu]} {
990         if {$strict} {
991             error "that feature is only available to secure users, sorry."
992         } else {
993             return
994         }
995     }
996     set luser [irctolower $n]
997     upvar #0 nick_username($luser) nu
998     if {![info exists nu]} {
999         error "nick $n is secure, you must identify yourself first."
1000     }
1001     if {"$wantu" != "$nu"} {
1002         error "you are the wrong user - the nick $n belongs to $wantu, not $nu"
1003     }
1004 }
1005
1006 proc channel_securitycheck {channel n} {
1007     # You must also call `nick_securitycheck 1'
1008     set mgrs [chandb_get $channel managers]
1009     if {[lsearch -exact [irctolower $mgrs] [irctolower $n]] < 0} {
1010         error "you are not a manager of $channel"
1011     }
1012 }
1013
1014 proc def_chancmd {name body} {
1015     proc channel/$name {} \
1016             "    upvar 1 target chan; upvar 1 n n; upvar 1 text text; $body"
1017 }
1018
1019 proc ta_listop {findnow procvalue} {
1020     # findnow and procvalue are code fragments which will be executed
1021     # in the caller's level.  findnow should set ta_listop_ev to
1022     # the current list, and procvalue should treat ta_listop_ev as
1023     # a proposed value in the list and check and possibly modify
1024     # (canonicalise?) it.  After ta_listop, ta_listop_ev will
1025     # be the new value of the list.
1026     upvar 1 ta_listop_ev exchg
1027     upvar 1 text text
1028     set opcode [ta_word]
1029     switch -exact _$opcode {
1030         _= { }
1031         _+ - _- {
1032             uplevel 1 $findnow
1033             foreach item $exchg { set array($item) 1 }
1034         }
1035         default {
1036             error "list change opcode must be one of + - ="
1037         }
1038     }
1039     foreach exchg [split $text " "] {
1040         if {![string length $exchg]} continue
1041         uplevel 1 $procvalue
1042         if {"$opcode" != "-"} {
1043             set array($exchg) 1
1044         } else {
1045             catch { unset array($exchg) }
1046         }
1047     }
1048     set exchg [lsort [array names array]]
1049 }
1050
1051 def_chancmd manager {
1052     ta_listop {
1053         if {[chandb_exists $chan]} {
1054             set ta_listop_ev [chandb_get $chan managers]
1055         } else {
1056             set ta_listop_ev [list [irctolower $n]]
1057         }
1058     } {
1059         check_nick $ta_listop_ev
1060         set ta_listop_ev [irctolower $ta_listop_ev]
1061     }
1062     if {[llength $ta_listop_ev]} {
1063         chandb_set $chan managers $ta_listop_ev
1064         ucmdr "Managers of $chan: $ta_listop_ev" {}
1065     } else {
1066         chandb_delete $chan
1067         ucmdr {} {} "forgets about managing $chan." {}
1068     }
1069 }
1070
1071 def_chancmd autojoin {
1072     set yesno [ta_word]
1073     switch -exact [string tolower $yesno] {
1074         no { set nv 0 }
1075         yes { set nv 1 }
1076         default { error "channel autojoin must be `yes' or `no' }
1077     }
1078     chandb_set $chan autojoin $nv
1079     ucmdr [expr {$nv ? "I will join $chan when I'm restarted " : \
1080             "I won't join $chan when I'm restarted "}] {}
1081 }
1082
1083 def_chancmd userinvite {
1084     set nv [string tolower [ta_word]]
1085     switch -exact $nv {
1086         pub { set txt "!invite will work for $chan, but it won't work by /msg" }
1087         here { set txt "!invite and /msg invite will work, but only for users who are already on $chan." }
1088         all { set txt "Any user will be able to invite themselves or anyone else to $chan." }
1089         none { set txt "I will not invite anyone to $chan." }
1090         default {
1091             error "channel userinvite must be `pub', `here', `all' or `none'
1092         }
1093     }
1094     chandb_set $chan userinvite $nv
1095     ucmdr $txt {}
1096 }
1097
1098 def_chancmd topic {
1099     set what [ta_word]
1100     switch -exact $what {
1101         leave {
1102             ta_nomore
1103             chandb_set $chan topicset {}
1104             ucmdr "I won't ever change the topic of $chan." {}
1105         }
1106         set {
1107             set t [string trim $text]
1108             if {![string length $t]} {
1109                 error "you must specific the topic to set"
1110             }
1111             chandb_set $chan topicset $t
1112             ucmdr "Whenever I'm alone on $chan, I'll set the topic to $t." {}
1113         }
1114         see - tell {
1115             ta_listop {
1116                 set ta_listop_ev [chandb_get $chan topic$what]
1117             } {
1118                 if {"$ta_listop_ev" != "*"} {
1119                     if {![ischan $ta_listop_ev]} {
1120                         error "bad channel \`$ta_listop_ev' in topic $what"
1121                     }
1122                     set ta_listop_ev [irctolower $ta_listop_ev]
1123                 }
1124             }
1125             chandb_set $chan topic$what $ta_listop_ev
1126             ucmdr "Topic $what list for $chan: $ta_listop_ev" {}
1127         }
1128         default {
1129             error "unknown channel topic subcommand - see help channel"
1130         }
1131     }
1132 }
1133
1134 def_chancmd mode {
1135     set mode [ta_word]
1136     if {"$mode" != "*" && ![regexp {^(([-+][imnpst]+)+)$} $mode mode]} {
1137         error {channel mode must be * or match ([-+][imnpst]+)+}
1138     }
1139     chandb_set $chan mode $mode
1140     if {"$mode" == "*"} {
1141         ucmdr "I won't ever change the mode of $chan." {}
1142     } else {
1143         ucmdr "Whenever I'm alone on $chan, I'll set the mode to $mode." {}
1144     }
1145 }
1146
1147 def_chancmd show {
1148     if {[chandb_exists $chan]} {
1149         set l "Settings for $chan: autojoin "
1150         append l [lindex {no yes} [chandb_get $chan autojoin]]
1151         append l ", mode " [chandb_get $chan mode]
1152         append l ", userinvite " [chandb_get $chan userinvite] "."
1153         append l "\nManagers: "
1154         append l [join [chandb_get $chan managers] " "]
1155         foreach {ts sep} {see "\n" tell "  "} {
1156             set t [chandb_get $chan topic$ts]
1157             append l $sep
1158             if {[llength $t]} {
1159                 append l "Topic $ts list: $t."
1160             } else {
1161                 append l "Topic $ts list is empty."
1162             }
1163         }
1164         append l "\n"
1165         set t [chandb_get $chan topicset]
1166         if {[string length $t]} {
1167             append l "Topic to set: $t"
1168         } else {
1169             append l "I will not change the topic."
1170         }
1171         ucmdr {} $l
1172     } else {
1173         ucmdr {} "The channel $chan is not managed."
1174     }
1175 }
1176
1177 proc channelmgr_monoop {} {
1178     upvar 1 dest dest
1179     upvar 1 text text
1180     upvar 1 n n
1181     upvar 1 p p
1182     upvar 1 target target
1183     global chan_nicks
1184
1185     prefix_nick
1186
1187     if {[ischan $dest]} { set target $dest }
1188     if {[ta_anymore]} { set target [ta_word] }
1189     ta_nomore
1190     if {![info exists target]} {
1191         error "you must specify, or invoke me on, the relevant channel"
1192     }
1193     if {![info exists chan_nicks([irctolower $target])]} {
1194         error "I am not on $target."
1195     }
1196     if {![ischan $target]} { error "not a valid channel" }
1197
1198     if {![chandb_exists $target]} { error "$target is not a managed channel." }
1199     nick_securitycheck 1
1200     channel_securitycheck $target $n
1201 }
1202
1203 def_ucmd op {
1204     channelmgr_monoop
1205     sendout MODE $target +o $n
1206 }
1207
1208 def_ucmd leave {
1209     channelmgr_monoop
1210     doleave $target
1211 }
1212
1213 def_ucmd invite {
1214     global chan_nicks
1215     
1216     if {[ischan $dest]} {
1217         set target $dest
1218         set onchan 1
1219     } else {
1220         set target [ta_word]
1221         set onchan 0
1222     }
1223     set ltarget [irctolower $target]
1224     if {![ischan $target]} { error "$target is not a channel." }
1225     if {![info exists chan_nicks($ltarget)]} { error "I am not on $target." }
1226     set ui [chandb_get $ltarget userinvite]
1227     if {"$ui" == "pub" && !$onchan} {
1228         error "Invitations to $target must be made with !invite."
1229     }
1230     if {"$ui" != "all"} {
1231         prefix_nick
1232         if {[lsearch -exact $chan_nicks($ltarget) [irctolower $n]] < 0} {
1233  error "Invitations to $target may only be made by a user on the channel."
1234         }
1235     }
1236     if {"$ui" == "none"} {
1237         error "Sorry, I've not been authorised to invite people to $target."
1238     }
1239     if {![ta_anymore]} {
1240         error "You have to say who to invite."
1241     }
1242     set invitees {}
1243     while {[ta_anymore]} {
1244         set invitee [ta_word]
1245         check_nick $invitee
1246         lappend invitees $invitee
1247     }
1248     foreach invitee $invitees {
1249         sendout INVITE $invitee $ltarget
1250     }
1251     set who [lindex $invitees 0]
1252     switch -exact llength $invitees {
1253         0 { error "zero invitees" }
1254         1 { }
1255         2 { append who " and [lindex $invitees 1]" }
1256         * {
1257             set who [join [lreplace $invitees end end] ", "]
1258             append who " and [lindex $invitees [llength $invitees]]"
1259         }
1260     }
1261     ucmdr {} "invites $who to $target."
1262 }
1263
1264 def_ucmd channel {
1265     if {[ischan $dest]} { set target $dest }
1266     if {![ta_anymore]} {
1267         set subcmd show
1268     } else {
1269         set subcmd [ta_word]
1270     }
1271     if {[ischan $subcmd]} {
1272         set target $subcmd
1273         if {![ta_anymore]} {
1274             set subcmd show
1275         } else {
1276             set subcmd [ta_word]
1277         }
1278     }
1279     if {![info exists target]} { error "privately, you must specify a channel" }
1280     set procname channel/$subcmd
1281     if {"$subcmd" != "show"} {
1282         if {[catch { info body $procname }]} { error "unknown channel setting $subcmd" }
1283         prefix_nick
1284         nick_securitycheck 1
1285         if {[chandb_exists $target]} {
1286             channel_securitycheck $target $n
1287         } else {
1288             upvar #0 chan_initialop([irctolower $target]) io
1289             upvar #0 nick_unique([irctolower $n]) u
1290             if {![info exists io]} { error "$target is not a managed channel" }
1291             if {"$io" != "$u"} { error "you are not the interim manager of $target" }
1292             if {"$subcmd" != "manager"} { error "use `channel manager' first" }
1293         }
1294     }
1295     channel/$subcmd
1296 }
1297
1298 def_ucmd who {
1299     if {[ta_anymore]} {
1300         set target [ta_word]; ta_nomore
1301         set myself 1
1302     } else {
1303         prefix_nick
1304         set target $n
1305         set myself [expr {"$target" != "$n"}]
1306     }
1307     set ltarget [irctolower $target]
1308     upvar #0 nick_case($ltarget) ctarget
1309     set nshow $target
1310     if {[info exists ctarget]} {
1311         upvar #0 nick_onchans($ltarget) oc
1312         upvar #0 nick_username($ltarget) nu
1313         if {[info exists oc]} { set nshow $ctarget }
1314     }
1315     if {![nickdb_exists $ltarget]} {
1316         set ol "$nshow is not a registered nick."
1317     } elseif {[string length [set username [nickdb_get $target username]]]} {
1318         set ol "The nick $nshow belongs to the user $username."
1319     } else {
1320         set ol "The nick $nshow is registered (but not to a username)."
1321     }
1322     if {![info exists ctarget] || ![info exists oc]} {
1323         if {$myself} {
1324             append ol "\nI can't see $nshow on anywhere."
1325         } else {
1326             append ol "\nYou aren't on any channels with me."
1327         }
1328     } elseif {![info exists nu]} {
1329         append ol "\n$nshow has not identified themselves."
1330     } elseif {![info exists username]} {
1331         append ol "\n$nshow has identified themselves as the user $nu."
1332     } elseif {"$nu" != "$username"} {
1333         append ol "\nHowever, $nshow is being used by the user $nu."
1334     } else {
1335         append ol "\n$nshow has identified themselves to me."
1336     }
1337     ucmdr {} $ol
1338 }
1339
1340 def_ucmd register {
1341     prefix_nick
1342     check_notonchan
1343     set old [nickdb_exists $n]
1344     if {$old} { nick_securitycheck 0 }
1345     set luser [irctolower $n]
1346     switch -exact [string tolower [string trim $text]] {
1347         {} {
1348             upvar #0 nick_username($luser) nu
1349             if {![info exists nu]} {
1350                 ucmdr {} \
1351  "You must identify yourself before using `register'.  See `help identify', or use `register insecure'."
1352             }
1353             nickdb_set $n username $nu
1354             ucmdr {} {} "makes a note of your username." {}
1355         }
1356         delete {
1357             nickdb_delete $n
1358             ucmdr {} {} "forgets your nickname." {}
1359         }
1360         insecure {
1361             nickdb_set $n username {}
1362             if {$old} {
1363                 ucmdr {} "Security is now disabled for your nickname !"
1364             } else {
1365                 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."
1366             }
1367         }
1368     }
1369 }
1370
1371 proc timeformat_desc {tf} {
1372     switch -exact $tf {
1373         ks { return "Times will be displayed in seconds or kiloseconds." }
1374         hms { return "Times will be displayed in hours, minutes, etc." }
1375         default { error "invalid timeformat: $v" }
1376     }
1377 }
1378
1379 proc def_setting {opt show_body set_body} {
1380     proc set_show/$opt {} "
1381         upvar 1 n n
1382         set opt $opt
1383         $show_body"
1384     if {![string length $set_body]} return
1385     proc set_set/$opt {} "
1386         upvar 1 n n
1387         upvar 1 text text
1388         set opt $opt
1389         $set_body"
1390 }
1391
1392 def_setting timeformat {
1393     set tf [nickdb_get $n timeformat]
1394     return "$tf: [timeformat_desc $tf]"
1395 } {
1396     set tf [string tolower [ta_word]]
1397     ta_nomore
1398     set desc [timeformat_desc $tf]
1399     nickdb_set $n timeformat $tf
1400     ucmdr {} $desc
1401 }
1402
1403 proc marktime_desc {mt} {
1404     if {"$mt" == "off"} {
1405         return "I will not send you periodic messages."
1406     } elseif {"$mt" == "once"} {
1407         return "I will send you one informational message when I see you."
1408     } else {
1409         return "I'll send you a message every [showintervalsecs $mt]."
1410     }
1411 }
1412
1413 def_setting marktime {
1414     set mt [nickdb_get $n marktime]
1415     set p $mt
1416     if {[string match $mt {[0-9]*}} { append p s }
1417     append p ": "
1418     append p [marktime_desc $mt]
1419     return $p
1420 } {
1421     global marktime_min
1422     set mt [string tolower [ta_word]]
1423     ta_nomore
1424
1425     if {"$mt" == "off" || "$mt" == "once"} {
1426     } elseif {[regexp {^([0-9]+)([a-z]+)$} $mt dummy value unit]} {
1427         switch -exact $unit {
1428             s { set u 1 }
1429             ks { set u 1000 }
1430             m { set u 60 }
1431             h { set u 3600 }
1432             default { error "unknown unit of time $unit" }
1433         }
1434         if {$value > 86400*21/$u} { error "marktime interval too large" }
1435         set mt [expr {$value*$u}]
1436         if {$mt < $marktime_min} { error "marktime interval too small" }
1437     } else {
1438         error "invalid syntax for marktime"
1439     }
1440     nickdb_set $n marktime $mt
1441     lnick_marktime_start [irctolower $n] "So:" 500
1442     ucmdr {} [marktime_desc $mt]
1443 }
1444
1445 def_setting security {
1446     set s [nickdb_get $n username]
1447     if {[string length $s]} {
1448         return "Your nick, $n, is controlled by the user $s."
1449     } else {
1450         return "Your nick, $n, is not secure."
1451     }
1452 } {}
1453
1454 def_ucmd set {
1455     prefix_nick
1456     check_notonchan
1457     if {![nickdb_exists $n]} {
1458         ucmdr {} "You are unknown to me and so have no settings.  (Use `register'.)"
1459     }
1460     if {![ta_anymore]} {
1461         set ol {}
1462         foreach proc [lsort [info procs]] {
1463             if {![regexp {^set_show/(.*)$} $proc dummy opt]} continue
1464             lappend ol [format "%-10s %s" $opt [set_show/$opt]]
1465         }
1466         ucmdr {} [join $ol "\n"]
1467     } else {
1468         set opt [ta_word]
1469         if {[catch { info body set_show/$opt }]} {
1470             error "no setting $opt"
1471         }
1472         if {![ta_anymore]} {
1473             ucmdr {} "$opt [set_show/$opt]"
1474         } else {
1475             nick_securitycheck 0
1476             if {[catch { info body set_set/$opt }]} {
1477                 error "setting $opt cannot be set with `set'"
1478             }
1479             set_set/$opt
1480         }
1481     }
1482 }
1483
1484 def_ucmd identpass {
1485     set username [ta_word]
1486     set passmd5 [md5sum "[ta_word]\n"]
1487     ta_nomore
1488     prefix_nick
1489     check_notonchan
1490     set luser [irctolower $n]
1491     upvar #0 nick_onchans($luser) onchans
1492     if {![info exists onchans] || ![llength $onchans]} {
1493         ucmdr "You must be on a channel with me to identify yourself." {}
1494     }
1495     check_username $username
1496     exec userv --timeout 3 $username << "$passmd5\n" > /dev/null \
1497             irc-identpass $n
1498     upvar #0 nick_username($luser) rec_username
1499     set rec_username $username
1500     ucmdr "Pleased to see you, $username." {}
1501 }
1502
1503 def_ucmd summon {
1504     set target [ta_word]
1505     ta_nomore
1506     check_username $target
1507     prefix_nick
1508
1509     upvar #0 lastsummon($target) ls
1510     set now [clock seconds]
1511     if {[info exists ls]} {
1512         set interval [expr {$now - $ls}]
1513         if {$interval < 30} {
1514             ucmdr {} \
1515  "Please be patient; $target was summoned only [showinterval $interval]."
1516         }
1517     }
1518     regsub {^[^!]*!} $p {} path
1519     if {[catch {
1520         exec userv --timeout 3 $target irc-summon $n $path \
1521                 [expr {[ischan $dest] ? "$dest" : ""}] \
1522                 < /dev/null
1523     } rv]} {
1524         regsub -all "\n" $rv { / } rv
1525         error $rv
1526     }
1527     if {[regexp {^problem (.*)} $rv dummy problem]} {
1528         ucmdr {} "The user `$target' $problem."
1529     } elseif {[regexp {^ok ([^ ]+) ([0-9]+)$} $rv dummy tty idlesince]} {
1530         set idletime [expr {$now - $idlesince}]
1531         set ls $now
1532         ucmdr {} {} {} "invites $target ($tty[expr {
1533             $idletime > 10 ? ", idle for [showintervalsecs $idletime]" : ""
1534         }]) to [expr {
1535             [ischan $dest] ? "join us here" : "talk to you"
1536         }]."
1537     } else {
1538         error "unexpected response from userv service: $rv"
1539     }
1540 }
1541
1542 proc md5sum {value} { exec md5sum << $value }
1543
1544 def_ucmd seen {
1545     global lastseen nick
1546     prefix_nick
1547     set ncase [ta_nick]
1548     set nlower [irctolower $ncase]
1549     ta_nomore
1550     set now [clock seconds]
1551     if {"$nlower" == "[irctolower $nick]"} {
1552         error "I am not self-aware."
1553     } elseif {![info exists lastseen($nlower)]} {
1554         set rstr "I've never seen $ncase."
1555     } else {
1556         manyset $lastseen($nlower) realnick time what
1557         set howlong [expr {$now - $time}]
1558         set string [showinterval $howlong]
1559         set rstr "I last saw $realnick $string, $what."
1560     }
1561     if {[ischan $dest]} {
1562         set where $dest
1563     } else {
1564         set where {}
1565     }
1566     upvar #0 lookedfor($nlower) lf
1567     if {[info exists lf]} { set oldvalue $lf } else { set oldvalue {} }
1568     set lf [list [list $now $n $where]]
1569     foreach v $oldvalue {
1570         if {"[irctolower [lindex $v 1]]" == "[irctolower $n]"} continue
1571         lappend lf $v
1572     }
1573     ucmdr {} $rstr
1574 }
1575
1576 proc lnick_marktime_cancel {luser} {
1577     upvar #0 nick_markid($luser) mi
1578     if {![info exists mi]} return
1579     catch { after cancel $mi }
1580     catch { unset mi }
1581 }
1582
1583 proc lnick_marktime_doafter {luser why ms} {
1584     lnick_marktime_cancel $luser
1585     upvar #0 nick_markid($luser) mi
1586     set mi [after $ms [list lnick_marktime_now $luser $why]]
1587 }
1588
1589 proc lnick_marktime_reset {luser} {
1590     set mt [nickdb_get $luser marktime]
1591     if {"$mt" == "off" || "$mt" == "once"} return
1592     lnick_marktime_doafter $luser "Time passes." [expr {$mt*1000}]
1593 }
1594
1595 proc lnick_marktime_start {luser why ms} {
1596     set mt [nickdb_get $luser marktime]
1597     if {"$mt" == "off"} {
1598         lnick_marktime_cancel $luser
1599     } else {
1600         lnick_marktime_doafter $luser $why $ms
1601     }
1602 }
1603
1604 proc lnick_marktime_now {luser why} {
1605     upvar #0 nick_onchans($luser) oc
1606     sendprivmsg $luser [lnick_pingstring $why $oc ""]
1607     lnick_marktime_reset $luser
1608 }    
1609
1610 proc lnick_pingstring {why oc apstring} {
1611     global nick_onchans
1612     catch { exec uptime } uptime
1613     set nnicks [llength [array names nick_onchans]]
1614     if {[regexp \
1615  {^ *([0-9:apm]+) +up.*, +(\d+) users, +load average: +([0-9., ]+) *$} \
1616             $uptime dummy time users load]} {
1617         regsub , $load {} load
1618         set uptime "$time  $nnicks/$users  $load"
1619     } else {
1620         append uptime ", $nnicks nicks"
1621     }
1622     if {[llength $oc]} {
1623         set best_la 0
1624         set activity quiet
1625         foreach ch $oc {
1626             upvar #0 chan_lastactivity($ch) la
1627             if {![info exists la]} continue
1628             if {$la <= $best_la} continue
1629             set activity "$ch [showintervalsecs [expr {[clock seconds]-$la}]]"
1630             set best_la $la
1631         }
1632     } else {
1633         set activity unseen
1634     }
1635     set str $why
1636     append str "  " $uptime "  " $activity
1637     if {[string length $apstring]} { append str "  " $apstring }
1638     return $str
1639 }
1640
1641 def_ucmd ping {
1642     if {[ischan $dest]} {
1643         set oc [irctolower $dest]
1644     } else {
1645         global nick_onchans
1646         prefix_nick
1647         set ln [irctolower $n]
1648         if {[info exists nick_onchans($ln)]} {
1649             set oc $nick_onchans($ln)
1650         } else {
1651             set oc {}
1652         }
1653         if {[llength $oc]} { lnick_marktime_reset $ln }
1654     }
1655     ucmdr {} [lnick_pingstring "Pong!" $oc $text]
1656 }
1657
1658 proc ensure_globalsecret {} {
1659     global globalsecret
1660     
1661     if {[info exists globalsecret]} return
1662     set gsfile [open /dev/urandom r]
1663     fconfigure $gsfile -translation binary
1664     set globalsecret [read $gsfile 32]
1665     binary scan $globalsecret H* globalsecret
1666     close $gsfile
1667     unset gsfile
1668 }
1669
1670 proc ensure_outqueue {} {
1671     out__vars
1672     if {[info exists out_queue]} return
1673     set out_creditms 0
1674     set out_creditat [clock seconds]
1675     set out_queue {}
1676     set out_lag_reported 0
1677     set out_lag_reportwhen $out_creditat
1678 }
1679
1680 proc fail {msg} {
1681     logerror "failing: $msg"
1682     exit 1
1683 }
1684
1685 proc ensure_connecting {} {
1686     global sock ownfullname host port nick socketargs
1687     global musthaveping_ms musthaveping_after
1688     
1689     if {[info exists sock]} return
1690     set sock [eval socket $socketargs [list $host $port]]
1691     fconfigure $sock -buffering line
1692     fconfigure $sock -translation crlf
1693
1694     sendout USER blight 0 * $ownfullname
1695     sendout NICK $nick
1696     fileevent $sock readable onread
1697
1698     set musthaveping_after [after $musthaveping_ms \
1699             {fail "no ping within timeout"}]
1700 }
1701
1702 proc connected {} {
1703     global musthaveping_after
1704
1705     after cancel $musthaveping_after
1706     unset musthaveping_after
1707
1708     foreach chan [chandb_list] {
1709         if {[chandb_get $chan autojoin]} { dojoin $chan }
1710     }
1711 }
1712
1713 ensure_globalsecret
1714 ensure_outqueue
1715 loadhelp
1716 ensure_connecting