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