;;; nntp.el --- nntp access for Gnus;; Copyright (C) 1987,88,89,90,92,93,94,95,96 Free Software Foundation, Inc.;; Author: Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>;; Lars Magne Ingebrigtsen <larsi@ifi.uio.no>;; Keywords: news;; This file is part of GNU Emacs.;; GNU Emacs is free software; you can redistribute it and/or modify;; it under the terms of the GNU General Public License as published by;; the Free Software Foundation; either version 2, or (at your option);; any later version.;; GNU Emacs is distributed in the hope that it will be useful,;; but WITHOUT ANY WARRANTY; without even the implied warranty of;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the;; GNU General Public License for more details.;; You should have received a copy of the GNU General Public License;; along with GNU Emacs; see the file COPYING. If not, write to the;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,;; Boston, MA 02111-1307, USA.;;; Commentary:;;; Code:(require'nnheader)(require'nnoo)(eval-when-compile(require'cl))(nnoo-declarenntp)(eval-and-compile(unless(fboundp'open-network-stream)(require'tcp)))(eval-when-compile(require'cl))(eval-and-compile(autoload'cancel-timer"timer")(autoload'telnet"telnet"nilt)(autoload'telnet-send-input"telnet"nilt)(autoload'timezone-parse-date"timezone"))(defvoonntp-server-hooknil"*Hooks for the NNTP server.If the kanji code of the NNTP server is different from the local kanjicode, the correct kanji code of the buffer associated with the NNTPserver must be specified as follows:\(setq nntp-server-hook (function (lambda () ;; Server's Kanji code is EUC (NEmacs hack). (make-local-variable 'kanji-fileio-code) (setq kanji-fileio-code 0))))If you'd like to change something depending on the server in thishook, use the variable `nntp-address'.")(defvoonntp-server-opened-hook'(nntp-send-mode-reader)"*Hook used for sending commands to the server at startup. The default value is `nntp-send-mode-reader', which makes an inndserver spawn an nnrpd server. Another useful function to put in thishook might be `nntp-send-authinfo', which will prompt for a passwordto allow posting from the server. Note that this is only necessary todo on servers that use strict access control.")(add-hook'nntp-server-opened-hook'nntp-send-mode-reader)(defvoonntp-server-action-alist'(("nntpd 1\\.5\\.11t"(remove-hook'nntp-server-opened-hook'nntp-send-mode-reader)))"Alist of regexps to match on server types and actions to be taken.For instance, if you want Gnus to beep every time you connectto innd, you could say something like:\(setq nntp-server-action-alist '((\"innd\" (ding))))You probably don't want to do that, though.")(defvoonntp-open-server-function'nntp-open-network-stream"*Function used for connecting to a remote system.It will be called with the address of the remote system.Two pre-made functions are `nntp-open-network-stream', which is thedefault, and simply connects to some port or other on the remotesystem (see nntp-port-number). The other is `nntp-open-rlogin', whichdoes an rlogin on the remote system, and then does a telnet to theNNTP server available there (see nntp-rlogin-parameters).")(defvoonntp-rlogin-parameters'("telnet""${NNTPSERVER:=localhost}""nntp")"*Parameters to `nntp-open-login'.That function may be used as `nntp-open-server-function'. In thatcase, this list will be used as the parameter list given to rsh.")(defvoonntp-rlogin-user-namenil"*User name on remote system when using the rlogin connect method.")(defvoonntp-addressnil"*The name of the NNTP server.")(defvoonntp-port-number"nntp""*Port number to connect to.")(defvoonntp-end-of-line"\r\n""String to use on the end of lines when talking to the NNTP server.This is \"\\r\\n\" by default, but should be \"\\n\" whenusing rlogin to communicate with the server.")(defvoonntp-large-newsgroup50"*The number of the articles which indicates a large newsgroup.If the number of the articles is greater than the value, verbosemessages will be shown to indicate the current status.")(defvoonntp-buggy-select(memqsystem-type'(fujitsu-uts))"*t if your select routine is buggy.If the select routine signals error or fall into infinite loop whilewaiting for the server response, the variable must be set to t. Incase of Fujitsu UTS, it is set to T since `accept-process-output'doesn't work properly.")(defvoonntp-maximum-request400"*The maximum number of the requests sent to the NNTP server at one time.If Emacs hangs up while retrieving headers, set the variable to alower value.")(defvoonntp-debug-read10000"*Display '...' every 10Kbytes of a message being received if it is non-nil.If it is a number, dots are displayed per the number.")(defvoonntp-nov-is-evilnil"*If non-nil, nntp will never attempt to use XOVER when talking to the server.")(defvoonntp-xover-commands'("XOVER""XOVERVIEW")"*List of strings that are used as commands to fetch NOV lines from a server.The strings are tried in turn until a positive response is gotten. Ifnone of the commands are successful, nntp will just grab headers oneby one.")(defvoonntp-nov-gap20"*Maximum allowed gap between two articles.If the gap between two consecutive articles is bigger than thisvariable, split the XOVER request into two requests.")(defvoonntp-connection-timeoutnil"*Number of seconds to wait before an nntp connection times out.If this variable is nil, which is the default, no timers are set.")(defvoonntp-command-timeoutnil"*Number of seconds to wait for a response when sending a command.If this variable is nil, which is the default, no timers are set.")(defvoonntp-retry-on-breaknil"*If non-nil, re-send the command when the user types `C-g'.")(defvoonntp-news-default-headersnil"*If non-nil, override `mail-default-headers' when posting news.")(defvoonntp-prepare-server-hooknil"*Hook run before a server is opened.If can be used to set up a server remotely, for instance. Say youhave an account at the machine \"other.machine\". This machine hasaccess to an NNTP server that you can't access locally. You couldthen use this hook to rsh to the remote machine and start a proxy NNTPserver there that you can connect to.")(defvoonntp-async-number5"*How many articles should be prefetched when in asynchronous mode.")(defvoonntp-warn-about-losing-connectiont"*If non-nil, beep when a server closes connection.")(defconstnntp-version"nntp 4.0""Version numbers of this version of NNTP.")(defvarnntp-server-buffernil"Buffer associated with the NNTP server process.")(defvoonntp-server-processnil"The NNTP server process.You'd better not use this variable in NNTP front-end program, butinstead use `nntp-server-buffer'.")(defvoonntp-status-stringnil"Save the server response message.")(defvarnntp-opened-connectionsnil"All (possibly) opened connections.")(defvoonntp-server-xover'try)(defvoonntp-server-list-active-group'try)(defvoonntp-current-group"")(defvoonntp-server-typenil)(defvoonntp-async-processnil)(defvoonntp-async-buffernil)(defvoonntp-async-articlesnil)(defvoonntp-async-fetchednil)(defvoonntp-async-group-alistnil);;; Interface functions.(nnoo-define-basicsnntp)(deffoonntp-retrieve-headers(articles&optionalgroupserverfetch-old)"Retrieve the headers of ARTICLES."(nntp-possibly-change-servergroupserver)(save-excursion(set-buffernntp-server-buffer)(erase-buffer)(if(and(notgnus-nov-is-evil)(notnntp-nov-is-evil)(nntp-retrieve-headers-with-xoverarticlesfetch-old));; We successfully retrieved the headers via XOVER.'nov;; XOVER didn't work, so we do it the hard, slow and inefficient;; way. (let((number(lengtharticles))(count0)(received0)(message-log-maxnil)(last-point(point-min)));; Send HEAD command.(whilearticles(nntp-send-strings-to-server"HEAD"(if(numberp(cararticles))(int-to-string(cararticles));; `articles' is either a list of article numbers;; or a list of article IDs.(cararticles)))(setqarticles(cdrarticles)count(1+count));; Every 400 header requests we have to read the stream in;; order to avoid deadlocks.(when(or(nullarticles);All requests have been sent.(zerop(%countnntp-maximum-request)))(nntp-accept-response)(while(progn(goto-charlast-point);; Count replies.(while(re-search-forward"^[0-9]"nilt)(setqreceived(1+received)))(setqlast-point(point))(<receivedcount));; If number of headers is greater than 100, give;; informative messages.(and(numberpnntp-large-newsgroup)(>numbernntp-large-newsgroup)(zerop(%received20))(nnheader-message7"NNTP: Receiving headers... %d%%"(/(*received100)number)))(nntp-accept-response))));; Wait for text of last command.(goto-char(point-max))(re-search-backward"^[0-9]"nilt)(when(looking-at"^[23]")(while(progn(goto-char(-(point-max)3))(not(looking-at"^\\.\r?\n")))(nntp-accept-response)))(and(numberpnntp-large-newsgroup)(>numbernntp-large-newsgroup)(nnheader-message7"NNTP: Receiving headers...done"));; Now all of replies are received. Fold continuation lines.(nnheader-fold-continuation-lines);; Remove all "\r"'s.(goto-char(point-min))(while(search-forward"\r"nilt)(replace-match""tt))'headers))))(deffoonntp-retrieve-groups(groups&optionalserver)"Retrieve group info on GROUPS."(nntp-possibly-change-servernilserver)(save-excursion(set-buffernntp-server-buffer);; The first time this is run, this variable is `try'. So we;; try. (when(eqnntp-server-list-active-group'try)(nntp-try-list-active(cargroups)))(erase-buffer)(let((count0)(received0)(last-point(point-min))(command(ifnntp-server-list-active-group"LIST ACTIVE""GROUP")))(whilegroups;; Send the command to the server.(nntp-send-strings-to-servercommand(cargroups))(setqgroups(cdrgroups))(setqcount(1+count));; Every 400 requests we have to read the stream in;; order to avoid deadlocks.(when(or(nullgroups);All requests have been sent.(zerop(%countnntp-maximum-request)))(nntp-accept-response)(while(progn(goto-charlast-point);; Count replies.(while(re-search-forward"^[0-9]"nilt)(setqreceived(1+received)))(setqlast-point(point))(<receivedcount))(nntp-accept-response))));; Wait for the reply from the final command.(whennntp-server-list-active-group(goto-char(point-max))(re-search-backward"^[0-9]"nilt)(when(looking-at"^[23]")(while(progn(goto-char(-(point-max)3))(not(looking-at"^\\.\r?\n")))(nntp-accept-response))));; Now all replies are received. We remove CRs.(goto-char(point-min))(while(search-forward"\r"nilt)(replace-match""tt))(if(notnntp-server-list-active-group)'group;; We have read active entries, so we just delete the;; superfluos gunk.(goto-char(point-min))(while(re-search-forward"^[.2-5]"nilt)(delete-region(match-beginning0)(progn(forward-line1)(point))))'active))))(deffoonntp-open-server(server&optionaldefsconnectionless)"Open the virtual server SERVER.If CONNECTIONLESS is non-nil, don't attempt to connect to any physicalservers.";; Called with just a port number as the defs.(when(or(stringp(cardefs))(numberp(cardefs)))(setqdefs`((nntp-port-number,(cardefs)))))(unless(assq'nntp-addressdefs)(setqdefs(appenddefs`((nntp-address,server)))))(nnoo-change-server'nntpserverdefs)(if(nntp-server-openedserver)t(or(nntp-server-openedserver)connectionless(prog2(run-hooks'nntp-prepare-server-hook)(nntp-open-server-semi-internalnntp-addressnntp-port-number)(nnheader-insert"")))))(deffoonntp-close-server(&optionalserver)"Close connection to SERVER."(nntp-possibly-change-servernilservert)(unwind-protect(progn;; Un-set default sentinel function before closing connection.(andnntp-server-process(eq'nntp-default-sentinel(process-sentinelnntp-server-process))(set-process-sentinelnntp-server-processnil));; We cannot send QUIT command unless the process is running.(when(nntp-server-openedserver)(nntp-send-commandnil"QUIT");; Give the QUIT time to arrive.(sleep-for1)))(nntp-close-server-internalserver)))(deffoonntp-request-close()"Close all server connections."(let(proc)(whilenntp-opened-connections(when(setqproc(popnntp-opened-connections));; Un-set default sentinel function before closing connection.(when(eq'nntp-default-sentinel(process-sentinelproc))(set-process-sentinelprocnil))(condition-case()(process-send-stringproc(concat"QUIT"nntp-end-of-line))(errornil));; Give the QUIT time to reach the server before we close;; down the process.(sleep-for1)(delete-processproc)))(andnntp-async-buffer(buffer-namenntp-async-buffer)(kill-buffernntp-async-buffer))(let((alist(cddr(assq'nntpnnoo-state-alist)))entry)(while(setqentry(popalist))(and(setqproc(cdr(assq'nntp-async-bufferentry)))(buffer-nameproc)(kill-bufferproc))))(nnoo-close-server'nntp)(setqnntp-async-group-alistnilnntp-async-articlesnil)))(deffoonntp-server-opened(&optionalserver)"Say whether a connection to SERVER has been opened."(and(nnoo-current-server-p'nntpserver)nntp-server-buffer(buffer-namenntp-server-buffer)nntp-server-process(memq(process-statusnntp-server-process)'(openrun))))(deffoonntp-status-message(&optionalserver)"Return server status as a string."(if(andnntp-status-string;; NNN MESSAGE(string-match"[0-9][0-9][0-9][ \t]+\\([^\r]*\\).*$"nntp-status-string))(substringnntp-status-string(match-beginning1)(match-end1));; Empty message if nothing.(ornntp-status-string"")))(deffoonntp-request-article(id&optionalgroupserverbuffer)"Request article ID (Message-ID or number)."(nntp-possibly-change-servergroupserver)(let(found);; First we see whether we can get the article from the async buffer. (when(and(numberpid)nntp-async-articles(memqidnntp-async-fetched))(save-excursion(set-buffernntp-async-buffer)(let((opoint(point))(art(if(numberpid)(int-to-stringid)id))begend)(when(and(or(re-search-forward(concat"^2.. +"art)nilt)(progn(goto-char(point-min))(re-search-forward(concat"^2.. +"art)opointt)))(progn(beginning-of-line)(setqbeg(point)end(re-search-forward"^\\.\r?\n"nilt))))(setqfoundt)(save-excursion(set-buffer(orbuffernntp-server-buffer))(erase-buffer)(insert-buffer-substringnntp-async-bufferbegend)(let((nntp-server-buffer(current-buffer)))(nntp-decode-text)))(delete-regionbegend)(whennntp-async-articles(nntp-async-fetch-articlesid))))))(iffoundid;; The article was not in the async buffer, so we fetch it now.(unwind-protect(progn(ifbuffer(set-process-buffernntp-server-processbuffer))(let((nntp-server-buffer(orbuffernntp-server-buffer))(art(or(and(numberpid)(int-to-stringid))id)))(prog1(and(nntp-send-command;; A bit odd regexp to ensure working over rlogin."^\\.\r?\n""ARTICLE"art)(if(numberpid)(consnntp-current-groupid);; We find out what the article number was.(nntp-find-group-and-number)))(nntp-decode-text)(andnntp-async-articles(nntp-async-fetch-articlesid)))))(whenbuffer(set-process-buffernntp-server-processnntp-server-buffer))))))(deffoonntp-request-body(id&optionalgroupserver)"Request body of article ID (Message-ID or number)."(nntp-possibly-change-servergroupserver)(prog1;; If NEmacs, end of message may look like: "\256\215" (".^M")(nntp-send-command"^\\.\r?\n""BODY"(or(and(numberpid)(int-to-stringid))id))(nntp-decode-text)))(deffoonntp-request-head(id&optionalgroupserver)"Request head of article ID (Message-ID or number)."(nntp-possibly-change-servergroupserver)(prog1(when(nntp-send-command"^\\.\r?\n""HEAD"(if(numberpid)(int-to-stringid)id))(if(numberpid)id;; We find out what the article number was.(nntp-find-group-and-number)))(nntp-decode-text)(save-excursion(set-buffernntp-server-buffer)(nnheader-fold-continuation-lines))))(deffoonntp-request-stat(id&optionalgroupserver)"Request STAT of article ID (Message-ID or number)."(nntp-possibly-change-servergroupserver)(nntp-send-command"^[23].*\r?\n""STAT"(or(and(numberpid)(int-to-stringid))id)))(deffoonntp-request-type(group&optionalarticle)'news)(deffoonntp-request-group(group&optionalserverdont-check)"Select GROUP."(nntp-possibly-change-servernilserver)(setqnntp-current-group(when(nntp-send-command"^2.*\r?\n""GROUP"group)group)))(deffoonntp-request-asynchronous(group&optionalserverarticles)"Enable pre-fetch in GROUP."(whennntp-async-articles(nntp-async-request-groupgroup))(whennntp-async-number(if(not(or(nntp-async-server-opened)(nntp-async-open-server)));; Couldn't open the second connection(progn(message"Can't open second connection to %s"nntp-address)(ding)(setqnntp-async-articlesnil)(sit-for2));; We opened the second connection (or it was opened already). (setqnntp-async-articlesarticles)(setqnntp-async-fetchednil);; Clear any old data.(save-excursion(set-buffernntp-async-buffer)(erase-buffer));; Select the correct current group on this server.(nntp-async-send-strings"GROUP"group)t)))(deffoonntp-list-active-group(group&optionalserver)"Return the active info on GROUP (which can be a regexp."(nntp-possibly-change-servergroupserver)(nntp-send-command"^.*\r?\n""LIST ACTIVE"group))(deffoonntp-request-group-description(group&optionalserver)"Get the description of GROUP."(nntp-possibly-change-servernilserver)(prog1(nntp-send-command"^.*\r?\n""XGTITLE"group)(nntp-decode-text)))(deffoonntp-close-group(group&optionalserver)"Close GROUP."(setqnntp-current-groupnil)t)(deffoonntp-request-list(&optionalserver)"List all active groups."(nntp-possibly-change-servernilserver)(prog1(nntp-send-command"^\\.\r?\n""LIST")(nntp-decode-text)))(deffoonntp-request-list-newsgroups(&optionalserver)"Get descriptions on all groups on SERVER."(nntp-possibly-change-servernilserver)(prog1(nntp-send-command"^\\.\r?\n""LIST NEWSGROUPS")(nntp-decode-text)))(deffoonntp-request-newgroups(date&optionalserver)"List groups that have arrived since DATE."(nntp-possibly-change-servernilserver)(let*((date(timezone-parse-datedate))(time-string(format"%s%02d%02d %s%s%s"(substring(arefdate0)2)(string-to-int(arefdate1))(string-to-int(arefdate2))(substring(arefdate3)02)(substring(arefdate3)35)(substring(arefdate3)68))))(prog1(nntp-send-command"^\\.\r?\n""NEWGROUPS"time-string)(nntp-decode-text))))(deffoonntp-request-list-distributions(&optionalserver)"List distributions."(nntp-possibly-change-servernilserver)(prog1(nntp-send-command"^\\.\r?\n""LIST DISTRIBUTIONS")(nntp-decode-text)))(deffoonntp-request-last(&optionalgroupserver)"Decrease the current article pointer."(nntp-possibly-change-servergroupserver)(nntp-send-command"^[23].*\r?\n""LAST"))(deffoonntp-request-next(&optionalgroupserver)"Advance the current article pointer."(nntp-possibly-change-servergroupserver)(nntp-send-command"^[23].*\r?\n""NEXT"))(deffoonntp-request-post(&optionalserver)"Post the current buffer."(nntp-possibly-change-servernilserver)(when(nntp-send-command"^[23].*\r?\n""POST")(nnheader-insert"")(nntp-encode-text)(nntp-send-region-to-server(point-min)(point-max));; 1.2a NNTP's post command is buggy. "^M" (\r) is not;; appended to end of the status message.(nntp-wait-for-response"^[23].*\n")));;; Internal functions.(defunnntp-send-mode-reader()"Send the MODE READER command to the nntp server.This function is supposed to be called from `nntp-server-opened-hook'.It will make innd servers spawn an nnrpd process to allow actual articlereading."(nntp-send-command"^.*\r?\n""MODE READER"))(defunnntp-send-nosy-authinfo()"Send the AUTHINFO to the nntp server.This function is supposed to be called from `nntp-server-opened-hook'.It will prompt for a password."(nntp-send-command"^.*\r?\n""AUTHINFO USER"(read-string"NNTP user name: "))(nntp-send-command"^.*\r?\n""AUTHINFO PASS"(read-string"NNTP password: ")))(defunnntp-send-authinfo()"Send the AUTHINFO to the nntp server.This function is supposed to be called from `nntp-server-opened-hook'.It will prompt for a password."(nntp-send-command"^.*\r?\n""AUTHINFO USER"(user-login-name))(nntp-send-command"^.*\r?\n""AUTHINFO PASS"(read-string"NNTP password: ")))(defunnntp-send-authinfo-from-file()"Send the AUTHINFO to the nntp server.This function is supposed to be called from `nntp-server-opened-hook'.It will prompt for a password."(when(file-exists-p"~/.nntp-authinfo")(save-excursion(set-buffer(get-buffer-create" *authinfo*"))(buffer-disable-undo(current-buffer))(erase-buffer)(insert-file-contents"~/.nntp-authinfo")(goto-char(point-min))(nntp-send-command"^.*\r?\n""AUTHINFO USER"(user-login-name))(nntp-send-command"^.*\r?\n""AUTHINFO PASS"(buffer-substring(point)(progn(end-of-line)(point))))(kill-buffer(current-buffer)))))(defunnntp-default-sentinel(procstatus)"Default sentinel function for NNTP server process."(let((servers(cddr(assq'nntpnnoo-state-alist)))server);; Go through the alist of server names and find the name of the;; server that the process that sent the signal is connected to.;; If you get my drift.(if(equalprocnntp-server-process)(setqservernntp-address)(while(andservers(not(equalproc(cdr(assq'nntp-server-process(carservers))))))(setqservers(cdrservers)))(setqserver(caarservers)))(when(andservernntp-warn-about-losing-connection)(nnheader-message3"nntp: Connection closed to server %s"server)(setqnntp-current-group"")(ding))))(defunnntp-kill-connection(server)"Choke the connection to SERVER."(let((proc(cdr(assq'nntp-server-process(assocserver(cddr(assq'nntpnnoo-state-alist)))))))(whenproc(delete-process(process-nameproc)))(nntp-close-serverserver)(nnheader-report'nntp(message"Connection timed out to server %s"server))(ding)(sit-for1)));; Encoding and decoding of NNTP text.(defunnntp-decode-text()"Decode text transmitted by NNTP.0. Delete status line.1. Delete `^M' at end of line.2. Delete `.' at end of buffer (end of text mark).3. Delete `.' at beginning of line."(save-excursion(set-buffernntp-server-buffer);; Insert newline at end of buffer.(goto-char(point-max))(or(bolp)(insert"\n"));; Delete status line.(delete-region(goto-char(point-min))(progn(forward-line1)(point)));; Delete `^M's.(while(search-forward"\r"nilt)(replace-match""tt));; Delete `.' at end of the buffer (end of text mark).(goto-char(point-max))(forward-line-1)(when(looking-at"^\\.\n")(delete-region(point)(progn(forward-line1)(point))));; Replace `..' at beginning of line with `.'.(goto-char(point-min));; (replace-regexp "^\\.\\." ".")(while(search-forward"\n.."nilt)(delete-char-1))))(defunnntp-encode-text()"Encode text in current buffer for NNTP transmission.1. Insert `.' at beginning of line.2. Insert `.' at end of buffer (end of text mark)."(save-excursion;; Replace `.' at beginning of line with `..'.(goto-char(point-min))(while(search-forward"\n."nilt)(insert"."))(goto-char(point-max));; Insert newline at end of buffer.(or(bolp)(insert"\n"));; Insert `.' at end of buffer (end of text mark).(insert"."nntp-end-of-line)));;;;;; Synchronous Communication with NNTP servers.;;;(defvarnntp-retry-command)(defunnntp-send-command(responsecmd&restargs)"Wait for server RESPONSE after sending CMD and optional ARGS to server."(let((timer(andnntp-command-timeout(nnheader-run-at-timenntp-command-timeoutnil'nntp-kill-command(nnoo-current-server'nntp))))(nntp-retry-commandt)result)(unwind-protect(save-excursion(whilenntp-retry-command(setqnntp-retry-commandnil);; Clear communication buffer.(set-buffernntp-server-buffer)(widen)(erase-buffer)(ifnntp-retry-on-break(condition-case()(progn(apply'nntp-send-strings-to-servercmdargs)(setqresult(ifresponse(nntp-wait-for-responseresponse)t)))(quit(setqnntp-retry-commandt)))(apply'nntp-send-strings-to-servercmdargs)(setqresult(ifresponse(nntp-wait-for-responseresponse)t))))result)(whentimer(nnheader-cancel-timertimer)))))(defunnntp-kill-command(server)"Kill and restart the connection to SERVER."(let((proc(cdr(assq'nntp-server-process(assocserver(cddr(assq'nntpnnoo-state-alist)))))))(whenproc(delete-process(process-nameproc)))(nntp-close-serverserver)(nntp-open-serverserver)(whennntp-current-group(nntp-request-groupnntp-current-group))(setqnntp-retry-commandt)))(defunnntp-send-command-old(responsecmd&restargs)"Wait for server RESPONSE after sending CMD and optional ARGS to server."(save-excursion;; Clear communication buffer.(set-buffernntp-server-buffer)(erase-buffer)(apply'nntp-send-strings-to-servercmdargs)(ifresponse(nntp-wait-for-responseresponse)t)))(defunnntp-wait-for-response(regexp&optionalslow)"Wait for server response which matches REGEXP."(save-excursion(let((statust)(waitt)(dotnum0);Number of "." being displayed.(dotsize;How often "." displayed.(if(numberpnntp-debug-read)nntp-debug-read10000)))(set-buffernntp-server-buffer);; Wait for status response (RFC977).;; 1xx - Informative message.;; 2xx - Command ok.;; 3xx - Command ok so far, send the rest of it.;; 4xx - Command was correct, but couldn't be performed for some;; reason.;; 5xx - Command unimplemented, or incorrect, or a serious;; program error occurred.(nntp-accept-response)(whilewait(goto-char(point-min))(ifslow(progn(cond((re-search-forward"^[23][0-9][0-9]"nilt)(setqwaitnil))((re-search-forward"^[45][0-9][0-9]"nilt)(setqstatusnil)(setqwaitnil))(t(nntp-accept-response)))(if(notwait)(delete-region(point-min)(progn(beginning-of-line)(point)))))(cond((looking-at"[23]")(setqwaitnil))((looking-at"[45]")(setqstatusnil)(setqwaitnil))(t(nntp-accept-response)))));; Save status message.(end-of-line)(setqnntp-status-string(nnheader-replace-chars-in-string(buffer-substring(point-min)(point))?\r?))(whenstatus(setqwaitt)(whilewait(goto-char(point-max))(if(bolp)(forward-line-1)(beginning-of-line))(if(looking-atregexp)(setqwaitnil)(whennntp-debug-read(let((newnum(/(buffer-size)dotsize))(message-log-maxnil))(unless(=dotnumnewnum)(setqdotnumnewnum)(nnheader-message7"NNTP: Reading %s"(make-stringdotnum?.)))))(nntp-accept-response)));; Remove "...".(when(andnntp-debug-read(>dotnum0))(message""));; Successfully received server response.t))));;;;;; Low-Level Interface to NNTP Server.;;; (defunnntp-find-group-and-number()(save-excursion(save-restriction(set-buffernntp-server-buffer)(narrow-to-region(goto-char(point-min))(or(search-forward"\n\n"nilt)(point-max)))(goto-char(point-min));; We first find the number by looking at the status line.(let((number(and(looking-at"2[0-9][0-9] +\\([0-9]+\\) ")(string-to-int(buffer-substring(match-beginning1)(match-end1)))))groupnewsgroupsxref)(andnumber(zeropnumber)(setqnumbernil));; Then we find the group name.(setqgroup(cond;; If there is only one group in the Newsgroups header,;; then it seems quite likely that this article comes;; from that group, I'd say.((and(setqnewsgroups(mail-fetch-field"newsgroups"))(not(string-match","newsgroups)))newsgroups);; If there is more than one group in the Newsgroups;; header, then the Xref header should be filled out.;; We hazard a guess that the group that has this;; article number in the Xref header is the one we are;; looking for. This might very well be wrong if this;; article happens to have the same number in several;; groups, but that's life. ((and(setqxref(mail-fetch-field"xref"))number(string-match(format"\\([^ :]+\\):%d"number)xref))(substringxref(match-beginning1)(match-end1)))(t"")))(when(string-match"\r"group)(setqgroup(substringgroup0(match-beginning0))))(consgroupnumber)))))(defunnntp-retrieve-headers-with-xover(articles&optionalfetch-old)(erase-buffer)(cond;; This server does not talk NOV.((notnntp-server-xover)nil);; We don't care about gaps.((or(notnntp-nov-gap)fetch-old)(nntp-send-xover-command(iffetch-old(if(numberpfetch-old)(max1(-(cararticles)fetch-old))1)(cararticles))(nntp-last-elementarticles)'wait)(goto-char(point-min))(when(looking-at"[1-5][0-9][0-9] ")(delete-region(point)(progn(forward-line1)(point))))(while(search-forward"\r"nilt)(replace-match""tt))(goto-char(point-max))(forward-line-1)(when(looking-at"\\.")(delete-region(point)(progn(forward-line1)(point)))));; We do it the hard way. For each gap, an XOVER command is sent;; to the server. We do not wait for a reply from the server, we;; just send them off as fast as we can. That means that we have;; to count the number of responses we get back to find out when we;; have gotten all we asked for.((numberpnntp-nov-gap)(let((count0)(received0)(last-point(point-min))(buf(current-buffer))first);; We have to check `nntp-server-xover'. If it gets set to nil,;; that means that the server does not understand XOVER, but we;; won't know that until we try.(while(andnntp-server-xoverarticles)(setqfirst(cararticles));; Search forward until we find a gap, or until we run out of;; articles. (while(and(cdrarticles)(<(-(nth1articles)(cararticles))nntp-nov-gap))(setqarticles(cdrarticles)))(when(nntp-send-xover-commandfirst(cararticles))(setqarticles(cdrarticles)count(1+count));; Every 400 requests we have to read the stream in;; order to avoid deadlocks.(when(or(nullarticles);All requests have been sent.(zerop(%countnntp-maximum-request)))(accept-process-output);; On some Emacs versions the preceding function has;; a tendency to change the buffer. Perhaps. It's;; quite difficult to reproduce, because it only;; seems to happen once in a blue moon. (set-bufferbuf)(while(progn(goto-charlast-point);; Count replies.(while(re-search-forward"^[0-9][0-9][0-9] "nilt)(setqreceived(1+received)))(setqlast-point(point))(<receivedcount))(accept-process-output)(set-bufferbuf)))))(whennntp-server-xover;; Wait for the reply from the final command.(goto-char(point-max))(re-search-backward"^[0-9][0-9][0-9] "nilt)(when(looking-at"^[23]")(while(progn(goto-char(point-max))(forward-line-1)(not(looking-at"^\\.\r?\n")))(nntp-accept-response)));; We remove any "." lines and status lines.(goto-char(point-min))(while(search-forward"\r"nilt)(delete-char-1))(goto-char(point-min))(delete-matching-lines"^\\.$\\|^[1-5][0-9][0-9] ")))))nntp-server-xover)(defunnntp-send-xover-command(begend&optionalwait-for-reply)"Send the XOVER command to the server."(let((range(format"%d-%d"(orbeg1)(orendbeg1))))(if(stringpnntp-server-xover);; If `nntp-server-xover' is a string, then we just send this;; command.(ifwait-for-reply(nntp-send-command"^\\.\r?\n"nntp-server-xoverrange);; We do not wait for the reply.(nntp-send-strings-to-servernntp-server-xoverrange))(let((commandsnntp-xover-commands));; `nntp-xover-commands' is a list of possible XOVER commands.;; We try them all until we get at positive response. (while(andcommands(eqnntp-server-xover'try))(nntp-send-command"^\\.\r?\n"(carcommands)range)(save-excursion(set-buffernntp-server-buffer)(goto-char(point-min))(and(looking-at"[23]"); No error message.;; We also have to look at the lines. Some buggy;; servers give back simple lines with just the;; article number. How... helpful.(progn(forward-line1)(looking-at"[0-9]+\t...")); More text after number.(setqnntp-server-xover(carcommands))))(setqcommands(cdrcommands)));; If none of the commands worked, we disable XOVER.(when(eqnntp-server-xover'try)(save-excursion(set-buffernntp-server-buffer)(erase-buffer)(setqnntp-server-xovernil)))nntp-server-xover))))(defunnntp-send-strings-to-server(&reststrings)"Send STRINGS to the server."(let((cmd(concat(mapconcat'identitystrings" ")nntp-end-of-line)));; We open the nntp server if it is down.(or(nntp-server-opened(nnoo-current-server'nntp))(nntp-open-server(nnoo-current-server'nntp))(error(nntp-status-message)));; Send the strings.(process-send-stringnntp-server-processcmd)t))(defunnntp-send-region-to-server(beginend)"Send the current buffer region (from BEGIN to END) to the server."(save-excursion(let((cur(current-buffer)));; Copy the buffer over to the send buffer.(nnheader-set-temp-buffer" *nntp send*")(insert-buffer-substringcurbeginend)(save-excursion(set-buffercur)(erase-buffer));; `process-send-region' does not work if the text to be sent is very;; large, so we send it piecemeal.(let((last(point-min))(size100));Size of text sent at once.(while(and(/=last(point-max))(memq(process-statusnntp-server-process)'(openrun)))(process-send-regionnntp-server-processlast(setqlast(min(+lastsize)(point-max))));; Read any output from the server. May be unnecessary.(accept-process-output)))(kill-buffer(current-buffer)))))(defunnntp-open-server-semi-internal(server&optionalservice)"Open SERVER.If SERVER is nil, use value of environment variable `NNTPSERVER'.If SERVICE, this this as the port number."(nnheader-insert"")(let((server(orserver(getenv"NNTPSERVER")))(statusnil)(timer(andnntp-connection-timeout(nnheader-run-at-timenntp-connection-timeoutnil'nntp-kill-connectionserver))))(save-excursion(set-buffernntp-server-buffer)(setqnntp-status-string"")(nnheader-message5"nntp: Connecting to server on %s..."nntp-address)(cond((andserver(nntp-open-server-internalserverservice))(setqnntp-addressserver)(setqstatus(condition-casenil(nntp-wait-for-response"^[23].*\r?\n"'slow)(errornil)(quitnil)))(unlessstatus(nntp-close-server-internalserver)(nnheader-report'nntp"Couldn't open connection to %s"(if(andnntp-address(not(equalnntp-address"")))nntp-addressserver)))(whennntp-server-process(set-process-sentinelnntp-server-process'nntp-default-sentinel);; You can send commands at startup like AUTHINFO here.;; Added by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>(run-hooks'nntp-server-opened-hook)))((nullserver)(nnheader-report'nntp"NNTP server is not specified."))(t; We couldn't open the server.(nnheader-report'nntp(buffer-substring(point-min)(point-max)))))(whentimer(nnheader-cancel-timertimer))(message"")(unlessstatus(nnoo-close-server'nntpserver)(setqnntp-async-numbernil))status)))(defvarnntp-default-directories'("~""/tmp""/")"Directories to as current directory in the nntp server buffer.")(defunnntp-open-server-internal(server&optionalservice)"Open connection to news server on SERVER by SERVICE (default is nntp)."(let(proc)(save-excursion(set-buffernntp-server-buffer);; Make sure we have a valid current directory for the;; nntp server buffer.(unless(file-exists-pdefault-directory)(let((dirsnntp-default-directories))(whiledirs(when(file-exists-p(cardirs))(setqdefault-directory(cardirs)dirsnil))(setqdirs(cdrdirs)))))(cond((and(setqproc(condition-casenil(funcallnntp-open-server-functionserver)(errornil)))(memq(process-statusproc)'(openrun)))(setqnntp-server-processproc)(setqnntp-addressserver);; Suggested by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.(process-kill-without-queryproc)(run-hooks'nntp-server-hook)(pushprocnntp-opened-connections)(condition-case()(nntp-read-server-type)(error(nnheader-report'nntp"Couldn't open server %s"server)(nntp-close-server)))nntp-server-process)(t(nnheader-report'nntp"Couldn't open server %s"server))))))(defunnntp-read-server-type()"Find out what the name of the server we have connected to is.";; Wait for the status string to arrive.(nntp-wait-for-response"^.*\n"t)(setqnntp-server-type(buffer-string))(let((alistnntp-server-action-alist)entry);; Run server-specific commmands.(whilealist(setqentry(popalist))(when(string-match(carentry)nntp-server-type)(if(and(listp(cadrentry))(not(eq'lambda(caadrentry))))(eval(cadrentry))(funcall(cadrentry)))))))(defunnntp-open-network-stream(server)(open-network-stream"nntpd"nntp-server-bufferservernntp-port-number))(defunnntp-open-rlogin(server)(let((proc(ifnntp-rlogin-user-name(start-process"nntpd"nntp-server-buffer"rsh""-l"nntp-rlogin-user-nameserver(mapconcat'identitynntp-rlogin-parameters" "))(start-process"nntpd"nntp-server-buffer"rsh"server(mapconcat'identitynntp-rlogin-parameters" ")))))proc))(defunnntp-telnet-to-machine()(let(b)(telnet"localhost")(goto-char(point-min))(while(not(re-search-forward"^login: *"nilt))(sit-for1)(goto-char(point-min)))(goto-char(point-max))(insert"larsi")(telnet-send-input)(setqb(point))(while(not(re-search-forward">"nilt))(sit-for1)(goto-charb))(goto-char(point-max))(insert"ls")(telnet-send-input)))(defunnntp-close-server-internal(&optionalserver)"Close connection to news server."(nntp-possibly-change-servernilserver)(ifnntp-server-process(delete-processnntp-server-process))(setqnntp-server-processnil)(setqnntp-address""))(defunnntp-accept-response()"Read response of server.It is well-known that the communication speed will be much improved bydefining this function as macro.";; To deal with server process exiting before;; accept-process-output is called.;; Suggested by Jason Venner <jason@violet.berkeley.edu>.;; This is a copy of `nntp-default-sentinel'.(let((buf(current-buffer)))(prog1(if(or(notnntp-server-process)(not(memq(process-statusnntp-server-process)'(openrun))))(error"nntp: Process connection closed; %s"(nntp-status-message))(ifnntp-buggy-select(progn;; We cannot use `accept-process-output'.;; Fujitsu UTS requires messages during sleep-for.;; I don't know why.(nnheader-message5"NNTP: Reading...")(sleep-for1)(nnheader-message5""))(condition-caseerrorcode(accept-process-outputnntp-server-process1)(error(cond((string-equal"select error: Invalid argument"(nth1errorcode));; Ignore select error.nil)(t(signal(carerrorcode)(cdrerrorcode))))))))(set-bufferbuf))))(defunnntp-last-element(list)"Return last element of LIST."(while(cdrlist)(setqlist(cdrlist)))(carlist))(defunnntp-possibly-change-server(newsgroupserver&optionalconnectionless)"Check whether the virtual server needs changing."(when(andserver(not(nntp-server-openedserver)));; This virtual server isn't open, so we (re)open it here.(nntp-open-serverservernilt))(when(andnewsgroup(not(equalnewsgroupnntp-current-group)));; Set the proper current group.(nntp-request-groupnewsgroupserver)))(defunnntp-try-list-active(group)(nntp-list-active-groupgroup)(save-excursion(set-buffernntp-server-buffer)(goto-char(point-min))(cond((looking-at"5[0-9]+")(setqnntp-server-list-active-groupnil))(t(setqnntp-server-list-active-groupt)))))(defunnntp-async-server-opened()(andnntp-async-process(memq(process-statusnntp-async-process)'(openrun))))(defunnntp-async-open-server()(save-excursion(set-buffer(generate-new-buffer" *async-nntp*"))(setqnntp-async-buffer(current-buffer))(buffer-disable-undo(current-buffer)))(let((nntp-server-processnil)(nntp-server-buffernntp-async-buffer))(nntp-open-server-semi-internalnntp-addressnntp-port-number)(if(not(setqnntp-async-processnntp-server-process))(progn(setqnntp-async-numbernil))(set-process-buffernntp-async-processnntp-async-buffer))))(defunnntp-async-fetch-articles(article)(if(stringparticle)()(let((articles(cdr(memq(assqarticlenntp-async-articles)nntp-async-articles)))(max(cond((numberpnntp-async-number)nntp-async-number)((eqnntp-async-numbert)(lengthnntp-async-articles))(t0)))nart)(while(and(>=(setqmax(1-max))0)articles)(or(memq(setqnart(caararticles))nntp-async-fetched)(progn(nntp-async-send-strings"ARTICLE "(int-to-stringnart))(setqnntp-async-fetched(consnartnntp-async-fetched))))(setqarticles(cdrarticles))))))(defunnntp-async-send-strings(&reststrings)(let((cmd(concat(mapconcat'identitystrings" ")nntp-end-of-line)))(or(nntp-async-server-opened)(nntp-async-open-server)(error(nntp-status-message)))(process-send-stringnntp-async-processcmd)))(defunnntp-async-request-group(group)(if(equalgroupnntp-current-group)()(let((asyncs(assocgroupnntp-async-group-alist)));; A new group has been selected, so we push the current state;; of async articles on an alist, and pull the old state off.(setqnntp-async-group-alist(cons(listnntp-current-groupnntp-async-articlesnntp-async-fetchednntp-async-process)(delqasyncsnntp-async-group-alist)))(andasyncs(progn(setqnntp-async-articles(nth1asyncs))(setqnntp-async-fetched(nth2asyncs))(setqnntp-async-process(nth3asyncs)))))))(provide'nntp);;; nntp.el ends here