Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  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. state = self.__dict__.copy()
  355. state["tb"] = None
  356. state["frames"] = []
  357. state["stack"] = []
  358. state["value"] = str(self.value) # Exception instance
  359. if isinstance(self.type, bytes):
  360. state["type"] = self.type
  361. else:
  362. state["type"] = reflect.qual(self.type).encode("utf-8") # Exception class
  363. if self.unsafeTracebacks:
  364. state["traceback"] = self.getTraceback()
  365. else:
  366. state["traceback"] = "Traceback unavailable\n"
  367. return state
  368. class CopiedFailure(RemoteCopy, failure.Failure):
  369. """
  370. A L{CopiedFailure} is a L{pb.RemoteCopy} of a L{failure.Failure}
  371. transferred via PB.
  372. @ivar type: The full import path of the exception class which was raised on
  373. the remote end.
  374. @type type: C{str}
  375. @ivar value: A str() representation of the remote value.
  376. @type value: L{CopiedFailure} or C{str}
  377. @ivar traceback: The remote traceback.
  378. @type traceback: C{str}
  379. """
  380. def printTraceback(self, file=None, elideFrameworkCode=0, detail="default"):
  381. if file is None:
  382. file = log.logfile
  383. failureType = self.type
  384. if not isinstance(failureType, str):
  385. failureType = failureType.decode("utf-8")
  386. file.write("Traceback from remote host -- ")
  387. file.write(failureType + ": " + self.value)
  388. file.write("\n")
  389. def throwExceptionIntoGenerator(self, g):
  390. """
  391. Throw the original exception into the given generator, preserving
  392. traceback information if available. In the case of a L{CopiedFailure}
  393. where the exception type is a string, a L{pb.RemoteError} is thrown
  394. instead.
  395. @return: The next value yielded from the generator.
  396. @raise StopIteration: If there are no more values in the generator.
  397. @raise RemoteError: The wrapped remote exception.
  398. """
  399. return g.throw(RemoteError(self.type, self.value, self.traceback))
  400. printBriefTraceback = printTraceback
  401. printDetailedTraceback = printTraceback
  402. setUnjellyableForClass(CopyableFailure, CopiedFailure)
  403. def failure2Copyable(fail, unsafeTracebacks=0):
  404. f = _newInstance(CopyableFailure, fail.__dict__)
  405. f.unsafeTracebacks = unsafeTracebacks
  406. return f
  407. class Broker(banana.Banana):
  408. """
  409. I am a broker for objects.
  410. """
  411. version = 6
  412. username = None
  413. factory = None
  414. def __init__(self, isClient=1, security=globalSecurity):
  415. banana.Banana.__init__(self, isClient)
  416. self.disconnected = 0
  417. self.disconnects = []
  418. self.failures = []
  419. self.connects = []
  420. self.localObjects = {}
  421. self.security = security
  422. self.pageProducers = []
  423. self.currentRequestID = 0
  424. self.currentLocalID = 0
  425. self.unserializingPerspective = None
  426. # Some terms:
  427. # PUID: process unique ID; return value of id() function. type "int".
  428. # LUID: locally unique ID; an ID unique to an object mapped over this
  429. # connection. type "int"
  430. # GUID: (not used yet) globally unique ID; an ID for an object which
  431. # may be on a redirected or meta server. Type as yet undecided.
  432. # Dictionary mapping LUIDs to local objects.
  433. # set above to allow root object to be assigned before connection is made
  434. # self.localObjects = {}
  435. # Dictionary mapping PUIDs to LUIDs.
  436. self.luids = {}
  437. # Dictionary mapping LUIDs to local (remotely cached) objects. Remotely
  438. # cached means that they're objects which originate here, and were
  439. # copied remotely.
  440. self.remotelyCachedObjects = {}
  441. # Dictionary mapping PUIDs to (cached) LUIDs
  442. self.remotelyCachedLUIDs = {}
  443. # Dictionary mapping (remote) LUIDs to (locally cached) objects.
  444. self.locallyCachedObjects = {}
  445. self.waitingForAnswers = {}
  446. # Mapping from LUIDs to weakref objects with callbacks for performing
  447. # any local cleanup which may be necessary for the corresponding
  448. # object once it no longer exists.
  449. self._localCleanup = {}
  450. def resumeProducing(self):
  451. """
  452. Called when the consumer attached to me runs out of buffer.
  453. """
  454. # Go backwards over the list so we can remove indexes from it as we go
  455. for pageridx in range(len(self.pageProducers) - 1, -1, -1):
  456. pager = self.pageProducers[pageridx]
  457. pager.sendNextPage()
  458. if not pager.stillPaging():
  459. del self.pageProducers[pageridx]
  460. if not self.pageProducers:
  461. self.transport.unregisterProducer()
  462. def pauseProducing(self):
  463. # Streaming producer method; not necessary to implement.
  464. pass
  465. def stopProducing(self):
  466. # Streaming producer method; not necessary to implement.
  467. pass
  468. def registerPageProducer(self, pager):
  469. self.pageProducers.append(pager)
  470. if len(self.pageProducers) == 1:
  471. self.transport.registerProducer(self, 0)
  472. def expressionReceived(self, sexp):
  473. """
  474. Evaluate an expression as it's received.
  475. """
  476. if isinstance(sexp, list):
  477. command = sexp[0]
  478. if not isinstance(command, str):
  479. command = command.decode("utf8")
  480. methodName = "proto_%s" % command
  481. method = getattr(self, methodName, None)
  482. if method:
  483. method(*sexp[1:])
  484. else:
  485. self.sendCall(b"didNotUnderstand", command)
  486. else:
  487. raise ProtocolError("Non-list expression received.")
  488. def proto_version(self, vnum):
  489. """
  490. Protocol message: (version version-number)
  491. Check to make sure that both ends of the protocol are speaking
  492. the same version dialect.
  493. @param vnum: The version number.
  494. """
  495. if vnum != self.version:
  496. raise ProtocolError(f"Version Incompatibility: {self.version} {vnum}")
  497. def sendCall(self, *exp):
  498. """
  499. Utility method to send an expression to the other side of the connection.
  500. @param exp: The expression.
  501. """
  502. self.sendEncoded(exp)
  503. def proto_didNotUnderstand(self, command):
  504. """
  505. Respond to stock 'C{didNotUnderstand}' message.
  506. Log the command that was not understood and continue. (Note:
  507. this will probably be changed to close the connection or raise
  508. an exception in the future.)
  509. @param command: The command to log.
  510. """
  511. log.msg("Didn't understand command: %r" % command)
  512. def connectionReady(self):
  513. """
  514. Initialize. Called after Banana negotiation is done.
  515. """
  516. self.sendCall(b"version", self.version)
  517. for notifier in self.connects:
  518. try:
  519. notifier()
  520. except BaseException:
  521. log.deferr()
  522. self.connects = None
  523. self.factory.clientConnectionMade(self)
  524. def connectionFailed(self):
  525. # XXX should never get called anymore? check!
  526. for notifier in self.failures:
  527. try:
  528. notifier()
  529. except BaseException:
  530. log.deferr()
  531. self.failures = None
  532. waitingForAnswers = None
  533. def connectionLost(self, reason):
  534. """
  535. The connection was lost.
  536. @param reason: message to put in L{failure.Failure}
  537. """
  538. self.disconnected = 1
  539. # Nuke potential circular references.
  540. self.luids = None
  541. if self.waitingForAnswers:
  542. for d in self.waitingForAnswers.values():
  543. try:
  544. d.errback(failure.Failure(PBConnectionLost(reason)))
  545. except BaseException:
  546. log.deferr()
  547. # Assure all Cacheable.stoppedObserving are called
  548. for lobj in self.remotelyCachedObjects.values():
  549. cacheable = lobj.object
  550. perspective = lobj.perspective
  551. try:
  552. cacheable.stoppedObserving(
  553. perspective, RemoteCacheObserver(self, cacheable, perspective)
  554. )
  555. except BaseException:
  556. log.deferr()
  557. # Loop on a copy to prevent notifiers to mixup
  558. # the list by calling dontNotifyOnDisconnect
  559. for notifier in self.disconnects[:]:
  560. try:
  561. notifier()
  562. except BaseException:
  563. log.deferr()
  564. self.disconnects = None
  565. self.waitingForAnswers = None
  566. self.localSecurity = None
  567. self.remoteSecurity = None
  568. self.remotelyCachedObjects = None
  569. self.remotelyCachedLUIDs = None
  570. self.locallyCachedObjects = None
  571. self.localObjects = None
  572. def notifyOnDisconnect(self, notifier):
  573. """
  574. @param notifier: callback to call when the Broker disconnects.
  575. """
  576. assert callable(notifier)
  577. self.disconnects.append(notifier)
  578. def notifyOnFail(self, notifier):
  579. """
  580. @param notifier: callback to call if the Broker fails to connect.
  581. """
  582. assert callable(notifier)
  583. self.failures.append(notifier)
  584. def notifyOnConnect(self, notifier):
  585. """
  586. @param notifier: callback to call when the Broker connects.
  587. """
  588. assert callable(notifier)
  589. if self.connects is None:
  590. try:
  591. notifier()
  592. except BaseException:
  593. log.err()
  594. else:
  595. self.connects.append(notifier)
  596. def dontNotifyOnDisconnect(self, notifier):
  597. """
  598. @param notifier: callback to remove from list of disconnect callbacks.
  599. """
  600. try:
  601. self.disconnects.remove(notifier)
  602. except ValueError:
  603. pass
  604. def localObjectForID(self, luid):
  605. """
  606. Get a local object for a locally unique ID.
  607. @return: An object previously stored with L{registerReference} or
  608. L{None} if there is no object which corresponds to the given
  609. identifier.
  610. """
  611. if isinstance(luid, str):
  612. luid = luid.encode("utf8")
  613. lob = self.localObjects.get(luid)
  614. if lob is None:
  615. return
  616. return lob.object
  617. maxBrokerRefsViolations = 0
  618. def registerReference(self, object):
  619. """
  620. Store a persistent reference to a local object and map its
  621. id() to a generated, session-unique ID.
  622. @param object: a local object
  623. @return: the generated ID
  624. """
  625. assert object is not None
  626. puid = object.processUniqueID()
  627. luid = self.luids.get(puid)
  628. if luid is None:
  629. if len(self.localObjects) > MAX_BROKER_REFS:
  630. self.maxBrokerRefsViolations = self.maxBrokerRefsViolations + 1
  631. if self.maxBrokerRefsViolations > 3:
  632. self.transport.loseConnection()
  633. raise Error("Maximum PB reference count exceeded. " "Goodbye.")
  634. raise Error("Maximum PB reference count exceeded.")
  635. luid = self.newLocalID()
  636. self.localObjects[luid] = Local(object)
  637. self.luids[puid] = luid
  638. else:
  639. self.localObjects[luid].incref()
  640. return luid
  641. def setNameForLocal(self, name, object):
  642. """
  643. Store a special (string) ID for this object.
  644. This is how you specify a 'base' set of objects that the remote
  645. protocol can connect to.
  646. @param name: An ID.
  647. @param object: The object.
  648. """
  649. if isinstance(name, str):
  650. name = name.encode("utf8")
  651. assert object is not None
  652. self.localObjects[name] = Local(object)
  653. def remoteForName(self, name):
  654. """
  655. Returns an object from the remote name mapping.
  656. Note that this does not check the validity of the name, only
  657. creates a translucent reference for it.
  658. @param name: The name to look up.
  659. @return: An object which maps to the name.
  660. """
  661. if isinstance(name, str):
  662. name = name.encode("utf8")
  663. return RemoteReference(None, self, name, 0)
  664. def cachedRemotelyAs(self, instance, incref=0):
  665. """
  666. @param instance: The instance to look up.
  667. @param incref: Flag to specify whether to increment the
  668. reference.
  669. @return: An ID that says what this instance is cached as
  670. remotely, or L{None} if it's not.
  671. """
  672. puid = instance.processUniqueID()
  673. luid = self.remotelyCachedLUIDs.get(puid)
  674. if (luid is not None) and (incref):
  675. self.remotelyCachedObjects[luid].incref()
  676. return luid
  677. def remotelyCachedForLUID(self, luid):
  678. """
  679. @param luid: The LUID to look up.
  680. @return: An instance which is cached remotely.
  681. """
  682. return self.remotelyCachedObjects[luid].object
  683. def cacheRemotely(self, instance):
  684. """
  685. XXX
  686. @return: A new LUID.
  687. """
  688. puid = instance.processUniqueID()
  689. luid = self.newLocalID()
  690. if len(self.remotelyCachedObjects) > MAX_BROKER_REFS:
  691. self.maxBrokerRefsViolations = self.maxBrokerRefsViolations + 1
  692. if self.maxBrokerRefsViolations > 3:
  693. self.transport.loseConnection()
  694. raise Error("Maximum PB cache count exceeded. " "Goodbye.")
  695. raise Error("Maximum PB cache count exceeded.")
  696. self.remotelyCachedLUIDs[puid] = luid
  697. # This table may not be necessary -- for now, it's to make sure that no
  698. # monkey business happens with id(instance)
  699. self.remotelyCachedObjects[luid] = Local(instance, self.serializingPerspective)
  700. return luid
  701. def cacheLocally(self, cid, instance):
  702. """(internal)
  703. Store a non-filled-out cached instance locally.
  704. """
  705. self.locallyCachedObjects[cid] = instance
  706. def cachedLocallyAs(self, cid):
  707. instance = self.locallyCachedObjects[cid]
  708. return instance
  709. def serialize(self, object, perspective=None, method=None, args=None, kw=None):
  710. """
  711. Jelly an object according to the remote security rules for this broker.
  712. @param object: The object to jelly.
  713. @param perspective: The perspective.
  714. @param method: The method.
  715. @param args: Arguments.
  716. @param kw: Keyword arguments.
  717. """
  718. if isinstance(object, defer.Deferred):
  719. object.addCallbacks(
  720. self.serialize,
  721. lambda x: x,
  722. callbackKeywords={
  723. "perspective": perspective,
  724. "method": method,
  725. "args": args,
  726. "kw": kw,
  727. },
  728. )
  729. return object
  730. # XXX This call is NOT REENTRANT and testing for reentrancy is just
  731. # crazy, so it likely won't be. Don't ever write methods that call the
  732. # broker's serialize() method recursively (e.g. sending a method call
  733. # from within a getState (this causes concurrency problems anyway so
  734. # you really, really shouldn't do it))
  735. self.serializingPerspective = perspective
  736. self.jellyMethod = method
  737. self.jellyArgs = args
  738. self.jellyKw = kw
  739. try:
  740. return jelly(object, self.security, None, self)
  741. finally:
  742. self.serializingPerspective = None
  743. self.jellyMethod = None
  744. self.jellyArgs = None
  745. self.jellyKw = None
  746. def unserialize(self, sexp, perspective=None):
  747. """
  748. Unjelly an sexp according to the local security rules for this broker.
  749. @param sexp: The object to unjelly.
  750. @param perspective: The perspective.
  751. """
  752. self.unserializingPerspective = perspective
  753. try:
  754. return unjelly(sexp, self.security, None, self)
  755. finally:
  756. self.unserializingPerspective = None
  757. def newLocalID(self):
  758. """
  759. @return: A newly generated LUID.
  760. """
  761. self.currentLocalID = self.currentLocalID + 1
  762. return self.currentLocalID
  763. def newRequestID(self):
  764. """
  765. @return: A newly generated request ID.
  766. """
  767. self.currentRequestID = self.currentRequestID + 1
  768. return self.currentRequestID
  769. def _sendMessage(self, prefix, perspective, objectID, message, args, kw):
  770. pbc = None
  771. pbe = None
  772. answerRequired = 1
  773. if "pbcallback" in kw:
  774. pbc = kw["pbcallback"]
  775. del kw["pbcallback"]
  776. if "pberrback" in kw:
  777. pbe = kw["pberrback"]
  778. del kw["pberrback"]
  779. if "pbanswer" in kw:
  780. assert (not pbe) and (not pbc), "You can't specify a no-answer requirement."
  781. answerRequired = kw["pbanswer"]
  782. del kw["pbanswer"]
  783. if self.disconnected:
  784. raise DeadReferenceError("Calling Stale Broker")
  785. try:
  786. netArgs = self.serialize(args, perspective=perspective, method=message)
  787. netKw = self.serialize(kw, perspective=perspective, method=message)
  788. except BaseException:
  789. return defer.fail(failure.Failure())
  790. requestID = self.newRequestID()
  791. if answerRequired:
  792. rval = defer.Deferred()
  793. self.waitingForAnswers[requestID] = rval
  794. if pbc or pbe:
  795. log.msg('warning! using deprecated "pbcallback"')
  796. rval.addCallbacks(pbc, pbe)
  797. else:
  798. rval = None
  799. self.sendCall(
  800. prefix + b"message",
  801. requestID,
  802. objectID,
  803. message,
  804. answerRequired,
  805. netArgs,
  806. netKw,
  807. )
  808. return rval
  809. def proto_message(
  810. self, requestID, objectID, message, answerRequired, netArgs, netKw
  811. ):
  812. self._recvMessage(
  813. self.localObjectForID,
  814. requestID,
  815. objectID,
  816. message,
  817. answerRequired,
  818. netArgs,
  819. netKw,
  820. )
  821. def proto_cachemessage(
  822. self, requestID, objectID, message, answerRequired, netArgs, netKw
  823. ):
  824. self._recvMessage(
  825. self.cachedLocallyAs,
  826. requestID,
  827. objectID,
  828. message,
  829. answerRequired,
  830. netArgs,
  831. netKw,
  832. )
  833. def _recvMessage(
  834. self,
  835. findObjMethod,
  836. requestID,
  837. objectID,
  838. message,
  839. answerRequired,
  840. netArgs,
  841. netKw,
  842. ):
  843. """
  844. Received a message-send.
  845. Look up message based on object, unserialize the arguments, and
  846. invoke it with args, and send an 'answer' or 'error' response.
  847. @param findObjMethod: A callable which takes C{objectID} as argument.
  848. @param requestID: The requiest ID.
  849. @param objectID: The object ID.
  850. @param message: The message.
  851. @param answerRequired:
  852. @param netArgs: Arguments.
  853. @param netKw: Keyword arguments.
  854. """
  855. if not isinstance(message, str):
  856. message = message.decode("utf8")
  857. try:
  858. object = findObjMethod(objectID)
  859. if object is None:
  860. raise Error("Invalid Object ID")
  861. netResult = object.remoteMessageReceived(self, message, netArgs, netKw)
  862. except Error as e:
  863. if answerRequired:
  864. # If the error is Jellyable or explicitly allowed via our
  865. # security options, send it back and let the code on the
  866. # other end deal with unjellying. If it isn't Jellyable,
  867. # wrap it in a CopyableFailure, which ensures it can be
  868. # unjellied on the other end. We have to do this because
  869. # all errors must be sent back.
  870. if isinstance(e, Jellyable) or self.security.isClassAllowed(
  871. e.__class__
  872. ):
  873. self._sendError(e, requestID)
  874. else:
  875. self._sendError(CopyableFailure(e), requestID)
  876. except BaseException:
  877. if answerRequired:
  878. log.msg("Peer will receive following PB traceback:", isError=True)
  879. f = CopyableFailure()
  880. self._sendError(f, requestID)
  881. log.err()
  882. else:
  883. if answerRequired:
  884. if isinstance(netResult, defer.Deferred):
  885. args = (requestID,)
  886. netResult.addCallbacks(
  887. self._sendAnswer,
  888. self._sendFailureOrError,
  889. callbackArgs=args,
  890. errbackArgs=args,
  891. )
  892. # XXX Should this be done somewhere else?
  893. else:
  894. self._sendAnswer(netResult, requestID)
  895. def _sendAnswer(self, netResult, requestID):
  896. """
  897. (internal) Send an answer to a previously sent message.
  898. @param netResult: The answer.
  899. @param requestID: The request ID.
  900. """
  901. self.sendCall(b"answer", requestID, netResult)
  902. def proto_answer(self, requestID, netResult):
  903. """
  904. (internal) Got an answer to a previously sent message.
  905. Look up the appropriate callback and call it.
  906. @param requestID: The request ID.
  907. @param netResult: The answer.
  908. """
  909. d = self.waitingForAnswers[requestID]
  910. del self.waitingForAnswers[requestID]
  911. d.callback(self.unserialize(netResult))
  912. def _sendFailureOrError(self, fail, requestID):
  913. """
  914. Call L{_sendError} or L{_sendFailure}, depending on whether C{fail}
  915. represents an L{Error} subclass or not.
  916. @param fail: The failure.
  917. @param requestID: The request ID.
  918. """
  919. if fail.check(Error) is None:
  920. self._sendFailure(fail, requestID)
  921. else:
  922. self._sendError(fail, requestID)
  923. def _sendFailure(self, fail, requestID):
  924. """
  925. Log error and then send it.
  926. @param fail: The failure.
  927. @param requestID: The request ID.
  928. """
  929. log.msg("Peer will receive following PB traceback:")
  930. log.err(fail)
  931. self._sendError(fail, requestID)
  932. def _sendError(self, fail, requestID):
  933. """
  934. (internal) Send an error for a previously sent message.
  935. @param fail: The failure.
  936. @param requestID: The request ID.
  937. """
  938. if isinstance(fail, failure.Failure):
  939. # If the failures value is jellyable or allowed through security,
  940. # send the value
  941. if isinstance(fail.value, Jellyable) or self.security.isClassAllowed(
  942. fail.value.__class__
  943. ):
  944. fail = fail.value
  945. elif not isinstance(fail, CopyableFailure):
  946. fail = failure2Copyable(fail, self.factory.unsafeTracebacks)
  947. if isinstance(fail, CopyableFailure):
  948. fail.unsafeTracebacks = self.factory.unsafeTracebacks
  949. self.sendCall(b"error", requestID, self.serialize(fail))
  950. def proto_error(self, requestID, fail):
  951. """
  952. (internal) Deal with an error.
  953. @param requestID: The request ID.
  954. @param fail: The failure.
  955. """
  956. d = self.waitingForAnswers[requestID]
  957. del self.waitingForAnswers[requestID]
  958. d.errback(self.unserialize(fail))
  959. def sendDecRef(self, objectID):
  960. """
  961. (internal) Send a DECREF directive.
  962. @param objectID: The object ID.
  963. """
  964. self.sendCall(b"decref", objectID)
  965. def proto_decref(self, objectID):
  966. """
  967. (internal) Decrement the reference count of an object.
  968. If the reference count is zero, it will free the reference to this
  969. object.
  970. @param objectID: The object ID.
  971. """
  972. if isinstance(objectID, str):
  973. objectID = objectID.encode("utf8")
  974. refs = self.localObjects[objectID].decref()
  975. if refs == 0:
  976. puid = self.localObjects[objectID].object.processUniqueID()
  977. del self.luids[puid]
  978. del self.localObjects[objectID]
  979. self._localCleanup.pop(puid, lambda: None)()
  980. def decCacheRef(self, objectID):
  981. """
  982. (internal) Send a DECACHE directive.
  983. @param objectID: The object ID.
  984. """
  985. self.sendCall(b"decache", objectID)
  986. def proto_decache(self, objectID):
  987. """
  988. (internal) Decrement the reference count of a cached object.
  989. If the reference count is zero, free the reference, then send an
  990. 'uncached' directive.
  991. @param objectID: The object ID.
  992. """
  993. refs = self.remotelyCachedObjects[objectID].decref()
  994. # log.msg('decaching: %s #refs: %s' % (objectID, refs))
  995. if refs == 0:
  996. lobj = self.remotelyCachedObjects[objectID]
  997. cacheable = lobj.object
  998. perspective = lobj.perspective
  999. # TODO: force_decache needs to be able to force-invalidate a
  1000. # cacheable reference.
  1001. try:
  1002. cacheable.stoppedObserving(
  1003. perspective, RemoteCacheObserver(self, cacheable, perspective)
  1004. )
  1005. except BaseException:
  1006. log.deferr()
  1007. puid = cacheable.processUniqueID()
  1008. del self.remotelyCachedLUIDs[puid]
  1009. del self.remotelyCachedObjects[objectID]
  1010. self.sendCall(b"uncache", objectID)
  1011. def proto_uncache(self, objectID):
  1012. """
  1013. (internal) Tell the client it is now OK to uncache an object.
  1014. @param objectID: The object ID.
  1015. """
  1016. # log.msg("uncaching locally %d" % objectID)
  1017. obj = self.locallyCachedObjects[objectID]
  1018. obj.broker = None
  1019. ## def reallyDel(obj=obj):
  1020. ## obj.__really_del__()
  1021. ## obj.__del__ = reallyDel
  1022. del self.locallyCachedObjects[objectID]
  1023. def respond(challenge, password):
  1024. """
  1025. Respond to a challenge.
  1026. This is useful for challenge/response authentication.
  1027. @param challenge: A challenge.
  1028. @param password: A password.
  1029. @return: The password hashed twice.
  1030. """
  1031. m = md5()
  1032. m.update(password)
  1033. hashedPassword = m.digest()
  1034. m = md5()
  1035. m.update(hashedPassword)
  1036. m.update(challenge)
  1037. doubleHashedPassword = m.digest()
  1038. return doubleHashedPassword
  1039. def challenge():
  1040. """
  1041. @return: Some random data.
  1042. """
  1043. crap = bytes(random.randint(65, 90) for x in range(random.randrange(15, 25)))
  1044. crap = md5(crap).digest()
  1045. return crap
  1046. class PBClientFactory(protocol.ClientFactory):
  1047. """
  1048. Client factory for PB brokers.
  1049. As with all client factories, use with reactor.connectTCP/SSL/etc..
  1050. getPerspective and getRootObject can be called either before or
  1051. after the connect.
  1052. """
  1053. protocol = Broker
  1054. unsafeTracebacks = False
  1055. def __init__(self, unsafeTracebacks=False, security=globalSecurity):
  1056. """
  1057. @param unsafeTracebacks: if set, tracebacks for exceptions will be sent
  1058. over the wire.
  1059. @type unsafeTracebacks: C{bool}
  1060. @param security: security options used by the broker, default to
  1061. C{globalSecurity}.
  1062. @type security: L{twisted.spread.jelly.SecurityOptions}
  1063. """
  1064. self.unsafeTracebacks = unsafeTracebacks
  1065. self.security = security
  1066. self._reset()
  1067. def buildProtocol(self, addr):
  1068. """
  1069. Build the broker instance, passing the security options to it.
  1070. """
  1071. p = self.protocol(isClient=True, security=self.security)
  1072. p.factory = self
  1073. return p
  1074. def _reset(self):
  1075. self.rootObjectRequests = [] # list of deferred
  1076. self._broker = None
  1077. self._root = None
  1078. def _failAll(self, reason):
  1079. deferreds = self.rootObjectRequests
  1080. self._reset()
  1081. for d in deferreds:
  1082. d.errback(reason)
  1083. def clientConnectionFailed(self, connector, reason):
  1084. self._failAll(reason)
  1085. def clientConnectionLost(self, connector, reason, reconnecting=0):
  1086. """
  1087. Reconnecting subclasses should call with reconnecting=1.
  1088. """
  1089. if reconnecting:
  1090. # Any pending requests will go to next connection attempt
  1091. # so we don't fail them.
  1092. self._broker = None
  1093. self._root = None
  1094. else:
  1095. self._failAll(reason)
  1096. def clientConnectionMade(self, broker):
  1097. self._broker = broker
  1098. self._root = broker.remoteForName("root")
  1099. ds = self.rootObjectRequests
  1100. self.rootObjectRequests = []
  1101. for d in ds:
  1102. d.callback(self._root)
  1103. def getRootObject(self):
  1104. """
  1105. Get root object of remote PB server.
  1106. @return: Deferred of the root object.
  1107. """
  1108. if self._broker and not self._broker.disconnected:
  1109. return defer.succeed(self._root)
  1110. d = defer.Deferred()
  1111. self.rootObjectRequests.append(d)
  1112. return d
  1113. def disconnect(self):
  1114. """
  1115. If the factory is connected, close the connection.
  1116. Note that if you set up the factory to reconnect, you will need to
  1117. implement extra logic to prevent automatic reconnection after this
  1118. is called.
  1119. """
  1120. if self._broker:
  1121. self._broker.transport.loseConnection()
  1122. def _cbSendUsername(self, root, username, password, client):
  1123. return root.callRemote("login", username).addCallback(
  1124. self._cbResponse, password, client
  1125. )
  1126. def _cbResponse(self, challenges, password, client):
  1127. challenge, challenger = challenges
  1128. return challenger.callRemote("respond", respond(challenge, password), client)
  1129. def _cbLoginAnonymous(self, root, client):
  1130. """
  1131. Attempt an anonymous login on the given remote root object.
  1132. @type root: L{RemoteReference}
  1133. @param root: The object on which to attempt the login, most likely
  1134. returned by a call to L{PBClientFactory.getRootObject}.
  1135. @param client: A jellyable object which will be used as the I{mind}
  1136. parameter for the login attempt.
  1137. @rtype: L{Deferred}
  1138. @return: A L{Deferred} which will be called back with a
  1139. L{RemoteReference} to an avatar when anonymous login succeeds, or
  1140. which will errback if anonymous login fails.
  1141. """
  1142. return root.callRemote("loginAnonymous", client)
  1143. def login(self, credentials, client=None):
  1144. """
  1145. Login and get perspective from remote PB server.
  1146. Currently the following credentials are supported::
  1147. L{twisted.cred.credentials.IUsernamePassword}
  1148. L{twisted.cred.credentials.IAnonymous}
  1149. @rtype: L{Deferred}
  1150. @return: A L{Deferred} which will be called back with a
  1151. L{RemoteReference} for the avatar logged in to, or which will
  1152. errback if login fails.
  1153. """
  1154. d = self.getRootObject()
  1155. if IAnonymous.providedBy(credentials):
  1156. d.addCallback(self._cbLoginAnonymous, client)
  1157. else:
  1158. d.addCallback(
  1159. self._cbSendUsername, credentials.username, credentials.password, client
  1160. )
  1161. return d
  1162. class PBServerFactory(protocol.ServerFactory):
  1163. """
  1164. Server factory for perspective broker.
  1165. Login is done using a Portal object, whose realm is expected to return
  1166. avatars implementing IPerspective. The credential checkers in the portal
  1167. should accept IUsernameHashedPassword or IUsernameMD5Password.
  1168. Alternatively, any object providing or adaptable to L{IPBRoot} can be
  1169. used instead of a portal to provide the root object of the PB server.
  1170. """
  1171. unsafeTracebacks = False
  1172. # object broker factory
  1173. protocol = Broker
  1174. def __init__(self, root, unsafeTracebacks=False, security=globalSecurity):
  1175. """
  1176. @param root: factory providing the root Referenceable used by the broker.
  1177. @type root: object providing or adaptable to L{IPBRoot}.
  1178. @param unsafeTracebacks: if set, tracebacks for exceptions will be sent
  1179. over the wire.
  1180. @type unsafeTracebacks: C{bool}
  1181. @param security: security options used by the broker, default to
  1182. C{globalSecurity}.
  1183. @type security: L{twisted.spread.jelly.SecurityOptions}
  1184. """
  1185. self.root = IPBRoot(root)
  1186. self.unsafeTracebacks = unsafeTracebacks
  1187. self.security = security
  1188. def buildProtocol(self, addr):
  1189. """
  1190. Return a Broker attached to the factory (as the service provider).
  1191. """
  1192. proto = self.protocol(isClient=False, security=self.security)
  1193. proto.factory = self
  1194. proto.setNameForLocal("root", self.root.rootObject(proto))
  1195. return proto
  1196. def clientConnectionMade(self, protocol):
  1197. # XXX does this method make any sense?
  1198. pass
  1199. class IUsernameMD5Password(ICredentials):
  1200. """
  1201. I encapsulate a username and a hashed password.
  1202. This credential is used for username/password over PB. CredentialCheckers
  1203. which check this kind of credential must store the passwords in plaintext
  1204. form or as a MD5 digest.
  1205. @type username: C{str} or C{Deferred}
  1206. @ivar username: The username associated with these credentials.
  1207. """
  1208. def checkPassword(password):
  1209. """
  1210. Validate these credentials against the correct password.
  1211. @type password: C{str}
  1212. @param password: The correct, plaintext password against which to
  1213. check.
  1214. @rtype: C{bool} or L{Deferred}
  1215. @return: C{True} if the credentials represented by this object match the
  1216. given password, C{False} if they do not, or a L{Deferred} which will
  1217. be called back with one of these values.
  1218. """
  1219. def checkMD5Password(password):
  1220. """
  1221. Validate these credentials against the correct MD5 digest of the
  1222. password.
  1223. @type password: C{str}
  1224. @param password: The correct MD5 digest of a password against which to
  1225. check.
  1226. @rtype: C{bool} or L{Deferred}
  1227. @return: C{True} if the credentials represented by this object match the
  1228. given digest, C{False} if they do not, or a L{Deferred} which will
  1229. be called back with one of these values.
  1230. """
  1231. @implementer(IPBRoot)
  1232. class _PortalRoot:
  1233. """
  1234. Root object, used to login to portal.
  1235. """
  1236. def __init__(self, portal):
  1237. self.portal = portal
  1238. def rootObject(self, broker):
  1239. return _PortalWrapper(self.portal, broker)
  1240. registerAdapter(_PortalRoot, Portal, IPBRoot)
  1241. class _JellyableAvatarMixin:
  1242. """
  1243. Helper class for code which deals with avatars which PB must be capable of
  1244. sending to a peer.
  1245. """
  1246. def _cbLogin(self, result):
  1247. """
  1248. Ensure that the avatar to be returned to the client is jellyable and
  1249. set up disconnection notification to call the realm's logout object.
  1250. """
  1251. (interface, avatar, logout) = result
  1252. if not IJellyable.providedBy(avatar):
  1253. avatar = AsReferenceable(avatar, "perspective")
  1254. puid = avatar.processUniqueID()
  1255. # only call logout once, whether the connection is dropped (disconnect)
  1256. # or a logout occurs (cleanup), and be careful to drop the reference to
  1257. # it in either case
  1258. logout = [logout]
  1259. def maybeLogout():
  1260. if not logout:
  1261. return
  1262. fn = logout[0]
  1263. del logout[0]
  1264. fn()
  1265. self.broker._localCleanup[puid] = maybeLogout
  1266. self.broker.notifyOnDisconnect(maybeLogout)
  1267. return avatar
  1268. class _PortalWrapper(Referenceable, _JellyableAvatarMixin):
  1269. """
  1270. Root Referenceable object, used to login to portal.
  1271. """
  1272. def __init__(self, portal, broker):
  1273. self.portal = portal
  1274. self.broker = broker
  1275. def remote_login(self, username):
  1276. """
  1277. Start of username/password login.
  1278. @param username: The username.
  1279. """
  1280. c = challenge()
  1281. return c, _PortalAuthChallenger(self.portal, self.broker, username, c)
  1282. def remote_loginAnonymous(self, mind):
  1283. """
  1284. Attempt an anonymous login.
  1285. @param mind: An object to use as the mind parameter to the portal login
  1286. call (possibly None).
  1287. @rtype: L{Deferred}
  1288. @return: A Deferred which will be called back with an avatar when login
  1289. succeeds or which will be errbacked if login fails somehow.
  1290. """
  1291. d = self.portal.login(Anonymous(), mind, IPerspective)
  1292. d.addCallback(self._cbLogin)
  1293. return d
  1294. @implementer(IUsernameHashedPassword, IUsernameMD5Password)
  1295. class _PortalAuthChallenger(Referenceable, _JellyableAvatarMixin):
  1296. """
  1297. Called with response to password challenge.
  1298. """
  1299. def __init__(self, portal, broker, username, challenge):
  1300. self.portal = portal
  1301. self.broker = broker
  1302. self.username = username
  1303. self.challenge = challenge
  1304. def remote_respond(self, response, mind):
  1305. self.response = response
  1306. d = self.portal.login(self, mind, IPerspective)
  1307. d.addCallback(self._cbLogin)
  1308. return d
  1309. def checkPassword(self, password):
  1310. """
  1311. L{IUsernameHashedPassword}
  1312. @param password: The password.
  1313. @return: L{_PortalAuthChallenger.checkMD5Password}
  1314. """
  1315. return self.checkMD5Password(md5(password).digest())
  1316. def checkMD5Password(self, md5Password):
  1317. """
  1318. L{IUsernameMD5Password}
  1319. @param md5Password:
  1320. @rtype: L{bool}
  1321. @return: L{True} if password matches.
  1322. """
  1323. md = md5()
  1324. md.update(md5Password)
  1325. md.update(self.challenge)
  1326. correct = md.digest()
  1327. return self.response == correct
  1328. __all__ = [
  1329. # Everything from flavors is exposed publicly here.
  1330. "IPBRoot",
  1331. "Serializable",
  1332. "Referenceable",
  1333. "NoSuchMethod",
  1334. "Root",
  1335. "ViewPoint",
  1336. "Viewable",
  1337. "Copyable",
  1338. "Jellyable",
  1339. "Cacheable",
  1340. "RemoteCopy",
  1341. "RemoteCache",
  1342. "RemoteCacheObserver",
  1343. "copyTags",
  1344. "setUnjellyableForClass",
  1345. "setUnjellyableFactoryForClass",
  1346. "setUnjellyableForClassTree",
  1347. "setCopierForClass",
  1348. "setFactoryForClass",
  1349. "setCopierForClassTree",
  1350. "MAX_BROKER_REFS",
  1351. "portno",
  1352. "ProtocolError",
  1353. "DeadReferenceError",
  1354. "Error",
  1355. "PBConnectionLost",
  1356. "RemoteMethod",
  1357. "IPerspective",
  1358. "Avatar",
  1359. "AsReferenceable",
  1360. "RemoteReference",
  1361. "CopyableFailure",
  1362. "CopiedFailure",
  1363. "failure2Copyable",
  1364. "Broker",
  1365. "respond",
  1366. "challenge",
  1367. "PBClientFactory",
  1368. "PBServerFactory",
  1369. "IUsernameMD5Password",
  1370. ]