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