Document channel manager invite.
[ircbot] / bot.tcl
1 # Core bot code
2
3 proc defset {varname val} {
4 upvar #0 $varname var
5 if {![info exists var]} { set var $val }
6 }
7
8 # must set host
9 defset port 6667
10
11 defset nick testbot
12 defset ownfullname "testing bot"
13 defset ownmailaddr test-irc-bot@example.com
14
15 defset musthaveping_ms 10000
16 defset out_maxburst 6
17 defset out_interval 2100
18 defset out_lag_lag 5000
19 defset out_lag_very 25000
20
21 defset marktime_min 300
22 defset marktime_join_startdelay 5000
23
24 proc manyset {list args} {
25 foreach val $list var $args {
26 upvar 1 $var my
27 set my $val
28 }
29 }
30
31 proc 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
54 proc usererror {emsg} { error $emsg {} {BLIGHT USER} }
55
56 proc 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
65 proc 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
76 proc 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
88 proc out_runqueue {now} {
89 global sock
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}]"
98 append orgwhen "([llength $out_queue])"
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
109 proc 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
117 proc sendout_priority {priority command args} {
118 global sock out_queue
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]} {
124 error "bad argument in output $i ($command $args)"
125 }
126 }
127 lappend args :$la
128 }
129 set args [lreplace $args 0 -1 $command]
130 set string [join $args { }]
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 }
141 }
142
143 proc sendout {command args} { eval sendout_priority [list 0 $command] $args }
144
145 proc log {data} {
146 puts $data
147 }
148
149 proc logerror {data} {
150 log $data
151 }
152
153 proc saveeic {} {
154 global saveei saveec errorInfo errorCode
155
156 set saveei $errorInfo
157 set saveec $errorCode
158
159 puts ">$saveec|$saveei<"
160 }
161
162 proc bgerror {msg} {
163 global save
164 logerror $msg
165 saveeic
166 }
167
168 proc onread {args} {
169 global sock nick calling_nick errorInfo errorCode
170
171 if {[gets $sock line] == -1} { fail "EOF/error on input" }
172 regsub -all "\[^ -\176\240-\376\]" $line ? line
173 set org $line
174
175 set ei $errorInfo
176 set ec $errorCode
177 catch { unset calling_nick }
178 set errorInfo $ei
179 set errorCode $ec
180
181 if {[regexp -nocase {^:([^ ]+) (.*)} $line dummy prefix remain]} {
182 set line $remain
183 if {[regexp {^([^!]+)!} $prefix dummy maybenick]} {
184 set calling_nick $maybenick
185 if {"[irctolower $maybenick]" == "[irctolower $nick]"} return
186 }
187 } else {
188 set prefix {}
189 }
190 if {![string length $line]} { return }
191 if {![regexp -nocase {^([0-9a-z]+) *(.*)} $line dummy command line]} {
192 log "bad command: $org"
193 return
194 }
195 set command [string toupper $command]
196 set params {}
197 while {[regexp {^([^ :]+) *(.*)} $line dummy thisword line]} {
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 }
206 if {"$command" == "PRIVMSG" &&
207 [regexp {^[&#+!]} [lindex $params 0]] &&
208 ![regexp {^![a-z][-a-z]*[a-z]( .*)?$} [lindex $params 1]]} {
209 # on-channel message, ignore
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 }
214 return
215 }
216 log "[clock seconds] <- $org"
217 set procname msg_$command
218 if {[catch { info body $procname }]} { return }
219 if {[catch {
220 eval [list $procname $prefix $command] $params
221 } emsg]} {
222 logerror "error: $emsg ($prefix $command $params)"
223 saveeic
224 }
225 }
226
227 proc sendprivmsg {dest l} {
228 foreach v [split $l "\n"] {
229 sendout [expr {[ischan $dest] ? "PRIVMSG" : "NOTICE"}] $dest $v
230 }
231 }
232 proc sendaction_priority {priority dest what} {
233 sendout_priority $priority PRIVMSG $dest "\001ACTION $what\001"
234 }
235 proc msendprivmsg {dest ll} { foreach l $ll { sendprivmsg $dest $l } }
236 proc msendprivmsg_delayed {delay dest ll} { after $delay [list msendprivmsg $dest $ll] }
237
238 proc prefix_none {} {
239 upvar 1 p p
240 if {[string length $p]} { error "prefix specified" }
241 }
242
243 proc msg_PING {p c s1} {
244 global musthaveping_after
245 prefix_none
246 sendout PONG $s1
247 if {[info exists musthaveping_after]} connected
248 }
249
250 proc 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
255 proc ischan {dest} {
256 return [regexp {^[&#+!]} $dest]
257 }
258
259 proc 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
269 proc 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
275 if {"[irctolower $n]" == "[irctolower $nick]"} {
276 error "from myself" {} {}
277 }
278 }
279
280 proc showintervalsecs {howlong abbrev} {
281 return [showintervalsecs/[opt timeformat] $howlong $abbrev]
282 }
283
284 proc showintervalsecs/ks {howlong abbrev} {
285 if {$howlong < 1000} {
286 return "${howlong}s"
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
298 return [format "$format${pfx}s" $value]
299 }
300 }
301 }
302
303 proc format_qty {qty unit abbrev} {
304 set o $qty
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 }
312 return $o
313 }
314
315 proc showintervalsecs/hms {qty abbrev} {
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 }
324 set o [format_qty $qty [lindex $ul 0] $abbrev]
325 if {$remainv} {
326 if {!$abbrev} { append o " " }
327 append o [format_qty $remainv $remainu $abbrev]
328 }
329 return $o
330 }
331
332 proc showinterval {howlong} {
333 if {$howlong <= 0} {
334 return {just now}
335 } else {
336 return "[showintervalsecs $howlong 0] ago"
337 }
338 }
339
340 proc showtime {when} {
341 return [showinterval [expr {[clock seconds] - $when}]]
342 }
343
344 proc 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
352 def_msgproc begin {dest str} {
353 set d $dest
354 set s $str
355 set a {}
356 }
357
358 def_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
368 def_msgproc finish {} {
369 msg__sendout $varbase
370 unset s
371 unset d
372 return $a
373 }
374
375 def_msgproc _sendout {} {
376 lappend a [string trimright $s]
377 set s {}
378 }
379
380 proc 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
386 proc recordlastseen_n {n how here} {
387 global lastseen lookedfor
388 set lastseen([irctolower $n]) [list $n [clock seconds] $how]
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 }
425 }
426
427 proc note_topic {showoff whoby topic} {
428 set msg "FYI, $whoby has changed the topic on $showoff"
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 }
441 foreach spy $tryspies {
442 set see [chandb_get $spy topicsee]
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
451 proc recordlastseen_p {p how here} {
452 prefix_nick
453 recordlastseen_n $n $how $here
454 }
455
456 proc 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
463 proc chanmode_o1 {m g p chan} {
464 global nick chan_initialop
465 prefix_nick
466 set who [chanmode_arg]
467 recordlastseen_n $n "being nice to $who" 1
468 if {"[irctolower $who]" == "[irctolower $nick]"} {
469 set nlower [irctolower $n]
470 upvar #0 nick_unique($nlower) u
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 }
484 }
485 }
486
487 proc chanmode_o0 {m g p chan} {
488 global nick chandeop
489 prefix_nick
490 set who [chanmode_arg]
491 recordlastseen_p $p "being mean to $who" 1
492 if {"[irctolower $who]" == "[irctolower $nick]"} {
493 set chandeop($chan) [list [clock seconds] $p]
494 }
495 }
496
497 proc 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 }]} {
509 recordlastseen_p $p "fiddling with $dest" 1
510 } else {
511 $procname $m $give $p $dest
512 }
513 }
514 }
515
516 proc 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
523 upvar #0 chan_lastactivity($lchan) la
524 catch { unset la }
525 }
526
527 proc doleave {lchan} {
528 sendout PART $lchan
529 leaving $lchan
530 }
531
532 proc dojoin {lchan} {
533 global chan_nicks
534 sendout JOIN $lchan
535 set chan_nicks($lchan) {}
536 }
537
538 proc check_justme {lchan} {
539 global nick
540 upvar #0 chan_nicks($lchan) nlist
541 if {[llength $nlist] != 1} return
542 if {"[lindex $nlist 0]" != "[irctolower $nick]"} return
543 if {[chandb_exists $lchan]} {
544 set mode [chandb_get $lchan mode]
545 if {"$mode" != "*"} {
546 sendout MODE $lchan $mode
547 }
548 set topic [chandb_get $lchan topicset]
549 if {[string length $topic]} {
550 sendout TOPIC $lchan $topic
551 }
552 } else {
553 doleave $lchan
554 }
555 }
556
557 proc process_kickpart {chan user} {
558 global nick
559 check_nick $user
560 set luser [irctolower $user]
561 set lchan [irctolower $chan]
562 if {![ischan $chan]} { error "not a channel" }
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 }
576 }
577 }
578
579 proc 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
586 proc 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
596 proc msg_KILL {p c user why} {
597 nick_forget $user
598 }
599
600 set nick_counter 0
601 set nick_arys {onchans username unique}
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)
606 # nick_markid($luser) -> <after id for marktime>
607
608 # chan_nicks($lchan) -> [list ... $luser ...]
609 # chan_lastactivity($lchan) -> [clock seconds]
610
611 proc lnick_forget {luser} {
612 global nick_arys chan_nicks
613 lnick_marktime_cancel $luser
614 foreach ary $nick_arys {
615 upvar #0 nick_${ary}($luser) av
616 catch { unset av }
617 }
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
625 proc nick_forget {user} {
626 global nick_arys chan_nicks
627 lnick_forget [irctolower $user]
628 nick_case $user
629 }
630
631 proc nick_case {user} {
632 global nick_case
633 set nick_case([irctolower $user]) $user
634 }
635
636 proc msg_NICK {p c newnick} {
637 global nick_arys nick_case
638 prefix_nick
639 recordlastseen_n $n "changing nicks to $newnick" 0
640 recordlastseen_n $newnick "changing nicks from $n" 1
641 set luser [irctolower $n]
642 lnick_marktime_cancel $luser
643 set lusernew [irctolower $newnick]
644 foreach ary $nick_arys {
645 upvar #0 nick_${ary}($luser) old
646 upvar #0 nick_${ary}($lusernew) new
647 if {[info exists new]} { error "nick collision ?! $ary $n $newnick" }
648 if {[info exists old]} { set new $old; unset old }
649 }
650 upvar #0 nick_onchans($lusernew) oc
651 foreach ch $oc {
652 upvar #0 chan_nicks($ch) nlist
653 set nlist [grep tn {"$tn" != "$luser"} $nlist]
654 lappend nlist $lusernew
655 }
656 lnick_marktime_start $lusernew "Hi." 500
657 nick_case $newnick
658 }
659
660 proc nick_ishere {n} {
661 global nick_counter
662 upvar #0 nick_unique([irctolower $n]) u
663 if {![info exists u]} { set u [incr nick_counter].$n.[clock seconds] }
664 nick_case $n
665 }
666
667 proc msg_JOIN {p c chan} {
668 prefix_nick
669 recordlastseen_n $n "joining $chan" 1
670 set nl [irctolower $n]
671 set lchan [irctolower $chan]
672 upvar #0 nick_onchans($nl) oc
673 upvar #0 chan_nicks($lchan) nlist
674 if {![info exists oc]} {
675 global marktime_join_startdelay
676 lnick_marktime_start $nl "Welcome." $marktime_join_startdelay
677 }
678 lappend oc $lchan
679 lappend nlist $nl
680 nick_ishere $n
681 }
682 proc msg_PART {p c chan} {
683 prefix_nick
684 recordlastseen_n $n "leaving $chan" 1
685 process_kickpart $chan $n
686 }
687 proc msg_QUIT {p c why} {
688 prefix_nick
689 recordlastseen_n $n "leaving ($why)" 0
690 nick_forget $n
691 }
692
693 proc msg_PRIVMSG {p c dest text} {
694 global errorCode
695
696 prefix_nick
697 if {[ischan $dest]} {
698 recordlastseen_n $n "invoking me in $dest" 1
699 set output $dest
700 } else {
701 recordlastseen_n $n "talking to me" 1
702 set output $n
703 }
704 nick_case $n
705
706 if {[catch {
707 regsub {^! *} $text {} text
708 set ucmd [ta_word]
709 set procname ucmd/[string tolower $ucmd]
710 if {[catch { info body $procname }]} {
711 usererror "Unknown command; try help for help."
712 }
713 $procname $p $dest
714 } rv]} {
715 if {"$errorCode" != "BLIGHT USER"} { set rv "error: $rv" }
716 sendprivmsg $n $rv
717 } else {
718 manyset $rv priv_msgs pub_msgs priv_acts pub_acts
719 foreach {td val} [list $n $priv_acts $output $pub_acts] {
720 foreach l [split $val "\n"] {
721 sendaction_priority 0 $td $l
722 }
723 }
724 foreach {td val} [list $n $priv_msgs $output $pub_msgs] {
725 foreach l [split $val "\n"] {
726 sendprivmsg $td $l
727 }
728 }
729 }
730 }
731
732 proc msg_INVITE {p c n chan} {
733 after 1000 [list dojoin [irctolower $chan]]
734 }
735
736 proc 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
745 proc msg_353 {p c dest type chan nicklist} {
746 global names_chans nick_onchans
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
767 }
768 set nlist $nlist_new
769 }
770
771 proc msg_366 {p c args} {
772 global names_chans nick_onchans
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} {
777 set oc [grep tc {[lsearch -exact $tc $names_chans] >= 0} $oc]
778 }
779 if {![llength $oc]} { lnick_forget $n }
780 }
781 unset names_chans
782 }
783
784 proc ta_anymore {} {
785 upvar 1 text text
786 return [expr {!![string length $text]}]
787 }
788
789 proc ta_nomore {} {
790 upvar 1 text text
791 if {[string length $text]} { error "too many parameters" }
792 }
793
794 proc 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
802 proc ta_nick {} {
803 upvar 1 text text
804 set v [ta_word]
805 check_nick $v
806 return $v
807 }
808
809 proc def_ucmd {cmdname body} {
810 proc ucmd/$cmdname {p dest} " upvar 1 text text\n$body"
811 }
812
813 proc ucmdr {priv pub args} {
814 return -code return [concat [list $priv $pub] $args]
815 }
816
817 proc loadhelp {} {
818 global help_topics errorInfo
819
820 catch { unset help_topics }
821 set f [open helpinfos r]
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 }
833 } elseif {[regexp {^\:\:} $l]} {
834 } elseif {[regexp {^\:([-+._0-9a-z]*)$} $l dummy newtopic]} {
835 if {[info exists topic]} {
836 error "help $newtopic while in $topic"
837 }
838 set topic $newtopic
839 set lines {}
840 } elseif {[regexp {^[^:#]} $l]} {
841 set topic
842 regsub -all {([^\\])\!\$?} _$l {\1} l
843 regsub -all {\\(.)} $l {\1} l
844 regsub {^_} $l {} l
845 lappend lines [string trimright $l]
846 } else {
847 error "eh ? $lno: $l"
848 }
849 }
850 if {[info exists topic]} { error "unfinished topic $topic" }
851 } {
852 set errorInfo "in helpinfos line $lno\n$errorInfo"
853 } {
854 close $f
855 }
856 }
857
858 def_ucmd help {
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 }
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 \
871 "is very lagged. Please ask for help$ontopic again later."
872 ucmdr {} {}
873 } else {
874 sendaction_priority 1 $replyto \
875 "is lagged. Your help$ontopic will arrive shortly ..."
876 }
877 }
878
879 upvar #0 help_topics($topic) info
880 if {![info exists info]} { ucmdr "No help on $topic, sorry." {} }
881 ucmdr $info {}
882 }
883
884 def_ucmd ? {
885 global help_topics
886 ucmdr $help_topics() {}
887 }
888
889 proc check_username {target} {
890 if {
891 [string length $target] > 8 ||
892 [regexp {[^-0-9a-z]} $target] ||
893 ![regexp {^[a-z]} $target]
894 } { error "invalid username" }
895 }
896
897 proc somedb__head {} {
898 uplevel 1 {
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]
905 try_except_finally { set newval [read $f] } {} { close $f }
906 if {[llength $newval] % 2} { error "invalid length" }
907 set iddbe $newval
908 }
909 }
910 }
911
912 proc def_somedb {name arglist body} {
913 foreach {nickchan fprefix} {nick users/n chan chans/c} {
914 proc ${nickchan}db_$name $arglist \
915 "set nickchan $nickchan; set fprefix $fprefix; $body"
916 }
917 }
918
919 def_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]
925 }
926 return $list
927 }
928
929 proc def_somedb_id {name arglist body} {
930 def_somedb $name [concat id $arglist] "somedb__head; $body"
931 }
932
933 def_somedb_id exists {} {
934 return [info exists iddbe]
935 }
936
937 def_somedb_id delete {} {
938 catch { unset iddbe }
939 file delete $idfn
940 }
941
942 set default_settings_nick {timeformat ks marktime off}
943 set default_settings_chan {
944 autojoin 1
945 mode *
946 userinvite pub
947 topicset {}
948 topicsee {}
949 topictell {}
950 }
951
952 def_somedb_id set {args} {
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 }
956 set newval {}
957 foreach {key value} [array get a] { lappend newval $key $value }
958 set f [open $idfn.new w]
959 try_except_finally {
960 puts $f $newval
961 close $f
962 file rename -force $idfn.new $idfn
963 } {
964 } {
965 catch { close $f }
966 }
967 set iddbe $newval
968 }
969
970 def_somedb_id get {key} {
971 upvar #0 default_settings_$nickchan def
972 if {[info exists iddbe]} {
973 set l [concat $iddbe $def]
974 } else {
975 set l $def
976 }
977 foreach {tkey value} $l {
978 if {"$tkey" == "$key"} { return $value }
979 }
980 error "unset setting $key"
981 }
982
983 proc 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
989 proc check_notonchan {} {
990 upvar 1 dest dest
991 if {[ischan $dest]} { usererror "That command must be sent privately." }
992 }
993
994 proc nick_securitycheck {strict} {
995 upvar 1 n n
996 if {![nickdb_exists $n]} {
997 usererror "You are unknown to me, use `register'."
998 }
999 set wantu [nickdb_get $n username]
1000 if {![string length $wantu]} {
1001 if {$strict} {
1002 usererror "That feature is only available to secure users, sorry."
1003 } else {
1004 return
1005 }
1006 }
1007 set luser [irctolower $n]
1008 upvar #0 nick_username($luser) nu
1009 if {![info exists nu]} {
1010 usererror "Nick $n is secure, you must identify yourself first."
1011 }
1012 if {"$wantu" != "$nu"} {
1013 usererror "You are the wrong user -\
1014 the nick $n belongs to $wantu, not $nu."
1015 }
1016 }
1017
1018 proc channel_ismanager {channel n} {
1019 set mgrs [chandb_get $channel managers]
1020 return [expr {[lsearch -exact [irctolower $mgrs] [irctolower $n]] >= 0}]
1021 }
1022
1023 proc channel_securitycheck {channel} {
1024 upvar n n
1025 if {![channel_ismanager $channel $n]} {
1026 usererror "You are not a manager of $channel."
1027 }
1028 nick_securitycheck 1
1029 }
1030
1031 proc def_chancmd {name body} {
1032 proc channel/$name {} \
1033 " upvar 1 target chan; upvar 1 n n; upvar 1 text text; $body"
1034 }
1035
1036 proc 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
1045 set opcode [ta_word]
1046 switch -exact _$opcode {
1047 _= { }
1048 _+ - _- {
1049 uplevel 1 $findnow
1050 foreach item $exchg { set array($item) 1 }
1051 }
1052 default {
1053 error "list change opcode must be one of + - ="
1054 }
1055 }
1056 foreach exchg [split $text " "] {
1057 if {![string length $exchg]} continue
1058 uplevel 1 $procvalue
1059 if {"$opcode" != "-"} {
1060 set array($exchg) 1
1061 } else {
1062 catch { unset array($exchg) }
1063 }
1064 }
1065 set exchg [lsort [array names array]]
1066 }
1067
1068 def_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" {}
1082 } else {
1083 chandb_delete $chan
1084 ucmdr {} {} "forgets about managing $chan." {}
1085 }
1086 }
1087
1088 def_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
1096 ucmdr [expr {$nv ? "I will join $chan when I'm restarted " : \
1097 "I won't join $chan when I'm restarted "}] {}
1098 }
1099
1100 def_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
1115 def_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
1129 ucmdr "Whenever I'm alone on $chan, I'll set the topic to $t." {}
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 {
1146 usererror "Unknown channel topic subcommand - see help channel."
1147 }
1148 }
1149 }
1150
1151 def_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" == "*"} {
1158 ucmdr "I won't ever change the mode of $chan." {}
1159 } else {
1160 ucmdr "Whenever I'm alone on $chan, I'll set the mode to $mode." {}
1161 }
1162 }
1163
1164 def_chancmd show {
1165 if {[chandb_exists $chan]} {
1166 set l "Settings for $chan: autojoin "
1167 append l [lindex {no yes} [chandb_get $chan autojoin]]
1168 append l ", mode " [chandb_get $chan mode]
1169 append l ", userinvite " [chandb_get $chan userinvite] "."
1170 append l "\nManagers: "
1171 append l [join [chandb_get $chan managers] " "]
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 }
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 }
1188 ucmdr {} $l
1189 } else {
1190 ucmdr {} "The channel $chan is not managed."
1191 }
1192 }
1193
1194 proc 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
1202 prefix_nick
1203
1204 if {[ischan $dest]} { set target $dest }
1205 if {[ta_anymore]} { set target [ta_word] }
1206 ta_nomore
1207 if {![info exists target]} {
1208 usererror "You must specify, or invoke me on, the relevant channel."
1209 }
1210 if {![info exists chan_nicks([irctolower $target])]} {
1211 usererror "I am not on $target."
1212 }
1213 if {![ischan $target]} { error "not a valid channel" }
1214
1215 if {![chandb_exists $target]} {
1216 usererror "$target is not a managed channel."
1217 }
1218 channel_securitycheck $target
1219 }
1220
1221 def_ucmd op {
1222 channelmgr_monoop
1223 sendout MODE $target +o $n
1224 }
1225
1226 def_ucmd leave {
1227 channelmgr_monoop
1228 doleave $target
1229 }
1230
1231 def_ucmd invite {
1232 global chan_nicks errorCode errorInfo
1233 prefix_nick
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]
1243 if {![ischan $target]} { error "$target is not a channel" }
1244 if {![info exists chan_nicks($ltarget)]} {
1245 usererror "I am not on $target."
1246 }
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
1276 }
1277 }
1278 if {![ta_anymore]} {
1279 usererror "You have to say who to invite."
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
1303 def_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"} {
1321 if {[catch { info body $procname }]} {
1322 usererror "unknown channel setting $subcmd."
1323 }
1324 prefix_nick
1325 if {[chandb_exists $target]} {
1326 channel_securitycheck $target
1327 } else {
1328 nick_securitycheck 1
1329 upvar #0 chan_initialop([irctolower $target]) io
1330 upvar #0 nick_unique([irctolower $n]) u
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 }
1340 }
1341 }
1342 channel/$subcmd
1343 }
1344
1345 def_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 }
1354 set ltarget [irctolower $target]
1355 upvar #0 nick_case($ltarget) ctarget
1356 set nshow $target
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 }
1361 }
1362 if {![nickdb_exists $ltarget]} {
1363 set ol "$nshow is not a registered nick."
1364 } elseif {[string length [set username [nickdb_get $target username]]]} {
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 }
1369 if {![info exists ctarget] || ![info exists oc]} {
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
1387 def_ucmd register {
1388 prefix_nick
1389 check_notonchan
1390 set old [nickdb_exists $n]
1391 if {$old} { nick_securitycheck 0 }
1392 set luser [irctolower $n]
1393 switch -exact [string tolower [string trim $text]] {
1394 {} {
1395 upvar #0 nick_username($luser) nu
1396 if {![info exists nu]} {
1397 ucmdr {} \
1398 "You must identify yourself before using `register'. See `help identify', or use `register insecure'."
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 }
1416 }
1417
1418 proc timeformat_desc {tf} {
1419 switch -exact $tf {
1420 ks { return "Times will be displayed in seconds or kiloseconds." }
1421 hms { return "Times will be displayed in hours, minutes, etc." }
1422 default { error "invalid timeformat: $v" }
1423 }
1424 }
1425
1426 proc 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
1439 def_setting timeformat {
1440 set tf [nickdb_get $n timeformat]
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
1450 proc 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 {
1456 return "I'll send you a message every [showintervalsecs $mt 0]."
1457 }
1458 }
1459
1460 def_setting marktime {
1461 set mt [nickdb_get $n marktime]
1462 set p $mt
1463 if {[string match {[0-9]*} $mt]} { append p s }
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
1492 def_setting security {
1493 set s [nickdb_get $n username]
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
1501 def_ucmd set {
1502 prefix_nick
1503 check_notonchan
1504 if {![nickdb_exists $n]} {
1505 ucmdr {} "You are unknown to me and so have no settings. (Use `register'.)"
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 {
1522 nick_securitycheck 0
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 }
1530
1531 def_ucmd identpass {
1532 set username [ta_word]
1533 set passmd5 [md5sum "[ta_word]\n"]
1534 ta_nomore
1535 prefix_nick
1536 check_notonchan
1537 set luser [irctolower $n]
1538 upvar #0 nick_onchans($luser) onchans
1539 if {![info exists onchans] || ![llength $onchans]} {
1540 ucmdr "You must be on a channel with me to identify yourself." {}
1541 }
1542 check_username $username
1543 exec userv --timeout 3 $username << "$passmd5\n" > /dev/null \
1544 irc-identpass $n
1545 upvar #0 nick_username($luser) rec_username
1546 set rec_username $username
1547 ucmdr "Pleased to see you, $username." {}
1548 }
1549
1550 def_ucmd summon {
1551 set target [ta_word]
1552 ta_nomore
1553 check_username $target
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]} {
1575 ucmdr {} "The user `$target' $problem."
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 {
1580 $idletime > 10 ? ", idle for [showintervalsecs $idletime 0]" : ""
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
1589 proc md5sum {value} { exec md5sum << $value }
1590
1591 def_ucmd seen {
1592 global lastseen nick
1593 prefix_nick
1594 set ncase [ta_nick]
1595 set nlower [irctolower $ncase]
1596 ta_nomore
1597 set now [clock seconds]
1598 if {"$nlower" == "[irctolower $nick]"} {
1599 usererror "I am not self-aware."
1600 } elseif {![info exists lastseen($nlower)]} {
1601 set rstr "I've never seen $ncase."
1602 } else {
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
1619 }
1620 ucmdr {} $rstr
1621 }
1622
1623 proc 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
1630 proc 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
1636 proc 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
1642 proc 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
1651 proc lnick_marktime_now {luser why} {
1652 upvar #0 nick_onchans($luser) oc
1653 global calling_nick
1654 set calling_nick $luser
1655 sendprivmsg $luser [lnick_pingstring $why $oc ""]
1656 lnick_marktime_reset $luser
1657 }
1658
1659 proc 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]} {
1666 regsub -all , $load {} load
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
1678 set since [showintervalsecs [expr {[clock seconds]-$la}] 1]
1679 set activity "$ch $since"
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
1691 def_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
1708 proc 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
1720 proc ensure_outqueue {} {
1721 out__vars
1722 if {[info exists out_queue]} return
1723 set out_creditms 0
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
1730 proc fail {msg} {
1731 logerror "failing: $msg"
1732 exit 1
1733 }
1734
1735 proc ensure_connecting {} {
1736 global sock ownfullname host port nick socketargs
1737 global musthaveping_ms musthaveping_after
1738
1739 if {[info exists sock]} return
1740 set sock [eval socket $socketargs [list $host $port]]
1741 fconfigure $sock -buffering line
1742 fconfigure $sock -translation crlf
1743
1744 sendout USER blight 0 * $ownfullname
1745 sendout NICK $nick
1746 fileevent $sock readable onread
1747
1748 set musthaveping_after [after $musthaveping_ms \
1749 {fail "no ping within timeout"}]
1750 }
1751
1752 proc 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
1763 ensure_globalsecret
1764 ensure_outqueue
1765 loadhelp
1766 ensure_connecting