chiark / gitweb /
bugfixes
[ircbot.git] / ledmodule.tcl
1 # maintains local list of users to userv-slurp config from
2 # each user provides list of
3 #    monitors
4 #    devicesets
5 #
6 # a monitor specifies
7 #    name
8 #    IRC channel(s)
9 #    nicks ignore totally
10 #    nicks ignore presence
11 #    nicks prefer speech
12 #    time for `a while ago'
13 #    time for `very-recently'
14 # syntax
15 #    nick ignore|nopresence|prefer <glob-pattern> [...]
16 #    times <very-recently> <a-while-ago>                  (default 120 450)
17 #      (affect subsequent `monitor' directives)
18 #    monitor <monname> <#chan>[,<#chan>...]
19 #      <monname> must start with <username>:
20 #
21 # a deviceset specifies
22 #    monitor
23 #    led-group
24 #    led states
25 # syntax
26 #    leds <led-group> <monname> <state>=<value>
27 # where state is one of
28 #    [pref]talk[now]  any non-ignored (with `pref', only any preferred)
29 #                     nick(s) spoke at least somewhat recently
30 #                     (with `now', only if they spoke very recently)
31 #    present          at least some non-nopresence nicks present
32 #    default          always matches
33 # where the first matching state wins; if none, no LEDs are set
34
35 set helpfile ledhelp
36
37 source irccore.tcl
38 source parsecmd.tcl
39 source stdhelp.tcl
40 source userv.tcl
41
42 defset errchan #$nick
43 defset retry_after 900000
44 defset chan_after 1500
45 defset chans_retry 3600000
46 defset debug_reset_after 86400000
47
48 defset debugusers {}
49
50 # variables
51 #
52 #   monitor/$monname(chans)           -> [list $chan1 $chan2 ...]
53 #   monitor/$monname(ignore)          -> [list $regexp ...]
54 #   monitor/$monname(prefer)          -> [list $regexp ...]
55 #   monitor/$monname(present-$chan)   -> [list $lnick ...]
56 #   monitor/$monname(last-talk)       -> $time_t
57 #   monitor/$monname(last-talkpref)   -> $time_t
58 #   monitor/$monname(time-recent)     -> $seconds
59 #   monitor/$monname(time-recentnow)  -> $seconds
60 #   monitor/$monname(talkchange)      -> [after ...]    or unset
61 #
62 #   deviceset/$username:$lno(monname)  -> $monname
63 #   deviceset/$username:$lno(group)    -> $led_group
64 #   deviceset/$username:$lno(username) -> $username
65 #   deviceset/$username:$lno(values)   -> $valuestring
66 #   deviceset/$username:$lno(states)   -> [list $state1 $value1 $state2 ...]
67 #   deviceset/$username:$lno(ochan)    -> [open remoteleds ... | r]  or unset
68 #   deviceset/$username:$lno(ichan)    -> fifo for remoteleds input  or unset
69 #   deviceset/$username:$lno(retry)    -> [after ... ]             or unset
70 #
71 #   onchans($chan)        [list mustleave]                 # in config_chane
72 #   onchans($chan)        [list idle]
73 #   onchans($chan)        [list forced]                    # for errchan
74 #   onchans($chan)        [list shortly [after ...]]       # do a NAMES
75
76 proc ldebug {facil m} {
77     global debugusers
78     # facil is
79     #    m$monname
80     #    d$deviceset
81     #    c$lchan
82     #    {}             for system stuff
83     if {![llength $debugusers]} return
84     if {[regexp {[mdu]([^:]+)\:} $facil dummy username] &&
85         [lsearch -exact $debugusers $username]==-1} return
86
87     regsub {^(.)} $facil {\1 } cc
88     reporterr "DEBUG $cc $m"
89 }    
90
91 proc list_objs {vp} {
92     set l {}
93     foreach v [info globals] {
94         if {![regsub ^$vp/ $v {} v]} continue
95         lappend l $v
96     }
97     return $l
98 }
99
100 proc privmsg_unlogged {p ischan params} {
101     global errorInfo
102     if {!$ischan} { return 0 }
103
104     # on-channel message
105     if {[catch {
106         prefix_nick
107         foreach m [list_objs monitor] {
108             mon_speech $m [irctolower [lindex $params 0]] [irctolower $n]
109         }
110     } emsg]} {
111         log "processing error: $emsg\n$errorInfo"
112     }
113     return 1;
114 }
115
116 proc reporterr {m} {
117     global errchan
118     sendprivmsg $errchan $m
119 }
120
121 proc msg_PRIVMSG {p c dest text} {
122     global errchan
123     prefix_nick
124     execute_usercommand $p $c $n $errchan $dest $text
125 }
126
127 proc proc_mon {name argl body} {
128     proc mon_$name [concat m $argl] "
129     upvar #0 monitor/\$m mm
130     $body"
131 }
132
133 proc mon_nick_is {globlist ln} {
134     foreach gl $globlist {
135         if {[string match $gl $ln]} { return 1 }
136     }
137     return 0
138 }
139
140 proc_mon gotchanlist {ch nll} {
141     global nick
142     if {[lsearch -exact $mm(chans) $ch] == -1} return
143     set l {}
144     foreach nl $nll {
145         if {![string compare $nl [irctolower $nick]]} continue
146         if {[mon_nick_is $mm(nopresence) $nl]} continue
147         lappend l $nl
148     }
149     ldebug m$m "$ch names: $l"
150     set mm(present-$ch) $l
151     mon_updateall $m
152 }
153
154 proc_mon speech {chan ln} {
155     if {[lsearch -exact $mm(chans) $chan] == -1} return
156     if {[mon_nick_is $mm(ignore) $ln]} return
157     set now [clock seconds]
158     set mm(last-talk) $now
159     if {[mon_nick_is $mm(prefer) $ln]} { set mm(last-talkpref) $now }
160     mon_updateall $m
161 }
162
163 proc_mon calcstate {} {
164     set s " default "
165     foreach ch $mm(chans) {
166         if {[llength $mm(present-$ch)]} { append s "present "; break }
167     }
168     set now [clock seconds]
169     set valid_until [expr {$now + 86400}]
170     set refresh_later 0
171     catch { after cancel $mm(talkchange) }
172     foreach p {{} pref} {
173         foreach t {{} now} {
174             set vu [expr {$mm(last-talk$p) + $mm(time-recent$t)}]
175             if {$vu < $now} continue
176             append s "${p}talk${t} "
177             set refresh_later 1
178             if {$vu < $valid_until} { set valid_until $vu }
179         }
180     }
181     regsub {^ default } $s { } ss
182     set ds [string trim $ss]
183     if {$refresh_later} {
184         set interval [expr {$valid_until - $now + 2}]
185         set ivms [expr {$interval*1000}]
186         set mm(talkchange) [after $ivms [list mon_updateall $m]]
187         ldebug m$m "until now+${interval}: $ds"
188     } else {
189         ldebug m$m "indefinitely: $ds"
190     }
191     return $s
192 }
193
194 proc_mon updateall {} {
195     set s [mon_calcstate $m]
196     foreach d [list_objs deviceset] {
197         upvar #0 deviceset/$d dd
198         if {[string compare $m $dd(monname)]} continue
199         dset_setbystate $d $s
200     }
201 }
202
203 proc_mon destroy {} {
204     ldebug m$m "destroying"
205     catch { after cancel $mm(talkchange) }
206     catch { unset mm }
207 }
208
209 proc proc_dset {name argl body} {
210     proc dset_$name [concat d $argl] "
211     upvar #0 deviceset/\$d dd
212     if {\[catch {
213         $body
214     } emsg\]==1} {
215         reporterr \"error on \$d: \$emsg\"
216     }"
217 }
218
219 proc timed_log {m} {
220     log "[clock seconds] $m"
221 }
222
223 proc_dset setbystate {s} {
224     foreach {sq v} $dd(states) {
225         if {![string match *$sq* $s]} continue
226         set lv $v; break
227     }
228     if {![info exists dd(ichan)]} return
229     if {![info exists lv]} {
230         reporterr "no state for $d matching$s"
231         return
232     }
233     ldebug d$d "matches $sq: $v"
234     timed_log "->$d $lv"
235     set dd(values) "$sq=$lv"
236     puts $dd(ichan) $lv
237 }
238
239 proc_dset destroy {} {
240     ldebug d$d "destroying"
241     catch { after cancel $dd(retry) }
242     catch {
243         if {[info exists dd(ochan)]} { timed_log ">\$$d destroy" }
244         close $dd(ochan)
245         close $dd(ichan)
246     }
247     catch { unset dd }
248 }
249
250 proc modvar_save_copy {cv defv} {
251     upvar 1 m m
252     upvar 1 mm mm
253     upvar 1 save/$m save
254     if {[info exists save($cv)]} {
255         set mm($cv) $save($cv)
256     } else {
257         set mm($cv) $defv
258     }
259 }
260
261 proc reloaduser {username} {
262     check_username $username
263     ldebug u$username "reloading"
264     if {[catch {
265         set cfg [exec userv --timeout 3 $username irc-ledcontrol-config \
266                 < /dev/null]
267     } emsg]} {
268         regsub "\n" $emsg " // " emsg
269         reporterr "error reloading $username: $emsg"
270         return ""
271     }
272     foreach d [list_objs deviceset] {
273         if {![string match $username:* $d]} continue
274         dset_destroy $d
275     }
276     foreach m [list_objs monitor] {
277         if {![string match $username* $m]} continue
278         upvar #0 monitor/$m mm
279         foreach cv [array names mm] { set save/${m}($cv) $mm($cv) }
280     }
281     if {![string length $cfg]} {
282         file delete pwdb/$username
283         return "no config from $username"
284     } elseif {[catch {
285         exec userv --timeout 3 $username irc-ledcontrol-passwords \
286                 < /dev/null > pwdb/p$username
287     } emsg]} {
288         reporterr "error reading passwords for $username: $emsg"
289         return ""
290     } elseif {[catch {
291         ldebug u$username "parsing"
292         foreach cv {ignore nopresence prefer} { set cc($cv) {} }
293         set cc(time-recentnow) 120
294         set cc(time-recent) 450
295         set lno 0
296         set contin {}
297         foreach l [split $cfg "\n"] {
298             incr lno
299             append contin [string trim $l]
300             if {[regsub {\\$} $contin { } contin]} continue
301             set l $contin
302             set contin {}
303             if {[regexp {^\#} $l]} {
304             } elseif {[regexp {^nick\s+(ignore|nopresence|prefer)\s+(\S.*)$} \
305                     $l dummy kind globs]} {
306                 set cc($kind) {}
307                 foreach gl [split $globs " "] {
308                     if {![string length $gl]} continue
309                     string match $gl {}
310                     lappend cc($kind) $gl
311                 }
312             } elseif {[regexp {^times\s+(\d+)\s+(\d+)$} $l dummy r rnow]} {
313                 foreach cv {{} now} { set cc(time-recent$cv) [set r$cv] }
314             } elseif {[regexp {^monitor\s+(\S+)\s+(\S.*)$} $l dummy m cl]} {
315                 set cc(chans) {}
316                 if {![string match $username:* $m]} {
317                     error "monname must start with $username:"
318                 }
319                 check_monname $m
320                 foreach ch [split $cl " "] {
321                     if {![string length $ch]} continue
322                     check_chan $ch
323                     if {![ischan $ch]} { error "invalid channel $ch" }
324                     lappend cc(chans) [irctolower $ch]
325                     chan_shortly $ch
326                 }
327                 upvar #0 monitor/$m mm
328                 foreach cv [array names cc] { set mm($cv) $cc($cv) }
329                 foreach cv {{} pref} {
330                     modvar_save_copy last-talk$cv 0
331                 }
332                 foreach cv [array names mm(chans)] {
333                     modvar_save_copy present-$cv {}
334                 }
335                 ldebug m$m "created"
336             } elseif {[regexp \
337  {^leds\s+([0-9A-Za-z][-.:/0-9A-Za-z]+)\s+(\S+)\s+(\S+.*)$} \
338                     $l dummy g m states]} {
339                 set d $username:$lno:$g
340                 set sl {}
341                 check_monname $m
342                 foreach sv [split $states " "] {
343                     if {![string length $sv]} continue
344                     if {![regexp \
345  {^((?:pref)?talk(?:now)?|present|default)\=([0-9a-z][,/+0-9A-Za-z]*)$} \
346                           $sv dummy lhs rhs]} {
347                         error "invalid state spec"
348                     }
349                     lappend sl $lhs $rhs
350                 }
351                 upvar #0 deviceset/$d dd
352                 set dd(monname) $m
353                 set dd(states) $sl
354                 set dd(group) $g
355                 set dd(values) startup
356                 set dd(username) $username
357                 dset_start $d
358                 ldebug d$d "created"
359             } else {
360                 error "invalid directive or syntax"
361             }
362         }
363         if {[string length $contin]} {
364             error "continuation line at end of file"
365         }
366     } emsg]} {
367         reporterr "setup error $username:$lno:$emsg"
368         return ""
369     } else {
370         return "reloaded $username"
371     }
372 }
373
374 proc check_monname {m} {
375     if {[regexp {[^-_+:.#0-9a-zA-Z]} $m badchar]} {
376         error "char $badchar not allowed in monnames"
377     }
378     if {![regexp {^[0-9a-zA-Z]} $m]} {
379         error "monname must start with alphanum"
380     }
381 }
382
383 proc_dset start {} {
384     catch { unset dd(retry) }
385     set username $dd(username)
386     ldebug d$d "starting"
387     if {[catch {
388         set cmdl [list remoteleds --pipe $dd(group) \
389                        --human --passfile-only pwdb/p$username]
390         timed_log "!-$d [join $cmdl " "]"
391         lappend cmdl < pwdb/fifo |& cat
392         catch { file delete pwdb/fifo }
393         exec mkfifo -m 0600 pwdb/fifo
394         set ichan [open pwdb/fifo r+]
395         set ochan [open |$cmdl r]
396         fconfigure $ichan -blocking 0 -buffering line
397         fconfigure $ochan -blocking 0 -buffering line
398         set dd(ichan) $ichan
399         set dd(ochan) $ochan
400         fileevent $ochan readable [list dset_rledout $d]
401     } emsg]} {
402         reporterr "remoteleds startup $d: $emsg"
403         catch { close $ichan }
404         catch { close $ochan }
405         dset_trylater $d
406     }
407 }
408
409 proc_dset rledout {} {
410     global errchan
411     while {[gets $dd(ochan) l] != -1} {
412         reporterr "on $d: $dd(values): $l"
413     }
414     if {[fblocked $dd(ochan)]} return
415     timed_log ">\$$d failure";
416     catch { close $dd(ichan) }
417     catch { close $dd(ochan) }
418     unset dd(ichan)
419     unset dd(ochan)
420     reporterr "on $d died"
421     dset_trylater $d
422 }
423
424 proc_dset trylater {} {
425     global retry_after
426     ldebug d$d "will try again later"
427     set dd(retry) [after $retry_after [list dset_start $d]]
428 }
429
430 proc config_change {} {
431     global onchans chans_retry errchan config_retry_after
432     ldebug {} "rechecking configuration etc"
433     foreach ch [array names onchans] {
434         manyset $onchans($ch) status after
435         if {"$status" == "shortly"} {
436             catch { after cancel $after }
437         }
438         set onchans($ch) mustleave
439     }
440     sendout JOIN $errchan
441     chan_shortly $errchan
442     foreach m [list_objs monitor] {
443         upvar #0 monitor/$m mm
444         foreach ch $mm(chans) {
445             sendout JOIN $ch
446             chan_shortly $ch
447         }
448     }
449     foreach ch [array names onchans] {
450         if {"[lindex $onchans($ch) 0]" != "mustleave"} continue
451         sendout PART $ch
452         unset onchans($ch)
453     }
454     catch { after cancel $config_retry_after }
455     set config_retry_after [after $chans_retry config_change]
456 }
457
458 proc allchans_shortly {} {
459     global onchans
460     foreach ch [array names onchans] { chan_shortly $ch }
461 }
462
463 proc chan_shortly {ch} {
464     global chan_after
465     set ch [irctolower $ch]
466     upvar #0 onchans($ch) oc
467     if {[info exists oc]} {
468         manyset $oc status after
469         if {"$status" == "shortly"} {
470             ldebug c$ch "queued check already pending"
471             return
472         }
473     }
474     ldebug c$ch "queueing check"
475     set oc [list shortly [after $chan_after chan_sendnames $ch]]
476 }
477
478 proc msg_353 {p c dest type chan nicklist} {
479     set lchan [irctolower $chan]
480     set nll [irctolower $nicklist]
481     regsub -all {[=@*]} $nll {} nll
482     ldebug c$lchan "all names: $nll"
483     foreach m [list_objs monitor] {
484         mon_gotchanlist $m $lchan $nll
485     }
486 }
487
488 proc chan_sendnames {ch} {
489     upvar #0 onchans($ch) oc
490     ldebug c$ch "asking for namelist"
491     sendout NAMES $ch
492     set oc idle
493 }
494
495 def_ucmd reload {
496     set username [ta_word]
497     ta_nomore
498     set m [reloaduser $username]
499     config_change
500     ucmdr {} $m
501 }
502
503 proc debug_reset {} {
504     global debugusers debug_cancelling
505     unset debug_cancelling
506     set debugusers {}
507     reporterr "debug mode timed out"
508 }
509
510 def_ucmd debug {
511     prefix_nick
512     global debugusers debug_cancelling debug_reset_after
513     if {![string length $text]} { error "must give list of usernames" }
514     llength $text
515     set debugusers $text
516     catch { after cancel $debug_cancelling }
517     set debug_cancelling [after $debug_reset_after debug_reset]
518     reporterr "debug enabled by $n: $debugusers"
519 }
520
521 def_ucmd nodebug {
522     prefix_nick
523     ta_nomore
524     global debugusers debug_cancelling
525     set debugusers {}
526     catch { after cancel $debug_cancelling }
527     catch { unset debug_cancelling }
528     reporterr "debug disabled by $n"
529 }
530
531 def_ucmd who {
532     set r {}
533     foreach m [list_objs monitor] {
534         upvar #0 monitor/$m mm
535         lappend r "monitoring $mm(chans) for $m"
536     }
537     foreach d [list_objs deviceset] {
538         upvar #0 deviceset/$d dd
539         regexp {^[^:]*\:[^:]*} $dd(group) dest
540         lappend r "sending $dd(monname) to $dest"
541     }
542     ucmdr [join $r "\n"] {}
543 }
544
545 proc connected {} {
546     ldebug {} "connected"
547     foreach f [glob -nocomplain pwdb/p*] {
548         regexp {^pwdb/p(.*)$} $f dummy username
549         set m [reloaduser $username]
550     }
551     config_change
552 }
553
554 proc msg_JOIN {p c chan} { chan_shortly $chan }
555 proc msg_PART {p c chan} { chan_shortly $chan }
556 proc msg_KILL {p c user why} { allchans_shortly }
557 proc msg_QUIT {p c why} { allchans_shortly }
558 proc msg_NICK {p c newnick} { allchans_shortly }
559 proc msg_KICK {p c chans users comment} {
560     if {[llength $chans] > 1} {
561         allchans_shortly
562     } else {
563         chan_shortly [lindex $chans 0]
564     }
565 }
566
567 if {[catch {
568     loadhelp
569     ensure_connecting
570 } emsg]} {
571     fail "startup: $emsg"
572 }