+source irccore.tcl
+source parsecmd.tcl
+source stdhelp.tcl
+
+defset marktime_min 300
+defset marktime_join_startdelay 5000
+
+proc privmsg_unlogged {prefix ischan params} {
+ if {!$ischan ||
+ [regexp {^![a-z][-a-z]*[a-z]( .*)?$} [lindex $params 1]]} {
+ return 0
+ }
+ # on-channel message, ignore
+ set chan [lindex $params 0]
+ upvar #0 chan_lastactivity([irctolower $chan]) la
+ set la [clock seconds]
+ catch_logged { recordlastseen_p $prefix "talking on $chan" 2 }
+ return 1
+}
+
+proc showintervalsecs {howlong abbrev} {
+ return [showintervalsecs/[opt timeformat] $howlong $abbrev]
+}
+
+proc formatsf {pfx value} {
+ foreach {min format} { 100 %.0f 10 %.1f 0 %.2f} {
+ set fval [format $format $value]
+ if {$fval < $min} continue
+ return [format "$fval${pfx}" $value]
+ }
+}
+
+proc showintervalsecs/beat {howlong abbrev} {
+ # We split in two to avoid overflow problems.
+ if {$howlong < 86 } {
+ # mB's
+ set pfx mB
+ return [format "%.0fmB" [expr {round($howlong * 1.157)*10} ]]
+ } else {
+ if {$howlong < 86400 } {
+ # B's
+ set pfx B
+ set value [expr {$howlong / 86.4}]
+ } else {
+ # kB's
+ set pfx kB
+ set value [expr {$howlong / 86400.0}]
+ }
+ }
+ return [formatsf $pfx $value]
+}
+
+proc showintervalsecs/ks {howlong abbrev} {
+ if {$howlong < 1000} {
+ return "${howlong}s"
+ } else {
+ if {$howlong < 1000000} {
+ set pfx ks
+ set scale 1000
+ } else {
+ set pfx Ms
+ set scale 1000000
+ }
+ set value [expr "$howlong.0 / $scale"]
+ return [formatsf $pfx $value]
+ }
+}
+
+proc format_qty {qty unit abbrev} {
+ set o $qty
+ if {$abbrev} {
+ append o [string range $unit 0 0]
+ } else {
+ append o " "
+ append o $unit
+ if {$qty != 1} { append o s }
+ }
+ return $o
+}
+
+proc showintervalsecs/hms {qty abbrev} {
+ set ul {second 60 minute 60 hour 24 day 7 week}
+ set remainv 0
+ while {[llength $ul] > 1 && $qty >= [set uv [lindex $ul 1]]} {
+ set remainu [lindex $ul 0]
+ set remainv [expr {$qty % $uv}]
+ set qty [expr {($qty-$remainv)/$uv}]
+ set ul [lreplace $ul 0 1]
+ }
+ set o [format_qty $qty [lindex $ul 0] $abbrev]
+ if {$remainv} {
+ if {!$abbrev} { append o " " }
+ append o [format_qty $remainv $remainu $abbrev]
+ }
+ return $o
+}
+
+proc showinterval {howlong} {
+ if {$howlong <= 0} {
+ return {just now}
+ } else {
+ return "[showintervalsecs $howlong 0] ago"
+ }
+}
+
+proc showtime {when} {
+ return [showinterval [expr {[clock seconds] - $when}]]
+}
+
+proc parse_interval {specified min} {
+ if {![regexp {^([0-9]+)([a-z]+)$} $specified dummy value unit]} {
+ error "invalid syntax for interval"
+ }
+ switch -exact $unit {
+ s { set u 1 }
+ ks { set u 1000 }
+ m { set u 60 }
+ h { set u 3600 }
+ mb { set u 0.0864 }
+ b { set u 86.4 }
+ kb { set u 86400 }
+ default { error "unknown unit of time $unit" }
+ }
+ if {$value > 86400*21/$u} { error "interval too large" }
+ set result [expr {round($value*$u)}]
+ if {$result < $min} { error "interval too small (<${min}s)" }
+ return $result
+}
+
+proc def_msgproc {name argl body} {
+ proc msg_$name "varbase $argl" "\
+ upvar #0 msg/\$varbase/dest d\n\
+ upvar #0 msg/\$varbase/str s\n\
+ upvar #0 msg/\$varbase/accum a\n\
+$body"
+}
+
+def_msgproc begin {dest str} {
+ set d $dest
+ set s $str
+ set a {}
+}
+
+def_msgproc append {str} {
+ set ns "$s$str"
+ if {[string length $s] && [string length $ns] > 65} {
+ msg__sendout $varbase
+ set s " [string trimleft $str]"
+ } else {
+ set s $ns
+ }
+}
+
+def_msgproc finish {} {
+ msg__sendout $varbase
+ unset s
+ unset d
+ return $a
+}
+
+def_msgproc _sendout {} {
+ lappend a [string trimright $s]
+ set s {}
+}
+
+proc looking_whenwhere {when where} {
+ set str [showtime [expr {$when-1}]]
+ if {[string length $where]} { append str " on $where" }
+ return $str
+}
+
+proc tell_getcstate {} {
+ # uses nl from caller's context
+ # imports telling (as the nick_telling) and u
+ # sets stt, telling_when
+ uplevel 1 {
+ upvar #0 nick_telling($nl) telling
+ upvar #0 nick_unique($nl) u
+
+ if {[info exists telling]} {
+ manyset $telling u_last stt telling_when
+ if {![info exists u] || "$u_last" != "$u"} {
+ set stt undelivered
+ }
+ } else {
+ set stt undelivered
+ set telling_when 0
+ }
+ }
+}
+
+proc tell_event {nl event} {
+ # For `act' we *haven't* yet done the 750ms delay; we implement
+ # that here. Also, here we turn `talk' into `talk' now and `act'
+ # later. We also support the psuedo-event `none'. The del msg
+ # and new msg events are handled by the command procedures, not here.
+ global calling_nick
+ if {[info exists calling_nick]} { set save $calling_nick }
+ set r DELAYED
+ switch -exact $event {
+ none { }
+ talk {
+ tell_event_core $nl talk
+ tell_event $nl act
+ }
+ act {
+ after 750 [list tell_event_core $nl $event]
+ }
+ ident - msgsarrive {
+ tell_event_core $nl $event
+ }
+ tellme {
+ set r [tell_event_core $nl TELLME]
+ }
+ default {
+ error "tell_event $nl $event"
+ }
+ }
+ if {[info exists save]} { set calling_nick $save }
+ return $r
+}
+
+proc tell_event_core {nl event} {
+ global tell_event_teventi errorInfo
+ set tell_event_teventi "*$event* $nl"
+ if {[catch {
+ tell_event_core1 $nl $event
+ } emsg]} {
+ log_intern "tell event error" "$emsg >$errorInfo<"
+ set emsg ERROR
+ } else {
+ if {"$emsg" != "nomsgs"} {
+ log_intern "tell event" "done $tell_event_teventi $emsg"
+ }
+ }
+ return $emsg
+}
+
+proc tell_event_core1 {nl event} {
+ # event is `talk', `act', `ident', `msgsarrive' or `TELLME'
+ # When user talks we actually get talk now and act later
+ global calling_nick
+ set calling_nick $nl
+ set iml [msgsdb_get $nl inbound]
+ if {![llength $iml]} { return nomsgs }
+
+ set now [clock seconds]
+ tell_getcstate
+ set ago [expr {$now - $telling_when}]
+
+ # Now we have the components of a telling state
+ # u - nick_unique (unset if not visible)
+ # stt - state: undelivered, mentioned, passede
+ # ago - how long ago since we did anything
+
+ # We compute an evstate to dispatch on as follows:
+
+ # evstate is string of letters
+ # current state
+ # u UNDELIVERED (MESSAGES)
+ # m MENTIONED
+ # p PASSED
+ # event
+ # t talk
+ # a act
+ # i ident
+ # m msgsarrive
+ # T tellme (user command)
+ # security level and timing
+ # ii Insecure
+ # ss Secure and soon (before interval)
+ # sl Secure and late (after interval)
+ # current identification
+ # i Identified
+ # u Unidentified
+ # reliability and timing
+ # uu Unreliable
+ # rv Remind, very soon (before within-interval)
+ # rs Remind, soon (between)
+ # rl Remind, late (after every-interval)
+ # ps Pester, soon (before interval)
+ # pl Pester, late (after interval)
+
+ set evstate {}
+
+ append evstate [string range $stt 0 0]
+ append evstate [string range $event 0 0]
+
+ manyset [nickdb_get_sec_effective $nl] sec secwhen
+ switch -exact $sec {
+ insecure { append evstate ii }
+ secure { append evstate [expr {$ago<$secwhen ? "ss" : "sl"}] }
+ default { append evstate "#$sec#" }
+ }
+
+ upvar #0 nick_username($nl) nu
+ if {[info exists nu] && "$nu" == "[nickdb_get_username $nl]"} {
+ append evstate i
+ } else {
+ append evstate u
+ }
+
+ manyset [nickdb_get $nl tellrel] rel relint relwithin
+ switch -exact $rel {
+ unreliable { append evstate uu }
+ remind { append evstate [expr {
+ $ago<$relwithin ? "rv" : $ago<$relint ? "rs" : "rl"
+ }]}
+ pester { append evstate [expr {$ago<$relint ? "ps" : "pl"}] }
+ default { append evstate "#$rel#" }
+ }
+
+ global tell_event_teventi
+ set tell_event_teventi "$evstate $ago $nl"
+ switch -glob $evstate {
+ pt???rv {
+ # consider delivered:
+ # (very recently passed, and the user talks)
+ set ndel [tell_delete_msgs {} $nl]
+ sendprivmsg $nl \
+ "I'm assuming you got the $ndel message(s) I just passed on."
+ return delivered
+ }
+ pm????? {
+ # oops, messages passed are now out of date
+ catch_restoreei { unset telling }
+ return reset
+ }
+ ?m????? {
+ # ignore new msgs if we haven't passed yet
+ return ignorenew
+ }
+ ut????? - mt????? -
+ pt???uu - pt???rs - pt???rl - pt???p? {
+ # ignore (any other `talk's) - act handles these
+ return ignoretalk
+ }
+ ui????? -
+ uaii?uu - uaii??l - uas?iuu - uas?i?l -
+ mi????? - pa????l -
+ ?Tii??? - ?Ts?i?? {
+ # pass and then stuff
+ if {[llength $iml] == 3} {
+ manyset $iml sender sentwhen msg
+ sendprivmsg $nl \
+ "$sender asked me, [showinterval [expr {$now-$sentwhen}]],\
+ to tell you: $msg"
+ } else {
+ sendprivmsg $nl \
+ "I have [expr {[llength $iml]/3}] messages for you:"
+ while {[llength $iml] >= 3} {
+ manyset [lrange $iml 0 2] sender sentwhen msg
+ set iml [lrange $iml 3 end]
+ sendprivmsg $nl \
+ " [showintervalsecs [expr {$now-$sentwhen}] 1] <$sender> $msg"
+ }
+ }
+ if {"$rel" == "unreliable"} {
+ tell_delete_msgs {} $nl
+ return toldunreliable
+ }
+ set stt passed
+ set re passed
+ }
+ uaslu?? {
+ sendprivmsg $nl {You have messages (so identify yourself please).}
+ set stt mentioned
+ set re mentioned
+ }
+ ?Ts?u?? {
+ sendprivmsg $nl {You must identify yourself to see your messages.}
+ return ignoreuitm
+ }
+ masl??? {
+ sendprivmsg $nl {Don't forget about your messages.}
+ return remind
+ }
+ pi????? {
+ return ignorepi
+ }
+ mass??? - pa????v - pa????s -
+ uaii??v - uaii??s -
+ uas?i?v - uas?i?s -
+ uassu?? {
+ # too soon
+ return ignoresoon
+ }
+ * {
+ error "tell_event_core nl=$nl evstate=$evstate ?"
+ }
+ }
+ if {![info exists u]} {
+ set telling [list {} undelivered $now]
+ } else {
+ set telling [list $u $stt $now]
+ }
+ return $re
+}
+
+proc recordlastseen_n {n how here} {
+ # here is:
+ # 0 - nick was seen leaving (or changing to another nicks or some such)
+ # 1 - nick was seen doing something else
+ # 2 - nick was seen talking on channel
+ global lastseen lookedfor
+ set nl [irctolower $n]
+ set now [clock seconds]
+ set lastseen($nl) [list $n $now $how]
+
+ if {!$here} return
+
+ tell_event $nl [lindex {none act talk} $here]
+
+ upvar #0 lookedfor($nl) lf
+ if {[info exists lf]} {
+ switch -exact [llength $lf] {
+ 0 {
+ set ml {}
+ }
+ 1 {
+ manyset [lindex $lf 0] when who where
+ set ml [list \
+ "FYI, $who was looking for you [looking_whenwhere $when $where]."]
+ }
+ default {
+ msg_begin tosend $n "FYI, people have been looking for you:"
+ set i 0
+ set fin ""
+ foreach e $lf {
+ incr i
+ if {$i == 1} {
+ msg_append tosend " "
+ } elseif {$i == [llength $lf]} {
+ msg_append tosend " and "
+ set fin .
+ } else {
+ msg_append tosend ", "
+ }
+ manyset $e when who where
+ msg_append tosend \
+ "$who ([looking_whenwhere $when $where])$fin"
+ }
+ set ml [msg_finish tosend]
+ }
+ }
+ unset lf
+ msendprivmsg_delayed 1000 $n $ml
+ }
+}
+
+proc note_topic {showoff whoby topic} {
+ set msg "FYI, $whoby has changed the topic on $showoff"
+ if {[string length $topic] < 160} {
+ append msg " to $topic"
+ } else {
+ append msg " but it is too long to reproduce here !"
+ }
+ set showoff [irctolower $showoff]
+ set tell [chandb_get $showoff topictell]
+ if {[lsearch -exact $tell *] >= 0} {
+ set tryspies [chandb_list]
+ } else {
+ set tryspies $tell
+ }
+ foreach spy $tryspies {
+ set see [chandb_get $spy topicsee]
+ if {[lsearch -exact $see $showoff] >= 0 || \
+ ([lsearch -exact $see *] >= 0 && \
+ [lsearch -exact $tell $spy] >= 0)} {
+ sendprivmsg $spy $msg
+ }
+ }
+}
+
+proc recordlastseen_p {p how here} {
+ prefix_nick
+ recordlastseen_n $n $how $here
+}
+
+proc chanmode_arg {} {
+ upvar 2 args cm_args
+ set rv [lindex $cm_args 0]
+ set cm_args [lreplace cm_args 0 0]
+ return $rv
+}
+
+proc chanmode_o1 {m g p chan} {
+ global nick chan_initialop
+ prefix_nick
+ set who [chanmode_arg]
+ recordlastseen_n $n "being nice to $who" 1
+ if {"[irctolower $who]" == "[irctolower $nick]"} {
+ set nlower [irctolower $n]
+ upvar #0 nick_unique($nlower) u
+ if {[chandb_exists $chan]} {
+ sendprivmsg $n Thanks.
+ } elseif {![info exists u]} {
+ sendprivmsg $n {Op me while not on the channel, why don't you ?}
+ } else {
+ set chan_initialop([irctolower $chan]) $u
+ sendprivmsg $n \
+ "Thanks. You can use `channel manager ...' to register this channel."
+ if {![string length [nickdb_get_username $n username]]} {
+ sendprivmsg $n \
+ "(But to do that you must register your nick securely first.)"
+ }
+ }
+ }
+}
+
+proc chanmode_o0 {m g p chan} {
+ global nick chandeop
+ prefix_nick
+ set who [chanmode_arg]
+ recordlastseen_p $p "being mean to $who" 1
+ if {"[irctolower $who]" == "[irctolower $nick]"} {
+ set chandeop($chan) [list [clock seconds] $p]
+ }
+}
+
+proc msg_MODE {p c dest modelist args} {
+ if {![ischan $dest]} return
+ if {[regexp {^\-(.+)$} $modelist dummy modelist]} {
+ set give 0
+ } elseif {[regexp {^\+(.+)$} $modelist dummy modelist]} {
+ set give 1
+ } else {
+ error "invalid modelist"
+ }
+ foreach m [split $modelist] {
+ set procname chanmode_$m$give
+ if {[catch { info body $procname }]} {
+ recordlastseen_p $p "fiddling with $dest" 1
+ } else {
+ $procname $m $give $p $dest
+ }
+ }
+}
+
+proc leaving {lchan} {
+ global nick_onchans
+ foreach luser [array names nick_onchans] {
+ upvar #0 nick_onchans($luser) oc
+ set oc [grep tc {"$tc" != "$lchan"} $oc]
+ }
+ upvar #0 chan_nicks($lchan) nlist
+ unset nlist
+ upvar #0 chan_lastactivity($lchan) la
+ catch { unset la }
+}
+
+proc doleave {lchan} {
+ sendout PART $lchan
+ leaving $lchan
+}
+
+proc dojoin {lchan} {
+ global chan_nicks
+ sendout JOIN $lchan
+ set chan_nicks($lchan) {}
+}
+
+proc check_justme {lchan} {
+ global nick
+ upvar #0 chan_nicks($lchan) nlist
+ if {[llength $nlist] != 1} return
+ if {"[lindex $nlist 0]" != "[irctolower $nick]"} return
+ if {[chandb_exists $lchan]} {
+ set mode [chandb_get $lchan mode]
+ if {"$mode" != "*"} {
+ sendout MODE $lchan $mode
+ }
+ set topic [chandb_get $lchan topicset]
+ if {[string length $topic]} {
+ sendout TOPIC $lchan $topic
+ }
+ } else {
+ doleave $lchan
+ }
+}
+
+proc process_kickpart {chan user} {
+ global nick
+ check_nick $user
+ set luser [irctolower $user]
+ set lchan [irctolower $chan]
+ if {![ischan $chan]} { error "not a channel" }
+ if {"$luser" == "[irctolower $nick]"} {
+ leaving $lchan
+ } else {
+ upvar #0 nick_onchans($luser) oc
+ upvar #0 chan_nicks($lchan) nlist
+ set oc [grep tc {"$tc" != "$lchan"} $oc]
+ set nlist [grep tn {"$tn" != "$luser"} $nlist]
+ nick_case $user
+ if {![llength $oc]} {
+ nick_forget $luser
+ } else {
+ check_justme $lchan
+ }
+ }
+}
+
+proc msg_TOPIC {p c dest topic} {
+ prefix_nick
+ if {![ischan $dest]} return
+ recordlastseen_n $n "changing the topic on $dest" 1
+ note_topic [irctolower $dest] $n $topic
+}
+
+proc msg_KICK {p c chans users comment} {
+ set chans [split $chans ,]
+ set users [split $users ,]
+ if {[llength $chans] > 1} {
+ foreach chan $chans user $users { process_kickpart $chan $user }
+ } else {
+ foreach user $users { process_kickpart [lindex $chans 0] $user }
+ }
+}
+
+proc msg_KILL {p c user why} {
+ nick_forget $user
+}
+
+set nick_counter 0
+set nick_arys {onchans username unique}
+# nick_onchans($luser) -> [list ... $lchan ...]
+# nick_username($luser) -> <securely known local username>
+# nick_unique($luser) -> <includes-counter>
+# nick_case($luser) -> $user (valid even if no longer visible)
+# nick_markid($luser) -> <after id for marktime>
+# nick_telling($luser) -> <unique> mentioned|passed <when>
+
+# chan_nicks($lchan) -> [list ... $luser ...]
+# chan_lastactivity($lchan) -> [clock seconds]
+
+proc lnick_forget {luser} {
+ global nick_arys chan_nicks
+ lnick_marktime_cancel $luser
+ foreach ary $nick_arys {
+ upvar #0 nick_${ary}($luser) av
+ catch { unset av }
+ }
+ foreach lch [array names chan_nicks] {
+ upvar #0 chan_nicks($lch) nlist
+ set nlist [grep tn {"$tn" != "$luser"} $nlist]
+ check_justme $lch
+ }
+}
+
+proc nick_forget {user} {
+ global nick_arys chan_nicks
+ lnick_forget [irctolower $user]
+ nick_case $user
+}
+
+proc nick_case {user} {
+ global nick_case
+ set nick_case([irctolower $user]) $user
+}
+
+proc msg_NICK {p c newnick} {
+ global nick_arys nick_case calling_nick
+ prefix_nick
+ recordlastseen_n $n "changing nicks to $newnick" 0
+ set calling_nick $newnick
+ recordlastseen_n $newnick "changing nicks from $n" 1
+ set luser [irctolower $n]
+ lnick_marktime_cancel $luser
+ set lusernew [irctolower $newnick]
+ foreach ary $nick_arys {
+ upvar #0 nick_${ary}($luser) old
+ upvar #0 nick_${ary}($lusernew) new
+ if {[info exists new]} { error "nick collision ?! $ary $n $newnick" }
+ if {[info exists old]} { set new $old; unset old }
+ }
+ upvar #0 nick_onchans($lusernew) oc
+ foreach ch $oc {
+ upvar #0 chan_nicks($ch) nlist
+ set nlist [grep tn {"$tn" != "$luser"} $nlist]
+ lappend nlist $lusernew
+ }
+ lnick_marktime_start $lusernew "Hi." 500 1
+ nick_case $newnick
+}
+
+proc nick_ishere {n} {
+ global nick_counter
+ upvar #0 nick_unique([irctolower $n]) u
+ if {![info exists u]} { set u [incr nick_counter].$n.[clock seconds] }
+ nick_case $n
+}
+
+proc msg_JOIN {p c chan} {
+ prefix_nick
+ nick_ishere $n
+ recordlastseen_n $n "joining $chan" 1
+ set nl [irctolower $n]
+ set lchan [irctolower $chan]
+ upvar #0 nick_onchans($nl) oc
+ upvar #0 chan_nicks($lchan) nlist
+ if {![info exists oc]} {
+ global marktime_join_startdelay
+ lnick_marktime_start $nl "Welcome." $marktime_join_startdelay 1
+ }
+ lappend oc $lchan
+ lappend nlist $nl
+}
+proc msg_PART {p c chan args} {
+ prefix_nick
+ set msg "leaving $chan"