PageRenderTime 55ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/lib-python/2.7/nntplib.py

https://bitbucket.org/bwesterb/pypy
Python | 627 lines | 618 code | 0 blank | 9 comment | 0 complexity | 50e07036ae7b2800e1e917c05bff1948 MD5 | raw file
  1. """An NNTP client class based on RFC 977: Network News Transfer Protocol.
  2. Example:
  3. >>> from nntplib import NNTP
  4. >>> s = NNTP('news')
  5. >>> resp, count, first, last, name = s.group('comp.lang.python')
  6. >>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last
  7. Group comp.lang.python has 51 articles, range 5770 to 5821
  8. >>> resp, subs = s.xhdr('subject', first + '-' + last)
  9. >>> resp = s.quit()
  10. >>>
  11. Here 'resp' is the server response line.
  12. Error responses are turned into exceptions.
  13. To post an article from a file:
  14. >>> f = open(filename, 'r') # file containing article, including header
  15. >>> resp = s.post(f)
  16. >>>
  17. For descriptions of all methods, read the comments in the code below.
  18. Note that all arguments and return values representing article numbers
  19. are strings, not numbers, since they are rarely used for calculations.
  20. """
  21. # RFC 977 by Brian Kantor and Phil Lapsley.
  22. # xover, xgtitle, xpath, date methods by Kevan Heydon
  23. # Imports
  24. import re
  25. import socket
  26. __all__ = ["NNTP","NNTPReplyError","NNTPTemporaryError",
  27. "NNTPPermanentError","NNTPProtocolError","NNTPDataError",
  28. "error_reply","error_temp","error_perm","error_proto",
  29. "error_data",]
  30. # Exceptions raised when an error or invalid response is received
  31. class NNTPError(Exception):
  32. """Base class for all nntplib exceptions"""
  33. def __init__(self, *args):
  34. Exception.__init__(self, *args)
  35. try:
  36. self.response = args[0]
  37. except IndexError:
  38. self.response = 'No response given'
  39. class NNTPReplyError(NNTPError):
  40. """Unexpected [123]xx reply"""
  41. pass
  42. class NNTPTemporaryError(NNTPError):
  43. """4xx errors"""
  44. pass
  45. class NNTPPermanentError(NNTPError):
  46. """5xx errors"""
  47. pass
  48. class NNTPProtocolError(NNTPError):
  49. """Response does not begin with [1-5]"""
  50. pass
  51. class NNTPDataError(NNTPError):
  52. """Error in response data"""
  53. pass
  54. # for backwards compatibility
  55. error_reply = NNTPReplyError
  56. error_temp = NNTPTemporaryError
  57. error_perm = NNTPPermanentError
  58. error_proto = NNTPProtocolError
  59. error_data = NNTPDataError
  60. # Standard port used by NNTP servers
  61. NNTP_PORT = 119
  62. # Response numbers that are followed by additional text (e.g. article)
  63. LONGRESP = ['100', '215', '220', '221', '222', '224', '230', '231', '282']
  64. # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
  65. CRLF = '\r\n'
  66. # The class itself
  67. class NNTP:
  68. def __init__(self, host, port=NNTP_PORT, user=None, password=None,
  69. readermode=None, usenetrc=True):
  70. """Initialize an instance. Arguments:
  71. - host: hostname to connect to
  72. - port: port to connect to (default the standard NNTP port)
  73. - user: username to authenticate with
  74. - password: password to use with username
  75. - readermode: if true, send 'mode reader' command after
  76. connecting.
  77. readermode is sometimes necessary if you are connecting to an
  78. NNTP server on the local machine and intend to call
  79. reader-specific commands, such as `group'. If you get
  80. unexpected NNTPPermanentErrors, you might need to set
  81. readermode.
  82. """
  83. self.host = host
  84. self.port = port
  85. self.sock = socket.create_connection((host, port))
  86. self.file = self.sock.makefile('rb')
  87. self.debugging = 0
  88. self.welcome = self.getresp()
  89. # 'mode reader' is sometimes necessary to enable 'reader' mode.
  90. # However, the order in which 'mode reader' and 'authinfo' need to
  91. # arrive differs between some NNTP servers. Try to send
  92. # 'mode reader', and if it fails with an authorization failed
  93. # error, try again after sending authinfo.
  94. readermode_afterauth = 0
  95. if readermode:
  96. try:
  97. self.welcome = self.shortcmd('mode reader')
  98. except NNTPPermanentError:
  99. # error 500, probably 'not implemented'
  100. pass
  101. except NNTPTemporaryError, e:
  102. if user and e.response[:3] == '480':
  103. # Need authorization before 'mode reader'
  104. readermode_afterauth = 1
  105. else:
  106. raise
  107. # If no login/password was specified, try to get them from ~/.netrc
  108. # Presume that if .netc has an entry, NNRP authentication is required.
  109. try:
  110. if usenetrc and not user:
  111. import netrc
  112. credentials = netrc.netrc()
  113. auth = credentials.authenticators(host)
  114. if auth:
  115. user = auth[0]
  116. password = auth[2]
  117. except IOError:
  118. pass
  119. # Perform NNRP authentication if needed.
  120. if user:
  121. resp = self.shortcmd('authinfo user '+user)
  122. if resp[:3] == '381':
  123. if not password:
  124. raise NNTPReplyError(resp)
  125. else:
  126. resp = self.shortcmd(
  127. 'authinfo pass '+password)
  128. if resp[:3] != '281':
  129. raise NNTPPermanentError(resp)
  130. if readermode_afterauth:
  131. try:
  132. self.welcome = self.shortcmd('mode reader')
  133. except NNTPPermanentError:
  134. # error 500, probably 'not implemented'
  135. pass
  136. # Get the welcome message from the server
  137. # (this is read and squirreled away by __init__()).
  138. # If the response code is 200, posting is allowed;
  139. # if it 201, posting is not allowed
  140. def getwelcome(self):
  141. """Get the welcome message from the server
  142. (this is read and squirreled away by __init__()).
  143. If the response code is 200, posting is allowed;
  144. if it 201, posting is not allowed."""
  145. if self.debugging: print '*welcome*', repr(self.welcome)
  146. return self.welcome
  147. def set_debuglevel(self, level):
  148. """Set the debugging level. Argument 'level' means:
  149. 0: no debugging output (default)
  150. 1: print commands and responses but not body text etc.
  151. 2: also print raw lines read and sent before stripping CR/LF"""
  152. self.debugging = level
  153. debug = set_debuglevel
  154. def putline(self, line):
  155. """Internal: send one line to the server, appending CRLF."""
  156. line = line + CRLF
  157. if self.debugging > 1: print '*put*', repr(line)
  158. self.sock.sendall(line)
  159. def putcmd(self, line):
  160. """Internal: send one command to the server (through putline())."""
  161. if self.debugging: print '*cmd*', repr(line)
  162. self.putline(line)
  163. def getline(self):
  164. """Internal: return one line from the server, stripping CRLF.
  165. Raise EOFError if the connection is closed."""
  166. line = self.file.readline()
  167. if self.debugging > 1:
  168. print '*get*', repr(line)
  169. if not line: raise EOFError
  170. if line[-2:] == CRLF: line = line[:-2]
  171. elif line[-1:] in CRLF: line = line[:-1]
  172. return line
  173. def getresp(self):
  174. """Internal: get a response from the server.
  175. Raise various errors if the response indicates an error."""
  176. resp = self.getline()
  177. if self.debugging: print '*resp*', repr(resp)
  178. c = resp[:1]
  179. if c == '4':
  180. raise NNTPTemporaryError(resp)
  181. if c == '5':
  182. raise NNTPPermanentError(resp)
  183. if c not in '123':
  184. raise NNTPProtocolError(resp)
  185. return resp
  186. def getlongresp(self, file=None):
  187. """Internal: get a response plus following text from the server.
  188. Raise various errors if the response indicates an error."""
  189. openedFile = None
  190. try:
  191. # If a string was passed then open a file with that name
  192. if isinstance(file, str):
  193. openedFile = file = open(file, "w")
  194. resp = self.getresp()
  195. if resp[:3] not in LONGRESP:
  196. raise NNTPReplyError(resp)
  197. list = []
  198. while 1:
  199. line = self.getline()
  200. if line == '.':
  201. break
  202. if line[:2] == '..':
  203. line = line[1:]
  204. if file:
  205. file.write(line + "\n")
  206. else:
  207. list.append(line)
  208. finally:
  209. # If this method created the file, then it must close it
  210. if openedFile:
  211. openedFile.close()
  212. return resp, list
  213. def shortcmd(self, line):
  214. """Internal: send a command and get the response."""
  215. self.putcmd(line)
  216. return self.getresp()
  217. def longcmd(self, line, file=None):
  218. """Internal: send a command and get the response plus following text."""
  219. self.putcmd(line)
  220. return self.getlongresp(file)
  221. def newgroups(self, date, time, file=None):
  222. """Process a NEWGROUPS command. Arguments:
  223. - date: string 'yymmdd' indicating the date
  224. - time: string 'hhmmss' indicating the time
  225. Return:
  226. - resp: server response if successful
  227. - list: list of newsgroup names"""
  228. return self.longcmd('NEWGROUPS ' + date + ' ' + time, file)
  229. def newnews(self, group, date, time, file=None):
  230. """Process a NEWNEWS command. Arguments:
  231. - group: group name or '*'
  232. - date: string 'yymmdd' indicating the date
  233. - time: string 'hhmmss' indicating the time
  234. Return:
  235. - resp: server response if successful
  236. - list: list of message ids"""
  237. cmd = 'NEWNEWS ' + group + ' ' + date + ' ' + time
  238. return self.longcmd(cmd, file)
  239. def list(self, file=None):
  240. """Process a LIST command. Return:
  241. - resp: server response if successful
  242. - list: list of (group, last, first, flag) (strings)"""
  243. resp, list = self.longcmd('LIST', file)
  244. for i in range(len(list)):
  245. # Parse lines into "group last first flag"
  246. list[i] = tuple(list[i].split())
  247. return resp, list
  248. def description(self, group):
  249. """Get a description for a single group. If more than one
  250. group matches ('group' is a pattern), return the first. If no
  251. group matches, return an empty string.
  252. This elides the response code from the server, since it can
  253. only be '215' or '285' (for xgtitle) anyway. If the response
  254. code is needed, use the 'descriptions' method.
  255. NOTE: This neither checks for a wildcard in 'group' nor does
  256. it check whether the group actually exists."""
  257. resp, lines = self.descriptions(group)
  258. if len(lines) == 0:
  259. return ""
  260. else:
  261. return lines[0][1]
  262. def descriptions(self, group_pattern):
  263. """Get descriptions for a range of groups."""
  264. line_pat = re.compile("^(?P<group>[^ \t]+)[ \t]+(.*)$")
  265. # Try the more std (acc. to RFC2980) LIST NEWSGROUPS first
  266. resp, raw_lines = self.longcmd('LIST NEWSGROUPS ' + group_pattern)
  267. if resp[:3] != "215":
  268. # Now the deprecated XGTITLE. This either raises an error
  269. # or succeeds with the same output structure as LIST
  270. # NEWSGROUPS.
  271. resp, raw_lines = self.longcmd('XGTITLE ' + group_pattern)
  272. lines = []
  273. for raw_line in raw_lines:
  274. match = line_pat.search(raw_line.strip())
  275. if match:
  276. lines.append(match.group(1, 2))
  277. return resp, lines
  278. def group(self, name):
  279. """Process a GROUP command. Argument:
  280. - group: the group name
  281. Returns:
  282. - resp: server response if successful
  283. - count: number of articles (string)
  284. - first: first article number (string)
  285. - last: last article number (string)
  286. - name: the group name"""
  287. resp = self.shortcmd('GROUP ' + name)
  288. if resp[:3] != '211':
  289. raise NNTPReplyError(resp)
  290. words = resp.split()
  291. count = first = last = 0
  292. n = len(words)
  293. if n > 1:
  294. count = words[1]
  295. if n > 2:
  296. first = words[2]
  297. if n > 3:
  298. last = words[3]
  299. if n > 4:
  300. name = words[4].lower()
  301. return resp, count, first, last, name
  302. def help(self, file=None):
  303. """Process a HELP command. Returns:
  304. - resp: server response if successful
  305. - list: list of strings"""
  306. return self.longcmd('HELP',file)
  307. def statparse(self, resp):
  308. """Internal: parse the response of a STAT, NEXT or LAST command."""
  309. if resp[:2] != '22':
  310. raise NNTPReplyError(resp)
  311. words = resp.split()
  312. nr = 0
  313. id = ''
  314. n = len(words)
  315. if n > 1:
  316. nr = words[1]
  317. if n > 2:
  318. id = words[2]
  319. return resp, nr, id
  320. def statcmd(self, line):
  321. """Internal: process a STAT, NEXT or LAST command."""
  322. resp = self.shortcmd(line)
  323. return self.statparse(resp)
  324. def stat(self, id):
  325. """Process a STAT command. Argument:
  326. - id: article number or message id
  327. Returns:
  328. - resp: server response if successful
  329. - nr: the article number
  330. - id: the message id"""
  331. return self.statcmd('STAT ' + id)
  332. def next(self):
  333. """Process a NEXT command. No arguments. Return as for STAT."""
  334. return self.statcmd('NEXT')
  335. def last(self):
  336. """Process a LAST command. No arguments. Return as for STAT."""
  337. return self.statcmd('LAST')
  338. def artcmd(self, line, file=None):
  339. """Internal: process a HEAD, BODY or ARTICLE command."""
  340. resp, list = self.longcmd(line, file)
  341. resp, nr, id = self.statparse(resp)
  342. return resp, nr, id, list
  343. def head(self, id):
  344. """Process a HEAD command. Argument:
  345. - id: article number or message id
  346. Returns:
  347. - resp: server response if successful
  348. - nr: article number
  349. - id: message id
  350. - list: the lines of the article's header"""
  351. return self.artcmd('HEAD ' + id)
  352. def body(self, id, file=None):
  353. """Process a BODY command. Argument:
  354. - id: article number or message id
  355. - file: Filename string or file object to store the article in
  356. Returns:
  357. - resp: server response if successful
  358. - nr: article number
  359. - id: message id
  360. - list: the lines of the article's body or an empty list
  361. if file was used"""
  362. return self.artcmd('BODY ' + id, file)
  363. def article(self, id):
  364. """Process an ARTICLE command. Argument:
  365. - id: article number or message id
  366. Returns:
  367. - resp: server response if successful
  368. - nr: article number
  369. - id: message id
  370. - list: the lines of the article"""
  371. return self.artcmd('ARTICLE ' + id)
  372. def slave(self):
  373. """Process a SLAVE command. Returns:
  374. - resp: server response if successful"""
  375. return self.shortcmd('SLAVE')
  376. def xhdr(self, hdr, str, file=None):
  377. """Process an XHDR command (optional server extension). Arguments:
  378. - hdr: the header type (e.g. 'subject')
  379. - str: an article nr, a message id, or a range nr1-nr2
  380. Returns:
  381. - resp: server response if successful
  382. - list: list of (nr, value) strings"""
  383. pat = re.compile('^([0-9]+) ?(.*)\n?')
  384. resp, lines = self.longcmd('XHDR ' + hdr + ' ' + str, file)
  385. for i in range(len(lines)):
  386. line = lines[i]
  387. m = pat.match(line)
  388. if m:
  389. lines[i] = m.group(1, 2)
  390. return resp, lines
  391. def xover(self, start, end, file=None):
  392. """Process an XOVER command (optional server extension) Arguments:
  393. - start: start of range
  394. - end: end of range
  395. Returns:
  396. - resp: server response if successful
  397. - list: list of (art-nr, subject, poster, date,
  398. id, references, size, lines)"""
  399. resp, lines = self.longcmd('XOVER ' + start + '-' + end, file)
  400. xover_lines = []
  401. for line in lines:
  402. elem = line.split("\t")
  403. try:
  404. xover_lines.append((elem[0],
  405. elem[1],
  406. elem[2],
  407. elem[3],
  408. elem[4],
  409. elem[5].split(),
  410. elem[6],
  411. elem[7]))
  412. except IndexError:
  413. raise NNTPDataError(line)
  414. return resp,xover_lines
  415. def xgtitle(self, group, file=None):
  416. """Process an XGTITLE command (optional server extension) Arguments:
  417. - group: group name wildcard (i.e. news.*)
  418. Returns:
  419. - resp: server response if successful
  420. - list: list of (name,title) strings"""
  421. line_pat = re.compile("^([^ \t]+)[ \t]+(.*)$")
  422. resp, raw_lines = self.longcmd('XGTITLE ' + group, file)
  423. lines = []
  424. for raw_line in raw_lines:
  425. match = line_pat.search(raw_line.strip())
  426. if match:
  427. lines.append(match.group(1, 2))
  428. return resp, lines
  429. def xpath(self,id):
  430. """Process an XPATH command (optional server extension) Arguments:
  431. - id: Message id of article
  432. Returns:
  433. resp: server response if successful
  434. path: directory path to article"""
  435. resp = self.shortcmd("XPATH " + id)
  436. if resp[:3] != '223':
  437. raise NNTPReplyError(resp)
  438. try:
  439. [resp_num, path] = resp.split()
  440. except ValueError:
  441. raise NNTPReplyError(resp)
  442. else:
  443. return resp, path
  444. def date (self):
  445. """Process the DATE command. Arguments:
  446. None
  447. Returns:
  448. resp: server response if successful
  449. date: Date suitable for newnews/newgroups commands etc.
  450. time: Time suitable for newnews/newgroups commands etc."""
  451. resp = self.shortcmd("DATE")
  452. if resp[:3] != '111':
  453. raise NNTPReplyError(resp)
  454. elem = resp.split()
  455. if len(elem) != 2:
  456. raise NNTPDataError(resp)
  457. date = elem[1][2:8]
  458. time = elem[1][-6:]
  459. if len(date) != 6 or len(time) != 6:
  460. raise NNTPDataError(resp)
  461. return resp, date, time
  462. def post(self, f):
  463. """Process a POST command. Arguments:
  464. - f: file containing the article
  465. Returns:
  466. - resp: server response if successful"""
  467. resp = self.shortcmd('POST')
  468. # Raises error_??? if posting is not allowed
  469. if resp[0] != '3':
  470. raise NNTPReplyError(resp)
  471. while 1:
  472. line = f.readline()
  473. if not line:
  474. break
  475. if line[-1] == '\n':
  476. line = line[:-1]
  477. if line[:1] == '.':
  478. line = '.' + line
  479. self.putline(line)
  480. self.putline('.')
  481. return self.getresp()
  482. def ihave(self, id, f):
  483. """Process an IHAVE command. Arguments:
  484. - id: message-id of the article
  485. - f: file containing the article
  486. Returns:
  487. - resp: server response if successful
  488. Note that if the server refuses the article an exception is raised."""
  489. resp = self.shortcmd('IHAVE ' + id)
  490. # Raises error_??? if the server already has it
  491. if resp[0] != '3':
  492. raise NNTPReplyError(resp)
  493. while 1:
  494. line = f.readline()
  495. if not line:
  496. break
  497. if line[-1] == '\n':
  498. line = line[:-1]
  499. if line[:1] == '.':
  500. line = '.' + line
  501. self.putline(line)
  502. self.putline('.')
  503. return self.getresp()
  504. def quit(self):
  505. """Process a QUIT command and close the socket. Returns:
  506. - resp: server response if successful"""
  507. resp = self.shortcmd('QUIT')
  508. self.file.close()
  509. self.sock.close()
  510. del self.file, self.sock
  511. return resp
  512. # Test retrieval when run as a script.
  513. # Assumption: if there's a local news server, it's called 'news'.
  514. # Assumption: if user queries a remote news server, it's named
  515. # in the environment variable NNTPSERVER (used by slrn and kin)
  516. # and we want readermode off.
  517. if __name__ == '__main__':
  518. import os
  519. newshost = 'news' and os.environ["NNTPSERVER"]
  520. if newshost.find('.') == -1:
  521. mode = 'readermode'
  522. else:
  523. mode = None
  524. s = NNTP(newshost, readermode=mode)
  525. resp, count, first, last, name = s.group('comp.lang.python')
  526. print resp
  527. print 'Group', name, 'has', count, 'articles, range', first, 'to', last
  528. resp, subs = s.xhdr('subject', first + '-' + last)
  529. print resp
  530. for item in subs:
  531. print "%7s %s" % item
  532. resp = s.quit()
  533. print resp