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