r8584: add downcasing to sexp output
[irc-logger.git] / logger.lisp
1 ;;;  -*- Mode: Lisp -*-
2 ;;;; $Id: logger.lisp,v 1.11 2003/12/16 21:19:56 krosenberg Exp $
3 ;;;;
4 ;;;; Purpose: A IRC logging bot 
5 ;;;; Author:  Kevin Rosenberg
6
7 (in-package irc-logger)
8
9 (defvar *daemon-monitor-process* nil "Process of background monitor.")
10
11 (defclass channel ()
12   ((name :initarg :name :reader name
13          :documentation "Name of channel.")
14    (streams :initarg :streams :reader streams
15             :documentation "List of output streams.")
16    (output-root :initarg :output-root :reader output-root)
17    (current-output-names :initarg :current-output-names :accessor current-output-names)))
18
19    
20 (defclass logger ()
21   ((connection :initarg :connection :accessor connection
22                :documentation "IRC connection object.")
23    (handler :initform nil :accessor handler
24             :documentation "Background handler process.")
25    (nick :initarg :nick :reader nickname
26          :documentation "Nickname of the bot.")
27    (password :initarg :password :reader password
28              :documentation "Nickname's nickserver password.")
29    (server :initarg :server :reader server
30            :documentation "Connected IRC server.")
31    (channel-names :initarg :channel-names :accessor channel-names
32                   :documentation "List of channel names.")
33    (realname :initarg :realname :reader realname
34            :documentation "Realname for cl-irc")
35    (username :initarg :username :reader username
36            :documentation "Username for cl-irc")
37    (logging-stream :initarg :logging-stream :reader logging-stream 
38                    :documentation "logging-stream for cl-irc.")
39    (channels :initarg :channels :accessor channels
40              :documentation "List of channels.")
41    (user-output :initarg :user-output :reader user-output
42                 :documentation
43                 "Output parameter from user, maybe stream or pathname.")
44    (unichannel :initarg :unichannel :reader unichannel :type boolean
45                :documentation "T if user-output is directory for individual channel output.")
46    (formats :initarg :formats :reader formats
47                   :documentation
48                   "A list of output formats.")
49    (async :initarg :async :reader async
50                   :documentation
51                   "Whether to use async")
52    (last-pong :initform nil :accessor last-pong
53                   :documentation
54                   "utime of last pong message")
55    (private-log :initarg :private-log :reader private-log
56                 :documentation "Pathname of the private log file for the daemon.")
57    (unknown-log :initarg :unknown-log :reader unknown-log
58                 :documentation "Pathname of the log file for unknown messages.")
59    (private-log-stream :initarg :private-log-stream :reader private-log-stream
60                        :documentation "Stream of the private log file for the daemon.")
61    (unknown-log-stream :initarg :unknown-log-stream :reader unknown-log-stream
62                 :documentation "Stream of the log file for unknown messages.")
63    (monitor-events :initform nil :accessor monitor-events
64                    :documentation "List of events for the monitor to process.")
65    (warning-message-utime :initform nil :accessor warning-message-utime
66                   :documentation
67                   "Time of last, potentially active, warning message.")))
68
69 (defvar *loggers* nil "List of active loggers.")
70
71 (defparameter *user-address-scanner*
72   (create-scanner
73    '(:sequence #\!
74      (:register
75       (:greedy-repetition 1 nil :non-whitespace-char-class)))
76    :case-insensitive-mode t))
77
78 (defun find-logger-with-nick (nick)
79   (find nick (the list *loggers*) :test #'string-equal :key #'nickname))
80
81 (defun find-logger-with-connection (conn)
82   (find conn (the list *loggers*) :test #'eq :key #'connection))
83
84 (defun canonicalize-channel-name (name)
85   (string-left-trim '(#\#) name))
86
87 (defun find-channel-with-name (logger name)
88   (find name (the list (channels logger)) :test #'string-equal :key #'name))
89   
90 (defun make-output-name (name year month day)
91     (format nil "~A-~4,'0D.~2,'0D.~2,'0D" (canonicalize-channel-name name)
92             year month day))
93
94 (defun make-output-name-utime (name utime)
95   (multiple-value-bind
96         (second minute hour day-of-month month year day-of-week daylight-p zone)
97       (decode-universal-time utime)
98     (declare (ignore second minute hour day-of-week daylight-p zone))
99     (make-output-name name year month day-of-month)))
100
101 (defgeneric write-file-header (format channel-name stream))
102
103 (defmethod write-file-header ((format t) channel-name stream)
104   (declare (ignore channel-name stream))
105   )
106
107 (defgeneric write-file-footer (format channel-name stream))
108
109 (defmethod write-file-footer ((format t) channel-name stream)
110   (declare (ignore channel-name stream))
111   )
112                                
113 (defun %log-file-path (output-root channel-name year month day type)
114   (make-pathname
115    :defaults output-root
116    :directory (append (pathname-directory output-root)
117                       (list
118                        (string-left-trim '(#\#) channel-name)
119                        (format nil "~4,'0D-~2,'0D" year month)))
120    :name (make-output-name channel-name year month day)
121    :type type))
122
123 (defgeneric log-file-path (output-root channel-name year month day format))
124
125 (defmethod log-file-path (output-root channel-name year month day
126                           (format (eql :raw)))
127   (%log-file-path output-root channel-name year month day "raw"))
128
129 (defmethod log-file-path (output-root channel-name year month day (format (eql :sexp)))
130   (%log-file-path output-root channel-name year month day "sexp"))
131
132 (defmethod log-file-path (output-root channel-name year month day (format (eql :text)))
133   (%log-file-path output-root channel-name year month day "txt"))
134
135 (defmethod log-file-path (output-root channel-name year month day (format string))
136   (%log-file-path output-root channel-name year month day format))
137
138
139 (defun log-file-path-utime (output-root channel-name format utime)
140   (multiple-value-bind
141         (second minute hour day month year day-of-week daylight-p zone)
142       (decode-universal-time utime)
143     (declare (ignore second minute hour day-of-week daylight-p zone))
144     (log-file-path output-root channel-name year month day format)))
145
146 (defun get-stream (channel istream)
147   (elt (streams channel) istream))
148
149 (defun (setf get-stream) (value channel istream)
150   (setf (elt (streams channel) istream) value))
151
152 (defun get-format (logger istream)
153   (elt (formats logger) istream))
154
155 (defun get-output-name (channel istream)
156   (elt (current-output-names channel) istream))
157
158 (defun (setf get-output-name) (value channel istream)
159   (setf (elt (current-output-names channel) istream) value))
160
161 (defun ensure-output-stream-for-unichannel (utime logger channel istream)
162   (let ((name (make-output-name-utime (name channel) utime)))
163     (unless (string= name (get-output-name channel istream))
164       (when (get-stream channel istream)
165         (write-file-footer (get-format logger istream)
166                            (name channel)
167                            (get-stream channel istream))
168         (close (get-stream channel istream)))
169       (setf (get-output-name channel istream) name)
170       (let ((path (log-file-path-utime (output-root channel) (name channel)
171                                        (get-format logger istream) utime)))
172         (unless (probe-file path)
173           (ensure-directories-exist path)
174           (setf (get-stream channel istream)
175                 (open path :direction :output :if-exists :error
176                       :if-does-not-exist :create))
177           (write-file-header (get-format logger istream)
178                              (name channel)
179                               (get-stream channel istream))
180           (close (get-stream channel istream)))
181         (setf (get-stream channel istream)
182               (open path :direction :output :if-exists :append
183                     :if-does-not-exist :create))))))
184
185 (defun ensure-output-stream (utime logger channel istream)
186   "Ensures that *output-stream* is correct."
187   (cond
188    ((streamp (user-output logger))
189     (unless (get-stream channel istream)
190       (setf (get-stream channel istream) (user-output logger))))
191    ((pathnamep (user-output logger))
192     (cond
193      ((unichannel logger)
194       (ensure-output-stream-for-unichannel utime logger channel istream))
195      (t
196       (setf (get-stream channel istream)
197         (open (user-output logger) :direction :output :if-exists :append
198               :if-does-not-exist :create)))))))
199
200 (defun format-date-time (utime)
201   (multiple-value-bind
202         (second minute hour day-of-month month year day-of-week daylight-p zone)
203       (decode-universal-time utime)
204     (declare (ignore day-of-week daylight-p zone))
205     (format nil "~4,'0D/~2,'0D/~2,'0D ~2,'0D:~2,'0D:~2,'0D" year month day-of-month hour minute second)))
206
207 (defun format-utime (utime)
208   (multiple-value-bind
209         (second minute hour day-of-month month year day-of-week daylight-p zone)
210       (decode-universal-time utime)
211     (declare (ignore day-of-month month year day-of-week daylight-p zone))
212     (format nil "~2,'0D:~2,'0D:~2,'0D" hour minute second)))
213
214 (defun format-utime-short (utime)
215   (multiple-value-bind
216         (second minute hour day-of-month month year day-of-week daylight-p zone)
217       (decode-universal-time utime)
218     (declare (ignore second day-of-month month year day-of-week daylight-p zone))
219     (format nil "~2,'0D:~2,'0D" hour minute)))
220
221 (defun user-address (msg)
222   (let ((split (split *user-address-scanner* (raw-message-string msg)
223                       :with-registers-p t)))
224     (if (second split)
225         (second split)
226         "")))
227
228 (defun need-user-address? (type)
229   (case type
230     ((:action :privmsg :names :rpl_topic)
231      nil)
232     (t
233      t)))
234
235 (defgeneric %output-event (format stream utime type channel source text msg 
236                            unichannel))
237
238 (defmethod %output-event ((format t) stream utime type channel source text
239                           msg unichannel)
240   (%output-event :raw stream utime type channel source text msg unichannel))
241
242 (defmethod %output-event ((format (eql :raw)) stream utime type channel source
243                           text msg unichannel)
244   (declare (ignore utime type channel source text text unichannel))
245   (when msg
246     (format stream "~S~%" 
247             (string-right-trim '(#\return) (raw-message-string msg)))))
248
249 (defconstant +posix-epoch+
250   (encode-universal-time 0 0 0 1 1 1970 0))
251
252 (defun posix-time-to-utime (time)
253   (+ time +posix-epoch+))
254
255 (defun last-sexp-field (type msg)
256   (cond
257    ((null msg)
258     nil)
259    ((eq type :kick)
260     (trailing-argument msg))
261    ((eq type :rpl_topicwhotime)
262     (when (stringp (car (last (arguments msg))))
263       (let ((secs (parse-integer (car (last (arguments msg))) :junk-allowed t)))
264         (when secs
265           (posix-time-to-utime secs)))))
266    ((need-user-address? type)
267     (user-address msg))))
268
269 (defmethod %output-event ((format (eql :sexp)) stream utime type channel source text
270                           msg unichannel)
271   (with-standard-io-syntax
272     (let ((cl:*print-case* :downcase))
273       (if unichannel
274           (format stream "(~S ~S ~S ~S ~S)~%" utime type source text (last-sexp-field type msg))
275         (format stream "(~S ~S ~S ~S ~S ~S)~%" utime type source channel text
276                 (last-sexp-field type msg))))))
277
278 (defmethod %output-event ((format (eql :text)) stream utime type channel
279                           source text msg unichannel)
280   (format stream "~A " (format-utime utime))
281   (when (and (null unichannel) channel)
282     (format stream "[~A] " channel))
283   
284   (let ((user-address (when (and msg (need-user-address? type)) (user-address msg))))
285     (case type
286       (:privmsg
287        (format stream "<~A> ~A" source text))
288       (:action
289        (format stream "*~A* ~A" source text))
290       (:join
291        (format stream "~A [~A] has joined ~A" source user-address channel))
292       (:part
293        (format stream "-!- ~A [~A] has left ~A" source user-address channel))
294       (:nick
295        (format stream "-!- ~A is now known as ~A" source text))
296       (:kick
297        (format stream "-!- ~A [~A] has been kicked from ~A" source user-address channel))
298       (:quit
299        (format stream "-!- ~A [~A] has quit [~A]" source user-address (if text text "")))
300       (:mode
301        (format stream "-!- ~A has set mode ~A"  source text))
302       (:topic
303        (format stream "-!- ~A changed the topic of ~A to: ~A" source channel text))
304       (:notice
305        (format stream "-~A:~A- ~A" source channel text))
306       (:daemon
307        (format stream "-!!!- ~A" text))
308       (:names
309        (format stream "-!- names: ~A" text))
310       (:rpl_topic
311        (format stream "-!- topic: ~A" text))
312       (t
313        (warn "Unhandled msg type ~A." type))))
314   (write-char #\Newline stream))
315
316 (defun output-event-for-a-stream (msg type channel text logger istream)
317   (ensure-output-stream (received-time msg) logger channel istream)
318   (%output-event  (get-format logger istream) (get-stream channel istream)
319                   (received-time msg) type (name channel) (source msg) text msg
320                   (unichannel logger))
321   (force-output (get-stream channel istream)))
322
323 (defun log-daemon-message (logger fmt &rest args)
324   (let ((text (apply #'format nil fmt args))
325         (time (get-universal-time)))
326     (format (get-private-log-stream logger)
327             "~A ~A~%" (format-date-time time) text)
328     (force-output (get-private-log-stream logger))
329     (dolist (channel (channels logger))
330       (dotimes (istream (length (formats logger)))
331         (ensure-output-stream time logger channel istream)
332         (%output-event  (get-format logger istream)
333                         (get-stream channel istream)
334                         time :daemon nil nil text nil
335                         (unichannel logger))
336         (force-output (get-stream channel istream))))))
337
338 (defvar *msg*)
339 (defun output-event (msg type channel-name &optional text)
340   (setq *msg* msg)
341   (dolist (logger *loggers*)
342     (case type
343       ((:error :server :kill)
344        (format (get-private-log-stream logger)
345                "~A ~A~%"
346                (format-date-time (received-time msg))
347                (raw-message-string msg))
348        (force-output (get-private-log-stream logger)))
349       ((:quit :nick)
350        ;; send to all channels that a nickname is joined
351        (let* ((user (find-user (connection logger)
352                                (case type
353                                  (:nick (source msg))
354                                  (:quit (source msg)))))
355               (channels (when user (cl-irc::channels user))))
356          (dolist (channel (mapcar
357                            #'(lambda (name) (find-channel-with-name logger name)) 
358                            (mapcar #'cl-irc::name channels)))
359            (when channel
360              (dotimes (i (length (formats logger)))
361                (output-event-for-a-stream msg type channel text logger i))))))
362       (t
363        ;; msg contains channel name
364        (let* ((channel (find-channel-with-name logger channel-name)))
365          (when channel
366            (dotimes (i (length (formats logger)))
367              (output-event-for-a-stream msg type channel text logger i))))))))
368
369 (defun get-private-log-stream (logger)
370   (if (and logger (private-log-stream logger))
371       (private-log-stream logger)
372     *standard-output*))
373
374 (defun get-unknown-log-stream (logger)
375   (if (and logger (unknown-log-stream logger))
376       (unknown-log-stream logger)
377     *standard-output*))
378
379 (defun privmsg-hook (msg)
380   (let ((logger (find-logger-with-connection (connection msg)))
381         (channel (first (arguments msg))))
382     (cond
383      ((equal channel (nickname logger))
384       (format
385        (get-private-log-stream logger)
386        "~A ~A~%" 
387        (format-date-time (get-universal-time))
388        (raw-message-string msg))
389       (force-output (get-private-log-stream logger)))
390      (t
391       (output-event msg :privmsg channel (trailing-argument msg))))))
392
393 (defun action-hook (msg)
394   (output-event msg :action (first (arguments msg))
395                 (subseq (trailing-argument msg) 8 
396                         (- (length (trailing-argument msg)) 1))))
397
398 (defun nick-hook (msg)
399   (output-event msg :nick nil (trailing-argument msg)))
400
401 (defun part-hook (msg)
402   (output-event msg :part (first (arguments msg))))
403
404 (defun quit-hook (msg)
405   (output-event msg :quit nil (trailing-argument msg)))
406
407 (defun join-hook (msg)
408   (output-event msg :join (trailing-argument msg)))
409
410 (defun kick-hook (msg)
411   (let ((logger (find-logger-with-connection (connection msg)))
412         (channel (first (arguments msg)))
413         (who-kicked (second (arguments msg))))
414     (output-event msg :kick channel who-kicked)
415     (when (string-equal (nickname logger) who-kicked)
416       (format
417        (get-private-log-stream logger)
418        "~A Logging daemon ~A has been kicked from ~A (~A)~%"
419        (format-date-time (received-time msg))
420        (nickname logger)
421        channel
422        (trailing-argument msg))
423       (force-output (get-private-log-stream logger))
424       (daemon-sleep 1)
425       (remove-channel-logger logger channel)
426       (daemon-sleep 1)
427       (add-channel-logger logger channel)
428       (format
429        (get-private-log-stream logger)
430        "~A Rejoined ~A~%"
431        (format-date-time (received-time msg))
432        channel)
433       (force-output (get-private-log-stream logger)))))
434
435 (defun notice-hook (msg)
436   (let ((logger (find-logger-with-connection (connection msg)))
437         (channel (first (arguments msg))))
438     (cond
439       ((and (string-equal (source msg) "NickServ")
440             (string-equal channel (nickname logger))
441             (string-equal "owned by someone else" (trailing-argument msg)))
442        (if logger
443            (privmsg (connection msg) (source msg) (format nil "IDENTIFY ~A" (password logger)))
444          (format
445           (get-private-log-stream logger)
446           "~A NickServ asks for identity with connection not found.~%"
447           (format-date-time (received-time msg)))))
448       ((equal channel (nickname logger))
449        (format
450         (get-private-log-stream logger)
451         "~A ~A~%" 
452         (format-date-time (get-universal-time))
453         (raw-message-string msg))
454        (force-output (get-private-log-stream logger)))
455       (t
456        (output-event msg :notice channel (trailing-argument msg))))))
457
458 (defun ping-hook (msg)
459   (let ((logger (find-logger-with-connection (connection msg))))
460     (pong (connection msg) (server logger))
461     #+debug (format *standard-output* "Sending pong to ~A~%" (server logger))))
462
463 (defun pong-hook (msg)
464   (let ((logger (find-logger-with-connection (connection msg))))
465     (setf (last-pong logger) (received-time msg))))
466         
467 (defun topic-hook (msg)
468   (output-event msg :topic (first (arguments msg)) (trailing-argument msg)))
469
470 (defun mode-hook (msg)
471   (output-event msg :mode (first (arguments msg)) 
472                 (format nil "~{~A~^ ~}" (cdr (arguments msg)))))
473
474 (defun rpl_namreply-hook (msg)
475   (output-event msg :names (third (arguments msg))
476                 (trailing-argument msg)))
477
478 (defun rpl_endofnames-hook (msg)
479   (declare (ignore msg))
480   ;; nothing to do for this message
481   )
482
483 (defun rpl_topic-hook (msg)
484   (output-event msg :rpl_topic (format nil "~{~A~^ ~}" (arguments msg))
485                 (trailing-argument msg)))
486
487 (defun rpl_topicwhotime-hook (msg)
488   (output-event msg :rpl_topicwhotime
489                 (second (arguments msg))
490                 (third (arguments msg))))
491
492
493 (defun invite-hook (msg)
494   (let ((logger (find-logger-with-connection (connection msg))))
495     (format 
496      (get-private-log-stream logger)
497      "~A ~A~%"
498      (format-date-time (get-universal-time))
499      (raw-message-string msg))
500     (force-output (get-private-log-stream logger))))
501
502
503 (defun make-a-channel (name formats output)
504   (make-instance 'channel
505                  :name name
506                  :streams (make-array (length formats) :initial-element nil)
507                  :output-root (when (and (pathnamep output)
508                                          (null (pathname-name output)))
509                                 output)
510                  :current-output-names (make-array (length formats)
511                                                    :initial-element nil)))
512   
513 (defun make-channels (names formats output)
514   (loop for i from 0 to (1- (length names))
515         collect (make-a-channel (elt names i) formats output)))
516
517 (defun is-unichannel-output (user-output)
518   "Returns T if output is setup for a single channel directory structure."
519   (and (pathnamep user-output) (null (pathname-name user-output))))
520
521 (defun do-connect-and-join (nick server username realname logging-stream channels)
522   (let ((conn (connect :nickname nick :server server
523                        :username username :realname realname
524                        :logging-stream logging-stream)))
525     (mapc #'(lambda (channel) (join conn channel)) channels)
526     (add-hook conn 'irc::irc-privmsg-message 'privmsg-hook)
527     (add-hook conn 'irc::ctcp-action-message 'action-hook)
528     (add-hook conn 'irc::irc-nick-message 'nick-hook)
529     (add-hook conn 'irc::irc-part-message 'part-hook)
530     (add-hook conn 'irc::irc-quit-message 'quit-hook)
531     (add-hook conn 'irc::irc-join-message 'join-hook)
532     (add-hook conn 'irc::irc-kick-message 'kick-hook)
533     (add-hook conn 'irc::irc-mode-message 'mode-hook)
534     (add-hook conn 'irc::irc-topic-message 'topic-hook)
535     (add-hook conn 'irc::irc-notice-message 'notice-hook)
536     (add-hook conn 'irc::irc-error-message 'error-hook)
537     (add-hook conn 'irc::irc-ping-message 'ping-hook)
538     (add-hook conn 'irc::irc-pong-message 'pong-hook)
539     (add-hook conn 'irc::irc-kill-message 'kill-hook)
540     (add-hook conn 'irc::irc-invite-message 'invite-hook)
541     (add-hook conn 'irc::irc-rpl_killdone-message 'warning-hook)
542     (add-hook conn 'irc::irc-rpl_closing-message 'warning-hook)
543     (add-hook conn 'irc::irc-rpl_topic-message 'rpl_topic-hook)
544     (add-hook conn 'irc::irc-rpl_namreply-message 'rpl_namreply-hook)
545     (add-hook conn 'irc::irc-rpl_endofnames-message 'rpl_endofnames-hook)
546     (add-hook conn 'irc::irc-rpl_topicwhotime-message 'rpl_topicwhotime-hook)
547     conn))
548
549 (defmethod cl-irc::irc-message-event :around ((msg cl-irc::irc-message))
550   (let ((result (call-next-method msg)))
551     (typecase msg
552       ((or irc::irc-privmsg-message irc::ctcp-action-message irc::irc-nick-message
553         irc::irc-part-message irc::irc-quit-message irc::irc-join-message
554         irc::irc-kick-message irc::irc-mode-message irc::irc-topic-message
555         irc::irc-notice-message irc::irc-error-message irc::irc-ping-message
556         irc::irc-pong-message irc::irc-kill-message irc::irc-invite-message
557         irc::irc-rpl_killdone-message irc::irc-rpl_closing-message
558         irc::irc-rpl_topic-message irc::irc-rpl_namreply-message
559         irc::irc-rpl_endofnames-message irc::irc-rpl_topicwhotime-message
560         irc::irc-rpl_motd-message irc::irc-rpl_motdstart-message
561         irc::irc-rpl_endofmotd-message)
562        ;; nothing to do
563        )
564       (t
565        (let ((logger (find-logger-with-connection (connection msg))))
566          (format (get-unknown-log-stream
567                   (find-logger-with-connection (connection msg)))
568                  "~A ~A~%"
569                  (format-date-time (received-time msg ))
570                  (raw-message-string msg))
571          (force-output (get-unknown-log-stream logger)))))
572     result))
573
574 (defun create-logger (nick server &key channels output password
575                       realname username async
576                       private-log unknown-log
577                       (logging-stream t) (formats '(:text)))
578   "OUTPUT may be a pathname or a stream"
579   ;; check arguments
580   (assert formats)
581   (if (and channels (atom channels))
582       (setq channels (list channels)))
583   (if (atom formats)
584       (setq formats (list formats)))
585   (if (stringp output)
586       (setq output (parse-namestring output)))
587   (let* ((conn (do-connect-and-join nick server username realname logging-stream channels))
588          (logger (make-instance
589                   'logger
590                   :connection conn
591                   :nick nick
592                   :password password
593                   :server server
594                   :channels (make-channels channels formats output)
595                   :channel-names channels
596                   :username username
597                   :realname realname
598                   :async async
599                   :logging-stream logging-stream
600                   :user-output output
601                   :formats formats
602                   :private-log private-log
603                   :unknown-log unknown-log
604                   :private-log-stream (when private-log
605                                         (open private-log :direction :output
606                                               :if-exists :append
607                                               :if-does-not-exist :create))
608                   :unknown-log-stream (when unknown-log
609                                         (open unknown-log :direction :output
610                                               :if-exists :append
611                                               :if-does-not-exist :create))
612                   :unichannel (is-unichannel-output output))))
613     (unless *daemon-monitor-process*
614       (setq *daemon-monitor-process* (cl-irc::start-process 'daemon-monitor "logger-monitor")))
615     logger))
616
617 (defun start-logger (logger async)
618   (if async
619       (setf (handler logger)
620         (start-background-message-handler (connection logger)))
621       (read-message-loop (connection logger))))
622
623 (defun remove-logger (nick)
624   "Quit the active connection with nick and remove from active list."
625   (let ((logger (find-logger-with-nick nick)))
626     (cond
627       ((null logger)
628        (warn
629         "~A No active connection found with nick ~A [remove-logger].~%"
630         (format-date-time (get-universal-time))
631         nick)
632        nil)
633       (t
634        (ignore-errors (irc:quit (connection logger) ""))
635        (stop-background-message-handler (handler logger))
636        (sleep 1)
637        (dolist (channel (channels logger))
638          (let ((c (connection logger)))
639            (when c
640              (ignore-errors (remove-channel c (find-channel c (name channel)))))))
641        (when (private-log-stream logger)
642          (close (private-log-stream logger)))
643        (when (unknown-log-stream logger)
644          (close (unknown-log-stream logger)))
645
646        (setq *loggers*
647              (delete nick *loggers*  :test #'string-equal :key #'nickname))
648        t))))
649
650 (defun add-logger (nick server &key channels output (password "")
651                                     realname username private-log unknown-log
652                                     (logging-stream t) (async t)
653                                     (formats '(:sexp)))
654   (when (find-logger-with-nick nick)
655     (format
656      (get-private-log-stream (find-logger-with-nick nick))
657      "~A Closing previously active connection [add-logger].~%"
658      (format-date-time (get-universal-time)))
659     (ignore-errors (remove-logger nick)))
660   (let ((logger (create-logger nick server :channels channels :output output
661                                :logging-stream logging-stream :password password
662                                :realname realname :username username
663                                :private-log private-log 
664                                :unknown-log unknown-log 
665                                :formats formats
666                                :async async)))
667     (push logger *loggers*)
668     (start-logger logger async)
669     logger))
670   
671 (defun add-channel-logger (logger channel-name)
672   (cond
673     ((find-channel-with-name logger channel-name)
674      (format (get-private-log-stream logger)
675              "~A Channel ~A already in logger ~A.~%" 
676              (format-date-time (get-universal-time))
677              channel-name logger)
678      (force-output (get-private-log-stream logger))
679      nil)
680     (t
681      (let ((channel (make-a-channel channel-name (formats logger) (user-output logger))))
682        (join (connection logger) channel-name)
683        (push channel (channels logger))
684        (push channel-name (channel-names logger))))))
685
686 (defun remove-channel-logger (logger channel-name)
687   (let ((channel (find-channel-with-name logger channel-name)))
688     (cond
689       (channel
690        (part (connection logger) channel-name)
691        (dotimes (i (length (streams channel)))
692          (when (streamp (get-stream channel i))
693            (close (get-stream channel i))
694            (setf (get-stream channel i) nil)))
695        (setf (channels logger) (delete channel-name (channels logger)
696                                        :test #'string-equal
697                                        :key #'name))
698        (setf (channel-names logger) (delete channel-name (channel-names logger)
699                                             :test #'string-equal))
700        t)
701       (t
702        (format
703         (get-private-log-stream logger)
704         "~A Channel name ~A not found in logger ~A.~%" 
705         (format-date-time (get-universal-time)) 
706         channel-name logger)
707        nil))))
708
709 (defun add-hook-logger (logger class hook)
710   (add-hook (connection logger) class hook))
711
712 (defun remove-hook-logger (logger class hook)
713   (remove-hook (connection logger) class hook))
714
715 (defvar *warning-message-utime* nil)
716
717 (defun kill-hook (msg)
718   (let ((target (second (arguments msg)))
719         (logger (find-logger-with-connection (connection msg))))
720     (when (and (stringp target)
721                (string-equal target (nickname logger)))
722       (setf (warning-message-utime logger) (received-time msg)))
723     (format (get-private-log-stream logger)
724             "~A Killed by ~A~%"
725             (format-date-time (received-time msg))
726             (source msg))
727     (force-output (get-private-log-stream logger))))
728
729 (defun error-hook (msg)
730   (let ((text (trailing-argument msg))
731         (logger (find-logger-with-connection (connection msg))))
732     (when (and (stringp text) 
733                (zerop (search (format nil "Closing Link: ~A" (nickname logger)) text)))
734       (setf (warning-message-utime logger) (received-time msg)))
735     (output-event msg :error nil (trailing-argument msg))))
736
737 (defun warning-hook (msg)
738   (let ((logger (find-logger-with-connection (connection msg))))
739     (output-event msg :server 
740                   (format nil "~{~A~^ ~} ~A)"
741                           (arguments msg)
742                           (trailing-argument msg)))
743     (when logger
744       (setf (warning-message-utime logger) (get-universal-time)))))
745   
746 (defun daemon-sleep (seconds)
747   #-allegro (sleep seconds)
748   #+allegro (mp:process-sleep seconds))
749
750 (defun log-disconnection (logger)
751   ;; avoid generating too many reconnect messages in the logs
752   (when (or (null (warning-message-utime logger))
753             (< (- (get-universal-time) (warning-message-utime logger)) 300))
754     (log-daemon-message logger "Disconnected. Attempting reconnection at ~A."
755                         (format-date-time (get-universal-time)))))
756
757 (defun log-reconnection (logger)
758   (log-daemon-message
759    logger
760    "Connection restablished at ~A." (format-date-time (get-universal-time))))
761
762 (defun is-connected (logger)
763   (when (ignore-errors (ping (connection logger) (server logger)))
764     (dotimes (i 20)
765       (when (and (last-pong logger)
766                  (< (- (get-universal-time) (last-pong logger)) 21))
767         (return-from is-connected t))
768       (sleep 1))))
769
770
771 (let (*recon-nick* *recon-server* *recon-username* *recon-realname*
772       *recon-user-output* *recon-private-log* *recon-unknown-log*
773       *recon-formats* *recon-async* *recon-logging-stream* *recon-channel-names*)
774   (declare (special *recon-nick* *recon-server* *recon-username* *recon-realname*
775                     *recon-formats* *recon-password* *recon-async* 
776                     *recon-user-output* *recon-private-log* *recon-unknown-log*
777                     *recon-logging-stream* *recon-channel-names*))
778   
779   (defun attempt-reconnection (logger)
780     (when (is-connected logger)
781       (return-from attempt-reconnection nil))
782     
783     (log-disconnection logger)
784     (when (connection logger)
785       (ignore-errors (quit (connection logger) "Client terminated by server"))
786       (setf *recon-nick* (nickname logger)
787             *recon-server* (server logger)
788             *recon-username* (username logger)
789             *recon-realname* (realname logger)
790             *recon-password* (password logger)
791             *recon-async* (async logger)
792             *recon-user-output* (user-output logger)
793             *recon-private-log* (private-log logger)
794             *recon-unknown-log* (unknown-log logger)
795             *recon-formats* (formats logger)
796             *recon-logging-stream* (logging-stream logger)
797             *recon-channel-names* (channel-names logger))
798       (ignore-errors (remove-logger logger)))
799     
800     (let ((new-logger
801            (ignore-errors
802             (add-logger *recon-nick* *recon-server*
803                         :channels *recon-channel-names*
804                         :output *recon-user-output*
805                         :password *recon-password*
806                         :realname *recon-realname*
807                         :username *recon-username*
808                         :logging-stream *recon-logging-stream*
809                         :private-log *recon-private-log*
810                         :unknown-log *recon-unknown-log*
811                         :async *recon-async*
812                         :formats *recon-formats*))))
813       (when new-logger
814         (sleep 5)
815         (when (is-connected new-logger)
816           (log-reconnection new-logger)))))
817       
818   )
819
820 (defun daemon-monitor ()
821   "This function runs in the background and monitors the connection of the logger."
822   ;; run forever
823   (do ()
824       ()
825     (block main-loop
826       (dolist (logger *loggers*)
827         (do ((warning-time (warning-message-utime logger) (warning-message-utime logger)))
828             ((or (is-connected logger) (null warning-time)))
829           (cond
830            ((and warning-time (> (- (get-universal-time) warning-time) 180))
831             ;;give up frequent checking because no disconnection despite waiting
832             (setf (warning-message-utime logger) nil))
833            ((not (is-connected logger))
834             (unless warning-time
835               (setf (warning-message-utime logger) (get-universal-time)))
836             (attempt-reconnection logger)
837             ;;after a succesful reconnection, the value of logger will be invalid 
838             (sleep 30)
839             (return-from main-loop))
840            (t
841             (daemon-sleep 30)))))
842       (do ((i 0 (1+ i)))
843           ((or (>= i 20) (some (lambda (logger) (warning-message-utime logger)) *loggers*))) 
844         (daemon-sleep 15)))))
845   
846
847