You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pb.py 51KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  1. # -*- test-case-name: twisted.spread.test.test_pb -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Perspective Broker
  6. \"This isn\'t a professional opinion, but it's probably got enough
  7. internet to kill you.\" --glyph
  8. Introduction
  9. ============
  10. This is a broker for proxies for and copies of objects. It provides a
  11. translucent interface layer to those proxies.
  12. The protocol is not opaque, because it provides objects which represent the
  13. remote proxies and require no context (server references, IDs) to operate on.
  14. It is not transparent because it does I{not} attempt to make remote objects
  15. behave identically, or even similarly, to local objects. Method calls are
  16. invoked asynchronously, and specific rules are applied when serializing
  17. arguments.
  18. To get started, begin with L{PBClientFactory} and L{PBServerFactory}.
  19. @author: Glyph Lefkowitz
  20. """
  21. from __future__ import absolute_import, division
  22. import random
  23. from hashlib import md5
  24. from zope.interface import implementer, Interface
  25. # Twisted Imports
  26. from twisted.python import log, failure, reflect
  27. from twisted.python.compat import (unicode, _bytesChr as chr, range,
  28. comparable, cmp)
  29. from twisted.internet import defer, protocol
  30. from twisted.cred.portal import Portal
  31. from twisted.cred.credentials import IAnonymous, ICredentials
  32. from twisted.cred.credentials import IUsernameHashedPassword, Anonymous
  33. from twisted.persisted import styles
  34. from twisted.python.components import registerAdapter
  35. from twisted.spread.interfaces import IJellyable, IUnjellyable
  36. from twisted.spread.jelly import jelly, unjelly, globalSecurity, _newInstance
  37. from twisted.spread import banana
  38. from twisted.spread.flavors import Serializable
  39. from twisted.spread.flavors import Referenceable, NoSuchMethod
  40. from twisted.spread.flavors import Root, IPBRoot
  41. from twisted.spread.flavors import ViewPoint
  42. from twisted.spread.flavors import Viewable
  43. from twisted.spread.flavors import Copyable
  44. from twisted.spread.flavors import Jellyable
  45. from twisted.spread.flavors import Cacheable
  46. from twisted.spread.flavors import RemoteCopy
  47. from twisted.spread.flavors import RemoteCache
  48. from twisted.spread.flavors import RemoteCacheObserver
  49. from twisted.spread.flavors import copyTags
  50. from twisted.spread.flavors import setUnjellyableForClass
  51. from twisted.spread.flavors import setUnjellyableFactoryForClass
  52. from twisted.spread.flavors import setUnjellyableForClassTree
  53. # These three are backwards compatibility aliases for the previous three.
  54. # Ultimately they should be deprecated. -exarkun
  55. from twisted.spread.flavors import setCopierForClass
  56. from twisted.spread.flavors import setFactoryForClass
  57. from twisted.spread.flavors import setCopierForClassTree
  58. MAX_BROKER_REFS = 1024
  59. portno = 8787
  60. class ProtocolError(Exception):
  61. """
  62. This error is raised when an invalid protocol statement is received.
  63. """
  64. class DeadReferenceError(ProtocolError):
  65. """
  66. This error is raised when a method is called on a dead reference (one whose
  67. broker has been disconnected).
  68. """
  69. class Error(Exception):
  70. """
  71. This error can be raised to generate known error conditions.
  72. When a PB callable method (perspective_, remote_, view_) raises
  73. this error, it indicates that a traceback should not be printed,
  74. but instead, the string representation of the exception should be
  75. sent.
  76. """
  77. class RemoteError(Exception):
  78. """
  79. This class is used to wrap a string-ified exception from the remote side to
  80. be able to reraise it. (Raising string exceptions is no longer possible in
  81. Python 2.6+)
  82. The value of this exception will be a str() representation of the remote
  83. value.
  84. @ivar remoteType: The full import path of the exception class which was
  85. raised on the remote end.
  86. @type remoteType: C{str}
  87. @ivar remoteTraceback: The remote traceback.
  88. @type remoteTraceback: C{str}
  89. @note: It's not possible to include the remoteTraceback if this exception is
  90. thrown into a generator. It must be accessed as an attribute.
  91. """
  92. def __init__(self, remoteType, value, remoteTraceback):
  93. Exception.__init__(self, value)
  94. self.remoteType = remoteType
  95. self.remoteTraceback = remoteTraceback
  96. @comparable
  97. class RemoteMethod:
  98. """
  99. This is a translucent reference to a remote message.
  100. """
  101. def __init__(self, obj, name):
  102. """
  103. Initialize with a L{RemoteReference} and the name of this message.
  104. """
  105. self.obj = obj
  106. self.name = name
  107. def __cmp__(self, other):
  108. return cmp((self.obj, self.name), other)
  109. def __hash__(self):
  110. return hash((self.obj, self.name))
  111. def __call__(self, *args, **kw):
  112. """
  113. Asynchronously invoke a remote method.
  114. """
  115. return self.obj.broker._sendMessage(b'', self.obj.perspective,
  116. self.obj.luid, self.name.encode("utf-8"), args, kw)
  117. class PBConnectionLost(Exception):
  118. pass
  119. class IPerspective(Interface):
  120. """
  121. per*spec*tive, n. : The relationship of aspects of a subject to each
  122. other and to a whole: 'a perspective of history'; 'a need to view
  123. the problem in the proper perspective'.
  124. This is a Perspective Broker-specific wrapper for an avatar. That
  125. is to say, a PB-published view on to the business logic for the
  126. system's concept of a 'user'.
  127. The concept of attached/detached is no longer implemented by the
  128. framework. The realm is expected to implement such semantics if
  129. needed.
  130. """
  131. def perspectiveMessageReceived(broker, message, args, kwargs):
  132. """
  133. This method is called when a network message is received.
  134. @arg broker: The Perspective Broker.
  135. @type message: str
  136. @arg message: The name of the method called by the other end.
  137. @type args: list in jelly format
  138. @arg args: The arguments that were passed by the other end. It
  139. is recommend that you use the `unserialize' method of the
  140. broker to decode this.
  141. @type kwargs: dict in jelly format
  142. @arg kwargs: The keyword arguments that were passed by the
  143. other end. It is recommended that you use the
  144. `unserialize' method of the broker to decode this.
  145. @rtype: A jelly list.
  146. @return: It is recommended that you use the `serialize' method
  147. of the broker on whatever object you need to return to
  148. generate the return value.
  149. """
  150. @implementer(IPerspective)
  151. class Avatar:
  152. """
  153. A default IPerspective implementor.
  154. This class is intended to be subclassed, and a realm should return
  155. an instance of such a subclass when IPerspective is requested of
  156. it.
  157. A peer requesting a perspective will receive only a
  158. L{RemoteReference} to a pb.Avatar. When a method is called on
  159. that L{RemoteReference}, it will translate to a method on the
  160. remote perspective named 'perspective_methodname'. (For more
  161. information on invoking methods on other objects, see
  162. L{flavors.ViewPoint}.)
  163. """
  164. def perspectiveMessageReceived(self, broker, message, args, kw):
  165. """
  166. This method is called when a network message is received.
  167. This will call::
  168. self.perspective_%(message)s(*broker.unserialize(args),
  169. **broker.unserialize(kw))
  170. to handle the method; subclasses of Avatar are expected to
  171. implement methods using this naming convention.
  172. """
  173. args = broker.unserialize(args, self)
  174. kw = broker.unserialize(kw, self)
  175. method = getattr(self, "perspective_%s" % message)
  176. try:
  177. state = method(*args, **kw)
  178. except TypeError:
  179. log.msg("%s didn't accept %s and %s" % (method, args, kw))
  180. raise
  181. return broker.serialize(state, self, method, args, kw)
  182. class AsReferenceable(Referenceable):
  183. """
  184. A reference directed towards another object.
  185. """
  186. def __init__(self, object, messageType="remote"):
  187. self.remoteMessageReceived = getattr(
  188. object, messageType + "MessageReceived")
  189. @implementer(IUnjellyable)
  190. @comparable
  191. class RemoteReference(Serializable, styles.Ephemeral):
  192. """
  193. A translucent reference to a remote object.
  194. I may be a reference to a L{flavors.ViewPoint}, a
  195. L{flavors.Referenceable}, or an L{IPerspective} implementer (e.g.,
  196. pb.Avatar). From the client's perspective, it is not possible to
  197. tell which except by convention.
  198. I am a \"translucent\" reference because although no additional
  199. bookkeeping overhead is given to the application programmer for
  200. manipulating a reference, return values are asynchronous.
  201. See also L{twisted.internet.defer}.
  202. @ivar broker: The broker I am obtained through.
  203. @type broker: L{Broker}
  204. """
  205. def __init__(self, perspective, broker, luid, doRefCount):
  206. """(internal) Initialize me with a broker and a locally-unique ID.
  207. The ID is unique only to the particular Perspective Broker
  208. instance.
  209. """
  210. self.luid = luid
  211. self.broker = broker
  212. self.doRefCount = doRefCount
  213. self.perspective = perspective
  214. self.disconnectCallbacks = []
  215. def notifyOnDisconnect(self, callback):
  216. """
  217. Register a callback to be called if our broker gets disconnected.
  218. @param callback: a callable which will be called with one
  219. argument, this instance.
  220. """
  221. assert callable(callback)
  222. self.disconnectCallbacks.append(callback)
  223. if len(self.disconnectCallbacks) == 1:
  224. self.broker.notifyOnDisconnect(self._disconnected)
  225. def dontNotifyOnDisconnect(self, callback):
  226. """
  227. Remove a callback that was registered with notifyOnDisconnect.
  228. @param callback: a callable
  229. """
  230. self.disconnectCallbacks.remove(callback)
  231. if not self.disconnectCallbacks:
  232. self.broker.dontNotifyOnDisconnect(self._disconnected)
  233. def _disconnected(self):
  234. """
  235. Called if we are disconnected and have callbacks registered.
  236. """
  237. for callback in self.disconnectCallbacks:
  238. callback(self)
  239. self.disconnectCallbacks = None
  240. def jellyFor(self, jellier):
  241. """
  242. If I am being sent back to where I came from, serialize as a local backreference.
  243. """
  244. if jellier.invoker:
  245. assert self.broker == jellier.invoker, "Can't send references to brokers other than their own."
  246. return b"local", self.luid
  247. else:
  248. return b"unpersistable", "References cannot be serialized"
  249. def unjellyFor(self, unjellier, unjellyList):
  250. self.__init__(unjellier.invoker.unserializingPerspective, unjellier.invoker, unjellyList[1], 1)
  251. return self
  252. def callRemote(self, _name, *args, **kw):
  253. """
  254. Asynchronously invoke a remote method.
  255. @type _name: L{str}
  256. @param _name: the name of the remote method to invoke
  257. @param args: arguments to serialize for the remote function
  258. @param kw: keyword arguments to serialize for the remote function.
  259. @rtype: L{twisted.internet.defer.Deferred}
  260. @returns: a Deferred which will be fired when the result of
  261. this remote call is received.
  262. """
  263. if not isinstance(_name, bytes):
  264. _name = _name.encode('utf8')
  265. # Note that we use '_name' instead of 'name' so the user can call
  266. # remote methods with 'name' as a keyword parameter, like this:
  267. # ref.callRemote("getPeopleNamed", count=12, name="Bob")
  268. return self.broker._sendMessage(b'', self.perspective, self.luid,
  269. _name, args, kw)
  270. def remoteMethod(self, key):
  271. """
  272. @param key: The key.
  273. @return: A L{RemoteMethod} for this key.
  274. """
  275. return RemoteMethod(self, key)
  276. def __cmp__(self, other):
  277. """
  278. @param other: another L{RemoteReference} to compare me to.
  279. """
  280. if isinstance(other, RemoteReference):
  281. if other.broker == self.broker:
  282. return cmp(self.luid, other.luid)
  283. return cmp(self.broker, other)
  284. def __hash__(self):
  285. """
  286. Hash me.
  287. """
  288. return self.luid
  289. def __del__(self):
  290. """
  291. Do distributed reference counting on finalization.
  292. """
  293. if self.doRefCount:
  294. self.broker.sendDecRef(self.luid)
  295. setUnjellyableForClass("remote", RemoteReference)
  296. class Local:
  297. """
  298. (internal) A reference to a local object.
  299. """
  300. def __init__(self, object, perspective=None):
  301. """
  302. Initialize.
  303. """
  304. self.object = object
  305. self.perspective = perspective
  306. self.refcount = 1
  307. def __repr__(self):
  308. return "<pb.Local %r ref:%s>" % (self.object, self.refcount)
  309. def incref(self):
  310. """
  311. Increment the reference count.
  312. @return: the reference count after incrementing
  313. """
  314. self.refcount = self.refcount + 1
  315. return self.refcount
  316. def decref(self):
  317. """
  318. Decrement the reference count.
  319. @return: the reference count after decrementing
  320. """
  321. self.refcount = self.refcount - 1
  322. return self.refcount
  323. # Failure
  324. class CopyableFailure(failure.Failure, Copyable):
  325. """
  326. A L{flavors.RemoteCopy} and L{flavors.Copyable} version of
  327. L{twisted.python.failure.Failure} for serialization.
  328. """
  329. unsafeTracebacks = 0
  330. def getStateToCopy(self):
  331. """
  332. Collect state related to the exception which occurred, discarding
  333. state which cannot reasonably be serialized.
  334. """
  335. state = self.__dict__.copy()
  336. state['tb'] = None
  337. state['frames'] = []
  338. state['stack'] = []
  339. state['value'] = str(self.value) # Exception instance
  340. if isinstance(self.type, bytes):
  341. state['type'] = self.type
  342. else:
  343. state['type'] = reflect.qual(self.type).encode('utf-8') # Exception class
  344. if self.unsafeTracebacks:
  345. state['traceback'] = self.getTraceback()
  346. else:
  347. state['traceback'] = 'Traceback unavailable\n'
  348. return state
  349. class CopiedFailure(RemoteCopy, failure.Failure):
  350. """
  351. A L{CopiedFailure} is a L{pb.RemoteCopy} of a L{failure.Failure}
  352. transferred via PB.
  353. @ivar type: The full import path of the exception class which was raised on
  354. the remote end.
  355. @type type: C{str}
  356. @ivar value: A str() representation of the remote value.
  357. @type value: L{CopiedFailure} or C{str}
  358. @ivar traceback: The remote traceback.
  359. @type traceback: C{str}
  360. """
  361. def printTraceback(self, file=None, elideFrameworkCode=0, detail='default'):
  362. if file is None:
  363. file = log.logfile
  364. failureType = self.type
  365. if not isinstance(failureType, str):
  366. failureType = failureType.decode("utf-8")
  367. file.write("Traceback from remote host -- ")
  368. file.write(failureType + ": " + self.value)
  369. file.write('\n')
  370. def throwExceptionIntoGenerator(self, g):
  371. """
  372. Throw the original exception into the given generator, preserving
  373. traceback information if available. In the case of a L{CopiedFailure}
  374. where the exception type is a string, a L{pb.RemoteError} is thrown
  375. instead.
  376. @return: The next value yielded from the generator.
  377. @raise StopIteration: If there are no more values in the generator.
  378. @raise RemoteError: The wrapped remote exception.
  379. """
  380. return g.throw(RemoteError(self.type, self.value, self.traceback))
  381. printBriefTraceback = printTraceback
  382. printDetailedTraceback = printTraceback
  383. setUnjellyableForClass(CopyableFailure, CopiedFailure)
  384. def failure2Copyable(fail, unsafeTracebacks=0):
  385. f = _newInstance(CopyableFailure, fail.__dict__)
  386. f.unsafeTracebacks = unsafeTracebacks
  387. return f
  388. class Broker(banana.Banana):
  389. """
  390. I am a broker for objects.
  391. """
  392. version = 6
  393. username = None
  394. factory = None
  395. def __init__(self, isClient=1, security=globalSecurity):
  396. banana.Banana.__init__(self, isClient)
  397. self.disconnected = 0
  398. self.disconnects = []
  399. self.failures = []
  400. self.connects = []
  401. self.localObjects = {}
  402. self.security = security
  403. self.pageProducers = []
  404. self.currentRequestID = 0
  405. self.currentLocalID = 0
  406. self.unserializingPerspective = None
  407. # Some terms:
  408. # PUID: process unique ID; return value of id() function. type "int".
  409. # LUID: locally unique ID; an ID unique to an object mapped over this
  410. # connection. type "int"
  411. # GUID: (not used yet) globally unique ID; an ID for an object which
  412. # may be on a redirected or meta server. Type as yet undecided.
  413. # Dictionary mapping LUIDs to local objects.
  414. # set above to allow root object to be assigned before connection is made
  415. # self.localObjects = {}
  416. # Dictionary mapping PUIDs to LUIDs.
  417. self.luids = {}
  418. # Dictionary mapping LUIDs to local (remotely cached) objects. Remotely
  419. # cached means that they're objects which originate here, and were
  420. # copied remotely.
  421. self.remotelyCachedObjects = {}
  422. # Dictionary mapping PUIDs to (cached) LUIDs
  423. self.remotelyCachedLUIDs = {}
  424. # Dictionary mapping (remote) LUIDs to (locally cached) objects.
  425. self.locallyCachedObjects = {}
  426. self.waitingForAnswers = {}
  427. # Mapping from LUIDs to weakref objects with callbacks for performing
  428. # any local cleanup which may be necessary for the corresponding
  429. # object once it no longer exists.
  430. self._localCleanup = {}
  431. def resumeProducing(self):
  432. """
  433. Called when the consumer attached to me runs out of buffer.
  434. """
  435. # Go backwards over the list so we can remove indexes from it as we go
  436. for pageridx in range(len(self.pageProducers)-1, -1, -1):
  437. pager = self.pageProducers[pageridx]
  438. pager.sendNextPage()
  439. if not pager.stillPaging():
  440. del self.pageProducers[pageridx]
  441. if not self.pageProducers:
  442. self.transport.unregisterProducer()
  443. def pauseProducing(self):
  444. # Streaming producer method; not necessary to implement.
  445. pass
  446. def stopProducing(self):
  447. # Streaming producer method; not necessary to implement.
  448. pass
  449. def registerPageProducer(self, pager):
  450. self.pageProducers.append(pager)
  451. if len(self.pageProducers) == 1:
  452. self.transport.registerProducer(self, 0)
  453. def expressionReceived(self, sexp):
  454. """
  455. Evaluate an expression as it's received.
  456. """
  457. if isinstance(sexp, list):
  458. command = sexp[0]
  459. if not isinstance(command, str):
  460. command = command.decode('utf8')
  461. methodName = "proto_%s" % command
  462. method = getattr(self, methodName, None)
  463. if method:
  464. method(*sexp[1:])
  465. else:
  466. self.sendCall(b"didNotUnderstand", command)
  467. else:
  468. raise ProtocolError("Non-list expression received.")
  469. def proto_version(self, vnum):
  470. """
  471. Protocol message: (version version-number)
  472. Check to make sure that both ends of the protocol are speaking
  473. the same version dialect.
  474. @param vnum: The version number.
  475. """
  476. if vnum != self.version:
  477. raise ProtocolError("Version Incompatibility: %s %s" % (self.version, vnum))
  478. def sendCall(self, *exp):
  479. """
  480. Utility method to send an expression to the other side of the connection.
  481. @param exp: The expression.
  482. """
  483. self.sendEncoded(exp)
  484. def proto_didNotUnderstand(self, command):
  485. """
  486. Respond to stock 'C{didNotUnderstand}' message.
  487. Log the command that was not understood and continue. (Note:
  488. this will probably be changed to close the connection or raise
  489. an exception in the future.)
  490. @param command: The command to log.
  491. """
  492. log.msg("Didn't understand command: %r" % command)
  493. def connectionReady(self):
  494. """
  495. Initialize. Called after Banana negotiation is done.
  496. """
  497. self.sendCall(b"version", self.version)
  498. for notifier in self.connects:
  499. try:
  500. notifier()
  501. except:
  502. log.deferr()
  503. self.connects = None
  504. self.factory.clientConnectionMade(self)
  505. def connectionFailed(self):
  506. # XXX should never get called anymore? check!
  507. for notifier in self.failures:
  508. try:
  509. notifier()
  510. except:
  511. log.deferr()
  512. self.failures = None
  513. waitingForAnswers = None
  514. def connectionLost(self, reason):
  515. """
  516. The connection was lost.
  517. @param reason: message to put in L{failure.Failure}
  518. """
  519. self.disconnected = 1
  520. # Nuke potential circular references.
  521. self.luids = None
  522. if self.waitingForAnswers:
  523. for d in self.waitingForAnswers.values():
  524. try:
  525. d.errback(failure.Failure(PBConnectionLost(reason)))
  526. except:
  527. log.deferr()
  528. # Assure all Cacheable.stoppedObserving are called
  529. for lobj in self.remotelyCachedObjects.values():
  530. cacheable = lobj.object
  531. perspective = lobj.perspective
  532. try:
  533. cacheable.stoppedObserving(perspective, RemoteCacheObserver(self, cacheable, perspective))
  534. except:
  535. log.deferr()
  536. # Loop on a copy to prevent notifiers to mixup
  537. # the list by calling dontNotifyOnDisconnect
  538. for notifier in self.disconnects[:]:
  539. try:
  540. notifier()
  541. except:
  542. log.deferr()
  543. self.disconnects = None
  544. self.waitingForAnswers = None
  545. self.localSecurity = None
  546. self.remoteSecurity = None
  547. self.remotelyCachedObjects = None
  548. self.remotelyCachedLUIDs = None
  549. self.locallyCachedObjects = None
  550. self.localObjects = None
  551. def notifyOnDisconnect(self, notifier):
  552. """
  553. @param notifier: callback to call when the Broker disconnects.
  554. """
  555. assert callable(notifier)
  556. self.disconnects.append(notifier)
  557. def notifyOnFail(self, notifier):
  558. """
  559. @param notifier: callback to call if the Broker fails to connect.
  560. """
  561. assert callable(notifier)
  562. self.failures.append(notifier)
  563. def notifyOnConnect(self, notifier):
  564. """
  565. @param notifier: callback to call when the Broker connects.
  566. """
  567. assert callable(notifier)
  568. if self.connects is None:
  569. try:
  570. notifier()
  571. except:
  572. log.err()
  573. else:
  574. self.connects.append(notifier)
  575. def dontNotifyOnDisconnect(self, notifier):
  576. """
  577. @param notifier: callback to remove from list of disconnect callbacks.
  578. """
  579. try:
  580. self.disconnects.remove(notifier)
  581. except ValueError:
  582. pass
  583. def localObjectForID(self, luid):
  584. """
  585. Get a local object for a locally unique ID.
  586. @return: An object previously stored with L{registerReference} or
  587. L{None} if there is no object which corresponds to the given
  588. identifier.
  589. """
  590. if isinstance(luid, unicode):
  591. luid = luid.encode('utf8')
  592. lob = self.localObjects.get(luid)
  593. if lob is None:
  594. return
  595. return lob.object
  596. maxBrokerRefsViolations = 0
  597. def registerReference(self, object):
  598. """
  599. Store a persistent reference to a local object and map its
  600. id() to a generated, session-unique ID.
  601. @param object: a local object
  602. @return: the generated ID
  603. """
  604. assert object is not None
  605. puid = object.processUniqueID()
  606. luid = self.luids.get(puid)
  607. if luid is None:
  608. if len(self.localObjects) > MAX_BROKER_REFS:
  609. self.maxBrokerRefsViolations = self.maxBrokerRefsViolations + 1
  610. if self.maxBrokerRefsViolations > 3:
  611. self.transport.loseConnection()
  612. raise Error("Maximum PB reference count exceeded. "
  613. "Goodbye.")
  614. raise Error("Maximum PB reference count exceeded.")
  615. luid = self.newLocalID()
  616. self.localObjects[luid] = Local(object)
  617. self.luids[puid] = luid
  618. else:
  619. self.localObjects[luid].incref()
  620. return luid
  621. def setNameForLocal(self, name, object):
  622. """
  623. Store a special (string) ID for this object.
  624. This is how you specify a 'base' set of objects that the remote
  625. protocol can connect to.
  626. @param name: An ID.
  627. @param object: The object.
  628. """
  629. if isinstance(name, unicode):
  630. name = name.encode('utf8')
  631. assert object is not None
  632. self.localObjects[name] = Local(object)
  633. def remoteForName(self, name):
  634. """
  635. Returns an object from the remote name mapping.
  636. Note that this does not check the validity of the name, only
  637. creates a translucent reference for it.
  638. @param name: The name to look up.
  639. @return: An object which maps to the name.
  640. """
  641. if isinstance(name, unicode):
  642. name = name.encode('utf8')
  643. return RemoteReference(None, self, name, 0)
  644. def cachedRemotelyAs(self, instance, incref=0):
  645. """
  646. @param instance: The instance to look up.
  647. @param incref: Flag to specify whether to increment the
  648. reference.
  649. @return: An ID that says what this instance is cached as
  650. remotely, or L{None} if it's not.
  651. """
  652. puid = instance.processUniqueID()
  653. luid = self.remotelyCachedLUIDs.get(puid)
  654. if (luid is not None) and (incref):
  655. self.remotelyCachedObjects[luid].incref()
  656. return luid
  657. def remotelyCachedForLUID(self, luid):
  658. """
  659. @param luid: The LUID to look up.
  660. @return: An instance which is cached remotely.
  661. """
  662. return self.remotelyCachedObjects[luid].object
  663. def cacheRemotely(self, instance):
  664. """
  665. XXX
  666. @return: A new LUID.
  667. """
  668. puid = instance.processUniqueID()
  669. luid = self.newLocalID()
  670. if len(self.remotelyCachedObjects) > MAX_BROKER_REFS:
  671. self.maxBrokerRefsViolations = self.maxBrokerRefsViolations + 1
  672. if self.maxBrokerRefsViolations > 3:
  673. self.transport.loseConnection()
  674. raise Error("Maximum PB cache count exceeded. "
  675. "Goodbye.")
  676. raise Error("Maximum PB cache count exceeded.")
  677. self.remotelyCachedLUIDs[puid] = luid
  678. # This table may not be necessary -- for now, it's to make sure that no
  679. # monkey business happens with id(instance)
  680. self.remotelyCachedObjects[luid] = Local(instance, self.serializingPerspective)
  681. return luid
  682. def cacheLocally(self, cid, instance):
  683. """(internal)
  684. Store a non-filled-out cached instance locally.
  685. """
  686. self.locallyCachedObjects[cid] = instance
  687. def cachedLocallyAs(self, cid):
  688. instance = self.locallyCachedObjects[cid]
  689. return instance
  690. def serialize(self, object, perspective=None, method=None, args=None, kw=None):
  691. """
  692. Jelly an object according to the remote security rules for this broker.
  693. @param object: The object to jelly.
  694. @param perspective: The perspective.
  695. @param method: The method.
  696. @param args: Arguments.
  697. @param kw: Keyword arguments.
  698. """
  699. if isinstance(object, defer.Deferred):
  700. object.addCallbacks(self.serialize, lambda x: x,
  701. callbackKeywords={
  702. 'perspective': perspective,
  703. 'method': method,
  704. 'args': args,
  705. 'kw': kw
  706. })
  707. return object
  708. # XXX This call is NOT REENTRANT and testing for reentrancy is just
  709. # crazy, so it likely won't be. Don't ever write methods that call the
  710. # broker's serialize() method recursively (e.g. sending a method call
  711. # from within a getState (this causes concurrency problems anyway so
  712. # you really, really shouldn't do it))
  713. self.serializingPerspective = perspective
  714. self.jellyMethod = method
  715. self.jellyArgs = args
  716. self.jellyKw = kw
  717. try:
  718. return jelly(object, self.security, None, self)
  719. finally:
  720. self.serializingPerspective = None
  721. self.jellyMethod = None
  722. self.jellyArgs = None
  723. self.jellyKw = None
  724. def unserialize(self, sexp, perspective = None):
  725. """
  726. Unjelly an sexp according to the local security rules for this broker.
  727. @param sexp: The object to unjelly.
  728. @param perspective: The perspective.
  729. """
  730. self.unserializingPerspective = perspective
  731. try:
  732. return unjelly(sexp, self.security, None, self)
  733. finally:
  734. self.unserializingPerspective = None
  735. def newLocalID(self):
  736. """
  737. @return: A newly generated LUID.
  738. """
  739. self.currentLocalID = self.currentLocalID + 1
  740. return self.currentLocalID
  741. def newRequestID(self):
  742. """
  743. @return: A newly generated request ID.
  744. """
  745. self.currentRequestID = self.currentRequestID + 1
  746. return self.currentRequestID
  747. def _sendMessage(self, prefix, perspective, objectID, message, args, kw):
  748. pbc = None
  749. pbe = None
  750. answerRequired = 1
  751. if 'pbcallback' in kw:
  752. pbc = kw['pbcallback']
  753. del kw['pbcallback']
  754. if 'pberrback' in kw:
  755. pbe = kw['pberrback']
  756. del kw['pberrback']
  757. if 'pbanswer' in kw:
  758. assert (not pbe) and (not pbc), "You can't specify a no-answer requirement."
  759. answerRequired = kw['pbanswer']
  760. del kw['pbanswer']
  761. if self.disconnected:
  762. raise DeadReferenceError("Calling Stale Broker")
  763. try:
  764. netArgs = self.serialize(args, perspective=perspective, method=message)
  765. netKw = self.serialize(kw, perspective=perspective, method=message)
  766. except:
  767. return defer.fail(failure.Failure())
  768. requestID = self.newRequestID()
  769. if answerRequired:
  770. rval = defer.Deferred()
  771. self.waitingForAnswers[requestID] = rval
  772. if pbc or pbe:
  773. log.msg('warning! using deprecated "pbcallback"')
  774. rval.addCallbacks(pbc, pbe)
  775. else:
  776. rval = None
  777. self.sendCall(prefix + b"message", requestID, objectID, message, answerRequired, netArgs, netKw)
  778. return rval
  779. def proto_message(self, requestID, objectID, message, answerRequired, netArgs, netKw):
  780. self._recvMessage(self.localObjectForID, requestID, objectID, message, answerRequired, netArgs, netKw)
  781. def proto_cachemessage(self, requestID, objectID, message, answerRequired, netArgs, netKw):
  782. self._recvMessage(self.cachedLocallyAs, requestID, objectID, message, answerRequired, netArgs, netKw)
  783. def _recvMessage(self, findObjMethod, requestID, objectID, message, answerRequired, netArgs, netKw):
  784. """
  785. Received a message-send.
  786. Look up message based on object, unserialize the arguments, and
  787. invoke it with args, and send an 'answer' or 'error' response.
  788. @param findObjMethod: A callable which takes C{objectID} as argument.
  789. @param requestID: The requiest ID.
  790. @param objectID: The object ID.
  791. @param message: The message.
  792. @param answerRequired:
  793. @param netArgs: Arguments.
  794. @param netKw: Keyword arguments.
  795. """
  796. if not isinstance(message, str):
  797. message = message.decode('utf8')
  798. try:
  799. object = findObjMethod(objectID)
  800. if object is None:
  801. raise Error("Invalid Object ID")
  802. netResult = object.remoteMessageReceived(self, message, netArgs, netKw)
  803. except Error as e:
  804. if answerRequired:
  805. # If the error is Jellyable or explicitly allowed via our
  806. # security options, send it back and let the code on the
  807. # other end deal with unjellying. If it isn't Jellyable,
  808. # wrap it in a CopyableFailure, which ensures it can be
  809. # unjellied on the other end. We have to do this because
  810. # all errors must be sent back.
  811. if isinstance(e, Jellyable) or self.security.isClassAllowed(e.__class__):
  812. self._sendError(e, requestID)
  813. else:
  814. self._sendError(CopyableFailure(e), requestID)
  815. except:
  816. if answerRequired:
  817. log.msg("Peer will receive following PB traceback:", isError=True)
  818. f = CopyableFailure()
  819. self._sendError(f, requestID)
  820. log.err()
  821. else:
  822. if answerRequired:
  823. if isinstance(netResult, defer.Deferred):
  824. args = (requestID,)
  825. netResult.addCallbacks(self._sendAnswer, self._sendFailureOrError,
  826. callbackArgs=args, errbackArgs=args)
  827. # XXX Should this be done somewhere else?
  828. else:
  829. self._sendAnswer(netResult, requestID)
  830. def _sendAnswer(self, netResult, requestID):
  831. """
  832. (internal) Send an answer to a previously sent message.
  833. @param netResult: The answer.
  834. @param requestID: The request ID.
  835. """
  836. self.sendCall(b"answer", requestID, netResult)
  837. def proto_answer(self, requestID, netResult):
  838. """
  839. (internal) Got an answer to a previously sent message.
  840. Look up the appropriate callback and call it.
  841. @param requestID: The request ID.
  842. @param netResult: The answer.
  843. """
  844. d = self.waitingForAnswers[requestID]
  845. del self.waitingForAnswers[requestID]
  846. d.callback(self.unserialize(netResult))
  847. def _sendFailureOrError(self, fail, requestID):
  848. """
  849. Call L{_sendError} or L{_sendFailure}, depending on whether C{fail}
  850. represents an L{Error} subclass or not.
  851. @param fail: The failure.
  852. @param requestID: The request ID.
  853. """
  854. if fail.check(Error) is None:
  855. self._sendFailure(fail, requestID)
  856. else:
  857. self._sendError(fail, requestID)
  858. def _sendFailure(self, fail, requestID):
  859. """
  860. Log error and then send it.
  861. @param fail: The failure.
  862. @param requestID: The request ID.
  863. """
  864. log.msg("Peer will receive following PB traceback:")
  865. log.err(fail)
  866. self._sendError(fail, requestID)
  867. def _sendError(self, fail, requestID):
  868. """
  869. (internal) Send an error for a previously sent message.
  870. @param fail: The failure.
  871. @param requestID: The request ID.
  872. """
  873. if isinstance(fail, failure.Failure):
  874. # If the failures value is jellyable or allowed through security,
  875. # send the value
  876. if (isinstance(fail.value, Jellyable) or
  877. self.security.isClassAllowed(fail.value.__class__)):
  878. fail = fail.value
  879. elif not isinstance(fail, CopyableFailure):
  880. fail = failure2Copyable(fail, self.factory.unsafeTracebacks)
  881. if isinstance(fail, CopyableFailure):
  882. fail.unsafeTracebacks = self.factory.unsafeTracebacks
  883. self.sendCall(b"error", requestID, self.serialize(fail))
  884. def proto_error(self, requestID, fail):
  885. """
  886. (internal) Deal with an error.
  887. @param requestID: The request ID.
  888. @param fail: The failure.
  889. """
  890. d = self.waitingForAnswers[requestID]
  891. del self.waitingForAnswers[requestID]
  892. d.errback(self.unserialize(fail))
  893. def sendDecRef(self, objectID):
  894. """
  895. (internal) Send a DECREF directive.
  896. @param objectID: The object ID.
  897. """
  898. self.sendCall(b"decref", objectID)
  899. def proto_decref(self, objectID):
  900. """
  901. (internal) Decrement the reference count of an object.
  902. If the reference count is zero, it will free the reference to this
  903. object.
  904. @param objectID: The object ID.
  905. """
  906. if isinstance(objectID, unicode):
  907. objectID = objectID.encode('utf8')
  908. refs = self.localObjects[objectID].decref()
  909. if refs == 0:
  910. puid = self.localObjects[objectID].object.processUniqueID()
  911. del self.luids[puid]
  912. del self.localObjects[objectID]
  913. self._localCleanup.pop(puid, lambda: None)()
  914. def decCacheRef(self, objectID):
  915. """
  916. (internal) Send a DECACHE directive.
  917. @param objectID: The object ID.
  918. """
  919. self.sendCall(b"decache", objectID)
  920. def proto_decache(self, objectID):
  921. """
  922. (internal) Decrement the reference count of a cached object.
  923. If the reference count is zero, free the reference, then send an
  924. 'uncached' directive.
  925. @param objectID: The object ID.
  926. """
  927. refs = self.remotelyCachedObjects[objectID].decref()
  928. # log.msg('decaching: %s #refs: %s' % (objectID, refs))
  929. if refs == 0:
  930. lobj = self.remotelyCachedObjects[objectID]
  931. cacheable = lobj.object
  932. perspective = lobj.perspective
  933. # TODO: force_decache needs to be able to force-invalidate a
  934. # cacheable reference.
  935. try:
  936. cacheable.stoppedObserving(perspective, RemoteCacheObserver(self, cacheable, perspective))
  937. except:
  938. log.deferr()
  939. puid = cacheable.processUniqueID()
  940. del self.remotelyCachedLUIDs[puid]
  941. del self.remotelyCachedObjects[objectID]
  942. self.sendCall(b"uncache", objectID)
  943. def proto_uncache(self, objectID):
  944. """
  945. (internal) Tell the client it is now OK to uncache an object.
  946. @param objectID: The object ID.
  947. """
  948. # log.msg("uncaching locally %d" % objectID)
  949. obj = self.locallyCachedObjects[objectID]
  950. obj.broker = None
  951. ## def reallyDel(obj=obj):
  952. ## obj.__really_del__()
  953. ## obj.__del__ = reallyDel
  954. del self.locallyCachedObjects[objectID]
  955. def respond(challenge, password):
  956. """
  957. Respond to a challenge.
  958. This is useful for challenge/response authentication.
  959. @param challenge: A challenge.
  960. @param password: A password.
  961. @return: The password hashed twice.
  962. """
  963. m = md5()
  964. m.update(password)
  965. hashedPassword = m.digest()
  966. m = md5()
  967. m.update(hashedPassword)
  968. m.update(challenge)
  969. doubleHashedPassword = m.digest()
  970. return doubleHashedPassword
  971. def challenge():
  972. """
  973. @return: Some random data.
  974. """
  975. crap = b''
  976. for x in range(random.randrange(15,25)):
  977. crap = crap + chr(random.randint(65,90))
  978. crap = md5(crap).digest()
  979. return crap
  980. class PBClientFactory(protocol.ClientFactory):
  981. """
  982. Client factory for PB brokers.
  983. As with all client factories, use with reactor.connectTCP/SSL/etc..
  984. getPerspective and getRootObject can be called either before or
  985. after the connect.
  986. """
  987. protocol = Broker
  988. unsafeTracebacks = False
  989. def __init__(self, unsafeTracebacks=False, security=globalSecurity):
  990. """
  991. @param unsafeTracebacks: if set, tracebacks for exceptions will be sent
  992. over the wire.
  993. @type unsafeTracebacks: C{bool}
  994. @param security: security options used by the broker, default to
  995. C{globalSecurity}.
  996. @type security: L{twisted.spread.jelly.SecurityOptions}
  997. """
  998. self.unsafeTracebacks = unsafeTracebacks
  999. self.security = security
  1000. self._reset()
  1001. def buildProtocol(self, addr):
  1002. """
  1003. Build the broker instance, passing the security options to it.
  1004. """
  1005. p = self.protocol(isClient=True, security=self.security)
  1006. p.factory = self
  1007. return p
  1008. def _reset(self):
  1009. self.rootObjectRequests = [] # list of deferred
  1010. self._broker = None
  1011. self._root = None
  1012. def _failAll(self, reason):
  1013. deferreds = self.rootObjectRequests
  1014. self._reset()
  1015. for d in deferreds:
  1016. d.errback(reason)
  1017. def clientConnectionFailed(self, connector, reason):
  1018. self._failAll(reason)
  1019. def clientConnectionLost(self, connector, reason, reconnecting=0):
  1020. """
  1021. Reconnecting subclasses should call with reconnecting=1.
  1022. """
  1023. if reconnecting:
  1024. # Any pending requests will go to next connection attempt
  1025. # so we don't fail them.
  1026. self._broker = None
  1027. self._root = None
  1028. else:
  1029. self._failAll(reason)
  1030. def clientConnectionMade(self, broker):
  1031. self._broker = broker
  1032. self._root = broker.remoteForName("root")
  1033. ds = self.rootObjectRequests
  1034. self.rootObjectRequests = []
  1035. for d in ds:
  1036. d.callback(self._root)
  1037. def getRootObject(self):
  1038. """
  1039. Get root object of remote PB server.
  1040. @return: Deferred of the root object.
  1041. """
  1042. if self._broker and not self._broker.disconnected:
  1043. return defer.succeed(self._root)
  1044. d = defer.Deferred()
  1045. self.rootObjectRequests.append(d)
  1046. return d
  1047. def disconnect(self):
  1048. """
  1049. If the factory is connected, close the connection.
  1050. Note that if you set up the factory to reconnect, you will need to
  1051. implement extra logic to prevent automatic reconnection after this
  1052. is called.
  1053. """
  1054. if self._broker:
  1055. self._broker.transport.loseConnection()
  1056. def _cbSendUsername(self, root, username, password, client):
  1057. return root.callRemote("login", username).addCallback(
  1058. self._cbResponse, password, client)
  1059. def _cbResponse(self, challenges, password, client):
  1060. challenge, challenger = challenges
  1061. return challenger.callRemote("respond", respond(challenge, password), client)
  1062. def _cbLoginAnonymous(self, root, client):
  1063. """
  1064. Attempt an anonymous login on the given remote root object.
  1065. @type root: L{RemoteReference}
  1066. @param root: The object on which to attempt the login, most likely
  1067. returned by a call to L{PBClientFactory.getRootObject}.
  1068. @param client: A jellyable object which will be used as the I{mind}
  1069. parameter for the login attempt.
  1070. @rtype: L{Deferred}
  1071. @return: A L{Deferred} which will be called back with a
  1072. L{RemoteReference} to an avatar when anonymous login succeeds, or
  1073. which will errback if anonymous login fails.
  1074. """
  1075. return root.callRemote("loginAnonymous", client)
  1076. def login(self, credentials, client=None):
  1077. """
  1078. Login and get perspective from remote PB server.
  1079. Currently the following credentials are supported::
  1080. L{twisted.cred.credentials.IUsernamePassword}
  1081. L{twisted.cred.credentials.IAnonymous}
  1082. @rtype: L{Deferred}
  1083. @return: A L{Deferred} which will be called back with a
  1084. L{RemoteReference} for the avatar logged in to, or which will
  1085. errback if login fails.
  1086. """
  1087. d = self.getRootObject()
  1088. if IAnonymous.providedBy(credentials):
  1089. d.addCallback(self._cbLoginAnonymous, client)
  1090. else:
  1091. d.addCallback(
  1092. self._cbSendUsername, credentials.username,
  1093. credentials.password, client)
  1094. return d
  1095. class PBServerFactory(protocol.ServerFactory):
  1096. """
  1097. Server factory for perspective broker.
  1098. Login is done using a Portal object, whose realm is expected to return
  1099. avatars implementing IPerspective. The credential checkers in the portal
  1100. should accept IUsernameHashedPassword or IUsernameMD5Password.
  1101. Alternatively, any object providing or adaptable to L{IPBRoot} can be
  1102. used instead of a portal to provide the root object of the PB server.
  1103. """
  1104. unsafeTracebacks = False
  1105. # object broker factory
  1106. protocol = Broker
  1107. def __init__(self, root, unsafeTracebacks=False, security=globalSecurity):
  1108. """
  1109. @param root: factory providing the root Referenceable used by the broker.
  1110. @type root: object providing or adaptable to L{IPBRoot}.
  1111. @param unsafeTracebacks: if set, tracebacks for exceptions will be sent
  1112. over the wire.
  1113. @type unsafeTracebacks: C{bool}
  1114. @param security: security options used by the broker, default to
  1115. C{globalSecurity}.
  1116. @type security: L{twisted.spread.jelly.SecurityOptions}
  1117. """
  1118. self.root = IPBRoot(root)
  1119. self.unsafeTracebacks = unsafeTracebacks
  1120. self.security = security
  1121. def buildProtocol(self, addr):
  1122. """
  1123. Return a Broker attached to the factory (as the service provider).
  1124. """
  1125. proto = self.protocol(isClient=False, security=self.security)
  1126. proto.factory = self
  1127. proto.setNameForLocal("root", self.root.rootObject(proto))
  1128. return proto
  1129. def clientConnectionMade(self, protocol):
  1130. # XXX does this method make any sense?
  1131. pass
  1132. class IUsernameMD5Password(ICredentials):
  1133. """
  1134. I encapsulate a username and a hashed password.
  1135. This credential is used for username/password over PB. CredentialCheckers
  1136. which check this kind of credential must store the passwords in plaintext
  1137. form or as a MD5 digest.
  1138. @type username: C{str} or C{Deferred}
  1139. @ivar username: The username associated with these credentials.
  1140. """
  1141. def checkPassword(password):
  1142. """
  1143. Validate these credentials against the correct password.
  1144. @type password: C{str}
  1145. @param password: The correct, plaintext password against which to
  1146. check.
  1147. @rtype: C{bool} or L{Deferred}
  1148. @return: C{True} if the credentials represented by this object match the
  1149. given password, C{False} if they do not, or a L{Deferred} which will
  1150. be called back with one of these values.
  1151. """
  1152. def checkMD5Password(password):
  1153. """
  1154. Validate these credentials against the correct MD5 digest of the
  1155. password.
  1156. @type password: C{str}
  1157. @param password: The correct MD5 digest of a password against which to
  1158. check.
  1159. @rtype: C{bool} or L{Deferred}
  1160. @return: C{True} if the credentials represented by this object match the
  1161. given digest, C{False} if they do not, or a L{Deferred} which will
  1162. be called back with one of these values.
  1163. """
  1164. @implementer(IPBRoot)
  1165. class _PortalRoot:
  1166. """
  1167. Root object, used to login to portal.
  1168. """
  1169. def __init__(self, portal):
  1170. self.portal = portal
  1171. def rootObject(self, broker):
  1172. return _PortalWrapper(self.portal, broker)
  1173. registerAdapter(_PortalRoot, Portal, IPBRoot)
  1174. class _JellyableAvatarMixin:
  1175. """
  1176. Helper class for code which deals with avatars which PB must be capable of
  1177. sending to a peer.
  1178. """
  1179. def _cbLogin(self, result):
  1180. """
  1181. Ensure that the avatar to be returned to the client is jellyable and
  1182. set up disconnection notification to call the realm's logout object.
  1183. """
  1184. (interface, avatar, logout) = result
  1185. if not IJellyable.providedBy(avatar):
  1186. avatar = AsReferenceable(avatar, "perspective")
  1187. puid = avatar.processUniqueID()
  1188. # only call logout once, whether the connection is dropped (disconnect)
  1189. # or a logout occurs (cleanup), and be careful to drop the reference to
  1190. # it in either case
  1191. logout = [ logout ]
  1192. def maybeLogout():
  1193. if not logout:
  1194. return
  1195. fn = logout[0]
  1196. del logout[0]
  1197. fn()
  1198. self.broker._localCleanup[puid] = maybeLogout
  1199. self.broker.notifyOnDisconnect(maybeLogout)
  1200. return avatar
  1201. class _PortalWrapper(Referenceable, _JellyableAvatarMixin):
  1202. """
  1203. Root Referenceable object, used to login to portal.
  1204. """
  1205. def __init__(self, portal, broker):
  1206. self.portal = portal
  1207. self.broker = broker
  1208. def remote_login(self, username):
  1209. """
  1210. Start of username/password login.
  1211. @param username: The username.
  1212. """
  1213. c = challenge()
  1214. return c, _PortalAuthChallenger(self.portal, self.broker, username, c)
  1215. def remote_loginAnonymous(self, mind):
  1216. """
  1217. Attempt an anonymous login.
  1218. @param mind: An object to use as the mind parameter to the portal login
  1219. call (possibly None).
  1220. @rtype: L{Deferred}
  1221. @return: A Deferred which will be called back with an avatar when login
  1222. succeeds or which will be errbacked if login fails somehow.
  1223. """
  1224. d = self.portal.login(Anonymous(), mind, IPerspective)
  1225. d.addCallback(self._cbLogin)
  1226. return d
  1227. @implementer(IUsernameHashedPassword, IUsernameMD5Password)
  1228. class _PortalAuthChallenger(Referenceable, _JellyableAvatarMixin):
  1229. """
  1230. Called with response to password challenge.
  1231. """
  1232. def __init__(self, portal, broker, username, challenge):
  1233. self.portal = portal
  1234. self.broker = broker
  1235. self.username = username
  1236. self.challenge = challenge
  1237. def remote_respond(self, response, mind):
  1238. self.response = response
  1239. d = self.portal.login(self, mind, IPerspective)
  1240. d.addCallback(self._cbLogin)
  1241. return d
  1242. def checkPassword(self, password):
  1243. """
  1244. L{IUsernameHashedPassword}
  1245. @param password: The password.
  1246. @return: L{_PortalAuthChallenger.checkMD5Password}
  1247. """
  1248. return self.checkMD5Password(md5(password).digest())
  1249. def checkMD5Password(self, md5Password):
  1250. """
  1251. L{IUsernameMD5Password}
  1252. @param md5Password:
  1253. @rtype: L{bool}
  1254. @return: L{True} if password matches.
  1255. """
  1256. md = md5()
  1257. md.update(md5Password)
  1258. md.update(self.challenge)
  1259. correct = md.digest()
  1260. return self.response == correct
  1261. __all__ = [
  1262. # Everything from flavors is exposed publicly here.
  1263. 'IPBRoot', 'Serializable', 'Referenceable', 'NoSuchMethod', 'Root',
  1264. 'ViewPoint', 'Viewable', 'Copyable', 'Jellyable', 'Cacheable',
  1265. 'RemoteCopy', 'RemoteCache', 'RemoteCacheObserver', 'copyTags',
  1266. 'setUnjellyableForClass', 'setUnjellyableFactoryForClass',
  1267. 'setUnjellyableForClassTree',
  1268. 'setCopierForClass', 'setFactoryForClass', 'setCopierForClassTree',
  1269. 'MAX_BROKER_REFS', 'portno',
  1270. 'ProtocolError', 'DeadReferenceError', 'Error', 'PBConnectionLost',
  1271. 'RemoteMethod', 'IPerspective', 'Avatar', 'AsReferenceable',
  1272. 'RemoteReference', 'CopyableFailure', 'CopiedFailure', 'failure2Copyable',
  1273. 'Broker', 'respond', 'challenge', 'PBClientFactory', 'PBServerFactory',
  1274. 'IUsernameMD5Password',
  1275. ]