erc-backend.el 79.9 KB
Newer Older
1 2
;;; erc-backend.el --- Backend network communication for ERC

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 2004-2015 Free Software Foundation, Inc.
4 5 6

;; Filename: erc-backend.el
;; Author: Lawrence Mitchell <wence@gmx.li>
7
;; Maintainer: emacs-devel@gnu.org
8 9 10 11 12
;; Created: 2004-05-7
;; Keywords: IRC chat client internet

;; This file is part of GNU Emacs.

13
;; GNU Emacs is free software: you can redistribute it and/or modify
14
;; it under the terms of the GNU General Public License as published by
15 16
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
17 18 19 20 21 22 23

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
24
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

;;; Commentary:

;; This file defines backend network communication handlers for ERC.
;;
;; How things work:
;;
;; You define a new handler with `define-erc-response-handler'.  This
;; defines a function, a corresponding hook variable, and populates a
;; global hash table `erc-server-responses' with a map from response
;; to hook variable.  See the function documentation for more
;; information.
;;
;; Upon receiving a line from the server, `erc-parse-server-response'
;; is called on it.
;;
;; A line generally looks like:
;;
;; LINE := ':' SENDER ' ' COMMAND ' ' (COMMAND-ARGS ' ')* ':' CONTENTS
;; SENDER := Not ':' | ' '
;; COMMAND := Not ':' | ' '
;; COMMAND-ARGS := Not ':' | ' '
;;
;; This gets parsed and stuffed into an `erc-response' struct.  You
;; can access the fields of the struct with:
;;
;; COMMAND --- `erc-response.command'
;; COMMAND-ARGS --- `erc-response.command-args'
;; CONTENTS --- `erc-response.contents'
;; SENDER --- `erc-response.sender'
;; LINE --- `erc-response.unparsed'
;;
;; WARNING, WARNING!!
;; It's probably not a good idea to destructively modify the list
;; of command-args in your handlers, since other functions down the
;; line may well need to access the arguments too.
;;
;; That is, unless you're /absolutely/ sure that your handler doesn't
;; invoke some other function that needs to use COMMAND-ARGS, don't do
;; something like
;;
;; (while (erc-response.command-args parsed)
;;   (let ((a (pop (erc-response.command-args parsed))))
;;     ...))
;;
;; The parsed response is handed over to
;; `erc-handle-parsed-server-response', which checks whether it should
;; carry out duplicate suppression, and then runs `erc-call-hooks'.
;; `erc-call-hooks' retrieves the relevant hook variable from
;; `erc-server-responses' and runs it.
;;
;; Most handlers then destructure the parsed response in some way
;; (depending on what the handler is, the arguments have different
;; meanings), and generally display something, usually using
;; `erc-display-message'.

;;; TODO:

Paul Eggert's avatar
Paul Eggert committed
83
;; o Generalize the display-line code so that we can use it to
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
;;   display the stuff we send, as well as the stuff we receive.
;;   Then, move all display-related code into another backend-like
;;   file, erc-display.el, say.
;;
;; o Clean up the handlers using new display code (has to be written
;;   first).

;;; History:

;; 2004/05/10 -- Handler bodies taken out of erc.el and ported to new
;;               interface.

;; 2005-08-13 -- Moved sending commands from erc.el.

;;; Code:

