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