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