nnheader-report takes a format string as the parameter.
[gnus] / lisp / nntp.el
1 ;;; nntp.el --- nntp access for Gnus
2
3 ;; Copyright (C) 1987, 1988, 1989, 1990, 1992, 1993, 1994, 1995, 1996,
4 ;;   1997, 1998, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
5 ;;   2009, 2010  Free Software Foundation, Inc.
6
7 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
8 ;; Keywords: news
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 ;; For Emacs <22.2 and XEmacs.
30 (eval-and-compile
31   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
32
33 (require 'nnheader)
34 (require 'nnoo)
35 (require 'gnus-util)
36 (require 'gnus)
37 (require 'proto-stream)
38 (require 'gnus-group) ;; gnus-group-name-charset
39
40 (nnoo-declare nntp)
41
42 (eval-when-compile (require 'cl))
43
44 (autoload 'auth-source-user-or-password "auth-source")
45
46 (defgroup nntp nil
47   "NNTP access for Gnus."
48   :group 'gnus)
49
50 (defvoo nntp-address nil
51   "Address of the physical nntp server.")
52
53 (defvoo nntp-port-number "nntp"
54   "Port number on the physical nntp server.")
55
56 (defvoo nntp-server-opened-hook '(nntp-send-mode-reader)
57   "*Hook used for sending commands to the server at startup.
58 The default value is `nntp-send-mode-reader', which makes an innd
59 server spawn an nnrpd server.")
60
61 (defvoo nntp-authinfo-function 'nntp-send-authinfo
62   "Function used to send AUTHINFO to the server.
63 It is called with no parameters.")
64
65 (defvoo nntp-server-action-alist
66     '(("nntpd 1\\.5\\.11t"
67        (remove-hook 'nntp-server-opened-hook 'nntp-send-mode-reader))
68       ("NNRP server Netscape"
69        (setq nntp-server-list-active-group nil)))
70   "Alist of regexps to match on server types and actions to be taken.
71 For instance, if you want Gnus to beep every time you connect
72 to innd, you could say something like:
73
74 \(setq nntp-server-action-alist
75        '((\"innd\" (ding))))
76
77 You probably don't want to do that, though.")
78
79 (defvoo nntp-open-connection-function 'nntp-open-network-stream
80   "*Function used for connecting to a remote system.
81 It will be called with the buffer to output in as argument.
82
83 Currently, five such functions are provided (please refer to their
84 respective doc string for more information), three of them establishing
85 direct connections to the nntp server, and two of them using an indirect
86 host.
87
88 Direct connections:
89 - `nntp-open-network-stream' (the default),
90 - `nntp-open-ssl-stream',
91 - `nntp-open-tls-stream',
92 - `nntp-open-netcat-stream'.
93 - `nntp-open-telnet-stream'.
94
95 Indirect connections:
96 - `nntp-open-via-rlogin-and-netcat',
97 - `nntp-open-via-rlogin-and-telnet',
98 - `nntp-open-via-telnet-and-telnet'.")
99
100 (defvoo nntp-never-echoes-commands nil
101   "*Non-nil means the nntp server never echoes commands.
102 It is reported that some nntps server doesn't echo commands.  So, you
103 may want to set this to non-nil in the method for such a server setting
104 `nntp-open-connection-function' to `nntp-open-ssl-stream' for example.
105 Note that the `nntp-open-connection-functions-never-echo-commands'
106 variable overrides the nil value of this variable.")
107
108 (defvoo nntp-open-connection-functions-never-echo-commands
109     '(nntp-open-network-stream)
110   "*List of functions that never echo commands.
111 Add or set a function which you set to `nntp-open-connection-function'
112 to this list if it does not echo commands.  Note that a non-nil value
113 of the `nntp-never-echoes-commands' variable overrides this variable.")
114
115 (defvoo nntp-pre-command nil
116   "*Pre-command to use with the various nntp-open-via-* methods.
117 This is where you would put \"runsocks\" or stuff like that.")
118
119 (defvoo nntp-telnet-command "telnet"
120   "*Telnet command used to connect to the nntp server.
121 This command is used by the methods `nntp-open-telnet-stream',
122 `nntp-open-via-rlogin-and-telnet' and `nntp-open-via-telnet-and-telnet'.")
123
124 (defvoo nntp-telnet-switches '("-8")
125   "*Switches given to the telnet command `nntp-telnet-command'.")
126
127 (defvoo nntp-end-of-line "\r\n"
128   "*String to use on the end of lines when talking to the NNTP server.
129 This is \"\\r\\n\" by default, but should be \"\\n\" when using an indirect
130 connection method (nntp-open-via-*).")
131
132 (defvoo nntp-via-rlogin-command "rsh"
133   "*Rlogin command used to connect to an intermediate host.
134 This command is used by the methods `nntp-open-via-rlogin-and-telnet'
135 and `nntp-open-via-rlogin-and-netcat'.  The default is \"rsh\", but \"ssh\"
136 is a popular alternative.")
137
138 (defvoo nntp-via-rlogin-command-switches nil
139   "*Switches given to the rlogin command `nntp-via-rlogin-command'.
140 If you use \"ssh\" for `nntp-via-rlogin-command', you may set this to
141 \(\"-C\") in order to compress all data connections, otherwise set this
142 to \(\"-t\" \"-e\" \"none\") or (\"-C\" \"-t\" \"-e\" \"none\") if the telnet
143 command requires a pseudo-tty allocation on an intermediate host.")
144
145 (defvoo nntp-via-telnet-command "telnet"
146   "*Telnet command used to connect to an intermediate host.
147 This command is used by the `nntp-open-via-telnet-and-telnet' method.")
148
149 (defvoo nntp-via-telnet-switches '("-8")
150   "*Switches given to the telnet command `nntp-via-telnet-command'.")
151
152 (defvoo nntp-netcat-command "nc"
153   "*Netcat command used to connect to the nntp server.
154 This command is used by the `nntp-open-netcat-stream' and
155 `nntp-open-via-rlogin-and-netcat' methods.")
156
157 (defvoo nntp-netcat-switches nil
158   "*Switches given to the netcat command `nntp-netcat-command'.")
159
160 (defvoo nntp-via-user-name nil
161   "*User name to log in on an intermediate host with.
162 This variable is used by the various nntp-open-via-* methods.")
163
164 (defvoo nntp-via-user-password nil
165   "*Password to use to log in on an intermediate host with.
166 This variable is used by the `nntp-open-via-telnet-and-telnet' method.")
167
168 (defvoo nntp-via-address nil
169   "*Address of an intermediate host to connect to.
170 This variable is used by the various nntp-open-via-* methods.")
171
172 (defvoo nntp-via-envuser nil
173   "*Whether both telnet client and server support the ENVIRON option.
174 If non-nil, there will be no prompt for a login name.")
175
176 (defvoo nntp-via-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
177   "*Regular expression to match the shell prompt on an intermediate host.
178 This variable is used by the `nntp-open-via-telnet-and-telnet' method.")
179
180 (defvoo nntp-large-newsgroup 50
181   "*The number of articles which indicates a large newsgroup.
182 If the number of articles is greater than the value, verbose
183 messages will be shown to indicate the current status.")
184
185 (defvoo nntp-maximum-request 400
186   "*The maximum number of the requests sent to the NNTP server at one time.
187 If Emacs hangs up while retrieving headers, set the variable to a
188 lower value.")
189
190 (defvoo nntp-nov-is-evil nil
191   "*If non-nil, nntp will never attempt to use XOVER when talking to the server.")
192
193 (defvoo nntp-xover-commands '("XOVER" "XOVERVIEW")
194   "*List of strings that are used as commands to fetch NOV lines from a server.
195 The strings are tried in turn until a positive response is gotten.  If
196 none of the commands are successful, nntp will just grab headers one
197 by one.")
198
199 (defvoo nntp-nov-gap 5
200   "*Maximum allowed gap between two articles.
201 If the gap between two consecutive articles is bigger than this
202 variable, split the XOVER request into two requests.")
203
204 (defvoo nntp-xref-number-is-evil nil
205   "*If non-nil, Gnus never trusts article numbers in the Xref header.
206 Some news servers, e.g., ones running Diablo, run multiple engines
207 having the same articles but article numbers are not kept synchronized
208 between them.  If you connect to such a server, set this to a non-nil
209 value, and Gnus never uses article numbers (that appear in the Xref
210 header and vary by which engine is chosen) to refer to articles.")
211
212 (defvoo nntp-prepare-server-hook nil
213   "*Hook run before a server is opened.
214 If can be used to set up a server remotely, for instance.  Say you
215 have an account at the machine \"other.machine\".  This machine has
216 access to an NNTP server that you can't access locally.  You could
217 then use this hook to rsh to the remote machine and start a proxy NNTP
218 server there that you can connect to.  See also
219 `nntp-open-connection-function'")
220
221 (defvoo nntp-coding-system-for-read 'binary
222   "*Coding system to read from NNTP.")
223
224 (defvoo nntp-coding-system-for-write 'binary
225   "*Coding system to write to NNTP.")
226
227 ;; Marks
228 (defvoo nntp-marks-is-evil nil
229   "*If non-nil, Gnus will never generate and use marks file for nntp groups.
230 See `nnml-marks-is-evil' for more information.")
231
232 (defvoo nntp-marks-file-name ".marks")
233 (defvoo nntp-marks nil)
234 (defvar nntp-marks-modtime (gnus-make-hashtable))
235
236 (defcustom nntp-marks-directory
237   (nnheader-concat gnus-directory "marks/")
238   "*The directory where marks for nntp groups will be stored."
239   :group 'nntp
240   :type 'directory)
241
242 (defcustom nntp-authinfo-file "~/.authinfo"
243   ".netrc-like file that holds nntp authinfo passwords."
244   :group 'nntp
245   :type
246   '(choice file
247            (repeat :tag "Entries"
248                    :menu-tag "Inline"
249                    (list :format "%v"
250                          :value ("" ("login" . "") ("password" . ""))
251                          (string :tag "Host")
252                          (checklist :inline t
253                                     (cons :format "%v"
254                                           (const :format "" "login")
255                                           (string :format "Login: %v"))
256                                     (cons :format "%v"
257                                           (const :format "" "password")
258                                           (string :format "Password: %v")))))))
259
260 \f
261
262 (defvoo nntp-connection-timeout nil
263   "*Number of seconds to wait before an nntp connection times out.
264 If this variable is nil, which is the default, no timers are set.
265 NOTE: This variable is never seen to work in Emacs 20 and XEmacs 21.")
266
267 (defvoo nntp-prepare-post-hook nil
268   "*Hook run just before posting an article.  It is supposed to be used
269 to insert Cancel-Lock headers.")
270
271 (defvoo nntp-server-list-active-group 'try
272   "If nil, then always use GROUP instead of LIST ACTIVE.
273 This is usually slower, but on misconfigured servers that don't
274 update their active files often, this can help.")
275
276 ;;; Internal variables.
277
278 (defvar nntp-record-commands nil
279   "*If non-nil, nntp will record all commands in the \"*nntp-log*\" buffer.")
280
281 (defvar nntp-have-messaged nil)
282
283 (defvar nntp-process-wait-for nil)
284 (defvar nntp-process-to-buffer nil)
285 (defvar nntp-process-callback nil)
286 (defvar nntp-process-decode nil)
287 (defvar nntp-process-start-point nil)
288 (defvar nntp-inside-change-function nil)
289 (defvoo nntp-last-command-time nil)
290 (defvoo nntp-last-command nil)
291 (defvoo nntp-authinfo-password nil)
292 (defvoo nntp-authinfo-user nil)
293 (defvoo nntp-authinfo-force nil)
294
295 (defvar nntp-connection-list nil)
296
297 (defvoo nntp-server-type nil)
298 (defvoo nntp-connection-alist nil)
299 (defvoo nntp-status-string "")
300 (defconst nntp-version "nntp 5.0")
301 (defvoo nntp-inhibit-erase nil)
302 (defvoo nntp-inhibit-output nil)
303
304 (defvoo nntp-server-xover 'try)
305
306 (defvar nntp-async-timer nil)
307 (defvar nntp-async-process-list nil)
308
309 (defvar nntp-authinfo-rejected nil
310 "A custom error condition used to report 'Authentication Rejected' errors.
311 Condition handlers that match just this condition ensure that the nntp
312 backend doesn't catch this error.")
313 (put 'nntp-authinfo-rejected 'error-conditions '(error nntp-authinfo-rejected))
314 (put 'nntp-authinfo-rejected 'error-message "Authorization Rejected")
315
316 \f
317
318 ;;; Internal functions.
319
320 (defsubst nntp-send-string (process string)
321   "Send STRING to PROCESS."
322   ;; We need to store the time to provide timeouts, and
323   ;; to store the command so the we can replay the command
324   ;; if the server gives us an AUTHINFO challenge.
325   (setq nntp-last-command-time (current-time)
326         nntp-last-command string)
327   (when nntp-record-commands
328     (nntp-record-command string))
329   (process-send-string process (concat string nntp-end-of-line))
330   (or (memq (process-status process) '(open run))
331       (nntp-report "Server closed connection")))
332
333 (defun nntp-record-command (string)
334   "Record the command STRING."
335   (with-current-buffer (get-buffer-create "*nntp-log*")
336     (goto-char (point-max))
337     (let ((time (current-time)))
338       (insert (format-time-string "%Y%m%dT%H%M%S" time)
339               "." (format "%03d" (/ (nth 2 time) 1000))
340               " " nntp-address " " string "\n"))))
341
342 (defun nntp-report (&rest args)
343   "Report an error from the nntp backend.  The first string in ARGS
344 can be a format string.  For some commands, the failed command may be
345 retried once before actually displaying the error report."
346
347   (when nntp-record-commands
348     (nntp-record-command "*** CALLED nntp-report ***"))
349
350   (nnheader-report 'nntp args)
351
352   (apply 'error args))
353
354 (defun nntp-report-1 (&rest args)
355   "Throws out to nntp-with-open-group-error so that the connection may
356 be restored and the command retried."
357
358   (when nntp-record-commands
359     (nntp-record-command "*** CONNECTION LOST ***"))
360
361   (throw 'nntp-with-open-group-error t))
362
363 (defmacro nntp-insert-buffer-substring (buffer &optional start end)
364   "Copy string from unibyte buffer to multibyte current buffer."
365   (if (featurep 'xemacs)
366       `(insert-buffer-substring ,buffer ,start ,end)
367     `(if enable-multibyte-characters
368          (insert (with-current-buffer ,buffer
369                    (mm-string-to-multibyte
370                     ,(if (or start end)
371                          `(buffer-substring (or ,start (point-min))
372                                             (or ,end (point-max)))
373                        '(buffer-string)))))
374        (insert-buffer-substring ,buffer ,start ,end))))
375
376 (defmacro nntp-copy-to-buffer (buffer start end)
377   "Copy string from unibyte current buffer to multibyte buffer."
378   (if (featurep 'xemacs)
379       `(copy-to-buffer ,buffer ,start ,end)
380     `(let ((string (buffer-substring ,start ,end)))
381        (with-current-buffer ,buffer
382          (erase-buffer)
383          (insert (if enable-multibyte-characters
384                      (mm-string-to-multibyte string)
385                    string))
386          (goto-char (point-min))
387          nil))))
388
389 (defsubst nntp-wait-for (process wait-for buffer &optional decode discard)
390   "Wait for WAIT-FOR to arrive from PROCESS."
391
392   (with-current-buffer (process-buffer process)
393     (goto-char (point-min))
394
395     (while (and (or (not (memq (char-after (point)) '(?2 ?3 ?4 ?5)))
396                     (looking-at "48[02]"))
397                 (memq (process-status process) '(open run)))
398       (cond ((looking-at "480")
399              (nntp-handle-authinfo process))
400             ((looking-at "482")
401              (nnheader-report 'nntp "%s"
402                               (get 'nntp-authinfo-rejected 'error-message))
403              (signal 'nntp-authinfo-rejected nil))
404             ((looking-at "^.*\n")
405              (delete-region (point) (progn (forward-line 1) (point)))))
406       (nntp-accept-process-output process)
407       (goto-char (point-min)))
408     (prog1
409         (cond
410          ((looking-at "[45]")
411           (progn
412             (nntp-snarf-error-message)
413             nil))
414          ((not (memq (process-status process) '(open run)))
415           (nntp-report "Server closed connection"))
416          (t
417           (goto-char (point-max))
418           (let ((limit (point-min))
419                 response)
420             (while (not (re-search-backward wait-for limit t))
421               (nntp-accept-process-output process)
422               ;; We assume that whatever we wait for is less than 1000
423               ;; characters long.
424               (setq limit (max (- (point-max) 1000) (point-min)))
425               (goto-char (point-max)))
426             (setq response (match-string 0))
427             (with-current-buffer nntp-server-buffer
428               (setq nntp-process-response response)))
429           (nntp-decode-text (not decode))
430           (unless discard
431             (with-current-buffer buffer
432               (goto-char (point-max))
433               (nntp-insert-buffer-substring (process-buffer process))
434               ;; Nix out "nntp reading...." message.
435               (when nntp-have-messaged
436                 (setq nntp-have-messaged nil)
437                 (nnheader-message 5 ""))))
438           t))
439       (unless discard
440         (erase-buffer)))))
441
442 (defun nntp-kill-buffer (buffer)
443   (when (buffer-name buffer)
444     (kill-buffer buffer)
445     (nnheader-init-server-buffer)))
446
447 (defun nntp-erase-buffer (buffer)
448   "Erase contents of BUFFER."
449   (with-current-buffer buffer
450     (erase-buffer)))
451
452 (defsubst nntp-find-connection (buffer)
453   "Find the connection delivering to BUFFER."
454   (let ((alist nntp-connection-alist)
455         (buffer (if (stringp buffer) (get-buffer buffer) buffer))
456         process entry)
457     (while (and alist (setq entry (pop alist)))
458       (when (eq buffer (cadr entry))
459         (setq process (car entry)
460               alist nil)))
461     (when process
462       (if (memq (process-status process) '(open run))
463           process
464         (nntp-kill-buffer (process-buffer process))
465         (setq nntp-connection-alist (delq entry nntp-connection-alist))
466         nil))))
467
468 (defsubst nntp-find-connection-entry (buffer)
469   "Return the entry for the connection to BUFFER."
470   (assq (nntp-find-connection buffer) nntp-connection-alist))
471
472 (defun nntp-find-connection-buffer (buffer)
473   "Return the process connection buffer tied to BUFFER."
474   (let ((process (nntp-find-connection buffer)))
475     (when process
476       (process-buffer process))))
477
478 (defsubst nntp-retrieve-data (command address port buffer
479                                       &optional wait-for callback decode)
480   "Use COMMAND to retrieve data into BUFFER from PORT on ADDRESS."
481   (let ((process (or (nntp-find-connection buffer)
482                      (nntp-open-connection buffer))))
483     (if process
484         (progn
485           (unless (or nntp-inhibit-erase nnheader-callback-function)
486             (nntp-erase-buffer (process-buffer process)))
487           (condition-case err
488               (progn
489                 (when command
490                   (nntp-send-string process command))
491                 (cond
492                  ((eq callback 'ignore)
493                   t)
494                  ((and callback wait-for)
495                   (nntp-async-wait process wait-for buffer decode callback)
496                   t)
497                  (wait-for
498                   (nntp-wait-for process wait-for buffer decode))
499                  (t t)))
500             (nntp-authinfo-rejected
501              (signal 'nntp-authinfo-rejected (cdr err)))
502             (error
503              (nnheader-report 'nntp "Couldn't open connection to %s: %s"
504                               address err))
505             (quit
506              (message "Quit retrieving data from nntp")
507              (signal 'quit nil)
508              nil)))
509       (nnheader-report 'nntp "Couldn't open connection to %s" address))))
510
511 (defsubst nntp-send-command (wait-for &rest strings)
512   "Send STRINGS to server and wait until WAIT-FOR returns."
513   (when (and (not nnheader-callback-function)
514              (not nntp-inhibit-output))
515     (nntp-erase-buffer nntp-server-buffer))
516   (let* ((command (mapconcat 'identity strings " "))
517          (process (nntp-find-connection nntp-server-buffer))
518          (buffer (and process (process-buffer process)))
519          (pos (and buffer (with-current-buffer buffer (point)))))
520     (if process
521         (prog1
522             (nntp-retrieve-data command
523                                 nntp-address nntp-port-number
524                                 nntp-server-buffer
525                                 wait-for nnheader-callback-function)
526           ;; If nothing to wait for, still remove possibly echo'ed commands.
527           ;; We don't have echoes if `nntp-never-echoes-commands' is non-nil
528           ;; or the value of `nntp-open-connection-function' is in
529           ;; `nntp-open-connection-functions-never-echo-commands', so we
530           ;; skip this in that cases.
531           (unless (or wait-for
532                       nntp-never-echoes-commands
533                       (memq
534                        nntp-open-connection-function
535                        nntp-open-connection-functions-never-echo-commands))
536             (nntp-accept-response)
537             (with-current-buffer buffer
538               (goto-char pos)
539               (if (looking-at (regexp-quote command))
540                   (delete-region pos (progn (forward-line 1)
541                                             (point-at-bol)))))))
542       (nnheader-report 'nntp "Couldn't open connection to %s."
543                        nntp-address))))
544
545 (defun nntp-send-command-nodelete (wait-for &rest strings)
546   "Send STRINGS to server and wait until WAIT-FOR returns."
547   (let* ((command (mapconcat 'identity strings " "))
548          (process (nntp-find-connection nntp-server-buffer))
549          (buffer (and process (process-buffer process)))
550          (pos (and buffer (with-current-buffer buffer (point)))))
551     (if process
552         (prog1
553             (nntp-retrieve-data command
554                                 nntp-address nntp-port-number
555                                 nntp-server-buffer
556                                 wait-for nnheader-callback-function)
557           ;; If nothing to wait for, still remove possibly echo'ed commands
558           (unless wait-for
559             (nntp-accept-response)
560             (with-current-buffer buffer
561               (goto-char pos)
562               (if (looking-at (regexp-quote command))
563                   (delete-region pos (progn (forward-line 1)
564                                             (point-at-bol)))))))
565       (nnheader-report 'nntp "Couldn't open connection to %s."
566                        nntp-address))))
567
568 (defun nntp-send-command-and-decode (wait-for &rest strings)
569   "Send STRINGS to server and wait until WAIT-FOR returns."
570   (when (and (not nnheader-callback-function)
571              (not nntp-inhibit-output))
572     (nntp-erase-buffer nntp-server-buffer))
573   (let* ((command (mapconcat 'identity strings " "))
574          (process (nntp-find-connection nntp-server-buffer))
575          (buffer (and process (process-buffer process)))
576          (pos (and buffer (with-current-buffer buffer (point)))))
577     (if process
578         (prog1
579             (nntp-retrieve-data command
580                                 nntp-address nntp-port-number
581                                 nntp-server-buffer
582                                 wait-for nnheader-callback-function t)
583           ;; If nothing to wait for, still remove possibly echo'ed commands
584           (unless wait-for
585             (nntp-accept-response)
586             (with-current-buffer buffer
587               (goto-char pos)
588               (if (looking-at (regexp-quote command))
589                   (delete-region pos (progn (forward-line 1) (point-at-bol))))
590               )))
591       (nnheader-report 'nntp "Couldn't open connection to %s."
592                        nntp-address))))
593
594
595 (defun nntp-send-buffer (wait-for)
596   "Send the current buffer to server and wait until WAIT-FOR returns."
597   (when (and (not nnheader-callback-function)
598              (not nntp-inhibit-output))
599     (nntp-erase-buffer
600      (nntp-find-connection-buffer nntp-server-buffer)))
601   (nntp-encode-text)
602   ;; Make sure we did not forget to encode some of the content.
603   (assert (save-excursion (goto-char (point-min))
604                           (not (re-search-forward "[^\000-\377]" nil t))))
605   (mm-disable-multibyte)
606   (process-send-region (nntp-find-connection nntp-server-buffer)
607                        (point-min) (point-max))
608   (nntp-retrieve-data
609    nil nntp-address nntp-port-number nntp-server-buffer
610    wait-for nnheader-callback-function))
611
612 \f
613
614 ;;; Interface functions.
615
616 (nnoo-define-basics nntp)
617
618 (defsubst nntp-next-result-arrived-p ()
619   (cond
620    ;; A result that starts with a 2xx code is terminated by
621    ;; a line with only a "." on it.
622    ((eq (char-after) ?2)
623     (if (re-search-forward "\n\\.\r?\n" nil t)
624         (progn
625           ;; Some broken news servers add another dot at the end.
626           ;; Protect against inflooping there.
627           (while (looking-at "^\\.\r?\n")
628             (forward-line 1))
629           t)
630       nil))
631    ;; A result that starts with a 3xx or 4xx code is terminated
632    ;; by a newline.
633    ((looking-at "[34]")
634     (if (search-forward "\n" nil t)
635         t
636       nil))
637    ;; No result here.
638    (t
639     nil)))
640
641 (eval-when-compile
642   (defvar nntp-with-open-group-internal nil)
643   (defvar nntp-report-n nil))
644
645 (defun nntp-with-open-group-function (-group -server -connectionless -bodyfun)
646   "Protect against servers that don't like clients that keep idle connections opens.
647 The problem being that these servers may either close a connection or
648 simply ignore any further requests on a connection.  Closed
649 connections are not detected until `accept-process-output' has updated
650 the `process-status'.  Dropped connections are not detected until the
651 connection timeouts (which may be several minutes) or
652 `nntp-connection-timeout' has expired.  When these occur
653 `nntp-with-open-group', opens a new connection then re-issues the NNTP
654 command whose response triggered the error."
655   (letf ((nntp-report-n (symbol-function 'nntp-report))
656          ((symbol-function 'nntp-report) (symbol-function 'nntp-report-1))
657          (nntp-with-open-group-internal nil))
658     (while (catch 'nntp-with-open-group-error
659              ;; Open the connection to the server
660              ;; NOTE: Existing connections are NOT tested.
661              (nntp-possibly-change-group -group -server -connectionless)
662
663              (let ((-timer
664                     (and nntp-connection-timeout
665                          (run-at-time
666                           nntp-connection-timeout nil
667                           (lambda ()
668                             (let* ((-process (nntp-find-connection
669                                              nntp-server-buffer))
670                                    (-buffer  (and -process
671                                                   (process-buffer -process))))
672                               ;; When I an able to identify the
673                               ;; connection to the server AND I've
674                               ;; received NO reponse for
675                               ;; nntp-connection-timeout seconds.
676                               (when (and -buffer (eq 0 (buffer-size -buffer)))
677                                 ;; Close the connection.  Take no
678                                 ;; other action as the accept input
679                                 ;; code will handle the closed
680                                 ;; connection.
681                                 (nntp-kill-buffer -buffer))))))))
682                (unwind-protect
683                    (setq nntp-with-open-group-internal
684                          (condition-case nil
685                              (funcall -bodyfun)
686                            (quit
687                             (unless debug-on-quit
688                               (nntp-close-server))
689                             (signal 'quit nil))))
690                  (when -timer
691                    (nnheader-cancel-timer -timer)))
692                nil))
693       (setf (symbol-function 'nntp-report) nntp-report-n))
694     nntp-with-open-group-internal))
695
696 (defmacro nntp-with-open-group (group server &optional connectionless &rest forms)
697   "Protect against servers that don't like clients that keep idle connections opens.
698 The problem being that these servers may either close a connection or
699 simply ignore any further requests on a connection.  Closed
700 connections are not detected until `accept-process-output' has updated
701 the `process-status'.  Dropped connections are not detected until the
702 connection timeouts (which may be several minutes) or
703 `nntp-connection-timeout' has expired.  When these occur
704 `nntp-with-open-group', opens a new connection then re-issues the NNTP
705 command whose response triggered the error."
706   (declare (indent 2) (debug (form form [&optional symbolp] def-body)))
707   (when (and (listp connectionless)
708              (not (eq connectionless nil)))
709     (setq forms (cons connectionless forms)
710           connectionless nil))
711   `(nntp-with-open-group-function ,group ,server ,connectionless (lambda () ,@forms)))
712
713 (deffoo nntp-retrieve-headers (articles &optional group server fetch-old)
714   "Retrieve the headers of ARTICLES."
715   (nntp-with-open-group
716    group server
717    (with-current-buffer (nntp-find-connection-buffer nntp-server-buffer)
718      (erase-buffer)
719      (if (and (not gnus-nov-is-evil)
720               (not nntp-nov-is-evil)
721               (nntp-retrieve-headers-with-xover articles fetch-old))
722          ;; We successfully retrieved the headers via XOVER.
723          'nov
724        ;; XOVER didn't work, so we do it the hard, slow and inefficient
725        ;; way.
726        (let ((number (length articles))
727              (articles articles)
728              (count 0)
729              (received 0)
730              (last-point (point-min))
731              (buf (nntp-find-connection-buffer nntp-server-buffer))
732              (nntp-inhibit-erase t)
733              article)
734          ;; Send HEAD commands.
735          (while (setq article (pop articles))
736            (nntp-send-command
737             nil
738             "HEAD" (if (numberp article)
739                        (int-to-string article)
740                      ;; `articles' is either a list of article numbers
741                      ;; or a list of article IDs.
742                      article))
743            (incf count)
744            ;; Every 400 requests we have to read the stream in
745            ;; order to avoid deadlocks.
746            (when (or (null articles)    ;All requests have been sent.
747                      (zerop (% count nntp-maximum-request)))
748              (nntp-accept-response)
749              (while (progn
750                       (set-buffer buf)
751                       (goto-char last-point)
752                       ;; Count replies.
753                       (while (nntp-next-result-arrived-p)
754                         (setq last-point (point))
755                         (incf received))
756                       (< received count))
757                ;; If number of headers is greater than 100, give
758                ;;  informative messages.
759                (and (numberp nntp-large-newsgroup)
760                     (> number nntp-large-newsgroup)
761                     (zerop (% received 20))
762                     (nnheader-message 6 "NNTP: Receiving headers... %d%%"
763                                       (/ (* received 100) number)))
764                (nntp-accept-response))))
765          (and (numberp nntp-large-newsgroup)
766               (> number nntp-large-newsgroup)
767               (nnheader-message 6 "NNTP: Receiving headers...done"))
768
769          ;; Now all of replies are received.  Fold continuation lines.
770          (nnheader-fold-continuation-lines)
771          ;; Remove all "\r"'s.
772          (nnheader-strip-cr)
773          (nntp-copy-to-buffer nntp-server-buffer (point-min) (point-max))
774          'headers)))))
775
776 (deffoo nntp-retrieve-groups (groups &optional server)
777   "Retrieve group info on GROUPS."
778   (nntp-with-open-group
779    nil server
780    (when (nntp-find-connection-buffer nntp-server-buffer)
781      (catch 'done
782        (save-excursion
783          ;; Erase nntp-server-buffer before nntp-inhibit-erase.
784          (nntp-erase-buffer nntp-server-buffer)
785          (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
786          ;; The first time this is run, this variable is `try'.  So we
787          ;; try.
788          (when (eq nntp-server-list-active-group 'try)
789            (nntp-try-list-active (car groups)))
790          (erase-buffer)
791          (let ((count 0)
792                (groups groups)
793                (received 0)
794                (last-point (point-min))
795                (nntp-inhibit-erase t)
796                (buf (nntp-find-connection-buffer nntp-server-buffer))
797                (command (if nntp-server-list-active-group
798                             "LIST ACTIVE" "GROUP")))
799            (while groups
800              ;; Timeout may have killed the buffer.
801              (unless (gnus-buffer-live-p buf)
802                (nnheader-report 'nntp "Connection to %s is closed." server)
803                (throw 'done nil))
804              ;; Send the command to the server.
805              (nntp-send-command nil command (pop groups))
806              (incf count)
807              ;; Every 400 requests we have to read the stream in
808              ;; order to avoid deadlocks.
809              (when (or (null groups)    ;All requests have been sent.
810                        (zerop (% count nntp-maximum-request)))
811                (nntp-accept-response)
812                (while (and (gnus-buffer-live-p buf)
813                            (progn
814                              ;; Search `blue moon' in this file for the
815                              ;; reason why set-buffer here.
816                              (set-buffer buf)
817                              (goto-char last-point)
818                              ;; Count replies.
819                              (while (re-search-forward "^[0-9]" nil t)
820                                (incf received))
821                              (setq last-point (point))
822                              (< received count)))
823                  (nntp-accept-response))))
824
825            ;; Wait for the reply from the final command.
826            (unless (gnus-buffer-live-p buf)
827              (nnheader-report 'nntp "Connection to %s is closed." server)
828              (throw 'done nil))
829            (set-buffer buf)
830            (goto-char (point-max))
831            (re-search-backward "^[0-9]" nil t)
832            (when (looking-at "^[23]")
833              (while (and (gnus-buffer-live-p buf)
834                          (progn
835                            (set-buffer buf)
836                            (goto-char (point-max))
837                            (if (not nntp-server-list-active-group)
838                                (not (re-search-backward "\r?\n"
839                                                         (- (point) 3) t))
840                              (not (re-search-backward "^\\.\r?\n"
841                                                       (- (point) 4) t)))))
842                (nntp-accept-response)))
843
844            ;; Now all replies are received.  We remove CRs.
845            (unless (gnus-buffer-live-p buf)
846              (nnheader-report 'nntp "Connection to %s is closed." server)
847              (throw 'done nil))
848            (set-buffer buf)
849            (goto-char (point-min))
850            (while (search-forward "\r" nil t)
851              (replace-match "" t t))
852
853            (if (not nntp-server-list-active-group)
854                (progn
855                  (nntp-copy-to-buffer nntp-server-buffer
856                                       (point-min) (point-max))
857                  'group)
858              ;; We have read active entries, so we just delete the
859              ;; superfluous gunk.
860              (goto-char (point-min))
861              (while (re-search-forward "^[.2-5]" nil t)
862                (delete-region (match-beginning 0)
863                               (progn (forward-line 1) (point))))
864              (nntp-copy-to-buffer nntp-server-buffer (point-min) (point-max))
865              'active)))))))
866
867 (deffoo nntp-retrieve-articles (articles &optional group server)
868   (nntp-with-open-group
869     group server
870    (save-excursion
871      (let ((number (length articles))
872            (articles articles)
873            (count 0)
874            (received 0)
875            (last-point (point-min))
876            (buf (nntp-find-connection-buffer nntp-server-buffer))
877            (nntp-inhibit-erase t)
878            (map (apply 'vector articles))
879            (point 1)
880            article)
881        (set-buffer buf)
882        (erase-buffer)
883        ;; Send ARTICLE command.
884        (while (setq article (pop articles))
885          (nntp-send-command
886           nil
887           "ARTICLE" (if (numberp article)
888                         (int-to-string article)
889                       ;; `articles' is either a list of article numbers
890                       ;; or a list of article IDs.
891                       article))
892          (incf count)
893          ;; Every 400 requests we have to read the stream in
894          ;; order to avoid deadlocks.
895          (when (or (null articles)      ;All requests have been sent.
896                    (zerop (% count nntp-maximum-request)))
897            (nntp-accept-response)
898            (while (progn
899                     (set-buffer buf)
900                     (goto-char last-point)
901                     ;; Count replies.
902                     (while (nntp-next-result-arrived-p)
903                       (aset map received (cons (aref map received) (point)))
904                       (setq last-point (point))
905                       (incf received))
906                     (< received count))
907              ;; If number of headers is greater than 100, give
908              ;;  informative messages.
909              (and (numberp nntp-large-newsgroup)
910                   (> number nntp-large-newsgroup)
911                   (zerop (% received 20))
912                   (nnheader-message 6 "NNTP: Receiving articles... %d%%"
913                                     (/ (* received 100) number)))
914              (nntp-accept-response))))
915        (and (numberp nntp-large-newsgroup)
916             (> number nntp-large-newsgroup)
917             (nnheader-message 6 "NNTP: Receiving articles...done"))
918
919        ;; Now we have all the responses.  We go through the results,
920        ;; wash it and copy it over to the server buffer.
921        (set-buffer nntp-server-buffer)
922        (erase-buffer)
923        (setq last-point (point-min))
924        (mapcar
925         (lambda (entry)
926           (narrow-to-region
927            (setq point (goto-char (point-max)))
928            (progn
929              (nntp-insert-buffer-substring buf last-point (cdr entry))
930              (point-max)))
931           (setq last-point (cdr entry))
932           (nntp-decode-text)
933           (widen)
934           (cons (car entry) point))
935         map)))))
936
937 (defun nntp-try-list-active (group)
938   (nntp-list-active-group group)
939   (with-current-buffer nntp-server-buffer
940     (goto-char (point-min))
941     (cond ((or (eobp)
942                (looking-at "5[0-9]+"))
943            (setq nntp-server-list-active-group nil))
944           (t
945            (setq nntp-server-list-active-group t)))))
946
947 (deffoo nntp-list-active-group (group &optional server)
948   "Return the active info on GROUP (which can be a regexp)."
949   (nntp-with-open-group
950    nil server
951    (nntp-send-command "^\\.*\r?\n" "LIST ACTIVE" group)))
952
953 (deffoo nntp-request-group-articles (group &optional server)
954   "Return the list of existing articles in GROUP."
955   (nntp-with-open-group
956    nil server
957    (nntp-send-command "^\\.*\r?\n" "LISTGROUP" group)))
958
959 (deffoo nntp-request-article (article &optional group server buffer command)
960   (nntp-with-open-group
961     group server
962     (when (nntp-send-command-and-decode
963            "\r?\n\\.\r?\n" "ARTICLE"
964            (if (numberp article) (int-to-string article) article))
965       (if (and buffer
966                (not (equal buffer nntp-server-buffer)))
967           (with-current-buffer nntp-server-buffer
968             (copy-to-buffer buffer (point-min) (point-max))
969             (nntp-find-group-and-number group))
970         (nntp-find-group-and-number group)))))
971
972 (deffoo nntp-request-head (article &optional group server)
973   (nntp-with-open-group
974    group server
975    (when (nntp-send-command
976           "\r?\n\\.\r?\n" "HEAD"
977           (if (numberp article) (int-to-string article) article))
978      (prog1
979          (nntp-find-group-and-number group)
980        (nntp-decode-text)))))
981
982 (deffoo nntp-request-body (article &optional group server)
983   (nntp-with-open-group
984    group server
985    (nntp-send-command-and-decode
986     "\r?\n\\.\r?\n" "BODY"
987     (if (numberp article) (int-to-string article) article))))
988
989 (deffoo nntp-request-group (group &optional server dont-check info)
990   (nntp-with-open-group
991     nil server
992     (when (nntp-send-command "^[245].*\n" "GROUP" group)
993       (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
994         (setcar (cddr entry) group)))))
995
996 (deffoo nntp-close-group (group &optional server)
997   t)
998
999 (deffoo nntp-server-opened (&optional server)
1000   "Say whether a connection to SERVER has been opened."
1001   (and (nnoo-current-server-p 'nntp server)
1002        nntp-server-buffer
1003        (gnus-buffer-live-p nntp-server-buffer)
1004        (nntp-find-connection nntp-server-buffer)))
1005
1006 (deffoo nntp-open-server (server &optional defs connectionless)
1007   (nnheader-init-server-buffer)
1008   (if (nntp-server-opened server)
1009       t
1010     (when (or (stringp (car defs))
1011               (numberp (car defs)))
1012       (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
1013     (unless (assq 'nntp-address defs)
1014       (setq defs (append defs (list (list 'nntp-address server)))))
1015     (nnoo-change-server 'nntp server defs)
1016     (if connectionless
1017         t
1018       (or (nntp-find-connection nntp-server-buffer)
1019           (nntp-open-connection nntp-server-buffer)))))
1020
1021 (deffoo nntp-close-server (&optional server)
1022   (nntp-possibly-change-group nil server t)
1023   (let ((process (nntp-find-connection nntp-server-buffer)))
1024     (while process
1025       (when (memq (process-status process) '(open run))
1026         (ignore-errors
1027           (nntp-send-string process "QUIT")
1028           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
1029             ;; Ok, this is evil, but when using telnet and stuff
1030             ;; as the connection method, it's important that the
1031             ;; QUIT command actually is sent out before we kill
1032             ;; the process.
1033             (sleep-for 1))))
1034       (nntp-kill-buffer (process-buffer process))
1035       (setq process (car (pop nntp-connection-alist))))
1036     (nnoo-close-server 'nntp)))
1037
1038 (deffoo nntp-request-close ()
1039   (let (process)
1040     (while (setq process (pop nntp-connection-list))
1041       (when (memq (process-status process) '(open run))
1042         (ignore-errors
1043           (nntp-send-string process "QUIT")
1044           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
1045             ;; Ok, this is evil, but when using telnet and stuff
1046             ;; as the connection method, it's important that the
1047             ;; QUIT command actually is sent out before we kill
1048             ;; the process.
1049             (sleep-for 1))))
1050       (nntp-kill-buffer (process-buffer process)))))
1051
1052 (deffoo nntp-request-list (&optional server)
1053   (nntp-with-open-group
1054    nil server
1055    (nntp-send-command-and-decode "\r?\n\\.\r?\n" "LIST")))
1056
1057 (deffoo nntp-request-list-newsgroups (&optional server)
1058   (nntp-with-open-group
1059    nil server
1060    (nntp-send-command "\r?\n\\.\r?\n" "LIST NEWSGROUPS")))
1061
1062 (deffoo nntp-request-newgroups (date &optional server)
1063   (nntp-with-open-group
1064    nil server
1065    (with-current-buffer nntp-server-buffer
1066      (let* ((time (date-to-time date))
1067             (ls (- (cadr time) (nth 8 (decode-time time)))))
1068        (cond ((< ls 0)
1069               (setcar time (1- (car time)))
1070               (setcar (cdr time) (+ ls 65536)))
1071              ((>= ls 65536)
1072               (setcar time (1+ (car time)))
1073               (setcar (cdr time) (- ls 65536)))
1074              (t
1075               (setcar (cdr time) ls)))
1076        (prog1
1077            (nntp-send-command
1078             "^\\.\r?\n" "NEWGROUPS"
1079             (format-time-string "%y%m%d %H%M%S" time)
1080             "GMT")
1081          (nntp-decode-text))))))
1082
1083 (deffoo nntp-request-post (&optional server)
1084   (nntp-with-open-group
1085    nil server
1086    (when (nntp-send-command "^[23].*\r?\n" "POST")
1087      (let ((response (with-current-buffer nntp-server-buffer
1088                        nntp-process-response))
1089            server-id)
1090        (when (and response
1091                   (string-match "^[23].*\\(<[^\t\n @<>]+@[^\t\n @<>]+>\\)"
1092                                 response))
1093          (setq server-id (match-string 1 response))
1094          (narrow-to-region (goto-char (point-min))
1095                            (if (search-forward "\n\n" nil t)
1096                                (1- (point))
1097                              (point-max)))
1098          (unless (mail-fetch-field "Message-ID")
1099            (goto-char (point-min))
1100            (insert "Message-ID: " server-id "\n"))
1101          (widen))
1102        (run-hooks 'nntp-prepare-post-hook)
1103        (nntp-send-buffer "^[23].*\n")))))
1104
1105 (deffoo nntp-request-type (group article)
1106   'news)
1107
1108 (deffoo nntp-asynchronous-p ()
1109   t)
1110
1111 (deffoo nntp-request-set-mark (group actions &optional server)
1112   (when (and (not nntp-marks-is-evil)
1113              nntp-marks-file-name)
1114     (nntp-possibly-create-directory group server)
1115     (nntp-open-marks group server)
1116     (setq nntp-marks (nnheader-update-marks-actions nntp-marks actions))
1117     (nntp-save-marks group server))
1118   nil)
1119
1120 (deffoo nntp-request-marks (group info &optional server)
1121   (when (and (not nntp-marks-is-evil)
1122              nntp-marks-file-name)
1123     (nntp-possibly-create-directory group server)
1124     (when (nntp-marks-changed-p group server)
1125       (nnheader-message 8 "Updating marks for %s..." group)
1126       (nntp-open-marks group server)
1127       ;; Update info using `nntp-marks'.
1128       (mapc (lambda (pred)
1129               (unless (memq (cdr pred) gnus-article-unpropagated-mark-lists)
1130                 (gnus-info-set-marks
1131                  info
1132                  (gnus-update-alist-soft
1133                   (cdr pred)
1134                   (cdr (assq (cdr pred) nntp-marks))
1135                   (gnus-info-marks info))
1136                  t)))
1137             gnus-article-mark-lists)
1138       (let ((seen (cdr (assq 'read nntp-marks))))
1139         (gnus-info-set-read info
1140                             (if (and (integerp (car seen))
1141                                      (null (cdr seen)))
1142                                 (list (cons (car seen) (car seen)))
1143                               seen)))
1144       (nnheader-message 8 "Updating marks for %s...done" group)))
1145   nil)
1146
1147
1148
1149 ;;; Hooky functions.
1150
1151 (defun nntp-send-mode-reader ()
1152   "Send the MODE READER command to the nntp server.
1153 This function is supposed to be called from `nntp-server-opened-hook'.
1154 It will make innd servers spawn an nnrpd process to allow actual article
1155 reading."
1156   (nntp-send-command "^.*\n" "MODE READER"))
1157
1158 (declare-function netrc-parse "netrc" (&optional file))
1159 (declare-function netrc-machine "netrc"
1160                   (list machine &optional port defaultport))
1161 (declare-function netrc-get "netrc" (alist type))
1162
1163 (defun nntp-send-authinfo (&optional send-if-force)
1164   "Send the AUTHINFO to the nntp server.
1165 It will look in the \"~/.authinfo\" file for matching entries.  If
1166 nothing suitable is found there, it will prompt for a user name
1167 and a password.
1168
1169 If SEND-IF-FORCE, only send authinfo to the server if the
1170 .authinfo file has the FORCE token."
1171   (require 'netrc)
1172   (let* ((list (netrc-parse nntp-authinfo-file))
1173          (alist (netrc-machine list nntp-address "nntp"))
1174          (force (or (netrc-get alist "force") nntp-authinfo-force))
1175          (auth-info
1176           (auth-source-user-or-password '("login" "password") nntp-address "nntp"))
1177          (auth-user (nth 0 auth-info))
1178          (auth-passwd (nth 1 auth-info))
1179          (user (or
1180                 ;; this is preferred to netrc-*
1181                 auth-user
1182                 (netrc-get alist "login")
1183                 nntp-authinfo-user))
1184          (passwd (or
1185                   ;; this is preferred to netrc-*
1186                   auth-passwd
1187                   (netrc-get alist "password"))))
1188     (when (or (not send-if-force)
1189               force)
1190       (unless user
1191         (setq user (read-string (format "NNTP (%s) user name: " nntp-address))
1192               nntp-authinfo-user user))
1193       (unless (member user '(nil ""))
1194         (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
1195         (when t                         ;???Should check if AUTHINFO succeeded
1196           (nntp-send-command
1197            "^2.*\r?\n" "AUTHINFO PASS"
1198            (or passwd
1199                nntp-authinfo-password
1200                (setq nntp-authinfo-password
1201                      (read-passwd (format "NNTP (%s@%s) password: "
1202                                           user nntp-address))))))))))
1203
1204 (defun nntp-send-nosy-authinfo ()
1205   "Send the AUTHINFO to the nntp server."
1206   (let ((user (read-string (format "NNTP (%s) user name: " nntp-address))))
1207     (unless (member user '(nil ""))
1208       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
1209       (when t                           ;???Should check if AUTHINFO succeeded
1210         (nntp-send-command "^2.*\r?\n" "AUTHINFO PASS"
1211                            (read-passwd (format "NNTP (%s@%s) password: "
1212                                                 user nntp-address)))))))
1213
1214 (defun nntp-send-authinfo-from-file ()
1215   "Send the AUTHINFO to the nntp server.
1216
1217 The authinfo login name is taken from the user's login name and the
1218 password contained in '~/.nntp-authinfo'."
1219   (when (file-exists-p "~/.nntp-authinfo")
1220     (with-temp-buffer
1221       (insert-file-contents "~/.nntp-authinfo")
1222       (goto-char (point-min))
1223       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" (user-login-name))
1224       (nntp-send-command
1225        "^2.*\r?\n" "AUTHINFO PASS"
1226        (buffer-substring (point) (point-at-eol))))))
1227
1228 ;;; Internal functions.
1229
1230 (defun nntp-handle-authinfo (process)
1231   "Take care of an authinfo response from the server."
1232   (let ((last nntp-last-command))
1233     (funcall nntp-authinfo-function)
1234     ;; We have to re-send the function that was interrupted by
1235     ;; the authinfo request.
1236     (nntp-erase-buffer nntp-server-buffer)
1237     (nntp-send-string process last)))
1238
1239 (defun nntp-make-process-buffer (buffer)
1240   "Create a new, fresh buffer usable for nntp process connections."
1241   (with-current-buffer
1242       (generate-new-buffer
1243        (format " *server %s %s %s*"
1244                nntp-address nntp-port-number
1245                (gnus-buffer-exists-p buffer)))
1246     (mm-disable-multibyte)
1247     (set (make-local-variable 'after-change-functions) nil)
1248     (set (make-local-variable 'nntp-process-wait-for) nil)
1249     (set (make-local-variable 'nntp-process-callback) nil)
1250     (set (make-local-variable 'nntp-process-to-buffer) nil)
1251     (set (make-local-variable 'nntp-process-start-point) nil)
1252     (set (make-local-variable 'nntp-process-decode) nil)
1253     (current-buffer)))
1254
1255 (defun nntp-open-connection (buffer)
1256   "Open a connection to PORT on ADDRESS delivering output to BUFFER."
1257   (run-hooks 'nntp-prepare-server-hook)
1258   (let* ((pbuffer (nntp-make-process-buffer buffer))
1259          (timer
1260           (and nntp-connection-timeout
1261                (run-at-time
1262                 nntp-connection-timeout nil
1263                 `(lambda ()
1264                    (nntp-kill-buffer ,pbuffer)))))
1265          (process
1266           (condition-case err
1267               (let ((coding-system-for-read nntp-coding-system-for-read)
1268                     (coding-system-for-write nntp-coding-system-for-write)
1269                     (map '((nntp-open-network-stream network)
1270                            (nntp-open-ssl-stream tls)
1271                            (nntp-open-tls-stream tls))))
1272                 (if (assoc nntp-open-connection-function map)
1273                     (car (open-protocol-stream
1274                           "nntpd" pbuffer nntp-address nntp-port-number
1275                           :type (cadr
1276                                  (assoc nntp-open-connection-function map))
1277                           :end-of-command "^\\([2345]\\|[.]\\).*\n"
1278                           :capability-command "CAPABILITIES\r\n"
1279                           :success "^3"
1280                           :starttls-function
1281                           (lambda (capabilities)
1282                             (if (not (string-match "STARTTLS" capabilities))
1283                                 nil
1284                               "STARTTLS\r\n"))))
1285                   (funcall nntp-open-connection-function pbuffer)))
1286             (error
1287              (nnheader-report 'nntp "%s" err))
1288             (quit
1289              (message "Quit opening connection to %s" nntp-address)
1290              (nntp-kill-buffer pbuffer)
1291              (signal 'quit nil)
1292              nil))))
1293     (when timer
1294       (nnheader-cancel-timer timer))
1295     (unless process
1296       (nntp-kill-buffer pbuffer))
1297     (when (and (buffer-name pbuffer)
1298                process)
1299       (gnus-set-process-query-on-exit-flag process nil)
1300       (if (and (nntp-wait-for process "^2.*\n" buffer nil t)
1301                (memq (process-status process) '(open run)))
1302           (prog1
1303               (caar (push (list process buffer nil) nntp-connection-alist))
1304             (push process nntp-connection-list)
1305             (with-current-buffer pbuffer
1306               (nntp-read-server-type)
1307               (erase-buffer)
1308               (set-buffer nntp-server-buffer)
1309               (let ((nnheader-callback-function nil))
1310                 (run-hooks 'nntp-server-opened-hook)
1311                 (nntp-send-authinfo t))))
1312         (nntp-kill-buffer (process-buffer process))
1313         nil))))
1314
1315 (defun nntp-read-server-type ()
1316   "Find out what the name of the server we have connected to is."
1317   ;; Wait for the status string to arrive.
1318   (setq nntp-server-type (buffer-string))
1319   (let ((case-fold-search t))
1320     ;; Run server-specific commands.
1321     (dolist (entry nntp-server-action-alist)
1322       (when (string-match (car entry) nntp-server-type)
1323         (if (and (listp (cadr entry))
1324                  (not (eq 'lambda (caadr entry))))
1325             (eval (cadr entry))
1326           (funcall (cadr entry)))))))
1327
1328 (defun nntp-async-wait (process wait-for buffer decode callback)
1329   (with-current-buffer (process-buffer process)
1330     (unless nntp-inside-change-function
1331       (erase-buffer))
1332     (setq nntp-process-wait-for wait-for
1333           nntp-process-to-buffer buffer
1334           nntp-process-decode decode
1335           nntp-process-callback callback
1336           nntp-process-start-point (point-max))
1337     (setq after-change-functions '(nntp-after-change-function))))
1338
1339 (defun nntp-async-timer-handler ()
1340   (mapcar
1341    (lambda (proc)
1342      (if (memq (process-status proc) '(open run))
1343          (nntp-async-trigger proc)
1344        (nntp-async-stop proc)))
1345    nntp-async-process-list))
1346
1347 (defun nntp-async-stop (proc)
1348   (setq nntp-async-process-list (delq proc nntp-async-process-list))
1349   (when (and nntp-async-timer (not nntp-async-process-list))
1350     (nnheader-cancel-timer nntp-async-timer)
1351     (setq nntp-async-timer nil)))
1352
1353 (defun nntp-after-change-function (beg end len)
1354   (unwind-protect
1355       ;; we only care about insertions at eob
1356       (when (and (eq 0 len) (eq (point-max) end))
1357         (save-match-data
1358           (let ((proc (get-buffer-process (current-buffer))))
1359             (when proc
1360               (nntp-async-trigger proc)))))
1361     ;; any throw from after-change-functions will leave it
1362     ;; set to nil.  so we reset it here, if necessary.
1363     (when quit-flag
1364       (setq after-change-functions '(nntp-after-change-function)))))
1365
1366 (defun nntp-async-trigger (process)
1367   (with-current-buffer (process-buffer process)
1368     (when nntp-process-callback
1369       ;; do we have an error message?
1370       (goto-char nntp-process-start-point)
1371       (if (memq (following-char) '(?4 ?5))
1372           ;; wants credentials?
1373           (if (looking-at "480")
1374               (nntp-handle-authinfo process)
1375             ;; report error message.
1376             (nntp-snarf-error-message)
1377             (nntp-do-callback nil))
1378
1379         ;; got what we expect?
1380         (goto-char (point-max))
1381         (when (re-search-backward
1382                nntp-process-wait-for nntp-process-start-point t)
1383           (let ((response (match-string 0)))
1384             (with-current-buffer nntp-server-buffer
1385               (setq nntp-process-response response)))
1386           (nntp-async-stop process)
1387           ;; convert it.
1388           (when (gnus-buffer-exists-p nntp-process-to-buffer)
1389             (let ((buf (current-buffer))
1390                   (start nntp-process-start-point)
1391                   (decode nntp-process-decode))
1392               (with-current-buffer nntp-process-to-buffer
1393                 (goto-char (point-max))
1394                 (save-restriction
1395                   (narrow-to-region (point) (point))
1396                   (nntp-insert-buffer-substring buf start)
1397                   (when decode
1398                     (nntp-decode-text))))))
1399           ;; report it.
1400           (goto-char (point-max))
1401           (nntp-do-callback
1402            (buffer-name (get-buffer nntp-process-to-buffer))))))))
1403
1404 (defun nntp-do-callback (arg)
1405   (let ((callback nntp-process-callback)
1406         (nntp-inside-change-function t))
1407     (setq nntp-process-callback nil)
1408     (funcall callback arg)))
1409
1410 (defun nntp-snarf-error-message ()
1411   "Save the error message in the current buffer."
1412   (let ((message (buffer-string)))
1413     (while (string-match "[\r\n]+" message)
1414       (setq message (replace-match " " t t message)))
1415     (nnheader-report 'nntp "%s" message)
1416     message))
1417
1418 (defun nntp-accept-process-output (process)
1419   "Wait for output from PROCESS and message some dots."
1420   (with-current-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
1421                            nntp-server-buffer)
1422     (let ((len (/ (buffer-size) 1024))
1423           message-log-max)
1424       (unless (< len 10)
1425         (setq nntp-have-messaged t)
1426         (nnheader-message 7 "nntp read: %dk" len)))
1427     (prog1
1428         (nnheader-accept-process-output process)
1429       ;; accept-process-output may update status of process to indicate
1430       ;; that the server has closed the connection.  This MUST be
1431       ;; handled here as the buffer restored by the save-excursion may
1432       ;; be the process's former output buffer (i.e. now killed)
1433       (or (and process
1434                (memq (process-status process) '(open run)))
1435           (nntp-report "Server closed connection")))))
1436
1437 (defun nntp-accept-response ()
1438   "Wait for output from the process that outputs to BUFFER."
1439   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
1440
1441 (defun nntp-possibly-change-group (group server &optional connectionless)
1442   (let ((nnheader-callback-function nil))
1443     (when server
1444       (or (nntp-server-opened server)
1445           (nntp-open-server server nil connectionless)))
1446
1447     (unless connectionless
1448       (or (nntp-find-connection nntp-server-buffer)
1449           (nntp-open-connection nntp-server-buffer))))
1450
1451   (when group
1452     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
1453       (cond ((not entry)
1454              (nntp-report "Server closed connection"))
1455             ((not (equal group (caddr entry)))
1456              (with-current-buffer (process-buffer (car entry))
1457                (erase-buffer)
1458                (nntp-send-command "^[245].*\n" "GROUP" group)
1459                (setcar (cddr entry) group)
1460                (erase-buffer)
1461                (nntp-erase-buffer nntp-server-buffer)))))))
1462
1463 (defun nntp-decode-text (&optional cr-only)
1464   "Decode the text in the current buffer."
1465   (goto-char (point-min))
1466   (while (search-forward "\r" nil t)
1467     (delete-char -1))
1468   (unless cr-only
1469     ;; Remove trailing ".\n" end-of-transfer marker.
1470     (goto-char (point-max))
1471     (forward-line -1)
1472     (when (looking-at ".\n")
1473       (delete-char 2))
1474     ;; Delete status line.
1475     (goto-char (point-min))
1476     (while (looking-at "[1-5][0-9][0-9] .*\n")
1477       ;; For some unknown reason, there is more than one status line.
1478       (delete-region (point) (progn (forward-line 1) (point))))
1479     ;; Remove "." -> ".." encoding.
1480     (while (search-forward "\n.." nil t)
1481       (delete-char -1))))
1482
1483 (defun nntp-encode-text ()
1484   "Encode the text in the current buffer."
1485   (save-excursion
1486     ;; Replace "." at beginning of line with "..".
1487     (goto-char (point-min))
1488     (while (re-search-forward "^\\." nil t)
1489       (insert "."))
1490     (goto-char (point-max))
1491     ;; Insert newline at the end of the buffer.
1492     (unless (bolp)
1493       (insert "\n"))
1494     ;; Insert `.' at end of buffer (end of text mark).
1495     (goto-char (point-max))
1496     (insert ".\n")
1497     (goto-char (point-min))
1498     (while (not (eobp))
1499       (end-of-line)
1500       (delete-char 1)
1501       (insert nntp-end-of-line))))
1502
1503 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
1504   (set-buffer nntp-server-buffer)
1505   (erase-buffer)
1506   (cond
1507
1508    ;; This server does not talk NOV.
1509    ((not nntp-server-xover)
1510     nil)
1511
1512    ;; We don't care about gaps.
1513    ((or (not nntp-nov-gap)
1514         fetch-old)
1515     (nntp-send-xover-command
1516      (if fetch-old
1517          (if (numberp fetch-old)
1518              (max 1 (- (car articles) fetch-old))
1519            1)
1520        (car articles))
1521      (car (last articles)) 'wait)
1522
1523     (goto-char (point-min))
1524     (when (looking-at "[1-5][0-9][0-9] .*\n")
1525       (delete-region (point) (progn (forward-line 1) (point))))
1526     (while (search-forward "\r" nil t)
1527       (replace-match "" t t))
1528     (goto-char (point-max))
1529     (forward-line -1)
1530     (when (looking-at "\\.")
1531       (delete-region (point) (progn (forward-line 1) (point)))))
1532
1533    ;; We do it the hard way.  For each gap, an XOVER command is sent
1534    ;; to the server.  We do not wait for a reply from the server, we
1535    ;; just send them off as fast as we can.  That means that we have
1536    ;; to count the number of responses we get back to find out when we
1537    ;; have gotten all we asked for.
1538    ((numberp nntp-nov-gap)
1539     (let ((count 0)
1540           (received 0)
1541           last-point
1542           in-process-buffer-p
1543           (buf nntp-server-buffer)
1544           (process-buffer (nntp-find-connection-buffer nntp-server-buffer))
1545           first last status)
1546       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
1547       ;; that means that the server does not understand XOVER, but we
1548       ;; won't know that until we try.
1549       (while (and nntp-server-xover articles)
1550         (setq first (car articles))
1551         ;; Search forward until we find a gap, or until we run out of
1552         ;; articles.
1553         (while (and (cdr articles)
1554                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
1555           (setq articles (cdr articles)))
1556
1557         (setq in-process-buffer-p (stringp nntp-server-xover))
1558         (nntp-send-xover-command first (setq last (car articles)))
1559         (setq articles (cdr articles))
1560
1561         (when (and nntp-server-xover in-process-buffer-p)
1562           ;; Don't count tried request.
1563           (setq count (1+ count))
1564
1565           ;; Every 400 requests we have to read the stream in
1566           ;; order to avoid deadlocks.
1567           (when (or (null articles)     ;All requests have been sent.
1568                     (= 1 (% count nntp-maximum-request)))
1569
1570             (nntp-accept-response)
1571             ;; On some Emacs versions the preceding function has a
1572             ;; tendency to change the buffer.  Perhaps.  It's quite
1573             ;; difficult to reproduce, because it only seems to happen
1574             ;; once in a blue moon.
1575             (set-buffer process-buffer)
1576             (while (progn
1577                      (goto-char (or last-point (point-min)))
1578                      ;; Count replies.
1579                      (while (re-search-forward "^\\([0-9][0-9][0-9]\\) .*\n"
1580                                                nil t)
1581                        (incf received)
1582                        (setq status (match-string 1))
1583                        (if (string-match "^[45]" status)
1584                            (setq status 'error)
1585                          (setq status 'ok)))
1586                      (setq last-point (point))
1587                      (or (< received count)
1588                          (if (eq status 'error)
1589                              nil
1590                            ;; I haven't started reading the final response
1591                            (progn
1592                              (goto-char (point-max))
1593                              (forward-line -1)
1594                              (not (looking-at "^\\.\r?\n"))))))
1595               ;; I haven't read the end of the final response
1596               (nntp-accept-response)
1597               (set-buffer process-buffer))))
1598
1599         ;; Some nntp servers seem to have an extension to the XOVER
1600         ;; extension.  On these servers, requesting an article range
1601         ;; preceeding the active range does not return an error as
1602         ;; specified in the RFC.  What we instead get is the NOV entry
1603         ;; for the first available article.  Obviously, a client can
1604         ;; use that entry to avoid making unnecessary requests.  The
1605         ;; only problem is for a client that assumes that the response
1606         ;; will always be within the requested ranage.  For such a
1607         ;; client, we can get N copies of the same entry (one for each
1608         ;; XOVER command sent to the server).
1609
1610         (when (<= count 1)
1611           (goto-char (point-min))
1612           (when (re-search-forward "^[0-9][0-9][0-9] .*\n\\([0-9]+\\)" nil t)
1613             (let ((low-limit (string-to-number
1614                               (buffer-substring (match-beginning 1)
1615                                                 (match-end 1)))))
1616               (while (and articles (<= (car articles) low-limit))
1617                 (setq articles (cdr articles))))))
1618         (set-buffer buf))
1619
1620       (when nntp-server-xover
1621         (when in-process-buffer-p
1622           (set-buffer buf)
1623           (goto-char (point-max))
1624           (nntp-insert-buffer-substring process-buffer)
1625           (set-buffer process-buffer)
1626           (erase-buffer)
1627           (set-buffer buf))
1628
1629         ;; We remove any "." lines and status lines.
1630         (goto-char (point-min))
1631         (while (search-forward "\r" nil t)
1632           (delete-char -1))
1633         (goto-char (point-min))
1634         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
1635         t))))
1636
1637   nntp-server-xover)
1638
1639 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1640   "Send the XOVER command to the server."
1641   (let ((range (format "%d-%d" beg end))
1642         (nntp-inhibit-erase t))
1643     (if (stringp nntp-server-xover)
1644         ;; If `nntp-server-xover' is a string, then we just send this
1645         ;; command.
1646         (if wait-for-reply
1647             (nntp-send-command-nodelete
1648              "\r?\n\\.\r?\n" nntp-server-xover range)
1649           ;; We do not wait for the reply.
1650           (nntp-send-command-nodelete nil nntp-server-xover range))
1651       (let ((commands nntp-xover-commands))
1652         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1653         ;; We try them all until we get at positive response.
1654         (while (and commands (eq nntp-server-xover 'try))
1655           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1656           (with-current-buffer nntp-server-buffer
1657             (goto-char (point-min))
1658             (and (looking-at "[23]")    ; No error message.
1659                  ;; We also have to look at the lines.  Some buggy
1660                  ;; servers give back simple lines with just the
1661                  ;; article number.  How... helpful.
1662                  (progn
1663                    (forward-line 1)
1664                    ;; More text after number, or a dot.
1665                    (looking-at "[0-9]+\t...\\|\\.\r?\n"))
1666                  (setq nntp-server-xover (car commands))))
1667           (setq commands (cdr commands)))
1668         ;; If none of the commands worked, we disable XOVER.
1669         (when (eq nntp-server-xover 'try)
1670           (nntp-erase-buffer nntp-server-buffer)
1671           (setq nntp-server-xover nil))
1672         nntp-server-xover))))
1673
1674 (defun nntp-find-group-and-number (&optional group)
1675   (save-excursion
1676     (save-restriction
1677       ;; FIXME: This is REALLY FISHY: set-buffer after save-restriction?!?
1678       (set-buffer nntp-server-buffer)
1679       (narrow-to-region (goto-char (point-min))
1680                         (or (search-forward "\n\n" nil t) (point-max)))
1681       (goto-char (point-min))
1682       ;; We first find the number by looking at the status line.
1683       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1684                          (string-to-number
1685                           (buffer-substring (match-beginning 1)
1686                                             (match-end 1)))))
1687             newsgroups xref)
1688         (and number (zerop number) (setq number nil))
1689         (if number
1690             ;; Then we find the group name.
1691             (setq group
1692                   (cond
1693                    ;; If there is only one group in the Newsgroups
1694                    ;; header, then it seems quite likely that this
1695                    ;; article comes from that group, I'd say.
1696                    ((and (setq newsgroups
1697                                (mail-fetch-field "newsgroups"))
1698                          (not (string-match "," newsgroups)))
1699                     newsgroups)
1700                    ;; If there is more than one group in the
1701                    ;; Newsgroups header, then the Xref header should
1702                    ;; be filled out.  We hazard a guess that the group
1703                    ;; that has this article number in the Xref header
1704                    ;; is the one we are looking for.  This might very
1705                    ;; well be wrong if this article happens to have
1706                    ;; the same number in several groups, but that's
1707                    ;; life.
1708                    ((and (setq xref (mail-fetch-field "xref"))
1709                          number
1710                          (string-match
1711                           (format "\\([^ :]+\\):%d" number) xref))
1712                     (match-string 1 xref))
1713                    (t "")))
1714           (cond
1715            ((and (not nntp-xref-number-is-evil)
1716                  (setq xref (mail-fetch-field "xref"))
1717                  (string-match
1718                   (if group
1719                       (concat "\\(" (regexp-quote group) "\\):\\([0-9]+\\)")
1720                     "\\([^ :]+\\):\\([0-9]+\\)")
1721                   xref))
1722             (setq group (match-string 1 xref)
1723                   number (string-to-number (match-string 2 xref))))
1724            ((and (setq newsgroups
1725                        (mail-fetch-field "newsgroups"))
1726                  (not (string-match "," newsgroups)))
1727             (setq group newsgroups))
1728            (group)
1729            (t (setq group ""))))
1730         (when (string-match "\r" group)
1731           (setq group (substring group 0 (match-beginning 0))))
1732         (cons group number)))))
1733
1734 (defun nntp-wait-for-string (regexp)
1735   "Wait until string arrives in the buffer."
1736   (let ((buf (current-buffer))
1737         proc)
1738     (goto-char (point-min))
1739     (while (and (setq proc (get-buffer-process buf))
1740                 (memq (process-status proc) '(open run))
1741                 (not (re-search-forward regexp nil t)))
1742       (accept-process-output proc 0.1)
1743       (set-buffer buf)
1744       (goto-char (point-min)))))
1745
1746
1747 ;; ==========================================================================
1748 ;; Obsolete nntp-open-* connection methods -- drv
1749 ;; ==========================================================================
1750
1751 (defvoo nntp-open-telnet-envuser nil
1752   "*If non-nil, telnet session (client and server both) will support the ENVIRON option and not prompt for login name.")
1753
1754 (defvoo nntp-telnet-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
1755   "*Regular expression to match the shell prompt on the remote machine.")
1756
1757 (defvoo nntp-rlogin-program "rsh"
1758   "*Program used to log in on remote machines.
1759 The default is \"rsh\", but \"ssh\" is a popular alternative.")
1760
1761 (defvoo nntp-rlogin-parameters '("telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1762   "*Parameters to `nntp-open-rlogin'.
1763 That function may be used as `nntp-open-connection-function'.  In that
1764 case, this list will be used as the parameter list given to rsh.")
1765
1766 (defvoo nntp-rlogin-user-name nil
1767   "*User name on remote system when using the rlogin connect method.")
1768
1769 (defvoo nntp-telnet-parameters
1770     '("exec" "telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1771   "*Parameters to `nntp-open-telnet'.
1772 That function may be used as `nntp-open-connection-function'.  In that
1773 case, this list will be executed as a command after logging in
1774 via telnet.")
1775
1776 (defvoo nntp-telnet-user-name nil
1777   "User name to log in via telnet with.")
1778
1779 (defvoo nntp-telnet-passwd nil
1780   "Password to use to log in via telnet with.")
1781
1782 (defun nntp-service-to-port (svc)
1783   (cond
1784    ((integerp svc) (number-to-string svc))
1785    ((string-match "\\`[0-9]+\\'" svc) svc)
1786    (t
1787     (with-temp-buffer
1788       (ignore-errors (insert-file-contents "/etc/services"))
1789       (goto-char (point-min))
1790       (if (re-search-forward (concat "^" (regexp-quote svc)
1791                                      "[ \t]+\\([0-9]+\\)/tcp"))
1792           (match-string 1)
1793         svc)))))
1794
1795 (defun nntp-open-telnet (buffer)
1796   (with-current-buffer buffer
1797     (erase-buffer)
1798     (let ((proc (apply
1799                  'start-process
1800                  "nntpd" buffer nntp-telnet-command nntp-telnet-switches))
1801           (case-fold-search t))
1802       (when (memq (process-status proc) '(open run))
1803         (nntp-wait-for-string "^r?telnet")
1804         (process-send-string proc "set escape \^X\n")
1805         (cond
1806          ((and nntp-open-telnet-envuser nntp-telnet-user-name)
1807           (process-send-string proc (concat "open " "-l" nntp-telnet-user-name
1808                                             nntp-address "\n")))
1809          (t
1810           (process-send-string proc (concat "open " nntp-address "\n"))))
1811         (cond
1812          ((not nntp-open-telnet-envuser)
1813           (nntp-wait-for-string "^\r*.?login:")
1814           (process-send-string
1815            proc (concat
1816                  (or nntp-telnet-user-name
1817                      (setq nntp-telnet-user-name (read-string "login: ")))
1818                  "\n"))))
1819         (nntp-wait-for-string "^\r*.?password:")
1820         (process-send-string
1821          proc (concat
1822                (or nntp-telnet-passwd
1823                    (setq nntp-telnet-passwd
1824                          (read-passwd "Password: ")))
1825                "\n"))
1826         (nntp-wait-for-string nntp-telnet-shell-prompt)
1827         (process-send-string
1828          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1829         (nntp-wait-for-string "^\r*20[01]")
1830         (beginning-of-line)
1831         (delete-region (point-min) (point))
1832         (process-send-string proc "\^]")
1833         (nntp-wait-for-string "^r?telnet")
1834         (process-send-string proc "mode character\n")
1835         (accept-process-output proc 1)
1836         (sit-for 1)
1837         (goto-char (point-min))
1838         (forward-line 1)
1839         (delete-region (point) (point-max)))
1840       proc)))
1841
1842 (defun nntp-open-rlogin (buffer)
1843   "Open a connection to SERVER using rsh."
1844   (let ((proc (if nntp-rlogin-user-name
1845                   (apply 'start-process
1846                          "nntpd" buffer nntp-rlogin-program
1847                          nntp-address "-l" nntp-rlogin-user-name
1848                          nntp-rlogin-parameters)
1849                 (apply 'start-process
1850                        "nntpd" buffer nntp-rlogin-program nntp-address
1851                        nntp-rlogin-parameters))))
1852     (with-current-buffer buffer
1853       (nntp-wait-for-string "^\r*20[01]")
1854       (beginning-of-line)
1855       (delete-region (point-min) (point))
1856       proc)))
1857
1858
1859 ;; ==========================================================================
1860 ;; Replacements for the nntp-open-* functions -- drv
1861 ;; ==========================================================================
1862
1863 (defun nntp-open-telnet-stream (buffer)
1864   "Open a nntp connection by telnet'ing the news server.
1865 `nntp-open-netcat-stream' is recommended in place of this function
1866 because it is more reliable.
1867
1868 Please refer to the following variables to customize the connection:
1869 - `nntp-pre-command',
1870 - `nntp-telnet-command',
1871 - `nntp-telnet-switches',
1872 - `nntp-address',
1873 - `nntp-port-number',
1874 - `nntp-end-of-line'."
1875   (let ((command `(,nntp-telnet-command
1876                    ,@nntp-telnet-switches
1877                    ,nntp-address
1878                    ,(nntp-service-to-port nntp-port-number)))
1879         proc)
1880     (and nntp-pre-command
1881          (push nntp-pre-command command))
1882     (setq proc (apply 'start-process "nntpd" buffer command))
1883     (with-current-buffer buffer
1884       (nntp-wait-for-string "^\r*20[01]")
1885       (beginning-of-line)
1886       (delete-region (point-min) (point))
1887       proc)))
1888
1889 (defun nntp-open-via-rlogin-and-telnet (buffer)
1890   "Open a connection to an nntp server through an intermediate host.
1891 First rlogin to the remote host, and then telnet the real news server
1892 from there.
1893 `nntp-open-via-rlogin-and-netcat' is recommended in place of this function
1894 because it is more reliable.
1895
1896 Please refer to the following variables to customize the connection:
1897 - `nntp-pre-command',
1898 - `nntp-via-rlogin-command',
1899 - `nntp-via-rlogin-command-switches',
1900 - `nntp-via-user-name',
1901 - `nntp-via-address',
1902 - `nntp-telnet-command',
1903 - `nntp-telnet-switches',
1904 - `nntp-address',
1905 - `nntp-port-number',
1906 - `nntp-end-of-line'."
1907   (let ((command `(,nntp-via-address
1908                    ,nntp-telnet-command
1909                    ,@nntp-telnet-switches))
1910         proc)
1911     (when nntp-via-user-name
1912       (setq command `("-l" ,nntp-via-user-name ,@command)))
1913     (when nntp-via-rlogin-command-switches
1914       (setq command (append nntp-via-rlogin-command-switches command)))
1915     (push nntp-via-rlogin-command command)
1916     (and nntp-pre-command
1917          (push nntp-pre-command command))
1918     (setq proc (apply 'start-process "nntpd" buffer command))
1919     (with-current-buffer buffer
1920       (nntp-wait-for-string "^r?telnet")
1921       (process-send-string proc (concat "open " nntp-address " "
1922                                         (nntp-service-to-port nntp-port-number)
1923                                         "\n"))
1924       (nntp-wait-for-string "^\r*20[01]")
1925       (beginning-of-line)
1926       (delete-region (point-min) (point))
1927       (process-send-string proc "\^]")
1928       (nntp-wait-for-string "^r?telnet")
1929       (process-send-string proc "mode character\n")
1930       (accept-process-output proc 1)
1931       (sit-for 1)
1932       (goto-char (point-min))
1933       (forward-line 1)
1934       (delete-region (point) (point-max)))
1935     proc))
1936
1937 (defun nntp-open-via-rlogin-and-netcat (buffer)
1938   "Open a connection to an nntp server through an intermediate host.
1939 First rlogin to the remote host, and then connect to the real news
1940 server from there using the netcat command.
1941
1942 Please refer to the following variables to customize the connection:
1943 - `nntp-pre-command',
1944 - `nntp-via-rlogin-command',
1945 - `nntp-via-rlogin-command-switches',
1946 - `nntp-via-user-name',
1947 - `nntp-via-address',
1948 - `nntp-netcat-command',
1949 - `nntp-netcat-switches',
1950 - `nntp-address',
1951 - `nntp-port-number'."
1952   (let ((command `(,@(when nntp-pre-command
1953                        (list nntp-pre-command))
1954                    ,nntp-via-rlogin-command
1955                    ,@nntp-via-rlogin-command-switches
1956                    ,@(when nntp-via-user-name
1957                        (list "-l" nntp-via-user-name))
1958                    ,nntp-via-address
1959                    ,nntp-netcat-command
1960                    ,@nntp-netcat-switches
1961                    ,nntp-address
1962                    ,(nntp-service-to-port nntp-port-number))))
1963     ;; A non-nil connection type results in mightily odd behavior where
1964     ;; (process-send-string proc "\^M") ends up sending a "\n" to the
1965     ;; ssh process.  --Stef
1966     ;; Also a nil connection allow ssh-askpass to work under X11.
1967     (let ((process-connection-type nil))
1968       (apply 'start-process "nntpd" buffer command))))
1969
1970 (defun nntp-open-netcat-stream (buffer)
1971   "Open a connection to an nntp server through netcat.
1972 I.e. use the `nc' command rather than Emacs's builtin networking code.
1973
1974 Please refer to the following variables to customize the connection:
1975 - `nntp-pre-command',
1976 - `nntp-netcat-command',
1977 - `nntp-netcat-switches',
1978 - `nntp-address',
1979 - `nntp-port-number'."
1980   (let ((command `(,nntp-netcat-command
1981                    ,@nntp-netcat-switches
1982                    ,nntp-address
1983                    ,(nntp-service-to-port nntp-port-number))))
1984     (and nntp-pre-command (push nntp-pre-command command))
1985     (let ((process-connection-type nil)) ;See `nntp-open-via-rlogin-and-netcat'.
1986       (apply 'start-process "nntpd" buffer command))))
1987
1988
1989 (defun nntp-open-via-telnet-and-telnet (buffer)
1990   "Open a connection to an nntp server through an intermediate host.
1991 First telnet the remote host, and then telnet the real news server
1992 from there.
1993
1994 Please refer to the following variables to customize the connection:
1995 - `nntp-pre-command',
1996 - `nntp-via-telnet-command',
1997 - `nntp-via-telnet-switches',
1998 - `nntp-via-address',
1999 - `nntp-via-envuser',
2000 - `nntp-via-user-name',
2001 - `nntp-via-user-password',
2002 - `nntp-via-shell-prompt',
2003 - `nntp-telnet-command',
2004 - `nntp-telnet-switches',
2005 - `nntp-address',
2006 - `nntp-port-number',
2007 - `nntp-end-of-line'."
2008   (with-current-buffer buffer
2009     (erase-buffer)
2010     (let ((command `(,nntp-via-telnet-command ,@nntp-via-telnet-switches))
2011           (case-fold-search t)
2012           proc)
2013       (and nntp-pre-command (push nntp-pre-command command))
2014       (setq proc (apply 'start-process "nntpd" buffer command))
2015       (when (memq (process-status proc) '(open run))
2016         (nntp-wait-for-string "^r?telnet")
2017         (process-send-string proc "set escape \^X\n")
2018         (cond
2019          ((and nntp-via-envuser nntp-via-user-name)
2020           (process-send-string proc (concat "open " "-l" nntp-via-user-name
2021                                             nntp-via-address "\n")))
2022          (t
2023           (process-send-string proc (concat "open " nntp-via-address
2024                                             "\n"))))
2025         (when (not nntp-via-envuser)
2026           (nntp-wait-for-string "^\r*.?login:")
2027           (process-send-string proc
2028                                (concat
2029                                 (or nntp-via-user-name
2030                                     (setq nntp-via-user-name
2031                                           (read-string "login: ")))
2032                                 "\n")))
2033         (nntp-wait-for-string "^\r*.?password:")
2034         (process-send-string proc
2035                              (concat
2036                               (or nntp-via-user-password
2037                                   (setq nntp-via-user-password
2038                                         (read-passwd "Password: ")))
2039                               "\n"))
2040         (nntp-wait-for-string nntp-via-shell-prompt)
2041         (let ((real-telnet-command `("exec"
2042                                      ,nntp-telnet-command
2043                                      ,@nntp-telnet-switches
2044                                      ,nntp-address
2045                                      ,(nntp-service-to-port nntp-port-number))))
2046           (process-send-string proc
2047                                (concat (mapconcat 'identity
2048                                                   real-telnet-command " ")
2049                                        "\n")))
2050         (nntp-wait-for-string "^\r*20[01]")
2051         (beginning-of-line)
2052         (delete-region (point-min) (point))
2053         (process-send-string proc "\^]")
2054         (nntp-wait-for-string "^r?telnet")
2055         (process-send-string proc "mode character\n")
2056         (accept-process-output proc 1)
2057         (sit-for 1)
2058         (goto-char (point-min))
2059         (forward-line 1)
2060         (delete-region (point) (point-max)))
2061       proc)))
2062
2063 ;; Marks handling
2064
2065 (defun nntp-marks-directory (server)
2066   (expand-file-name server nntp-marks-directory))
2067
2068 (defvar nntp-server-to-method-cache nil
2069   "Alist of servers and select methods.")
2070
2071 (defun nntp-group-pathname (server group &optional file)
2072   "Return an absolute file name of FILE for GROUP on SERVER."
2073   (let ((method (cdr (assoc server nntp-server-to-method-cache))))
2074     (unless method
2075       (push (cons server (setq method (or (gnus-server-to-method server)
2076                                           (gnus-find-method-for-group group))))
2077             nntp-server-to-method-cache))
2078     (nnmail-group-pathname
2079      (mm-decode-coding-string group
2080                               (inline (gnus-group-name-charset method group)))
2081      (nntp-marks-directory server)
2082      file)))
2083
2084 (defun nntp-possibly-create-directory (group server)
2085   (let ((dir (nntp-group-pathname server group))
2086         (file-name-coding-system nnmail-pathname-coding-system))
2087     (unless (file-exists-p dir)
2088       (make-directory (directory-file-name dir) t)
2089       (nnheader-message 5 "Creating nntp marks directory %s" dir))))
2090
2091 (autoload 'time-less-p "time-date")
2092
2093 (defun nntp-marks-changed-p (group server)
2094   (let ((file (nntp-group-pathname server group nntp-marks-file-name))
2095         (file-name-coding-system nnmail-pathname-coding-system))
2096     (if (null (gnus-gethash file nntp-marks-modtime))
2097         t ;; never looked at marks file, assume it has changed
2098       (time-less-p (gnus-gethash file nntp-marks-modtime)
2099                    (nth 5 (file-attributes file))))))
2100
2101 (defun nntp-save-marks (group server)
2102   (let ((file-name-coding-system nnmail-pathname-coding-system)
2103         (file (nntp-group-pathname server group nntp-marks-file-name)))
2104     (condition-case err
2105         (progn
2106           (nntp-possibly-create-directory group server)
2107           (with-temp-file file
2108             (erase-buffer)
2109             (gnus-prin1 nntp-marks)
2110             (insert "\n"))
2111           (gnus-sethash file
2112                         (nth 5 (file-attributes file))
2113                         nntp-marks-modtime))
2114       (error (or (gnus-yes-or-no-p
2115                   (format "Could not write to %s (%s).  Continue? " file err))
2116                  (error "Cannot write to %s (%s)" file err))))))
2117
2118 (defun nntp-open-marks (group server)
2119   (let ((file (nntp-group-pathname server group nntp-marks-file-name))
2120         (file-name-coding-system nnmail-pathname-coding-system))
2121     (if (file-exists-p file)
2122         (condition-case err
2123             (with-temp-buffer
2124               (gnus-sethash file (nth 5 (file-attributes file))
2125                             nntp-marks-modtime)
2126               (nnheader-insert-file-contents file)
2127               (setq nntp-marks (read (current-buffer)))
2128               (dolist (el gnus-article-unpropagated-mark-lists)
2129                 (setq nntp-marks (gnus-remassoc el nntp-marks))))
2130           (error (or (gnus-yes-or-no-p
2131                       (format "Error reading nntp marks file %s (%s).  Continuing will use marks from .newsrc.eld.  Continue? " file err))
2132                      (error "Cannot read nntp marks file %s (%s)" file err))))
2133       ;; User didn't have a .marks file.  Probably first time
2134       ;; user of the .marks stuff.  Bootstrap it from .newsrc.eld.
2135       (let ((info (gnus-get-info
2136                    (gnus-group-prefixed-name
2137                     group
2138                     (gnus-server-to-method (format "nntp:%s" server)))))
2139             (decoded-name (mm-decode-coding-string
2140                            group
2141                            (gnus-group-name-charset
2142                             (gnus-server-to-method server) group))))
2143         (nnheader-message 7 "Bootstrapping marks for %s..." decoded-name)
2144         (setq nntp-marks (gnus-info-marks info))
2145         (push (cons 'read (gnus-info-read info)) nntp-marks)
2146         (dolist (el gnus-article-unpropagated-mark-lists)
2147           (setq nntp-marks (gnus-remassoc el nntp-marks)))
2148         (nntp-save-marks group server)
2149         (nnheader-message 7 "Bootstrapping marks for %s...done"
2150                           decoded-name)))))
2151
2152 (provide 'nntp)
2153
2154 ;;; nntp.el ends here