nntplib.py 40 KB

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