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