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