Require `gnus-clfns' when compiling.
[elisp/gnus.git-] / lisp / nntp.el
1 ;;; nntp.el --- nntp access for Gnus
2 ;;; Copyright (C) 1987-90,92-99 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;         Katsumi Yamaoka <yamaoka@jpl.org>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to
22 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (eval-when-compile (require 'cl))
29 (eval-when-compile (require 'gnus-clfns))
30
31 (require 'nnheader)
32 (require 'nnoo)
33 (require 'gnus-util)
34
35 (nnoo-declare nntp)
36
37 (defvoo nntp-address nil
38   "Address of the physical nntp server.")
39
40 (defvoo nntp-port-number "nntp"
41   "Port number on the physical nntp server.")
42
43 (defvoo nntp-server-opened-hook '(nntp-send-mode-reader)
44   "*Hook used for sending commands to the server at startup.
45 The default value is `nntp-send-mode-reader', which makes an innd
46 server spawn an nnrpd server.")
47
48 (defvoo nntp-authinfo-function 'nntp-send-authinfo
49   "Function used to send AUTHINFO to the server.
50 It is called with no parameters.")
51
52 (defvoo nntp-server-action-alist
53     '(("nntpd 1\\.5\\.11t"
54        (remove-hook 'nntp-server-opened-hook 'nntp-send-mode-reader))
55       ("NNRP server Netscape"
56        (setq nntp-server-list-active-group nil)))
57   "Alist of regexps to match on server types and actions to be taken.
58 For instance, if you want Gnus to beep every time you connect
59 to innd, you could say something like:
60
61 \(setq nntp-server-action-alist
62        '((\"innd\" (ding))))
63
64 You probably don't want to do that, though.")
65
66 (defvoo nntp-open-connection-function 'nntp-open-network-stream
67   "*Function used for connecting to a remote system.
68 It will be called with the buffer to output in.
69
70 Two pre-made functions are `nntp-open-network-stream', which is the
71 default, and simply connects to some port or other on the remote
72 system (see nntp-port-number).  The other are `nntp-open-rlogin',
73 which does an rlogin on the remote system, and then does a telnet to
74 the NNTP server available there (see nntp-rlogin-parameters) and
75 `nntp-open-telnet' which telnets to a remote system, logs in and does
76 the same.")
77
78 (defvoo nntp-rlogin-program "rsh"
79   "*Program used to log in on remote machines.
80 The default is \"rsh\", but \"ssh\" is a popular alternative.")
81
82 (defvoo nntp-rlogin-parameters '("telnet" "-8" "${NNTPSERVER:=news}" "nntp")
83   "*Parameters to `nntp-open-rlogin'.
84 That function may be used as `nntp-open-connection-function'.  In that
85 case, this list will be used as the parameter list given to rsh.")
86
87 (defvoo nntp-rlogin-user-name nil
88   "*User name on remote system when using the rlogin connect method.")
89
90 (defvoo nntp-telnet-parameters
91     '("exec" "telnet" "-8" "${NNTPSERVER:=news}" "nntp")
92   "*Parameters to `nntp-open-telnet'.
93 That function may be used as `nntp-open-connection-function'.  In that
94 case, this list will be executed as a command after logging in
95 via telnet.")
96
97 (defvoo nntp-telnet-user-name nil
98   "User name to log in via telnet with.")
99
100 (defvoo nntp-telnet-passwd nil
101   "Password to use to log in via telnet with.")
102
103 (defvoo nntp-open-telnet-envuser nil
104   "*If non-nil, telnet session (client and server both) will support the ENVIRON option and not prompt for login name.")
105
106 (defvoo nntp-telnet-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
107   "*Regular expression to match the shell prompt on the remote machine.")
108
109 (defvoo nntp-telnet-command "telnet"
110   "Command used to start telnet.")
111
112 (defvoo nntp-telnet-switches '("-8")
113   "Switches given to the telnet command.")
114
115 (defvoo nntp-end-of-line "\r\n"
116   "String to use on the end of lines when talking to the NNTP server.
117 This is \"\\r\\n\" by default, but should be \"\\n\" when
118 using rlogin or telnet to communicate with the server.")
119
120 (defvoo nntp-large-newsgroup 50
121   "*The number of the articles which indicates a large newsgroup.
122 If the number of the articles is greater than the value, verbose
123 messages will be shown to indicate the current status.")
124
125 (defvoo nntp-maximum-request 400
126   "*The maximum number of the requests sent to the NNTP server at one time.
127 If Emacs hangs up while retrieving headers, set the variable to a
128 lower value.")
129
130 (defvoo nntp-nov-is-evil nil
131   "*If non-nil, nntp will never attempt to use XOVER when talking to the server.")
132
133 (defvoo nntp-xover-commands '("XOVER" "XOVERVIEW")
134   "*List of strings that are used as commands to fetch NOV lines from a server.
135 The strings are tried in turn until a positive response is gotten.  If
136 none of the commands are successful, nntp will just grab headers one
137 by one.")
138
139 (defvoo nntp-nov-gap 5
140   "*Maximum allowed gap between two articles.
141 If the gap between two consecutive articles is bigger than this
142 variable, split the XOVER request into two requests.")
143
144 (defvoo nntp-prepare-server-hook nil
145   "*Hook run before a server is opened.
146 If can be used to set up a server remotely, for instance.  Say you
147 have an account at the machine \"other.machine\".  This machine has
148 access to an NNTP server that you can't access locally.  You could
149 then use this hook to rsh to the remote machine and start a proxy NNTP
150 server there that you can connect to.  See also
151 `nntp-open-connection-function'")
152
153 (defvoo nntp-warn-about-losing-connection t
154   "*If non-nil, beep when a server closes connection.")
155
156 (defcustom nntp-authinfo-file "~/.authinfo"
157   ".netrc-like file that holds nntp authinfo passwords."
158   :type
159   '(choice file
160            (repeat :tag "Entries"
161                    :menu-tag "Inline"
162                    (list :format "%v"
163                          :value ("" ("login" . "") ("password" . ""))
164                          (string :tag "Host")
165                          (checklist :inline t
166                                     (cons :format "%v"
167                                           (const :format "" "login")
168                                           (string :format "Login: %v"))
169                                     (cons :format "%v"
170                                           (const :format "" "password")
171                                           (string :format "Password: %v")))))))
172
173 \f
174
175 (defvoo nntp-connection-timeout nil
176   "*Number of seconds to wait before an nntp connection times out.
177 If this variable is nil, which is the default, no timers are set.")
178
179 (defvoo nntp-prepare-post-hook nil
180   "*Hook run just before posting an article. It is supposed to be used for
181 inserting Cancel-Lock headers, signing with Gpg, etc.")
182
183 ;;; Internal variables.
184
185 (defvar nntp-record-commands nil
186   "*If non-nil, nntp will record all commands in the \"*nntp-log*\" buffer.")
187
188 (defvar nntp-have-messaged nil)
189
190 (defvar nntp-process-wait-for nil)
191 (defvar nntp-process-to-buffer nil)
192 (defvar nntp-process-callback nil)
193 (defvar nntp-process-decode nil)
194 (defvar nntp-process-start-point nil)
195 (defvar nntp-inside-change-function nil)
196 (defvoo nntp-last-command-time nil)
197 (defvoo nntp-last-command nil)
198 (defvoo nntp-authinfo-password nil)
199 (defvoo nntp-authinfo-user nil)
200
201 (defvar nntp-connection-list nil)
202
203 (defvoo nntp-server-type nil)
204 (defvoo nntp-connection-alist nil)
205 (defvoo nntp-status-string "")
206 (defconst nntp-version "nntp 5.0")
207 (defvoo nntp-inhibit-erase nil)
208 (defvoo nntp-inhibit-output nil)
209
210 (defvoo nntp-server-xover 'try)
211 (defvoo nntp-server-list-active-group 'try)
212
213 (defvar nntp-async-needs-kluge
214   (string-match "^GNU Emacs 20\\.3\\." (emacs-version))
215   "*When non-nil, nntp will poll asynchronous connections
216 once a second.  By default, this is turned on only for Emacs
217 20.3, which has a bug that breaks nntp's normal method of
218 noticing asynchronous data.")
219
220 (defvar nntp-async-timer nil)
221 (defvar nntp-async-process-list nil)
222
223 (eval-and-compile
224   (autoload 'mail-source-read-passwd "mail-source")
225   (autoload 'open-ssl-stream "ssl"))
226
227 \f
228
229 ;;; Internal functions.
230
231 (defsubst nntp-send-string (process string)
232   "Send STRING to PROCESS."
233   ;; We need to store the time to provide timeouts, and
234   ;; to store the command so the we can replay the command
235   ;; if the server gives us an AUTHINFO challenge.
236   (setq nntp-last-command-time (current-time)
237         nntp-last-command string)
238   (when nntp-record-commands
239     (nntp-record-command string))
240   (process-send-string process (concat string nntp-end-of-line)))
241
242 (defun nntp-record-command (string)
243   "Record the command STRING."
244   (save-excursion
245     (set-buffer (get-buffer-create "*nntp-log*"))
246     (goto-char (point-max))
247     (let ((time (current-time)))
248       (insert (format-time-string "%Y%m%dT%H%M%S" time)
249               "." (format "%03d" (/ (nth 2 time) 1000))
250               " " nntp-address " " string "\n"))))
251
252 (defsubst nntp-wait-for (process wait-for buffer &optional decode discard)
253   "Wait for WAIT-FOR to arrive from PROCESS."
254   (save-excursion
255     (set-buffer (process-buffer process))
256     (goto-char (point-min))
257     (while (and (or (not (memq (char-after (point)) '(?2 ?3 ?4 ?5)))
258                     (looking-at "480"))
259                 (memq (process-status process) '(open run)))
260       (when (looking-at "480")
261         (nntp-handle-authinfo process))
262       (nntp-accept-process-output process)
263       (goto-char (point-min)))
264     (prog1
265         (cond
266          ((looking-at "[45]")
267           (progn
268             (nntp-snarf-error-message)
269             nil))
270          ((not (memq (process-status process) '(open run)))
271           (nnheader-report 'nntp "Server closed connection"))
272          (t
273           (goto-char (point-max))
274           (let ((limit (point-min))
275                 response)
276             (while (not (re-search-backward wait-for limit t))
277               (nntp-accept-process-output process)
278               ;; We assume that whatever we wait for is less than 1000
279               ;; characters long.
280               (setq limit (max (- (point-max) 1000) (point-min)))
281               (goto-char (point-max)))
282             (setq response (match-string 0))
283             (save-current-buffer
284               (set-buffer nntp-server-buffer)
285               (setq nntp-process-response response)))
286           (nntp-decode-text (not decode))
287           (unless discard
288             (save-excursion
289               (set-buffer buffer)
290               (goto-char (point-max))
291               (insert-buffer-substring (process-buffer process))
292               ;; Nix out "nntp reading...." message.
293               (when nntp-have-messaged
294                 (setq nntp-have-messaged nil)
295                 (nnheader-message 5 ""))
296               t))))
297       (unless discard
298         (erase-buffer)))))
299
300 (defun nntp-kill-buffer (buffer)
301   (when (buffer-name buffer)
302     (kill-buffer buffer)
303     (nnheader-init-server-buffer)))
304
305 (defsubst nntp-find-connection (buffer)
306   "Find the connection delivering to BUFFER."
307   (let ((alist nntp-connection-alist)
308         (buffer (if (stringp buffer) (get-buffer buffer) buffer))
309         process entry)
310     (while (setq entry (pop alist))
311       (when (eq buffer (cadr entry))
312         (setq process (car entry)
313               alist nil)))
314     (when process
315       (if (memq (process-status process) '(open run))
316           process
317         (nntp-kill-buffer (process-buffer process))
318         (setq nntp-connection-alist (delq entry nntp-connection-alist))
319         nil))))
320
321 (defsubst nntp-find-connection-entry (buffer)
322   "Return the entry for the connection to BUFFER."
323   (assq (nntp-find-connection buffer) nntp-connection-alist))
324
325 (defun nntp-find-connection-buffer (buffer)
326   "Return the process connection buffer tied to BUFFER."
327   (let ((process (nntp-find-connection buffer)))
328     (when process
329       (process-buffer process))))
330
331 (defsubst nntp-retrieve-data (command address port buffer
332                                       &optional wait-for callback decode)
333   "Use COMMAND to retrieve data into BUFFER from PORT on ADDRESS."
334   (let ((process (or (nntp-find-connection buffer)
335                      (nntp-open-connection buffer))))
336     (if (not process)
337         (nnheader-report 'nntp "Couldn't open connection to %s" address)
338       (unless (or nntp-inhibit-erase nnheader-callback-function)
339         (save-excursion
340           (set-buffer (process-buffer process))
341           (erase-buffer)))
342       (when command
343         (nntp-send-string process command))
344       (cond
345        ((eq callback 'ignore)
346         t)
347        ((and callback wait-for)
348         (nntp-async-wait process wait-for buffer decode callback)
349         t)
350        (wait-for
351         (nntp-wait-for process wait-for buffer decode))
352        (t t)))))
353
354 (defsubst nntp-send-command (wait-for &rest strings)
355   "Send STRINGS to server and wait until WAIT-FOR returns."
356   (when (and (not nnheader-callback-function)
357              (not nntp-inhibit-output))
358     (save-excursion
359       (set-buffer nntp-server-buffer)
360       (erase-buffer)))
361   (nntp-retrieve-data
362    (mapconcat 'identity strings " ")
363    nntp-address nntp-port-number nntp-server-buffer
364    wait-for nnheader-callback-function))
365
366 (defun nntp-send-command-nodelete (wait-for &rest strings)
367   "Send STRINGS to server and wait until WAIT-FOR returns."
368   (nntp-retrieve-data
369    (mapconcat 'identity strings " ")
370    nntp-address nntp-port-number nntp-server-buffer
371    wait-for nnheader-callback-function))
372
373 (defun nntp-send-command-and-decode (wait-for &rest strings)
374   "Send STRINGS to server and wait until WAIT-FOR returns."
375   (when (and (not nnheader-callback-function)
376              (not nntp-inhibit-output))
377     (save-excursion
378       (set-buffer nntp-server-buffer)
379       (erase-buffer)))
380   (nntp-retrieve-data
381    (mapconcat 'identity strings " ")
382    nntp-address nntp-port-number nntp-server-buffer
383    wait-for nnheader-callback-function t))
384
385 (defun nntp-send-buffer (wait-for)
386   "Send the current buffer to server and wait until WAIT-FOR returns."
387   (when (and (not nnheader-callback-function)
388              (not nntp-inhibit-output))
389     (save-excursion
390       (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
391       (erase-buffer)))
392   (nntp-encode-text)
393   (process-send-region (nntp-find-connection nntp-server-buffer)
394                        (point-min) (point-max))
395   (nntp-retrieve-data
396    nil nntp-address nntp-port-number nntp-server-buffer
397    wait-for nnheader-callback-function))
398
399 \f
400
401 ;;; Interface functions.
402
403 (nnoo-define-basics nntp)
404
405 (defsubst nntp-next-result-arrived-p ()
406   (cond
407    ;; A result that starts with a 2xx code is terminated by
408    ;; a line with only a "." on it.
409    ((eq (char-after) ?2)
410     (if (re-search-forward "\n\\.\r?\n" nil t)
411         t
412       nil))
413    ;; A result that starts with a 3xx or 4xx code is terminated
414    ;; by a newline.
415    ((looking-at "[34]")
416     (if (search-forward "\n" nil t)
417         t
418       nil))
419    ;; No result here.
420    (t
421     nil)))
422
423 (deffoo nntp-retrieve-headers (articles &optional group server fetch-old)
424   "Retrieve the headers of ARTICLES."
425   (nntp-possibly-change-group group server)
426   (save-excursion
427     (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
428     (erase-buffer)
429     (if (and (not gnus-nov-is-evil)
430              (not nntp-nov-is-evil)
431              (nntp-retrieve-headers-with-xover articles fetch-old))
432         ;; We successfully retrieved the headers via XOVER.
433         'nov
434       ;; XOVER didn't work, so we do it the hard, slow and inefficient
435       ;; way.
436       (let ((number (length articles))
437             (count 0)
438             (received 0)
439             (last-point (point-min))
440             (buf (nntp-find-connection-buffer nntp-server-buffer))
441             (nntp-inhibit-erase t)
442             article)
443         ;; Send HEAD commands.
444         (while (setq article (pop articles))
445           (nntp-send-command
446            nil
447            "HEAD" (if (numberp article)
448                       (int-to-string article)
449                     ;; `articles' is either a list of article numbers
450                     ;; or a list of article IDs.
451                     article))
452           (incf count)
453           ;; Every 400 requests we have to read the stream in
454           ;; order to avoid deadlocks.
455           (when (or (null articles)     ;All requests have been sent.
456                     (zerop (% count nntp-maximum-request)))
457             (nntp-accept-response)
458             (while (progn
459                      (set-buffer buf)
460                      (goto-char last-point)
461                      ;; Count replies.
462                      (while (nntp-next-result-arrived-p)
463                        (setq last-point (point))
464                        (incf received))
465                      (< received count))
466               ;; If number of headers is greater than 100, give
467               ;;  informative messages.
468               (and (numberp nntp-large-newsgroup)
469                    (> number nntp-large-newsgroup)
470                    (zerop (% received 20))
471                    (nnheader-message 6 "NNTP: Receiving headers... %d%%"
472                                      (/ (* received 100) number)))
473               (nntp-accept-response))))
474         (and (numberp nntp-large-newsgroup)
475              (> number nntp-large-newsgroup)
476              (nnheader-message 6 "NNTP: Receiving headers...done"))
477
478         ;; Now all of replies are received.  Fold continuation lines.
479         (nnheader-fold-continuation-lines)
480         ;; Remove all "\r"'s.
481         (nnheader-strip-cr)
482         (copy-to-buffer nntp-server-buffer (point-min) (point-max))
483         'headers))))
484
485 (deffoo nntp-retrieve-groups (groups &optional server)
486   "Retrieve group info on GROUPS."
487   (nntp-possibly-change-group nil server)
488   (when (nntp-find-connection-buffer nntp-server-buffer)
489     (save-excursion
490       ;; Erase nntp-server-buffer before nntp-inhibit-erase.
491       (set-buffer nntp-server-buffer)
492       (erase-buffer)
493       (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
494       ;; The first time this is run, this variable is `try'.  So we
495       ;; try.
496       (when (eq nntp-server-list-active-group 'try)
497         (nntp-try-list-active (car groups)))
498       (erase-buffer)
499       (let ((count 0)
500             (received 0)
501             (last-point (point-min))
502             (nntp-inhibit-erase t)
503             (buf (nntp-find-connection-buffer nntp-server-buffer))
504             (command (if nntp-server-list-active-group "LIST ACTIVE" "GROUP")))
505         (while groups
506           ;; Send the command to the server.
507           (nntp-send-command nil command (pop groups))
508           (incf count)
509           ;; Every 400 requests we have to read the stream in
510           ;; order to avoid deadlocks.
511           (when (or (null groups)       ;All requests have been sent.
512                     (zerop (% count nntp-maximum-request)))
513             (nntp-accept-response)
514             (while (progn
515                      ;; Search `blue moon' in this file for the
516                      ;; reason why set-buffer here.
517                      (set-buffer buf)
518                      (goto-char last-point)
519                      ;; Count replies.
520                      (while (re-search-forward "^[0-9]" nil t)
521                        (incf received))
522                      (setq last-point (point))
523                      (< received count))
524               (nntp-accept-response))))
525
526         ;; Wait for the reply from the final command.
527         (set-buffer buf)
528         (goto-char (point-max))
529         (re-search-backward "^[0-9]" nil t)
530         (when (looking-at "^[23]")
531           (while (progn
532                    (set-buffer buf)
533                    (goto-char (point-max))
534                    (if (not nntp-server-list-active-group)
535                        (not (re-search-backward "\r?\n" (- (point) 3) t))
536                      (not (re-search-backward "^\\.\r?\n" (- (point) 4) t))))
537             (nntp-accept-response)))
538
539         ;; Now all replies are received.  We remove CRs.
540         (set-buffer buf)
541         (goto-char (point-min))
542         (while (search-forward "\r" nil t)
543           (replace-match "" t t))
544
545         (if (not nntp-server-list-active-group)
546             (progn
547               (copy-to-buffer nntp-server-buffer (point-min) (point-max))
548               'group)
549           ;; We have read active entries, so we just delete the
550           ;; superfluous gunk.
551           (goto-char (point-min))
552           (while (re-search-forward "^[.2-5]" nil t)
553             (delete-region (match-beginning 0)
554                            (progn (forward-line 1) (point))))
555           (copy-to-buffer nntp-server-buffer (point-min) (point-max))
556           'active)))))
557
558 (deffoo nntp-retrieve-articles (articles &optional group server)
559   (nntp-possibly-change-group group server)
560   (save-excursion
561     (let ((number (length articles))
562           (count 0)
563           (received 0)
564           (last-point (point-min))
565           (buf (nntp-find-connection-buffer nntp-server-buffer))
566           (nntp-inhibit-erase t)
567           (map (apply 'vector articles))
568           (point 1)
569           article)
570       (set-buffer buf)
571       (erase-buffer)
572       ;; Send ARTICLE command.
573       (while (setq article (pop articles))
574         (nntp-send-command
575          nil
576          "ARTICLE" (if (numberp article)
577                        (int-to-string article)
578                      ;; `articles' is either a list of article numbers
579                      ;; or a list of article IDs.
580                      article))
581         (incf count)
582         ;; Every 400 requests we have to read the stream in
583         ;; order to avoid deadlocks.
584         (when (or (null articles)       ;All requests have been sent.
585                   (zerop (% count nntp-maximum-request)))
586           (nntp-accept-response)
587           (while (progn
588                    (set-buffer buf)
589                    (goto-char last-point)
590                    ;; Count replies.
591                    (while (nntp-next-result-arrived-p)
592                      (aset map received (cons (aref map received) (point)))
593                      (setq last-point (point))
594                      (incf received))
595                    (< received count))
596             ;; If number of headers is greater than 100, give
597             ;;  informative messages.
598             (and (numberp nntp-large-newsgroup)
599                  (> number nntp-large-newsgroup)
600                  (zerop (% received 20))
601                  (nnheader-message 6 "NNTP: Receiving articles... %d%%"
602                                    (/ (* received 100) number)))
603             (nntp-accept-response))))
604       (and (numberp nntp-large-newsgroup)
605            (> number nntp-large-newsgroup)
606            (nnheader-message 6 "NNTP: Receiving articles...done"))
607
608       ;; Now we have all the responses.  We go through the results,
609       ;; wash it and copy it over to the server buffer.
610       (set-buffer nntp-server-buffer)
611       (erase-buffer)
612       (setq last-point (point-min))
613       (mapcar
614        (lambda (entry)
615          (narrow-to-region
616           (setq point (goto-char (point-max)))
617           (progn
618             (insert-buffer-substring buf last-point (cdr entry))
619             (point-max)))
620          (setq last-point (cdr entry))
621          (nntp-decode-text)
622          (widen)
623          (cons (car entry) point))
624        map))))
625
626 (defun nntp-try-list-active (group)
627   (nntp-list-active-group group)
628   (save-excursion
629     (set-buffer nntp-server-buffer)
630     (goto-char (point-min))
631     (cond ((or (eobp)
632                (looking-at "5[0-9]+"))
633            (setq nntp-server-list-active-group nil))
634           (t
635            (setq nntp-server-list-active-group t)))))
636
637 (deffoo nntp-list-active-group (group &optional server)
638   "Return the active info on GROUP (which can be a regexp)."
639   (nntp-possibly-change-group nil server)
640   (nntp-send-command "^\\.*\r?\n" "LIST ACTIVE" group))
641
642 (deffoo nntp-request-group-articles (group &optional server)
643   "Return the list of existing articles in GROUP."
644   (nntp-possibly-change-group nil server)
645   (nntp-send-command "^\\.*\r?\n" "LISTGROUP" group))
646
647 (deffoo nntp-request-article (article &optional group server buffer command)
648   (nntp-possibly-change-group group server)
649   (when (nntp-send-command-and-decode
650          "\r?\n\\.\r?\n" "ARTICLE"
651          (if (numberp article) (int-to-string article) article))
652     (if (and buffer
653              (not (equal buffer nntp-server-buffer)))
654         (save-excursion
655           (set-buffer nntp-server-buffer)
656           (copy-to-buffer buffer (point-min) (point-max))
657           (nntp-find-group-and-number))
658       (nntp-find-group-and-number))))
659
660 (deffoo nntp-request-head (article &optional group server)
661   (nntp-possibly-change-group group server)
662   (when (nntp-send-command
663          "\r?\n\\.\r?\n" "HEAD"
664          (if (numberp article) (int-to-string article) article))
665     (prog1
666         (nntp-find-group-and-number)
667       (nntp-decode-text))))
668
669 (deffoo nntp-request-body (article &optional group server)
670   (nntp-possibly-change-group group server)
671   (nntp-send-command-and-decode
672    "\r?\n\\.\r?\n" "BODY"
673    (if (numberp article) (int-to-string article) article)))
674
675 (deffoo nntp-request-group (group &optional server dont-check)
676   (nntp-possibly-change-group nil server)
677   (when (nntp-send-command "^[245].*\n" "GROUP" group)
678     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
679       (setcar (cddr entry) group))))
680
681 (deffoo nntp-close-group (group &optional server)
682   t)
683
684 (deffoo nntp-server-opened (&optional server)
685   "Say whether a connection to SERVER has been opened."
686   (and (nnoo-current-server-p 'nntp server)
687        nntp-server-buffer
688        (gnus-buffer-live-p nntp-server-buffer)
689        (nntp-find-connection nntp-server-buffer)))
690
691 (deffoo nntp-open-server (server &optional defs connectionless)
692   (nnheader-init-server-buffer)
693   (if (nntp-server-opened server)
694       t
695     (when (or (stringp (car defs))
696               (numberp (car defs)))
697       (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
698     (unless (assq 'nntp-address defs)
699       (setq defs (append defs (list (list 'nntp-address server)))))
700     (nnoo-change-server 'nntp server defs)
701     (unless connectionless
702       (or (nntp-find-connection nntp-server-buffer)
703           (nntp-open-connection nntp-server-buffer)))))
704
705 (deffoo nntp-close-server (&optional server)
706   (nntp-possibly-change-group nil server t)
707   (let ((process (nntp-find-connection nntp-server-buffer)))
708     (while process
709       (when (memq (process-status process) '(open run))
710         (ignore-errors
711           (nntp-send-string process "QUIT")
712           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
713             ;; Ok, this is evil, but when using telnet and stuff
714             ;; as the connection method, it's important that the
715             ;; QUIT command actually is sent out before we kill
716             ;; the process.
717             (sleep-for 1))))
718       (nntp-kill-buffer (process-buffer process))
719       (setq process (car (pop nntp-connection-alist))))
720     (nnoo-close-server 'nntp)))
721
722 (deffoo nntp-request-close ()
723   (let (process)
724     (while (setq process (pop nntp-connection-list))
725       (when (memq (process-status process) '(open run))
726         (ignore-errors
727           (nntp-send-string process "QUIT")
728           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
729             ;; Ok, this is evil, but when using telnet and stuff
730             ;; as the connection method, it's important that the
731             ;; QUIT command actually is sent out before we kill
732             ;; the process.
733             (sleep-for 1))))
734       (nntp-kill-buffer (process-buffer process)))))
735
736 (deffoo nntp-request-list (&optional server)
737   (nntp-possibly-change-group nil server)
738   (nntp-send-command-and-decode "\r?\n\\.\r?\n" "LIST"))
739
740 (deffoo nntp-request-list-newsgroups (&optional server)
741   (nntp-possibly-change-group nil server)
742   (nntp-send-command "\r?\n\\.\r?\n" "LIST NEWSGROUPS"))
743
744 (deffoo nntp-request-newgroups (date &optional server)
745   (nntp-possibly-change-group nil server)
746   (save-excursion
747     (set-buffer nntp-server-buffer)
748     (prog1
749         (nntp-send-command
750          "^\\.\r?\n" "NEWGROUPS"
751          (format-time-string "%y%m%d %H%M%S" (date-to-time date)))
752       (nntp-decode-text))))
753
754 (deffoo nntp-request-post (&optional server)
755   (nntp-possibly-change-group nil server)
756   (when (nntp-send-command "^[23].*\r?\n" "POST")
757     (let ((response (save-current-buffer
758                       (set-buffer nntp-server-buffer)
759                       nntp-process-response))
760           server-id)
761       (when (and response
762                  (string-match "^[23].*\\(<[^\t\n @<>]+@[^\t\n @<>]+>\\)"
763                                response))
764         (setq server-id (match-string 1 response))
765         (narrow-to-region (goto-char (point-min))
766                           (if (search-forward "\n\n" nil t)
767                               (1- (point))
768                             (point-max)))
769         (unless (mail-fetch-field "Message-ID")
770           (goto-char (point-min))
771           (insert "Message-ID: " server-id "\n"))
772         (widen))
773       (run-hooks 'nntp-prepare-post-hook)
774       (nntp-send-buffer "^[23].*\n"))))
775
776 (deffoo nntp-request-type (group article)
777   'news)
778
779 (deffoo nntp-asynchronous-p ()
780   t)
781
782 ;;; Hooky functions.
783
784 (defun nntp-send-mode-reader ()
785   "Send the MODE READER command to the nntp server.
786 This function is supposed to be called from `nntp-server-opened-hook'.
787 It will make innd servers spawn an nnrpd process to allow actual article
788 reading."
789   (nntp-send-command "^.*\n" "MODE READER"))
790
791 (defun nntp-send-authinfo (&optional send-if-force)
792   "Send the AUTHINFO to the nntp server.
793 It will look in the \"~/.authinfo\" file for matching entries.  If
794 nothing suitable is found there, it will prompt for a user name
795 and a password.
796
797 If SEND-IF-FORCE, only send authinfo to the server if the
798 .authinfo file has the FORCE token."
799   (let* ((list (gnus-parse-netrc nntp-authinfo-file))
800          (alist (gnus-netrc-machine list nntp-address))
801          (force (gnus-netrc-get alist "force"))
802          (user (or (gnus-netrc-get alist "login") nntp-authinfo-user))
803          (passwd (gnus-netrc-get alist "password")))
804     (when (or (not send-if-force)
805               force)
806       (unless user
807         (setq user (read-string (format "NNTP (%s) user name: " nntp-address))
808               nntp-authinfo-user user))
809       (unless (member user '(nil ""))
810         (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
811         (when t                         ;???Should check if AUTHINFO succeeded
812           (nntp-send-command
813            "^2.*\r?\n" "AUTHINFO PASS"
814            (or passwd
815                nntp-authinfo-password
816                (setq nntp-authinfo-password
817                      (mail-source-read-passwd (format "NNTP (%s@%s) password: "
818                                                       user nntp-address))))))))))
819
820 (defun nntp-send-nosy-authinfo ()
821   "Send the AUTHINFO to the nntp server."
822   (let ((user (read-string (format "NNTP (%s) user name: " nntp-address))))
823     (unless (member user '(nil ""))
824       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
825       (when t                           ;???Should check if AUTHINFO succeeded
826         (nntp-send-command "^2.*\r?\n" "AUTHINFO PASS"
827                            (mail-source-read-passwd "NNTP (%s@%s) password: "
828                                                     user nntp-address))))))
829
830 (defun nntp-send-authinfo-from-file ()
831   "Send the AUTHINFO to the nntp server.
832
833 The authinfo login name is taken from the user's login name and the
834 password contained in '~/.nntp-authinfo'."
835   (when (file-exists-p "~/.nntp-authinfo")
836     (with-temp-buffer
837       (insert-file-contents "~/.nntp-authinfo")
838       (goto-char (point-min))
839       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" (user-login-name))
840       (nntp-send-command
841        "^2.*\r?\n" "AUTHINFO PASS"
842        (buffer-substring (point) (progn (end-of-line) (point)))))))
843
844 ;;; Internal functions.
845
846 (defun nntp-handle-authinfo (process)
847   "Take care of an authinfo response from the server."
848   (let ((last nntp-last-command))
849     (funcall nntp-authinfo-function)
850     ;; We have to re-send the function that was interrupted by
851     ;; the authinfo request.
852     (save-excursion
853       (set-buffer nntp-server-buffer)
854       (erase-buffer))
855     (nntp-send-string process last)))
856
857 (defun nntp-make-process-buffer (buffer)
858   "Create a new, fresh buffer usable for nntp process connections."
859   (save-excursion
860     (set-buffer
861      (generate-new-buffer
862       (format " *server %s %s %s*"
863               nntp-address nntp-port-number
864               (gnus-buffer-exists-p buffer))))
865     (set (make-local-variable 'after-change-functions) nil)
866     (set (make-local-variable 'nntp-process-wait-for) nil)
867     (set (make-local-variable 'nntp-process-callback) nil)
868     (set (make-local-variable 'nntp-process-to-buffer) nil)
869     (set (make-local-variable 'nntp-process-start-point) nil)
870     (set (make-local-variable 'nntp-process-decode) nil)
871     (current-buffer)))
872
873 (defun nntp-open-connection (buffer)
874   "Open a connection to PORT on ADDRESS delivering output to BUFFER."
875   (run-hooks 'nntp-prepare-server-hook)
876   (let* ((pbuffer (nntp-make-process-buffer buffer))
877          (timer
878           (and nntp-connection-timeout
879                (nnheader-run-at-time
880                 nntp-connection-timeout nil
881                 `(lambda ()
882                    (nntp-kill-buffer ,pbuffer)))))
883          (process
884           (condition-case ()
885               (funcall nntp-open-connection-function pbuffer)
886             (error nil)
887             (quit nil))))
888     (when timer
889       (nnheader-cancel-timer timer))
890     (when (and (buffer-name pbuffer)
891                process)
892       (process-kill-without-query process)
893       (nntp-wait-for process "^.*\n" buffer nil t)
894       (if (memq (process-status process) '(open run))
895           (prog1
896               (caar (push (list process buffer nil) nntp-connection-alist))
897             (push process nntp-connection-list)
898             (save-excursion
899               (set-buffer pbuffer)
900               (nntp-read-server-type)
901               (erase-buffer)
902               (set-buffer nntp-server-buffer)
903               (let ((nnheader-callback-function nil))
904                 (run-hooks 'nntp-server-opened-hook)
905                 (nntp-send-authinfo t))))
906         (nntp-kill-buffer (process-buffer process))
907         nil))))
908
909 (defun nntp-open-network-stream (buffer)
910   (open-network-stream-as-binary
911    "nntpd" buffer nntp-address nntp-port-number))
912
913 (defun nntp-open-ssl-stream (buffer)
914   (let* ((ssl-program-arguments '("-connect" (concat host ":" service)))
915          (proc (open-ssl-stream "nntpd" buffer nntp-address nntp-port-number)))
916     (save-excursion
917       (set-buffer buffer)
918       (nntp-wait-for-string "^\r*20[01]")
919       (beginning-of-line)
920       (delete-region (point-min) (point))
921       proc)))
922
923 (defun nntp-read-server-type ()
924   "Find out what the name of the server we have connected to is."
925   ;; Wait for the status string to arrive.
926   (setq nntp-server-type (buffer-string))
927   (let ((alist nntp-server-action-alist)
928         (case-fold-search t)
929         entry)
930     ;; Run server-specific commands.
931     (while alist
932       (setq entry (pop alist))
933       (when (string-match (car entry) nntp-server-type)
934         (if (and (listp (cadr entry))
935                  (not (eq 'lambda (caadr entry))))
936             (eval (cadr entry))
937           (funcall (cadr entry)))))))
938
939 (defun nntp-async-wait (process wait-for buffer decode callback)
940   (save-excursion
941     (set-buffer (process-buffer process))
942     (unless nntp-inside-change-function
943       (erase-buffer))
944     (setq nntp-process-wait-for wait-for
945           nntp-process-to-buffer buffer
946           nntp-process-decode decode
947           nntp-process-callback callback
948           nntp-process-start-point (point-max))
949     (setq after-change-functions '(nntp-after-change-function))
950     (if nntp-async-needs-kluge
951         (nntp-async-kluge process))))
952
953 (defun nntp-async-kluge (process)
954   ;; emacs 20.3 bug: process output with encoding 'binary
955   ;; doesn't trigger after-change-functions.
956   (unless nntp-async-timer
957     (setq nntp-async-timer
958           (nnheader-run-at-time 1 1 'nntp-async-timer-handler)))
959   (add-to-list 'nntp-async-process-list process))
960
961 (defun nntp-async-timer-handler ()
962   (mapcar
963    (lambda (proc)
964      (if (memq (process-status proc) '(open run))
965          (nntp-async-trigger proc)
966        (nntp-async-stop proc)))
967    nntp-async-process-list))
968
969 (defun nntp-async-stop (proc)
970   (setq nntp-async-process-list (delq proc nntp-async-process-list))
971   (when (and nntp-async-timer (not nntp-async-process-list))
972     (nnheader-cancel-timer nntp-async-timer)
973     (setq nntp-async-timer nil)))
974
975 (defun nntp-after-change-function (beg end len)
976   (unwind-protect
977       ;; we only care about insertions at eob
978       (when (and (eq 0 len) (eq (point-max) end))
979         (save-match-data
980           (let ((proc (get-buffer-process (current-buffer))))
981             (when proc
982               (nntp-async-trigger proc)))))
983     ;; any throw from after-change-functions will leave it
984     ;; set to nil.  so we reset it here, if necessary.
985     (when quit-flag
986       (setq after-change-functions '(nntp-after-change-function)))))
987
988 (defun nntp-async-trigger (process)
989   (save-excursion
990     (set-buffer (process-buffer process))
991     (when nntp-process-callback
992       ;; do we have an error message?
993       (goto-char nntp-process-start-point)
994       (if (memq (following-char) '(?4 ?5))
995           ;; wants credentials?
996           (if (looking-at "480")
997               (nntp-handle-authinfo nntp-process-to-buffer)
998             ;; report error message.
999             (nntp-snarf-error-message)
1000             (nntp-do-callback nil))
1001
1002         ;; got what we expect?
1003         (goto-char (point-max))
1004         (when (re-search-backward
1005                nntp-process-wait-for nntp-process-start-point t)
1006           (let ((response (match-string 0)))
1007             (save-current-buffer
1008               (set-buffer nntp-server-buffer)
1009               (setq nntp-process-response response)))
1010           (nntp-async-stop process)
1011           ;; convert it.
1012           (when (gnus-buffer-exists-p nntp-process-to-buffer)
1013             (let ((buf (current-buffer))
1014                   (start nntp-process-start-point)
1015                   (decode nntp-process-decode))
1016               (save-excursion
1017                 (set-buffer nntp-process-to-buffer)
1018                 (goto-char (point-max))
1019                 (save-restriction
1020                   (narrow-to-region (point) (point))
1021                   (insert-buffer-substring buf start)
1022                   (when decode
1023                     (nntp-decode-text))))))
1024           ;; report it.
1025           (goto-char (point-max))
1026           (nntp-do-callback
1027            (buffer-name (get-buffer nntp-process-to-buffer))))))))
1028
1029 (defun nntp-do-callback (arg)
1030   (let ((callback nntp-process-callback)
1031         (nntp-inside-change-function t))
1032     (setq nntp-process-callback nil)
1033     (funcall callback arg)))
1034
1035 (defun nntp-snarf-error-message ()
1036   "Save the error message in the current buffer."
1037   (let ((message (buffer-string)))
1038     (while (string-match "[\r\n]+" message)
1039       (setq message (replace-match " " t t message)))
1040     (nnheader-report 'nntp message)
1041     message))
1042
1043 (defun nntp-accept-process-output (process &optional timeout)
1044   "Wait for output from PROCESS and message some dots."
1045   (save-excursion
1046     (set-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
1047                     nntp-server-buffer))
1048     (let ((len (/ (point-max) 1024))
1049           message-log-max)
1050       (unless (< len 10)
1051         (setq nntp-have-messaged t)
1052         (nnheader-message 7 "nntp read: %dk" len)))
1053     (accept-process-output process (or timeout 1))))
1054
1055 (defun nntp-accept-response ()
1056   "Wait for output from the process that outputs to BUFFER."
1057   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
1058
1059 (defun nntp-possibly-change-group (group server &optional connectionless)
1060   (let ((nnheader-callback-function nil))
1061     (when server
1062       (or (nntp-server-opened server)
1063           (nntp-open-server server nil connectionless)))
1064
1065     (unless connectionless
1066       (or (nntp-find-connection nntp-server-buffer)
1067           (nntp-open-connection nntp-server-buffer))))
1068
1069   (when group
1070     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
1071       (when (not (equal group (caddr entry)))
1072         (save-excursion
1073           (set-buffer (process-buffer (car entry)))
1074           (erase-buffer)
1075           (nntp-send-command "^[245].*\n" "GROUP" group)
1076           (setcar (cddr entry) group)
1077           (erase-buffer))))))
1078
1079 (defun nntp-decode-text (&optional cr-only)
1080   "Decode the text in the current buffer."
1081   (goto-char (point-min))
1082   (while (search-forward "\r" nil t)
1083     (delete-char -1))
1084   (unless cr-only
1085     ;; Remove trailing ".\n" end-of-transfer marker.
1086     (goto-char (point-max))
1087     (forward-line -1)
1088     (when (looking-at ".\n")
1089       (delete-char 2))
1090     ;; Delete status line.
1091     (goto-char (point-min))
1092     (delete-region (point) (progn (forward-line 1) (point)))
1093     ;; Remove "." -> ".." encoding.
1094     (while (search-forward "\n.." nil t)
1095       (delete-char -1))))
1096
1097 (defun nntp-encode-text ()
1098   "Encode the text in the current buffer."
1099   (save-excursion
1100     ;; Replace "." at beginning of line with "..".
1101     (goto-char (point-min))
1102     (while (re-search-forward "^\\." nil t)
1103       (insert "."))
1104     (goto-char (point-max))
1105     ;; Insert newline at the end of the buffer.
1106     (unless (bolp)
1107       (insert "\n"))
1108     ;; Insert `.' at end of buffer (end of text mark).
1109     (goto-char (point-max))
1110     (insert ".\n")
1111     (goto-char (point-min))
1112     (while (not (eobp))
1113       (end-of-line)
1114       (delete-char 1)
1115       (insert nntp-end-of-line))))
1116
1117 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
1118   (set-buffer nntp-server-buffer)
1119   (erase-buffer)
1120   (cond
1121
1122    ;; This server does not talk NOV.
1123    ((not nntp-server-xover)
1124     nil)
1125
1126    ;; We don't care about gaps.
1127    ((or (not nntp-nov-gap)
1128         fetch-old)
1129     (nntp-send-xover-command
1130      (if fetch-old
1131          (if (numberp fetch-old)
1132              (max 1 (- (car articles) fetch-old))
1133            1)
1134        (car articles))
1135      (car (last articles)) 'wait)
1136
1137     (goto-char (point-min))
1138     (when (looking-at "[1-5][0-9][0-9] .*\n")
1139       (delete-region (point) (progn (forward-line 1) (point))))
1140     (while (search-forward "\r" nil t)
1141       (replace-match "" t t))
1142     (goto-char (point-max))
1143     (forward-line -1)
1144     (when (looking-at "\\.")
1145       (delete-region (point) (progn (forward-line 1) (point)))))
1146
1147    ;; We do it the hard way.  For each gap, an XOVER command is sent
1148    ;; to the server.  We do not wait for a reply from the server, we
1149    ;; just send them off as fast as we can.  That means that we have
1150    ;; to count the number of responses we get back to find out when we
1151    ;; have gotten all we asked for.
1152    ((numberp nntp-nov-gap)
1153     (let ((count 0)
1154           (received 0)
1155           last-point
1156           in-process-buffer-p
1157           (buf nntp-server-buffer)
1158           (process-buffer (nntp-find-connection-buffer nntp-server-buffer))
1159           first)
1160       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
1161       ;; that means that the server does not understand XOVER, but we
1162       ;; won't know that until we try.
1163       (while (and nntp-server-xover articles)
1164         (setq first (car articles))
1165         ;; Search forward until we find a gap, or until we run out of
1166         ;; articles.
1167         (while (and (cdr articles)
1168                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
1169           (setq articles (cdr articles)))
1170
1171         (setq in-process-buffer-p (stringp nntp-server-xover))
1172         (nntp-send-xover-command first (car articles))
1173         (setq articles (cdr articles))
1174         
1175         (when (and nntp-server-xover in-process-buffer-p)
1176           ;; Don't count tried request.
1177           (setq count (1+ count))
1178           
1179           ;; Every 400 requests we have to read the stream in
1180           ;; order to avoid deadlocks.
1181           (when (or (null articles)     ;All requests have been sent.
1182                     (zerop (% count nntp-maximum-request)))
1183
1184             (nntp-accept-response)
1185             ;; On some Emacs versions the preceding function has a
1186             ;; tendency to change the buffer.  Perhaps.  It's quite
1187             ;; difficult to reproduce, because it only seems to happen
1188             ;; once in a blue moon.
1189             (set-buffer process-buffer)
1190             (while (progn
1191                      (goto-char (or last-point (point-min)))
1192                      ;; Count replies.
1193                      (while (re-search-forward "^[0-9][0-9][0-9] .*\n" nil t)
1194                        (incf received))
1195                      (setq last-point (point))
1196                      (< received count))
1197               (nntp-accept-response)
1198               (set-buffer process-buffer))
1199             (set-buffer buf))))
1200
1201       (when nntp-server-xover
1202         (when in-process-buffer-p
1203           (set-buffer process-buffer)
1204           ;; Wait for the reply from the final command.
1205           (goto-char (point-max))
1206           (while (not (re-search-backward "^[0-9][0-9][0-9] " nil t))
1207             (nntp-accept-response)
1208             (set-buffer process-buffer)
1209             (goto-char (point-max)))
1210           (when (looking-at "^[23]")
1211             (while (progn
1212                      (goto-char (point-max))
1213                      (forward-line -1)
1214                      (not (looking-at "^\\.\r?\n")))
1215               (nntp-accept-response)
1216               (set-buffer process-buffer)))
1217           (set-buffer buf)
1218           (goto-char (point-max))
1219           (insert-buffer-substring process-buffer)
1220           (set-buffer process-buffer)
1221           (erase-buffer)
1222           (set-buffer buf))
1223
1224         ;; We remove any "." lines and status lines.
1225         (goto-char (point-min))
1226         (while (search-forward "\r" nil t)
1227           (delete-char -1))
1228         (goto-char (point-min))
1229         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
1230         t))))
1231
1232   nntp-server-xover)
1233
1234 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1235   "Send the XOVER command to the server."
1236   (let ((range (format "%d-%d" beg end))
1237         (nntp-inhibit-erase t))
1238     (if (stringp nntp-server-xover)
1239         ;; If `nntp-server-xover' is a string, then we just send this
1240         ;; command.
1241         (if wait-for-reply
1242             (nntp-send-command-nodelete
1243              "\r?\n\\.\r?\n" nntp-server-xover range)
1244           ;; We do not wait for the reply.
1245           (nntp-send-command-nodelete nil nntp-server-xover range))
1246       (let ((commands nntp-xover-commands))
1247         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1248         ;; We try them all until we get at positive response.
1249         (while (and commands (eq nntp-server-xover 'try))
1250           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1251           (save-excursion
1252             (set-buffer nntp-server-buffer)
1253             (goto-char (point-min))
1254             (and (looking-at "[23]")    ; No error message.
1255                  ;; We also have to look at the lines.  Some buggy
1256                  ;; servers give back simple lines with just the
1257                  ;; article number.  How... helpful.
1258                  (progn
1259                    (forward-line 1)
1260                    (looking-at "[0-9]+\t...")) ; More text after number.
1261                  (setq nntp-server-xover (car commands))))
1262           (setq commands (cdr commands)))
1263         ;; If none of the commands worked, we disable XOVER.
1264         (when (eq nntp-server-xover 'try)
1265           (save-excursion
1266             (set-buffer nntp-server-buffer)
1267             (erase-buffer)
1268             (setq nntp-server-xover nil)))
1269         nntp-server-xover))))
1270
1271 ;;; Alternative connection methods.
1272
1273 (defun nntp-wait-for-string (regexp)
1274   "Wait until string arrives in the buffer."
1275   (let ((buf (current-buffer)))
1276     (goto-char (point-min))
1277     (while (not (re-search-forward regexp nil t))
1278       (accept-process-output (nntp-find-connection nntp-server-buffer))
1279       (set-buffer buf)
1280       (goto-char (point-min)))))
1281
1282 (defun nntp-open-telnet (buffer)
1283   (save-excursion
1284     (set-buffer buffer)
1285     (erase-buffer)
1286     (let ((proc (as-binary-process
1287                  (apply
1288                   'start-process
1289                   "nntpd" buffer nntp-telnet-command nntp-telnet-switches)))
1290           (case-fold-search t))
1291       (when (memq (process-status proc) '(open run))
1292         (process-send-string proc "set escape \^X\n")
1293         (cond
1294          ((and nntp-open-telnet-envuser nntp-telnet-user-name)
1295           (process-send-string proc (concat "open " "-l" nntp-telnet-user-name
1296                                             nntp-address "\n")))
1297          (t
1298           (process-send-string proc (concat "open " nntp-address "\n"))))
1299         (cond
1300          ((not nntp-open-telnet-envuser)
1301           (nntp-wait-for-string "^\r*.?login:")
1302           (process-send-string
1303            proc (concat
1304                  (or nntp-telnet-user-name
1305                      (setq nntp-telnet-user-name (read-string "login: ")))
1306                  "\n"))))
1307         (nntp-wait-for-string "^\r*.?password:")
1308         (process-send-string
1309          proc (concat
1310                (or nntp-telnet-passwd
1311                    (setq nntp-telnet-passwd
1312                          (mail-source-read-passwd "Password: ")))
1313                "\n"))
1314         (nntp-wait-for-string nntp-telnet-shell-prompt)
1315         (process-send-string
1316          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1317         (nntp-wait-for-string "^\r*20[01]")
1318         (beginning-of-line)
1319         (delete-region (point-min) (point))
1320         (process-send-string proc "\^]")
1321         (nntp-wait-for-string "^telnet")
1322         (process-send-string proc "mode character\n")
1323         (accept-process-output proc 1)
1324         (sit-for 1)
1325         (goto-char (point-min))
1326         (forward-line 1)
1327         (delete-region (point) (point-max)))
1328       proc)))
1329
1330 (defun nntp-open-rlogin (buffer)
1331   "Open a connection to SERVER using rsh."
1332   (let ((proc (if nntp-rlogin-user-name
1333                   (as-binary-process
1334                    (apply 'start-process
1335                           "nntpd" buffer nntp-rlogin-program
1336                           nntp-address "-l" nntp-rlogin-user-name
1337                           nntp-rlogin-parameters))
1338                 (as-binary-process
1339                  (apply 'start-process
1340                         "nntpd" buffer nntp-rlogin-program nntp-address
1341                         nntp-rlogin-parameters)))))
1342     (save-excursion
1343       (set-buffer buffer)
1344       (nntp-wait-for-string "^\r*20[01]")
1345       (beginning-of-line)
1346       (delete-region (point-min) (point))
1347       proc)))
1348
1349 (defun nntp-find-group-and-number ()
1350   (save-excursion
1351     (save-restriction
1352       (set-buffer nntp-server-buffer)
1353       (narrow-to-region (goto-char (point-min))
1354                         (or (search-forward "\n\n" nil t) (point-max)))
1355       (goto-char (point-min))
1356       ;; We first find the number by looking at the status line.
1357       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1358                          (string-to-int
1359                           (buffer-substring (match-beginning 1)
1360                                             (match-end 1)))))
1361             group newsgroups xref)
1362         (and number (zerop number) (setq number nil))
1363         ;; Then we find the group name.
1364         (setq group
1365               (cond
1366                ;; If there is only one group in the Newsgroups header,
1367                ;; then it seems quite likely that this article comes
1368                ;; from that group, I'd say.
1369                ((and (setq newsgroups (mail-fetch-field "newsgroups"))
1370                      (not (string-match "," newsgroups)))
1371                 newsgroups)
1372                ;; If there is more than one group in the Newsgroups
1373                ;; header, then the Xref header should be filled out.
1374                ;; We hazard a guess that the group that has this
1375                ;; article number in the Xref header is the one we are
1376                ;; looking for.  This might very well be wrong if this
1377                ;; article happens to have the same number in several
1378                ;; groups, but that's life.
1379                ((and (setq xref (mail-fetch-field "xref"))
1380                      number
1381                      (string-match (format "\\([^ :]+\\):%d" number) xref))
1382                 (substring xref (match-beginning 1) (match-end 1)))
1383                (t "")))
1384         (when (string-match "\r" group)
1385           (setq group (substring group 0 (match-beginning 0))))
1386         (cons group number)))))
1387
1388 (provide 'nntp)
1389
1390 ;;; nntp.el ends here