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