(require 'erc-compat)
101
(eval-when-compile (require 'cl-lib))
102 103 104
;; There's a fairly strong mutual dependency between erc.el and erc-backend.el.
;; Luckily, erc.el does not need erc-backend.el for macroexpansion whereas the
;; reverse is true:
105 106
(provide 'erc-backend)
(require 'erc)
107 108 109 110 111 112

;;;; Variables and options

(defvar erc-server-responses (make-hash-table :test #'equal)
  "Hashtable mapping server responses to their handler hooks.")

113
(cl-defstruct (erc-response (:conc-name erc-response.))
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
  (unparsed "" :type string)
  (sender "" :type string)
  (command "" :type string)
  (command-args '() :type list)
  (contents "" :type string))

;;; User data

(defvar erc-server-current-nick nil
  "Nickname on the current server.
Use `erc-current-nick' to access this.")
(make-variable-buffer-local 'erc-server-current-nick)

;;; Server attributes

(defvar erc-server-process nil
  "The process object of the corresponding server connection.")
(make-variable-buffer-local 'erc-server-process)

(defvar erc-session-server nil
  "The server name used to connect to for this session.")
(make-variable-buffer-local 'erc-session-server)

137 138 139 140
(defvar erc-session-connector nil
  "The function used to connect to this session (nil for the default).")
(make-variable-buffer-local 'erc-session-connector)

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
(defvar erc-session-port nil
  "The port used to connect to.")
(make-variable-buffer-local 'erc-session-port)

(defvar erc-server-announced-name nil
  "The name the server announced to use.")
(make-variable-buffer-local 'erc-server-announced-name)

(defvar erc-server-version nil
  "The name and version of the server's ircd.")
(make-variable-buffer-local 'erc-server-version)

(defvar erc-server-parameters nil
  "Alist listing the supported server parameters.

This is only set if the server sends 005 messages saying what is
supported on the server.

Entries are of the form:
  (PARAMETER . VALUE)
or
  (PARAMETER) if no value is provided.

Some examples of possible parameters sent by servers:
CHANMODES=b,k,l,imnpst - list of supported channel modes
CHANNELLEN=50 - maximum length of channel names
CHANTYPES=#&!+ - supported channel prefixes
CHARMAPPING=rfc1459 - character mapping used for nickname and channels
KICKLEN=160 - maximum allowed kick message length
MAXBANS=30 - maximum number of bans per channel
MAXCHANNELS=10 - maximum number of channels allowed to join
NETWORK=EFnet -  the network identifier
NICKLEN=9 - maximum allowed length of nicknames
PREFIX=(ov)@+ - list of channel modes and the user prefixes if user has mode
RFC2812 - server supports RFC 2812 features
SILENCE=10 - supports the SILENCE command, maximum allowed number of entries
TOPICLEN=160 - maximum allowed topic length
WALLCHOPS - supports sending messages to all operators in a channel")
(make-variable-buffer-local 'erc-server-parameters)

;;; Server and connection state

Miles Bader's avatar
Miles Bader committed
183 184 185
(defvar erc-server-ping-timer-alist nil
  "Mapping of server buffers to their specific ping timer.")

186
(defvar erc-server-connected nil
Miles Bader's avatar
Miles Bader committed
187 188 189 190 191
  "Non-nil if the current buffer has been used by ERC to establish
an IRC connection.

If you wish to determine whether an IRC connection is currently
active, use the `erc-server-process-alive' function instead.")
192 193
(make-variable-buffer-local 'erc-server-connected)

Miles Bader's avatar
Miles Bader committed
194 195 196 197
(defvar erc-server-reconnect-count 0
  "Number of times we have failed to reconnect to the current server.")
(make-variable-buffer-local 'erc-server-reconnect-count)

198 199 200 201
(defvar erc-server-quitting nil
  "Non-nil if the user requests a quit.")
(make-variable-buffer-local 'erc-server-quitting)

Miles Bader's avatar
Miles Bader committed
202 203 204 205 206 207 208 209 210
(defvar erc-server-reconnecting nil
  "Non-nil if the user requests an explicit reconnect, and the
current IRC process is still alive.")
(make-variable-buffer-local 'erc-server-reconnecting)

(defvar erc-server-timed-out nil
  "Non-nil if the IRC server failed to respond to a ping.")
(make-variable-buffer-local 'erc-server-timed-out)

Miles Bader's avatar
Miles Bader committed
211 212 213 214
(defvar erc-server-banned nil
  "Non-nil if the user is denied access because of a server ban.")
(make-variable-buffer-local 'erc-server-banned)

Miles Bader's avatar
Miles Bader committed
215 216 217 218
(defvar erc-server-error-occurred nil
  "Non-nil if the user triggers some server error.")
(make-variable-buffer-local 'erc-server-error-occurred)

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
(defvar erc-server-lines-sent nil
  "Line counter.")
(make-variable-buffer-local 'erc-server-lines-sent)

(defvar erc-server-last-peers '(nil . nil)
  "Last peers used, both sender and receiver.
Those are used for /MSG destination shortcuts.")
(make-variable-buffer-local 'erc-server-last-peers)

(defvar erc-server-last-sent-time nil
  "Time the message was sent.
This is useful for flood protection.")
(make-variable-buffer-local 'erc-server-last-sent-time)

(defvar erc-server-last-ping-time nil
  "Time the last ping was sent.
This is useful for flood protection.")
(make-variable-buffer-local 'erc-server-last-ping-time)

Miles Bader's avatar
Miles Bader committed
238 239 240 241 242
(defvar erc-server-last-received-time nil
  "Time the last message was received from the server.
This is useful for detecting hung connections.")
(make-variable-buffer-local 'erc-server-last-received-time)

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
(defvar erc-server-lag nil
  "Calculated server lag time in seconds.
This variable is only set in a server buffer.")
(make-variable-buffer-local 'erc-server-lag)

(defvar erc-server-filter-data nil
  "The data that arrived from the server
but has not been processed yet.")
(make-variable-buffer-local 'erc-server-filter-data)

(defvar erc-server-duplicates (make-hash-table :test 'equal)
  "Internal variable used to track duplicate messages.")
(make-variable-buffer-local 'erc-server-duplicates)

;; From Circe
(defvar erc-server-processing-p nil
  "Non-nil when we're currently processing a message.

When ERC receives a private message, it sets up a new buffer for
this query.  These in turn, though, do start flyspell. This
involves starting an external process, in which case Emacs will
wait - and when it waits, it does accept other stuff from, say,
network exceptions.  So, if someone sends you two messages
quickly after each other, ispell is started for the first, but
might take long enough for the second message to be processed
first.")
(make-variable-buffer-local 'erc-server-processing-p)

(defvar erc-server-flood-last-message 0
  "When we sent the last message.
See `erc-server-flood-margin' for an explanation of the flood
protection algorithm.")
(make-variable-buffer-local 'erc-server-flood-last-message)

(defvar erc-server-flood-queue nil
  "The queue of messages waiting to be sent to the server.
See `erc-server-flood-margin' for an explanation of the flood
protection algorithm.")
(make-variable-buffer-local 'erc-server-flood-queue)

(defvar erc-server-flood-timer nil
  "The timer to resume sending.")
(make-variable-buffer-local 'erc-server-flood-timer)

;;; IRC protocol and misc options

(defgroup erc-server nil
  "Parameters for dealing with IRC servers."
  :group 'erc)

(defcustom erc-server-auto-reconnect t
  "Non-nil means that ERC will attempt to reestablish broken connections.

Reconnection will happen automatically for any unexpected disconnection."
  :group 'erc-server
  :type 'boolean)

Miles Bader's avatar
Miles Bader committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
(defcustom erc-server-reconnect-attempts 2
  "The number of times that ERC will attempt to reestablish a
broken connection, or t to always attempt to reconnect.

This only has an effect if `erc-server-auto-reconnect' is non-nil."
  :group 'erc-server
  :type '(choice (const :tag "Always reconnect" t)
                 integer))

(defcustom erc-server-reconnect-timeout 1
  "The amount of time, in seconds, that ERC will wait between
successive reconnect attempts.

If a key is pressed while ERC is waiting, it will stop waiting."
  :group 'erc-server
  :type 'number)

317
(defcustom erc-split-line-length 440
318
  "The maximum length of a single message.
319 320 321 322 323 324 325 326 327 328 329 330
If a message exceeds this size, it is broken into multiple ones.

IRC allows for lines up to 512 bytes. Two of them are CR LF.
And a typical message looks like this:

  :nicky!uhuser@host212223.dialin.fnordisp.net PRIVMSG #lazybastards :Hello!

You can limit here the maximum length of the \"Hello!\" part.
Good luck."
  :type 'integer
  :group 'erc-server)

331 332 333 334 335
(defcustom erc-coding-system-precedence '(utf-8 undecided)
  "List of coding systems to be preferred when receiving a string from the server.
This will only be consulted if the coding system in
`erc-server-coding-system' is `undecided'."
  :group 'erc-server
Kelvin White's avatar
Kelvin White committed
336
  :version "24.1"
337 338
  :type '(repeat coding-system))

339 340 341 342 343 344 345 346 347 348
(defcustom erc-server-coding-system (if (and (fboundp 'coding-system-p)
                                             (coding-system-p 'undecided)
                                             (coding-system-p 'utf-8))
                                        '(utf-8 . undecided)
                                      nil)
  "The default coding system for incoming and outgoing text.
This is either a coding system, a cons, a function, or nil.

If a cons, the encoding system for outgoing text is in the car
and the decoding system for incoming text is in the cdr. The most
349 350 351
interesting use for this is to put `undecided' in the cdr. This
means that `erc-coding-system-precedence' will be consulted, and the
first match there will be used.
352 353 354

If a function, it is called with the argument `target' and should
return a coding system or a cons as described above.
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372

If you need to send non-ASCII text to people not using a client that
does decoding on its own, you must tell ERC what encoding to use.
Emacs cannot guess it, since it does not know what the people on the
other end of the line are using."
  :group 'erc-server
  :type '(choice (const :tag "None" nil)
                 coding-system
                 (cons (coding-system :tag "encoding" :value utf-8)
                       (coding-system :tag "decoding" :value undecided))
                 function))

(defcustom erc-encoding-coding-alist nil
  "Alist of target regexp and coding-system pairs to use.
This overrides `erc-server-coding-system' depending on the
current target as returned by `erc-default-target'.

Example: If you know that the channel #linux-ru uses the coding-system
373
`cyrillic-koi8', then add (\"#linux-ru\" . cyrillic-koi8) to the
374 375 376 377 378
alist."
  :group 'erc-server
  :type '(repeat (cons (string :tag "Target")
                       coding-system)))

l3thal's avatar
l3thal committed
379
(defcustom erc-server-connect-function 'erc-open-network-stream
380 381 382 383 384 385
  "Function used to initiate a connection.
It should take same arguments as `open-network-stream' does."
  :group 'erc-server
  :type 'function)

(defcustom erc-server-prevent-duplicates '("301")
386
  "Either nil or a list of strings.
387 388 389 390 391 392
Each string is a IRC message type, like PRIVMSG or NOTICE.
All Message types in that list of subjected to duplicate prevention."
  :type '(choice (const nil) (list string))
  :group 'erc-server)

(defcustom erc-server-duplicate-timeout 60
393
  "The time allowed in seconds between duplicate messages.
394 395 396 397 398 399

If two identical messages arrive within this value of one another, the second
isn't displayed."
  :type 'integer
  :group 'erc-server)

400
(defcustom erc-server-timestamp-format "%Y-%m-%d %T"
401
  "Timestamp format used with server response messages.
402
This string is processed using `format-time-string'."
Kelvin White's avatar
Kelvin White committed
403
  :version "24.3"
404 405 406
  :type 'string
  :group 'erc-server)

407 408 409 410 411 412
;;; Flood-related

;; Most of this is courtesy of Jorgen Schaefer and Circe
;; (http://www.nongnu.org/circe)

(defcustom erc-server-flood-margin 10
413
  "A margin on how much excess data we send.
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
The flood protection algorithm of ERC works like the one
detailed in RFC 2813, section 5.8 \"Flood control of clients\".

  * If `erc-server-flood-last-message' is less than the current
    time, set it equal.
  * While `erc-server-flood-last-message' is less than
    `erc-server-flood-margin' seconds ahead of the current
    time, send a message, and increase
    `erc-server-flood-last-message' by
    `erc-server-flood-penalty' for each message."
  :type 'integer
  :group 'erc-server)

(defcustom erc-server-flood-penalty 3
  "How much we penalize a message.
See `erc-server-flood-margin' for an explanation of the flood
protection algorithm."
  :type 'integer
  :group 'erc-server)

;; Ping handling

Miles Bader's avatar
Miles Bader committed
436
(defcustom erc-server-send-ping-interval 30
437
  "Interval of sending pings to the server, in seconds.
438 439
If this is set to nil, pinging the server is disabled."
  :group 'erc-server
Miles Bader's avatar
Miles Bader committed
440 441 442 443
  :type '(choice (const :tag "Disabled" nil)
                 (integer :tag "Seconds")))

(defcustom erc-server-send-ping-timeout 120
444
  "If the time between ping and response is greater than this, reconnect.
Miles Bader's avatar
Miles Bader committed
445 446 447 448 449 450 451 452 453
The time is in seconds.

This must be greater than or equal to the value for
`erc-server-send-ping-interval'.

If this is set to nil, never try to reconnect."
  :group 'erc-server
  :type '(choice (const :tag "Disabled" nil)
                 (integer :tag "Seconds")))
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485

(defvar erc-server-ping-handler nil
  "This variable holds the periodic ping timer.")
(make-variable-buffer-local 'erc-server-ping-handler)

;;;; Helper functions

;; From Circe
(defun erc-split-line (longline)
  "Return a list of lines which are not too long for IRC.
The length is specified in `erc-split-line-length'.

Currently this is called by `erc-send-input'."
  (if (< (length longline)
         erc-split-line-length)
      (list longline)
    (with-temp-buffer
      (insert longline)
      (let ((fill-column erc-split-line-length))
        (fill-region (point-min) (point-max)
                     nil t))
      (split-string (buffer-string) "\n"))))

;; Used by CTCP functions
(defun erc-upcase-first-word (str)
  "Upcase the first word in STR."
  (with-temp-buffer
    (insert str)
    (goto-char (point-min))
    (upcase-word 1)
    (buffer-string)))

Miles Bader's avatar
Miles Bader committed
486 487 488 489 490 491 492 493 494 495
(defun erc-server-setup-periodical-ping (buffer)
  "Set up a timer to periodically ping the current server.
The current buffer is given by BUFFER."
  (with-current-buffer buffer
    (and erc-server-ping-handler (erc-cancel-timer erc-server-ping-handler))
    (when erc-server-send-ping-interval
      (setq erc-server-ping-handler (run-with-timer
                                     4 erc-server-send-ping-interval
                                     #'erc-server-send-ping
                                     buffer))
496 497 498 499 500 501 502 503 504 505 506 507 508

      ;; I check the timer alist for an existing timer. If one exists,
      ;; I get rid of it
      (let ((timer-tuple (assq buffer erc-server-ping-timer-alist)))
        (if timer-tuple
            ;; this buffer already has a timer. Cancel it and set the new one
            (progn
              (erc-cancel-timer (cdr timer-tuple))
              (setf (cdr (assq buffer erc-server-ping-timer-alist)) erc-server-ping-handler))

          ;; no existing timer for this buffer. Add new one
          (add-to-list 'erc-server-ping-timer-alist
                       (cons buffer erc-server-ping-handler)))))))
509

510 511 512 513 514 515
(defun erc-server-process-alive (&optional buffer)
  "Return non-nil when BUFFER has an `erc-server-process' open or running."
  (with-current-buffer (or buffer (current-buffer))
    (and erc-server-process
         (processp erc-server-process)
         (memq (process-status erc-server-process) '(run open)))))
516 517

;;;; Connecting to a server
l3thal's avatar
l3thal committed
518 519 520 521
(defun erc-open-network-stream (name buffer host service)
  "As `open-network-stream', but does non-blocking IO"
  (make-network-process :name name :buffer  buffer
                        :host host :service service :nowait t))
522

Miles Bader's avatar
Miles Bader committed
523 524 525
(defun erc-server-connect (server port buffer)
  "Perform the connection and login using the specified SERVER and PORT.
We will store server variables in the buffer given by BUFFER."
526 527
  (let ((msg (erc-format-message 'connect ?S server ?p port)))
    (message "%s" msg)
Miles Bader's avatar
Miles Bader committed
528 529 530
    (let ((process (funcall erc-server-connect-function
                            (format "erc-%s-%s" server port)
                            nil server port)))
531 532
      (unless (processp process)
        (error "Connection attempt failed"))
Miles Bader's avatar
Miles Bader committed
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
      (message "%s...done" msg)
      ;; Misc server variables
      (with-current-buffer buffer
        (setq erc-server-process process)
        (setq erc-server-quitting nil)
        (setq erc-server-reconnecting nil)
        (setq erc-server-timed-out nil)
        (setq erc-server-banned nil)
        (setq erc-server-error-occurred nil)
        (let ((time (erc-current-time)))
          (setq erc-server-last-sent-time time)
          (setq erc-server-last-ping-time time)
          (setq erc-server-last-received-time time))
        (setq erc-server-lines-sent 0)
        ;; last peers (sender and receiver)
        (setq erc-server-last-peers '(nil . nil)))
      ;; we do our own encoding and decoding
      (when (fboundp 'set-process-coding-system)
        (set-process-coding-system process 'raw-text))
      ;; process handlers
      (set-process-sentinel process 'erc-process-sentinel)
      (set-process-filter process 'erc-server-filter-function)
      (set-process-buffer process buffer)))
556
  (erc-log "\n\n\n********************************************\n")
557
  (message "%s" (erc-format-message
Miles Bader's avatar
Miles Bader committed
558 559
            'login ?n
            (with-current-buffer buffer (erc-current-nick))))
560 561 562 563 564
  ;; wait with script loading until we receive a confirmation (first
  ;; MOTD line)
  (if (eq erc-server-connect-function 'open-network-stream-nowait)
      ;; it's a bit unclear otherwise that it's attempting to establish a
      ;; connection
Miles Bader's avatar
Miles Bader committed
565
      (erc-display-message nil nil buffer "Opening connection..\n")
566 567
    (erc-login)))

Miles Bader's avatar
Miles Bader committed
568 569 570
(defun erc-server-reconnect ()
"Reestablish the current IRC connection.
Make sure you are in an ERC buffer when running this."
571 572 573 574 575 576
  (let ((buffer (erc-server-buffer)))
    (unless (buffer-live-p buffer)
      (if (eq major-mode 'erc-mode)
          (setq buffer (current-buffer))
        (error "Reconnect must be run from an ERC buffer")))
    (with-current-buffer buffer
Miles Bader's avatar
Miles Bader committed
577 578 579 580
      (erc-update-mode-line)
      (erc-set-active-buffer (current-buffer))
      (setq erc-server-last-sent-time 0)
      (setq erc-server-lines-sent 0)
581
      (let ((erc-server-connect-function (or erc-session-connector
l3thal's avatar
l3thal committed
582
                                             'erc-open-network-stream)))
583 584
        (erc-open erc-session-server erc-session-port erc-server-current-nick
                  erc-session-user-full-name t erc-session-password)))))
Miles Bader's avatar
Miles Bader committed
585

l3thal's avatar
l3thal committed
586 587 588 589 590
(defun erc-server-delayed-reconnect (event buffer)
  (if (buffer-live-p buffer)
    (with-current-buffer buffer
      (erc-server-reconnect))))

591 592 593
(defun erc-server-filter-function (process string)
  "The process filter for the ERC server."
  (with-current-buffer (process-buffer process)
Miles Bader's avatar
Miles Bader committed
594
    (setq erc-server-last-received-time (erc-current-time))
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
    ;; If you think this is written in a weird way - please refer to the
    ;; docstring of `erc-server-processing-p'
    (if erc-server-processing-p
        (setq erc-server-filter-data
              (if erc-server-filter-data
                  (concat erc-server-filter-data string)
                string))
      ;; This will be true even if another process is spawned!
      (let ((erc-server-processing-p t))
        (setq erc-server-filter-data (if erc-server-filter-data
                                           (concat erc-server-filter-data
                                                   string)
                                         string))
        (while (and erc-server-filter-data
                    (string-match "[\n\r]+" erc-server-filter-data))
          (let ((line (substring erc-server-filter-data
                                 0 (match-beginning 0))))
            (setq erc-server-filter-data
                  (if (= (match-end 0)
                         (length erc-server-filter-data))
                      nil
                    (substring erc-server-filter-data
                               (match-end 0))))
618
            (erc-log-irc-protocol line nil)
619 620
            (erc-parse-server-response process line)))))))

Miles Bader's avatar
Miles Bader committed
621 622 623
(defsubst erc-server-reconnect-p (event)
  "Return non-nil if ERC should attempt to reconnect automatically.
EVENT is the message received from the closed connection process."
Miles Bader's avatar
Miles Bader committed
624 625 626 627 628 629 630 631 632 633 634 635 636
  (or erc-server-reconnecting
      (and erc-server-auto-reconnect
           (not erc-server-banned)
           (not erc-server-error-occurred)
           ;; make sure we don't infinitely try to reconnect, unless the
           ;; user wants that
           (or (eq erc-server-reconnect-attempts t)
               (and (integerp erc-server-reconnect-attempts)
                    (< erc-server-reconnect-count
                       erc-server-reconnect-attempts)))
           (or erc-server-timed-out
               (not (string-match "^deleted" event)))
           ;; open-network-stream-nowait error for connection refused
l3thal's avatar
l3thal committed
637
           (if (string-match "^failed with code 111" event) 'nonblocking t))))
Miles Bader's avatar
Miles Bader committed
638

639 640 641 642 643
(defun erc-process-sentinel-2 (event buffer)
  "Called when `erc-process-sentinel-1' has detected an unexpected disconnect."
  (if (not (buffer-live-p buffer))
      (erc-update-mode-line)
    (with-current-buffer buffer
l3thal's avatar
l3thal committed
644 645 646
      (let ((reconnect-p (erc-server-reconnect-p event)) message delay)
        (setq message (if reconnect-p 'disconnected 'disconnected-noreconnect))
        (erc-display-message nil 'error (current-buffer) message)
647 648 649 650 651 652 653 654 655 656 657
        (if (not reconnect-p)
            ;; terminate, do not reconnect
            (progn
              (erc-display-message nil 'error (current-buffer)
                                   'terminated ?e event)
              ;; Update mode line indicators
              (erc-update-mode-line)
              (set-buffer-modified-p nil))
          ;; reconnect
          (condition-case err
              (progn
l3thal's avatar
l3thal committed
658 659 660 661 662 663 664 665 666 667
                (setq erc-server-reconnecting   nil
                      erc-server-reconnect-count (1+ erc-server-reconnect-count))
                (setq delay erc-server-reconnect-timeout)
                (run-at-time delay nil
                             #'erc-server-delayed-reconnect event buffer))
            (error (unless (integerp erc-server-reconnect-attempts)
                     (message "%s ... %s"
                              "Reconnecting until we succeed"
                              "kill the ERC server buffer to stop"))
                   (erc-server-delayed-reconnect event buffer))))))))
668 669

(defun erc-process-sentinel-1 (event buffer)
Miles Bader's avatar
Miles Bader committed
670 671 672
  "Called when `erc-process-sentinel' has decided that we're disconnecting.
Determine whether user has quit or whether erc has been terminated.
Conditionally try to reconnect and take appropriate action."
673 674 675 676 677 678 679 680
  (with-current-buffer buffer
    (if erc-server-quitting
        ;; normal quit
        (progn
          (erc-display-message nil 'error (current-buffer) 'finished)
          ;; Update mode line indicators
          (erc-update-mode-line)
          ;; Kill server buffer if user wants it
681
          (set-buffer-modified-p nil)
682 683 684 685
          (when erc-kill-server-buffer-on-quit
            (kill-buffer (current-buffer))))
      ;; unexpected disconnect
      (erc-process-sentinel-2 event buffer))))
686 687 688

(defun erc-process-sentinel (cproc event)
  "Sentinel function for ERC process."
689 690 691 692
  (let ((buf (process-buffer cproc)))
    (when (buffer-live-p buf)
      (with-current-buffer buf
        (erc-log (format
l3thal's avatar
l3thal committed
693
                  "SENTINEL: proc: %S    status: %S  event: %S (quitting: %S)"
694 695 696 697 698 699 700 701 702 703 704 705
                  cproc (process-status cproc) event erc-server-quitting))
        (if (string-match "^open" event)
            ;; newly opened connection (no wait)
            (erc-login)
          ;; assume event is 'failed
          (erc-with-all-buffers-of-server cproc nil
                                          (setq erc-server-connected nil))
          (when erc-server-ping-handler
            (progn (erc-cancel-timer erc-server-ping-handler)
                   (setq erc-server-ping-handler nil)))
          (run-hook-with-args 'erc-disconnected-hook
                              (erc-current-nick) (system-name) "")
706 707 708
          (dolist (buf (erc-buffer-filter (lambda () (boundp 'erc-channel-users)) cproc))
            (with-current-buffer buf
              (setq erc-channel-users (make-hash-table :test 'equal))))
709 710 711 712 713 714 715 716
          ;; Remove the prompt
          (goto-char (or (marker-position erc-input-marker) (point-max)))
          (forward-line 0)
          (erc-remove-text-properties-region (point) (point-max))
          (delete-region (point) (point-max))
          ;; Decide what to do with the buffer
          ;; Restart if disconnected
          (erc-process-sentinel-1 event buf))))))
717 718 719 720 721 722 723

;;;; Sending messages

(defun erc-coding-system-for-target (target)
  "Return the coding system or cons cell appropriate for TARGET.
This is determined via `erc-encoding-coding-alist' or
`erc-server-coding-system'."
Miles Bader's avatar
Miles Bader committed
724
  (unless target (setq target (erc-default-target)))
Miles Bader's avatar
Miles Bader committed
725 726 727 728 729 730
  (or (when target
        (let ((case-fold-search t))
          (catch 'match
            (dolist (pat erc-encoding-coding-alist)
              (when (string-match (car pat) target)
                (throw 'match (cdr pat)))))))
731
      (and (functionp erc-server-coding-system)
732
           (funcall erc-server-coding-system target))
733 734 735 736 737 738 739 740 741 742 743
      erc-server-coding-system))

(defun erc-decode-string-from-target (str target)
  "Decode STR as appropriate for TARGET.
This is indicated by `erc-encoding-coding-alist', defaulting to the value of
`erc-server-coding-system'."
  (unless (stringp str)
    (setq str ""))
  (let ((coding (erc-coding-system-for-target target)))
    (when (consp coding)
      (setq coding (cdr coding)))
744 745 746 747 748 749 750 751
    (when (eq coding 'undecided)
      (let ((codings (detect-coding-string str))
            (precedence erc-coding-system-precedence))
        (while (and precedence
                    (not (memq (car precedence) codings)))
          (pop precedence))
        (when precedence
          (setq coding (car precedence)))))
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
    (erc-decode-coding-string str coding)))

;; proposed name, not used by anything yet
(defun erc-send-line (text display-fn)
  "Send TEXT to the current server.  Wrapping and flood control apply.
Use DISPLAY-FN to show the results."
  (mapc (lambda (line)
          (erc-server-send line)
          (funcall display-fn))
        (erc-split-line text)))

;; From Circe, with modifications
(defun erc-server-send (string &optional forcep target)
  "Send STRING to the current server.
If FORCEP is non-nil, no flood protection is done - the string is
sent directly. This might cause the messages to arrive in a wrong
order.

If TARGET is specified, look up encoding information for that
channel in `erc-encoding-coding-alist' or
`erc-server-coding-system'.

See `erc-server-flood-margin' for an explanation of the flood
protection algorithm."
  (erc-log (concat "erc-server-send: " string "(" (buffer-name) ")"))
  (setq erc-server-last-sent-time (erc-current-time))
Miles Bader's avatar
Miles Bader committed
778
  (let ((encoding (erc-coding-system-for-target target)))
779 780
    (when (consp encoding)
      (setq encoding (car encoding)))
Miles Bader's avatar
Miles Bader committed
781 782
    (if (erc-server-process-alive)
        (erc-with-server-buffer
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
          (let ((str (concat string "\r\n")))
            (if forcep
                (progn
                  (setq erc-server-flood-last-message
                        (+ erc-server-flood-penalty
                           erc-server-flood-last-message))
                  (erc-log-irc-protocol str 'outbound)
                  (condition-case err
                      (progn
                        ;; Set encoding just before sending the string
                        (when (fboundp 'set-process-coding-system)
                          (set-process-coding-system erc-server-process
                                                     'raw-text encoding))
                        (process-send-string erc-server-process str))
                    ;; See `erc-server-send-queue' for full
                    ;; explanation of why we need this condition-case
                    (error nil)))
              (setq erc-server-flood-queue
                    (append erc-server-flood-queue
                            (list (cons str encoding))))
              (erc-server-send-queue (current-buffer))))
          t)
      (message "ERC: No process running")
      nil)))

808 809 810
(defun erc-server-send-ping (buf)
  "Send a ping to the IRC server buffer in BUF.
Additionally, detect whether the IRC process has hung."
811 812 813
  (if (and (buffer-live-p buf)
           (with-current-buffer buf
             erc-server-last-received-time))
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
      (with-current-buffer buf
        (if (and erc-server-send-ping-timeout
                 (>
                  (erc-time-diff (erc-current-time)
                                 erc-server-last-received-time)
                  erc-server-send-ping-timeout))
            (progn
              ;; if the process is hung, kill it
              (setq erc-server-timed-out t)
              (delete-process erc-server-process))
          (erc-server-send (format "PING %.0f" (erc-current-time)))))
    ;; remove timer if the server buffer has been killed
    (let ((timer (assq buf erc-server-ping-timer-alist)))
      (when timer
        (erc-cancel-timer (cdr timer))
        (setcdr timer nil)))))

831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
;; From Circe
(defun erc-server-send-queue (buffer)
  "Send messages in `erc-server-flood-queue'.
See `erc-server-flood-margin' for an explanation of the flood
protection algorithm."
  (with-current-buffer buffer
    (let ((now (erc-current-time)))
      (when erc-server-flood-timer
        (erc-cancel-timer erc-server-flood-timer)
        (setq erc-server-flood-timer nil))
      (when (< erc-server-flood-last-message
               now)
        (setq erc-server-flood-last-message now))
      (while (and erc-server-flood-queue
                  (< erc-server-flood-last-message
                     (+ now erc-server-flood-margin)))
        (let ((msg (caar erc-server-flood-queue))
              (encoding (cdar erc-server-flood-queue)))
          (setq erc-server-flood-queue (cdr erc-server-flood-queue)
                erc-server-flood-last-message
                (+ erc-server-flood-last-message
                   erc-server-flood-penalty))
          (erc-log-irc-protocol msg 'outbound)
          (erc-log (concat "erc-server-send-queue: "
                           msg "(" (buffer-name buffer) ")"))
          (when (erc-server-process-alive)
            (condition-case err
                ;; Set encoding just before sending the string
                (progn
                  (when (fboundp 'set-process-coding-system)
                    (set-process-coding-system erc-server-process
                                               'raw-text encoding))
                  (process-send-string erc-server-process msg))
              ;; Sometimes the send can occur while the process is
              ;; being killed, which results in a weird SIGPIPE error.
              ;; Catch this and ignore it.
              (error nil)))))
      (when erc-server-flood-queue
        (setq erc-server-flood-timer
Miles Bader's avatar
Miles Bader committed
870 871
              (run-at-time (+ 0.2 erc-server-flood-penalty)
                           nil #'erc-server-send-queue buffer))))))
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951

(defun erc-message (message-command line &optional force)
  "Send LINE to the server as a privmsg or a notice.
MESSAGE-COMMAND should be either \"PRIVMSG\" or \"NOTICE\".
If the target is \",\", the last person you've got a message from will
be used. If the target is \".\", the last person you've sent a message
to will be used."
  (cond
   ((string-match "^\\s-*\\(\\S-+\\) ?\\(.*\\)" line)
    (let ((tgt (match-string 1 line))
          (s (match-string 2 line)))
      (erc-log (format "cmd: MSG(%s): [%s] %s" message-command tgt s))
      (cond
       ((string= tgt ",")
        (if (car erc-server-last-peers)
            (setq tgt (car erc-server-last-peers))
          (setq tgt nil)))
       ((string= tgt ".")
        (if (cdr erc-server-last-peers)
            (setq tgt (cdr erc-server-last-peers))
          (setq tgt nil))))
      (cond
       (tgt
        (setcdr erc-server-last-peers tgt)
        (erc-server-send (format "%s %s :%s" message-command tgt s)
                         force))
       (t
        (erc-display-message nil 'error (current-buffer) 'no-target))))
    t)
   (t nil)))

;;; CTCP

(defun erc-send-ctcp-message (tgt l &optional force)
  "Send CTCP message L to TGT.

If TGT is nil the message is not sent.
The command must contain neither a prefix nor a trailing `\\n'.

See also `erc-server-send'."
  (let ((l (erc-upcase-first-word l)))
    (cond
     (tgt
      (erc-log (format "erc-send-CTCP-message: [%s] %s" tgt l))
      (erc-server-send (format "PRIVMSG %s :\C-a%s\C-a" tgt l)
                       force)))))

(defun erc-send-ctcp-notice (tgt l &optional force)
  "Send CTCP notice L to TGT.

If TGT is nil the message is not sent.
The command must contain neither a prefix nor a trailing `\\n'.

See also `erc-server-send'."
  (let ((l (erc-upcase-first-word l)))
    (cond
     (tgt
      (erc-log (format "erc-send-CTCP-notice: [%s] %s" tgt l))
      (erc-server-send (format "NOTICE %s :\C-a%s\C-a" tgt l)
                       force)))))

;;;; Handling responses

(defun erc-parse-server-response (proc string)
  "Parse and act upon a complete line from an IRC server.
PROC is the process (connection) from which STRING was received.
PROCs `process-buffer' is `current-buffer' when this function is called."
  (unless (string= string "") ;; Ignore empty strings
    (save-match-data
      (let ((posn (if (eq (aref string 0) ?:)
                      (string-match " " string)
                    0))
            (msg (make-erc-response :unparsed string)))

        (setf (erc-response.sender msg)
              (if (eq posn 0)
                  erc-session-server
                (substring string 1 posn)))

        (setf (erc-response.command msg)
952
              (let* ((bposn (string-match "[^ \n]" string posn))
953 954
                     (eposn (string-match " " string bposn)))
                (setq posn (and eposn
955
                                (string-match "[^ \n]" string eposn)))
956 957 958 959 960 961 962
                (substring string bposn eposn)))

        (while (and posn
                    (not (eq (aref string posn) ?:)))
          (push (let* ((bposn posn)
                       (eposn (string-match " " string bposn)))
                  (setq posn (and eposn
963
                                  (string-match "[^ \n]" string eposn)))
964 965 966 967 968 969 970
                  (substring string bposn eposn))
                (erc-response.command-args msg)))
        (when posn
      (let ((str (substring string (1+ posn))))
        (push str (erc-response.command-args msg))))

    (setf (erc-response.contents msg)
971
          (car (erc-response.command-args msg)))
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022

    (setf (erc-response.command-args msg)
          (nreverse (erc-response.command-args msg)))

    (erc-decode-parsed-server-response msg)

    (erc-handle-parsed-server-response proc msg)))))

(defun erc-decode-parsed-server-response (parsed-response)
  "Decode a pre-parsed PARSED-RESPONSE before it can be handled.

If there is a channel name in `erc-response.command-args', decode
`erc-response' according to this channel name and
`erc-encoding-coding-alist', or use `erc-server-coding-system'
for decoding."
  (let ((args (erc-response.command-args parsed-response))
        (decode-target nil)
        (decoded-args ()))
    (dolist (arg args nil)
      (when (string-match "^[#&].*" arg)
        (setq decode-target arg)))
    (when (stringp decode-target)
      (setq decode-target (erc-decode-string-from-target decode-target nil)))
    (setf (erc-response.unparsed parsed-response)
          (erc-decode-string-from-target
           (erc-response.unparsed parsed-response)
           decode-target))
    (setf (erc-response.sender parsed-response)
          (erc-decode-string-from-target
           (erc-response.sender parsed-response)
           decode-target))
    (setf (erc-response.command parsed-response)
          (erc-decode-string-from-target
           (erc-response.command parsed-response)
           decode-target))
    (dolist (arg (nreverse args) nil)
      (push (erc-decode-string-from-target arg decode-target)
            decoded-args))
    (setf (erc-response.command-args parsed-response) decoded-args)
    (setf (erc-response.contents parsed-response)
          (erc-decode-string-from-target
           (erc-response.contents parsed-response)
           decode-target))))

(defun erc-handle-parsed-server-response (process parsed-response)
  "Handle a pre-parsed PARSED-RESPONSE from PROCESS.

Hands off to helper functions via `erc-call-hooks'."
  (if (member (erc-response.command parsed-response)
              erc-server-prevent-duplicates)
      (let ((m (erc-response.unparsed parsed-response)))
Paul Eggert's avatar
Paul Eggert committed
1023
        ;; duplicate suppression
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
        (if (< (or (gethash m erc-server-duplicates) 0)
               (- (erc-current-time) erc-server-duplicate-timeout))
            (erc-call-hooks process parsed-response))
        (puthash m (erc-current-time) erc-server-duplicates))
    ;; Hand off to the relevant handler.
    (erc-call-hooks process parsed-response)))

(defun erc-get-hook (command)
  "Return the hook variable associated with COMMAND.

See also `erc-server-responses'."
  (gethash (format (if (numberp command) "%03i" "%s") command)
           erc-server-responses))

(defun erc-call-hooks (process message)
  "Call hooks associated with MESSAGE in PROCESS.

Finds hooks by looking in the `erc-server-responses' hashtable."
  (let ((hook (or (erc-get-hook (erc-response.command message))
                  'erc-default-server-functions)))
    (run-hook-with-args-until-success hook process message)
Miles Bader's avatar
Miles Bader committed
1045 1046
    (erc-with-server-buffer
      (run-hook-with-args 'erc-timer-hook (erc-current-time)))))
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065

(add-hook 'erc-default-server-functions 'erc-handle-unknown-server-response)

(defun erc-handle-unknown-server-response (proc parsed)
  "Display unknown server response's message."
  (let ((line (concat (erc-response.sender parsed)
                      " "
                      (erc-response.command parsed)
                      " "
                      (mapconcat 'identity (erc-response.command-args parsed)
                                 " "))))
    (erc-display-message parsed 'notice proc line)))


(put 'define-erc-response-handler 'edebug-form-spec
     '(&define :name erc-response-handler
               (name &rest name)
               &optional sexp sexp def-body))

1066
(cl-defmacro define-erc-response-handler ((name &rest aliases)
1067 1068 1069 1070 1071 1072 1073
                                        &optional extra-fn-doc extra-var-doc
                                        &rest fn-body)
  "Define an ERC handler hook/function pair.
NAME is the response name as sent by the server (see the IRC RFC for
meanings).

This creates:
1074
 - a hook variable `erc-server-NAME-functions' initialized to `erc-server-NAME'.
1075 1076 1077 1078 1079
 - a function `erc-server-NAME' with body FN-BODY.

If ALIASES is non-nil, each alias in ALIASES is `defalias'ed to
`erc-server-NAME'.
Alias hook variables are created as `erc-server-ALIAS-functions' and
1080
initialized to the same default value as `erc-server-NAME-functions'.
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100

FN-BODY is the body of `erc-server-NAME' it may refer to the two
function arguments PROC and PARSED.

If EXTRA-FN-DOC is non-nil, it is inserted at the beginning of the
defined function's docstring.

If EXTRA-VAR-DOC is non-nil, it is inserted at the beginning of the
defined variable's docstring.

As an example:

  (define-erc-response-handler (311 WHOIS WI)
    \"Some non-generic function documentation.\"
    \"Some non-generic variable documentation.\"
    (do-stuff-with-whois proc parsed))

Would expand to:

  (prog2
Paul Eggert's avatar
Paul Eggert committed
1101
      (defvar erc-server-311-functions \\='erc-server-311
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
        \"Some non-generic variable documentation.

  Hook called upon receiving a 311 server response.
  Each function is called with two arguments, the process associated
  with the response and the parsed response.
  See also `erc-server-311'.\")

      (defun erc-server-311 (proc parsed)
        \"Some non-generic function documentation.

  Handler for a 311 server response.
  PROC is the server process which returned the response.
  PARSED is the actual response as an `erc-response' struct.
  If you want to add responses don't modify this function, but rather
  add things to `erc-server-311-functions' instead.\"
        (do-stuff-with-whois proc parsed))

1119 1120 1121
    (puthash \"311\" \\='erc-server-311-functions erc-server-responses)
    (puthash \"WHOIS\" \\='erc-server-WHOIS-functions erc-server-responses)
    (puthash \"WI\" \\='erc-server-WI-functions erc-server-responses)
1122

1123 1124
    (defalias \\='erc-server-WHOIS \\='erc-server-311)
    (defvar erc-server-WHOIS-functions \\='erc-server-311
1125 1126 1127
      \"Some non-generic variable documentation.

  Hook called upon receiving a WHOIS server response.
1128

1129
  Each function is called with two arguments, the process associated
1130 1131 1132
  with the response and the parsed response.  If the function returns
  non-nil, stop processing the hook.  Otherwise, continue.

1133 1134
  See also `erc-server-311'.\")

1135 1136
    (defalias \\='erc-server-WI \\='erc-server-311)
    (defvar erc-server-WI-functions \\='erc-server-311
1137 1138 1139 1140
      \"Some non-generic variable documentation.

  Hook called upon receiving a WI server response.
  Each function is called with two arguments, the process associated
1141 1142 1143
  with the response and the parsed response.  If the function returns
  non-nil, stop processing the hook.  Otherwise, continue.

1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
  See also `erc-server-311'.\"))

\(fn (NAME &rest ALIASES) &optional EXTRA-FN-DOC EXTRA-VAR-DOC &rest FN-BODY)"
  (if (numberp name) (setq name (intern (format "%03i" name))))
  (setq aliases (mapcar (lambda (a)
                          (if (numberp a)
                              (format "%03i" a)
                            a))
                        aliases))
  (let* ((hook-name (intern (format "erc-server-%s-functions" name)))
         (fn-name (intern (format "erc-server-%s" name)))
Paul Eggert's avatar
Paul Eggert committed
1155 1156
         (hook-doc (format-message "\
%sHook called upon receiving a %%s server response.
1157
Each function is called with two arguments, the process associated
1158 1159 1160
with the response and the parsed response.  If the function returns
non-nil, stop processing the hook.  Otherwise, continue.

1161 1162 1163 1164 1165
See also `%s'."
                           (if extra-var-doc
                               (concat extra-var-doc "\n\n")
                             "")
                           fn-name))
Paul Eggert's avatar
Paul Eggert committed
1166 1167
         (fn-doc (format-message "\
%sHandler for a %s server response.
1168 1169 1170 1171 1172 1173 1174 1175 1176
PROC is the server process which returned the response.
PARSED is the actual response as an `erc-response' struct.
If you want to add responses don't modify this function, but rather
add things to `%s' instead."
                         (if extra-fn-doc
                             (concat extra-fn-doc "\n\n")
                           "")
                         name hook-name))
         (fn-alternates
1177 1178
          (cl-loop for alias in aliases
                   collect (intern (format "erc-server-%s" alias))))
1179
         (var-alternates
1180 1181
          (cl-loop for alias in aliases
                   collect (intern (format "erc-server-%s-functions" alias)))))
1182
    `(prog2
1183 1184 1185 1186 1187
         ;; Normal hook variable.  The variable may already have a
         ;; value at this point, so I default to nil, and (add-hook)
         ;; unconditionally
         (defvar ,hook-name nil ,(format hook-doc name))
         (add-to-list ',hook-name ',fn-name)
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
         ;; Handler function
         (defun ,fn-name (proc parsed)
           ,fn-doc
           ,@fn-body)

       ;; Make find-function and find-variable find them
       (put ',fn-name 'definition-name ',name)
       (put ',hook-name 'definition-name ',name)

       ;; Hashtable map of responses to hook variables
1198 1199 1200 1201
       ,@(cl-loop for response in (cons name aliases)
                  for var in (cons hook-name var-alternates)
                  collect `(puthash ,(format "%s" response) ',var
                                    erc-server-responses))
1202 1203 1204
       ;; Alternates.
       ;; Functions are defaliased, hook variables are defvared so we
       ;; can add hooks to one alias, but not another.
1205 1206 1207 1208 1209 1210
       ,@(cl-loop for fn in fn-alternates
                  for var in var-alternates
                  for a in aliases
                  nconc (list `(defalias ',fn ',fn-name)
                              `(defvar ,var ',fn-name ,(format hook-doc a))
                              `(put ',var 'definition-name ',hook-name))))))
1211 1212 1213

(define-erc-response-handler (ERROR)
  "Handle an ERROR command from the server." nil
Miles Bader's avatar
Miles Bader committed
1214
  (setq erc-server-error-occurred t)
1215 1216 1217 1218 1219 1220 1221
  (erc-display-message
   parsed 'error nil 'ERROR
   ?s (erc-response.sender parsed) ?c (erc-response.contents parsed)))

(define-erc-response-handler (INVITE)
  "Handle invitation messages."
  nil
1222
  (let ((target (car (erc-response.command-args parsed)))
1223
        (chnl (erc-response.contents parsed)))
1224 1225
    (pcase-let ((`(,nick ,login ,host)
                 (erc-parse-user (erc-response.sender parsed))))
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
      (setq erc-invitation chnl)
      (when (string= target (erc-current-nick))
        (erc-display-message
         parsed 'notice 'active
         'INVITE ?n nick ?u login ?h host ?c chnl)))))

(define-erc-response-handler (JOIN)
  "Handle join messages."
  nil
  (let ((chnl (erc-response.contents parsed))
        (buffer nil))
1237 1238
    (pcase-let ((`(,nick ,login ,host)
                 (erc-parse-user (erc-response.sender parsed))))
1239 1240 1241 1242 1243 1244 1245
      ;; strip the stupid combined JOIN facility (IRC 2.9)
      (if (string-match "^\\(.*\\)?\^g.*$" chnl)
          (setq chnl (match-string 1 chnl)))
      (save-excursion
        (let* ((str (cond
                     ;; If I have joined a channel
                     ((erc-current-nick-p nick)
Miles Bader's avatar
Miles Bader committed
1246 1247 1248
                      (setq buffer (erc-open erc-session-server erc-session-port
                                             nick erc-session-user-full-name
                                             nil nil
1249
                                             (list chnl) chnl
Miles Bader's avatar
Miles Bader committed
1250
                                             erc-server-process))
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
                      (when buffer
                        (set-buffer buffer)
                        (erc-add-default-channel chnl)
                        (erc-server-send (format "MODE %s" chnl)))
                      (erc-with-buffer (chnl proc)
                        (erc-channel-begin-receiving-names))
                      (erc-update-mode-line)
                      (run-hooks 'erc-join-hook)
                      (erc-make-notice
                       (erc-format-message 'JOIN-you ?c chnl)))
                     (t
                      (setq buffer (erc-get-buffer chnl proc))
                      (erc-make-notice
                       (erc-format-message
                        'JOIN ?n nick ?u login ?h host ?c chnl))))))
          (when buffer (set-buffer buffer))
l3thal's avatar
l3thal committed
1267
          (erc-update-channel-member chnl nick nick t nil nil nil nil nil host login)
1268 1269 1270 1271 1272 1273
          ;; on join, we want to stay in the new channel buffer
          ;;(set-buffer ob)
          (erc-display-message parsed nil buffer str))))))

(define-erc-response-handler (KICK)
  "Handle kick messages received from the server." nil
1274 1275
  (let* ((ch (nth 0 (erc-response.command-args parsed)))
         (tgt (nth 1 (erc-response.command-args parsed)))
1276 1277
         (reason (erc-trim-string (erc-response.contents parsed)))
         (buffer (erc-get-buffer ch proc)))
1278 1279
    (pcase-let ((`(,nick ,login ,host)
                 (erc-parse-user (erc-response.sender parsed))))
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
      (erc-remove-channel-member buffer tgt)
      (cond
       ((string= tgt (erc-current-nick))
        (erc-display-message
         parsed 'notice buffer
         'KICK-you ?n nick ?u login ?h host ?c ch ?r reason)
        (run-hook-with-args 'erc-kick-hook buffer)
        (erc-with-buffer
            (buffer)
          (erc-remove-channel-users))
        (erc-delete-default-channel ch buffer)
        (erc-update-mode-line buffer))
       ((string= nick (erc-current-nick))
        (erc-display-message
         parsed 'notice buffer
         'KICK-by-you ?k tgt ?c ch ?r reason))
       (t (erc-display-message
             parsed 'notice buffer
             'KICK ?k tgt ?n nick ?u login ?h host ?c ch ?r reason))))))

(define-erc-response-handler (MODE)
  "Handle server mode changes." nil
1302
  (let ((tgt (car (erc-response.command-args parsed)))
1303 1304
        (mode (mapconcat 'identity (cdr (erc-response.command-args parsed))
                         " ")))
1305 1306
    (pcase-let ((`(,nick ,login ,host)
                 (erc-parse-user (erc-response.sender parsed))))
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
      (erc-log (format "MODE: %s -> %s: %s" nick tgt mode))
      ;; dirty hack
      (let ((buf (cond ((erc-channel-p tgt)
                        (erc-get-buffer tgt proc))
                       ((string= tgt (erc-current-nick)) nil)
                       ((erc-active-buffer) (erc-active-buffer))
                       (t (erc-get-buffer tgt)))))
        (with-current-buffer (or buf
                                 (current-buffer))
          (erc-update-modes tgt mode nick host login))
          (if (or (string= login "") (string= host ""))
              (erc-display-message parsed 'notice buf
                                   'MODE-nick ?n nick
                                   ?t tgt ?m mode)
            (erc-display-message parsed 'notice buf
                                 'MODE ?n nick ?u login
                                 ?h host ?t tgt ?m mode)))
      (erc-banlist-update proc parsed))))

(define-erc-response-handler (NICK)
  "Handle nick change messages." nil
  (let ((nn (erc-response.contents parsed))
        bufs)
1330 1331
    (pcase-let ((`(,nick ,login ,host)
                 (erc-parse-user (erc-response.sender parsed))))
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
      (setq bufs (erc-buffer-list-with-nick nick proc))
      (erc-log (format "NICK: %s -> %s" nick nn))
      ;; if we had a query with this user, make sure future messages will be
      ;; sent to the correct nick. also add to bufs, since the user will want
      ;; to see the nick change in the query, and if it's a newly begun query,
      ;; erc-channel-users won't contain it
      (erc-buffer-filter
       (lambda ()
         (when (equal (erc-default-target) nick)
           (setq erc-default-recipients
                 (cons nn (cdr erc-default-recipients)))
1343
           (rename-buffer nn t)         ; bug#12002
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
           (erc-update-mode-line)
           (add-to-list 'bufs (current-buffer)))))
      (erc-update-user-nick nick nn host nil nil login)
      (cond
       ((string= nick (erc-current-nick))
        (add-to-list 'bufs (erc-server-buffer))
        (erc-set-current-nick nn)
        (erc-update-mode-line)
        (setq erc-nick-change-attempt-count 0)
        (setq erc-default-nicks (if (consp erc-nick) erc-nick (list erc-nick)))
        (erc-display-message
         parsed 'notice bufs
         'NICK-you ?n nick ?N nn)
        (run-hook-with-args 'erc-nick-changed-functions nn nick))
       (t
        (erc-handle-user-status-change 'nick (list nick login host) (list nn))
        (erc-display-message parsed 'notice bufs 'NICK ?n nick
                             ?u login ?h host ?N nn))))))

(define-erc-response-handler (PART)
  "Handle part messages." nil
1365
  (let* ((chnl (car (erc-response.command-args parsed)))
1366 1367
         (reason (erc-trim-string (erc-response.contents parsed)))
         (buffer (erc-get-buffer chnl proc)))
1368 1369
    (pcase-let ((`(,nick ,login ,host)
                 (erc-parse-user (erc-response.sender parsed))))
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
      (erc-remove-channel-member buffer nick)
      (erc-display-message parsed 'notice buffer
                           'PART ?n nick ?u login
                           ?h host ?c chnl ?r (or reason ""))
      (when (string= nick (erc-current-nick))
        (run-hook-with-args 'erc-part-hook buffer)
        (erc-with-buffer
            (buffer)
          (erc-remove-channel-users))
        (erc-delete-default-channel chnl buffer)
        (erc-update-mode-line buffer)
        (when erc-kill-buffer-on-part
          (kill-buffer buffer))))))

(define-erc-response-handler (PING)
  "Handle ping messages." nil
1386
  (let ((pinger (car (erc-response.command-args parsed))))
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
    (erc-log (format "PING: %s" pinger))
    ;; ping response to the server MUST be forced, or you can lose big
    (erc-server-send (format "PONG :%s" pinger) t)
    (when erc-verbose-server-ping
      (erc-display-message
       parsed 'error proc
       'PING ?s (erc-time-diff erc-server-last-ping-time (erc-current-time))))
    (setq erc-server-last-ping-time (erc-current-time))))

(define-erc-response-handler (PONG)
  "Handle pong messages." nil
  (let ((time (string-to-number (erc-response.contents parsed))))
    (when (> time 0)
      (setq erc-server-lag (erc-time-diff time (erc-current-time)))
      (when erc-verbose-server-ping
        (erc-display-message
         parsed 'notice proc 'PONG
1404
         ?h (car (erc-response.command-args parsed)) ?i erc-server-lag
1405 1406 1407 1408
         ?s (if (/= erc-server-lag 1) "s" "")))
      (erc-update-mode-line))))

(define-erc-response-handler (PRIVMSG NOTICE)
1409
  "Handle private messages, including messages in channels." nil
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
  (let ((sender-spec (erc-response.sender parsed))
        (cmd (erc-response.command parsed))
        (tgt (car (erc-response.command-args parsed)))
        (msg (erc-response.contents parsed)))
    (if (or (erc-ignored-user-p sender-spec)
            (erc-ignored-reply-p msg tgt proc))
        (when erc-minibuffer-ignored
          (message "Ignored %s from %s to %s" cmd sender-spec tgt))
      (let* ((sndr (erc-parse-user sender-spec))
             (nick (nth 0 sndr))
             (login (nth 1 sndr))
             (host (nth 2 sndr))
             (msgp (string= cmd "PRIVMSG"))
             (noticep (string= cmd "NOTICE"))
             ;; S.B. downcase *both* tgt and current nick
             (privp (erc-current-nick-p tgt))
             s buffer
             fnick)
        (setf (erc-response.contents parsed) msg)
        (setq buffer (erc-get-buffer (if privp nick tgt) proc))
        (when buffer
          (with-current-buffer buffer
            ;; update the chat partner info.  Add to the list if private
1433
            ;; message.  We will accumulate private identities indefinitely
1434 1435
            ;; at this point.
            (erc-update-channel-member (if privp nick tgt) nick nick
l3thal's avatar
l3thal committed
1436
                                       privp nil nil nil nil nil host login nil nil t)
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
            (let ((cdata (erc-get-channel-user nick)))
              (setq fnick (funcall erc-format-nick-function
                                   (car cdata) (cdr cdata))))))
        (cond
         ((erc-is-message-ctcp-p msg)
          (setq s (if msgp
                      (erc-process-ctcp-query proc parsed nick login host)
                    (erc-process-ctcp-reply proc parsed nick login host
                                            (match-string 1 msg)))))
         (t
          (setcar erc-server-last-peers nick)
          (setq s (erc-format-privmessage
                   (or fnick nick) msg
                   ;; If buffer is a query buffer,
                   ;; format the nick as for a channel.
                   (and (not (and buffer
                                  (erc-query-buffer-p buffer)
                                  erc-format-query-as-channel-p))
                        privp)
                   msgp))))
        (when s
          (if (and noticep privp)
              (progn
                (run-hook-with-args 'erc-echo-notice-always-hook
                                    s parsed buffer nick)
                (run-hook-with-args-until-success
                 'erc-echo-notice-hook s parsed buffer nick))
            (erc-display-message parsed nil buffer s)))
        (when (string= cmd "PRIVMSG")
          (erc-auto-query proc parsed))))))

Juanma Barranquero's avatar
Juanma Barranquero committed
1468
;; FIXME: need clean way of specifying extra hooks in
1469 1470 1471 1472
;; define-erc-response-handler.
(add-hook 'erc-server-PRIVMSG-functions 'erc-auto-query)

(define-erc-response-handler (QUIT)
1473
  "Another user has quit IRC." nil
1474 1475
  (let ((reason (erc-response.contents parsed))
        bufs)
1476 1477
    (pcase-let ((`(,nick ,login ,host)
                 (erc-parse-user (erc-response.sender parsed))))
1478 1479 1480 1481 1482 1483 1484 1485
      (setq bufs (erc-buffer-list-with-nick nick proc))
      (erc-remove-user nick)
      (setq reason (erc-wash-quit-reason reason nick login host))
      (erc-display-message parsed 'notice bufs
                           'QUIT ?n nick ?u login
                           ?h host ?r reason))))

(define-erc-response-handler (TOPIC)
1486
  "The channel topic has changed." nil
1487
  (let* ((ch (car (erc-response.command-args parsed)))
1488
         (topic (erc-trim-string (erc-response.contents parsed)))
l3thal's avatar
l3thal committed
1489
         (time (format-time-string erc-server-timestamp-format)))
1490 1491
    (pcase-let ((`(,nick ,login ,host)
                 (erc-parse-user (erc-response.sender parsed))))
l3thal's avatar
l3thal committed
1492
      (erc-update-channel-member ch nick nick nil nil nil nil nil nil host login)
1493 1494 1495 1496 1497 1498
      (erc-update-channel-topic ch (format "%s\C-o (%s, %s)" topic nick time))
      (erc-display-message parsed 'notice (erc-get-buffer ch proc)
                           'TOPIC ?n nick ?u login ?h host
                           ?c ch ?T topic))))

(define-erc-response-handler (WALLOPS)
1499
  "Display a WALLOPS message." nil
1500
  (let ((message (erc-response.contents parsed)))
1501 1502
    (pcase-let ((`(,nick ,login ,host)
                 (erc-parse-user (erc-response.sender parsed))))
1503 1504 1505 1506 1507 1508 1509
      (erc-display-message
       parsed 'notice nil
       'WALLOPS ?n nick ?m message))))

(define-erc-response-handler (001)
  "Set `erc-server-current-nick' to reflect server settings and display the welcome message."
  nil
1510
  (erc-set-current-nick (car (erc-response.command-args parsed)))
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
  (erc-update-mode-line)                ; needed here?
  (setq erc-nick-change-attempt-count 0)
  (setq erc-default-nicks (if (consp erc-nick) erc-nick (list erc-nick)))
  (erc-display-message
   parsed 'notice 'active (erc-response.contents parsed)))

(define-erc-response-handler (MOTD 002 003 371 372 374 375)
  "Display the server's message of the day." nil
  (erc-handle-login)
  (erc-display-message
   parsed 'notice (if erc-server-connected 'active proc)
   (erc-response.contents parsed)))

(define-erc-response-handler (376 422)
1525
  "End of MOTD/MOTD is missing." nil
1526 1527 1528 1529
  (erc-server-MOTD proc parsed)
  (erc-connection-established proc parsed))

(define-erc-response-handler (004)
1530
  "Display the server's identification." nil
1531 1532
  (pcase-let ((`(,server-name ,server-version)
               (cdr (erc-response.command-args parsed))))
1533 1534 1535 1536 1537