Component protocol

You are here: All Systems / cl-irc / protocol

;;;; $Id: protocol.lisp,v 1.25 2005/09/25 14:55:02 bmastenbrook Exp $
;;;; $Source: /project/cl-irc/cvsroot/cl-irc/protocol.lisp,v $

;;;; See LICENSE for licensing information.

(in-package :irc)

;;
;; Condition
;;

(define-condition no-such-reply ()
  ((reply-number
    :reader reply-number
    :initarg :reply-number
)
)

  (:report (lambda (condition stream)
             (format stream "No such reply ~A." (reply-number condition))
)
)
)




;;
;; Modes
;;

;; generic abstract mode class

(defclass irc-mode ()
  ((value
    :initarg :value
    :accessor value
    :initform nil
)

   (value-type
    :initarg :value-type
    :accessor value-type
    :documentation "The framework sets this to `:user' or `:non-user'.
Essentially, if it's `:user', the value(s) held must be derived from the
user class."
)
)
)


(defgeneric set-mode-value (mode-object value))
(defgeneric unset-mode-value (mode-object value))
(defgeneric reset-mode-value (mode-object))
(defgeneric has-value-p (mode-object value &key key test))

(defmethod reset-mode-value ((mode irc-mode))
  (setf (value mode) nil)
)



;; mode class for holding boolean values

(defclass boolean-value-mode (irc-mode) ())

(defmethod set-mode-value ((mode boolean-value-mode) value)
  (declare (ignore value))
  (setf (value mode) t)
)


(defmethod unset-mode-value ((mode boolean-value-mode) value)
  (declare (ignore value))
  (setf (value mode) nil)
)


(defmethod has-value-p ((mode boolean-value-mode) value
                        &key key test
)

  (declare (ignore value key test))
  (value mode)
)


;; mode class for holding single values

(defclass single-value-mode (irc-mode) ())

(defmethod set-mode-value ((mode single-value-mode) value)
  (setf (value mode) value)
)


(defmethod unset-mode-value ((mode single-value-mode) value)
  (when (or (null value)
            (equal value (value mode))
)

    (setf (value mode) nil)
)
)


