nntplib.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. """An NNTP client class based on:
  2. - RFC 977: Network News Transfer Protocol
  3. - RFC 2980: Common NNTP Extensions
  4. - RFC 3977: Network News Transfer Protocol (version 2)
  5. Example:
  6. >>> from nntplib import NNTP
  7. >>> s = NNTP('news')
  8. >>> resp, count, first, last, name = s.group('comp.lang.python')
  9. >>> print('Group', name, 'has', count, 'articles, range', first, 'to', last)
  10. Group comp.lang.python has 51 articles, range 5770 to 5821
  11. >>> resp, subs = s.xhdr('subject', '{0}-{1}'.format(first, last))
  12. >>> resp = s.quit()
  13. >>>
  14. Here 'resp' is the server response line.
  15. Error responses are turned into exceptions.
  16. To post an article from a file:
  17. >>> f = open(filename, 'rb') # file containing article, including header
  18. >>> resp = s.post(f)
  19. >>>
  20. For descriptions of all methods, read the comments in the code below.
  21. Note that all arguments and return values representing article numbers
  22. are strings, not numbers, since they are rarely used for calculations.
  23. """
  24. # RFC 977 by Brian Kantor and Phil Lapsley.
  25. # xover, xgtitle, xpath, date methods by Kevan Heydon
  26. # Incompatible changes from the 2.x nntplib:
  27. # - all commands are encoded as UTF-8 data (using the "surrogateescape"
  28. # error handler), except for raw message data (POST, IHAVE)
  29. # - all responses are decoded as UTF-8 data (using the "surrogateescape"
  30. # error handler), except for raw message data (ARTICLE, HEAD, BODY)
  31. # - the `file` argument to various methods is keyword-only
  32. #
  33. # - NNTP.date() returns a datetime object
  34. # - NNTP.newgroups() and NNTP.newnews() take a datetime (or date) object,
  35. # rather than a pair of (date, time) strings.
  36. # - NNTP.newgroups() and NNTP.list() return a list of GroupInfo named tuples
  37. # - NNTP.descriptions() returns a dict mapping group names to descriptions
  38. # - NNTP.xover() returns a list of dicts mapping field names (header or metadata)
  39. # to field values; each dict representing a message overview.
  40. # - NNTP.article(), NNTP.head() and NNTP.body() return a (response, ArticleInfo)
  41. # tuple.
  42. # - the "internal" methods have been marked private (they now start with
  43. # an underscore)
  44. # Other changes from the 2.x/3.1 nntplib:
  45. # - automatic querying of capabilities at connect
  46. # - New method NNTP.getcapabilities()
  47. # - New method NNTP.over()
  48. # - New helper function decode_header()
  49. # - NNTP.post() and NNTP.ihave() accept file objects, bytes-like objects and
  50. # arbitrary iterables yielding lines.
  51. # - An extensive test suite :-)
  52. # TODO:
  53. # - return structured data (GroupInfo etc.) everywhere
  54. # - support HDR
  55. # Imports
  56. import re
  57. import socket
  58. import collections
  59. import datetime
  60. import warnings
  61. try:
  62. import ssl
  63. except ImportError:
  64. _have_ssl = False
  65. else:
  66. _have_ssl = True
  67. from email.header import decode_header as _email_decode_header
  68. from socket import _GLOBAL_DEFAULT_TIMEOUT
  69. __all__ = ["NNTP",
  70. "NNTPError", "NNTPReplyError", "NNTPTemporaryError",
  71. "NNTPPermanentError", "NNTPProtocolError", "NNTPDataError",
  72. "decode_header",
  73. ]
  74. # maximal line length when calling readline(). This is to prevent
  75. # reading arbitrary length lines. RFC 3977 limits NNTP line length to
  76. # 512 characters, including CRLF. We have selected 2048 just to be on
  77. # the safe side.
  78. _MAXLINE = 2048
  79. # Exceptions raised when an error or invalid response is received
  80. class NNTPError(Exception):
  81. """Base class for all nntplib exceptions"""
  82. def __init__(self, *args):
  83. Exception.__init__(self, *args)
  84. try:
  85. self.response = args[0]
  86. except IndexError:
  87. self.response = 'No response given'
  88. class NNTPReplyError(NNTPError):
  89. """Unexpected [123]xx reply"""
  90. pass
  91. class NNTPTemporaryError(NNTPError):
  92. """4xx errors"""
  93. pass
  94. class NNTPPermanentError(NNTPError):
  95. """5xx errors"""
  96. pass
  97. class NNTPProtocolError(NNTPError):
  98. """Response does not begin with [1-5]"""
  99. pass
  100. class NNTPDataError(NNTPError):
  101. """Error in response data"""
  102. pass
  103. # Standard port used by NNTP servers
  104. NNTP_PORT = 119
  105. NNTP_SSL_PORT = 563
  106. # Response numbers that are followed by additional text (e.g. article)
  107. _LONGRESP = {
  108. '100', # HELP
  109. '101', # CAPABILITIES
  110. '211', # LISTGROUP (also not multi-line with GROUP)
  111. '215', # LIST
  112. '220', # ARTICLE
  113. '221', # HEAD, XHDR
  114. '222', # BODY
  115. '224', # OVER, XOVER
  116. '225', # HDR
  117. '230', # NEWNEWS
  118. '231', # NEWGROUPS
  119. '282', # XGTITLE
  120. }
  121. # Default decoded value for LIST OVERVIEW.FMT if not supported
  122. _DEFAULT_OVERVIEW_FMT = [
  123. "subject", "from", "date", "message-id", "references", ":bytes", ":lines"]
  124. # Alternative names allowed in LIST OVERVIEW.FMT response
  125. _OVERVIEW_FMT_ALTERNATIVES = {
  126. 'bytes': ':bytes',
  127. 'lines': ':lines',
  128. }
  129. # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
  130. _CRLF = b'\r\n'
  131. GroupInfo = collections.namedtuple('GroupInfo',
  132. ['group', 'last', 'first', 'flag'])
  133. ArticleInfo = collections.namedtuple('ArticleInfo',
  134. ['number', 'message_id', 'lines'])
  135. # Helper function(s)
  136. def decode_header(header_str):
  137. """Takes a unicode string representing a munged header value
  138. and decodes it as a (possibly non-ASCII) readable value."""
  139. parts = []
  140. for v, enc in _email_decode_header(header_str):
  141. if isinstance(v, bytes):
  142. parts.append(v.decode(enc or 'ascii'))
  143. else:
  144. parts.append(v)
  145. return ''.join(parts)
  146. def _parse_overview_fmt(lines):
  147. """Parse a list of string representing the response to LIST OVERVIEW.FMT
  148. and return a list of header/metadata names.
  149. Raises NNTPDataError if the response is not compliant
  150. (cf. RFC 3977, section 8.4)."""
  151. fmt = []
  152. for line in lines:
  153. if line[0] == ':':
  154. # Metadata name (e.g. ":bytes")
  155. name, _, suffix = line[1:].partition(':')
  156. name = ':' + name
  157. else:
  158. # Header name (e.g. "Subject:" or "Xref:full")
  159. name, _, suffix = line.partition(':')
  160. name = name.lower()
  161. name = _OVERVIEW_FMT_ALTERNATIVES.get(name, name)
  162. # Should we do something with the suffix?
  163. fmt.append(name)
  164. defaults = _DEFAULT_OVERVIEW_FMT
  165. if len(fmt) < len(defaults):
  166. raise NNTPDataError("LIST OVERVIEW.FMT response too short")
  167. if fmt[:len(defaults)] != defaults:
  168. raise NNTPDataError("LIST OVERVIEW.FMT redefines default fields")
  169. return fmt
  170. def _parse_overview(lines, fmt, data_process_func=None):
  171. """Parse the response to an OVER or XOVER command according to the
  172. overview format `fmt`."""
  173. n_defaults = len(_DEFAULT_OVERVIEW_FMT)
  174. overview = []
  175. for line in lines:
  176. fields = {}
  177. article_number, *tokens = line.split('\t')
  178. article_number = int(article_number)
  179. for i, token in enumerate(tokens):
  180. if i >= len(fmt):
  181. # XXX should we raise an error? Some servers might not
  182. # support LIST OVERVIEW.FMT and still return additional
  183. # headers.
  184. continue
  185. field_name = fmt[i]
  186. is_metadata = field_name.startswith(':')
  187. if i >= n_defaults and not is_metadata:
  188. # Non-default header names are included in full in the response
  189. # (unless the field is totally empty)
  190. h = field_name + ": "
  191. if token and token[:len(h)].lower() != h:
  192. raise NNTPDataError("OVER/XOVER response doesn't include "
  193. "names of additional headers")
  194. token = token[len(h):] if token else None
  195. fields[fmt[i]] = token
  196. overview.append((article_number, fields))
  197. return overview
  198. def _parse_datetime(date_str, time_str=None):
  199. """Parse a pair of (date, time) strings, and return a datetime object.
  200. If only the date is given, it is assumed to be date and time
  201. concatenated together (e.g. response to the DATE command).
  202. """
  203. if time_str is None:
  204. time_str = date_str[-6:]
  205. date_str = date_str[:-6]
  206. hours = int(time_str[:2])
  207. minutes = int(time_str[2:4])
  208. seconds = int(time_str[4:])
  209. year = int(date_str[:-4])
  210. month = int(date_str[-4:-2])
  211. day = int(date_str[-2:])
  212. # RFC 3977 doesn't say how to interpret 2-char years. Assume that
  213. # there are no dates before 1970 on Usenet.
  214. if year < 70:
  215. year += 2000
  216. elif year < 100:
  217. year += 1900
  218. return datetime.datetime(year, month, day, hours, minutes, seconds)
  219. def _unparse_datetime(dt, legacy=False):
  220. """Format a date or datetime object as a pair of (date, time) strings
  221. in the format required by the NEWNEWS and NEWGROUPS commands. If a
  222. date object is passed, the time is assumed to be midnight (00h00).
  223. The returned representation depends on the legacy flag:
  224. * if legacy is False (the default):
  225. date has the YYYYMMDD format and time the HHMMSS format
  226. * if legacy is True:
  227. date has the YYMMDD format and time the HHMMSS format.
  228. RFC 3977 compliant servers should understand both formats; therefore,
  229. legacy is only needed when talking to old servers.
  230. """
  231. if not isinstance(dt, datetime.datetime):
  232. time_str = "000000"
  233. else:
  234. time_str = "{0.hour:02d}{0.minute:02d}{0.second:02d}".format(dt)
  235. y = dt.year
  236. if legacy:
  237. y = y % 100
  238. date_str = "{0:02d}{1.month:02d}{1.day:02d}".format(y, dt)
  239. else:
  240. date_str = "{0:04d}{1.month:02d}{1.day:02d}".format(y, dt)
  241. return date_str, time_str
  242. if _have_ssl:
  243. def _encrypt_on(sock, context, hostname):
  244. """Wrap a socket in SSL/TLS. Arguments:
  245. - sock: Socket to wrap
  246. - context: SSL context to use for the encrypted connection
  247. Returns:
  248. - sock: New, encrypted socket.
  249. """
  250. # Generate a default SSL context if none was passed.
  251. if context is None:
  252. context = ssl._create_stdlib_context()
  253. return context.wrap_socket(sock, server_hostname=hostname)
  254. # The classes themselves
  255. class _NNTPBase:
  256. # UTF-8 is the character set for all NNTP commands and responses: they
  257. # are automatically encoded (when sending) and decoded (and receiving)
  258. # by this class.
  259. # However, some multi-line data blocks can contain arbitrary bytes (for
  260. # example, latin-1 or utf-16 data in the body of a message). Commands
  261. # taking (POST, IHAVE) or returning (HEAD, BODY, ARTICLE) raw message
  262. # data will therefore only accept and produce bytes objects.
  263. # Furthermore, since there could be non-compliant servers out there,
  264. # we use 'surrogateescape' as the error handler for fault tolerance
  265. # and easy round-tripping. This could be useful for some applications
  266. # (e.g. NNTP gateways).
  267. encoding = 'utf-8'
  268. errors = 'surrogateescape'
  269. def __init__(self, file, host,
  270. readermode=None, timeout=_GLOBAL_DEFAULT_TIMEOUT):
  271. """Initialize an instance. Arguments:
  272. - file: file-like object (open for read/write in binary mode)
  273. - host: hostname of the server
  274. - readermode: if true, send 'mode reader' command after
  275. connecting.
  276. - timeout: timeout (in seconds) used for socket connections
  277. readermode is sometimes necessary if you are connecting to an
  278. NNTP server on the local machine and intend to call
  279. reader-specific commands, such as `group'. If you get
  280. unexpected NNTPPermanentErrors, you might need to set
  281. readermode.
  282. """
  283. self.host = host
  284. self.file = file
  285. self.debugging = 0
  286. self.welcome = self._getresp()
  287. # Inquire about capabilities (RFC 3977).
  288. self._caps = None
  289. self.getcapabilities()
  290. # 'MODE READER' is sometimes necessary to enable 'reader' mode.
  291. # However, the order in which 'MODE READER' and 'AUTHINFO' need to
  292. # arrive differs between some NNTP servers. If _setreadermode() fails
  293. # with an authorization failed error, it will set this to True;
  294. # the login() routine will interpret that as a request to try again
  295. # after performing its normal function.
  296. # Enable only if we're not already in READER mode anyway.
  297. self.readermode_afterauth = False
  298. if readermode and 'READER' not in self._caps:
  299. self._setreadermode()
  300. if not self.readermode_afterauth:
  301. # Capabilities might have changed after MODE READER
  302. self._caps = None
  303. self.getcapabilities()
  304. # RFC 4642 2.2.2: Both the client and the server MUST know if there is
  305. # a TLS session active. A client MUST NOT attempt to start a TLS
  306. # session if a TLS session is already active.
  307. self.tls_on = False
  308. # Log in and encryption setup order is left to subclasses.
  309. self.authenticated = False
  310. def __enter__(self):
  311. return self
  312. def __exit__(self, *args):
  313. is_connected = lambda: hasattr(self, "file")
  314. if is_connected():
  315. try:
  316. self.quit()
  317. except (OSError, EOFError):
  318. pass
  319. finally:
  320. if is_connected():
  321. self._close()
  322. def getwelcome(self):
  323. """Get the welcome message from the server
  324. (this is read and squirreled away by __init__()).
  325. If the response code is 200, posting is allowed;
  326. if it 201, posting is not allowed."""
  327. if self.debugging: print('*welcome*', repr(self.welcome))
  328. return self.welcome
  329. def getcapabilities(self):
  330. """Get the server capabilities, as read by __init__().
  331. If the CAPABILITIES command is not supported, an empty dict is
  332. returned."""
  333. if self._caps is None:
  334. self.nntp_version = 1
  335. self.nntp_implementation = None
  336. try:
  337. resp, caps = self.capabilities()
  338. except (NNTPPermanentError, NNTPTemporaryError):
  339. # Server doesn't support capabilities
  340. self._caps = {}
  341. else:
  342. self._caps = caps
  343. if 'VERSION' in caps:
  344. # The server can advertise several supported versions,
  345. # choose the highest.
  346. self.nntp_version = max(map(int, caps['VERSION']))
  347. if 'IMPLEMENTATION' in caps:
  348. self.nntp_implementation = ' '.join(caps['IMPLEMENTATION'])
  349. return self._caps
  350. def set_debuglevel(self, level):
  351. """Set the debugging level. Argument 'level' means:
  352. 0: no debugging output (default)
  353. 1: print commands and responses but not body text etc.
  354. 2: also print raw lines read and sent before stripping CR/LF"""
  355. self.debugging = level
  356. debug = set_debuglevel
  357. def _putline(self, line):
  358. """Internal: send one line to the server, appending CRLF.
  359. The `line` must be a bytes-like object."""
  360. line = line + _CRLF
  361. if self.debugging > 1: print('*put*', repr(line))
  362. self.file.write(line)
  363. self.file.flush()
  364. def _putcmd(self, line):
  365. """Internal: send one command to the server (through _putline()).
  366. The `line` must be a unicode string."""
  367. if self.debugging: print('*cmd*', repr(line))
  368. line = line.encode(self.encoding, self.errors)
  369. self._putline(line)
  370. def _getline(self, strip_crlf=True):
  371. """Internal: return one line from the server, stripping _CRLF.
  372. Raise EOFError if the connection is closed.
  373. Returns a bytes object."""
  374. line = self.file.readline(_MAXLINE +1)
  375. if len(line) > _MAXLINE:
  376. raise NNTPDataError('line too long')
  377. if self.debugging > 1:
  378. print('*get*', repr(line))
  379. if not line: raise EOFError
  380. if strip_crlf:
  381. if line[-2:] == _CRLF:
  382. line = line[:-2]
  383. elif line[-1:] in _CRLF:
  384. line = line[:-1]
  385. return line
  386. def _getresp(self):
  387. """Internal: get a response from the server.
  388. Raise various errors if the response indicates an error.
  389. Returns a unicode string."""
  390. resp = self._getline()
  391. if self.debugging: print('*resp*', repr(resp))
  392. resp = resp.decode(self.encoding, self.errors)
  393. c = resp[:1]
  394. if c == '4':
  395. raise NNTPTemporaryError(resp)
  396. if c == '5':
  397. raise NNTPPermanentError(resp)
  398. if c not in '123':
  399. raise NNTPProtocolError(resp)
  400. return resp
  401. def _getlongresp(self, file=None):
  402. """Internal: get a response plus following text from the server.
  403. Raise various errors if the response indicates an error.
  404. Returns a (response, lines) tuple where `response` is a unicode
  405. string and `lines` is a list of bytes objects.
  406. If `file` is a file-like object, it must be open in binary mode.
  407. """
  408. openedFile = None
  409. try:
  410. # If a string was passed then open a file with that name
  411. if isinstance(file, (str, bytes)):
  412. openedFile = file = open(file, "wb")
  413. resp = self._getresp()
  414. if resp[:3] not in _LONGRESP:
  415. raise NNTPReplyError(resp)
  416. lines = []
  417. if file is not None:
  418. # XXX lines = None instead?
  419. terminators = (b'.' + _CRLF, b'.\n')
  420. while 1:
  421. line = self._getline(False)
  422. if line in terminators:
  423. break
  424. if line.startswith(b'..'):
  425. line = line[1:]
  426. file.write(line)
  427. else:
  428. terminator = b'.'
  429. while 1:
  430. line = self._getline()
  431. if line == terminator:
  432. break
  433. if line.startswith(b'..'):
  434. line = line[1:]
  435. lines.append(line)
  436. finally:
  437. # If this method created the file, then it must close it
  438. if openedFile:
  439. openedFile.close()
  440. return resp, lines
  441. def _shortcmd(self, line):
  442. """Internal: send a command and get the response.
  443. Same return value as _getresp()."""
  444. self._putcmd(line)
  445. return self._getresp()
  446. def _longcmd(self, line, file=None):
  447. """Internal: send a command and get the response plus following text.
  448. Same return value as _getlongresp()."""
  449. self._putcmd(line)
  450. return self._getlongresp(file)
  451. def _longcmdstring(self, line, file=None):
  452. """Internal: send a command and get the response plus following text.
  453. Same as _longcmd() and _getlongresp(), except that the returned `lines`
  454. are unicode strings rather than bytes objects.
  455. """
  456. self._putcmd(line)
  457. resp, list = self._getlongresp(file)
  458. return resp, [line.decode(self.encoding, self.errors)
  459. for line in list]
  460. def _getoverviewfmt(self):
  461. """Internal: get the overview format. Queries the server if not
  462. already done, else returns the cached value."""
  463. try:
  464. return self._cachedoverviewfmt
  465. except AttributeError:
  466. pass
  467. try:
  468. resp, lines = self._longcmdstring("LIST OVERVIEW.FMT")
  469. except NNTPPermanentError:
  470. # Not supported by server?
  471. fmt = _DEFAULT_OVERVIEW_FMT[:]
  472. else:
  473. fmt = _parse_overview_fmt(lines)
  474. self._cachedoverviewfmt = fmt
  475. return fmt
  476. def _grouplist(self, lines):
  477. # Parse lines into "group last first flag"
  478. return [GroupInfo(*line.split()) for line in lines]
  479. def capabilities(self):
  480. """Process a CAPABILITIES command. Not supported by all servers.
  481. Return:
  482. - resp: server response if successful
  483. - caps: a dictionary mapping capability names to lists of tokens
  484. (for example {'VERSION': ['2'], 'OVER': [], LIST: ['ACTIVE', 'HEADERS'] })
  485. """
  486. caps = {}
  487. resp, lines = self._longcmdstring("CAPABILITIES")
  488. for line in lines:
  489. name, *tokens = line.split()
  490. caps[name] = tokens
  491. return resp, caps
  492. def newgroups(self, date, *, file=None):
  493. """Process a NEWGROUPS command. Arguments:
  494. - date: a date or datetime object
  495. Return:
  496. - resp: server response if successful
  497. - list: list of newsgroup names
  498. """
  499. if not isinstance(date, (datetime.date, datetime.date)):
  500. raise TypeError(
  501. "the date parameter must be a date or datetime object, "
  502. "not '{:40}'".format(date.__class__.__name__))
  503. date_str, time_str = _unparse_datetime(date, self.nntp_version < 2)
  504. cmd = 'NEWGROUPS {0} {1}'.format(date_str, time_str)
  505. resp, lines = self._longcmdstring(cmd, file)
  506. return resp, self._grouplist(lines)
  507. def newnews(self, group, date, *, file=None):
  508. """Process a NEWNEWS command. Arguments:
  509. - group: group name or '*'
  510. - date: a date or datetime object
  511. Return:
  512. - resp: server response if successful
  513. - list: list of message ids
  514. """
  515. if not isinstance(date, (datetime.date, datetime.date)):
  516. raise TypeError(
  517. "the date parameter must be a date or datetime object, "
  518. "not '{:40}'".format(date.__class__.__name__))
  519. date_str, time_str = _unparse_datetime(date, self.nntp_version < 2)
  520. cmd = 'NEWNEWS {0} {1} {2}'.format(group, date_str, time_str)
  521. return self._longcmdstring(cmd, file)
  522. def list(self, group_pattern=None, *, file=None):
  523. """Process a LIST or LIST ACTIVE command. Arguments:
  524. - group_pattern: a pattern indicating which groups to query
  525. - file: Filename string or file object to store the result in
  526. Returns:
  527. - resp: server response if successful
  528. - list: list of (group, last, first, flag) (strings)
  529. """
  530. if group_pattern is not None:
  531. command = 'LIST ACTIVE ' + group_pattern
  532. else:
  533. command = 'LIST'
  534. resp, lines = self._longcmdstring(command, file)
  535. return resp, self._grouplist(lines)
  536. def _getdescriptions(self, group_pattern, return_all):
  537. line_pat = re.compile('^(?P<group>[^ \t]+)[ \t]+(.*)$')
  538. # Try the more std (acc. to RFC2980) LIST NEWSGROUPS first
  539. resp, lines = self._longcmdstring('LIST NEWSGROUPS ' + group_pattern)
  540. if not resp.startswith('215'):
  541. # Now the deprecated XGTITLE. This either raises an error
  542. # or succeeds with the same output structure as LIST
  543. # NEWSGROUPS.
  544. resp, lines = self._longcmdstring('XGTITLE ' + group_pattern)
  545. groups = {}
  546. for raw_line in lines:
  547. match = line_pat.search(raw_line.strip())
  548. if match:
  549. name, desc = match.group(1, 2)
  550. if not return_all:
  551. return desc
  552. groups[name] = desc
  553. if return_all:
  554. return resp, groups
  555. else:
  556. # Nothing found
  557. return ''
  558. def description(self, group):
  559. """Get a description for a single group. If more than one
  560. group matches ('group' is a pattern), return the first. If no
  561. group matches, return an empty string.
  562. This elides the response code from the server, since it can
  563. only be '215' or '285' (for xgtitle) anyway. If the response
  564. code is needed, use the 'descriptions' method.
  565. NOTE: This neither checks for a wildcard in 'group' nor does
  566. it check whether the group actually exists."""
  567. return self._getdescriptions(group, False)
  568. def descriptions(self, group_pattern):
  569. """Get descriptions for a range of groups."""
  570. return self._getdescriptions(group_pattern, True)
  571. def group(self, name):
  572. """Process a GROUP command. Argument:
  573. - group: the group name
  574. Returns:
  575. - resp: server response if successful
  576. - count: number of articles
  577. - first: first article number
  578. - last: last article number
  579. - name: the group name
  580. """
  581. resp = self._shortcmd('GROUP ' + name)
  582. if not resp.startswith('211'):
  583. raise NNTPReplyError(resp)
  584. words = resp.split()
  585. count = first = last = 0
  586. n = len(words)
  587. if n > 1:
  588. count = words[1]
  589. if n > 2:
  590. first = words[2]
  591. if n > 3:
  592. last = words[3]
  593. if n > 4:
  594. name = words[4].lower()
  595. return resp, int(count), int(first), int(last), name
  596. def help(self, *, file=None):
  597. """Process a HELP command. Argument:
  598. - file: Filename string or file object to store the result in
  599. Returns:
  600. - resp: server response if successful
  601. - list: list of strings returned by the server in response to the
  602. HELP command
  603. """
  604. return self._longcmdstring('HELP', file)
  605. def _statparse(self, resp):
  606. """Internal: parse the response line of a STAT, NEXT, LAST,
  607. ARTICLE, HEAD or BODY command."""
  608. if not resp.startswith('22'):
  609. raise NNTPReplyError(resp)
  610. words = resp.split()
  611. art_num = int(words[1])
  612. message_id = words[2]
  613. return resp, art_num, message_id
  614. def _statcmd(self, line):
  615. """Internal: process a STAT, NEXT or LAST command."""
  616. resp = self._shortcmd(line)
  617. return self._statparse(resp)
  618. def stat(self, message_spec=None):
  619. """Process a STAT command. Argument:
  620. - message_spec: article number or message id (if not specified,
  621. the current article is selected)
  622. Returns:
  623. - resp: server response if successful
  624. - art_num: the article number
  625. - message_id: the message id
  626. """
  627. if message_spec:
  628. return self._statcmd('STAT {0}'.format(message_spec))
  629. else:
  630. return self._statcmd('STAT')
  631. def next(self):
  632. """Process a NEXT command. No arguments. Return as for STAT."""
  633. return self._statcmd('NEXT')
  634. def last(self):
  635. """Process a LAST command. No arguments. Return as for STAT."""
  636. return self._statcmd('LAST')
  637. def _artcmd(self, line, file=None):
  638. """Internal: process a HEAD, BODY or ARTICLE command."""
  639. resp, lines = self._longcmd(line, file)
  640. resp, art_num, message_id = self._statparse(resp)
  641. return resp, ArticleInfo(art_num, message_id, lines)
  642. def head(self, message_spec=None, *, file=None):
  643. """Process a HEAD command. Argument:
  644. - message_spec: article number or message id
  645. - file: filename string or file object to store the headers in
  646. Returns:
  647. - resp: server response if successful
  648. - ArticleInfo: (article number, message id, list of header lines)
  649. """
  650. if message_spec is not None:
  651. cmd = 'HEAD {0}'.format(message_spec)
  652. else:
  653. cmd = 'HEAD'
  654. return self._artcmd(cmd, file)
  655. def body(self, message_spec=None, *, file=None):
  656. """Process a BODY command. Argument:
  657. - message_spec: article number or message id
  658. - file: filename string or file object to store the body in
  659. Returns:
  660. - resp: server response if successful
  661. - ArticleInfo: (article number, message id, list of body lines)
  662. """
  663. if message_spec is not None:
  664. cmd = 'BODY {0}'.format(message_spec)
  665. else:
  666. cmd = 'BODY'
  667. return self._artcmd(cmd, file)
  668. def article(self, message_spec=None, *, file=None):
  669. """Process an ARTICLE command. Argument:
  670. - message_spec: article number or message id
  671. - file: filename string or file object to store the article in
  672. Returns:
  673. - resp: server response if successful
  674. - ArticleInfo: (article number, message id, list of article lines)
  675. """
  676. if message_spec is not None:
  677. cmd = 'ARTICLE {0}'.format(message_spec)
  678. else:
  679. cmd = 'ARTICLE'
  680. return self._artcmd(cmd, file)
  681. def slave(self):
  682. """Process a SLAVE command. Returns:
  683. - resp: server response if successful
  684. """
  685. return self._shortcmd('SLAVE')
  686. def xhdr(self, hdr, str, *, file=None):
  687. """Process an XHDR command (optional server extension). Arguments:
  688. - hdr: the header type (e.g. 'subject')
  689. - str: an article nr, a message id, or a range nr1-nr2
  690. - file: Filename string or file object to store the result in
  691. Returns:
  692. - resp: server response if successful
  693. - list: list of (nr, value) strings
  694. """
  695. pat = re.compile('^([0-9]+) ?(.*)\n?')
  696. resp, lines = self._longcmdstring('XHDR {0} {1}'.format(hdr, str), file)
  697. def remove_number(line):
  698. m = pat.match(line)
  699. return m.group(1, 2) if m else line
  700. return resp, [remove_number(line) for line in lines]
  701. def xover(self, start, end, *, file=None):
  702. """Process an XOVER command (optional server extension) Arguments:
  703. - start: start of range
  704. - end: end of range
  705. - file: Filename string or file object to store the result in
  706. Returns:
  707. - resp: server response if successful
  708. - list: list of dicts containing the response fields
  709. """
  710. resp, lines = self._longcmdstring('XOVER {0}-{1}'.format(start, end),
  711. file)
  712. fmt = self._getoverviewfmt()
  713. return resp, _parse_overview(lines, fmt)
  714. def over(self, message_spec, *, file=None):
  715. """Process an OVER command. If the command isn't supported, fall
  716. back to XOVER. Arguments:
  717. - message_spec:
  718. - either a message id, indicating the article to fetch
  719. information about
  720. - or a (start, end) tuple, indicating a range of article numbers;
  721. if end is None, information up to the newest message will be
  722. retrieved
  723. - or None, indicating the current article number must be used
  724. - file: Filename string or file object to store the result in
  725. Returns:
  726. - resp: server response if successful
  727. - list: list of dicts containing the response fields
  728. NOTE: the "message id" form isn't supported by XOVER
  729. """
  730. cmd = 'OVER' if 'OVER' in self._caps else 'XOVER'
  731. if isinstance(message_spec, (tuple, list)):
  732. start, end = message_spec
  733. cmd += ' {0}-{1}'.format(start, end or '')
  734. elif message_spec is not None:
  735. cmd = cmd + ' ' + message_spec
  736. resp, lines = self._longcmdstring(cmd, file)
  737. fmt = self._getoverviewfmt()
  738. return resp, _parse_overview(lines, fmt)
  739. def xgtitle(self, group, *, file=None):
  740. """Process an XGTITLE command (optional server extension) Arguments:
  741. - group: group name wildcard (i.e. news.*)
  742. Returns:
  743. - resp: server response if successful
  744. - list: list of (name,title) strings"""
  745. warnings.warn("The XGTITLE extension is not actively used, "
  746. "use descriptions() instead",
  747. DeprecationWarning, 2)
  748. line_pat = re.compile('^([^ \t]+)[ \t]+(.*)$')
  749. resp, raw_lines = self._longcmdstring('XGTITLE ' + group, file)
  750. lines = []
  751. for raw_line in raw_lines:
  752. match = line_pat.search(raw_line.strip())
  753. if match:
  754. lines.append(match.group(1, 2))
  755. return resp, lines
  756. def xpath(self, id):
  757. """Process an XPATH command (optional server extension) Arguments:
  758. - id: Message id of article
  759. Returns:
  760. resp: server response if successful
  761. path: directory path to article
  762. """
  763. warnings.warn("The XPATH extension is not actively used",
  764. DeprecationWarning, 2)
  765. resp = self._shortcmd('XPATH {0}'.format(id))
  766. if not resp.startswith('223'):
  767. raise NNTPReplyError(resp)
  768. try:
  769. [resp_num, path] = resp.split()
  770. except ValueError:
  771. raise NNTPReplyError(resp)
  772. else:
  773. return resp, path
  774. def date(self):
  775. """Process the DATE command.
  776. Returns:
  777. - resp: server response if successful
  778. - date: datetime object
  779. """
  780. resp = self._shortcmd("DATE")
  781. if not resp.startswith('111'):
  782. raise NNTPReplyError(resp)
  783. elem = resp.split()
  784. if len(elem) != 2:
  785. raise NNTPDataError(resp)
  786. date = elem[1]
  787. if len(date) != 14:
  788. raise NNTPDataError(resp)
  789. return resp, _parse_datetime(date, None)
  790. def _post(self, command, f):
  791. resp = self._shortcmd(command)
  792. # Raises a specific exception if posting is not allowed
  793. if not resp.startswith('3'):
  794. raise NNTPReplyError(resp)
  795. if isinstance(f, (bytes, bytearray)):
  796. f = f.splitlines()
  797. # We don't use _putline() because:
  798. # - we don't want additional CRLF if the file or iterable is already
  799. # in the right format
  800. # - we don't want a spurious flush() after each line is written
  801. for line in f:
  802. if not line.endswith(_CRLF):
  803. line = line.rstrip(b"\r\n") + _CRLF
  804. if line.startswith(b'.'):
  805. line = b'.' + line
  806. self.file.write(line)
  807. self.file.write(b".\r\n")
  808. self.file.flush()
  809. return self._getresp()
  810. def post(self, data):
  811. """Process a POST command. Arguments:
  812. - data: bytes object, iterable or file containing the article
  813. Returns:
  814. - resp: server response if successful"""
  815. return self._post('POST', data)
  816. def ihave(self, message_id, data):
  817. """Process an IHAVE command. Arguments:
  818. - message_id: message-id of the article
  819. - data: file containing the article
  820. Returns:
  821. - resp: server response if successful
  822. Note that if the server refuses the article an exception is raised."""
  823. return self._post('IHAVE {0}'.format(message_id), data)
  824. def _close(self):
  825. self.file.close()
  826. del self.file
  827. def quit(self):
  828. """Process a QUIT command and close the socket. Returns:
  829. - resp: server response if successful"""
  830. try:
  831. resp = self._shortcmd('QUIT')
  832. finally:
  833. self._close()
  834. return resp
  835. def login(self, user=None, password=None, usenetrc=True):
  836. if self.authenticated:
  837. raise ValueError("Already logged in.")
  838. if not user and not usenetrc:
  839. raise ValueError(
  840. "At least one of `user` and `usenetrc` must be specified")
  841. # If no login/password was specified but netrc was requested,
  842. # try to get them from ~/.netrc
  843. # Presume that if .netrc has an entry, NNRP authentication is required.
  844. try:
  845. if usenetrc and not user:
  846. import netrc
  847. credentials = netrc.netrc()
  848. auth = credentials.authenticators(self.host)
  849. if auth:
  850. user = auth[0]
  851. password = auth[2]
  852. except OSError:
  853. pass
  854. # Perform NNTP authentication if needed.
  855. if not user:
  856. return
  857. resp = self._shortcmd('authinfo user ' + user)
  858. if resp.startswith('381'):
  859. if not password:
  860. raise NNTPReplyError(resp)
  861. else:
  862. resp = self._shortcmd('authinfo pass ' + password)
  863. if not resp.startswith('281'):
  864. raise NNTPPermanentError(resp)
  865. # Capabilities might have changed after login
  866. self._caps = None
  867. self.getcapabilities()
  868. # Attempt to send mode reader if it was requested after login.
  869. # Only do so if we're not in reader mode already.
  870. if self.readermode_afterauth and 'READER' not in self._caps:
  871. self._setreadermode()
  872. # Capabilities might have changed after MODE READER
  873. self._caps = None
  874. self.getcapabilities()
  875. def _setreadermode(self):
  876. try:
  877. self.welcome = self._shortcmd('mode reader')
  878. except NNTPPermanentError:
  879. # Error 5xx, probably 'not implemented'
  880. pass
  881. except NNTPTemporaryError as e:
  882. if e.response.startswith('480'):
  883. # Need authorization before 'mode reader'
  884. self.readermode_afterauth = True
  885. else:
  886. raise
  887. if _have_ssl:
  888. def starttls(self, context=None):
  889. """Process a STARTTLS command. Arguments:
  890. - context: SSL context to use for the encrypted connection
  891. """
  892. # Per RFC 4642, STARTTLS MUST NOT be sent after authentication or if
  893. # a TLS session already exists.
  894. if self.tls_on:
  895. raise ValueError("TLS is already enabled.")
  896. if self.authenticated:
  897. raise ValueError("TLS cannot be started after authentication.")
  898. resp = self._shortcmd('STARTTLS')
  899. if resp.startswith('382'):
  900. self.file.close()
  901. self.sock = _encrypt_on(self.sock, context, self.host)
  902. self.file = self.sock.makefile("rwb")
  903. self.tls_on = True
  904. # Capabilities may change after TLS starts up, so ask for them
  905. # again.
  906. self._caps = None
  907. self.getcapabilities()
  908. else:
  909. raise NNTPError("TLS failed to start.")
  910. class NNTP(_NNTPBase):
  911. def __init__(self, host, port=NNTP_PORT, user=None, password=None,
  912. readermode=None, usenetrc=False,
  913. timeout=_GLOBAL_DEFAULT_TIMEOUT):
  914. """Initialize an instance. Arguments:
  915. - host: hostname to connect to
  916. - port: port to connect to (default the standard NNTP port)
  917. - user: username to authenticate with
  918. - password: password to use with username
  919. - readermode: if true, send 'mode reader' command after
  920. connecting.
  921. - usenetrc: allow loading username and password from ~/.netrc file
  922. if not specified explicitly
  923. - timeout: timeout (in seconds) used for socket connections
  924. readermode is sometimes necessary if you are connecting to an
  925. NNTP server on the local machine and intend to call
  926. reader-specific commands, such as `group'. If you get
  927. unexpected NNTPPermanentErrors, you might need to set
  928. readermode.
  929. """
  930. self.host = host
  931. self.port = port
  932. self.sock = socket.create_connection((host, port), timeout)
  933. file = None
  934. try:
  935. file = self.sock.makefile("rwb")
  936. _NNTPBase.__init__(self, file, host,
  937. readermode, timeout)
  938. if user or usenetrc:
  939. self.login(user, password, usenetrc)
  940. except:
  941. if file:
  942. file.close()
  943. self.sock.close()
  944. raise
  945. def _close(self):
  946. try:
  947. _NNTPBase._close(self)
  948. finally:
  949. self.sock.close()
  950. if _have_ssl:
  951. class NNTP_SSL(_NNTPBase):
  952. def __init__(self, host, port=NNTP_SSL_PORT,
  953. user=None, password=None, ssl_context=None,
  954. readermode=None, usenetrc=False,
  955. timeout=_GLOBAL_DEFAULT_TIMEOUT):
  956. """This works identically to NNTP.__init__, except for the change
  957. in default port and the `ssl_context` argument for SSL connections.
  958. """
  959. self.sock = socket.create_connection((host, port), timeout)
  960. file = None
  961. try:
  962. self.sock = _encrypt_on(self.sock, ssl_context, host)
  963. file = self.sock.makefile("rwb")
  964. _NNTPBase.__init__(self, file, host,
  965. readermode=readermode, timeout=timeout)
  966. if user or usenetrc:
  967. self.login(user, password, usenetrc)
  968. except:
  969. if file:
  970. file.close()
  971. self.sock.close()
  972. raise
  973. def _close(self):
  974. try:
  975. _NNTPBase._close(self)
  976. finally:
  977. self.sock.close()
  978. __all__.append("NNTP_SSL")
  979. # Test retrieval when run as a script.
  980. if __name__ == '__main__':
  981. import argparse
  982. parser = argparse.ArgumentParser(description="""\
  983. nntplib built-in demo - display the latest articles in a newsgroup""")
  984. parser.add_argument('-g', '--group', default='gmane.comp.python.general',
  985. help='group to fetch messages from (default: %(default)s)')
  986. parser.add_argument('-s', '--server', default='news.gmane.org',
  987. help='NNTP server hostname (default: %(default)s)')
  988. parser.add_argument('-p', '--port', default=-1, type=int,
  989. help='NNTP port number (default: %s / %s)' % (NNTP_PORT, NNTP_SSL_PORT))
  990. parser.add_argument('-n', '--nb-articles', default=10, type=int,
  991. help='number of articles to fetch (default: %(default)s)')
  992. parser.add_argument('-S', '--ssl', action='store_true', default=False,
  993. help='use NNTP over SSL')
  994. args = parser.parse_args()
  995. port = args.port
  996. if not args.ssl:
  997. if port == -1:
  998. port = NNTP_PORT
  999. s = NNTP(host=args.server, port=port)
  1000. else:
  1001. if port == -1:
  1002. port = NNTP_SSL_PORT
  1003. s = NNTP_SSL(host=args.server, port=port)
  1004. caps = s.getcapabilities()
  1005. if 'STARTTLS' in caps:
  1006. s.starttls()
  1007. resp, count, first, last, name = s.group(args.group)
  1008. print('Group', name, 'has', count, 'articles, range', first, 'to', last)
  1009. def cut(s, lim):
  1010. if len(s) > lim:
  1011. s = s[:lim - 4] + "..."
  1012. return s
  1013. first = str(int(last) - args.nb_articles + 1)
  1014. resp, overviews = s.xover(first, last)
  1015. for artnum, over in overviews:
  1016. author = decode_header(over['from']).split('<', 1)[0]
  1017. subject = decode_header(over['subject'])
  1018. lines = int(over[':lines'])
  1019. print("{:7} {:20} {:42} ({})".format(
  1020. artnum, cut(author, 20), cut(subject, 42), lines)
  1021. )
  1022. s.quit()