3 proc defset {varname val} {
5 if {![info exists var]} { set var $val }
12 defset ownfullname "testing bot"
13 defset ownmailaddr test-irc-bot@example.com
15 defset musthaveping_ms 10000
17 defset out_interval 2100
18 defset out_lag_lag 5000
19 defset out_lag_very 25000
21 defset marktime_min 300
22 defset marktime_join_startdelay 5000
24 proc manyset {list args} {
25 foreach val $list var $args {
31 proc try_except_finally {try except finally} {
32 global errorInfo errorCode
33 set er [catch { uplevel 1 $try } emsg]
37 if {[catch { uplevel 1 $except } emsg3]} {
38 append ei "\nALSO ERROR HANDLING ERROR:\n$emsg3"
41 set er2 [catch { uplevel 1 $finally } emsg2]
44 append ei "\nALSO ERROR CLEANING UP:\n$emsg2"
46 return -code $er -errorinfo $ei -errorcode $ec $emsg
48 return -code $er2 -errorinfo $errorInfo -errorcode $errorCode $emsg2
56 global out_queue out_creditms out_creditat out_interval out_maxburst
57 global out_lag_lag out_lag_very
58 #set pr [lindex [info level 0] 0]
59 #puts $pr>[clock seconds]|$out_creditat|$out_creditms|[llength $out_queue]<
65 if {[llength $out_queue]*$out_interval > $out_lag_very} {
67 } elseif {[llength $out_queue]*$out_interval > $out_lag_lag} {
77 set now [clock seconds]
78 incr out_creditms [expr {($now - $out_creditat) * 1000}]
80 if {$out_creditms > $out_maxburst*$out_interval} {
81 set out_creditms [expr {$out_maxburst*$out_interval}]
86 proc out_runqueue {now} {
90 while {[llength $out_queue] && $out_creditms >= $out_interval} {
91 #puts rq>$now|$out_creditat|$out_creditms|[llength $out_queue]<
92 manyset [lindex $out_queue 0] orgwhen msg
93 set out_queue [lrange $out_queue 1 end]
94 if {[llength $out_queue]} {
95 append orgwhen "+[expr {$now - $orgwhen}]"
96 append orgwhen "([llength $out_queue])"
98 puts "$orgwhen -> $msg"
100 incr out_creditms -$out_interval
102 if {[llength $out_queue]} {
103 after $out_interval out_nextmessage
107 proc out_nextmessage {} {
109 set now [clock seconds]
110 incr out_creditms $out_interval
111 set out_creditat $now
115 proc sendout_priority {priority command args} {
116 global sock out_queue
117 if {[llength $args]} {
118 set la [lindex $args end]
119 set args [lreplace $args end end]
121 if {[regexp {[: ]} $i]} {
122 error "bad argument in output $i ($command $args)"
127 set args [lreplace $args 0 -1 $command]
128 set string [join $args { }]
129 set now [clock seconds]
130 set newe [list $now $string]
132 set out_queue [concat [list $newe] $out_queue]
134 lappend out_queue $newe
136 if {[llength $out_queue] == 1} {
141 proc sendout {command args} { eval sendout_priority [list 0 $command] $args }
147 proc logerror {data} {
152 global saveei saveec errorInfo errorCode
154 set saveei $errorInfo
155 set saveec $errorCode
157 puts ">$saveec|$saveei<"
167 global sock nick calling_nick errorInfo errorCode
169 if {[gets $sock line] == -1} { fail "EOF/error on input" }
170 regsub -all "\[^ -\176\240-\376\]" $line ? line
175 catch { unset calling_nick }
179 if {[regexp -nocase {^:([^ ]+) (.*)} $line dummy prefix remain]} {
181 if {[regexp {^([^!]+)!} $prefix dummy maybenick]} {
182 set calling_nick $maybenick
183 if {"[irctolower $maybenick]" == "[irctolower $nick]"} return
188 if {![string length $line]} { return }
189 if {![regexp -nocase {^([0-9a-z]+) *(.*)} $line dummy command line]} {
190 log "bad command: $org"
193 set command [string toupper $command]
195 while {[regexp {^([^ :]+) *(.*)} $line dummy thisword line]} {
196 lappend params $thisword
198 if {[regexp {^:(.*)} $line dummy thisword]} {
199 lappend params $thisword
200 } elseif {[string length $line]} {
201 log "junk at end: $org"
204 if {"$command" == "PRIVMSG" &&
205 [regexp {^[&#+!]} [lindex $params 0]] &&
206 ![regexp {^![a-z][-a-z]*[a-z]( .*)?$} [lindex $params 1]]} {
207 # on-channel message, ignore
208 set chan [lindex $params 0]
209 upvar #0 chan_lastactivity([irctolower $chan]) la
210 set la [clock seconds]
211 catch { recordlastseen_p $prefix "talking on $chan" 1 }
214 log "[clock seconds] <- $org"
215 set procname msg_$command
216 if {[catch { info body $procname }]} { return }
218 eval [list $procname $prefix $command] $params
220 logerror "error: $emsg ($prefix $command $params)"
225 proc sendprivmsg {dest l} {
226 foreach v [split $l "\n"] {
227 sendout [expr {[ischan $dest] ? "PRIVMSG" : "NOTICE"}] $dest $v
230 proc sendaction_priority {priority dest what} {
231 sendout_priority $priority PRIVMSG $dest "\001ACTION $what\001"
233 proc msendprivmsg {dest ll} { foreach l $ll { sendprivmsg $dest $l } }
234 proc msendprivmsg_delayed {delay dest ll} { after $delay [list msendprivmsg $dest $ll] }
236 proc prefix_none {} {
238 if {[string length $p]} { error "prefix specified" }
241 proc msg_PING {p c s1} {
242 global musthaveping_after
245 if {[info exists musthaveping_after]} connected
248 proc check_nick {n} {
249 if {[regexp -nocase {[^][\\`_^{|}a-z0-9-]} $n]} { error "bad char in nick" }
250 if {[regexp {^[-0-9]} $n]} { error "bad nick start" }
254 return [regexp {^[&#+!]} $dest]
257 proc irctolower {v} {
258 foreach {from to} [list "\\\[" "{" \
262 regsub -all $from $v $to v
264 return [string tolower $v]
267 proc prefix_nick {} {
271 if {![regexp {^([^!]+)!} $p dummy n]} { error "not from nick" }
273 if {"[irctolower $n]" == "[irctolower $nick]"} {
274 error "from myself" {} {}
278 proc showintervalsecs {howlong} {
279 return [showintervalsecs/[opt timeformat] $howlong]
282 proc showintervalsecs/ks {howlong} {
283 if {$howlong < 1000} {
286 if {$howlong < 1000000} {
293 set value [expr "$howlong.0 / $scale"]
294 foreach {min format} {100 %.0f 10 %.1f 1 %.2f} {
295 if {$value < $min} continue
296 return [format "$format${pfx}s" $value]
301 proc format_qty {qty unit} {
305 if {$qty != 1} { append o s }
309 proc showintervalsecs/hms {qty} {
310 set ul {second 60 minute 60 hour 24 day 7 week}
312 while {[llength $ul] > 1 && $qty >= [set uv [lindex $ul 1]]} {
313 set remainu [lindex $ul 0]
314 set remainv [expr {$qty % $uv}]
315 set qty [expr {($qty-$remainv)/$uv}]
316 set ul [lreplace $ul 0 1]
318 set o [format_qty $qty [lindex $ul 0]]
321 append o [format_qty $remainv $remainu]
326 proc showinterval {howlong} {
330 return "[showintervalsecs $howlong] ago"
334 proc showtime {when} {
335 return [showinterval [expr {[clock seconds] - $when}]]
338 proc def_msgproc {name argl body} {
339 proc msg_$name "varbase $argl" "\
340 upvar #0 msg/\$varbase/dest d\n\
341 upvar #0 msg/\$varbase/str s\n\
342 upvar #0 msg/\$varbase/accum a\n\
346 def_msgproc begin {dest str} {
352 def_msgproc append {str} {
354 if {[string length $s] && [string length $ns] > 65} {
355 msg__sendout $varbase
356 set s " [string trimleft $str]"
362 def_msgproc finish {} {
363 msg__sendout $varbase
369 def_msgproc _sendout {} {
370 lappend a [string trimright $s]
374 proc looking_whenwhere {when where} {
375 set str [showtime [expr {$when-1}]]
376 if {[string length $where]} { append str " on $where" }
380 proc recordlastseen_n {n how here} {
381 global lastseen lookedfor
382 set lastseen([irctolower $n]) [list $n [clock seconds] $how]
384 upvar #0 lookedfor([irctolower $n]) lf
385 if {[info exists lf]} {
386 switch -exact [llength $lf] {
391 manyset [lindex $lf 0] when who where
393 "FYI, $who was looking for you [looking_whenwhere $when $where]."]
396 msg_begin tosend $n "FYI, people have been looking for you:"
402 msg_append tosend " "
403 } elseif {$i == [llength $lf]} {
404 msg_append tosend " and "
407 msg_append tosend ", "
409 manyset $e when who where
411 "$who ([looking_whenwhere $when $where])$fin"
413 set ml [msg_finish tosend]
417 msendprivmsg_delayed 1000 $n $ml
421 proc note_topic {showoff whoby topic} {
422 set msg "FYI, $whoby has changed the topic on $showoff"
423 if {[string length $topic] < 160} {
424 append msg " to $topic"
426 append msg " but it is too long to reproduce here !"
428 set showoff [irctolower $showoff]
429 set tell [chandb_get $showoff topictell]
430 if {[lsearch -exact $tell *] >= 0} {
431 set tryspies [chandb_list]
435 foreach spy $tryspies {
436 set see [chandb_get $spy topicsee]
437 if {[lsearch -exact $see $showoff] >= 0 || \
438 ([lsearch -exact $see *] >= 0 && \
439 [lsearch -exact $tell $spy] >= 0)} {
440 sendprivmsg $spy $msg
445 proc recordlastseen_p {p how here} {
447 recordlastseen_n $n $how $here
450 proc chanmode_arg {} {
452 set rv [lindex $cm_args 0]
453 set cm_args [lreplace cm_args 0 0]
457 proc chanmode_o1 {m g p chan} {
458 global nick chan_initialop
460 set who [chanmode_arg]
461 recordlastseen_n $n "being nice to $who" 1
462 if {"[irctolower $who]" == "[irctolower $nick]"} {
463 set nlower [irctolower $n]
464 upvar #0 nick_unique($nlower) u
465 if {[chandb_exists $chan]} {
466 sendprivmsg $n Thanks.
467 } elseif {![info exists u]} {
468 sendprivmsg $n {Op me while not on the channel, why don't you ?}
470 set chan_initialop([irctolower $chan]) $u
472 "Thanks. You can use `channel manager ...' to register this channel."
473 if {![nickdb_exists $n] || ![string length [nickdb_get $n username]]} {
475 "(But to do that you must register your nick securely first.)"
481 proc chanmode_o0 {m g p chan} {
484 set who [chanmode_arg]
485 recordlastseen_p $p "being mean to $who" 1
486 if {"[irctolower $who]" == "[irctolower $nick]"} {
487 set chandeop($chan) [list [clock seconds] $p]
491 proc msg_MODE {p c dest modelist args} {
492 if {![ischan $dest]} return
493 if {[regexp {^\-(.+)$} $modelist dummy modelist]} {
495 } elseif {[regexp {^\+(.+)$} $modelist dummy modelist]} {
498 error "invalid modelist"
500 foreach m [split $modelist] {
501 set procname chanmode_$m$give
502 if {[catch { info body $procname }]} {
503 recordlastseen_p $p "fiddling with $dest" 1
505 $procname $m $give $p $dest
510 proc leaving {lchan} {
511 foreach luser [array names nick_onchans] {
512 upvar #0 nick_onchans($luser) oc
513 set oc [grep tc {"$tc" != "$lchan"} $oc]
515 upvar #0 chan_nicks($lchan) nlist
517 upvar #0 chan_lastactivity($lchan) la
521 proc doleave {lchan} {
526 proc dojoin {lchan} {
529 set chan_nicks($lchan) {}
532 proc check_justme {lchan} {
534 upvar #0 chan_nicks($lchan) nlist
535 if {[llength $nlist] != 1} return
536 if {"[lindex $nlist 0]" != "[irctolower $nick]"} return
537 if {[chandb_exists $lchan]} {
538 set mode [chandb_get $lchan mode]
539 if {"$mode" != "*"} {
540 sendout MODE $lchan $mode
542 set topic [chandb_get $lchan topicset]
543 if {[string length $topic]} {
544 sendout TOPIC $lchan $topic
551 proc process_kickpart {chan user} {
554 set luser [irctolower $user]
555 set lchan [irctolower $chan]
556 if {![ischan $chan]} { error "not a channel" }
557 if {"$luser" == "[irctolower $nick]"} {
560 upvar #0 nick_onchans($luser) oc
561 upvar #0 chan_nicks($lchan) nlist
562 set oc [grep tc {"$tc" != "$lchan"} $oc]
563 set nlist [grep tn {"$tn" != "$luser"} $nlist]
565 if {![llength $oc]} {
573 proc msg_TOPIC {p c dest topic} {
575 if {![ischan $dest]} return
576 recordlastseen_n $n "changing the topic on $dest" 1
577 note_topic [irctolower $dest] $n $topic
580 proc msg_KICK {p c chans users comment} {
581 set chans [split $chans ,]
582 set users [split $users ,]
583 if {[llength $chans] > 1} {
584 foreach chan $chans user $users { process_kickpart $chan $user }
586 foreach user $users { process_kickpart [lindex $chans 0] $user }
590 proc msg_KILL {p c user why} {
595 set nick_arys {onchans username unique}
596 # nick_onchans($luser) -> [list ... $lchan ...]
597 # nick_username($luser) -> <securely known local username>
598 # nick_unique($luser) -> <counter>
599 # nick_case($luser) -> $user (valid even if no longer visible)
600 # nick_markid($luser) -> <after id for marktime>
602 # chan_nicks($lchan) -> [list ... $luser ...]
603 # chan_lastactivity($lchan) -> [clock seconds]
605 proc lnick_forget {luser} {
606 global nick_arys chan_nicks
607 lnick_marktime_cancel $luser
608 foreach ary $nick_arys {
609 upvar #0 nick_${ary}($luser) av
612 foreach lch [array names chan_nicks] {
613 upvar #0 chan_nicks($lch) nlist
614 set nlist [grep tn {"$tn" != "$luser"} $nlist]
619 proc nick_forget {user} {
620 global nick_arys chan_nicks
621 lnick_forget [irctolower $user]
625 proc nick_case {user} {
627 set nick_case([irctolower $user]) $user
630 proc msg_NICK {p c newnick} {
631 global nick_arys nick_case
633 recordlastseen_n $n "changing nicks to $newnick" 0
634 recordlastseen_n $newnick "changing nicks from $n" 1
635 set luser [irctolower $n]
636 lnick_marktime_cancel $luser
637 set lusernew [irctolower $newnick]
638 foreach ary $nick_arys {
639 upvar #0 nick_${ary}($luser) old
640 upvar #0 nick_${ary}($lusernew) new
641 if {[info exists new]} { error "nick collision ?! $ary $n $newnick" }
642 if {[info exists old]} { set new $old; unset old }
644 upvar #0 nick_onchans($lusernew) oc
646 upvar #0 chan_nicks($ch) nlist
647 set nlist [grep tn {"$tn" != "$luser"} $nlist]
648 lappend nlist $lusernew
650 lnick_marktime_start $lusernew "Hi." 500
654 proc nick_ishere {n} {
656 upvar #0 nick_unique([irctolower $n]) u
657 if {![info exists u]} { set u [incr nick_counter].$n.[clock seconds] }
661 proc msg_JOIN {p c chan} {
663 recordlastseen_n $n "joining $chan" 1
664 set nl [irctolower $n]
665 set lchan [irctolower $chan]
666 upvar #0 nick_onchans($nl) oc
667 upvar #0 chan_nicks($lchan) nlist
668 if {![info exists oc]} {
669 global marktime_join_startdelay
670 lnick_marktime_start $nl "Welcome." $marktime_join_startdelay
676 proc msg_PART {p c chan} {
678 recordlastseen_n $n "leaving $chan" 1
679 process_kickpart $chan $n
681 proc msg_QUIT {p c why} {
683 recordlastseen_n $n "leaving ($why)" 0
687 proc msg_PRIVMSG {p c dest text} {
689 if {[ischan $dest]} {
690 recordlastseen_n $n "invoking me in $dest" 1
693 recordlastseen_n $n "talking to me" 1
699 regsub {^! *} $text {} text
701 set procname ucmd/[string tolower $ucmd]
702 if {[catch { info body $procname }]} {
703 error "unknown command; try help for help"
707 sendprivmsg $n "error: $rv"
709 manyset $rv priv_msgs pub_msgs priv_acts pub_acts
710 foreach {td val} [list $n $priv_acts $output $pub_acts] {
711 foreach l [split $val "\n"] {
712 sendaction_priority 0 $td $l
715 foreach {td val} [list $n $priv_msgs $output $pub_msgs] {
716 foreach l [split $val "\n"] {
723 proc msg_INVITE {p c n chan} {
724 after 1000 [list dojoin [irctolower $chan]]
727 proc grep {var predicate list} {
731 if {[uplevel 1 [list expr $predicate]]} { lappend o $v }
736 proc msg_353 {p c dest type chan nicklist} {
737 global names_chans nick_onchans
738 set lchan [irctolower $chan]
739 upvar #0 chan_nicks($lchan) nlist
740 lappend names_chans $lchan
741 if {![info exists nlist]} {
742 # We don't think we're on this channel, so ignore it !
743 # Unfortunately, because we don't get a reply to PART,
744 # we have to remember ourselves whether we're on a channel,
745 # and ignore stuff if we're not, to avoid races. Feh.
749 foreach user [split $nicklist { }] {
750 regsub {^[@+]} $user {} user
751 if {![string length $user]} continue
753 set luser [irctolower $user]
754 upvar #0 nick_onchans($luser) oc
756 lappend nlist_new $luser
762 proc msg_366 {p c args} {
763 global names_chans nick_onchans
764 set lchan [irctolower $c]
765 foreach luser [array names nick_onchans] {
766 upvar #0 nick_onchans($luser) oc
767 if {[llength names_chans] > 1} {
768 set oc [grep tc {[lsearch -exact $tc $names_chans] >= 0} $oc]
770 if {![llength $oc]} { lnick_forget $n }
777 return [expr {!![string length $text]}]
782 if {[string length $text]} { error "too many parameters" }
787 if {![regexp {^([^ ]+) *(.*)} $text dummy firstword text]} {
788 error "too few parameters"
800 proc def_ucmd {cmdname body} {
801 proc ucmd/$cmdname {p dest} " upvar 1 text text\n$body"
804 proc ucmdr {priv pub args} {
805 return -code return [concat [list $priv $pub] $args]
809 global help_topics errorInfo
811 catch { unset help_topics }
812 set f [open helpinfos r]
815 while {[gets $f l] >= 0} {
817 if {[regexp {^#.*} $l]} {
818 } elseif {[regexp {^ *$} $l]} {
819 if {[info exists topic]} {
820 set help_topics($topic) [join $lines "\n"]
824 } elseif {[regexp {^\:\:} $l]} {
825 } elseif {[regexp {^\:([-+._0-9a-z]*)$} $l dummy newtopic]} {
826 if {[info exists topic]} {
827 error "help $newtopic while in $topic"
831 } elseif {[regexp {^[^:#]} $l]} {
833 regsub -all {([^\\])\!\$?} _$l {\1} l
834 regsub -all {\\(.)} $l {\1} l
836 lappend lines [string trimright $l]
838 error "eh ? $lno: $l"
841 if {[info exists topic]} { error "unfinished topic $topic" }
843 set errorInfo "in helpinfos line $lno\n$errorInfo"
852 set topic [irctolower [string trim $text]]
853 if {[string length $topic]} {
854 set ontopic " on `$topic'"
858 if {[set lag [out_lagged]]} {
859 if {[ischan $dest]} { set replyto $dest } else { set replyto $n }
861 sendaction_priority 1 $replyto \
862 "is very lagged. Please ask for help$ontopic again later."
865 sendaction_priority 1 $replyto \
866 "is lagged. Your help$ontopic will arrive shortly ..."
870 upvar #0 help_topics($topic) info
871 if {![info exists info]} { ucmdr "No help on $topic, sorry." {} }
877 ucmdr $help_topics() {}
880 proc check_username {target} {
882 [string length $target] > 8 ||
883 [regexp {[^-0-9a-z]} $target] ||
884 ![regexp {^[a-z]} $target]
885 } { error "invalid username" }
888 proc somedb__head {} {
890 set idl [irctolower $id]
891 upvar #0 ${nickchan}db($idl) ndbe
892 binary scan $idl H* idh
893 set idfn $fprefix$idh
894 if {![info exists iddbe] && [file exists $idfn]} {
896 try_except_finally { set newval [read $f] } {} { close $f }
897 if {[llength $newval] % 2} { error "invalid length" }
903 proc def_somedb {name arglist body} {
904 foreach {nickchan fprefix} {nick users/n chan chans/c} {
905 proc ${nickchan}db_$name $arglist \
906 "set nickchan $nickchan; set fprefix $fprefix; $body"
912 foreach path [glob -nocomplain -path $fprefix *] {
913 binary scan $path "A[string length $fprefix]A*" afprefix thinghex
914 if {"$afprefix" != "$fprefix"} { error "wrong prefix $path $afprefix" }
915 lappend list [binary format H* $thinghex]
920 proc def_somedb_id {name arglist body} {
921 def_somedb $name [concat id $arglist] "somedb__head; $body"
924 def_somedb_id exists {} {
925 return [info exists iddbe]
928 def_somedb_id delete {} {
929 catch { unset iddbe }
933 set default_settings_nick {timeformat ks marktime off}
934 set default_settings_chan {
943 def_somedb_id set {args} {
944 upvar #0 default_settings_$nickchan def
945 if {![info exists iddbe]} { set iddbe $def }
946 foreach {key value} [concat $iddbe $args] { set a($key) $value }
948 foreach {key value} [array get a] { lappend newval $key $value }
949 set f [open $idfn.new w]
953 file rename -force $idfn.new $idfn
961 def_somedb_id get {key} {
962 upvar #0 default_settings_$nickchan def
963 if {[info exists iddbe]} {
964 set l [concat $iddbe $def]
968 foreach {tkey value} $l {
969 if {"$tkey" == "$key"} { return $value }
971 error "unset setting $key"
976 if {[info exists calling_nick]} { set n $calling_nick } { set n {} }
977 return [nickdb_get $n $key]
980 proc check_notonchan {} {
982 if {[ischan $dest]} { error "that command must be sent privately" }
985 proc nick_securitycheck {strict} {
987 if {![nickdb_exists $n]} { error "you are unknown to me, use `register'." }
988 set wantu [nickdb_get $n username]
989 if {![string length $wantu]} {
991 error "that feature is only available to secure users, sorry."
996 set luser [irctolower $n]
997 upvar #0 nick_username($luser) nu
998 if {![info exists nu]} {
999 error "nick $n is secure, you must identify yourself first."
1001 if {"$wantu" != "$nu"} {
1002 error "you are the wrong user - the nick $n belongs to $wantu, not $nu"
1006 proc channel_securitycheck {channel n} {
1007 # You must also call `nick_securitycheck 1'
1008 set mgrs [chandb_get $channel managers]
1009 if {[lsearch -exact [irctolower $mgrs] [irctolower $n]] < 0} {
1010 error "you are not a manager of $channel"
1014 proc def_chancmd {name body} {
1015 proc channel/$name {} \
1016 " upvar 1 target chan; upvar 1 n n; upvar 1 text text; $body"
1019 proc ta_listop {findnow procvalue} {
1020 # findnow and procvalue are code fragments which will be executed
1021 # in the caller's level. findnow should set ta_listop_ev to
1022 # the current list, and procvalue should treat ta_listop_ev as
1023 # a proposed value in the list and check and possibly modify
1024 # (canonicalise?) it. After ta_listop, ta_listop_ev will
1025 # be the new value of the list.
1026 upvar 1 ta_listop_ev exchg
1028 set opcode [ta_word]
1029 switch -exact _$opcode {
1033 foreach item $exchg { set array($item) 1 }
1036 error "list change opcode must be one of + - ="
1039 foreach exchg [split $text " "] {
1040 if {![string length $exchg]} continue
1041 uplevel 1 $procvalue
1042 if {"$opcode" != "-"} {
1045 catch { unset array($exchg) }
1048 set exchg [lsort [array names array]]
1051 def_chancmd manager {
1053 if {[chandb_exists $chan]} {
1054 set ta_listop_ev [chandb_get $chan managers]
1056 set ta_listop_ev [list [irctolower $n]]
1059 check_nick $ta_listop_ev
1060 set ta_listop_ev [irctolower $ta_listop_ev]
1062 if {[llength $ta_listop_ev]} {
1063 chandb_set $chan managers $ta_listop_ev
1064 ucmdr "Managers of $chan: $ta_listop_ev" {}
1067 ucmdr {} {} "forgets about managing $chan." {}
1071 def_chancmd autojoin {
1073 switch -exact [string tolower $yesno] {
1076 default { error "channel autojoin must be `yes' or `no' }
1078 chandb_set $chan autojoin $nv
1079 ucmdr [expr {$nv ? "I will join $chan when I'm restarted " : \
1080 "I won't join $chan when I'm restarted "}] {}
1083 def_chancmd userinvite {
1084 set nv [string tolower [ta_word]]
1086 pub { set txt "!invite will work for $chan, but it won't work by /msg" }
1087 here { set txt "!invite and /msg invite will work, but only for users who are already on $chan." }
1088 all { set txt "Any user will be able to invite themselves or anyone else to $chan." }
1089 none { set txt "I will not invite anyone to $chan." }
1091 error "channel userinvite must be `pub', `here', `all' or `none'
1094 chandb_set $chan userinvite $nv
1100 switch -exact $what {
1103 chandb_set $chan topicset {}
1104 ucmdr "I won't ever change the topic of $chan." {}
1107 set t [string trim $text]
1108 if {![string length $t]} {
1109 error "you must specific the topic to set"
1111 chandb_set $chan topicset $t
1112 ucmdr "Whenever I'm alone on $chan, I'll set the topic to $t." {}
1116 set ta_listop_ev [chandb_get $chan topic$what]
1118 if {"$ta_listop_ev" != "*"} {
1119 if {![ischan $ta_listop_ev]} {
1120 error "bad channel \`$ta_listop_ev' in topic $what"
1122 set ta_listop_ev [irctolower $ta_listop_ev]
1125 chandb_set $chan topic$what $ta_listop_ev
1126 ucmdr "Topic $what list for $chan: $ta_listop_ev" {}
1129 error "unknown channel topic subcommand - see help channel"
1136 if {"$mode" != "*" && ![regexp {^(([-+][imnpst]+)+)$} $mode mode]} {
1137 error {channel mode must be * or match ([-+][imnpst]+)+}
1139 chandb_set $chan mode $mode
1140 if {"$mode" == "*"} {
1141 ucmdr "I won't ever change the mode of $chan." {}
1143 ucmdr "Whenever I'm alone on $chan, I'll set the mode to $mode." {}
1148 if {[chandb_exists $chan]} {
1149 set l "Settings for $chan: autojoin "
1150 append l [lindex {no yes} [chandb_get $chan autojoin]]
1151 append l ", mode " [chandb_get $chan mode]
1152 append l ", userinvite " [chandb_get $chan userinvite] "."
1153 append l "\nManagers: "
1154 append l [join [chandb_get $chan managers] " "]
1155 foreach {ts sep} {see "\n" tell " "} {
1156 set t [chandb_get $chan topic$ts]
1159 append l "Topic $ts list: $t."
1161 append l "Topic $ts list is empty."
1165 set t [chandb_get $chan topicset]
1166 if {[string length $t]} {
1167 append l "Topic to set: $t"
1169 append l "I will not change the topic."
1173 ucmdr {} "The channel $chan is not managed."
1177 proc channelmgr_monoop {} {
1182 upvar 1 target target
1187 if {[ischan $dest]} { set target $dest }
1188 if {[ta_anymore]} { set target [ta_word] }
1190 if {![info exists target]} {
1191 error "you must specify, or invoke me on, the relevant channel"
1193 if {![info exists chan_nicks([irctolower $target])]} {
1194 error "I am not on $target."
1196 if {![ischan $target]} { error "not a valid channel" }
1198 if {![chandb_exists $target]} { error "$target is not a managed channel." }
1199 nick_securitycheck 1
1200 channel_securitycheck $target $n
1205 sendout MODE $target +o $n
1216 if {[ischan $dest]} {
1220 set target [ta_word]
1223 set ltarget [irctolower $target]
1224 if {![ischan $target]} { error "$target is not a channel." }
1225 if {![info exists chan_nicks($ltarget)]} { error "I am not on $target." }
1226 set ui [chandb_get $ltarget userinvite]
1227 if {"$ui" == "pub" && !$onchan} {
1228 error "Invitations to $target must be made with !invite."
1230 if {"$ui" != "all"} {
1232 if {[lsearch -exact $chan_nicks($ltarget) [irctolower $n]] < 0} {
1233 error "Invitations to $target may only be made by a user on the channel."
1236 if {"$ui" == "none"} {
1237 error "Sorry, I've not been authorised to invite people to $target."
1239 if {![ta_anymore]} {
1240 error "You have to say who to invite."
1243 while {[ta_anymore]} {
1244 set invitee [ta_word]
1246 lappend invitees $invitee
1248 foreach invitee $invitees {
1249 sendout INVITE $invitee $ltarget
1251 set who [lindex $invitees 0]
1252 switch -exact llength $invitees {
1253 0 { error "zero invitees" }
1255 2 { append who " and [lindex $invitees 1]" }
1257 set who [join [lreplace $invitees end end] ", "]
1258 append who " and [lindex $invitees [llength $invitees]]"
1261 ucmdr {} "invites $who to $target."
1265 if {[ischan $dest]} { set target $dest }
1266 if {![ta_anymore]} {
1269 set subcmd [ta_word]
1271 if {[ischan $subcmd]} {
1273 if {![ta_anymore]} {
1276 set subcmd [ta_word]
1279 if {![info exists target]} { error "privately, you must specify a channel" }
1280 set procname channel/$subcmd
1281 if {"$subcmd" != "show"} {
1282 if {[catch { info body $procname }]} { error "unknown channel setting $subcmd" }
1284 nick_securitycheck 1
1285 if {[chandb_exists $target]} {
1286 channel_securitycheck $target $n
1288 upvar #0 chan_initialop([irctolower $target]) io
1289 upvar #0 nick_unique([irctolower $n]) u
1290 if {![info exists io]} { error "$target is not a managed channel" }
1291 if {"$io" != "$u"} { error "you are not the interim manager of $target" }
1292 if {"$subcmd" != "manager"} { error "use `channel manager' first" }
1300 set target [ta_word]; ta_nomore
1305 set myself [expr {"$target" != "$n"}]
1307 set ltarget [irctolower $target]
1308 upvar #0 nick_case($ltarget) ctarget
1310 if {[info exists ctarget]} {
1311 upvar #0 nick_onchans($ltarget) oc
1312 upvar #0 nick_username($ltarget) nu
1313 if {[info exists oc]} { set nshow $ctarget }
1315 if {![nickdb_exists $ltarget]} {
1316 set ol "$nshow is not a registered nick."
1317 } elseif {[string length [set username [nickdb_get $target username]]]} {
1318 set ol "The nick $nshow belongs to the user $username."
1320 set ol "The nick $nshow is registered (but not to a username)."
1322 if {![info exists ctarget] || ![info exists oc]} {
1324 append ol "\nI can't see $nshow on anywhere."
1326 append ol "\nYou aren't on any channels with me."
1328 } elseif {![info exists nu]} {
1329 append ol "\n$nshow has not identified themselves."
1330 } elseif {![info exists username]} {
1331 append ol "\n$nshow has identified themselves as the user $nu."
1332 } elseif {"$nu" != "$username"} {
1333 append ol "\nHowever, $nshow is being used by the user $nu."
1335 append ol "\n$nshow has identified themselves to me."
1343 set old [nickdb_exists $n]
1344 if {$old} { nick_securitycheck 0 }
1345 set luser [irctolower $n]
1346 switch -exact [string tolower [string trim $text]] {
1348 upvar #0 nick_username($luser) nu
1349 if {![info exists nu]} {
1351 "You must identify yourself before using `register'. See `help identify', or use `register insecure'."
1353 nickdb_set $n username $nu
1354 ucmdr {} {} "makes a note of your username." {}
1358 ucmdr {} {} "forgets your nickname." {}
1361 nickdb_set $n username {}
1363 ucmdr {} "Security is now disabled for your nickname !"
1365 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."
1371 proc timeformat_desc {tf} {
1373 ks { return "Times will be displayed in seconds or kiloseconds." }
1374 hms { return "Times will be displayed in hours, minutes, etc." }
1375 default { error "invalid timeformat: $v" }
1379 proc def_setting {opt show_body set_body} {
1380 proc set_show/$opt {} "
1384 if {![string length $set_body]} return
1385 proc set_set/$opt {} "
1392 def_setting timeformat {
1393 set tf [nickdb_get $n timeformat]
1394 return "$tf: [timeformat_desc $tf]"
1396 set tf [string tolower [ta_word]]
1398 set desc [timeformat_desc $tf]
1399 nickdb_set $n timeformat $tf
1403 proc marktime_desc {mt} {
1404 if {"$mt" == "off"} {
1405 return "I will not send you periodic messages."
1406 } elseif {"$mt" == "once"} {
1407 return "I will send you one informational message when I see you."
1409 return "I'll send you a message every [showintervalsecs $mt]."
1413 def_setting marktime {
1414 set mt [nickdb_get $n marktime]
1416 if {[string match $mt {[0-9]*}} { append p s }
1418 append p [marktime_desc $mt]
1422 set mt [string tolower [ta_word]]
1425 if {"$mt" == "off" || "$mt" == "once"} {
1426 } elseif {[regexp {^([0-9]+)([a-z]+)$} $mt dummy value unit]} {
1427 switch -exact $unit {
1432 default { error "unknown unit of time $unit" }
1434 if {$value > 86400*21/$u} { error "marktime interval too large" }
1435 set mt [expr {$value*$u}]
1436 if {$mt < $marktime_min} { error "marktime interval too small" }
1438 error "invalid syntax for marktime"
1440 nickdb_set $n marktime $mt
1441 lnick_marktime_start [irctolower $n] "So:" 500
1442 ucmdr {} [marktime_desc $mt]
1445 def_setting security {
1446 set s [nickdb_get $n username]
1447 if {[string length $s]} {
1448 return "Your nick, $n, is controlled by the user $s."
1450 return "Your nick, $n, is not secure."
1457 if {![nickdb_exists $n]} {
1458 ucmdr {} "You are unknown to me and so have no settings. (Use `register'.)"
1460 if {![ta_anymore]} {
1462 foreach proc [lsort [info procs]] {
1463 if {![regexp {^set_show/(.*)$} $proc dummy opt]} continue
1464 lappend ol [format "%-10s %s" $opt [set_show/$opt]]
1466 ucmdr {} [join $ol "\n"]
1469 if {[catch { info body set_show/$opt }]} {
1470 error "no setting $opt"
1472 if {![ta_anymore]} {
1473 ucmdr {} "$opt [set_show/$opt]"
1475 nick_securitycheck 0
1476 if {[catch { info body set_set/$opt }]} {
1477 error "setting $opt cannot be set with `set'"
1484 def_ucmd identpass {
1485 set username [ta_word]
1486 set passmd5 [md5sum "[ta_word]\n"]
1490 set luser [irctolower $n]
1491 upvar #0 nick_onchans($luser) onchans
1492 if {![info exists onchans] || ![llength $onchans]} {
1493 ucmdr "You must be on a channel with me to identify yourself." {}
1495 check_username $username
1496 exec userv --timeout 3 $username << "$passmd5\n" > /dev/null \
1498 upvar #0 nick_username($luser) rec_username
1499 set rec_username $username
1500 ucmdr "Pleased to see you, $username." {}
1504 set target [ta_word]
1506 check_username $target
1509 upvar #0 lastsummon($target) ls
1510 set now [clock seconds]
1511 if {[info exists ls]} {
1512 set interval [expr {$now - $ls}]
1513 if {$interval < 30} {
1515 "Please be patient; $target was summoned only [showinterval $interval]."
1518 regsub {^[^!]*!} $p {} path
1520 exec userv --timeout 3 $target irc-summon $n $path \
1521 [expr {[ischan $dest] ? "$dest" : ""}] \
1524 regsub -all "\n" $rv { / } rv
1527 if {[regexp {^problem (.*)} $rv dummy problem]} {
1528 ucmdr {} "The user `$target' $problem."
1529 } elseif {[regexp {^ok ([^ ]+) ([0-9]+)$} $rv dummy tty idlesince]} {
1530 set idletime [expr {$now - $idlesince}]
1532 ucmdr {} {} {} "invites $target ($tty[expr {
1533 $idletime > 10 ? ", idle for [showintervalsecs $idletime]" : ""
1535 [ischan $dest] ? "join us here" : "talk to you"
1538 error "unexpected response from userv service: $rv"
1542 proc md5sum {value} { exec md5sum << $value }
1545 global lastseen nick
1548 set nlower [irctolower $ncase]
1550 set now [clock seconds]
1551 if {"$nlower" == "[irctolower $nick]"} {
1552 error "I am not self-aware."
1553 } elseif {![info exists lastseen($nlower)]} {
1554 set rstr "I've never seen $ncase."
1556 manyset $lastseen($nlower) realnick time what
1557 set howlong [expr {$now - $time}]
1558 set string [showinterval $howlong]
1559 set rstr "I last saw $realnick $string, $what."
1561 if {[ischan $dest]} {
1566 upvar #0 lookedfor($nlower) lf
1567 if {[info exists lf]} { set oldvalue $lf } else { set oldvalue {} }
1568 set lf [list [list $now $n $where]]
1569 foreach v $oldvalue {
1570 if {"[irctolower [lindex $v 1]]" == "[irctolower $n]"} continue
1576 proc lnick_marktime_cancel {luser} {
1577 upvar #0 nick_markid($luser) mi
1578 if {![info exists mi]} return
1579 catch { after cancel $mi }
1583 proc lnick_marktime_doafter {luser why ms} {
1584 lnick_marktime_cancel $luser
1585 upvar #0 nick_markid($luser) mi
1586 set mi [after $ms [list lnick_marktime_now $luser $why]]
1589 proc lnick_marktime_reset {luser} {
1590 set mt [nickdb_get $luser marktime]
1591 if {"$mt" == "off" || "$mt" == "once"} return
1592 lnick_marktime_doafter $luser "Time passes." [expr {$mt*1000}]
1595 proc lnick_marktime_start {luser why ms} {
1596 set mt [nickdb_get $luser marktime]
1597 if {"$mt" == "off"} {
1598 lnick_marktime_cancel $luser
1600 lnick_marktime_doafter $luser $why $ms
1604 proc lnick_marktime_now {luser why} {
1605 upvar #0 nick_onchans($luser) oc
1606 sendprivmsg $luser [lnick_pingstring $why $oc ""]
1607 lnick_marktime_reset $luser
1610 proc lnick_pingstring {why oc apstring} {
1612 catch { exec uptime } uptime
1613 set nnicks [llength [array names nick_onchans]]
1615 {^ *([0-9:apm]+) +up.*, +(\d+) users, +load average: +([0-9., ]+) *$} \
1616 $uptime dummy time users load]} {
1617 regsub , $load {} load
1618 set uptime "$time $nnicks/$users $load"
1620 append uptime ", $nnicks nicks"
1622 if {[llength $oc]} {
1626 upvar #0 chan_lastactivity($ch) la
1627 if {![info exists la]} continue
1628 if {$la <= $best_la} continue
1629 set activity "$ch [showintervalsecs [expr {[clock seconds]-$la}]]"
1636 append str " " $uptime " " $activity
1637 if {[string length $apstring]} { append str " " $apstring }
1642 if {[ischan $dest]} {
1643 set oc [irctolower $dest]
1647 set ln [irctolower $n]
1648 if {[info exists nick_onchans($ln)]} {
1649 set oc $nick_onchans($ln)
1653 if {[llength $oc]} { lnick_marktime_reset $ln }
1655 ucmdr {} [lnick_pingstring "Pong!" $oc $text]
1658 proc ensure_globalsecret {} {
1661 if {[info exists globalsecret]} return
1662 set gsfile [open /dev/urandom r]
1663 fconfigure $gsfile -translation binary
1664 set globalsecret [read $gsfile 32]
1665 binary scan $globalsecret H* globalsecret
1670 proc ensure_outqueue {} {
1672 if {[info exists out_queue]} return
1674 set out_creditat [clock seconds]
1676 set out_lag_reported 0
1677 set out_lag_reportwhen $out_creditat
1681 logerror "failing: $msg"
1685 proc ensure_connecting {} {
1686 global sock ownfullname host port nick socketargs
1687 global musthaveping_ms musthaveping_after
1689 if {[info exists sock]} return
1690 set sock [eval socket $socketargs [list $host $port]]
1691 fconfigure $sock -buffering line
1692 fconfigure $sock -translation crlf
1694 sendout USER blight 0 * $ownfullname
1696 fileevent $sock readable onread
1698 set musthaveping_after [after $musthaveping_ms \
1699 {fail "no ping within timeout"}]
1703 global musthaveping_after
1705 after cancel $musthaveping_after
1706 unset musthaveping_after
1708 foreach chan [chandb_list] {
1709 if {[chandb_get $chan autojoin]} { dojoin $chan }