blob: a266cbd08414314c807267f979e99a80b6b57e78 [file] [log] [blame]
Guido van Rossumc629d341992-11-05 10:43:02 +00001# An NNTP client class. Based on RFC 977: Network News Transfer
2# Protocol, by Brian Kantor and Phil Lapsley.
3
4
5# Example:
6#
Guido van Rossum18fc5691992-11-26 09:17:19 +00007# >>> from nntplib import NNTP
Guido van Rossum8421c4e1995-09-22 00:52:38 +00008# >>> s = NNTP('news')
9# >>> resp, count, first, last, name = s.group('comp.lang.python')
Guido van Rossumc629d341992-11-05 10:43:02 +000010# >>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last
Guido van Rossum8421c4e1995-09-22 00:52:38 +000011# Group comp.lang.python has 51 articles, range 5770 to 5821
Guido van Rossumc629d341992-11-05 10:43:02 +000012# >>> resp, subs = s.xhdr('subject', first + '-' + last)
13# >>> resp = s.quit()
14# >>>
15#
16# Here 'resp' is the server response line.
17# Error responses are turned into exceptions.
18#
19# To post an article from a file:
20# >>> f = open(filename, 'r') # file containing article, including header
21# >>> resp = s.post(f)
22# >>>
23#
24# For descriptions of all methods, read the comments in the code below.
25# Note that all arguments and return values representing article numbers
26# are strings, not numbers, since they are rarely used for calculations.
27
Guido van Rossum8421c4e1995-09-22 00:52:38 +000028# (xover, xgtitle, xpath, date methods by Kevan Heydon)
29
Guido van Rossumc629d341992-11-05 10:43:02 +000030
31# Imports
32import regex
33import socket
34import string
35
36
Guido van Rossum18fc5691992-11-26 09:17:19 +000037# Exception raised when an error or invalid response is received
Guido van Rossumc629d341992-11-05 10:43:02 +000038
Guido van Rossum18fc5691992-11-26 09:17:19 +000039error_reply = 'nntplib.error_reply' # unexpected [123]xx reply
40error_temp = 'nntplib.error_temp' # 4xx errors
41error_perm = 'nntplib.error_perm' # 5xx errors
42error_proto = 'nntplib.error_proto' # response does not begin with [1-5]
Guido van Rossum8421c4e1995-09-22 00:52:38 +000043error_data = 'nntplib.error_data' # error in response data
Guido van Rossumc629d341992-11-05 10:43:02 +000044
45
46# Standard port used by NNTP servers
47NNTP_PORT = 119
48
49
50# Response numbers that are followed by additional text (e.g. article)
Guido van Rossum8421c4e1995-09-22 00:52:38 +000051LONGRESP = ['100', '215', '220', '221', '222', '224', '230', '231', '282']
Guido van Rossumc629d341992-11-05 10:43:02 +000052
53
54# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
55CRLF = '\r\n'
56
57
58# The class itself
59
60class NNTP:
61
62 # Initialize an instance. Arguments:
63 # - host: hostname to connect to
64 # - port: port to connect to (default the standard NNTP port)
65
Guido van Rossumdd659751997-10-20 23:29:44 +000066 def __init__(self, host, port = NNTP_PORT, user=None, password=None):
Guido van Rossumc629d341992-11-05 10:43:02 +000067 self.host = host
68 self.port = port
69 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
70 self.sock.connect(self.host, self.port)
Jack Jansen2bb57b81996-02-14 16:06:24 +000071 self.file = self.sock.makefile('rb')
Guido van Rossumc629d341992-11-05 10:43:02 +000072 self.debugging = 0
73 self.welcome = self.getresp()
Guido van Rossumdd659751997-10-20 23:29:44 +000074 if user:
75 resp = self.shortcmd('authinfo user '+user)
76 if resp[:3] == '381':
77 if not password:
78 raise error_reply, resp
79 else:
80 resp = self.shortcmd('authinfo pass '+password)
81 if resp[:3] != '281':
82 raise error_perm, resp
Guido van Rossumc629d341992-11-05 10:43:02 +000083
84 # Get the welcome message from the server
Guido van Rossum7bc817d1993-12-17 15:25:27 +000085 # (this is read and squirreled away by __init__()).
Guido van Rossumc629d341992-11-05 10:43:02 +000086 # If the response code is 200, posting is allowed;
87 # if it 201, posting is not allowed
88
89 def getwelcome(self):
90 if self.debugging: print '*welcome*', `self.welcome`
91 return self.welcome
92
93 # Set the debugging level. Argument level means:
94 # 0: no debugging output (default)
95 # 1: print commands and responses but not body text etc.
96 # 2: also print raw lines read and sent before stripping CR/LF
97
Guido van Rossumcf5394f1995-03-30 10:42:34 +000098 def set_debuglevel(self, level):
Guido van Rossumc629d341992-11-05 10:43:02 +000099 self.debugging = level
Guido van Rossumcf5394f1995-03-30 10:42:34 +0000100 debug = set_debuglevel
Guido van Rossumc629d341992-11-05 10:43:02 +0000101
102 # Internal: send one line to the server, appending CRLF
103 def putline(self, line):
104 line = line + CRLF
105 if self.debugging > 1: print '*put*', `line`
106 self.sock.send(line)
107
108 # Internal: send one command to the server (through putline())
109 def putcmd(self, line):
110 if self.debugging: print '*cmd*', `line`
111 self.putline(line)
112
113 # Internal: return one line from the server, stripping CRLF.
114 # Raise EOFError if the connection is closed
115 def getline(self):
116 line = self.file.readline()
117 if self.debugging > 1:
118 print '*get*', `line`
119 if not line: raise EOFError
120 if line[-2:] == CRLF: line = line[:-2]
121 elif line[-1:] in CRLF: line = line[:-1]
122 return line
123
124 # Internal: get a response from the server.
125 # Raise various errors if the response indicates an error
126 def getresp(self):
127 resp = self.getline()
128 if self.debugging: print '*resp*', `resp`
129 c = resp[:1]
130 if c == '4':
Guido van Rossum18fc5691992-11-26 09:17:19 +0000131 raise error_temp, resp
Guido van Rossumc629d341992-11-05 10:43:02 +0000132 if c == '5':
Guido van Rossum18fc5691992-11-26 09:17:19 +0000133 raise error_perm, resp
Guido van Rossumc629d341992-11-05 10:43:02 +0000134 if c not in '123':
Guido van Rossum18fc5691992-11-26 09:17:19 +0000135 raise error_proto, resp
Guido van Rossumc629d341992-11-05 10:43:02 +0000136 return resp
137
138 # Internal: get a response plus following text from the server.
139 # Raise various errors if the response indicates an error
140 def getlongresp(self):
141 resp = self.getresp()
142 if resp[:3] not in LONGRESP:
143 raise error_reply, resp
144 list = []
145 while 1:
146 line = self.getline()
147 if line == '.':
148 break
Guido van Rossume2ed9df1997-08-26 23:26:18 +0000149 if line[:2] == '..':
150 line = line[1:]
Guido van Rossumc629d341992-11-05 10:43:02 +0000151 list.append(line)
152 return resp, list
153
154 # Internal: send a command and get the response
155 def shortcmd(self, line):
156 self.putcmd(line)
157 return self.getresp()
158
159 # Internal: send a command and get the response plus following text
160 def longcmd(self, line):
161 self.putcmd(line)
162 return self.getlongresp()
163
164 # Process a NEWGROUPS command. Arguments:
165 # - date: string 'yymmdd' indicating the date
166 # - time: string 'hhmmss' indicating the time
167 # Return:
168 # - resp: server response if succesful
169 # - list: list of newsgroup names
170
171 def newgroups(self, date, time):
172 return self.longcmd('NEWGROUPS ' + date + ' ' + time)
173
174 # Process a NEWNEWS command. Arguments:
175 # - group: group name or '*'
176 # - date: string 'yymmdd' indicating the date
177 # - time: string 'hhmmss' indicating the time
178 # Return:
179 # - resp: server response if succesful
180 # - list: list of article ids
181
182 def newnews(self, group, date, time):
183 cmd = 'NEWNEWS ' + group + ' ' + date + ' ' + time
184 return self.longcmd(cmd)
185
186 # Process a LIST command. Return:
187 # - resp: server response if succesful
Guido van Rossumbe9f2121995-01-10 10:35:55 +0000188 # - list: list of (group, last, first, flag) (strings)
Guido van Rossumc629d341992-11-05 10:43:02 +0000189
190 def list(self):
191 resp, list = self.longcmd('LIST')
192 for i in range(len(list)):
Guido van Rossumbe9f2121995-01-10 10:35:55 +0000193 # Parse lines into "group last first flag"
Guido van Rossumc6995531997-03-14 04:18:20 +0000194 list[i] = tuple(string.split(list[i]))
Guido van Rossumc629d341992-11-05 10:43:02 +0000195 return resp, list
196
197 # Process a GROUP command. Argument:
198 # - group: the group name
199 # Returns:
200 # - resp: server response if succesful
201 # - count: number of articles (string)
202 # - first: first article number (string)
203 # - last: last article number (string)
204 # - name: the group name
205
206 def group(self, name):
207 resp = self.shortcmd('GROUP ' + name)
208 if resp[:3] <> '211':
209 raise error_reply, resp
210 words = string.split(resp)
211 count = first = last = 0
212 n = len(words)
213 if n > 1:
214 count = words[1]
215 if n > 2:
216 first = words[2]
217 if n > 3:
218 last = words[3]
219 if n > 4:
220 name = string.lower(words[4])
221 return resp, count, first, last, name
222
223 # Process a HELP command. Returns:
224 # - resp: server response if succesful
225 # - list: list of strings
226
227 def help(self):
228 return self.longcmd('HELP')
229
230 # Internal: parse the response of a STAT, NEXT or LAST command
231 def statparse(self, resp):
232 if resp[:2] <> '22':
233 raise error_reply, resp
234 words = string.split(resp)
235 nr = 0
236 id = ''
237 n = len(words)
238 if n > 1:
239 nr = words[1]
240 if n > 2:
241 id = string.lower(words[2])
242 return resp, nr, id
243
244 # Internal: process a STAT, NEXT or LAST command
245 def statcmd(self, line):
246 resp = self.shortcmd(line)
247 return self.statparse(resp)
248
249 # Process a STAT command. Argument:
250 # - id: article number or message id
251 # Returns:
252 # - resp: server response if succesful
253 # - nr: the article number
254 # - id: the article id
255
256 def stat(self, id):
257 return self.statcmd('STAT ' + id)
258
259 # Process a NEXT command. No arguments. Return as for STAT
260
261 def next(self):
262 return self.statcmd('NEXT')
263
264 # Process a LAST command. No arguments. Return as for STAT
265
266 def last(self):
267 return self.statcmd('LAST')
268
269 # Internal: process a HEAD, BODY or ARTICLE command
270 def artcmd(self, line):
271 resp, list = self.longcmd(line)
272 resp, nr, id = self.statparse(resp)
273 return resp, nr, id, list
274
275 # Process a HEAD command. Argument:
276 # - id: article number or message id
277 # Returns:
278 # - resp: server response if succesful
279 # - list: the lines of the article's header
280
281 def head(self, id):
282 return self.artcmd('HEAD ' + id)
283
284 # Process a BODY command. Argument:
285 # - id: article number or message id
286 # Returns:
287 # - resp: server response if succesful
288 # - list: the lines of the article's body
289
290 def body(self, id):
291 return self.artcmd('BODY ' + id)
292
293 # Process an ARTICLE command. Argument:
294 # - id: article number or message id
295 # Returns:
296 # - resp: server response if succesful
297 # - list: the lines of the article
298
299 def article(self, id):
300 return self.artcmd('ARTICLE ' + id)
301
302 # Process a SLAVE command. Returns:
303 # - resp: server response if succesful
304
305 def slave(self):
306 return self.shortcmd('SLAVE')
307
308 # Process an XHDR command (optional server extension). Arguments:
309 # - hdr: the header type (e.g. 'subject')
310 # - str: an article nr, a message id, or a range nr1-nr2
311 # Returns:
312 # - resp: server response if succesful
313 # - list: list of (nr, value) strings
314
315 def xhdr(self, hdr, str):
316 resp, lines = self.longcmd('XHDR ' + hdr + ' ' + str)
317 for i in range(len(lines)):
318 line = lines[i]
319 n = regex.match('^[0-9]+', line)
320 nr = line[:n]
321 if n < len(line) and line[n] == ' ': n = n+1
322 lines[i] = (nr, line[n:])
323 return resp, lines
324
Guido van Rossum8421c4e1995-09-22 00:52:38 +0000325 # Process an XOVER command (optional server extension) Arguments:
326 # - start: start of range
327 # - end: end of range
328 # Returns:
329 # - resp: server response if succesful
330 # - list: list of (art-nr, subject, poster, date, id, refrences, size, lines)
331
332 def xover(self,start,end):
333 resp, lines = self.longcmd('XOVER ' + start + '-' + end)
334 xover_lines = []
335 for line in lines:
336 elem = string.splitfields(line,"\t")
337 try:
Guido van Rossumc3fb88b1997-07-17 15:21:52 +0000338 xover_lines.append((elem[0],
339 elem[1],
340 elem[2],
341 elem[3],
342 elem[4],
343 string.split(elem[5]),
344 elem[6],
345 elem[7]))
Guido van Rossum8421c4e1995-09-22 00:52:38 +0000346 except IndexError:
347 raise error_data,line
348 return resp,xover_lines
349
350 # Process an XGTITLE command (optional server extension) Arguments:
351 # - group: group name wildcard (i.e. news.*)
352 # Returns:
353 # - resp: server response if succesful
354 # - list: list of (name,title) strings
355
356 def xgtitle(self, group):
357 line_pat = regex.compile("^\([^ \t]+\)[ \t]+\(.*\)$")
358 resp, raw_lines = self.longcmd('XGTITLE ' + group)
359 lines = []
360 for raw_line in raw_lines:
361 if line_pat.search(string.strip(raw_line)) == 0:
362 lines.append(line_pat.group(1),
363 line_pat.group(2))
364
365 return resp, lines
366
367 # Process an XPATH command (optional server extension) Arguments:
368 # - id: Message id of article
369 # Returns:
370 # resp: server response if succesful
371 # path: directory path to article
372
373 def xpath(self,id):
374 resp = self.shortcmd("XPATH " + id)
375 if resp[:3] <> '223':
376 raise error_reply, resp
377 try:
378 [resp_num, path] = string.split(resp)
379 except ValueError:
380 raise error_reply, resp
381 else:
382 return resp, path
383
384 # Process the DATE command. Arguments:
385 # None
386 # Returns:
387 # resp: server response if succesful
388 # date: Date suitable for newnews/newgroups commands etc.
389 # time: Time suitable for newnews/newgroups commands etc.
390
391 def date (self):
392 resp = self.shortcmd("DATE")
393 if resp[:3] <> '111':
394 raise error_reply, resp
395 elem = string.split(resp)
396 if len(elem) != 2:
397 raise error_data, resp
398 date = elem[1][2:8]
399 time = elem[1][-6:]
400 if len(date) != 6 or len(time) != 6:
401 raise error_data, resp
402 return resp, date, time
403
404
Guido van Rossumc629d341992-11-05 10:43:02 +0000405 # Process a POST command. Arguments:
406 # - f: file containing the article
407 # Returns:
408 # - resp: server response if succesful
409
410 def post(self, f):
411 resp = self.shortcmd('POST')
412 # Raises error_??? if posting is not allowed
413 if resp[0] <> '3':
414 raise error_reply, resp
415 while 1:
416 line = f.readline()
417 if not line:
418 break
419 if line[-1] == '\n':
420 line = line[:-1]
Guido van Rossume2ed9df1997-08-26 23:26:18 +0000421 if line[:1] == '.':
422 line = '.' + line
Guido van Rossumc629d341992-11-05 10:43:02 +0000423 self.putline(line)
424 self.putline('.')
425 return self.getresp()
426
427 # Process an IHAVE command. Arguments:
428 # - id: message-id of the article
429 # - f: file containing the article
430 # Returns:
431 # - resp: server response if succesful
432 # Note that if the server refuses the article an exception is raised
433
434 def ihave(self, id, f):
435 resp = self.shortcmd('IHAVE ' + id)
Guido van Rossum18fc5691992-11-26 09:17:19 +0000436 # Raises error_??? if the server already has it
Guido van Rossumc629d341992-11-05 10:43:02 +0000437 if resp[0] <> '3':
438 raise error_reply, resp
439 while 1:
440 line = f.readline()
441 if not line:
442 break
443 if line[-1] == '\n':
444 line = line[:-1]
Guido van Rossume2ed9df1997-08-26 23:26:18 +0000445 if line[:1] == '.':
446 line = '.' + line
Guido van Rossumc629d341992-11-05 10:43:02 +0000447 self.putline(line)
448 self.putline('.')
449 return self.getresp()
450
451 # Process a QUIT command and close the socket. Returns:
452 # - resp: server response if succesful
453
454 def quit(self):
455 resp = self.shortcmd('QUIT')
456 self.file.close()
457 self.sock.close()
458 del self.file, self.sock
459 return resp
Guido van Rossume2ed9df1997-08-26 23:26:18 +0000460
461
462# Minimal test function
463def _test():
464 s = NNTP('news')
465 resp, count, first, last, name = s.group('comp.lang.python')
466 print resp
467 print 'Group', name, 'has', count, 'articles, range', first, 'to', last
468 resp, subs = s.xhdr('subject', first + '-' + last)
469 print resp
470 for item in subs:
471 print "%7s %s" % item
472 resp = s.quit()
473 print resp
474
475
476# Run the test when run as a script
477if __name__ == '__main__':
478 _test()