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