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