pb.py 52 KB

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