chiark / gitweb /
Dies if doesn't get a ping. Configs separated.
[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
e58e51a8
IJ
241 if {[info exists musthaveping_after]} {
242 after cancel $musthaveping_after
243 unset musthaveping_after
244 }
9bc33297
IJ
245}
246
cc2d31de
IJ
247proc 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
422f52e4
IJ
252proc ischan {dest} {
253 return [regexp {^[&#+!]} $dest]
254}
255
256proc 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
cc2d31de
IJ
266proc 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
a056c4bd
IJ
272 if {"[irctolower $n]" == "[irctolower $nick]"} {
273 error "from myself" {} {}
274 }
422f52e4
IJ
275}
276
7ce72032 277proc showintervalsecs {howlong} {
d83fb8db
IJ
278 return [showintervalsecs/[opt timeformat] $howlong]
279}
280
281proc showintervalsecs/ks {howlong} {
7ce72032
IJ
282 if {$howlong < 1000} {
283 return "${howlong}s"
83dd1224
IJ
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
7ce72032 295 return [format "$format${pfx}s" $value]
83dd1224
IJ
296 }
297 }
298}
299
d83fb8db
IJ
300proc 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
308proc 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
7ce72032
IJ
325proc showinterval {howlong} {
326 if {$howlong <= 0} {
327 return {just now}
328 } else {
329 return "[showintervalsecs $howlong] ago"
330 }
331}
332
83dd1224
IJ
333proc showtime {when} {
334 return [showinterval [expr {[clock seconds] - $when}]]
335}
336
337proc 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
345def_msgproc begin {dest str} {
346 set d $dest
347 set s $str
348 set a {}
349}
350
351def_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
361def_msgproc finish {} {
362 msg__sendout $varbase
363 unset s
364 unset d
365 return $a
366}
367
368def_msgproc _sendout {} {
369 lappend a [string trimright $s]
370 set s {}
371}
372
373proc 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
379proc recordlastseen_n {n how here} {
380 global lastseen lookedfor
422f52e4 381 set lastseen([irctolower $n]) [list $n [clock seconds] $how]
83dd1224
IJ
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 }
422f52e4
IJ
418}
419
83dd1224 420proc recordlastseen_p {p how here} {
422f52e4 421 prefix_nick
83dd1224 422 recordlastseen_n $n $how $here
422f52e4
IJ
423}
424
425proc 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
83dd1224 432proc chanmode_o1 {m g p chan} {
20087363 433 global nick chan_initialop
83dd1224
IJ
434 prefix_nick
435 set who [chanmode_arg]
436 recordlastseen_n $n "being nice to $who" 1
437 if {"[irctolower $who]" == "[irctolower $nick]"} {
20087363
IJ
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 }
83dd1224
IJ
453 }
454}
455
422f52e4
IJ
456proc chanmode_o0 {m g p chan} {
457 global nick chandeop
458 prefix_nick
459 set who [chanmode_arg]
83dd1224 460 recordlastseen_p $p "being mean to $who" 1
422f52e4
IJ
461 if {"[irctolower $who]" == "[irctolower $nick]"} {
462 set chandeop($chan) [list [clock seconds] $p]
463 }
cc2d31de 464}
9bc33297 465
422f52e4
IJ
466proc 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 }]} {
83dd1224 478 recordlastseen_p $p "fiddling with $dest" 1
422f52e4
IJ
479 } else {
480 $procname $m $give $p $dest
481 }
482 }
483}
484
a4a1f396
IJ
485proc 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
a056c4bd 493proc process_kickpart {chan user} {
a4a1f396 494 global nick
a056c4bd
IJ
495 check_nick $user
496 if {![ischan $chan]} { error "not a channel" }
a4a1f396
IJ
497 if {"[irctolower $user]" == "[irctolower $nick]"} {
498 channel_noone_seen $chan
499 }
a056c4bd
IJ
500 upvar #0 nick_onchans($user) oc
501 set lc [irctolower $chan]
502 set oc [grep tc {"$tc" != "$lc"} $oc]
d83fb8db 503 if {![llength $oc]} { nick_forget $user }
a4a1f396 504 nick_case $user
a056c4bd
IJ
505}
506
507proc 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
517proc msg_KILL {p c user why} {
518 nick_forget $user
519}
520
20087363
IJ
521set nick_counter 0
522set nick_arys {onchans username unique}
a056c4bd
IJ
523
524proc nick_forget {n} {
525 global nick_arys
526 foreach ary $nick_arys {
527 upvar #0 nick_${ary}($n) av
528 catch { unset av }
529 }
a4a1f396
IJ
530 nick_case $n
531}
532
533proc nick_case {n} {
534 global nick_case
535 set nick_case([irctolower $n]) $n
a056c4bd
IJ
536}
537
83dd1224 538proc msg_NICK {p c newnick} {
a4a1f396 539 global nick_arys nick_case
83dd1224
IJ
540 prefix_nick
541 recordlastseen_n $n "changing nicks to $newnick" 0
542 recordlastseen_n $newnick "changing nicks from $n" 1
a056c4bd
IJ
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 }
a4a1f396 549 nick_case $newnick
83dd1224
IJ
550}
551
20087363
IJ
552proc 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
a056c4bd
IJ
559proc 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]
20087363 564 nick_ishere $n
a056c4bd
IJ
565}
566proc msg_PART {p c chan} {
567 prefix_nick
568 recordlastseen_n $n "leaving $chan" 1
569 process_kickpart $chan $n
570}
571proc msg_QUIT {p c why} {
572 prefix_nick
573 recordlastseen_n $n "leaving ($why)" 0
574 nick_forget $n
575}
422f52e4 576
cc2d31de
IJ
577proc msg_PRIVMSG {p c dest text} {
578 prefix_nick
422f52e4 579 if {[ischan $dest]} {
83dd1224 580 recordlastseen_n $n "invoking me in $dest" 1
422f52e4 581 set output $dest
cc2d31de 582 } else {
83dd1224 583 recordlastseen_n $n "talking to me" 1
422f52e4
IJ
584 set output $n
585 }
a4a1f396 586 nick_case $n
422f52e4
IJ
587
588 if {[catch {
589 regsub {^! *} $text {} text
590 set ucmd [ta_word]
83dd1224 591 set procname ucmd/[string tolower $ucmd]
422f52e4
IJ
592 if {[catch { info body $procname }]} {
593 error "unknown command; try help for help"
594 }
83dd1224 595 $procname $p $dest
422f52e4 596 } rv]} {
7ce72032 597 sendprivmsg $n "error: $rv"
422f52e4 598 } else {
7ce72032 599 manyset $rv priv_msgs pub_msgs priv_acts pub_acts
7a70431a 600 foreach {td val} [list $n $priv_acts $output $pub_acts] {
7ce72032 601 foreach l [split $val "\n"] {
7818b6af 602 sendaction_priority 0 $td $l
7ce72032
IJ
603 }
604 }
7a70431a 605 foreach {td val} [list $n $priv_msgs $output $pub_msgs] {
422f52e4 606 foreach l [split $val "\n"] {
7a70431a 607 sendprivmsg $td $l
422f52e4
IJ
608 }
609 }
610 }
611}
612
a056c4bd
IJ
613proc msg_INVITE {p c n chan} {
614 after 1000 [list sendout JOIN $chan]
615}
616
617proc 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
626proc 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
a4a1f396 631 channel_noone_seen $chan
a056c4bd
IJ
632 foreach n [split $nicklist { }] {
633 regsub {^[@+]} $n {} n
a056c4bd 634 if {![string length $n]} continue
a4a1f396 635 check_nick $n
a056c4bd
IJ
636 upvar #0 nick_onchans($n) oc
637 lappend oc $chan
20087363 638 nick_ishere $n
a056c4bd
IJ
639 }
640}
641
642proc 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
11d9bff9
IJ
654proc ta_anymore {} {
655 upvar 1 text text
656 return [expr {!![string length $text]}]
657}
658
422f52e4
IJ
659proc ta_nomore {} {
660 upvar 1 text text
661 if {[string length $text]} { error "too many parameters" }
662}
663
664proc 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
672proc ta_nick {} {
673 upvar 1 text text
674 set v [ta_word]
675 check_nick $v
676 return $v
677}
678
83dd1224
IJ
679proc def_ucmd {cmdname body} {
680 proc ucmd/$cmdname {p dest} " upvar 1 text text\n$body"
681}
682
7ce72032
IJ
683proc ucmdr {priv pub args} {
684 return -code return [concat [list $priv $pub] $args]
422f52e4 685}
e1ba63be 686
e6cc22dc
IJ
687proc loadhelp {} {
688 global help_topics
689
690 catch { unset help_topics }
691 set f [open helpinfos r]
d83fb8db
IJ
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"
e6cc22dc 714 }
e6cc22dc 715 }
d83fb8db
IJ
716 if {[info exists topic]} { error "unfinished topic $topic" }
717 } {} {
718 close $f
e6cc22dc 719 }
422f52e4
IJ
720}
721
e6cc22dc 722def_ucmd help {
7818b6af
IJ
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
e6cc22dc 735 upvar #0 help_topics([irctolower [string trim $text]]) info
4fd2739c 736 if {![info exists info]} { ucmdr "No help on $text, sorry." {} }
e6cc22dc
IJ
737 ucmdr $info {}
738}
e1ba63be 739
e6cc22dc
IJ
740def_ucmd ? {
741 global help_topics
742 ucmdr $help_topics() {}
743}
e1ba63be 744
4fd2739c 745proc check_username {target} {
7ce72032
IJ
746 if {
747 [string length $target] > 8 ||
748 [regexp {[^-0-9a-z]} $target] ||
749 ![regexp {^[a-z]} $target]
750 } { error "invalid username" }
4fd2739c
IJ
751}
752
20087363 753proc somedb__head {} {
7a70431a 754 uplevel 1 {
20087363
IJ
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]
7a70431a
IJ
761 try_except_finally { set newval [read $f] } {} { close $f }
762 if {[llength $newval] % 2} { error "invalid length" }
20087363 763 set iddbe $newval
7a70431a
IJ
764 }
765 }
766}
767
20087363
IJ
768proc 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 }
7a70431a
IJ
773}
774
20087363
IJ
775def_somedb exists {id} {
776 return [info exists iddbe]
7a70431a
IJ
777}
778
20087363
IJ
779def_somedb delete {id} {
780 catch { unset iddbe }
781 file delete $idfn
7a70431a
IJ
782}
783
20087363
IJ
784set default_settings_nick {timeformat ks}
785set default_settings_chan {autojoin 1}
7a70431a 786
20087363
IJ
787def_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 }
7a70431a
IJ
791 set newval {}
792 foreach {key value} [array get a] { lappend newval $key $value }
20087363 793 set f [open $idfn.new w]
7a70431a
IJ
794 try_except_finally {
795 puts $f $newval
796 close $f
20087363 797 file rename -force $idfn.new $idfn
7a70431a 798 } {
7a70431a 799 } {
d83fb8db 800 catch { close $f }
7a70431a 801 }
20087363 802 set iddbe $newval
7a70431a
IJ
803}
804
20087363
IJ
805def_somedb get {id key} {
806 upvar #0 default_settings_$nickchan def
807 if {[info exists iddbe]} {
808 set l $iddbe
7a70431a 809 } else {
20087363 810 set l $def
7a70431a
IJ
811 }
812 foreach {tkey value} $l {
813 if {"$tkey" == "$key"} { return $value }
814 }
815 error "unset setting $key"
816}
817
20087363
IJ
818proc 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
7a70431a
IJ
824proc check_notonchan {} {
825 upvar 1 dest dest
826 if {[ischan $dest]} { error "that command must be sent privately" }
827}
828
829proc nick_securitycheck {strict} {
830 upvar 1 n n
831 if {![nickdb_exists $n]} { error "you are unknown to me, use `register'." }
20087363 832 set wantu [nickdb_get $n username]
7a70431a
IJ
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
20087363
IJ
849proc channel_securitycheck {channel n} {
850 # You must also call `nick_securitycheck 1'
c362e172
IJ
851 set mgrs [chandb_get $channel managers]
852 if {[lsearch -exact [irctolower $mgrs] [irctolower $n]] < 0} {
20087363
IJ
853 error "you are not a manager of $channel"
854 }
855}
856
857proc def_chancmd {name body} {
858 proc channel/$name {} \
859 " upvar 1 target chan; upvar 1 n n; upvar 1 text text; $body"
860}
861
862def_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
896def_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
906def_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
918def_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
931def_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
a4a1f396
IJ
965def_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."
20087363 983 } elseif {[string length [set username [nickdb_get $target username]]]} {
a4a1f396
IJ
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
7a70431a
IJ
1006def_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 {} \
a4a1f396 1016 "You must identify yourself before using `register'. See `help identify', or use `register insecure'."
7a70431a
IJ
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 }
11d9bff9
IJ
1034}
1035
1036proc timeformat_desc {tf} {
1037 switch -exact $tf {
86892128 1038 ks { return "Times will be displayed in seconds or kiloseconds." }
11d9bff9
IJ
1039 hms { return "Times will be displayed in hours, minutes, etc." }
1040 default { error "invalid timeformat: $v" }
1041 }
1042}
1043
1044proc 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
1057def_setting timeformat {
20087363 1058 set tf [nickdb_get $n timeformat]
11d9bff9
IJ
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
1068def_setting security {
20087363 1069 set s [nickdb_get $n username]
11d9bff9
IJ
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
1077def_ucmd set {
1078 prefix_nick
1079 check_notonchan
1080 if {![nickdb_exists $n]} {
d83fb8db 1081 ucmdr {} "You are unknown to me and so have no settings. (Use `register'.)"
11d9bff9
IJ
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 {
86892128 1098 nick_securitycheck 0
11d9bff9
IJ
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}
7a70431a 1106
4fd2739c
IJ
1107def_ucmd identpass {
1108 set username [ta_word]
d83fb8db 1109 set passmd5 [md5sum "[ta_word]\n"]
4fd2739c
IJ
1110 ta_nomore
1111 prefix_nick
11d9bff9 1112 check_notonchan
4fd2739c
IJ
1113 upvar #0 nick_onchans($n) onchans
1114 if {![info exists onchans] || ![llength $onchans]} {
7a70431a 1115 ucmdr "You must be on a channel with me to identify yourself." {}
4fd2739c
IJ
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
7a70431a 1122 ucmdr "Pleased to see you, $username." {}
4fd2739c
IJ
1123}
1124
1125def_ucmd summon {
1126 set target [ta_word]
1127 ta_nomore
1128 check_username $target
7ce72032
IJ
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]} {
8a8d337d 1150 ucmdr {} "The user `$target' $problem."
7ce72032
IJ
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
a69f7d2c
IJ
1164proc md5sum {value} { exec md5sum << $value }
1165
83dd1224 1166def_ucmd seen {
422f52e4 1167 global lastseen nick
83dd1224
IJ
1168 prefix_nick
1169 set ncase [ta_nick]
1170 set nlower [irctolower $ncase]
422f52e4 1171 ta_nomore
83dd1224
IJ
1172 set now [clock seconds]
1173 if {"$nlower" == "[irctolower $nick]"} {
422f52e4 1174 error "I am not self-aware."
83dd1224
IJ
1175 } elseif {![info exists lastseen($nlower)]} {
1176 set rstr "I've never seen $ncase."
422f52e4 1177 } else {
83dd1224
IJ
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
cc2d31de 1194 }
83dd1224 1195 ucmdr {} $rstr
cc2d31de
IJ
1196}
1197
28c8ab78
IJ
1198proc 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
1210proc 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
1220proc fail {msg} {
1221 logerror "failing: $msg"
1222 exit 1
1223}
1224
1225proc ensure_connecting {} {
1226 global sock ownfullname host port nick
1227 global musthaveping_ms musthaveping_after
1228
1229 if {[info exists sock]} return
cc2d31de
IJ
1230 set sock [socket $host $port]
1231 fconfigure $sock -buffering line
cc2d31de
IJ
1232 fconfigure $sock -translation crlf
1233
b3d361ab 1234 sendout USER blight 0 * $ownfullname
cc2d31de
IJ
1235 sendout NICK $nick
1236 fileevent $sock readable onread
28c8ab78
IJ
1237
1238 set musthaveping_after [after $musthaveping_ms \
1239 {fail "no ping within timeout"}]
cc2d31de
IJ
1240}
1241
28c8ab78
IJ
1242ensure_globalsecret
1243ensure_outqueue
e6cc22dc 1244loadhelp
28c8ab78 1245ensure_connecting