chiark / gitweb /
Improved msg
[ircbot] / bot.tcl
... / ...
CommitLineData
1# Actual IRC bot code
2
3set helpfile helpinfos
4
5source irccore.tcl
6source parsecmd.tcl
7source stdhelp.tcl
8
9defset marktime_min 300
10defset marktime_join_startdelay 5000
11
12proc privmsg_unlogged {prefix ischan params} {
13 if {!$ischan ||
14 [regexp {^![a-z][-a-z]*[a-z]( .*)?$} [lindex $params 1]]} {
15 return 0
16 }
17 # on-channel message, ignore
18 set chan [lindex $params 0]
19 upvar #0 chan_lastactivity([irctolower $chan]) la
20 set la [clock seconds]
21 catch_logged { recordlastseen_p $prefix "talking on $chan" 2 }
22 return 1
23}
24
25proc showintervalsecs {howlong abbrev} {
26 return [showintervalsecs/[opt timeformat] $howlong $abbrev]
27}
28
29proc formatsf {pfx value} {
30 foreach {min format} { 100 %.0f 10 %.1f 0 %.2f} {
31 set fval [format $format $value]
32 if {$fval < $min} continue
33 return [format "$fval${pfx}" $value]
34 }
35}
36
37proc showintervalsecs/beat {howlong abbrev} {
38 # We split in two to avoid overflow problems.
39 if {$howlong < 86 } {
40 # mB's
41 set pfx mB
42 return [format "%.0fmB" [expr {round($howlong * 1.157)*10} ]]
43 } else {
44 if {$howlong < 86400 } {
45 # B's
46 set pfx B
47 set value [expr {$howlong / 86.4}]
48 } else {
49 # kB's
50 set pfx kB
51 set value [expr {$howlong / 86400.0}]
52 }
53 }
54 return [formatsf $pfx $value]
55}
56
57proc showintervalsecs/ks {howlong abbrev} {
58 if {$howlong < 1000} {
59 return "${howlong}s"
60 } else {
61 if {$howlong < 1000000} {
62 set pfx ks
63 set scale 1000
64 } else {
65 set pfx Ms
66 set scale 1000000
67 }
68 set value [expr "$howlong.0 / $scale"]
69 return [formatsf $pfx $value]
70 }
71}
72
73proc format_qty {qty unit abbrev} {
74 set o $qty
75 if {$abbrev} {
76 append o [string range $unit 0 0]
77 } else {
78 append o " "
79 append o $unit
80 if {$qty != 1} { append o s }
81 }
82 return $o
83}
84
85proc showintervalsecs/hms {qty abbrev} {
86 set ul {second 60 minute 60 hour 24 day 7 week}
87 set remainv 0
88 while {[llength $ul] > 1 && $qty >= [set uv [lindex $ul 1]]} {
89 set remainu [lindex $ul 0]
90 set remainv [expr {$qty % $uv}]
91 set qty [expr {($qty-$remainv)/$uv}]
92 set ul [lreplace $ul 0 1]
93 }
94 set o [format_qty $qty [lindex $ul 0] $abbrev]
95 if {$remainv} {
96 if {!$abbrev} { append o " " }
97 append o [format_qty $remainv $remainu $abbrev]
98 }
99 return $o
100}
101
102proc showinterval {howlong} {
103 if {$howlong <= 0} {
104 return {just now}
105 } else {
106 return "[showintervalsecs $howlong 0] ago"
107 }
108}
109
110proc showtime {when} {
111 return [showinterval [expr {[clock seconds] - $when}]]
112}
113
114proc parse_interval {specified min} {
115 if {![regexp {^([0-9]+)([a-z]+)$} $specified dummy value unit]} {
116 error "invalid syntax for interval"
117 }
118 switch -exact $unit {
119 s { set u 1 }
120 ks { set u 1000 }
121 m { set u 60 }
122 h { set u 3600 }
123 mb { set u 0.0864 }
124 b { set u 86.4 }
125 kb { set u 86400 }
126 default { error "unknown unit of time $unit" }
127 }
128 if {$value > 86400*21/$u} { error "interval too large" }
129 set result [expr {round($value*$u)}]
130 if {$result < $min} { error "interval too small (<${min}s)" }
131 return $result
132}
133
134proc def_msgproc {name argl body} {
135 proc msg_$name "varbase $argl" "\
136 upvar #0 msg/\$varbase/dest d\n\
137 upvar #0 msg/\$varbase/str s\n\
138 upvar #0 msg/\$varbase/accum a\n\
139$body"
140}
141
142def_msgproc begin {dest str} {
143 set d $dest
144 set s $str
145 set a {}
146}
147
148def_msgproc append {str} {
149 set ns "$s$str"
150 if {[string length $s] && [string length $ns] > 65} {
151 msg__sendout $varbase
152 set s " [string trimleft $str]"
153 } else {
154 set s $ns
155 }
156}
157
158def_msgproc finish {} {
159 msg__sendout $varbase
160 unset s
161 unset d
162 return $a
163}
164
165def_msgproc _sendout {} {
166 lappend a [string trimright $s]
167 set s {}
168}
169
170proc looking_whenwhere {when where} {
171 set str [showtime [expr {$when-1}]]
172 if {[string length $where]} { append str " on $where" }
173 return $str
174}
175
176proc tell_getcstate {} {
177 # uses nl from caller's context
178 # imports telling (as the nick_telling) and u
179 # sets stt, telling_when
180 uplevel 1 {
181 upvar #0 nick_telling($nl) telling
182 upvar #0 nick_unique($nl) u
183
184 if {[info exists telling]} {
185 manyset $telling u_last stt telling_when
186 if {![info exists u] || "$u_last" != "$u"} {
187 set stt undelivered
188 }
189 } else {
190 set stt undelivered
191 set telling_when 0
192 }
193 }
194}
195
196proc tell_event {nl event} {
197 # For `act' we *haven't* yet done the 750ms delay; we implement
198 # that here. Also, here we turn `talk' into `talk' now and `act'
199 # later. We also support the psuedo-event `none'. The del msg
200 # and new msg events are handled by the command procedures, not here.
201 global calling_nick
202 if {[info exists calling_nick]} { set save $calling_nick }
203 set r DELAYED
204 switch -exact $event {
205 none { }
206 talk {
207 tell_event_core $nl talk
208 tell_event $nl act
209 }
210 act {
211 after 750 [list tell_event_core $nl $event]
212 }
213 ident - msgsarrive {
214 tell_event_core $nl $event
215 }
216 tellme {
217 set r [tell_event_core $nl TELLME]
218 }
219 default {
220 error "tell_event $nl $event"
221 }
222 }
223 if {[info exists save]} { set calling_nick $save }
224 return $r
225}
226
227proc tell_event_core {nl event} {
228 global tell_event_teventi errorInfo
229 set tell_event_teventi "*$event* $nl"
230 if {[catch {
231 tell_event_core1 $nl $event
232 } emsg]} {
233 log_intern "tell event error" "$emsg >$errorInfo<"
234 set emsg ERROR
235 } else {
236 log_intern "tell event" "done $tell_event_teventi $emsg"
237 }
238 return $emsg
239}
240
241proc tell_event_core1 {nl event} {
242 # event is `talk', `act', `ident', `msgsarrive' or `TELLME'
243 # When user talks we actually get talk now and act later
244 global calling_nick
245 set calling_nick $nl
246 set iml [msgsdb_get $nl inbound]
247 if {![llength $iml]} { return nomsgs }
248
249 set now [clock seconds]
250 tell_getcstate
251 set ago [expr {$now - $telling_when}]
252
253 # Now we have the components of a telling state
254 # u - nick_unique (unset if not visible)
255 # stt - state: undelivered, mentioned, passede
256 # ago - how long ago since we did anything
257
258 # We compute an evstate to dispatch on as follows:
259
260 # evstate is string of letters
261 # current state
262 # u UNDELIVERED (MESSAGES)
263 # m MENTIONED
264 # p PASSED
265 # event
266 # t talk
267 # a act
268 # i ident
269 # m msgsarrive
270 # T tellme (user command)
271 # security level and timing
272 # ii Insecure
273 # ss Secure and soon (before interval)
274 # sl Secure and late (after interval)
275 # current identification
276 # i Identified
277 # u Unidentified
278 # reliability and timing
279 # uu Unreliable
280 # rv Remind, very soon (before within-interval)
281 # rs Remind, soon (between)
282 # rl Remind, late (after every-interval)
283 # ps Pester, soon (before interval)
284 # pl Pester, late (after interval)
285
286 set evstate {}
287
288 append evstate [string range $stt 0 0]
289 append evstate [string range $event 0 0]
290
291 manyset [nickdb_get_sec_effective $nl] sec secwhen
292 switch -exact $sec {
293 insecure { append evstate ii }
294 secure { append evstate [expr {$ago<$secwhen ? "ss" : "sl"}] }
295 default { append evstate "#$sec#" }
296 }
297
298 upvar #0 nick_username($nl) nu
299 if {[info exists nu] && "$nu" == "[nickdb_get_username $nl]"} {
300 append evstate i
301 } else {
302 append evstate u
303 }
304
305 manyset [nickdb_get $nl tellrel] rel relint relwithin
306 switch -exact $rel {
307 unreliable { append evstate uu }
308 remind { append evstate [expr {
309 $ago<$relwithin ? "rv" : $ago<$relint ? "rs" : "rl"
310 }]}
311 pester { append evstate [expr {$ago<$relint ? "ps" : "pl"}] }
312 default { append evstate "#$rel#" }
313 }
314
315 global tell_event_teventi
316 set tell_event_teventi "$evstate $ago $nl"
317 switch -glob $evstate {
318 pt???rv {
319 # consider delivered:
320 # (very recently passed, and the user talks)
321 set ndel [tell_delete_msgs {} $nl]
322 sendprivmsg $nl \
323 "I'm assuming you got the $ndel message(s) I just passed on."
324 return delivered
325 }
326 pm????? {
327 # oops, messages passed are now out of date
328 catch_restoreei { unset telling }
329 return reset
330 }
331 ?m????? {
332 # ignore new msgs if we haven't passed yet
333 return ignorenew
334 }
335 ut????? - mt????? -
336 pt???uu - pt???rs - pt???rl - pt???p? {
337 # ignore (any other `talk's) - act handles these
338 return ignoretalk
339 }
340 ui????? -
341 uaii?uu - uaii??l - uas?iuu - uas?i?l -
342 mi????? - pa????l -
343 ?Tii??? - ?Ts?i?? {
344 # pass and then stuff
345 if {[llength $iml] == 3} {
346 manyset $iml sender sentwhen msg
347 sendprivmsg $nl \
348 "$sender asked me, [showinterval [expr {$now-$sentwhen}]],\
349 to tell you: $msg"
350 } else {
351 sendprivmsg $nl \
352 "I have [expr {[llength $iml]/3}] messages for you:"
353 while {[llength $iml] >= 3} {
354 manyset [lrange $iml 0 2] sender sentwhen msg
355 set iml [lrange $iml 3 end]
356 sendprivmsg $nl \
357 " [showintervalsecs [expr {$now-$sentwhen}] 1] <$sender> $msg"
358 }
359 }
360 if {"$rel" == "unreliable"} {
361 tell_delete_msgs {} $nl
362 return toldunreliable
363 }
364 set stt passed
365 set re passed
366 }
367 uaslu?? {
368 sendprivmsg $nl {You have messages (so identify yourself please).}
369 set stt mentioned
370 set re mentioned
371 }
372 ?Ts?u?? {
373 sendprivmsg $nl {You must identify yourself to see your messages.}
374 return ignoreuitm
375 }
376 masl??? {
377 sendprivmsg $nl {Don't forget about your messages.}
378 return remind
379 }
380 pi????? {
381 return ignorepi
382 }
383 mass??? - pa????v - pa????s -
384 uaii??v - uaii??s -
385 uas?i?v - uas?i?s -
386 uassu?? {
387 # too soon
388 return ignoresoon
389 }
390 * {
391 error "tell_event_core nl=$nl evstate=$evstate ?"
392 }
393 }
394 if {![info exists u]} {
395 set telling [list {} undelivered $now]
396 } else {
397 set telling [list $u $stt $now]
398 }
399 return $re
400}
401
402proc recordlastseen_n {n how here} {
403 # here is:
404 # 0 - nick was seen leaving (or changing to another nicks or some such)
405 # 1 - nick was seen doing something else
406 # 2 - nick was seen talking on channel
407 global lastseen lookedfor
408 set nl [irctolower $n]
409 set now [clock seconds]
410 set lastseen($nl) [list $n $now $how]
411
412 if {!$here} return
413
414 tell_event $nl [lindex {none act talk} $here]
415
416 upvar #0 lookedfor($nl) lf
417 if {[info exists lf]} {
418 switch -exact [llength $lf] {
419 0 {
420 set ml {}
421 }
422 1 {
423 manyset [lindex $lf 0] when who where
424 set ml [list \
425 "FYI, $who was looking for you [looking_whenwhere $when $where]."]
426 }
427 default {
428 msg_begin tosend $n "FYI, people have been looking for you:"
429 set i 0
430 set fin ""
431 foreach e $lf {
432 incr i
433 if {$i == 1} {
434 msg_append tosend " "
435 } elseif {$i == [llength $lf]} {
436 msg_append tosend " and "
437 set fin .
438 } else {
439 msg_append tosend ", "
440 }
441 manyset $e when who where
442 msg_append tosend \
443 "$who ([looking_whenwhere $when $where])$fin"
444 }
445 set ml [msg_finish tosend]
446 }
447 }
448 unset lf
449 msendprivmsg_delayed 1000 $n $ml
450 }
451}
452
453proc note_topic {showoff whoby topic} {
454 set msg "FYI, $whoby has changed the topic on $showoff"
455 if {[string length $topic] < 160} {
456 append msg " to $topic"
457 } else {
458 append msg " but it is too long to reproduce here !"
459 }
460 set showoff [irctolower $showoff]
461 set tell [chandb_get $showoff topictell]
462 if {[lsearch -exact $tell *] >= 0} {
463 set tryspies [chandb_list]
464 } else {
465 set tryspies $tell
466 }
467 foreach spy $tryspies {
468 set see [chandb_get $spy topicsee]
469 if {[lsearch -exact $see $showoff] >= 0 || \
470 ([lsearch -exact $see *] >= 0 && \
471 [lsearch -exact $tell $spy] >= 0)} {
472 sendprivmsg $spy $msg
473 }
474 }
475}
476
477proc recordlastseen_p {p how here} {
478 prefix_nick
479 recordlastseen_n $n $how $here
480}
481
482proc chanmode_arg {} {
483 upvar 2 args cm_args
484 set rv [lindex $cm_args 0]
485 set cm_args [lreplace cm_args 0 0]
486 return $rv
487}
488
489proc chanmode_o1 {m g p chan} {
490 global nick chan_initialop
491 prefix_nick
492 set who [chanmode_arg]
493 recordlastseen_n $n "being nice to $who" 1
494 if {"[irctolower $who]" == "[irctolower $nick]"} {
495 set nlower [irctolower $n]
496 upvar #0 nick_unique($nlower) u
497 if {[chandb_exists $chan]} {
498 sendprivmsg $n Thanks.
499 } elseif {![info exists u]} {
500 sendprivmsg $n {Op me while not on the channel, why don't you ?}
501 } else {
502 set chan_initialop([irctolower $chan]) $u
503 sendprivmsg $n \
504 "Thanks. You can use `channel manager ...' to register this channel."
505 if {![string length [nickdb_get_username $n username]]} {
506 sendprivmsg $n \
507 "(But to do that you must register your nick securely first.)"
508 }
509 }
510 }
511}
512
513proc chanmode_o0 {m g p chan} {
514 global nick chandeop
515 prefix_nick
516 set who [chanmode_arg]
517 recordlastseen_p $p "being mean to $who" 1
518 if {"[irctolower $who]" == "[irctolower $nick]"} {
519 set chandeop($chan) [list [clock seconds] $p]
520 }
521}
522
523proc msg_MODE {p c dest modelist args} {
524 if {![ischan $dest]} return
525 if {[regexp {^\-(.+)$} $modelist dummy modelist]} {
526 set give 0
527 } elseif {[regexp {^\+(.+)$} $modelist dummy modelist]} {
528 set give 1
529 } else {
530 error "invalid modelist"
531 }
532 foreach m [split $modelist] {
533 set procname chanmode_$m$give
534 if {[catch { info body $procname }]} {
535 recordlastseen_p $p "fiddling with $dest" 1
536 } else {
537 $procname $m $give $p $dest
538 }
539 }
540}
541
542proc leaving {lchan} {
543 foreach luser [array names nick_onchans] {
544 upvar #0 nick_onchans($luser) oc
545 set oc [grep tc {"$tc" != "$lchan"} $oc]
546 }
547 upvar #0 chan_nicks($lchan) nlist
548 unset nlist
549 upvar #0 chan_lastactivity($lchan) la
550 catch { unset la }
551}
552
553proc doleave {lchan} {
554 sendout PART $lchan
555 leaving $lchan
556}
557
558proc dojoin {lchan} {
559 global chan_nicks
560 sendout JOIN $lchan
561 set chan_nicks($lchan) {}
562}
563
564proc check_justme {lchan} {
565 global nick
566 upvar #0 chan_nicks($lchan) nlist
567 if {[llength $nlist] != 1} return
568 if {"[lindex $nlist 0]" != "[irctolower $nick]"} return
569 if {[chandb_exists $lchan]} {
570 set mode [chandb_get $lchan mode]
571 if {"$mode" != "*"} {
572 sendout MODE $lchan $mode
573 }
574 set topic [chandb_get $lchan topicset]
575 if {[string length $topic]} {
576 sendout TOPIC $lchan $topic
577 }
578 } else {
579 doleave $lchan
580 }
581}
582
583proc process_kickpart {chan user} {
584 global nick
585 check_nick $user
586 set luser [irctolower $user]
587 set lchan [irctolower $chan]
588 if {![ischan $chan]} { error "not a channel" }
589 if {"$luser" == "[irctolower $nick]"} {
590 leaving $lchan
591 } else {
592 upvar #0 nick_onchans($luser) oc
593 upvar #0 chan_nicks($lchan) nlist
594 set oc [grep tc {"$tc" != "$lchan"} $oc]
595 set nlist [grep tn {"$tn" != "$luser"} $nlist]
596 nick_case $user
597 if {![llength $oc]} {
598 nick_forget $luser
599 } else {
600 check_justme $lchan
601 }
602 }
603}
604
605proc msg_TOPIC {p c dest topic} {
606 prefix_nick
607 if {![ischan $dest]} return
608 recordlastseen_n $n "changing the topic on $dest" 1
609 note_topic [irctolower $dest] $n $topic
610}
611
612proc msg_KICK {p c chans users comment} {
613 set chans [split $chans ,]
614 set users [split $users ,]
615 if {[llength $chans] > 1} {
616 foreach chan $chans user $users { process_kickpart $chan $user }
617 } else {
618 foreach user $users { process_kickpart [lindex $chans 0] $user }
619 }
620}
621
622proc msg_KILL {p c user why} {
623 nick_forget $user
624}
625
626set nick_counter 0
627set nick_arys {onchans username unique}
628# nick_onchans($luser) -> [list ... $lchan ...]
629# nick_username($luser) -> <securely known local username>
630# nick_unique($luser) -> <includes-counter>
631# nick_case($luser) -> $user (valid even if no longer visible)
632# nick_markid($luser) -> <after id for marktime>
633# nick_telling($luser) -> <unique> mentioned|passed <when>
634
635# chan_nicks($lchan) -> [list ... $luser ...]
636# chan_lastactivity($lchan) -> [clock seconds]
637
638proc lnick_forget {luser} {
639 global nick_arys chan_nicks
640 lnick_marktime_cancel $luser
641 foreach ary $nick_arys {
642 upvar #0 nick_${ary}($luser) av
643 catch { unset av }
644 }
645 foreach lch [array names chan_nicks] {
646 upvar #0 chan_nicks($lch) nlist
647 set nlist [grep tn {"$tn" != "$luser"} $nlist]
648 check_justme $lch
649 }
650}
651
652proc nick_forget {user} {
653 global nick_arys chan_nicks
654 lnick_forget [irctolower $user]
655 nick_case $user
656}
657
658proc nick_case {user} {
659 global nick_case
660 set nick_case([irctolower $user]) $user
661}
662
663proc msg_NICK {p c newnick} {
664 global nick_arys nick_case calling_nick
665 prefix_nick
666 recordlastseen_n $n "changing nicks to $newnick" 0
667 set calling_nick $newnick
668 recordlastseen_n $newnick "changing nicks from $n" 1
669 set luser [irctolower $n]
670 lnick_marktime_cancel $luser
671 set lusernew [irctolower $newnick]
672 foreach ary $nick_arys {
673 upvar #0 nick_${ary}($luser) old
674 upvar #0 nick_${ary}($lusernew) new
675 if {[info exists new]} { error "nick collision ?! $ary $n $newnick" }
676 if {[info exists old]} { set new $old; unset old }
677 }
678 upvar #0 nick_onchans($lusernew) oc
679 foreach ch $oc {
680 upvar #0 chan_nicks($ch) nlist
681 set nlist [grep tn {"$tn" != "$luser"} $nlist]
682 lappend nlist $lusernew
683 }
684 lnick_marktime_start $lusernew "Hi." 500 1
685 nick_case $newnick
686}
687
688proc nick_ishere {n} {
689 global nick_counter
690 upvar #0 nick_unique([irctolower $n]) u
691 if {![info exists u]} { set u [incr nick_counter].$n.[clock seconds] }
692 nick_case $n
693}
694
695proc msg_JOIN {p c chan} {
696 prefix_nick
697 nick_ishere $n
698 recordlastseen_n $n "joining $chan" 1
699 set nl [irctolower $n]
700 set lchan [irctolower $chan]
701 upvar #0 nick_onchans($nl) oc
702 upvar #0 chan_nicks($lchan) nlist
703 if {![info exists oc]} {
704 global marktime_join_startdelay
705 lnick_marktime_start $nl "Welcome." $marktime_join_startdelay 1
706 }
707 lappend oc $lchan
708 lappend nlist $nl
709}
710proc msg_PART {p c chan args} {
711 prefix_nick
712 set msg "leaving $chan"
713 if {[llength $args]} {
714 set why [lindex $args 0]
715 if {"[irctolower $why]" != "[irctolower $n]"} { append msg " ($why)" }
716 }
717 recordlastseen_n $n $msg 1
718 process_kickpart $chan $n
719}
720proc msg_QUIT {p c why} {
721 prefix_nick
722 recordlastseen_n $n "leaving ($why)" 0
723 nick_forget $n
724}
725
726proc msg_PRIVMSG {p c dest text} {
727 global errorCode
728
729 prefix_nick
730 if {[ischan $dest]} {
731 recordlastseen_n $n "invoking me in $dest" 1
732 set output $dest
733 } else {
734 recordlastseen_n $n "talking to me" 1
735 set output $n
736 }
737 nick_case $n
738
739 execute_usercommand $p $c $n $output $dest $text
740}
741
742proc msg_INVITE {p c n chan} {
743 after 1000 [list dojoin [irctolower $chan]]
744}
745
746proc grep {var predicate list} {
747 set o {}
748 upvar 1 $var v
749 foreach v $list {
750 if {[uplevel 1 [list expr $predicate]]} { lappend o $v }
751 }
752 return $o
753}
754
755proc msg_353 {p c dest type chan nicklist} {
756 global names_chans nick_onchans
757 set lchan [irctolower $chan]
758 upvar #0 chan_nicks($lchan) nlist
759 lappend names_chans $lchan
760 if {![info exists nlist]} {
761 # We don't think we're on this channel, so ignore it !
762 # Unfortunately, because we don't get a reply to PART,
763 # we have to remember ourselves whether we're on a channel,
764 # and ignore stuff if we're not, to avoid races. Feh.
765 return
766 }
767 set nlist_new {}
768 foreach user [split $nicklist { }] {
769 regsub {^[@+]} $user {} user
770 if {![string length $user]} continue
771 check_nick $user
772 set luser [irctolower $user]
773 upvar #0 nick_onchans($luser) oc
774 lappend oc $lchan
775 lappend nlist_new $luser
776 nick_ishere $user
777 }
778 set nlist $nlist_new
779}
780
781proc msg_366 {p c args} {
782 global names_chans nick_onchans
783 set lchan [irctolower $c]
784 foreach luser [array names nick_onchans] {
785 upvar #0 nick_onchans($luser) oc
786 if {[llength names_chans] > 1} {
787 set oc [grep tc {[lsearch -exact $tc $names_chans] >= 0} $oc]
788 }
789 if {![llength $oc]} { lnick_forget $n }
790 }
791 unset names_chans
792}
793
794proc check_username {target} {
795 if {
796 [string length $target] > 8 ||
797 [regexp {[^-0-9a-z]} $target] ||
798 ![regexp {^[a-z]} $target]
799 } { error "invalid username" }
800}
801
802proc somedb__head {} {
803 uplevel 1 {
804 set idl [irctolower $id]
805 upvar #0 ${nickchan}db($idl) ndbe
806 binary scan $idl H* idh
807 set idfn $fprefix$idh
808 if {![info exists iddbe] && [file exists $idfn]} {
809 set f [open $idfn r]
810 try_except_finally { set newval [read $f] } {} { close $f }
811 if {[llength $newval] % 2} { error "invalid length" }
812 set iddbe $newval
813 }
814 }
815}
816
817proc def_somedb {name arglist body} {
818 foreach {nickchan fprefix} {
819 nick users/n
820 chan chans/c
821 msgs users/m
822 } {
823 proc ${nickchan}db_$name $arglist \
824 "set nickchan $nickchan; set fprefix $fprefix; $body"
825 }
826}
827
828def_somedb list {} {
829 set list {}
830 foreach path [glob -nocomplain -path $fprefix *] {
831 binary scan $path "A[string length $fprefix]A*" afprefix thinghex
832 if {"$afprefix" != "$fprefix"} { error "wrong prefix $path $afprefix" }
833 lappend list [binary format H* $thinghex]
834 }
835 return $list
836}
837
838proc def_somedb_id {name arglist body} {
839 def_somedb $name [concat id $arglist] "somedb__head; $body"
840}
841
842def_somedb_id exists {} {
843 return [info exists iddbe]
844}
845
846def_somedb_id delete {} {
847 catch { unset iddbe }
848 file delete $idfn
849}
850
851set default_settings_nick {
852 timeformat ks
853 marktime off
854 tellsec {secure 600}
855 tellrel {remind 3600 30}
856}
857
858set default_settings_chan {
859 autojoin 1
860 mode *
861 userinvite pub
862 topicset {}
863 topicsee {}
864 topictell {}
865}
866
867set default_settings_msgs {
868 inbound {}
869 outbound {}
870}
871# inbound -> [<nick> <time_t> <message>] ...
872# outbound -> [<nick> <time_t(earliest)> <count>] ...
873# neither are sorted particularly; only one entry per recipient in
874# output; both sender and recipient are cased
875
876def_somedb_id set {args} {
877 upvar #0 default_settings_$nickchan def
878 if {![info exists iddbe]} { set iddbe $def }
879 foreach {key value} [concat $iddbe $args] { set a($key) $value }
880 set newval {}
881 foreach {key value} [array get a] { lappend newval $key $value }
882 set f [open $idfn.new w]
883 try_except_finally {
884 puts $f $newval
885 close $f
886 file rename -force $idfn.new $idfn
887 } {
888 } {
889 catch { close $f }
890 }
891 set iddbe $newval
892}
893
894def_somedb_id get {key} {
895 upvar #0 default_settings_$nickchan def
896 if {[info exists iddbe]} {
897 set l [concat $iddbe $def]
898 } else {
899 set l $def
900 }
901 foreach {tkey value} $l {
902 if {"$tkey" == "$key"} { return $value }
903 }
904 error "unset setting $key"
905}
906
907proc opt {key} {
908 global calling_nick
909 if {[info exists calling_nick]} { set n $calling_nick } { set n {} }
910 return [nickdb_get $n $key]
911}
912
913proc check_notonchan {} {
914 upvar 1 dest dest
915 if {[ischan $dest]} { usererror "That command must be sent privately." }
916}
917
918proc nick_securitycheck {strict} {
919 upvar 1 n n
920 if {![nickdb_exists $n]} {
921 usererror "You are unknown to me, use `register'."
922 }
923 set wantu [nickdb_get $n username]
924 if {![string length $wantu]} {
925 if {$strict} {
926 usererror "That feature is only available to secure users, sorry."
927 } else {
928 return
929 }
930 }
931 set luser [irctolower $n]
932 upvar #0 nick_username($luser) nu
933 if {![info exists nu]} {
934 usererror "Nick $n is secure, you must identify yourself first."
935 }
936 if {"$wantu" != "$nu"} {
937 usererror "You are the wrong user -\
938 the nick $n belongs to $wantu, not $nu."
939 }
940}
941
942proc channel_ismanager {channel n} {
943 set mgrs [chandb_get $channel managers]
944 return [expr {[lsearch -exact [irctolower $mgrs] [irctolower $n]] >= 0}]
945}
946
947proc channel_securitycheck {channel} {
948 upvar n n
949 if {![channel_ismanager $channel $n]} {
950 usererror "You are not a manager of $channel."
951 }
952 nick_securitycheck 1
953}
954
955proc def_chancmd {name body} {
956 proc channel/$name {} \
957 " upvar 1 target chan; upvar 1 n n; upvar 1 text text; $body"
958}
959
960proc ta_listop {findnow procvalue} {
961 # findnow and procvalue are code fragments which will be executed
962 # in the caller's level. findnow should set ta_listop_ev to
963 # the current list, and procvalue should treat ta_listop_ev as
964 # a proposed value in the list and check and possibly modify
965 # (canonicalise?) it. After ta_listop, ta_listop_ev will
966 # be the new value of the list.
967 upvar 1 ta_listop_ev exchg
968 upvar 1 text text
969 set opcode [ta_word]
970 switch -exact _$opcode {
971 _= { }
972 _+ - _- {
973 uplevel 1 $findnow
974 foreach item $exchg { set array($item) 1 }
975 }
976 default {
977 error "list change opcode must be one of + - ="
978 }
979 }
980 foreach exchg [split $text " "] {
981 if {![string length $exchg]} continue
982 uplevel 1 $procvalue
983 if {"$opcode" != "-"} {
984 set array($exchg) 1
985 } else {
986 catch { unset array($exchg) }
987 }
988 }
989 set exchg [lsort [array names array]]
990}
991
992def_chancmd manager {
993 ta_listop {
994 if {[chandb_exists $chan]} {
995 set ta_listop_ev [chandb_get $chan managers]
996 } else {
997 set ta_listop_ev [list [irctolower $n]]
998 }
999 } {
1000 check_nick $ta_listop_ev
1001 set ta_listop_ev [irctolower $ta_listop_ev]
1002 }
1003 if {[llength $ta_listop_ev]} {
1004 chandb_set $chan managers $ta_listop_ev
1005 ucmdr "Managers of $chan: $ta_listop_ev" {}
1006 } else {
1007 chandb_delete $chan
1008 ucmdr {} {} "forgets about managing $chan." {}
1009 }
1010}
1011
1012def_chancmd autojoin {
1013 set yesno [ta_word]
1014 switch -exact [string tolower $yesno] {
1015 no { set nv 0 }
1016 yes { set nv 1 }
1017 default { error "channel autojoin must be `yes' or `no' }
1018 }
1019 chandb_set $chan autojoin $nv
1020 ucmdr [expr {$nv ? "I will join $chan when I'm restarted " : \
1021 "I won't join $chan when I'm restarted "}] {}
1022}
1023
1024def_chancmd userinvite {
1025 set nv [string tolower [ta_word]]
1026 switch -exact $nv {
1027 pub { set txt "!invite will work for $chan, but it won't work by /msg" }
1028 here { set txt "!invite and /msg invite will work, but only for users who are already on $chan." }
1029 all { set txt "Any user will be able to invite themselves or anyone else to $chan." }
1030 none { set txt "I will not invite anyone to $chan." }
1031 default {
1032 error "channel userinvite must be `pub', `here', `all' or `none'
1033 }
1034 }
1035 chandb_set $chan userinvite $nv
1036 ucmdr $txt {}
1037}
1038
1039def_chancmd topic {
1040 set what [ta_word]
1041 switch -exact $what {
1042 leave {
1043 ta_nomore
1044 chandb_set $chan topicset {}
1045 ucmdr "I won't ever change the topic of $chan." {}
1046 }
1047 set {
1048 set t [string trim $text]
1049 if {![string length $t]} {
1050 error "you must specific the topic to set"
1051 }
1052 chandb_set $chan topicset $t
1053 ucmdr "Whenever I'm alone on $chan, I'll set the topic to $t." {}
1054 }
1055 see - tell {
1056 ta_listop {
1057 set ta_listop_ev [chandb_get $chan topic$what]
1058 } {
1059 if {"$ta_listop_ev" != "*"} {
1060 if {![ischan $ta_listop_ev]} {
1061 error "bad channel \`$ta_listop_ev' in topic $what"
1062 }
1063 set ta_listop_ev [irctolower $ta_listop_ev]
1064 }
1065 }
1066 chandb_set $chan topic$what $ta_listop_ev
1067 ucmdr "Topic $what list for $chan: $ta_listop_ev" {}
1068 }
1069 default {
1070 usererror "Unknown channel topic subcommand - see help channel."
1071 }
1072 }
1073}
1074
1075def_chancmd mode {
1076 set mode [ta_word]
1077 if {"$mode" != "*" && ![regexp {^(([-+][imnpst]+)+)$} $mode mode]} {
1078 error {channel mode must be * or match ([-+][imnpst]+)+}
1079 }
1080 chandb_set $chan mode $mode
1081 if {"$mode" == "*"} {
1082 ucmdr "I won't ever change the mode of $chan." {}
1083 } else {
1084 ucmdr "Whenever I'm alone on $chan, I'll set the mode to $mode." {}
1085 }
1086}
1087
1088def_chancmd show {
1089 if {[chandb_exists $chan]} {
1090 set l "Settings for $chan: autojoin "
1091 append l [lindex {no yes} [chandb_get $chan autojoin]]
1092 append l ", mode " [chandb_get $chan mode]
1093 append l ", userinvite " [chandb_get $chan userinvite] "."
1094 append l "\nManagers: "
1095 append l [join [chandb_get $chan managers] " "]
1096 foreach {ts sep} {see "\n" tell " "} {
1097 set t [chandb_get $chan topic$ts]
1098 append l $sep
1099 if {[llength $t]} {
1100 append l "Topic $ts list: $t."
1101 } else {
1102 append l "Topic $ts list is empty."
1103 }
1104 }
1105 append l "\n"
1106 set t [chandb_get $chan topicset]
1107 if {[string length $t]} {
1108 append l "Topic to set: $t"
1109 } else {
1110 append l "I will not change the topic."
1111 }
1112 ucmdr {} $l
1113 } else {
1114 ucmdr {} "The channel $chan is not managed."
1115 }
1116}
1117
1118proc channelmgr_monoop {} {
1119 upvar 1 dest dest
1120 upvar 1 text text
1121 upvar 1 n n
1122 upvar 1 p p
1123 upvar 1 target target
1124 global chan_nicks
1125
1126 prefix_nick
1127
1128 if {[ischan $dest]} { set target $dest }
1129 if {[ta_anymore]} { set target [ta_word] }
1130 ta_nomore
1131 if {![info exists target]} {
1132 usererror "You must specify, or invoke me on, the relevant channel."
1133 }
1134 if {![info exists chan_nicks([irctolower $target])]} {
1135 usererror "I am not on $target."
1136 }
1137 if {![ischan $target]} { error "not a valid channel" }
1138
1139 if {![chandb_exists $target]} {
1140 usererror "$target is not a managed channel."
1141 }
1142 channel_securitycheck $target
1143}
1144
1145def_ucmd op {
1146 channelmgr_monoop
1147 sendout MODE $target +o $n
1148}
1149
1150def_ucmd leave {
1151 channelmgr_monoop
1152 doleave $target
1153}
1154
1155def_ucmd invite {
1156 global chan_nicks errorCode errorInfo
1157 prefix_nick
1158
1159 if {[ischan $dest]} {
1160 set target $dest
1161 set onchan 1
1162 } else {
1163 set target [ta_word]
1164 set onchan 0
1165 }
1166 set ltarget [irctolower $target]
1167 if {![ischan $target]} { error "$target is not a channel" }
1168 if {![info exists chan_nicks($ltarget)]} {
1169 usererror "I am not on $target."
1170 }
1171 set ui [chandb_get $ltarget userinvite]
1172 if {[catch {
1173 if {"$ui" == "pub" && !$onchan} {
1174 usererror "Invitations to $target must be made there with !invite."
1175 }
1176 if {"$ui" != "all"} {
1177 if {[lsearch -exact $chan_nicks($ltarget) [irctolower $n]] < 0} {
1178 usererror "Invitations to $target may only be made\
1179 by a user on the channel."
1180 }
1181 }
1182 if {"$ui" == "none"} {
1183 usererror "Sorry, I've not been authorised\
1184 to invite people to $target."
1185 }
1186 } emsg]} {
1187 if {"$errorCode" == "BLIGHT USER" && [channel_ismanager $target $n]} {
1188 if {[catch {
1189 nick_securitycheck 1
1190 } emsg2]} {
1191 if {"$errorCode" == "BLIGHT USER"} {
1192 usererror "$emsg2 Therefore you can't use your\
1193 channel manager privilege. $emsg"
1194 } else {
1195 error $error $errorInfo $errorCode
1196 }
1197 }
1198 } else {
1199 error $emsg $errorInfo $errorCode
1200 }
1201 }
1202 if {![ta_anymore]} {
1203 usererror "You have to say who to invite."
1204 }
1205 set invitees {}
1206 while {[ta_anymore]} {
1207 set invitee [ta_nick]
1208 lappend invitees $invitee
1209 }
1210 foreach invitee $invitees {
1211 sendout INVITE $invitee $ltarget
1212 }
1213 set who [lindex $invitees 0]
1214 switch -exact llength $invitees {
1215 0 { error "zero invitees" }
1216 1 { }
1217 2 { append who " and [lindex $invitees 1]" }
1218 * {
1219 set who [join [lreplace $invitees end end] ", "]
1220 append who " and [lindex $invitees [llength $invitees]]"
1221 }
1222 }
1223 ucmdr {} {} {} "invites $who to $target."
1224}
1225
1226def_ucmd channel {
1227 if {[ischan $dest]} { set target $dest }
1228 if {![ta_anymore]} {
1229 set subcmd show
1230 } else {
1231 set subcmd [ta_word]
1232 }
1233 if {[ischan $subcmd]} {
1234 set target $subcmd
1235 if {![ta_anymore]} {
1236 set subcmd show
1237 } else {
1238 set subcmd [ta_word]
1239 }
1240 }
1241 if {![info exists target]} { error "privately, you must specify a channel" }
1242 set procname channel/$subcmd
1243 if {"$subcmd" != "show"} {
1244 if {[catch { info body $procname }]} {
1245 usererror "unknown channel setting $subcmd."
1246 }
1247 prefix_nick
1248 if {[chandb_exists $target]} {
1249 channel_securitycheck $target
1250 } else {
1251 nick_securitycheck 1
1252 upvar #0 chan_initialop([irctolower $target]) io
1253 upvar #0 nick_unique([irctolower $n]) u
1254 if {![info exists io]} {
1255 usererror "$target is not a managed channel."
1256 }
1257 if {"$io" != "$u"} {
1258 usererror "You are not the interim manager of $target."
1259 }
1260 if {"$subcmd" != "manager"} {
1261 usererror "Please use `channel manager' first."
1262 }
1263 }
1264 }
1265 channel/$subcmd
1266}
1267
1268proc nickdb_get_username {n} {
1269 if {![nickdb_exists $n]} { return "" }
1270 return [nickdb_get $n username]
1271}
1272
1273proc nickdb_get_sec_effective {n} {
1274 set l [nickdb_get $n tellsec]
1275 set u [nickdb_get_username $n]
1276 if {"[lindex $l 0]" == "secure" && ![string length $u]} { set l insecure }
1277 return $l
1278}
1279
1280proc tell_peernicks {text} {
1281 global errorInfo errorCode
1282 set text [irctolower [string trim $text]]
1283 set senders [split $text " "]
1284 foreach sender $senders {
1285 if {[catch { check_nick $sender } emsg]} {
1286 error "invalid nick `$sender': $emsg" $errorInfo $errorCode
1287 }
1288 }
1289 return $senders
1290}
1291
1292proc msgsdb_set_maydelete {n key l otherkey} {
1293 msgsdb_set $n $key $l
1294 if {[llength $l]} return
1295 if {[llength [msgsdb_get $n $otherkey]]} return
1296 msgsdb_delete $n
1297}
1298
1299proc tell_delete_msgs {lsenders lrecip} {
1300 set ninbound {}
1301 set ndel 0
1302 foreach {s t m} [msgsdb_get $lrecip inbound] {
1303 if {[llength $lsenders]} {
1304 if {[lsearch -exact $lsenders [irctolower $s]] == -1} {
1305 lappend ninbound $s $t $m
1306 continue
1307 }
1308 }
1309 set rsenders($s) 1
1310 incr ndel
1311 }
1312 msgsdb_set_maydelete $lrecip inbound $ninbound outbound
1313 if {![llength $ninbound]} {
1314 upvar #0 nick_telling($lrecip) telling
1315 catch { unset telling }
1316 }
1317 foreach s [array names rsenders] {
1318 set noutbound {}
1319 foreach {r t c} [msgsdb_get $s outbound] {
1320 if {"[irctolower $r]" == "$lrecip"} continue
1321 lappend noutbound $r $t $c
1322 }
1323 msgsdb_set_maydelete $s outbound $noutbound inbound
1324 }
1325 return $ndel
1326}
1327
1328def_ucmd untell {
1329 prefix_nick
1330 check_notonchan
1331 nick_securitycheck 0
1332 set recipients [tell_peernicks $text]
1333 if {![llength $recipients]} {
1334 usererror "You must say which recipients' messages from you to forget."
1335 }
1336 set ndel 0
1337 foreach recip $recipients {
1338 incr ndel [tell_delete_msgs [irctolower $n] $recip]
1339 }
1340 ucmdr "Removed $ndel as yet undelivered message(s)." {}
1341}
1342
1343def_ucmd_alias delmsgs delmsg
1344def_ucmd delmsg {
1345 global errorInfo errorCode
1346 prefix_nick
1347 set nl [irctolower $n]
1348 check_notonchan
1349 manyset [nickdb_get_sec_effective $n] sec secwhen
1350 switch -exact $sec {
1351 insecure { }
1352 reject - mailto {
1353 usererror \
1354 "There are no messages to delete\
1355 because your message disposition prevents them from being left."
1356 }
1357 secure {
1358 nick_securitycheck 1
1359 }
1360 default {
1361 error "delmsg sec $sec"
1362 }
1363 }
1364 if {![llength [msgsdb_get $n inbound]]} {
1365 ucmdr "No incoming messages to delete." {}
1366 }
1367 tell_getcstate
1368 if {![info exists u]} {
1369 usererror \
1370 "I can't delete your messages unless I can see you on a channel with me.\
1371 Otherwise I might delete a message I hadn't told you about yet."
1372 }
1373 if {"$stt" != "passed"} {
1374 set telling [list $u undelivered 0]
1375 usererror \
1376 "There are message(s) you may not yet have seen;\
1377 I'll deliver them to you now.\
1378 If you actually want to delete them, just tell me `delmsg' again."
1379 }
1380 set senders [tell_peernicks $text]
1381 set ndel [tell_delete_msgs [irctolower $senders] [irctolower $n]]
1382 if {!$ndel} {
1383 if {[llength $senders]} {
1384 ucmdr "No relevant incoming messages to delete." {}
1385 }
1386 }
1387 switch -exact [llength $senders] {
1388 0 { ucmdr {} {} "deletes your $ndel message(s)." }
1389 1 { ucmdr {} {} "deletes your $ndel message(s) from $senders." }
1390 default {
1391 ucmdr {} {} "deletes your $ndel message(s) from\
1392 [lreplace $senders end end] and/or [lindex $senders end]."
1393 }
1394 }
1395}
1396
1397def_ucmd tellme {
1398 prefix_nick
1399 ta_nomore
1400 check_notonchan
1401 manyset [nickdb_get $n tellsec] sec
1402 switch -exact $sec {
1403 reject { ucmdr "But, you asked me to reject messages for you !" {} }
1404 mailto { ucmdr "But, you asked me to mail your messages to you !" {} }
1405 }
1406 switch -exact [tell_event [irctolower $n] tellme] {
1407 ERROR - INVALID { ucmdr {} {is ill. Help!} }
1408 nomsgs { ucmdr {You have no messages.} {} }
1409 default { }
1410 }
1411}
1412
1413def_ucmd tell {
1414 global nick_case ownmailaddr ownfullname
1415
1416 prefix_nick
1417 set target [ta_nick]
1418 if {![string length $text]} { error "tell them what?" }
1419 if {[string length $text] > 400} { error "message too long" }
1420
1421 set ltarget [irctolower $target]
1422 set ctarget $target
1423 if {[info exists nick_case($ltarget)]} { set ctarget $nick_case($ltarget) }
1424
1425 manyset [nickdb_get_sec_effective $target] sec mailtoint mailwhy
1426 manyset [nickdb_get $target tellrel] rel relint relwithin
1427 switch -exact $sec {
1428 insecure - secure {
1429 set now [clock seconds]
1430 set inbound [msgsdb_get $ltarget inbound]
1431 lappend inbound $n $now $text
1432 msgsdb_set $ltarget inbound $inbound
1433
1434 set outbound [msgsdb_get $n outbound]
1435 set noutbound {}
1436 set found 0
1437 foreach {recip time count} $outbound {
1438 if {"[irctolower $recip]" == "$ltarget"} {
1439 incr count
1440 set recip $ctarget
1441 set found 1
1442 }
1443 lappend noutbound $recip $time $count
1444 }
1445 if {!$found} {
1446 lappend noutbound $ctarget $now 1
1447 }
1448 msgsdb_set $n outbound $noutbound
1449 set msg "OK, I'll tell $ctarget"
1450 if {$found} { append msg " that too" }
1451 append msg ", "
1452 if {"$sec" != "secure"} {
1453 switch -exact $rel {
1454 unreliable { append msg "neither reliably nor securely" }
1455 remind { append msg "pretty reliably, but not securely" }
1456 pester { append msg "reliably but not securely" }
1457 }
1458 } else {
1459 switch -exact $rel {
1460 unreliable { append msg "securely but not reliably" }
1461 remind { append msg "securely and pretty reliably" }
1462 pester { append msg "reliably and securely" }
1463 }
1464 }
1465 append msg .
1466 tell_event $ltarget msgsarrive
1467 ucmdr $msg {}
1468 }
1469 mailto {
1470 set fmtmsg [exec fmt << " $text"]
1471 exec /usr/sbin/sendmail -odb -oi -t -oee -f $mailwhy \
1472 > /dev/null << \
1473 "From: $ownmailaddr ($ownfullname)
1474To: $mailtoint
1475Subject: IRC tell from $n
1476
1477$n asked me[expr {[ischan $dest] ? " on $dest" : ""}] to tell you:
1478[exec fmt << " $text"]
1479
1480(This message was for your nick $ctarget; your account $mailwhy
1481 arranged for it to be forwarded to $mailtoint.)
1482"
1483 ucmdr \
1484 "I've mailed $ctarget, which is what they prefer." \
1485 {}
1486 }
1487 reject {
1488 usererror "Sorry, $ctarget does not want me to take messages."
1489 }
1490 default {
1491 error "bad tellsec $sec"
1492 }
1493 }
1494}
1495
1496def_ucmd who {
1497 if {[ta_anymore]} {
1498 set target [ta_nick]; ta_nomore
1499 set myself 1
1500 } else {
1501 prefix_nick
1502 set target $n
1503 set myself [expr {"$target" != "$n"}]
1504 }
1505 set ltarget [irctolower $target]
1506 upvar #0 nick_case($ltarget) ctarget
1507 set nshow $target
1508 if {[info exists ctarget]} {
1509 upvar #0 nick_onchans($ltarget) oc
1510 upvar #0 nick_username($ltarget) nu
1511 if {[info exists oc]} { set nshow $ctarget }
1512 }
1513 if {![nickdb_exists $ltarget]} {
1514 set ol "$nshow is not a registered nick."
1515 } elseif {[string length [set username [nickdb_get $target username]]]} {
1516 set ol "The nick $nshow belongs to the user $username."
1517 } else {
1518 set ol "The nick $nshow is registered (but not to a username)."
1519 }
1520 if {![info exists ctarget] || ![info exists oc]} {
1521 if {$myself} {
1522 append ol "\nI can't see $nshow on anywhere."
1523 } else {
1524 append ol "\nYou aren't on any channels with me."
1525 }
1526 } elseif {![info exists nu]} {
1527 append ol "\n$nshow has not identified themselves."
1528 } elseif {![info exists username]} {
1529 append ol "\n$nshow has identified themselves as the user $nu."
1530 } elseif {"$nu" != "$username"} {
1531 append ol "\nHowever, $nshow is being used by the user $nu."
1532 } else {
1533 append ol "\n$nshow has identified themselves to me."
1534 }
1535 ucmdr {} $ol
1536}
1537
1538def_ucmd register {
1539 prefix_nick
1540 check_notonchan
1541 set old [nickdb_exists $n]
1542 if {$old} { nick_securitycheck 0 }
1543 set luser [irctolower $n]
1544 switch -exact [string tolower [string trim $text]] {
1545 {} {
1546 upvar #0 nick_username($luser) nu
1547 if {![info exists nu]} {
1548 ucmdr {} \
1549 "You must identify yourself before using `register'. See `help identify', or use `register insecure'."
1550 }
1551 nickdb_set $n username $nu
1552 ucmdr {} {} "makes a note of your username." {}
1553 }
1554 delete {
1555 nickdb_delete $n
1556 ucmdr {} {} "forgets your nickname." {}
1557 }
1558 insecure {
1559 nickdb_set $n username {}
1560 if {$old} {
1561 ucmdr {} "Security is now disabled for your nickname !"
1562 } else {
1563 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."
1564 }
1565 }
1566 default {
1567 error "you mean register / register delete / register insecure"
1568 }
1569 }
1570}
1571
1572proc timeformat_desc {tf} {
1573 switch -exact $tf {
1574 ks { return "Times will be displayed in seconds or kiloseconds." }
1575 hms { return "Times will be displayed in hours, minutes, etc." }
1576 beat { return "Times will be displayed in beats (1000B = 1d)." }
1577 default { error "invalid timeformat: $v" }
1578 }
1579}
1580
1581set settings {}
1582proc def_setting {opt show_body set_body} {
1583 global settings
1584 lappend settings $opt
1585 proc set_show/$opt {} "
1586 upvar 1 n n
1587 set opt $opt
1588 $show_body"
1589 if {![string length $set_body]} return
1590 proc set_set/$opt {} "
1591 upvar 1 n n
1592 upvar 1 text text
1593 set opt $opt
1594 $set_body"
1595}
1596
1597proc tellme_sec_desc {v n} {
1598 manyset $v sec mailtoint
1599 switch -exact $sec {
1600 insecure {
1601 return "I'll tell you your messages whenever I see you."
1602 }
1603 secure {
1604 if {[string length [nickdb_get_username $n]]} {
1605 return \
1606 "I'll keep the bodies of your messages private until you identify yourself, reminding you every [showintervalsecs $mailtoint 1]."
1607 } else {
1608 return \
1609 "I'll tell you your messages whenever I see you.\
1610 (Secure message delivery is enabled, but your nick is not registered\
1611 securely. See `help register'.)"
1612 }
1613 }
1614 reject {
1615 return "I shan't accept messages for you."
1616 }
1617 mailto {
1618 return "I'll forward your messages by email to $mailtoint."
1619 }
1620 default {
1621 error "bad tellsec $sec"
1622 }
1623 }
1624}
1625
1626proc tellme_rel_desc {v n} {
1627 manyset $v rel every within
1628 switch -exact $rel {
1629 unreliable {
1630 return "As soon as I've told you message(s), I'll forget them\
1631 - note that this means messages can get lost !"
1632 }
1633 pester {
1634 set u {}
1635 }
1636 remind {
1637 set u ", or talk on channel within [showintervalsecs $within 1] of me having told you"
1638 }
1639 default {
1640 error "bad tellrel $rel"
1641 }
1642 }
1643 return "After delivering messages, I'll remind you every\
1644 [showintervalsecs $every 1] until you say delmsg$u."
1645}
1646
1647def_setting timeformat {
1648 set tf [nickdb_get $n timeformat]
1649 return "$tf: [timeformat_desc $tf]"
1650} {
1651 set tf [string tolower [ta_word]]
1652 ta_nomore
1653 set desc [timeformat_desc $tf]
1654 nickdb_set $n timeformat $tf
1655 ucmdr {} $desc
1656}
1657
1658proc marktime_desc {mt} {
1659 if {"$mt" == "off"} {
1660 return "I will not send you periodic messages."
1661 } elseif {"$mt" == "once"} {
1662 return "I will send you one informational message when I see you."
1663 } else {
1664 return "I'll send you a message every [showintervalsecs $mt 0]."
1665 }
1666}
1667
1668def_setting marktime {
1669 set mt [nickdb_get $n marktime]
1670 set p $mt
1671 if {[string match {[0-9]*} $mt]} { append p s }
1672 append p ": "
1673 append p [marktime_desc $mt]
1674 return $p
1675} {
1676 global marktime_min
1677 set mt [string tolower [ta_word]]
1678 ta_nomore
1679
1680 if {"$mt" == "off" || "$mt" == "once"} {
1681 } else {
1682 set mt [parse_interval $mt $marktime_min]
1683 }
1684 nickdb_set $n marktime $mt
1685 lnick_marktime_start [irctolower $n] "So:" 500 0
1686 ucmdr {} [marktime_desc $mt]
1687}
1688
1689def_setting security {
1690 set s [nickdb_get $n username]
1691 if {[string length $s]} {
1692 return "Your nick, $n, is controlled by the user $s."
1693 } else {
1694 return "Your nick, $n, is not secure."
1695 }
1696} {}
1697
1698proc tellme_setting_sec_simple {} {
1699 uplevel 1 {
1700 ta_nomore
1701 set sr sec
1702 set v $setting
1703 }
1704}
1705
1706proc tellme_setting_neednomsgs {} {
1707 uplevel 1 {
1708 if {[llength [msgsdb_get $n inbound]]} {
1709 usererror "You must delete the incoming messages you have, first."
1710 }
1711 }
1712}
1713
1714def_setting tellme {
1715 set secv [nickdb_get $n tellsec]
1716 set ms [tellme_sec_desc $secv $n]
1717 manyset $secv sec
1718 switch -exact $sec {
1719 insecure - secure {
1720 set mr [tellme_rel_desc [nickdb_get $n tellrel] $n]
1721 return "$ms $mr"
1722 }
1723 reject - mailto {
1724 return $ms
1725 }
1726 }
1727} {
1728 set setting [string tolower [ta_word]]
1729 set nl [irctolower $n]
1730 switch -exact $setting {
1731 insecure {
1732 tellme_setting_sec_simple
1733 }
1734 secure {
1735 set every [ta_interval_optional 60 600]
1736 ta_nomore
1737 set sr sec
1738 set v [list secure $every]
1739 }
1740 reject {
1741 tellme_setting_neednomsgs
1742 tellme_setting_sec_simple
1743 }
1744 mailto {
1745 tellme_setting_neednomsgs
1746
1747 upvar #0 nick_username($nl) nu
1748 if {!([info exists nu] && [string length $nu])} {
1749 usererror \
1750 "Sorry, you must register securely to have your messages mailed\
1751 (to prevent the use of this feature for spamming). See `help register'."
1752 }
1753 set sr sec
1754 set v [list mailto [ta_word] $nu]
1755 }
1756 unreliable - pester - remind {
1757 manyset [nickdb_get $n tellsec] sec
1758 switch -exact $sec {
1759 reject - mailto {
1760 usererror \
1761 "Sorry, I shan't change when I'll consider a message delivered, because\
1762 you've asked me not to keep messages, or to mail them to you.\
1763 You should say `set tellme secure' or some such, first."
1764 }
1765 }
1766 set sr rel
1767 set v $setting
1768 if {"$setting" != "unreliable"} {
1769 set every [ta_interval_optional 300 3600]
1770 lappend v $every
1771 }
1772 if {"$setting" == "remind"} {
1773 set within [ta_interval_optional 5 30]
1774 if {$within > $every} {
1775 error "remind interval must be at least time to respond"
1776 }
1777 lappend v $within
1778 }
1779 ta_nomore
1780 }
1781 default {
1782 error "invalid tellme setting $setting"
1783 }
1784 }
1785 nickdb_set $n tell$sr $v
1786 upvar #0 nick_telling($nl) telling
1787 catch { unset telling }
1788 ucmdr [tellme_${sr}_desc $v $n] {}
1789}
1790
1791proc lnick_checktold {luser} {
1792 set ml [msgsdb_get $luser outbound]
1793 if {![llength $ml]} return
1794 set is1 [expr {[llength $ml]==3}]
1795 set m1 "FYI, I haven't yet delivered your"
1796 set ol {}
1797 set now [clock seconds]
1798 while {[llength $ml]} {
1799 manyset $ml r t n
1800 set ml [lreplace $ml 0 2]
1801 set td [expr {$now-$t}]
1802 if {$n == 1} {
1803 set iv [showinterval $td]
1804 set ifo "$r, $iv"
1805 set if1 "message to $r, $iv."
1806 } else {
1807 set iv [showintervalsecs $td 0]
1808 set ifo "$r, $n messages, oldest $iv"
1809 set if1 "$n messages to $r, oldest $iv."
1810 }
1811 if {$is1} {
1812 sendprivmsg $luser "$m1 $if1"
1813 return
1814 } else {
1815 lappend ol " to $ifo[expr {[llength $ml] ? ";" : "."}]"
1816 }
1817 }
1818 sendprivmsg $luser "$m1 messages:"
1819 msendprivmsg $luser $ol
1820}
1821
1822def_ucmd set {
1823 global settings
1824 prefix_nick
1825 check_notonchan
1826 if {![nickdb_exists $n]} {
1827 ucmdr {} "You are unknown to me and so have no settings. (Use `register'.)"
1828 }
1829 if {![ta_anymore]} {
1830 set ol {}
1831 foreach opt $settings {
1832 lappend ol [format "%-10s %s" $opt [set_show/$opt]]
1833 }
1834 ucmdr {} [join $ol "\n"]
1835 } else {
1836 set opt [ta_word]
1837 if {[catch { info body set_show/$opt }]} {
1838 error "no setting $opt"
1839 }
1840 if {![ta_anymore]} {
1841 ucmdr {} "$opt: [set_show/$opt]"
1842 } else {
1843 nick_securitycheck 0
1844 if {[catch { info body set_set/$opt }]} {
1845 error "setting $opt cannot be set with `set'"
1846 }
1847 set_set/$opt
1848 }
1849 }
1850}
1851
1852def_ucmd identpass {
1853 prefix_nick
1854 check_notonchan
1855 set luser [irctolower $n]
1856 set username [ta_word]
1857 set passmd5 [md5sum "[ta_word]\n"]
1858 ta_nomore
1859 upvar #0 nick_onchans($luser) onchans
1860 if {![info exists onchans] || ![llength $onchans]} {
1861 ucmdr "You must be on a channel with me to identify yourself." {}
1862 }
1863 check_username $username
1864 exec userv --timeout 3 $username << "$passmd5\n" > /dev/null \
1865 irc-identpass $n
1866 upvar #0 nick_username($luser) rec_username
1867 set rec_username $username
1868 after 50 [list tell_event $luser ident]
1869 ucmdr "Pleased to see you, $username." {}
1870}
1871
1872def_ucmd kill {
1873 global nick
1874 prefix_nick
1875 set target [ta_nick]
1876 if {![nickdb_exists $target]} { error "$target is not a registered nick." }
1877 set wantu [nickdb_get $target username]
1878 if {![string length $wantu]} { error "$target is insecurely registred." }
1879 upvar #0 nick_username([irctolower $n]) nu
1880 if {![info exists nu]} { error "You must identify yourself first." }
1881 if {"$wantu" != "$nu"} {
1882 error "You are the wrong user, $nu - $target belongs to $wantu."
1883 }
1884 set reason "at request of user $nu"
1885 if {[ta_anymore]} { append reason "; $text" }
1886 sendout KILL $target $reason
1887}
1888
1889def_ucmd summon {
1890 set target [ta_word]
1891 ta_nomore
1892 # fixme would be nice if the rest of the text was passed on instead
1893 check_username $target
1894 prefix_nick
1895
1896 upvar #0 lastsummon($target) ls
1897 set now [clock seconds]
1898 if {[info exists ls]} {
1899 set interval [expr {$now - $ls}]
1900 if {$interval < 30} {
1901 ucmdr {} \
1902 "Please be patient; $target was summoned only [showinterval $interval]."
1903 }
1904 }
1905 regsub {^[^!]*!} $p {} path
1906 if {[catch {
1907 exec userv --timeout 3 $target irc-summon $n $path \
1908 [expr {[ischan $dest] ? "$dest" : ""}] \
1909 < /dev/null
1910 } rv]} {
1911 regsub -all "\n" $rv { / } rv
1912 error $rv
1913 }
1914 if {[regexp {^problem (.*)} $rv dummy problem]} {
1915 ucmdr {} "The user `$target' $problem."
1916 } elseif {[regexp {^ok ([^ ]+) ([0-9]+)$} $rv dummy tty idlesince]} {
1917 set idletime [expr {$now - $idlesince}]
1918 set ls $now
1919 ucmdr {} {} {} "invites $target ($tty[expr {
1920 $idletime > 10 ? ", idle for [showintervalsecs $idletime 0]" : ""
1921 }]) to [expr {
1922 [ischan $dest] ? "join us here" : "talk to you"
1923 }]."
1924 } else {
1925 error "unexpected response from userv service: $rv"
1926 }
1927}
1928
1929proc md5sum {value} { exec md5sum << $value }
1930
1931def_ucmd seen {
1932 global lastseen nick
1933 prefix_nick
1934 set ncase [ta_nick]
1935 set nlower [irctolower $ncase]
1936 ta_nomore
1937 set now [clock seconds]
1938 if {"$nlower" == "[irctolower $nick]"} {
1939 usererror "I am not self-aware."
1940 } elseif {![info exists lastseen($nlower)]} {
1941 set rstr "I've never seen $ncase."
1942 } else {
1943 manyset $lastseen($nlower) realnick time what
1944 set howlong [expr {$now - $time}]
1945 set string [showinterval $howlong]
1946 set rstr "I last saw $realnick $string, $what."
1947 }
1948 if {[ischan $dest]} {
1949 set where $dest
1950 } else {
1951 set where {}
1952 }
1953 upvar #0 lookedfor($nlower) lf
1954 if {[info exists lf]} { set oldvalue $lf } else { set oldvalue {} }
1955 set lf [list [list $now $n $where]]
1956 foreach v $oldvalue {
1957 if {"[irctolower [lindex $v 1]]" == "[irctolower $n]"} continue
1958 lappend lf $v
1959 }
1960 ucmdr {} $rstr
1961}
1962
1963proc lnick_marktime_cancel {luser} {
1964 upvar #0 nick_markid($luser) mi
1965 if {![info exists mi]} return
1966 catch { after cancel $mi }
1967 catch { unset mi }
1968}
1969
1970proc lnick_marktime_doafter {luser why ms mentiontold} {
1971 lnick_marktime_cancel $luser
1972 upvar #0 nick_markid($luser) mi
1973 set mi [after $ms [list lnick_marktime_now $luser $why 0]]
1974}
1975
1976proc lnick_marktime_reset {luser} {
1977 set mt [nickdb_get $luser marktime]
1978 if {"$mt" == "off" || "$mt" == "once"} return
1979 lnick_marktime_doafter $luser "Time passes." [expr {$mt*1000}] 0
1980}
1981
1982proc lnick_marktime_start {luser why ms mentiontold} {
1983 set mt [nickdb_get $luser marktime]
1984 if {"$mt" == "off"} {
1985 lnick_marktime_cancel $luser
1986 if {$mentiontold} { after $ms [list lnick_checktold $luser] }
1987 } else {
1988 lnick_marktime_doafter $luser $why $ms $mentiontold
1989 }
1990}
1991
1992proc lnick_marktime_now {luser why mentiontold} {
1993 upvar #0 nick_onchans($luser) oc
1994 global calling_nick
1995 set calling_nick $luser
1996 sendprivmsg $luser [lnick_pingstring $why $oc ""]
1997 if {$mentiontold} { after 150 [list lnick_checktold $luser] }
1998 lnick_marktime_reset $luser
1999}
2000
2001proc lnick_pingstring {why oc apstring} {
2002 global nick_onchans
2003 catch { exec uptime } uptime
2004 set nnicks [llength [array names nick_onchans]]
2005 if {[regexp \
2006 {^ *([0-9:apm]+) +up.*, +(\d+) users?, +load average: +([0-9., ]+) *$} \
2007 $uptime dummy time users load]} {
2008 regsub -all , $load {} load
2009 set uptime "$time $nnicks/$users $load"
2010 } else {
2011 append uptime ", $nnicks nicks"
2012 }
2013 if {[llength $oc]} {
2014 set best_la 0
2015 set activity quiet
2016 foreach ch $oc {
2017 upvar #0 chan_lastactivity($ch) la
2018 if {![info exists la]} continue
2019 if {$la <= $best_la} continue
2020 set since [showintervalsecs [expr {[clock seconds]-$la}] 1]
2021 set activity "$ch $since"
2022 set best_la $la
2023 }
2024 } else {
2025 set activity unseen
2026 }
2027 set str $why
2028 append str " " $uptime " " $activity
2029 if {[string length $apstring]} { append str " " $apstring }
2030 return $str
2031}
2032
2033def_ucmd ping {
2034 prefix_nick
2035 set ln [irctolower $n]
2036 if {[ischan $dest]} {
2037 set oc [irctolower $dest]
2038 } else {
2039 global nick_onchans
2040 if {[info exists nick_onchans($ln)]} {
2041 set oc $nick_onchans($ln)
2042 } else {
2043 set oc {}
2044 }
2045 if {[llength $oc]} { lnick_marktime_reset $ln }
2046 }
2047 after 150 [list lnick_checktold $ln]
2048 ucmdr {} [lnick_pingstring "Pong!" $oc $text]
2049}
2050
2051proc ensure_globalsecret {} {
2052 global globalsecret
2053
2054 if {[info exists globalsecret]} return
2055 set gsfile [open /dev/urandom r]
2056 fconfigure $gsfile -translation binary
2057 set globalsecret [read $gsfile 32]
2058 binary scan $globalsecret H* globalsecret
2059 close $gsfile
2060 unset gsfile
2061}
2062
2063proc connected {} {
2064 global operuserpass
2065 if {[info exists operuserpass]} {
2066 eval sendout OPER $operuserpass
2067 }
2068 foreach chan [chandb_list] {
2069 if {[chandb_get $chan autojoin]} { dojoin $chan }
2070 }
2071}
2072
2073ensure_globalsecret
2074loadhelp
2075ensure_connecting