nntp.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. # -*- test-case-name: twisted.news.test.test_nntp -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. NNTP protocol support.
  6. The following protocol commands are currently understood::
  7. LIST LISTGROUP XOVER XHDR
  8. POST GROUP ARTICLE STAT HEAD
  9. BODY NEXT MODE STREAM MODE READER SLAVE
  10. LAST QUIT HELP IHAVE XPATH
  11. XINDEX XROVER TAKETHIS CHECK
  12. The following protocol commands require implementation::
  13. NEWNEWS
  14. XGTITLE XPAT
  15. XTHREAD AUTHINFO NEWGROUPS
  16. Other desired features:
  17. - A real backend
  18. - More robust client input handling
  19. - A control protocol
  20. """
  21. from __future__ import print_function
  22. import time
  23. from twisted.protocols import basic
  24. from twisted.python import log
  25. def parseRange(text):
  26. articles = text.split('-')
  27. if len(articles) == 1:
  28. try:
  29. a = int(articles[0])
  30. return a, a
  31. except ValueError:
  32. return None, None
  33. elif len(articles) == 2:
  34. try:
  35. if len(articles[0]):
  36. l = int(articles[0])
  37. else:
  38. l = None
  39. if len(articles[1]):
  40. h = int(articles[1])
  41. else:
  42. h = None
  43. except ValueError:
  44. return None, None
  45. return l, h
  46. def extractCode(line):
  47. line = line.split(' ', 1)
  48. if len(line) != 2:
  49. return None
  50. try:
  51. return int(line[0]), line[1]
  52. except ValueError:
  53. return None
  54. class NNTPError(Exception):
  55. def __init__(self, string):
  56. self.string = string
  57. def __str__(self):
  58. return 'NNTPError: %s' % self.string
  59. class NNTPClient(basic.LineReceiver):
  60. MAX_COMMAND_LENGTH = 510
  61. def __init__(self):
  62. self.currentGroup = None
  63. self._state = []
  64. self._error = []
  65. self._inputBuffers = []
  66. self._responseCodes = []
  67. self._responseHandlers = []
  68. self._postText = []
  69. self._newState(self._statePassive, None, self._headerInitial)
  70. def gotAllGroups(self, groups):
  71. "Override for notification when fetchGroups() action is completed"
  72. def getAllGroupsFailed(self, error):
  73. "Override for notification when fetchGroups() action fails"
  74. def gotOverview(self, overview):
  75. "Override for notification when fetchOverview() action is completed"
  76. def getOverviewFailed(self, error):
  77. "Override for notification when fetchOverview() action fails"
  78. def gotSubscriptions(self, subscriptions):
  79. "Override for notification when fetchSubscriptions() action is completed"
  80. def getSubscriptionsFailed(self, error):
  81. "Override for notification when fetchSubscriptions() action fails"
  82. def gotGroup(self, group):
  83. "Override for notification when fetchGroup() action is completed"
  84. def getGroupFailed(self, error):
  85. "Override for notification when fetchGroup() action fails"
  86. def gotArticle(self, article):
  87. "Override for notification when fetchArticle() action is completed"
  88. def getArticleFailed(self, error):
  89. "Override for notification when fetchArticle() action fails"
  90. def gotHead(self, head):
  91. "Override for notification when fetchHead() action is completed"
  92. def getHeadFailed(self, error):
  93. "Override for notification when fetchHead() action fails"
  94. def gotBody(self, info):
  95. "Override for notification when fetchBody() action is completed"
  96. def getBodyFailed(self, body):
  97. "Override for notification when fetchBody() action fails"
  98. def postedOk(self):
  99. "Override for notification when postArticle() action is successful"
  100. def postFailed(self, error):
  101. "Override for notification when postArticle() action fails"
  102. def gotXHeader(self, headers):
  103. "Override for notification when getXHeader() action is successful"
  104. def getXHeaderFailed(self, error):
  105. "Override for notification when getXHeader() action fails"
  106. def gotNewNews(self, news):
  107. "Override for notification when getNewNews() action is successful"
  108. def getNewNewsFailed(self, error):
  109. "Override for notification when getNewNews() action fails"
  110. def gotNewGroups(self, groups):
  111. "Override for notification when getNewGroups() action is successful"
  112. def getNewGroupsFailed(self, error):
  113. "Override for notification when getNewGroups() action fails"
  114. def setStreamSuccess(self):
  115. "Override for notification when setStream() action is successful"
  116. def setStreamFailed(self, error):
  117. "Override for notification when setStream() action fails"
  118. def fetchGroups(self):
  119. """
  120. Request a list of all news groups from the server. gotAllGroups()
  121. is called on success, getGroupsFailed() on failure
  122. """
  123. self.sendLine('LIST')
  124. self._newState(self._stateList, self.getAllGroupsFailed)
  125. def fetchOverview(self):
  126. """
  127. Request the overview format from the server. gotOverview() is called
  128. on success, getOverviewFailed() on failure
  129. """
  130. self.sendLine('LIST OVERVIEW.FMT')
  131. self._newState(self._stateOverview, self.getOverviewFailed)
  132. def fetchSubscriptions(self):
  133. """
  134. Request a list of the groups it is recommended a new user subscribe to.
  135. gotSubscriptions() is called on success, getSubscriptionsFailed() on
  136. failure
  137. """
  138. self.sendLine('LIST SUBSCRIPTIONS')
  139. self._newState(self._stateSubscriptions, self.getSubscriptionsFailed)
  140. def fetchGroup(self, group):
  141. """
  142. Get group information for the specified group from the server. gotGroup()
  143. is called on success, getGroupFailed() on failure.
  144. """
  145. self.sendLine('GROUP %s' % (group,))
  146. self._newState(None, self.getGroupFailed, self._headerGroup)
  147. def fetchHead(self, index = ''):
  148. """
  149. Get the header for the specified article (or the currently selected
  150. article if index is '') from the server. gotHead() is called on
  151. success, getHeadFailed() on failure
  152. """
  153. self.sendLine('HEAD %s' % (index,))
  154. self._newState(self._stateHead, self.getHeadFailed)
  155. def fetchBody(self, index = ''):
  156. """
  157. Get the body for the specified article (or the currently selected
  158. article if index is '') from the server. gotBody() is called on
  159. success, getBodyFailed() on failure
  160. """
  161. self.sendLine('BODY %s' % (index,))
  162. self._newState(self._stateBody, self.getBodyFailed)
  163. def fetchArticle(self, index = ''):
  164. """
  165. Get the complete article with the specified index (or the currently
  166. selected article if index is '') or Message-ID from the server.
  167. gotArticle() is called on success, getArticleFailed() on failure.
  168. """
  169. self.sendLine('ARTICLE %s' % (index,))
  170. self._newState(self._stateArticle, self.getArticleFailed)
  171. def postArticle(self, text):
  172. """
  173. Attempt to post an article with the specified text to the server. 'text'
  174. must consist of both head and body data, as specified by RFC 850. If the
  175. article is posted successfully, postedOk() is called, otherwise postFailed()
  176. is called.
  177. """
  178. self.sendLine('POST')
  179. self._newState(None, self.postFailed, self._headerPost)
  180. self._postText.append(text)
  181. def fetchNewNews(self, groups, date, distributions = ''):
  182. """
  183. Get the Message-IDs for all new news posted to any of the given
  184. groups since the specified date - in seconds since the epoch, GMT -
  185. optionally restricted to the given distributions. gotNewNews() is
  186. called on success, getNewNewsFailed() on failure.
  187. One invocation of this function may result in multiple invocations
  188. of gotNewNews()/getNewNewsFailed().
  189. """
  190. date, timeStr = time.strftime('%y%m%d %H%M%S', time.gmtime(date)).split()
  191. line = 'NEWNEWS %%s %s %s %s' % (date, timeStr, distributions)
  192. groupPart = ''
  193. while len(groups) and len(line) + len(groupPart) + len(groups[-1]) + 1 < NNTPClient.MAX_COMMAND_LENGTH:
  194. group = groups.pop()
  195. groupPart = groupPart + ',' + group
  196. self.sendLine(line % (groupPart,))
  197. self._newState(self._stateNewNews, self.getNewNewsFailed)
  198. if len(groups):
  199. self.fetchNewNews(groups, date, distributions)
  200. def fetchNewGroups(self, date, distributions):
  201. """
  202. Get the names of all new groups created/added to the server since
  203. the specified date - in seconds since the ecpoh, GMT - optionally
  204. restricted to the given distributions. gotNewGroups() is called
  205. on success, getNewGroupsFailed() on failure.
  206. """
  207. date, timeStr = time.strftime('%y%m%d %H%M%S', time.gmtime(date)).split()
  208. self.sendLine('NEWGROUPS %s %s %s' % (date, timeStr, distributions))
  209. self._newState(self._stateNewGroups, self.getNewGroupsFailed)
  210. def fetchXHeader(self, header, low = None, high = None, id = None):
  211. """
  212. Request a specific header from the server for an article or range
  213. of articles. If 'id' is not None, a header for only the article
  214. with that Message-ID will be requested. If both low and high are
  215. None, a header for the currently selected article will be selected;
  216. If both low and high are zero-length strings, headers for all articles
  217. in the currently selected group will be requested; Otherwise, high
  218. and low will be used as bounds - if one is None the first or last
  219. article index will be substituted, as appropriate.
  220. """
  221. if id is not None:
  222. r = header + ' <%s>' % (id,)
  223. elif low is high is None:
  224. r = header
  225. elif high is None:
  226. r = header + ' %d-' % (low,)
  227. elif low is None:
  228. r = header + ' -%d' % (high,)
  229. else:
  230. r = header + ' %d-%d' % (low, high)
  231. self.sendLine('XHDR ' + r)
  232. self._newState(self._stateXHDR, self.getXHeaderFailed)
  233. def setStream(self):
  234. """
  235. Set the mode to STREAM, suspending the normal "lock-step" mode of
  236. communications. setStreamSuccess() is called on success,
  237. setStreamFailed() on failure.
  238. """
  239. self.sendLine('MODE STREAM')
  240. self._newState(None, self.setStreamFailed, self._headerMode)
  241. def quit(self):
  242. self.sendLine('QUIT')
  243. self.transport.loseConnection()
  244. def _newState(self, method, error, responseHandler = None):
  245. self._inputBuffers.append([])
  246. self._responseCodes.append(None)
  247. self._state.append(method)
  248. self._error.append(error)
  249. self._responseHandlers.append(responseHandler)
  250. def _endState(self):
  251. buf = self._inputBuffers[0]
  252. del self._responseCodes[0]
  253. del self._inputBuffers[0]
  254. del self._state[0]
  255. del self._error[0]
  256. del self._responseHandlers[0]
  257. return buf
  258. def _newLine(self, line, check = 1):
  259. if check and line and line[0] == '.':
  260. line = line[1:]
  261. self._inputBuffers[0].append(line)
  262. def _setResponseCode(self, code):
  263. self._responseCodes[0] = code
  264. def _getResponseCode(self):
  265. return self._responseCodes[0]
  266. def lineReceived(self, line):
  267. if not len(self._state):
  268. self._statePassive(line)
  269. elif self._getResponseCode() is None:
  270. code = extractCode(line)
  271. if code is None or not (200 <= code[0] < 400): # An error!
  272. self._error[0](line)
  273. self._endState()
  274. else:
  275. self._setResponseCode(code)
  276. if self._responseHandlers[0]:
  277. self._responseHandlers[0](code)
  278. else:
  279. self._state[0](line)
  280. def _statePassive(self, line):
  281. log.msg('Server said: %s' % line)
  282. def _passiveError(self, error):
  283. log.err('Passive Error: %s' % (error,))
  284. def _headerInitial(self, response):
  285. (code, message) = response
  286. if code == 200:
  287. self.canPost = 1
  288. else:
  289. self.canPost = 0
  290. self._endState()
  291. def _stateList(self, line):
  292. if line != '.':
  293. data = filter(None, line.strip().split())
  294. self._newLine((data[0], int(data[1]), int(data[2]), data[3]), 0)
  295. else:
  296. self.gotAllGroups(self._endState())
  297. def _stateOverview(self, line):
  298. if line != '.':
  299. self._newLine(filter(None, line.strip().split()), 0)
  300. else:
  301. self.gotOverview(self._endState())
  302. def _stateSubscriptions(self, line):
  303. if line != '.':
  304. self._newLine(line.strip(), 0)
  305. else:
  306. self.gotSubscriptions(self._endState())
  307. def _headerGroup(self, response):
  308. (code, line) = response
  309. self.gotGroup(tuple(line.split()))
  310. self._endState()
  311. def _stateArticle(self, line):
  312. if line != '.':
  313. if line.startswith('.'):
  314. line = line[1:]
  315. self._newLine(line, 0)
  316. else:
  317. self.gotArticle('\n'.join(self._endState())+'\n')
  318. def _stateHead(self, line):
  319. if line != '.':
  320. self._newLine(line, 0)
  321. else:
  322. self.gotHead('\n'.join(self._endState()))
  323. def _stateBody(self, line):
  324. if line != '.':
  325. if line.startswith('.'):
  326. line = line[1:]
  327. self._newLine(line, 0)
  328. else:
  329. self.gotBody('\n'.join(self._endState())+'\n')
  330. def _headerPost(self, response):
  331. (code, message) = response
  332. if code == 340:
  333. self.transport.write(self._postText[0].replace('\n', '\r\n').replace('\r\n.', '\r\n..'))
  334. if self._postText[0][-1:] != '\n':
  335. self.sendLine('')
  336. self.sendLine('.')
  337. del self._postText[0]
  338. self._newState(None, self.postFailed, self._headerPosted)
  339. else:
  340. self.postFailed('%d %s' % (code, message))
  341. self._endState()
  342. def _headerPosted(self, response):
  343. (code, message) = response
  344. if code == 240:
  345. self.postedOk()
  346. else:
  347. self.postFailed('%d %s' % (code, message))
  348. self._endState()
  349. def _stateXHDR(self, line):
  350. if line != '.':
  351. self._newLine(line.split(), 0)
  352. else:
  353. self._gotXHeader(self._endState())
  354. def _stateNewNews(self, line):
  355. if line != '.':
  356. self._newLine(line, 0)
  357. else:
  358. self.gotNewNews(self._endState())
  359. def _stateNewGroups(self, line):
  360. if line != '.':
  361. self._newLine(line, 0)
  362. else:
  363. self.gotNewGroups(self._endState())
  364. def _headerMode(self, response):
  365. (code, message) = response
  366. if code == 203:
  367. self.setStreamSuccess()
  368. else:
  369. self.setStreamFailed((code, message))
  370. self._endState()
  371. class NNTPServer(basic.LineReceiver):
  372. COMMANDS = [
  373. 'LIST', 'GROUP', 'ARTICLE', 'STAT', 'MODE', 'LISTGROUP', 'XOVER',
  374. 'XHDR', 'HEAD', 'BODY', 'NEXT', 'LAST', 'POST', 'QUIT', 'IHAVE',
  375. 'HELP', 'SLAVE', 'XPATH', 'XINDEX', 'XROVER', 'TAKETHIS', 'CHECK'
  376. ]
  377. def __init__(self):
  378. self.servingSlave = 0
  379. def connectionMade(self):
  380. self.inputHandler = None
  381. self.currentGroup = None
  382. self.currentIndex = None
  383. self.sendLine('200 server ready - posting allowed')
  384. def lineReceived(self, line):
  385. if self.inputHandler is not None:
  386. self.inputHandler(line)
  387. else:
  388. parts = line.strip().split()
  389. if len(parts):
  390. cmd, parts = parts[0].upper(), parts[1:]
  391. if cmd in NNTPServer.COMMANDS:
  392. func = getattr(self, 'do_%s' % cmd)
  393. try:
  394. func(*parts)
  395. except TypeError:
  396. self.sendLine('501 command syntax error')
  397. log.msg("501 command syntax error")
  398. log.msg("command was", line)
  399. log.deferr()
  400. except:
  401. self.sendLine('503 program fault - command not performed')
  402. log.msg("503 program fault")
  403. log.msg("command was", line)
  404. log.deferr()
  405. else:
  406. self.sendLine('500 command not recognized')
  407. def do_LIST(self, subcmd = '', *dummy):
  408. subcmd = subcmd.strip().lower()
  409. if subcmd == 'newsgroups':
  410. # XXX - this could use a real implementation, eh?
  411. self.sendLine('215 Descriptions in form "group description"')
  412. self.sendLine('.')
  413. elif subcmd == 'overview.fmt':
  414. defer = self.factory.backend.overviewRequest()
  415. defer.addCallbacks(self._gotOverview, self._errOverview)
  416. log.msg('overview')
  417. elif subcmd == 'subscriptions':
  418. defer = self.factory.backend.subscriptionRequest()
  419. defer.addCallbacks(self._gotSubscription, self._errSubscription)
  420. log.msg('subscriptions')
  421. elif subcmd == '':
  422. defer = self.factory.backend.listRequest()
  423. defer.addCallbacks(self._gotList, self._errList)
  424. else:
  425. self.sendLine('500 command not recognized')
  426. def _gotList(self, list):
  427. self.sendLine('215 newsgroups in form "group high low flags"')
  428. for i in list:
  429. self.sendLine('%s %d %d %s' % tuple(i))
  430. self.sendLine('.')
  431. def _errList(self, failure):
  432. print('LIST failed: ', failure)
  433. self.sendLine('503 program fault - command not performed')
  434. def _gotSubscription(self, parts):
  435. self.sendLine('215 information follows')
  436. for i in parts:
  437. self.sendLine(i)
  438. self.sendLine('.')
  439. def _errSubscription(self, failure):
  440. print('SUBSCRIPTIONS failed: ', failure)
  441. self.sendLine('503 program fault - comand not performed')
  442. def _gotOverview(self, parts):
  443. self.sendLine('215 Order of fields in overview database.')
  444. for i in parts:
  445. self.sendLine(i + ':')
  446. self.sendLine('.')
  447. def _errOverview(self, failure):
  448. print('LIST OVERVIEW.FMT failed: ', failure)
  449. self.sendLine('503 program fault - command not performed')
  450. def do_LISTGROUP(self, group = None):
  451. group = group or self.currentGroup
  452. if group is None:
  453. self.sendLine('412 Not currently in newsgroup')
  454. else:
  455. defer = self.factory.backend.listGroupRequest(group)
  456. defer.addCallbacks(self._gotListGroup, self._errListGroup)
  457. def _gotListGroup(self, result):
  458. (group, articles) = result
  459. self.currentGroup = group
  460. if len(articles):
  461. self.currentIndex = int(articles[0])
  462. else:
  463. self.currentIndex = None
  464. self.sendLine('211 list of article numbers follow')
  465. for i in articles:
  466. self.sendLine(str(i))
  467. self.sendLine('.')
  468. def _errListGroup(self, failure):
  469. print('LISTGROUP failed: ', failure)
  470. self.sendLine('502 no permission')
  471. def do_XOVER(self, range):
  472. if self.currentGroup is None:
  473. self.sendLine('412 No news group currently selected')
  474. else:
  475. l, h = parseRange(range)
  476. defer = self.factory.backend.xoverRequest(self.currentGroup, l, h)
  477. defer.addCallbacks(self._gotXOver, self._errXOver)
  478. def _gotXOver(self, parts):
  479. self.sendLine('224 Overview information follows')
  480. for i in parts:
  481. self.sendLine('\t'.join(map(str, i)))
  482. self.sendLine('.')
  483. def _errXOver(self, failure):
  484. print('XOVER failed: ', failure)
  485. self.sendLine('420 No article(s) selected')
  486. def xhdrWork(self, header, range):
  487. if self.currentGroup is None:
  488. self.sendLine('412 No news group currently selected')
  489. else:
  490. if range is None:
  491. if self.currentIndex is None:
  492. self.sendLine('420 No current article selected')
  493. return
  494. else:
  495. l = h = self.currentIndex
  496. else:
  497. # FIXME: articles may be a message-id
  498. l, h = parseRange(range)
  499. if l is h is None:
  500. self.sendLine('430 no such article')
  501. else:
  502. return self.factory.backend.xhdrRequest(self.currentGroup, l, h, header)
  503. def do_XHDR(self, header, range = None):
  504. d = self.xhdrWork(header, range)
  505. if d:
  506. d.addCallbacks(self._gotXHDR, self._errXHDR)
  507. def _gotXHDR(self, parts):
  508. self.sendLine('221 Header follows')
  509. for i in parts:
  510. self.sendLine('%d %s' % i)
  511. self.sendLine('.')
  512. def _errXHDR(self, failure):
  513. print('XHDR failed: ', failure)
  514. self.sendLine('502 no permission')
  515. def do_POST(self):
  516. self.inputHandler = self._doingPost
  517. self.message = ''
  518. self.sendLine('340 send article to be posted. End with <CR-LF>.<CR-LF>')
  519. def _doingPost(self, line):
  520. if line == '.':
  521. self.inputHandler = None
  522. article = self.message
  523. self.message = ''
  524. defer = self.factory.backend.postRequest(article)
  525. defer.addCallbacks(self._gotPost, self._errPost)
  526. else:
  527. self.message = self.message + line + '\r\n'
  528. def _gotPost(self, parts):
  529. self.sendLine('240 article posted ok')
  530. def _errPost(self, failure):
  531. print('POST failed: ', failure)
  532. self.sendLine('441 posting failed')
  533. def do_CHECK(self, id):
  534. d = self.factory.backend.articleExistsRequest(id)
  535. d.addCallbacks(self._gotCheck, self._errCheck)
  536. def _gotCheck(self, result):
  537. if result:
  538. self.sendLine("438 already have it, please don't send it to me")
  539. else:
  540. self.sendLine('238 no such article found, please send it to me')
  541. def _errCheck(self, failure):
  542. print('CHECK failed: ', failure)
  543. self.sendLine('431 try sending it again later')
  544. def do_TAKETHIS(self, id):
  545. self.inputHandler = self._doingTakeThis
  546. self.message = ''
  547. def _doingTakeThis(self, line):
  548. if line == '.':
  549. self.inputHandler = None
  550. article = self.message
  551. self.message = ''
  552. d = self.factory.backend.postRequest(article)
  553. d.addCallbacks(self._didTakeThis, self._errTakeThis)
  554. else:
  555. self.message = self.message + line + '\r\n'
  556. def _didTakeThis(self, result):
  557. self.sendLine('239 article transferred ok')
  558. def _errTakeThis(self, failure):
  559. print('TAKETHIS failed: ', failure)
  560. self.sendLine('439 article transfer failed')
  561. def do_GROUP(self, group):
  562. defer = self.factory.backend.groupRequest(group)
  563. defer.addCallbacks(self._gotGroup, self._errGroup)
  564. def _gotGroup(self, result):
  565. (name, num, high, low, flags) = result
  566. self.currentGroup = name
  567. self.currentIndex = low
  568. self.sendLine('211 %d %d %d %s group selected' % (num, low, high, name))
  569. def _errGroup(self, failure):
  570. print('GROUP failed: ', failure)
  571. self.sendLine('411 no such group')
  572. def articleWork(self, article, cmd, func):
  573. if self.currentGroup is None:
  574. self.sendLine('412 no newsgroup has been selected')
  575. else:
  576. if not article:
  577. if self.currentIndex is None:
  578. self.sendLine('420 no current article has been selected')
  579. else:
  580. article = self.currentIndex
  581. else:
  582. if article[0] == '<':
  583. return func(self.currentGroup, index = None, id = article)
  584. else:
  585. try:
  586. article = int(article)
  587. return func(self.currentGroup, article)
  588. except ValueError:
  589. self.sendLine('501 command syntax error')
  590. def do_ARTICLE(self, article = None):
  591. defer = self.articleWork(article, 'ARTICLE', self.factory.backend.articleRequest)
  592. if defer:
  593. defer.addCallbacks(self._gotArticle, self._errArticle)
  594. def _gotArticle(self, result):
  595. (index, id, article) = result
  596. self.currentIndex = index
  597. self.sendLine('220 %d %s article' % (index, id))
  598. s = basic.FileSender()
  599. d = s.beginFileTransfer(article, self.transport)
  600. d.addCallback(self.finishedFileTransfer)
  601. ##
  602. ## Helper for FileSender
  603. ##
  604. def finishedFileTransfer(self, lastsent):
  605. if lastsent != '\n':
  606. line = '\r\n.'
  607. else:
  608. line = '.'
  609. self.sendLine(line)
  610. ##
  611. def _errArticle(self, failure):
  612. print('ARTICLE failed: ', failure)
  613. self.sendLine('423 bad article number')
  614. def do_STAT(self, article = None):
  615. defer = self.articleWork(article, 'STAT', self.factory.backend.articleRequest)
  616. if defer:
  617. defer.addCallbacks(self._gotStat, self._errStat)
  618. def _gotStat(self, result):
  619. (index, id, article) = result
  620. self.currentIndex = index
  621. self.sendLine('223 %d %s article retreived - request text separately' % (index, id))
  622. def _errStat(self, failure):
  623. print('STAT failed: ', failure)
  624. self.sendLine('423 bad article number')
  625. def do_HEAD(self, article = None):
  626. defer = self.articleWork(article, 'HEAD', self.factory.backend.headRequest)
  627. if defer:
  628. defer.addCallbacks(self._gotHead, self._errHead)
  629. def _gotHead(self, result):
  630. (index, id, head) = result
  631. self.currentIndex = index
  632. self.sendLine('221 %d %s article retrieved' % (index, id))
  633. self.transport.write(head + '\r\n')
  634. self.sendLine('.')
  635. def _errHead(self, failure):
  636. print('HEAD failed: ', failure)
  637. self.sendLine('423 no such article number in this group')
  638. def do_BODY(self, article):
  639. defer = self.articleWork(article, 'BODY', self.factory.backend.bodyRequest)
  640. if defer:
  641. defer.addCallbacks(self._gotBody, self._errBody)
  642. def _gotBody(self, result):
  643. (index, id, body) = result
  644. self.currentIndex = index
  645. self.sendLine('221 %d %s article retrieved' % (index, id))
  646. self.lastsent = ''
  647. s = basic.FileSender()
  648. d = s.beginFileTransfer(body, self.transport)
  649. d.addCallback(self.finishedFileTransfer)
  650. def _errBody(self, failure):
  651. print('BODY failed: ', failure)
  652. self.sendLine('423 no such article number in this group')
  653. # NEXT and LAST are just STATs that increment currentIndex first.
  654. # Accordingly, use the STAT callbacks.
  655. def do_NEXT(self):
  656. i = self.currentIndex + 1
  657. defer = self.factory.backend.articleRequest(self.currentGroup, i)
  658. defer.addCallbacks(self._gotStat, self._errStat)
  659. def do_LAST(self):
  660. i = self.currentIndex - 1
  661. defer = self.factory.backend.articleRequest(self.currentGroup, i)
  662. defer.addCallbacks(self._gotStat, self._errStat)
  663. def do_MODE(self, cmd):
  664. cmd = cmd.strip().upper()
  665. if cmd == 'READER':
  666. self.servingSlave = 0
  667. self.sendLine('200 Hello, you can post')
  668. elif cmd == 'STREAM':
  669. self.sendLine('500 Command not understood')
  670. else:
  671. # This is not a mistake
  672. self.sendLine('500 Command not understood')
  673. def do_QUIT(self):
  674. self.sendLine('205 goodbye')
  675. self.transport.loseConnection()
  676. def do_HELP(self):
  677. self.sendLine('100 help text follows')
  678. self.sendLine('Read the RFC.')
  679. self.sendLine('.')
  680. def do_SLAVE(self):
  681. self.sendLine('202 slave status noted')
  682. self.servingeSlave = 1
  683. def do_XPATH(self, article):
  684. # XPATH is a silly thing to have. No client has the right to ask
  685. # for this piece of information from me, and so that is what I'll
  686. # tell them.
  687. self.sendLine('502 access restriction or permission denied')
  688. def do_XINDEX(self, article):
  689. # XINDEX is another silly command. The RFC suggests it be relegated
  690. # to the history books, and who am I to disagree?
  691. self.sendLine('502 access restriction or permission denied')
  692. def do_XROVER(self, range=None):
  693. """
  694. Handle a request for references of all messages in the currently
  695. selected group.
  696. This generates the same response a I{XHDR References} request would
  697. generate.
  698. """
  699. self.do_XHDR('References', range)
  700. def do_IHAVE(self, id):
  701. self.factory.backend.articleExistsRequest(id).addCallback(self._foundArticle)
  702. def _foundArticle(self, result):
  703. if result:
  704. self.sendLine('437 article rejected - do not try again')
  705. else:
  706. self.sendLine('335 send article to be transferred. End with <CR-LF>.<CR-LF>')
  707. self.inputHandler = self._handleIHAVE
  708. self.message = ''
  709. def _handleIHAVE(self, line):
  710. if line == '.':
  711. self.inputHandler = None
  712. self.factory.backend.postRequest(
  713. self.message
  714. ).addCallbacks(self._gotIHAVE, self._errIHAVE)
  715. self.message = ''
  716. else:
  717. self.message = self.message + line + '\r\n'
  718. def _gotIHAVE(self, result):
  719. self.sendLine('235 article transferred ok')
  720. def _errIHAVE(self, failure):
  721. print('IHAVE failed: ', failure)
  722. self.sendLine('436 transfer failed - try again later')
  723. class UsenetClientProtocol(NNTPClient):
  724. """
  725. A client that connects to an NNTP server and asks for articles new
  726. since a certain time.
  727. """
  728. def __init__(self, groups, date, storage):
  729. """
  730. Fetch all new articles from the given groups since the
  731. given date and dump them into the given storage. groups
  732. is a list of group names. date is an integer or floating
  733. point representing seconds since the epoch (GMT). storage is
  734. any object that implements the NewsStorage interface.
  735. """
  736. NNTPClient.__init__(self)
  737. self.groups, self.date, self.storage = groups, date, storage
  738. def connectionMade(self):
  739. NNTPClient.connectionMade(self)
  740. log.msg("Initiating update with remote host: " + str(self.transport.getPeer()))
  741. self.setStream()
  742. self.fetchNewNews(self.groups, self.date, '')
  743. def articleExists(self, exists, article):
  744. if exists:
  745. self.fetchArticle(article)
  746. else:
  747. self.count = self.count - 1
  748. self.disregard = self.disregard + 1
  749. def gotNewNews(self, news):
  750. self.disregard = 0
  751. self.count = len(news)
  752. log.msg("Transferring " + str(self.count) +
  753. " articles from remote host: " + str(self.transport.getPeer()))
  754. for i in news:
  755. self.storage.articleExistsRequest(i).addCallback(self.articleExists, i)
  756. def getNewNewsFailed(self, reason):
  757. log.msg("Updated failed (" + reason + ") with remote host: " + str(self.transport.getPeer()))
  758. self.quit()
  759. def gotArticle(self, article):
  760. self.storage.postRequest(article)
  761. self.count = self.count - 1
  762. if not self.count:
  763. log.msg("Completed update with remote host: " + str(self.transport.getPeer()))
  764. if self.disregard:
  765. log.msg("Disregarded %d articles." % (self.disregard,))
  766. self.factory.updateChecks(self.transport.getPeer())
  767. self.quit()