(defmethod has-value-p ((mode single-value-mode) value
                        &key (key #'identity) (test #'equal)
)

  (funcall test
           value
           (funcall key (value mode))
)
)



;; mode class for holding lists of values

(defclass list-value-mode (irc-mode) ())

(defmethod set-mode-value ((mode list-value-mode) value)
  (push value (value mode))
)


(defmethod unset-mode-value ((mode list-value-mode) value)
  (setf (value mode)
        (remove value (value mode))
)
)


(defmethod has-value-p ((mode list-value-mode) value
                        &key (key #'identity) (test #'equal)
)

  (let ((key-value (funcall key value)))
    (some #'(lambda (x)
              (funcall test
                       key-value
                       (funcall key x)
)
)

          (value mode)
)
)
)


;;
;; Connection
;;


(defclass connection ()
  ((user
    :initarg :user
    :accessor user
)

   (server-name
    :initarg :server-name
    :accessor server-name
    :initform "Unknown server"
)

   (server-stream
    :initarg :server-stream
    :accessor server-stream
    :documentation "Stream used to talk to the IRC server."
)

   (server-capabilities
    :initform *default-isupport-values*
    :accessor server-capabilities
    :documentation "Assoc array for rpl_isupport message;
see http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt"
)

   (client-stream
    :initarg :client-stream
    :accessor client-stream
    :initform t
    :documentation "Messages coming back from the server is sent to
this stream."
)

   (channels
    :initarg :channels
    :accessor channels
    :initform (make-hash-table :test #'equal)
)

   (hooks
    :initarg :hooks
    :accessor hooks
    :initform (make-hash-table :test #'equal)
)

   (channel-mode-descriptions
    :initarg :channel-mode-descriptions
    :accessor channel-mode-descriptions
    :initform (chanmode-descs-from-isupport *default-isupport-values*)
    :documentation
    "Describes the modes an application intends to register with channels."
)

   (nick-prefixes
    :initarg :nick-prefixes
    :accessor nick-prefixes
    :initform (nick-prefixes-from-isupport *default-isupport-values*)
)

   (user-mode-destriptions
    :initarg :user-mode-descriptions
    :accessor user-mode-descriptions
    :initform (mapcar #'(lambda (x)
                          (make-mode-description :char (car x)
                                                 :symbol (cdr x)
)
)

                      *char-to-user-modes-map*
)

    :documentation
    "Describes the modes an application intends to register with channels."
)

   (users
    :initarg :users
    :accessor users
    :initform (make-hash-table :test #'equal)
)
)
)


(defmethod print-object ((object connection) stream)
  "Print the object for the Lisp reader."
  (print-unreadable-object (object stream :type t :identity t)
    (princ (server-name object) stream)
)
)


(defgeneric add-default-hooks (connection))
(defgeneric client-raw-log (connection message))
(defgeneric connectedp (connection))
(defgeneric read-message (connection))
(defgeneric start-process (function name))
(defgeneric start-background-message-handler (connection))
(defgeneric read-message-loop (connection))
(defgeneric read-irc-message (connection))
(defgeneric send-irc-message (connection command
                             &optional trailing-argument &rest arguments
)
)

(defgeneric get-hooks (connection class))
(defgeneric add-hook (connection class hook))
(defgeneric remove-hook (connection class hook))
(defgeneric remove-hooks (connection class))
(defgeneric remove-all-hooks (connection))

(defgeneric case-map-name (connection))
(defgeneric re-apply-case-mapping (connection))

(defun make-connection (&key (connection-type 'connection)
                             (user nil)
                             (server-name "")
                             (server-stream nil)
                             (client-stream t)
                             (hooks nil)
)

  (let ((connection (make-instance connection-type
                                   :user user
                                   :server-name server-name
                                   :server-stream server-stream
                                   :client-stream client-stream
)
)
)

    (dolist (hook hooks)
      (add-hook connection (car hook) (cadr hook))
)

    connection
)
)


(defmethod add-default-hooks ((connection connection))
  (dolist (message '(irc-rpl_isupport-message
                     irc-rpl_whoisuser-message
                     irc-rpl_banlist-message
                     irc-rpl_endofbanlist-message
                     irc-rpl_exceptlist-message
                     irc-rpl_endofexceptlist-message
                     irc-rpl_invitelist-message
                     irc-rpl_endofinvitelist-message
                     irc-rpl_list-message
                     irc-rpl_topic-message
                     irc-rpl_namreply-message
                     irc-rpl_endofnames-message
                     irc-ping-message
                     irc-join-message
                     irc-topic-message
                     irc-part-message
                     irc-quit-message
                     irc-kick-message
                     irc-nick-message
                     irc-mode-message
                     irc-rpl_channelmodeis-message
                     ctcp-time-message
                     ctcp-source-message
                     ctcp-finger-message
                     ctcp-version-message
                     ctcp-ping-message
)
)

      (add-hook connection message #'default-hook)
)
)


(defmethod client-raw-log ((connection connection) message)
  (let ((stream (client-stream connection)))
    (format stream (format nil "RAW LOG: ~A~%" message))
    (force-output stream)
)
)


(defmethod connectedp ((connection connection))
  "Returns t if `connection' is connected to a server and is ready for
input."

  (let ((stream (server-stream connection)))
    (and (streamp stream)
         (open-stream-p stream)
)
)
)


(define-condition invalidate-me (condition)
  ((stream :initarg :stream
           :reader invalidate-me-stream
)

   (condition :initarg :condition
              :reader invalidate-me-condition
)
)
)


(defmethod read-message ((connection connection))
  (let ((read-more-p t))
    (handler-case
        (progn
          (when (and (connectedp connection) read-more-p)
            (let ((message (read-irc-message connection)))
              (when *debug-p*
                (format *debug-stream* "~A" (describe message))
)

              (irc-message-event message)
              message
)
)
)
; needed because of the "loop while" in read-message-loop
       (stream-error (c) (setf read-more-p nil)
                    (signal 'invalidate-me :stream
                            (server-stream connection)
                            :condition c
)
)
)
)
)


(defvar *process-count* 0)

(defmethod start-process (function name)
  #+allegro (mp:process-run-function name function)
  #+cmu (mp:make-process function :name name)
  #+lispworks (mp:process-run-function name nil function)
  #+sb-thread (sb-thread:make-thread function)
  #+openmcl (ccl:process-run-function name function)
  #+armedbear (ext:make-thread function)
)


(defmethod start-background-message-handler ((connection connection))
  "Read messages from the `connection', parse them and dispatch
irc-message-event on them. Returns background process ID if available."

  (flet ((do-loop () (read-message-loop connection)))
    (let ((name (format nil "irc-hander-~D" (incf *process-count*))))
      #+(or allegro cmu lispworks sb-thread openmcl armedbear)
      (start-process #'do-loop name)
      #+(and sbcl (not sb-thread))
      (sb-sys:add-fd-handler (sb-sys:fd-stream-fd
                              (server-stream connection)
)

                             :input (lambda (fd)
                                      (declare (ignore fd))
                                      (handler-case
                                          (read-message connection)
                                        (invalidate-me (c)
                                          (sb-sys:invalidate-descriptor
                                           (sb-sys:fd-stream-fd
                                            (invalidate-me-stream c)
)
)

                                          (format t "Socket closed: ~A~%"
                                                  (invalidate-me-condition c)
)
)
)
)
)
)
)
)


(defun stop-background-message-handler (process)
  "Stops a background message handler process returned by the start function."
    #+cmu (mp:destroy-process process)
    #+allegro (mp:process-kill process)
    #+sb-thread (sb-thread:destroy-thread process)
    #+lispworks (mp:process-kill process)
    #+openmcl (ccl:process-kill process)
    #+armedbear (ext:destroy-thread process)
)


(defmethod read-message-loop ((connection connection))
  (loop while (read-message connection))
)


(defmethod read-irc-message ((connection connection))
  "Read and parse an IRC-message from the `connection'."
  (let ((message (create-irc-message
                  (read-line (server-stream connection) t)
)
)
)

    (setf (connection message) connection)
    message
)
)


(defmethod send-irc-message ((connection connection) command
                             &optional trailing-argument &rest arguments
)

  "Turn the arguments into a valid IRC message and send it to the
server, via the `connection'."

  (let ((raw-message (make-irc-message command
                                       :arguments arguments
                                       :trailing-argument trailing-argument
)
)
)

    (write-sequence raw-message (server-stream connection))
    (force-output (server-stream connection))
    raw-message
)
)


(defmethod get-hooks ((connection connection) (class symbol))
  "Return a list of all hooks for `class'."
  (gethash class (hooks connection))
)


(defmethod add-hook ((connection connection) class hook)
  "Add `hook' to `class'."
  (setf (gethash class (hooks connection))
        (pushnew hook (gethash class (hooks connection)))
)
)


(defmethod remove-hook ((connection connection) class hook)
  "Remove `hook' from `class'."
  (setf (gethash class (hooks connection))
        (delete hook (gethash class (hooks connection)))
)
)


(defmethod remove-hooks ((connection connection) class)
  "Remove all hooks for `class'."
  (setf (gethash class (hooks connection)) nil)
)


(defmethod remove-all-hooks ((connection connection))
  (clrhash (hooks connection))
)


(defmethod case-map-name ((connection connection))
  (let ((case-mapping (assoc "CASEMAPPING" (server-capabilities connection)
                             :test #'equal
)
)
)

    (intern (string-upcase (second case-mapping)) (find-package "KEYWORD"))
)
)


(defmethod re-apply-case-mapping ((connection connection))
  (setf (normalized-nickname (user connection))
        (normalize-nickname connection (nickname (user connection)))
)

  (flet ((set-new-users-hash (object)
           (let ((new-users (make-hash-table :test #'equal)))
             (maphash
              #'(lambda (norm-nick user)
                  (declare (ignore norm-nick))
                  (setf (gethash
                         (setf (normalized-nickname user)
                               (normalize-nickname connection
                                                   (nickname user)
)
)

                         new-users
)
user
)
)

              (users object)
)

             (setf (users object) new-users)
)
)
)


    (set-new-users-hash connection)
    (let ((new-channels (make-hash-table :test #'equal)))
      (maphash #'(lambda (norm-name channel)
                   (declare (ignore norm-name))
                   (setf (gethash
                          (setf (normalized-name channel)
                                (normalize-channel-name connection
                                                        (name channel)
)
)

                          new-channels
)
channel
)

                   (set-new-users-hash channel)
)

               (channels connection)
)

      (setf (channels connection) new-channels)
)
)
)



;;
;; DCC Connection
;;

(defclass dcc-connection ()
  ((user
    :initarg :user
    :accessor user
    :documentation "The user at the other end of this connection.  The
user at this end can be reached via your normal connection object."
)

   (stream
    :initarg :stream
    :accessor dcc-stream
)

   (output-stream
    :initarg :output-stream
    :accessor output-stream
    :initform t
)
)
)


(defmethod print-object ((object dcc-connection) stream)
  "Print the object for the Lisp reader."
  (print-unreadable-object (object stream :type t :identity t)
    (if (user object)
        (format stream "with ~A@~A"
                (nickname (user object))
                (hostname (user object))
)

      ""
)
)
)


(defun make-dcc-connection (&key (user nil)
                                 (remote-address nil)
                                 (remote-port nil)
                                 (output-stream t)
)

  (make-instance 'dcc-connection
                 :user user
                 :stream (socket-stream remote-address remote-port)
                 :output-stream output-stream
)
)


(defgeneric dcc-close (connection))
(defgeneric send-dcc-message (connection message))

(defmethod read-message ((connection dcc-connection))
  (let ((message (read-line (dcc-stream connection))))
    (format (output-stream connection) "~A~%" message)
    (force-output (output-stream connection))
    message
)
)


(defmethod read-message-loop ((connection dcc-connection))
  (loop while (read-message connection))
)


(defmethod send-dcc-message ((connection dcc-connection) message)
  (format (dcc-stream connection) "~A~%" message)
)


;; argh.  I want to name this quit but that gives me issues with
;; generic functions.  need to resolve.
(defmethod dcc-close ((connection dcc-connection))
  #+(and sbcl (not sb-thread))
  (sb-sys:invalidate-descriptor (sb-sys:fd-stream-fd (stream connection)))
  (close (dcc-stream connection))
  (setf (user connection) nil)
  (setf *dcc-connections* (remove connection *dcc-connections*))
  
)


(defmethod connectedp ((connection dcc-connection))
  (let ((stream (dcc-stream connection)))
    (and (streamp stream)
         (open-stream-p stream)
)
)
)


;;
;; Channel
;;

(defclass channel ()
  ((name
    :initarg :name
    :accessor name
)

   (normalized-name
    :initarg :normalized-name
    :accessor normalized-name
)

   (topic
    :initarg :topic
    :accessor topic
)

   (modes
    :initarg :modes
    :accessor modes
    :initform '()
)

   (users
    :initarg :users
    :accessor users
    :initform (make-hash-table :test #'equal)
)

   (user-count
    :initarg :user-count
    :accessor user-count
    :initform nil
    :documentation "May not represent the real number of users in the
channel.  Rather, the number returned from the LIST command gets stuck
in there so the user of this library can use it for searching
channels, for instance.  If the value is NIL then the slot has not
been populated by a LIST command."
)
)
)


(defmethod print-object ((object channel) stream)
  "Print the object for the Lisp reader."
  (print-unreadable-object (object stream :type t :identity t)
    (princ (name object) stream)
)
)


(defun normalize-channel-name (connection string)
  "Normalize `string' so that it represents an all-downcased channel
name."

  (irc-string-downcase (case-map-name connection) string)
)


(defun make-channel (connection
                     &key (name "")
                          (topic "")
                          (modes nil)
                          (users nil)
                          (user-count nil)
)

  (let ((channel
         (make-instance 'channel
                        :name name
                        :normalized-name
                        (normalize-channel-name connection name)
                        :topic topic
                        :modes modes
                        :user-count user-count
)
)
)

    (dolist (user users)
      (add-user channel user)
)

    channel
)
)


(defgeneric find-channel (connection channel))
(defgeneric remove-all-channels (connection))
(defgeneric add-channel (connection channel))
(defgeneric remove-channel (connection channel))
(defgeneric remove-users (channel))

(defgeneric mode-name-from-char (connection target mode-char)
  (:documentation "Map the mode character used in the MODE message to a
symbol used internally to describe the mode given a `target'."
)
)


(defgeneric mode-description (connection target mode-name)
  (:documentation "Retrieve a `mode-description' structure for the given
`mode-name' keyword."
)
)


(defgeneric get-mode (target mode)
  (:documentation "Get the value associated with `mode' for `target'
or `nil' if no mode available."
)
)


(defgeneric set-mode (target mode &optional parameter)
  (:documentation "Set the mode designated by the `mode' keyword to a
value passed in `parameter' or T if `parameter' is absent."
)
)


(defgeneric unset-mode (target mode &optional parameter)
  (:documentation
"Sets value of the mode designated by the `mode' keyword to nil.
If the mode holds a list of values `parameter' is used to indicate which
element to remove."
)
)


(defgeneric add-mode (target mode-name mode)
  (:documentation "Add the mode-holding object `mode-value' to `target'
under the access key `mode-name'.

If mode-value is a subtype of irc-mode, it is added as-is.
Otherwise, a mode-object will be generated from the "
)
)

(defgeneric remove-mode (target mode-name)
  (:documentation "Remove the mode-holding object in the `mode-name' key
from `target'."
)
)


(defgeneric has-mode-p (target mode)
  (:documentation "Return a generalised boolean indicating if `target' has
a mode `mode' associated with it."
)
)


(defgeneric has-mode-value-p (target mode value &key key test)
  (:documentation "Return a generalised boolean indicating if `target' has
a mode `mode' associated with the value `value' for given a `key' transform
and `test' test."
)
)


(defmethod find-channel ((connection connection) (channel string))
  "Return channel as designated by `channel'.  If no such channel can
be found, return nil."

  (let ((channel-name (normalize-channel-name connection channel)))
    (gethash channel-name (channels connection))
)
)


(defmethod remove-all-channels ((connection connection))
  "Remove all channels known to `connection'."
  (clrhash (channels connection))
)


(defmethod add-channel ((connection connection) (channel channel))
  "Add `channel' to `connection'."
  (setf (gethash (normalized-name channel) (channels connection)) channel)
)


(defmethod remove-channel ((connection connection) (channel channel))
  "Remove `channel' from `connection'."
  (remhash (normalized-name channel) (channels connection))
)


(defmethod remove-users ((channel channel))
  "Remove all users on `channel'."
  (clrhash (users channel))
  (do-property-list (prop val (modes channel))
     (when (and val (eq (value-type val) :user))
       (remf (modes channel) prop)
)
)
)


(defmethod mode-name-from-char ((connection connection)
                                (target channel) mode-char
)

  (declare (ignore target))
  (let ((mode-desc (find mode-char (channel-mode-descriptions connection)
                         :key #'mode-desc-char
)
)
)

    (when mode-desc
      (mode-desc-symbol (the mode-description mode-desc))
)
)
)


(defmethod mode-description ((connection connection)
                             (target channel) mode-name
)

  (declare (ignore target))
  (find mode-name (channel-mode-descriptions connection)
        :key #'mode-desc-symbol
)
)


(defgeneric make-mode (connection target mode-id))

(defmethod make-mode (connection target (mode character))
  (let ((mode-name (mode-name-from-char connection target mode)))
    (make-mode connection target mode-name)
)
)


(defmethod make-mode (connection target (mode symbol))
  (let ((mode-desc (mode-description connection target mode)))
    (make-instance (mode-desc-class mode-desc)
                   :value-type (if (mode-desc-nick-param-p mode-desc)
                                   :user :non-user
)
)
)
)


(defmethod add-mode (target mode-name mode)
  (setf (getf (modes target) mode-name) mode)
)


(defmethod remove-mode (target mode-name)
  (remf (modes target) mode-name)
)


(defmethod get-mode (target mode)
  (let ((mode-object (has-mode-p target mode)))
    (when mode-object
      (value mode-object)
)
)
)


(defmethod set-mode (target mode &optional parameter)
  (set-mode-value (getf (modes target) mode) parameter)
)


(defmethod unset-mode (target mode &optional parameter)
  (let ((mode (getf (modes target) mode)))
    (when mode
      (unset-mode-value mode parameter)
)
)
)


(defmethod has-mode-p (target mode)
  (multiple-value-bind
      (indicator value tail)
      (get-properties (modes target) (list mode))
    (when (or indicator value tail)
      value
)
)
)


(