chiark / gitweb /
Dies if doesn't get a ping. Configs separated.
[ircbot] / bot.tcl
1 # Core bot code
2
3 proc defset {varname val} {
4     upvar #0 $varname var
5     if {![info exists var]} { set var $val }
6 }
7
8 # must set host
9 defset port 6667
10
11 defset nick testbot
12 defset ownfullname "testing bot"
13 defset ownmailaddr test-irc-bot@example.com
14
15 defset musthaveping_ms 10000
16 defset out_maxburst 6
17 defset out_interval 2100
18 defset out_lag_lag 5000
19 defset out_lag_very 25000
20
21 proc manyset {list args} {
22     foreach val $list var $args {
23         upvar 1 $var my
24         set my $val
25     }
26 }
27
28 proc try_except_finally {try except finally} {
29     global errorInfo errorCode
30     set er [catch { uplevel 1 $try } emsg]
31     if {$er} {
32         set ei $errorInfo
33         set ec $errorCode
34         if {[catch { uplevel 1 $except } emsg3]} {
35             append ei "\nALSO ERROR HANDLING ERROR:\n$emsg3"
36         }
37     }
38     set er2 [catch { uplevel 1 $finally } emsg2]
39     if {$er} {
40         if {$er2} {
41             append ei "\nALSO ERROR CLEANING UP:\n$emsg2"
42         }
43         return -code $er -errorinfo $ei -errorcode $ec $emsg
44     } elseif {$er2} {
45         return -code $er2 -errorinfo $errorInfo -errorcode $errorCode $emsg2
46     } else {
47         return $emsg
48     }
49 }
50
51 proc out__vars {} {
52     uplevel 1 {
53         global out_queue out_creditms out_creditat out_interval out_maxburst
54         global out_lag_lag out_lag_very
55 #set pr [lindex [info level 0] 0]
56 #puts $pr>[clock seconds]|$out_creditat|$out_creditms|[llength $out_queue]<
57     }
58 }
59
60 proc out_lagged {} {
61     out__vars
62     if {[llength $out_queue]*$out_interval > $out_lag_very} {
63         return 2
64     } elseif {[llength $out_queue]*$out_interval > $out_lag_lag} {
65         return 1
66     } else {
67         return 0
68     }
69 }
70
71 proc out_restart {} {
72     out__vars
73     
74     set now [clock seconds]
75     incr out_creditms [expr {($now - $out_creditat) * 1000}]
76     set out_creditat $now
77     if {$out_creditms > $out_maxburst*$out_interval} {
78         set out_creditms [expr {$out_maxburst*$out_interval}]
79     }
80     out_runqueue $now
81 }
82
83 proc out_runqueue {now} {
84     global sock
85     out__vars
86     
87     while {[llength $out_queue] && $out_creditms >= $out_interval} {
88 #puts rq>$now|$out_creditat|$out_creditms|[llength $out_queue]<
89         manyset [lindex $out_queue 0] orgwhen msg
90         set out_queue [lrange $out_queue 1 end]
91         if {[llength $out_queue]} {
92             append orgwhen "+[expr {$now - $orgwhen}]"
93             append orgwhen ([llength $out_queue])"
94         }
95         puts "$orgwhen -> $msg"
96         puts $sock $msg
97         incr out_creditms -$out_interval
98     }
99     if {[llength $out_queue]} {
100         after $out_interval out_nextmessage
101     }
102 }
103
104 proc out_nextmessage {} {
105     out__vars
106     set now [clock seconds]
107     incr out_creditms $out_interval
108     set out_creditat $now
109     out_runqueue $now
110 }
111
112 proc sendout_priority {priority command args} {
113     global sock out_queue
114     if {[llength $args]} {
115         set la [lindex $args end]
116         set args [lreplace $args end end]
117         foreach i $args {
118             if {[regexp {[: ]} $i]} {
119                 error "bad argument in output $i ($command $args)"
120             }
121         }
122         lappend args :$la
123     }
124     set args [lreplace $args 0 -1 $command]
125     set string [join $args { }]
126     set now [clock seconds]
127     set newe [list $now $string]
128     if {$priority} {
129         set out_queue [concat [list $newe] $out_queue]
130     } else {
131         lappend out_queue $newe
132     }
133     if {[llength $out_queue] == 1} {
134         out_restart
135     }
136 }
137
138 proc sendout {command args} { eval sendout_priority [list 0 $command] $args }
139     
140 proc log {data} {
141     puts $data
142 }
143
144 proc logerror {data} {
145     log $data
146 }
147
148 proc saveeic {} {
149     global saveei saveec errorInfo errorCode
150
151     set saveei $errorInfo
152     set saveec $errorCode
153
154     puts ">$saveec|$saveei<"
155 }
156
157 proc bgerror {msg} {
158     global save
159     logerror $msg
160     saveeic
161 }
162
163 proc onread {args} {
164     global sock nick calling_nick errorInfo errorCode
165     
166     if {[gets $sock line] == -1} { fail "EOF/error on input" }
167     regsub -all "\[^ -\176\240-\376\]" $line ? line
168     set org $line
169     
170     set ei $errorInfo
171     set ec $errorCode
172     catch { unset calling_nick }
173     set errorInfo $ei
174     set errorCode $ec
175     
176     if {[regexp -nocase {^:([^ ]+) (.*)} $line dummy prefix remain]} {
177         set line $remain
178         if {[regexp {^([^!]+)!} $prefix dummy maybenick]} {
179             set calling_nick $maybenick
180             if {"[irctolower $maybenick]" == "[irctolower $nick]"} return
181         }
182     } else {
183         set prefix {}
184     }
185     if {![string length $line]} { return }
186     if {![regexp -nocase {^([0-9a-z]+) *(.*)} $line dummy command line]} {
187         log "bad command: $org"
188         return
189     }
190     set command [string toupper $command]
191     set params {}
192     while {[regexp {^([^ :]+) *(.*)} $line dummy thisword line]} {
193         lappend params $thisword
194     }
195     if {[regexp {^:(.*)} $line dummy thisword]} {
196         lappend params $thisword
197     } elseif {[string length $line]} {
198         log "junk at end: $org"
199         return
200     }
201     if {"$command" == "PRIVMSG" &&
202         [regexp {^[&#+!]} [lindex $params 0]] &&
203         ![regexp {^!} [lindex $params 1]]} {
204         # on-channel message, ignore
205         catch {
206             recordlastseen_p $prefix "talking on [lindex $params 0]" 1
207         }
208         return
209     }
210     log "[clock seconds] <- $org"
211     set procname msg_$command
212     if {[catch { info body $procname }]} { return }
213     if {[catch {
214         eval [list $procname $prefix $command] $params
215     } emsg]} {
216         logerror "error: $emsg ($prefix $command $params)"
217         saveeic
218     }
219 }
220
221 proc sendprivmsg {dest l} {
222     foreach v [split $l "\n"] {
223         sendout [expr {[ischan $dest] ? "PRIVMSG" : "NOTICE"}] $dest $v
224     }
225 }
226 proc sendaction_priority {priority dest what} {
227     sendout_priority $priority PRIVMSG $dest "\001ACTION $what\001"
228 }
229 proc msendprivmsg {dest ll} { foreach l $ll { sendprivmsg $dest $l } }
230 proc msendprivmsg_delayed {delay dest ll} { after $delay [list msendprivmsg $dest $ll] }
231
232 proc prefix_none {} {
233     upvar 1 p p
234     if {[string length $p]} { error "prefix specified" }
235 }
236
237 proc msg_PING {p c s1} {
238     global musthaveping_after
239     prefix_none
240     sendout PONG $s1
241     if {[info exists musthaveping_after]} {
242         after cancel $musthaveping_after
243         unset musthaveping_after
244     }
245 }
246
247 proc check_nick {n} {
248     if {[regexp -nocase {[^][\\`_^{|}a-z0-9-]} $n]} { error "bad char in nick" }
249     if {[regexp {^[-0-9]} $n]} { error "bad nick start" }
250 }
251
252 proc ischan {dest} {
253     return [regexp {^[&#+!]} $dest]
254 }
255
256 proc irctolower {v} {
257     foreach {from to} [list "\\\[" "{" \
258                           "\\\]" "}" \
259                           "\\\\" "|" \
260                           "~"    "^"] {
261         regsub -all $from $v $to v
262     }
263     return [string tolower $v]
264 }
265
266 proc prefix_nick {} {
267     global nick
268     upvar 1 p p
269     upvar 1 n n
270     if {![regexp {^([^!]+)!} $p dummy n]} { error "not from nick" }
271     check_nick $n
272     if {"[irctolower $n]" == "[irctolower $nick]"} {
273         error "from myself" {} {}
274     }
275 }
276
277 proc showintervalsecs {howlong} {
278     return [showintervalsecs/[opt timeformat] $howlong]
279 }
280
281 proc showintervalsecs/ks {howlong} {
282     if {$howlong < 1000} {
283         return "${howlong}s"
284     } else {
285         if {$howlong < 1000000} {
286             set pfx k
287             set scale 1000
288         } else {
289             set pfx M
290             set scale 1000000
291         }
292         set value [expr "$howlong.0 / $scale"]
293         foreach {min format} {100 %.0f 10 %.1f 1 %.2f} {
294             if {$value < $min} continue
295             return [format "$format${pfx}s" $value]
296         }
297     }
298 }
299
300 proc format_qty {qty unit} {
301     set o $qty
302     append o " "
303     append o $unit
304     if {$qty != 1} { append o s }
305     return $o
306 }
307
308 proc showintervalsecs/hms {qty} {
309     set ul {second 60 minute 60 hour 24 day 7 week}
310     set remainv 0
311     while {[llength $ul] > 1 && $qty >= [set uv [lindex $ul 1]]} {
312         set remainu [lindex $ul 0]
313         set remainv [expr {$qty % $uv}]
314         set qty [expr {($qty-$remainv)/$uv}]
315         set ul [lreplace $ul 0 1]
316     }
317     set o [format_qty $qty [lindex $ul 0]]
318     if {$remainv} {
319         append o " "
320         append o [format_qty $remainv $remainu]
321     }
322     return $o
323 }
324
325 proc showinterval {howlong} {
326     if {$howlong <= 0} {
327         return {just now}
328     } else {
329         return "[showintervalsecs $howlong] ago"
330     }
331 }
332
333 proc showtime {when} {
334     return [showinterval [expr {[clock seconds] - $when}]]
335 }
336
337 proc def_msgproc {name argl body} {
338     proc msg_$name "varbase $argl" "\
339     upvar #0 msg/\$varbase/dest d\n\
340     upvar #0 msg/\$varbase/str s\n\
341     upvar #0 msg/\$varbase/accum a\n\
342 $body"
343 }
344
345 def_msgproc begin {dest str} {
346     set d $dest
347     set s $str
348     set a {}
349 }
350
351 def_msgproc append {str} {
352     set ns "$s$str"
353     if {[string length $s] && [string length $ns] > 65} {
354         msg__sendout $varbase
355         set s " [string trimleft $str]"
356     } else {
357         set s $ns
358     }
359 }
360
361 def_msgproc finish {} {
362     msg__sendout $varbase
363     unset s
364     unset d
365     return $a
366 }
367
368 def_msgproc _sendout {} {
369     lappend a [string trimright $s]
370     set s {}
371 }
372
373 proc looking_whenwhere {when where} {
374     set str [showtime [expr {$when-1}]]
375     if {[string length $where]} { append str " on $where" }
376     return $str
377 }
378
379 proc recordlastseen_n {n how here} {
380     global lastseen lookedfor
381     set lastseen([irctolower $n]) [list $n [clock seconds] $how]
382     if {!$here} return
383     upvar #0 lookedfor([irctolower $n]) lf
384     if {[info exists lf]} {
385         switch -exact [llength $lf] {
386             0 {
387                 set ml {}
388             }
389             1 {
390                 manyset [lindex $lf 0] when who where
391                 set ml [list \
392  "FYI, $who was looking for you [looking_whenwhere $when $where]."]
393             }
394             default {
395                 msg_begin tosend $n "FYI, people have been looking for you:"
396                 set i 0
397                 set fin ""
398                 foreach e $lf {
399                     incr i
400                     if {$i == 1} {
401                         msg_append tosend " "
402                     } elseif {$i == [llength $lf]} {
403                         msg_append tosend " and "
404                         set fin .
405                     } else {
406                         msg_append tosend ", "
407                     }
408                     manyset $e when who where
409                     msg_append tosend \
410                             "$who ([looking_whenwhere $when $where])$fin"
411                 }
412                 set ml [msg_finish tosend]
413             }
414         }
415         unset lf
416         msendprivmsg_delayed 1000 $n $ml
417     }
418 }
419                 
420 proc recordlastseen_p {p how here} {
421     prefix_nick
422     recordlastseen_n $n $how $here
423 }
424
425 proc chanmode_arg {} {
426     upvar 2 args cm_args
427     set rv [lindex $cm_args 0]
428     set cm_args [lreplace cm_args 0 0]
429     return $rv
430 }
431
432 proc chanmode_o1 {m g p chan} {
433     global nick chan_initialop
434     prefix_nick
435     set who [chanmode_arg]
436     recordlastseen_n $n "being nice to $who" 1
437     if {"[irctolower $who]" == "[irctolower $nick]"} {
438         set nl [irctolower $n]
439         upvar #0 nick_unique($n) u
440         if {[chandb_exists $chan]} {
441             sendprivmsg $n Thanks.
442         } elseif {![info exists u]} {
443             sendprivmsg $n {Op me while not on the channel, why don't you ?}
444         } else {
445             set chan_initialop([irctolower $chan]) $u
446             sendprivmsg $n \
447  "Thanks. You can use `channel manager ...' to register this channel."
448             if {![nickdb_exists $n] || ![string length [nickdb_get $n username]]} {
449                 sendprivmsg $n \
450  "(But to do that you must register your nick securely first.)"
451             }
452         }
453     }
454 }
455
456 proc chanmode_o0 {m g p chan} {
457     global nick chandeop
458     prefix_nick
459     set who [chanmode_arg]
460     recordlastseen_p $p "being mean to $who" 1
461     if {"[irctolower $who]" == "[irctolower $nick]"} {
462         set chandeop($chan) [list [clock seconds] $p]
463     }
464 }
465
466 proc msg_MODE {p c dest modelist args} {
467     if {![ischan $dest]} return
468     if {[regexp {^\-(.+)$} $modelist dummy modelist]} {
469         set give 0
470     } elseif {[regexp {^\+(.+)$} $modelist dummy modelist]} {
471         set give 1
472     } else {
473         error "invalid modelist"
474     }
475     foreach m [split $modelist] {
476         set procname chanmode_$m$give
477         if {[catch { info body $procname }]} {
478             recordlastseen_p $p "fiddling with $dest" 1
479         } else {
480             $procname $m $give  $p $dest
481         }
482     }
483 }
484
485 proc channel_noone_seen {chan} {
486     global nick_onchans
487     foreach n [array names nick_onchans] {
488         upvar #0 nick_onchans($n) oc
489         set oc [grep tc {"$tc" != "$chan"} $oc]
490     }
491 }
492
493 proc process_kickpart {chan user} {
494     global nick
495     check_nick $user
496     if {![ischan $chan]} { error "not a channel" }
497     if {"[irctolower $user]" == "[irctolower $nick]"} {
498         channel_noone_seen $chan
499     }
500     upvar #0 nick_onchans($user) oc
501     set lc [irctolower $chan]
502     set oc [grep tc {"$tc" != "$lc"} $oc]
503     if {![llength $oc]} { nick_forget $user }
504     nick_case $user
505 }    
506
507 proc msg_KICK {p c chans users comment} {
508     set chans [split $chans ,]
509     set users [split $users ,]
510     if {[llength $chans] > 1} {
511         foreach chan $chans user $users { process_kickpart $chan $user }
512     } else {
513         foreach user $users { process_kickpart [lindex $chans 0] $user }
514     }
515 }
516
517 proc msg_KILL {p c user why} {
518     nick_forget $user
519 }
520
521 set nick_counter 0
522 set nick_arys {onchans username unique}
523
524 proc nick_forget {n} {
525     global nick_arys
526     foreach ary $nick_arys {
527         upvar #0 nick_${ary}($n) av
528         catch { unset av }
529     }
530     nick_case $n
531 }
532
533 proc nick_case {n} {
534     global nick_case
535     set nick_case([irctolower $n]) $n
536 }
537
538 proc msg_NICK {p c newnick} {
539     global nick_arys nick_case
540     prefix_nick
541     recordlastseen_n $n "changing nicks to $newnick" 0
542     recordlastseen_n $newnick "changing nicks from $n" 1
543     foreach ary $nick_arys {
544         upvar #0 nick_${ary}($n) old
545         upvar #0 nick_${ary}($newnick) new
546         if {[info exists new]} { error "nick collision ?! $ary $n $newnick" }
547         if {[info exists old]} { set new $old; unset old }
548     }
549     nick_case $newnick
550 }
551
552 proc nick_ishere {n} {
553     global nick_counter
554     upvar #0 nick_unique($n) u
555     if {![info exists u]} { set u [incr nick_counter].$n.[clock seconds] }
556     nick_case $n
557 }
558
559 proc msg_JOIN {p c chan} {
560     prefix_nick
561     recordlastseen_n $n "joining $chan" 1
562     upvar #0 nick_onchans($n) oc
563     lappend oc [irctolower $chan]
564     nick_ishere $n
565 }
566 proc msg_PART {p c chan} {
567     prefix_nick
568     recordlastseen_n $n "leaving $chan" 1
569     process_kickpart $chan $n
570 }
571 proc msg_QUIT {p c why} {
572     prefix_nick
573     recordlastseen_n $n "leaving ($why)" 0
574     nick_forget $n
575 }
576
577 proc msg_PRIVMSG {p c dest text} {
578     prefix_nick
579     if {[ischan $dest]} {
580         recordlastseen_n $n "invoking me in $dest" 1
581         set output $dest
582     } else {
583         recordlastseen_n $n "talking to me" 1
584         set output $n
585     }
586     nick_case $n
587
588     if {[catch {
589         regsub {^! *} $text {} text
590         set ucmd [ta_word]
591         set procname ucmd/[string tolower $ucmd]
592         if {[catch { info body $procname }]} {
593             error "unknown command; try help for help"
594         }
595         $procname $p $dest
596     } rv]} {
597         sendprivmsg $n "error: $rv"
598     } else {
599         manyset $rv priv_msgs pub_msgs priv_acts pub_acts
600         foreach {td val} [list $n $priv_acts $output $pub_acts] {
601             foreach l [split $val "\n"] {
602                 sendaction_priority 0 $td $l
603             }
604         }
605         foreach {td val} [list $n $priv_msgs $output $pub_msgs] {
606             foreach l [split $val "\n"] {
607                 sendprivmsg $td $l
608             }
609         }
610     }
611 }
612
613 proc msg_INVITE {p c n chan} {
614     after 1000 [list sendout JOIN $chan]
615 }
616
617 proc grep {var predicate list} {
618     set o {}
619     upvar 1 $var v
620     foreach v $list {
621         if {[uplevel 1 [list expr $predicate]]} { lappend o $v }
622     }
623     return $o
624 }
625
626 proc msg_353 {p c dest type chan nicklist} {
627     global names_chans nick_onchans
628     if {![info exists names_chans]} { set names_chans {} }
629     set chan [irctolower $chan]
630     lappend names_chans $chan
631     channel_noone_seen $chan
632     foreach n [split $nicklist { }] {
633         regsub {^[@+]} $n {} n
634         if {![string length $n]} continue
635         check_nick $n
636         upvar #0 nick_onchans($n) oc
637         lappend oc $chan
638         nick_ishere $n
639     }
640 }
641
642 proc msg_366 {p c args} {
643     global names_chans nick_onchans
644     if {[llength names_chans] > 1} {
645         foreach n [array names nick_onchans] {
646             upvar #0 nick_onchans($n) oc
647             set oc [grep tc {[lsearch -exact $tc $names_chans] >= 0} $oc]
648             if {![llength $oc]} { nick_forget $n }
649         }
650     }
651     unset names_chans
652 }
653
654 proc ta_anymore {} {
655     upvar 1 text text
656     return [expr {!![string length $text]}]
657 }
658
659 proc ta_nomore {} {
660     upvar 1 text text
661     if {[string length $text]} { error "too many parameters" }
662 }
663
664 proc ta_word {} {
665     upvar 1 text text
666     if {![regexp {^([^  ]+) *(.*)} $text dummy firstword text]} {
667         error "too few parameters"
668     }
669     return $firstword
670 }
671
672 proc ta_nick {} {
673     upvar 1 text text
674     set v [ta_word]
675     check_nick $v
676     return $v
677 }
678
679 proc def_ucmd {cmdname body} {
680     proc ucmd/$cmdname {p dest} "    upvar 1 text text\n$body"
681 }
682
683 proc ucmdr {priv pub args} {
684     return -code return [concat [list $priv $pub] $args]
685 }
686
687 proc loadhelp {} {
688     global help_topics
689
690     catch { unset help_topics }
691     set f [open helpinfos r]
692     try_except_finally {
693         set lno 0
694         while {[gets $f l] >= 0} {
695             incr lno
696             if {[regexp {^#.*} $l]} {
697             } elseif {[regexp {^ *$} $l]} {
698                 if {[info exists topic]} {
699                     set help_topics($topic) [join $lines "\n"]
700                     unset topic
701                     unset lines
702                 }
703             } elseif {[regexp {^!([-+._0-9a-z]*)$} $l dummy newtopic]} {
704                 if {[info exists topic]} {
705                     error "help $newtopic while in $topic"
706                 }
707                 set topic $newtopic
708                 set lines {}
709             } elseif {[regexp {^[^!#]} $l]} {
710                 set topic
711                 lappend lines [string trimright $l]
712             } else {
713                 error "eh ? $lno: $l"
714             }
715         }
716         if {[info exists topic]} { error "unfinished topic $topic" }
717     } {} {
718         close $f
719     }
720 }
721
722 def_ucmd help {
723     if {[set lag [out_lagged]]} {
724         if {[ischan $dest]} { set replyto $dest } else { set replyto $n }
725         if {$lag > 1} {
726             sendaction_priority 1 $replyto \
727                 "is very lagged.  Please ask for help again later."
728             ucmdr {} {}
729         } else {
730             sendaction_priority 1 $replyto \
731                 "is lagged.  Your help will arrive shortly ..."
732         }
733     }
734     
735     upvar #0 help_topics([irctolower [string trim $text]]) info
736     if {![info exists info]} { ucmdr "No help on $text, sorry." {} }
737     ucmdr $info {}
738 }
739
740 def_ucmd ? {
741     global help_topics
742     ucmdr $help_topics() {}
743 }
744
745 proc check_username {target} {
746     if {
747         [string length $target] > 8 ||
748         [regexp {[^-0-9a-z]} $target] ||
749         ![regexp {^[a-z]} $target]
750     } { error "invalid username" }
751 }
752
753 proc somedb__head {} {
754     uplevel 1 {
755         set idl [irctolower $id]
756         upvar #0 ${nickchan}db($idl) ndbe
757         binary scan $idl H* idh
758         set idfn $fprefix$idh
759         if {![info exists iddbe] && [file exists $idfn]} {
760             set f [open $idfn r]
761             try_except_finally { set newval [read $f] } {} { close $f }
762             if {[llength $newval] % 2} { error "invalid length" }
763             set iddbe $newval
764         }
765     }
766 }
767
768 proc def_somedb {name arglist body} {
769     foreach {nickchan fprefix} {nick users/n chan chans/c} {
770         proc ${nickchan}db_$name $arglist \
771                 "set nickchan $nickchan; set fprefix $fprefix; somedb__head; $body"
772     }
773 }
774
775 def_somedb exists {id} {
776     return [info exists iddbe]
777 }
778
779 def_somedb delete {id} {
780     catch { unset iddbe }
781     file delete $idfn
782 }
783
784 set default_settings_nick {timeformat ks}
785 set default_settings_chan {autojoin 1}
786
787 def_somedb set {id args} {
788     upvar #0 default_settings_$nickchan def
789     if {![info exists iddbe]} { set iddbe $def }
790     foreach {key value} [concat $iddbe $args] { set a($key) $value }
791     set newval {}
792     foreach {key value} [array get a] { lappend newval $key $value }
793     set f [open $idfn.new w]
794     try_except_finally {
795         puts $f $newval
796         close $f
797         file rename -force $idfn.new $idfn
798     } {
799     } {
800         catch { close $f }
801     }
802     set iddbe $newval
803 }
804
805 def_somedb get {id key} {
806     upvar #0 default_settings_$nickchan def
807     if {[info exists iddbe]} {
808         set l $iddbe
809     } else {
810         set l $def
811     }
812     foreach {tkey value} $l {
813         if {"$tkey" == "$key"} { return $value }
814     }
815     error "unset setting $key"
816 }
817
818 proc opt {key} {
819     global calling_nick
820     if {[info exists calling_nick]} { set n $calling_nick } { set n {} }
821     return [nickdb_get $n $key]
822 }
823
824 proc check_notonchan {} {
825     upvar 1 dest dest
826     if {[ischan $dest]} { error "that command must be sent privately" }
827 }
828
829 proc nick_securitycheck {strict} {
830     upvar 1 n n
831     if {![nickdb_exists $n]} { error "you are unknown to me, use `register'." }
832     set wantu [nickdb_get $n username]
833     if {![string length $wantu]} {
834         if {$strict} {
835             error "that feature is only available to secure users, sorry."
836         } else {
837             return
838         }
839     }
840     upvar #0 nick_username($n) nu
841     if {![info exists nu]} {
842         error "nick $n is secure, you must identify yourself first."
843     }
844     if {"$wantu" != "$nu"} {
845         error "you are the wrong user - the nick $n belongs to $wantu, not $nu"
846     }
847 }
848
849 proc channel_securitycheck {channel n} {
850     # You must also call `nick_securitycheck 1'
851     set mgrs [chandb_get $channel managers]
852     if {[lsearch -exact [irctolower $mgrs] [irctolower $n]] < 0} {
853         error "you are not a manager of $channel"
854     }
855 }
856
857 proc def_chancmd {name body} {
858     proc channel/$name {} \
859             "    upvar 1 target chan; upvar 1 n n; upvar 1 text text; $body"
860 }
861
862 def_chancmd manager {
863     set opcode [ta_word]
864     switch -exact _$opcode {
865         _= { set ml {} }
866         _+ - _- {
867             if {[chandb_exists $chan]} {
868                 set ml [chandb_get $chan managers]
869             } else {
870                 set ml [list [irctolower $n]]
871             }
872         }
873         default {
874             error "`channel manager' opcode must be one of + - ="
875         }
876     }
877     foreach nn [split $text " "] {
878         if {![string length $nn]} continue
879         check_nick $nn
880         set nn [irctolower $nn]
881         if {"$opcode" != "-"} {
882             lappend ml $nn
883         } else {
884             set ml [grep nq {"$nq" != "$nn"} $ml]
885         }
886     }
887     if {[llength $ml]} {
888         chandb_set $chan managers $ml
889         ucmdr "Managers of $chan: $ml" {}
890     } else {
891         chandb_delete $chan
892         ucmdr {} {} "forgets about managing $chan." {}
893     }
894 }
895
896 def_chancmd autojoin {
897     set yesno [ta_word]
898     switch -exact [string tolower $yesno] {
899         no { set nv 0 }
900         yes { set nv 1 }
901         default { error "channel autojoin must be `yes' or `no' }
902     }
903     chandb_set $chan autojoin $nv
904 }
905
906 def_chancmd show {
907     if {[chandb_exists $chan]} {
908         set l "Settings for $chan: autojoin "
909         append l [lindex {no yes} [chandb_get $chan autojoin]]
910         append l "\nManagers: "
911         append l [join [chandb_get $chan managers] " "]
912         ucmdr {} $l
913     } else {
914         ucmdr {} "The channel $chan is not managed."
915     }
916 }
917
918 def_ucmd op {
919     if {[ischan $dest]} { set target $dest }
920     if {[ta_anymore]} { set target [ta_word] }
921     ta_nomore
922     if {![info exists target]} { error "you must specify, or !... on, the channel" }
923     if {![ischan $target]} { error "not a valid channel" }
924     if {![chandb_exists $target]} { error "$target is not a managed channel." }
925     prefix_nick
926     nick_securitycheck 1
927     channel_securitycheck $target $n
928     sendout MODE $target +o $n
929 }
930
931 def_ucmd channel {
932     if {[ischan $dest]} { set target $dest }
933     if {![ta_anymore]} {
934         set subcmd show
935     } else {
936         set subcmd [ta_word]
937     }
938     if {[ischan $subcmd]} {
939         set target $subcmd
940         if {![ta_anymore]} {
941             set subcmd show
942         } else {
943             set subcmd [ta_word]
944         }
945     }
946     if {![info exists target]} { error "privately, you must specify a channel" }
947     set procname channel/$subcmd
948     if {"$subcmd" != "show"} {
949         if {[catch { info body $procname }]} { error "unknown channel setting $subcmd" }
950         prefix_nick
951         nick_securitycheck 1
952         if {[chandb_exists $target]} {
953             channel_securitycheck $target $n
954         } else {
955             upvar #0 chan_initialop([irctolower $target]) io
956             upvar #0 nick_unique($n) u
957             if {![info exists io]} { error "$target is not a managed channel" }
958             if {"$io" != "$u"} { error "you are not the interim manager of $target" }
959             if {"$subcmd" != "manager"} { error "use `channel manager' first" }
960         }
961     }
962     channel/$subcmd
963 }
964
965 def_ucmd who {
966     if {[ta_anymore]} {
967         set target [ta_word]; ta_nomore
968         set myself 1
969     } else {
970         prefix_nick
971         set target $n
972         set myself [expr {"$target" != "$n"}]
973     }
974     upvar #0 nick_case([irctolower $target]) nc
975     set nshow $target
976     if {[info exists nc]} {
977         upvar #0 nick_onchans($nc) oc
978         upvar #0 nick_username($nc) nu
979         if {[info exists oc]} { set nshow $nc }
980     }
981     if {![nickdb_exists $target]} {
982         set ol "$nshow is not a registered nick."
983     } elseif {[string length [set username [nickdb_get $target username]]]} {
984         set ol "The nick $nshow belongs to the user $username."
985     } else {
986         set ol "The nick $nshow is registered (but not to a username)."
987     }
988     if {![info exists nc] || ![info exists oc]} {
989         if {$myself} {
990             append ol "\nI can't see $nshow on anywhere."
991         } else {
992             append ol "\nYou aren't on any channels with me."
993         }
994     } elseif {![info exists nu]} {
995         append ol "\n$nshow has not identified themselves."
996     } elseif {![info exists username]} {
997         append ol "\n$nshow has identified themselves as the user $nu."
998     } elseif {"$nu" != "$username"} {
999         append ol "\nHowever, $nshow is being used by the user $nu."
1000     } else {
1001         append ol "\n$nshow has identified themselves to me."
1002     }
1003     ucmdr {} $ol
1004 }
1005
1006 def_ucmd register {
1007     prefix_nick
1008     check_notonchan
1009     set old [nickdb_exists $n]
1010     if {$old} { nick_securitycheck 0 }
1011     switch -exact [string tolower [string trim $text]] {
1012         {} {
1013             upvar #0 nick_username($n) nu
1014             if {![info exists nu]} {
1015                 ucmdr {} \
1016  "You must identify yourself before using `register'.  See `help identify', or use `register insecure'."
1017             }
1018             nickdb_set $n username $nu
1019             ucmdr {} {} "makes a note of your username." {}
1020         }
1021         delete {
1022             nickdb_delete $n
1023             ucmdr {} {} "forgets your nickname." {}
1024         }
1025         insecure {
1026             nickdb_set $n username {}
1027             if {$old} {
1028                 ucmdr {} "Security is now disabled for your nickname !"
1029             } else {
1030                 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."
1031             }
1032         }
1033     }
1034 }
1035
1036 proc timeformat_desc {tf} {
1037     switch -exact $tf {
1038         ks { return "Times will be displayed in seconds or kiloseconds." }
1039         hms { return "Times will be displayed in hours, minutes, etc." }
1040         default { error "invalid timeformat: $v" }
1041     }
1042 }
1043
1044 proc def_setting {opt show_body set_body} {
1045     proc set_show/$opt {} "
1046         upvar 1 n n
1047         set opt $opt
1048         $show_body"
1049     if {![string length $set_body]} return
1050     proc set_set/$opt {} "
1051         upvar 1 n n
1052         upvar 1 text text
1053         set opt $opt
1054         $set_body"
1055 }
1056
1057 def_setting timeformat {
1058     set tf [nickdb_get $n timeformat]
1059     return "$tf: [timeformat_desc $tf]"
1060 } {
1061     set tf [string tolower [ta_word]]
1062     ta_nomore
1063     set desc [timeformat_desc $tf]
1064     nickdb_set $n timeformat $tf
1065     ucmdr {} $desc
1066 }
1067
1068 def_setting security {
1069     set s [nickdb_get $n username]
1070     if {[string length $s]} {
1071         return "Your nick, $n, is controlled by the user $s."
1072     } else {
1073         return "Your nick, $n, is not secure."
1074     }
1075 } {}
1076
1077 def_ucmd set {
1078     prefix_nick
1079     check_notonchan
1080     if {![nickdb_exists $n]} {
1081         ucmdr {} "You are unknown to me and so have no settings.  (Use `register'.)"
1082     }
1083     if {![ta_anymore]} {
1084         set ol {}
1085         foreach proc [lsort [info procs]] {
1086             if {![regexp {^set_show/(.*)$} $proc dummy opt]} continue
1087             lappend ol [format "%-10s %s" $opt [set_show/$opt]]
1088         }
1089         ucmdr {} [join $ol "\n"]
1090     } else {
1091         set opt [ta_word]
1092         if {[catch { info body set_show/$opt }]} {
1093             error "no setting $opt"
1094         }
1095         if {![ta_anymore]} {
1096             ucmdr {} "$opt [set_show/$opt]"
1097         } else {
1098             nick_securitycheck 0
1099             if {[catch { info body set_set/$opt }]} {
1100                 error "setting $opt cannot be set with `set'"
1101             }
1102             set_set/$opt
1103         }
1104     }
1105 }
1106
1107 def_ucmd identpass {
1108     set username [ta_word]
1109     set passmd5 [md5sum "[ta_word]\n"]
1110     ta_nomore
1111     prefix_nick
1112     check_notonchan
1113     upvar #0 nick_onchans($n) onchans
1114     if {![info exists onchans] || ![llength $onchans]} {
1115         ucmdr "You must be on a channel with me to identify yourself." {}
1116     }
1117     check_username $username
1118     exec userv --timeout 3 $username << "$passmd5\n" > /dev/null \
1119             irc-identpass $n
1120     upvar #0 nick_username($n) rec_username
1121     set rec_username $username
1122     ucmdr "Pleased to see you, $username." {}
1123 }
1124
1125 def_ucmd summon {
1126     set target [ta_word]
1127     ta_nomore
1128     check_username $target
1129     prefix_nick
1130
1131     upvar #0 lastsummon($target) ls
1132     set now [clock seconds]
1133     if {[info exists ls]} {
1134         set interval [expr {$now - $ls}]
1135         if {$interval < 30} {
1136             ucmdr {} \
1137  "Please be patient; $target was summoned only [showinterval $interval]."
1138         }
1139     }
1140     regsub {^[^!]*!} $p {} path
1141     if {[catch {
1142         exec userv --timeout 3 $target irc-summon $n $path \
1143                 [expr {[ischan $dest] ? "$dest" : ""}] \
1144                 < /dev/null
1145     } rv]} {
1146         regsub -all "\n" $rv { / } rv
1147         error $rv
1148     }
1149     if {[regexp {^problem (.*)} $rv dummy problem]} {
1150         ucmdr {} "The user `$target' $problem."
1151     } elseif {[regexp {^ok ([^ ]+) ([0-9]+)$} $rv dummy tty idlesince]} {
1152         set idletime [expr {$now - $idlesince}]
1153         set ls $now
1154         ucmdr {} {} {} "invites $target ($tty[expr {
1155             $idletime > 10 ? ", idle for [showintervalsecs $idletime]" : ""
1156         }]) to [expr {
1157             [ischan $dest] ? "join us here" : "talk to you"
1158         }]."
1159     } else {
1160         error "unexpected response from userv service: $rv"
1161     }
1162 }
1163
1164 proc md5sum {value} { exec md5sum << $value }
1165
1166 def_ucmd seen {
1167     global lastseen nick
1168     prefix_nick
1169     set ncase [ta_nick]
1170     set nlower [irctolower $ncase]
1171     ta_nomore
1172     set now [clock seconds]
1173     if {"$nlower" == "[irctolower $nick]"} {
1174         error "I am not self-aware."
1175     } elseif {![info exists lastseen($nlower)]} {
1176         set rstr "I've never seen $ncase."
1177     } else {
1178         manyset $lastseen($nlower) realnick time what
1179         set howlong [expr {$now - $time}]
1180         set string [showinterval $howlong]
1181         set rstr "I last saw $realnick $string, $what."
1182     }
1183     if {[ischan $dest]} {
1184         set where $dest
1185     } else {
1186         set where {}
1187     }
1188     upvar #0 lookedfor($nlower) lf
1189     if {[info exists lf]} { set oldvalue $lf } else { set oldvalue {} }
1190     set lf [list [list $now $n $where]]
1191     foreach v $oldvalue {
1192         if {"[irctolower [lindex $v 1]]" == "[irctolower $n]"} continue
1193         lappend lf $v
1194     }
1195     ucmdr {} $rstr
1196 }
1197
1198 proc ensure_globalsecret {} {
1199     global globalsecret
1200     
1201     if {[info exists globalsecret]} return
1202     set gsfile [open /dev/urandom r]
1203     fconfigure $gsfile -translation binary
1204     set globalsecret [read $gsfile 32]
1205     binary scan $globalsecret H* globalsecret
1206     close $gsfile
1207     unset gsfile
1208 }
1209
1210 proc ensure_outqueue {} {
1211     out__vars
1212     if {[info exists out_queue]} return
1213     set out_creditms [expr {$out_maxburst*$out_interval}]
1214     set out_creditat [clock seconds]
1215     set out_queue {}
1216     set out_lag_reported 0
1217     set out_lag_reportwhen $out_creditat
1218 }
1219
1220 proc fail {msg} {
1221     logerror "failing: $msg"
1222     exit 1
1223 }
1224
1225 proc ensure_connecting {} {
1226     global sock ownfullname host port nick
1227     global musthaveping_ms musthaveping_after
1228     
1229     if {[info exists sock]} return
1230     set sock [socket $host $port]
1231     fconfigure $sock -buffering line
1232     fconfigure $sock -translation crlf
1233
1234     sendout USER blight 0 * $ownfullname
1235     sendout NICK $nick
1236     fileevent $sock readable onread
1237
1238     set musthaveping_after [after $musthaveping_ms \
1239             {fail "no ping within timeout"}]
1240 }
1241
1242 ensure_globalsecret
1243 ensure_outqueue
1244 loadhelp
1245 ensure_connecting