amp.py 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897
  1. # -*- test-case-name: twisted.test.test_amp -*-
  2. # Copyright (c) 2005 Divmod, Inc.
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. """
  6. This module implements AMP, the Asynchronous Messaging Protocol.
  7. AMP is a protocol for sending multiple asynchronous request/response pairs over
  8. the same connection. Requests and responses are both collections of key/value
  9. pairs.
  10. AMP is a very simple protocol which is not an application. This module is a
  11. "protocol construction kit" of sorts; it attempts to be the simplest wire-level
  12. implementation of Deferreds. AMP provides the following base-level features:
  13. - Asynchronous request/response handling (hence the name)
  14. - Requests and responses are both key/value pairs
  15. - Binary transfer of all data: all data is length-prefixed. Your
  16. application will never need to worry about quoting.
  17. - Command dispatching (like HTTP Verbs): the protocol is extensible, and
  18. multiple AMP sub-protocols can be grouped together easily.
  19. The protocol implementation also provides a few additional features which are
  20. not part of the core wire protocol, but are nevertheless very useful:
  21. - Tight TLS integration, with an included StartTLS command.
  22. - Handshaking to other protocols: because AMP has well-defined message
  23. boundaries and maintains all incoming and outgoing requests for you, you
  24. can start a connection over AMP and then switch to another protocol.
  25. This makes it ideal for firewall-traversal applications where you may
  26. have only one forwarded port but multiple applications that want to use
  27. it.
  28. Using AMP with Twisted is simple. Each message is a command, with a response.
  29. You begin by defining a command type. Commands specify their input and output
  30. in terms of the types that they expect to see in the request and response
  31. key-value pairs. Here's an example of a command that adds two integers, 'a'
  32. and 'b'::
  33. class Sum(amp.Command):
  34. arguments = [('a', amp.Integer()),
  35. ('b', amp.Integer())]
  36. response = [('total', amp.Integer())]
  37. Once you have specified a command, you need to make it part of a protocol, and
  38. define a responder for it. Here's a 'JustSum' protocol that includes a
  39. responder for our 'Sum' command::
  40. class JustSum(amp.AMP):
  41. def sum(self, a, b):
  42. total = a + b
  43. print 'Did a sum: %d + %d = %d' % (a, b, total)
  44. return {'total': total}
  45. Sum.responder(sum)
  46. Later, when you want to actually do a sum, the following expression will return
  47. a L{Deferred} which will fire with the result::
  48. ClientCreator(reactor, amp.AMP).connectTCP(...).addCallback(
  49. lambda p: p.callRemote(Sum, a=13, b=81)).addCallback(
  50. lambda result: result['total'])
  51. Command responders may also return Deferreds, causing the response to be
  52. sent only once the Deferred fires::
  53. class DelayedSum(amp.AMP):
  54. def slowSum(self, a, b):
  55. total = a + b
  56. result = defer.Deferred()
  57. reactor.callLater(3, result.callback, {'total': total})
  58. return result
  59. Sum.responder(slowSum)
  60. This is transparent to the caller.
  61. You can also define the propagation of specific errors in AMP. For example,
  62. for the slightly more complicated case of division, we might have to deal with
  63. division by zero::
  64. class Divide(amp.Command):
  65. arguments = [('numerator', amp.Integer()),
  66. ('denominator', amp.Integer())]
  67. response = [('result', amp.Float())]
  68. errors = {ZeroDivisionError: 'ZERO_DIVISION'}
  69. The 'errors' mapping here tells AMP that if a responder to Divide emits a
  70. L{ZeroDivisionError}, then the other side should be informed that an error of
  71. the type 'ZERO_DIVISION' has occurred. Writing a responder which takes
  72. advantage of this is very simple - just raise your exception normally::
  73. class JustDivide(amp.AMP):
  74. def divide(self, numerator, denominator):
  75. result = numerator / denominator
  76. print 'Divided: %d / %d = %d' % (numerator, denominator, total)
  77. return {'result': result}
  78. Divide.responder(divide)
  79. On the client side, the errors mapping will be used to determine what the
  80. 'ZERO_DIVISION' error means, and translated into an asynchronous exception,
  81. which can be handled normally as any L{Deferred} would be::
  82. def trapZero(result):
  83. result.trap(ZeroDivisionError)
  84. print "Divided by zero: returning INF"
  85. return 1e1000
  86. ClientCreator(reactor, amp.AMP).connectTCP(...).addCallback(
  87. lambda p: p.callRemote(Divide, numerator=1234,
  88. denominator=0)
  89. ).addErrback(trapZero)
  90. For a complete, runnable example of both of these commands, see the files in
  91. the Twisted repository::
  92. doc/core/examples/ampserver.py
  93. doc/core/examples/ampclient.py
  94. On the wire, AMP is a protocol which uses 2-byte lengths to prefix keys and
  95. values, and empty keys to separate messages::
  96. <2-byte length><key><2-byte length><value>
  97. <2-byte length><key><2-byte length><value>
  98. ...
  99. <2-byte length><key><2-byte length><value>
  100. <NUL><NUL> # Empty Key == End of Message
  101. And so on. Because it's tedious to refer to lengths and NULs constantly, the
  102. documentation will refer to packets as if they were newline delimited, like
  103. so::
  104. C: _command: sum
  105. C: _ask: ef639e5c892ccb54
  106. C: a: 13
  107. C: b: 81
  108. S: _answer: ef639e5c892ccb54
  109. S: total: 94
  110. Notes:
  111. In general, the order of keys is arbitrary. Specific uses of AMP may impose an
  112. ordering requirement, but unless this is specified explicitly, any ordering may
  113. be generated and any ordering must be accepted. This applies to the
  114. command-related keys I{_command} and I{_ask} as well as any other keys.
  115. Values are limited to the maximum encodable size in a 16-bit length, 65535
  116. bytes.
  117. Keys are limited to the maximum encodable size in a 8-bit length, 255 bytes.
  118. Note that we still use 2-byte lengths to encode keys. This small redundancy
  119. has several features:
  120. - If an implementation becomes confused and starts emitting corrupt data,
  121. or gets keys confused with values, many common errors will be signalled
  122. immediately instead of delivering obviously corrupt packets.
  123. - A single NUL will separate every key, and a double NUL separates
  124. messages. This provides some redundancy when debugging traffic dumps.
  125. - NULs will be present at regular intervals along the protocol, providing
  126. some padding for otherwise braindead C implementations of the protocol,
  127. so that <stdio.h> string functions will see the NUL and stop.
  128. - This makes it possible to run an AMP server on a port also used by a
  129. plain-text protocol, and easily distinguish between non-AMP clients (like
  130. web browsers) which issue non-NUL as the first byte, and AMP clients,
  131. which always issue NUL as the first byte.
  132. @var MAX_VALUE_LENGTH: The maximum length of a message.
  133. @type MAX_VALUE_LENGTH: L{int}
  134. @var ASK: Marker for an Ask packet.
  135. @type ASK: L{bytes}
  136. @var ANSWER: Marker for an Answer packet.
  137. @type ANSWER: L{bytes}
  138. @var COMMAND: Marker for a Command packet.
  139. @type COMMAND: L{bytes}
  140. @var ERROR: Marker for an AMP box of error type.
  141. @type ERROR: L{bytes}
  142. @var ERROR_CODE: Marker for an AMP box containing the code of an error.
  143. @type ERROR_CODE: L{bytes}
  144. @var ERROR_DESCRIPTION: Marker for an AMP box containing the description of the
  145. error.
  146. @type ERROR_DESCRIPTION: L{bytes}
  147. """
  148. from __future__ import absolute_import, division
  149. __metaclass__ = type
  150. import types, warnings
  151. from io import BytesIO
  152. from struct import pack
  153. import decimal, datetime
  154. from functools import partial
  155. from itertools import count
  156. from zope.interface import Interface, implementer
  157. from twisted.python.reflect import accumulateClassDict
  158. from twisted.python.failure import Failure
  159. from twisted.python._tzhelper import (
  160. FixedOffsetTimeZone as _FixedOffsetTZInfo, UTC as utc
  161. )
  162. from twisted.python import log, filepath
  163. from twisted.internet.interfaces import IFileDescriptorReceiver
  164. from twisted.internet.main import CONNECTION_LOST
  165. from twisted.internet.error import PeerVerifyError, ConnectionLost
  166. from twisted.internet.error import ConnectionClosed
  167. from twisted.internet.defer import Deferred, maybeDeferred, fail
  168. from twisted.protocols.basic import Int16StringReceiver, StatefulStringProtocol
  169. from twisted.python.compat import (
  170. iteritems, unicode, nativeString, intToBytes, _PY3, long,
  171. )
  172. try:
  173. from twisted.internet import ssl
  174. except ImportError:
  175. ssl = None
  176. if ssl and not ssl.supported:
  177. ssl = None
  178. if ssl is not None:
  179. from twisted.internet.ssl import (CertificateOptions, Certificate, DN,
  180. KeyPair)
  181. __all__ = [
  182. 'AMP',
  183. 'ANSWER',
  184. 'ASK',
  185. 'AmpBox',
  186. 'AmpError',
  187. 'AmpList',
  188. 'Argument',
  189. 'BadLocalReturn',
  190. 'BinaryBoxProtocol',
  191. 'Boolean',
  192. 'Box',
  193. 'BoxDispatcher',
  194. 'COMMAND',
  195. 'Command',
  196. 'CommandLocator',
  197. 'Decimal',
  198. 'Descriptor',
  199. 'ERROR',
  200. 'ERROR_CODE',
  201. 'ERROR_DESCRIPTION',
  202. 'Float',
  203. 'IArgumentType',
  204. 'IBoxReceiver',
  205. 'IBoxSender',
  206. 'IResponderLocator',
  207. 'IncompatibleVersions',
  208. 'Integer',
  209. 'InvalidSignature',
  210. 'ListOf',
  211. 'MAX_KEY_LENGTH',
  212. 'MAX_VALUE_LENGTH',
  213. 'MalformedAmpBox',
  214. 'NoEmptyBoxes',
  215. 'OnlyOneTLS',
  216. 'PROTOCOL_ERRORS',
  217. 'PYTHON_KEYWORDS',
  218. 'Path',
  219. 'ProtocolSwitchCommand',
  220. 'ProtocolSwitched',
  221. 'QuitBox',
  222. 'RemoteAmpError',
  223. 'SimpleStringLocator',
  224. 'StartTLS',
  225. 'String',
  226. 'TooLong',
  227. 'UNHANDLED_ERROR_CODE',
  228. 'UNKNOWN_ERROR_CODE',
  229. 'UnhandledCommand',
  230. 'utc',
  231. 'Unicode',
  232. 'UnknownRemoteError',
  233. 'parse',
  234. 'parseString',
  235. ]
  236. ASK = b'_ask'
  237. ANSWER = b'_answer'
  238. COMMAND = b'_command'
  239. ERROR = b'_error'
  240. ERROR_CODE = b'_error_code'
  241. ERROR_DESCRIPTION = b'_error_description'
  242. UNKNOWN_ERROR_CODE = b'UNKNOWN'
  243. UNHANDLED_ERROR_CODE = b'UNHANDLED'
  244. MAX_KEY_LENGTH = 0xff
  245. MAX_VALUE_LENGTH = 0xffff
  246. class IArgumentType(Interface):
  247. """
  248. An L{IArgumentType} can serialize a Python object into an AMP box and
  249. deserialize information from an AMP box back into a Python object.
  250. @since: 9.0
  251. """
  252. def fromBox(name, strings, objects, proto):
  253. """
  254. Given an argument name and an AMP box containing serialized values,
  255. extract one or more Python objects and add them to the C{objects}
  256. dictionary.
  257. @param name: The name associated with this argument. Most commonly
  258. this is the key which can be used to find a serialized value in
  259. C{strings}.
  260. @type name: C{bytes}
  261. @param strings: The AMP box from which to extract one or more
  262. values.
  263. @type strings: C{dict}
  264. @param objects: The output dictionary to populate with the value for
  265. this argument. The key used will be derived from C{name}. It may
  266. differ; in Python 3, for example, the key will be a Unicode/native
  267. string. See L{_wireNameToPythonIdentifier}.
  268. @type objects: C{dict}
  269. @param proto: The protocol instance which received the AMP box being
  270. interpreted. Most likely this is an instance of L{AMP}, but
  271. this is not guaranteed.
  272. @return: L{None}
  273. """
  274. def toBox(name, strings, objects, proto):
  275. """
  276. Given an argument name and a dictionary containing structured Python
  277. objects, serialize values into one or more strings and add them to
  278. the C{strings} dictionary.
  279. @param name: The name associated with this argument. Most commonly
  280. this is the key in C{strings} to associate with a C{bytes} giving
  281. the serialized form of that object.
  282. @type name: C{bytes}
  283. @param strings: The AMP box into which to insert one or more strings.
  284. @type strings: C{dict}
  285. @param objects: The input dictionary from which to extract Python
  286. objects to serialize. The key used will be derived from C{name}.
  287. It may differ; in Python 3, for example, the key will be a
  288. Unicode/native string. See L{_wireNameToPythonIdentifier}.
  289. @type objects: C{dict}
  290. @param proto: The protocol instance which will send the AMP box once
  291. it is fully populated. Most likely this is an instance of
  292. L{AMP}, but this is not guaranteed.
  293. @return: L{None}
  294. """
  295. class IBoxSender(Interface):
  296. """
  297. A transport which can send L{AmpBox} objects.
  298. """
  299. def sendBox(box):
  300. """
  301. Send an L{AmpBox}.
  302. @raise ProtocolSwitched: if the underlying protocol has been
  303. switched.
  304. @raise ConnectionLost: if the underlying connection has already been
  305. lost.
  306. """
  307. def unhandledError(failure):
  308. """
  309. An unhandled error occurred in response to a box. Log it
  310. appropriately.
  311. @param failure: a L{Failure} describing the error that occurred.
  312. """
  313. class IBoxReceiver(Interface):
  314. """
  315. An application object which can receive L{AmpBox} objects and dispatch them
  316. appropriately.
  317. """
  318. def startReceivingBoxes(boxSender):
  319. """
  320. The L{IBoxReceiver.ampBoxReceived} method will start being called;
  321. boxes may be responded to by responding to the given L{IBoxSender}.
  322. @param boxSender: an L{IBoxSender} provider.
  323. """
  324. def ampBoxReceived(box):
  325. """
  326. A box was received from the transport; dispatch it appropriately.
  327. """
  328. def stopReceivingBoxes(reason):
  329. """
  330. No further boxes will be received on this connection.
  331. @type reason: L{Failure}
  332. """
  333. class IResponderLocator(Interface):
  334. """
  335. An application object which can look up appropriate responder methods for
  336. AMP commands.
  337. """
  338. def locateResponder(name):
  339. """
  340. Locate a responder method appropriate for the named command.
  341. @param name: the wire-level name (commandName) of the AMP command to be
  342. responded to.
  343. @type name: C{bytes}
  344. @return: a 1-argument callable that takes an L{AmpBox} with argument
  345. values for the given command, and returns an L{AmpBox} containing
  346. argument values for the named command, or a L{Deferred} that fires the
  347. same.
  348. """
  349. class AmpError(Exception):
  350. """
  351. Base class of all Amp-related exceptions.
  352. """
  353. class ProtocolSwitched(Exception):
  354. """
  355. Connections which have been switched to other protocols can no longer
  356. accept traffic at the AMP level. This is raised when you try to send it.
  357. """
  358. class OnlyOneTLS(AmpError):
  359. """
  360. This is an implementation limitation; TLS may only be started once per
  361. connection.
  362. """
  363. class NoEmptyBoxes(AmpError):
  364. """
  365. You can't have empty boxes on the connection. This is raised when you
  366. receive or attempt to send one.
  367. """
  368. class InvalidSignature(AmpError):
  369. """
  370. You didn't pass all the required arguments.
  371. """
  372. class TooLong(AmpError):
  373. """
  374. One of the protocol's length limitations was violated.
  375. @ivar isKey: true if the string being encoded in a key position, false if
  376. it was in a value position.
  377. @ivar isLocal: Was the string encoded locally, or received too long from
  378. the network? (It's only physically possible to encode "too long" values on
  379. the network for keys.)
  380. @ivar value: The string that was too long.
  381. @ivar keyName: If the string being encoded was in a value position, what
  382. key was it being encoded for?
  383. """
  384. def __init__(self, isKey, isLocal, value, keyName=None):
  385. AmpError.__init__(self)
  386. self.isKey = isKey
  387. self.isLocal = isLocal
  388. self.value = value
  389. self.keyName = keyName
  390. def __repr__(self):
  391. hdr = self.isKey and "key" or "value"
  392. if not self.isKey:
  393. hdr += ' ' + repr(self.keyName)
  394. lcl = self.isLocal and "local" or "remote"
  395. return "%s %s too long: %d" % (lcl, hdr, len(self.value))
  396. class BadLocalReturn(AmpError):
  397. """
  398. A bad value was returned from a local command; we were unable to coerce it.
  399. """
  400. def __init__(self, message, enclosed):
  401. AmpError.__init__(self)
  402. self.message = message
  403. self.enclosed = enclosed
  404. def __repr__(self):
  405. return self.message + " " + self.enclosed.getBriefTraceback()
  406. __str__ = __repr__
  407. class RemoteAmpError(AmpError):
  408. """
  409. This error indicates that something went wrong on the remote end of the
  410. connection, and the error was serialized and transmitted to you.
  411. """
  412. def __init__(self, errorCode, description, fatal=False, local=None):
  413. """Create a remote error with an error code and description.
  414. @param errorCode: the AMP error code of this error.
  415. @type errorCode: C{bytes}
  416. @param description: some text to show to the user.
  417. @type description: C{str}
  418. @param fatal: a boolean, true if this error should terminate the
  419. connection.
  420. @param local: a local Failure, if one exists.
  421. """
  422. if local:
  423. localwhat = ' (local)'
  424. othertb = local.getBriefTraceback()
  425. else:
  426. localwhat = ''
  427. othertb = ''
  428. # Backslash-escape errorCode. Python 3.5 can do this natively
  429. # ("backslashescape") but Python 2.7 and Python 3.4 can't.
  430. if _PY3:
  431. errorCodeForMessage = "".join(
  432. "\\x%2x" % (c,) if c >= 0x80 else chr(c)
  433. for c in errorCode)
  434. else:
  435. errorCodeForMessage = "".join(
  436. "\\x%2x" % (ord(c),) if ord(c) >= 0x80 else c
  437. for c in errorCode)
  438. if othertb:
  439. message = "Code<%s>%s: %s\n%s" % (
  440. errorCodeForMessage, localwhat, description, othertb)
  441. else:
  442. message = "Code<%s>%s: %s" % (
  443. errorCodeForMessage, localwhat, description)
  444. super(RemoteAmpError, self).__init__(message)
  445. self.local = local
  446. self.errorCode = errorCode
  447. self.description = description
  448. self.fatal = fatal
  449. class UnknownRemoteError(RemoteAmpError):
  450. """
  451. This means that an error whose type we can't identify was raised from the
  452. other side.
  453. """
  454. def __init__(self, description):
  455. errorCode = UNKNOWN_ERROR_CODE
  456. RemoteAmpError.__init__(self, errorCode, description)
  457. class MalformedAmpBox(AmpError):
  458. """
  459. This error indicates that the wire-level protocol was malformed.
  460. """
  461. class UnhandledCommand(AmpError):
  462. """
  463. A command received via amp could not be dispatched.
  464. """
  465. class IncompatibleVersions(AmpError):
  466. """
  467. It was impossible to negotiate a compatible version of the protocol with
  468. the other end of the connection.
  469. """
  470. PROTOCOL_ERRORS = {UNHANDLED_ERROR_CODE: UnhandledCommand}
  471. class AmpBox(dict):
  472. """
  473. I am a packet in the AMP protocol, much like a regular bytes:bytes dictionary.
  474. """
  475. __slots__ = [] # be like a regular dictionary, don't magically
  476. # acquire a __dict__...
  477. def __init__(self, *args, **kw):
  478. """
  479. Initialize a new L{AmpBox}.
  480. In Python 3, keyword arguments MUST be Unicode/native strings whereas
  481. in Python 2 they could be either byte strings or Unicode strings.
  482. However, all keys of an L{AmpBox} MUST be byte strings, or possible to
  483. transparently coerce into byte strings (i.e. Python 2).
  484. In Python 3, therefore, native string keys are coerced to byte strings
  485. by encoding as ASCII. This can result in C{UnicodeEncodeError} being
  486. raised.
  487. @param args: See C{dict}, but all keys and values should be C{bytes}.
  488. On Python 3, native strings may be used as keys provided they
  489. contain only ASCII characters.
  490. @param kw: See C{dict}, but all keys and values should be C{bytes}.
  491. On Python 3, native strings may be used as keys provided they
  492. contain only ASCII characters.
  493. @raise UnicodeEncodeError: When a native string key cannot be coerced
  494. to an ASCII byte string (Python 3 only).
  495. """
  496. super(AmpBox, self).__init__(*args, **kw)
  497. if _PY3:
  498. nonByteNames = [n for n in self if not isinstance(n, bytes)]
  499. for nonByteName in nonByteNames:
  500. byteName = nonByteName.encode("ascii")
  501. self[byteName] = self.pop(nonByteName)
  502. def copy(self):
  503. """
  504. Return another AmpBox just like me.
  505. """
  506. newBox = self.__class__()
  507. newBox.update(self)
  508. return newBox
  509. def serialize(self):
  510. """
  511. Convert me into a wire-encoded string.
  512. @return: a C{bytes} encoded according to the rules described in the
  513. module docstring.
  514. """
  515. i = sorted(iteritems(self))
  516. L = []
  517. w = L.append
  518. for k, v in i:
  519. if type(k) == unicode:
  520. raise TypeError("Unicode key not allowed: %r" % k)
  521. if type(v) == unicode:
  522. raise TypeError(
  523. "Unicode value for key %r not allowed: %r" % (k, v))
  524. if len(k) > MAX_KEY_LENGTH:
  525. raise TooLong(True, True, k, None)
  526. if len(v) > MAX_VALUE_LENGTH:
  527. raise TooLong(False, True, v, k)
  528. for kv in k, v:
  529. w(pack("!H", len(kv)))
  530. w(kv)
  531. w(pack("!H", 0))
  532. return b''.join(L)
  533. def _sendTo(self, proto):
  534. """
  535. Serialize and send this box to an Amp instance. By the time it is being
  536. sent, several keys are required. I must have exactly ONE of::
  537. _ask
  538. _answer
  539. _error
  540. If the '_ask' key is set, then the '_command' key must also be
  541. set.
  542. @param proto: an AMP instance.
  543. """
  544. proto.sendBox(self)
  545. def __repr__(self):
  546. return 'AmpBox(%s)' % (dict.__repr__(self),)
  547. # amp.Box => AmpBox
  548. Box = AmpBox
  549. class QuitBox(AmpBox):
  550. """
  551. I am an AmpBox that, upon being sent, terminates the connection.
  552. """
  553. __slots__ = []
  554. def __repr__(self):
  555. return 'QuitBox(**%s)' % (super(QuitBox, self).__repr__(),)
  556. def _sendTo(self, proto):
  557. """
  558. Immediately call loseConnection after sending.
  559. """
  560. super(QuitBox, self)._sendTo(proto)
  561. proto.transport.loseConnection()
  562. class _SwitchBox(AmpBox):
  563. """
  564. Implementation detail of ProtocolSwitchCommand: I am an AmpBox which sets
  565. up state for the protocol to switch.
  566. """
  567. # DON'T set __slots__ here; we do have an attribute.
  568. def __init__(self, innerProto, **kw):
  569. """
  570. Create a _SwitchBox with the protocol to switch to after being sent.
  571. @param innerProto: the protocol instance to switch to.
  572. @type innerProto: an IProtocol provider.
  573. """
  574. super(_SwitchBox, self).__init__(**kw)
  575. self.innerProto = innerProto
  576. def __repr__(self):
  577. return '_SwitchBox(%r, **%s)' % (self.innerProto,
  578. dict.__repr__(self),)
  579. def _sendTo(self, proto):
  580. """
  581. Send me; I am the last box on the connection. All further traffic will be
  582. over the new protocol.
  583. """
  584. super(_SwitchBox, self)._sendTo(proto)
  585. proto._lockForSwitch()
  586. proto._switchTo(self.innerProto)
  587. @implementer(IBoxReceiver)
  588. class BoxDispatcher:
  589. """
  590. A L{BoxDispatcher} dispatches '_ask', '_answer', and '_error' L{AmpBox}es,
  591. both incoming and outgoing, to their appropriate destinations.
  592. Outgoing commands are converted into L{Deferred}s and outgoing boxes, and
  593. associated tracking state to fire those L{Deferred} when '_answer' boxes
  594. come back. Incoming '_answer' and '_error' boxes are converted into
  595. callbacks and errbacks on those L{Deferred}s, respectively.
  596. Incoming '_ask' boxes are converted into method calls on a supplied method
  597. locator.
  598. @ivar _outstandingRequests: a dictionary mapping request IDs to
  599. L{Deferred}s which were returned for those requests.
  600. @ivar locator: an object with a L{CommandLocator.locateResponder} method
  601. that locates a responder function that takes a Box and returns a result
  602. (either a Box or a Deferred which fires one).
  603. @ivar boxSender: an object which can send boxes, via the L{_sendBoxCommand}
  604. method, such as an L{AMP} instance.
  605. @type boxSender: L{IBoxSender}
  606. """
  607. _failAllReason = None
  608. _outstandingRequests = None
  609. _counter = long(0)
  610. boxSender = None
  611. def __init__(self, locator):
  612. self._outstandingRequests = {}
  613. self.locator = locator
  614. def startReceivingBoxes(self, boxSender):
  615. """
  616. The given boxSender is going to start calling boxReceived on this
  617. L{BoxDispatcher}.
  618. @param boxSender: The L{IBoxSender} to send command responses to.
  619. """
  620. self.boxSender = boxSender
  621. def stopReceivingBoxes(self, reason):
  622. """
  623. No further boxes will be received here. Terminate all currently
  624. outstanding command deferreds with the given reason.
  625. """
  626. self.failAllOutgoing(reason)
  627. def failAllOutgoing(self, reason):
  628. """
  629. Call the errback on all outstanding requests awaiting responses.
  630. @param reason: the Failure instance to pass to those errbacks.
  631. """
  632. self._failAllReason = reason
  633. OR = self._outstandingRequests.items()
  634. self._outstandingRequests = None # we can never send another request
  635. for key, value in OR:
  636. value.errback(reason)
  637. def _nextTag(self):
  638. """
  639. Generate protocol-local serial numbers for _ask keys.
  640. @return: a string that has not yet been used on this connection.
  641. """
  642. self._counter += 1
  643. return (b'%x' % (self._counter,))
  644. def _sendBoxCommand(self, command, box, requiresAnswer=True):
  645. """
  646. Send a command across the wire with the given C{amp.Box}.
  647. Mutate the given box to give it any additional keys (_command, _ask)
  648. required for the command and request/response machinery, then send it.
  649. If requiresAnswer is True, returns a C{Deferred} which fires when a
  650. response is received. The C{Deferred} is fired with an C{amp.Box} on
  651. success, or with an C{amp.RemoteAmpError} if an error is received.
  652. If the Deferred fails and the error is not handled by the caller of
  653. this method, the failure will be logged and the connection dropped.
  654. @param command: a C{bytes}, the name of the command to issue.
  655. @param box: an AmpBox with the arguments for the command.
  656. @param requiresAnswer: a boolean. Defaults to True. If True, return a
  657. Deferred which will fire when the other side responds to this command.
  658. If False, return None and do not ask the other side for acknowledgement.
  659. @return: a Deferred which fires the AmpBox that holds the response to
  660. this command, or None, as specified by requiresAnswer.
  661. @raise ProtocolSwitched: if the protocol has been switched.
  662. """
  663. if self._failAllReason is not None:
  664. if requiresAnswer:
  665. return fail(self._failAllReason)
  666. else:
  667. return None
  668. box[COMMAND] = command
  669. tag = self._nextTag()
  670. if requiresAnswer:
  671. box[ASK] = tag
  672. box._sendTo(self.boxSender)
  673. if requiresAnswer:
  674. result = self._outstandingRequests[tag] = Deferred()
  675. else:
  676. result = None
  677. return result
  678. def callRemoteString(self, command, requiresAnswer=True, **kw):
  679. """
  680. This is a low-level API, designed only for optimizing simple messages
  681. for which the overhead of parsing is too great.
  682. @param command: a C{bytes} naming the command.
  683. @param kw: arguments to the amp box.
  684. @param requiresAnswer: a boolean. Defaults to True. If True, return a
  685. Deferred which will fire when the other side responds to this command.
  686. If False, return None and do not ask the other side for acknowledgement.
  687. @return: a Deferred which fires the AmpBox that holds the response to
  688. this command, or None, as specified by requiresAnswer.
  689. """
  690. box = Box(kw)
  691. return self._sendBoxCommand(command, box, requiresAnswer)
  692. def callRemote(self, commandType, *a, **kw):
  693. """
  694. This is the primary high-level API for sending messages via AMP. Invoke it
  695. with a command and appropriate arguments to send a message to this
  696. connection's peer.
  697. @param commandType: a subclass of Command.
  698. @type commandType: L{type}
  699. @param a: Positional (special) parameters taken by the command.
  700. Positional parameters will typically not be sent over the wire. The
  701. only command included with AMP which uses positional parameters is
  702. L{ProtocolSwitchCommand}, which takes the protocol that will be
  703. switched to as its first argument.
  704. @param kw: Keyword arguments taken by the command. These are the
  705. arguments declared in the command's 'arguments' attribute. They will
  706. be encoded and sent to the peer as arguments for the L{commandType}.
  707. @return: If L{commandType} has a C{requiresAnswer} attribute set to
  708. L{False}, then return L{None}. Otherwise, return a L{Deferred} which
  709. fires with a dictionary of objects representing the result of this
  710. call. Additionally, this L{Deferred} may fail with an exception
  711. representing a connection failure, with L{UnknownRemoteError} if the
  712. other end of the connection fails for an unknown reason, or with any
  713. error specified as a key in L{commandType}'s C{errors} dictionary.
  714. """
  715. # XXX this takes command subclasses and not command objects on purpose.
  716. # There's really no reason to have all this back-and-forth between
  717. # command objects and the protocol, and the extra object being created
  718. # (the Command instance) is pointless. Command is kind of like
  719. # Interface, and should be more like it.
  720. # In other words, the fact that commandType is instantiated here is an
  721. # implementation detail. Don't rely on it.
  722. try:
  723. co = commandType(*a, **kw)
  724. except:
  725. return fail()
  726. return co._doCommand(self)
  727. def unhandledError(self, failure):
  728. """
  729. This is a terminal callback called after application code has had a
  730. chance to quash any errors.
  731. """
  732. return self.boxSender.unhandledError(failure)
  733. def _answerReceived(self, box):
  734. """
  735. An AMP box was received that answered a command previously sent with
  736. L{callRemote}.
  737. @param box: an AmpBox with a value for its L{ANSWER} key.
  738. """
  739. question = self._outstandingRequests.pop(box[ANSWER])
  740. question.addErrback(self.unhandledError)
  741. question.callback(box)
  742. def _errorReceived(self, box):
  743. """
  744. An AMP box was received that answered a command previously sent with
  745. L{callRemote}, with an error.
  746. @param box: an L{AmpBox} with a value for its L{ERROR}, L{ERROR_CODE},
  747. and L{ERROR_DESCRIPTION} keys.
  748. """
  749. question = self._outstandingRequests.pop(box[ERROR])
  750. question.addErrback(self.unhandledError)
  751. errorCode = box[ERROR_CODE]
  752. description = box[ERROR_DESCRIPTION]
  753. if isinstance(description, bytes):
  754. description = description.decode("utf-8", "replace")
  755. if errorCode in PROTOCOL_ERRORS:
  756. exc = PROTOCOL_ERRORS[errorCode](errorCode, description)
  757. else:
  758. exc = RemoteAmpError(errorCode, description)
  759. question.errback(Failure(exc))
  760. def _commandReceived(self, box):
  761. """
  762. @param box: an L{AmpBox} with a value for its L{COMMAND} and L{ASK}
  763. keys.
  764. """
  765. def formatAnswer(answerBox):
  766. answerBox[ANSWER] = box[ASK]
  767. return answerBox
  768. def formatError(error):
  769. if error.check(RemoteAmpError):
  770. code = error.value.errorCode
  771. desc = error.value.description
  772. if isinstance(desc, unicode):
  773. desc = desc.encode("utf-8", "replace")
  774. if error.value.fatal:
  775. errorBox = QuitBox()
  776. else:
  777. errorBox = AmpBox()
  778. else:
  779. errorBox = QuitBox()
  780. log.err(error) # here is where server-side logging happens
  781. # if the error isn't handled
  782. code = UNKNOWN_ERROR_CODE
  783. desc = b"Unknown Error"
  784. errorBox[ERROR] = box[ASK]
  785. errorBox[ERROR_DESCRIPTION] = desc
  786. errorBox[ERROR_CODE] = code
  787. return errorBox
  788. deferred = self.dispatchCommand(box)
  789. if ASK in box:
  790. deferred.addCallbacks(formatAnswer, formatError)
  791. deferred.addCallback(self._safeEmit)
  792. deferred.addErrback(self.unhandledError)
  793. def ampBoxReceived(self, box):
  794. """
  795. An AmpBox was received, representing a command, or an answer to a
  796. previously issued command (either successful or erroneous). Respond to
  797. it according to its contents.
  798. @param box: an AmpBox
  799. @raise NoEmptyBoxes: when a box is received that does not contain an
  800. '_answer', '_command' / '_ask', or '_error' key; i.e. one which does not
  801. fit into the command / response protocol defined by AMP.
  802. """
  803. if ANSWER in box:
  804. self._answerReceived(box)
  805. elif ERROR in box:
  806. self._errorReceived(box)
  807. elif COMMAND in box:
  808. self._commandReceived(box)
  809. else:
  810. raise NoEmptyBoxes(box)
  811. def _safeEmit(self, aBox):
  812. """
  813. Emit a box, ignoring L{ProtocolSwitched} and L{ConnectionLost} errors
  814. which cannot be usefully handled.
  815. """
  816. try:
  817. aBox._sendTo(self.boxSender)
  818. except (ProtocolSwitched, ConnectionLost):
  819. pass
  820. def dispatchCommand(self, box):
  821. """
  822. A box with a _command key was received.
  823. Dispatch it to a local handler call it.
  824. @param proto: an AMP instance.
  825. @param box: an AmpBox to be dispatched.
  826. """
  827. cmd = box[COMMAND]
  828. responder = self.locator.locateResponder(cmd)
  829. if responder is None:
  830. description = "Unhandled Command: %r" % (cmd,)
  831. return fail(RemoteAmpError(
  832. UNHANDLED_ERROR_CODE,
  833. description,
  834. False,
  835. local=Failure(UnhandledCommand())))
  836. return maybeDeferred(responder, box)
  837. @implementer(IResponderLocator)
  838. class CommandLocator:
  839. """
  840. A L{CommandLocator} is a collection of responders to AMP L{Command}s, with
  841. the help of the L{Command.responder} decorator.
  842. """
  843. class __metaclass__(type):
  844. """
  845. This metaclass keeps track of all of the Command.responder-decorated
  846. methods defined since the last CommandLocator subclass was defined. It
  847. assumes (usually correctly, but unfortunately not necessarily so) that
  848. those commands responders were all declared as methods of the class
  849. being defined. Note that this list can be incorrect if users use the
  850. Command.responder decorator outside the context of a CommandLocator
  851. class declaration.
  852. Command responders defined on subclasses are given precedence over
  853. those inherited from a base class.
  854. The Command.responder decorator explicitly cooperates with this
  855. metaclass.
  856. """
  857. _currentClassCommands = []
  858. def __new__(cls, name, bases, attrs):
  859. commands = cls._currentClassCommands[:]
  860. cls._currentClassCommands[:] = []
  861. cd = attrs['_commandDispatch'] = {}
  862. subcls = type.__new__(cls, name, bases, attrs)
  863. ancestors = list(subcls.__mro__[1:])
  864. ancestors.reverse()
  865. for ancestor in ancestors:
  866. cd.update(getattr(ancestor, '_commandDispatch', {}))
  867. for commandClass, responderFunc in commands:
  868. cd[commandClass.commandName] = (commandClass, responderFunc)
  869. if (bases and (
  870. subcls.lookupFunction != CommandLocator.lookupFunction)):
  871. def locateResponder(self, name):
  872. warnings.warn(
  873. "Override locateResponder, not lookupFunction.",
  874. category=PendingDeprecationWarning,
  875. stacklevel=2)
  876. return self.lookupFunction(name)
  877. subcls.locateResponder = locateResponder
  878. return subcls
  879. def _wrapWithSerialization(self, aCallable, command):
  880. """
  881. Wrap aCallable with its command's argument de-serialization
  882. and result serialization logic.
  883. @param aCallable: a callable with a 'command' attribute, designed to be
  884. called with keyword arguments.
  885. @param command: the command class whose serialization to use.
  886. @return: a 1-arg callable which, when invoked with an AmpBox, will
  887. deserialize the argument list and invoke appropriate user code for the
  888. callable's command, returning a Deferred which fires with the result or
  889. fails with an error.
  890. """
  891. def doit(box):
  892. kw = command.parseArguments(box, self)
  893. def checkKnownErrors(error):
  894. key = error.trap(*command.allErrors)
  895. code = command.allErrors[key]
  896. desc = str(error.value)
  897. return Failure(RemoteAmpError(
  898. code, desc, key in command.fatalErrors, local=error))
  899. def makeResponseFor(objects):
  900. try:
  901. return command.makeResponse(objects, self)
  902. except:
  903. # let's helpfully log this.
  904. originalFailure = Failure()
  905. raise BadLocalReturn(
  906. "%r returned %r and %r could not serialize it" % (
  907. aCallable,
  908. objects,
  909. command),
  910. originalFailure)
  911. return maybeDeferred(aCallable, **kw).addCallback(
  912. makeResponseFor).addErrback(
  913. checkKnownErrors)
  914. return doit
  915. def lookupFunction(self, name):
  916. """
  917. Deprecated synonym for L{CommandLocator.locateResponder}
  918. """
  919. if self.__class__.lookupFunction != CommandLocator.lookupFunction:
  920. return CommandLocator.locateResponder(self, name)
  921. else:
  922. warnings.warn("Call locateResponder, not lookupFunction.",
  923. category=PendingDeprecationWarning,
  924. stacklevel=2)
  925. return self.locateResponder(name)
  926. def locateResponder(self, name):
  927. """
  928. Locate a callable to invoke when executing the named command.
  929. @param name: the normalized name (from the wire) of the command.
  930. @type name: C{bytes}
  931. @return: a 1-argument function that takes a Box and returns a box or a
  932. Deferred which fires a Box, for handling the command identified by the
  933. given name, or None, if no appropriate responder can be found.
  934. """
  935. # Try to find a high-level method to invoke, and if we can't find one,
  936. # fall back to a low-level one.
  937. cd = self._commandDispatch
  938. if name in cd:
  939. commandClass, responderFunc = cd[name]
  940. if _PY3:
  941. responderMethod = types.MethodType(
  942. responderFunc, self)
  943. else:
  944. responderMethod = types.MethodType(
  945. responderFunc, self, self.__class__)
  946. return self._wrapWithSerialization(responderMethod, commandClass)
  947. if _PY3:
  948. # Python 3 ignores the __metaclass__ attribute and has instead new syntax
  949. # for setting the metaclass. Unfortunately it's not valid Python 2 syntax
  950. # so we work-around it by recreating CommandLocator using the metaclass
  951. # here.
  952. CommandLocator = CommandLocator.__metaclass__(
  953. "CommandLocator", (CommandLocator, ), {})
  954. @implementer(IResponderLocator)
  955. class SimpleStringLocator(object):
  956. """
  957. Implement the L{AMP.locateResponder} method to do simple, string-based
  958. dispatch.
  959. """
  960. baseDispatchPrefix = b'amp_'
  961. def locateResponder(self, name):
  962. """
  963. Locate a callable to invoke when executing the named command.
  964. @return: a function with the name C{"amp_" + name} on the same
  965. instance, or None if no such function exists.
  966. This function will then be called with the L{AmpBox} itself as an
  967. argument.
  968. @param name: the normalized name (from the wire) of the command.
  969. @type name: C{bytes}
  970. """
  971. fName = nativeString(self.baseDispatchPrefix + name.upper())
  972. return getattr(self, fName, None)
  973. PYTHON_KEYWORDS = [
  974. 'and', 'del', 'for', 'is', 'raise', 'assert', 'elif', 'from', 'lambda',
  975. 'return', 'break', 'else', 'global', 'not', 'try', 'class', 'except',
  976. 'if', 'or', 'while', 'continue', 'exec', 'import', 'pass', 'yield',
  977. 'def', 'finally', 'in', 'print']
  978. def _wireNameToPythonIdentifier(key):
  979. """
  980. (Private) Normalize an argument name from the wire for use with Python
  981. code. If the return value is going to be a python keyword it will be
  982. capitalized. If it contains any dashes they will be replaced with
  983. underscores.
  984. The rationale behind this method is that AMP should be an inherently
  985. multi-language protocol, so message keys may contain all manner of bizarre
  986. bytes. This is not a complete solution; there are still forms of arguments
  987. that this implementation will be unable to parse. However, Python
  988. identifiers share a huge raft of properties with identifiers from many
  989. other languages, so this is a 'good enough' effort for now. We deal
  990. explicitly with dashes because that is the most likely departure: Lisps
  991. commonly use dashes to separate method names, so protocols initially
  992. implemented in a lisp amp dialect may use dashes in argument or command
  993. names.
  994. @param key: a C{bytes}, looking something like 'foo-bar-baz' or 'from'
  995. @type key: C{bytes}
  996. @return: a native string which is a valid python identifier, looking
  997. something like 'foo_bar_baz' or 'From'.
  998. """
  999. lkey = nativeString(key.replace(b"-", b"_"))
  1000. if lkey in PYTHON_KEYWORDS:
  1001. return lkey.title()
  1002. return lkey
  1003. @implementer(IArgumentType)
  1004. class Argument:
  1005. """
  1006. Base-class of all objects that take values from Amp packets and convert
  1007. them into objects for Python functions.
  1008. This implementation of L{IArgumentType} provides several higher-level
  1009. hooks for subclasses to override. See L{toString} and L{fromString}
  1010. which will be used to define the behavior of L{IArgumentType.toBox} and
  1011. L{IArgumentType.fromBox}, respectively.
  1012. """
  1013. optional = False
  1014. def __init__(self, optional=False):
  1015. """
  1016. Create an Argument.
  1017. @param optional: a boolean indicating whether this argument can be
  1018. omitted in the protocol.
  1019. """
  1020. self.optional = optional
  1021. def retrieve(self, d, name, proto):
  1022. """
  1023. Retrieve the given key from the given dictionary, removing it if found.
  1024. @param d: a dictionary.
  1025. @param name: a key in I{d}.
  1026. @param proto: an instance of an AMP.
  1027. @raise KeyError: if I am not optional and no value was found.
  1028. @return: d[name].
  1029. """
  1030. if self.optional:
  1031. value = d.get(name)
  1032. if value is not None:
  1033. del d[name]
  1034. else:
  1035. value = d.pop(name)
  1036. return value
  1037. def fromBox(self, name, strings, objects, proto):
  1038. """
  1039. Populate an 'out' dictionary with mapping names to Python values
  1040. decoded from an 'in' AmpBox mapping strings to string values.
  1041. @param name: the argument name to retrieve
  1042. @type name: C{bytes}
  1043. @param strings: The AmpBox to read string(s) from, a mapping of
  1044. argument names to string values.
  1045. @type strings: AmpBox
  1046. @param objects: The dictionary to write object(s) to, a mapping of
  1047. names to Python objects. Keys will be native strings.
  1048. @type objects: dict
  1049. @param proto: an AMP instance.
  1050. """
  1051. st = self.retrieve(strings, name, proto)
  1052. nk = _wireNameToPythonIdentifier(name)
  1053. if self.optional and st is None:
  1054. objects[nk] = None
  1055. else:
  1056. objects[nk] = self.fromStringProto(st, proto)
  1057. def toBox(self, name, strings, objects, proto):
  1058. """
  1059. Populate an 'out' AmpBox with strings encoded from an 'in' dictionary
  1060. mapping names to Python values.
  1061. @param name: the argument name to retrieve
  1062. @type name: C{bytes}
  1063. @param strings: The AmpBox to write string(s) to, a mapping of
  1064. argument names to string values.
  1065. @type strings: AmpBox
  1066. @param objects: The dictionary to read object(s) from, a mapping of
  1067. names to Python objects. Keys should be native strings.
  1068. @type objects: dict
  1069. @param proto: the protocol we are converting for.
  1070. @type proto: AMP
  1071. """
  1072. obj = self.retrieve(objects, _wireNameToPythonIdentifier(name), proto)
  1073. if self.optional and obj is None:
  1074. # strings[name] = None
  1075. pass
  1076. else:
  1077. strings[name] = self.toStringProto(obj, proto)
  1078. def fromStringProto(self, inString, proto):
  1079. """
  1080. Convert a string to a Python value.
  1081. @param inString: the string to convert.
  1082. @type inString: C{bytes}
  1083. @param proto: the protocol we are converting for.
  1084. @type proto: AMP
  1085. @return: a Python object.
  1086. """
  1087. return self.fromString(inString)
  1088. def toStringProto(self, inObject, proto):
  1089. """
  1090. Convert a Python object to a string.
  1091. @param inObject: the object to convert.
  1092. @param proto: the protocol we are converting for.
  1093. @type proto: AMP
  1094. """
  1095. return self.toString(inObject)
  1096. def fromString(self, inString):
  1097. """
  1098. Convert a string to a Python object. Subclasses must implement this.
  1099. @param inString: the string to convert.
  1100. @type inString: C{bytes}
  1101. @return: the decoded value from C{inString}
  1102. """
  1103. def toString(self, inObject):
  1104. """
  1105. Convert a Python object into a string for passing over the network.
  1106. @param inObject: an object of the type that this Argument is intended
  1107. to deal with.
  1108. @return: the wire encoding of inObject
  1109. @rtype: C{bytes}
  1110. """
  1111. class Integer(Argument):
  1112. """
  1113. Encode any integer values of any size on the wire as the string
  1114. representation.
  1115. Example: C{123} becomes C{"123"}
  1116. """
  1117. fromString = int
  1118. def toString(self, inObject):
  1119. return intToBytes(inObject)
  1120. class String(Argument):
  1121. """
  1122. Don't do any conversion at all; just pass through 'str'.
  1123. """
  1124. def toString(self, inObject):
  1125. return inObject
  1126. def fromString(self, inString):
  1127. return inString
  1128. class Float(Argument):
  1129. """
  1130. Encode floating-point values on the wire as their repr.
  1131. """
  1132. fromString = float
  1133. def toString(self, inString):
  1134. if not isinstance(inString, float):
  1135. raise ValueError("Bad float value %r" % (inString,))
  1136. return str(inString).encode('ascii')
  1137. class Boolean(Argument):
  1138. """
  1139. Encode True or False as "True" or "False" on the wire.
  1140. """
  1141. def fromString(self, inString):
  1142. if inString == b'True':
  1143. return True
  1144. elif inString == b'False':
  1145. return False
  1146. else:
  1147. raise TypeError("Bad boolean value: %r" % (inString,))
  1148. def toString(self, inObject):
  1149. if inObject:
  1150. return b'True'
  1151. else:
  1152. return b'False'
  1153. class Unicode(String):
  1154. """
  1155. Encode a unicode string on the wire as UTF-8.
  1156. """
  1157. def toString(self, inObject):
  1158. return String.toString(self, inObject.encode('utf-8'))
  1159. def fromString(self, inString):
  1160. return String.fromString(self, inString).decode('utf-8')
  1161. class Path(Unicode):
  1162. """
  1163. Encode and decode L{filepath.FilePath} instances as paths on the wire.
  1164. This is really intended for use with subprocess communication tools:
  1165. exchanging pathnames on different machines over a network is not generally
  1166. meaningful, but neither is it disallowed; you can use this to communicate
  1167. about NFS paths, for example.
  1168. """
  1169. def fromString(self, inString):
  1170. return filepath.FilePath(Unicode.fromString(self, inString))
  1171. def toString(self, inObject):
  1172. return Unicode.toString(self, inObject.asTextMode().path)
  1173. class ListOf(Argument):
  1174. """
  1175. Encode and decode lists of instances of a single other argument type.
  1176. For example, if you want to pass::
  1177. [3, 7, 9, 15]
  1178. You can create an argument like this::
  1179. ListOf(Integer())
  1180. The serialized form of the entire list is subject to the limit imposed by
  1181. L{MAX_VALUE_LENGTH}. List elements are represented as 16-bit length
  1182. prefixed strings. The argument type passed to the L{ListOf} initializer is
  1183. responsible for producing the serialized form of each element.
  1184. @ivar elementType: The L{Argument} instance used to encode and decode list
  1185. elements (note, not an arbitrary L{IArgumentType} implementation:
  1186. arguments must be implemented using only the C{fromString} and
  1187. C{toString} methods, not the C{fromBox} and C{toBox} methods).
  1188. @param optional: a boolean indicating whether this argument can be
  1189. omitted in the protocol.
  1190. @since: 10.0
  1191. """
  1192. def __init__(self, elementType, optional=False):
  1193. self.elementType = elementType
  1194. Argument.__init__(self, optional)
  1195. def fromString(self, inString):
  1196. """
  1197. Convert the serialized form of a list of instances of some type back
  1198. into that list.
  1199. """
  1200. strings = []
  1201. parser = Int16StringReceiver()
  1202. parser.stringReceived = strings.append
  1203. parser.dataReceived(inString)
  1204. elementFromString = self.elementType.fromString
  1205. return [elementFromString(string) for string in strings]
  1206. def toString(self, inObject):
  1207. """
  1208. Serialize the given list of objects to a single string.
  1209. """
  1210. strings = []
  1211. for obj in inObject:
  1212. serialized = self.elementType.toString(obj)
  1213. strings.append(pack('!H', len(serialized)))
  1214. strings.append(serialized)
  1215. return b''.join(strings)
  1216. class AmpList(Argument):
  1217. """
  1218. Convert a list of dictionaries into a list of AMP boxes on the wire.
  1219. For example, if you want to pass::
  1220. [{'a': 7, 'b': u'hello'}, {'a': 9, 'b': u'goodbye'}]
  1221. You might use an AmpList like this in your arguments or response list::
  1222. AmpList([('a', Integer()),
  1223. ('b', Unicode())])
  1224. """
  1225. def __init__(self, subargs, optional=False):
  1226. """
  1227. Create an AmpList.
  1228. @param subargs: a list of 2-tuples of ('name', argument) describing the
  1229. schema of the dictionaries in the sequence of amp boxes.
  1230. @type subargs: A C{list} of (C{bytes}, L{Argument}) tuples.
  1231. @param optional: a boolean indicating whether this argument can be
  1232. omitted in the protocol.
  1233. """
  1234. assert all(isinstance(name, bytes) for name, _ in subargs), (
  1235. "AmpList should be defined with a list of (name, argument) "
  1236. "tuples where `name' is a byte string, got: %r" % (subargs, ))
  1237. self.subargs = subargs
  1238. Argument.__init__(self, optional)
  1239. def fromStringProto(self, inString, proto):
  1240. boxes = parseString(inString)
  1241. values = [_stringsToObjects(box, self.subargs, proto)
  1242. for box in boxes]
  1243. return values
  1244. def toStringProto(self, inObject, proto):
  1245. return b''.join([_objectsToStrings(
  1246. objects, self.subargs, Box(), proto
  1247. ).serialize() for objects in inObject])
  1248. class Descriptor(Integer):
  1249. """
  1250. Encode and decode file descriptors for exchange over a UNIX domain socket.
  1251. This argument type requires an AMP connection set up over an
  1252. L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>} provider (for
  1253. example, the kind of connection created by
  1254. L{IReactorUNIX.connectUNIX<twisted.internet.interfaces.IReactorUNIX.connectUNIX>}
  1255. and L{UNIXClientEndpoint<twisted.internet.endpoints.UNIXClientEndpoint>}).
  1256. There is no correspondence between the integer value of the file descriptor
  1257. on the sending and receiving sides, therefore an alternate approach is taken
  1258. to matching up received descriptors with particular L{Descriptor}
  1259. parameters. The argument is encoded to an ordinal (unique per connection)
  1260. for inclusion in the AMP command or response box. The descriptor itself is
  1261. sent using
  1262. L{IUNIXTransport.sendFileDescriptor<twisted.internet.interfaces.IUNIXTransport.sendFileDescriptor>}.
  1263. The receiver uses the order in which file descriptors are received and the
  1264. ordinal value to come up with the received copy of the descriptor.
  1265. """
  1266. def fromStringProto(self, inString, proto):
  1267. """
  1268. Take a unique identifier associated with a file descriptor which must
  1269. have been received by now and use it to look up that descriptor in a
  1270. dictionary where they are kept.
  1271. @param inString: The base representation (as a byte string) of an
  1272. ordinal indicating which file descriptor corresponds to this usage
  1273. of this argument.
  1274. @type inString: C{str}
  1275. @param proto: The protocol used to receive this descriptor. This
  1276. protocol must be connected via a transport providing
  1277. L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>}.
  1278. @type proto: L{BinaryBoxProtocol}
  1279. @return: The file descriptor represented by C{inString}.
  1280. @rtype: C{int}
  1281. """
  1282. return proto._getDescriptor(int(inString))
  1283. def toStringProto(self, inObject, proto):
  1284. """
  1285. Send C{inObject}, an integer file descriptor, over C{proto}'s connection
  1286. and return a unique identifier which will allow the receiver to
  1287. associate the file descriptor with this argument.
  1288. @param inObject: A file descriptor to duplicate over an AMP connection
  1289. as the value for this argument.
  1290. @type inObject: C{int}
  1291. @param proto: The protocol which will be used to send this descriptor.
  1292. This protocol must be connected via a transport providing
  1293. L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>}.
  1294. @return: A byte string which can be used by the receiver to reconstruct
  1295. the file descriptor.
  1296. @type: C{str}
  1297. """
  1298. identifier = proto._sendFileDescriptor(inObject)
  1299. outString = Integer.toStringProto(self, identifier, proto)
  1300. return outString
  1301. class Command:
  1302. """
  1303. Subclass me to specify an AMP Command.
  1304. @cvar arguments: A list of 2-tuples of (name, Argument-subclass-instance),
  1305. specifying the names and values of the parameters which are required for
  1306. this command.
  1307. @cvar response: A list like L{arguments}, but instead used for the return
  1308. value.
  1309. @cvar errors: A mapping of subclasses of L{Exception} to wire-protocol tags
  1310. for errors represented as L{str}s. Responders which raise keys from
  1311. this dictionary will have the error translated to the corresponding tag
  1312. on the wire.
  1313. Invokers which receive Deferreds from invoking this command with
  1314. L{BoxDispatcher.callRemote} will potentially receive Failures with keys
  1315. from this mapping as their value.
  1316. This mapping is inherited; if you declare a command which handles
  1317. C{FooError} as 'FOO_ERROR', then subclass it and specify C{BarError} as
  1318. 'BAR_ERROR', responders to the subclass may raise either C{FooError} or
  1319. C{BarError}, and invokers must be able to deal with either of those
  1320. exceptions.
  1321. @cvar fatalErrors: like 'errors', but errors in this list will always
  1322. terminate the connection, despite being of a recognizable error type.
  1323. @cvar commandType: The type of Box used to issue commands; useful only for
  1324. protocol-modifying behavior like startTLS or protocol switching. Defaults
  1325. to a plain vanilla L{Box}.
  1326. @cvar responseType: The type of Box used to respond to this command; only
  1327. useful for protocol-modifying behavior like startTLS or protocol switching.
  1328. Defaults to a plain vanilla L{Box}.
  1329. @ivar requiresAnswer: a boolean; defaults to True. Set it to False on your
  1330. subclass if you want callRemote to return None. Note: this is a hint only
  1331. to the client side of the protocol. The return-type of a command responder
  1332. method must always be a dictionary adhering to the contract specified by
  1333. L{response}, because clients are always free to request a response if they
  1334. want one.
  1335. """
  1336. class __metaclass__(type):
  1337. """
  1338. Metaclass hack to establish reverse-mappings for 'errors' and
  1339. 'fatalErrors' as class vars.
  1340. """
  1341. def __new__(cls, name, bases, attrs):
  1342. reverseErrors = attrs['reverseErrors'] = {}
  1343. er = attrs['allErrors'] = {}
  1344. if 'commandName' not in attrs:
  1345. if _PY3:
  1346. attrs['commandName'] = name.encode("ascii")
  1347. else:
  1348. attrs['commandName'] = name
  1349. newtype = type.__new__(cls, name, bases, attrs)
  1350. if not isinstance(newtype.commandName, bytes):
  1351. raise TypeError(
  1352. "Command names must be byte strings, got: %r"
  1353. % (newtype.commandName, ))
  1354. for name, _ in newtype.arguments:
  1355. if not isinstance(name, bytes):
  1356. raise TypeError(
  1357. "Argument names must be byte strings, got: %r"
  1358. % (name, ))
  1359. for name, _ in newtype.response:
  1360. if not isinstance(name, bytes):
  1361. raise TypeError(
  1362. "Response names must be byte strings, got: %r"
  1363. % (name, ))
  1364. errors = {}
  1365. fatalErrors = {}
  1366. accumulateClassDict(newtype, 'errors', errors)
  1367. accumulateClassDict(newtype, 'fatalErrors', fatalErrors)
  1368. if not isinstance(newtype.errors, dict):
  1369. newtype.errors = dict(newtype.errors)
  1370. if not isinstance(newtype.fatalErrors, dict):
  1371. newtype.fatalErrors = dict(newtype.fatalErrors)
  1372. for v, k in iteritems(errors):
  1373. reverseErrors[k] = v
  1374. er[v] = k
  1375. for v, k in iteritems(fatalErrors):
  1376. reverseErrors[k] = v
  1377. er[v] = k
  1378. for _, name in iteritems(newtype.errors):
  1379. if not isinstance(name, bytes):
  1380. raise TypeError(
  1381. "Error names must be byte strings, got: %r"
  1382. % (name, ))
  1383. for _, name in iteritems(newtype.fatalErrors):
  1384. if not isinstance(name, bytes):
  1385. raise TypeError(
  1386. "Fatal error names must be byte strings, got: %r"
  1387. % (name, ))
  1388. return newtype
  1389. arguments = []
  1390. response = []
  1391. extra = []
  1392. errors = {}
  1393. fatalErrors = {}
  1394. commandType = Box
  1395. responseType = Box
  1396. requiresAnswer = True
  1397. def __init__(self, **kw):
  1398. """
  1399. Create an instance of this command with specified values for its
  1400. parameters.
  1401. In Python 3, keyword arguments MUST be Unicode/native strings whereas
  1402. in Python 2 they could be either byte strings or Unicode strings.
  1403. A L{Command}'s arguments are defined in its schema using C{bytes}
  1404. names. The values for those arguments are plucked from the keyword
  1405. arguments using the name returned from L{_wireNameToPythonIdentifier}.
  1406. In other words, keyword arguments should be named using the
  1407. Python-side equivalent of the on-wire (C{bytes}) name.
  1408. @param kw: a dict containing an appropriate value for each name
  1409. specified in the L{arguments} attribute of my class.
  1410. @raise InvalidSignature: if you forgot any required arguments.
  1411. """
  1412. self.structured = kw
  1413. forgotten = []
  1414. for name, arg in self.arguments:
  1415. pythonName = _wireNameToPythonIdentifier(name)
  1416. if pythonName not in self.structured and not arg.optional:
  1417. forgotten.append(pythonName)
  1418. if forgotten:
  1419. raise InvalidSignature("forgot %s for %s" % (
  1420. ', '.join(forgotten), self.commandName))
  1421. forgotten = []
  1422. def makeResponse(cls, objects, proto):
  1423. """
  1424. Serialize a mapping of arguments using this L{Command}'s
  1425. response schema.
  1426. @param objects: a dict with keys matching the names specified in
  1427. self.response, having values of the types that the Argument objects in
  1428. self.response can format.
  1429. @param proto: an L{AMP}.
  1430. @return: an L{AmpBox}.
  1431. """
  1432. try:
  1433. responseType = cls.responseType()
  1434. except:
  1435. return fail()
  1436. return _objectsToStrings(objects, cls.response, responseType, proto)
  1437. makeResponse = classmethod(makeResponse)
  1438. def makeArguments(cls, objects, proto):
  1439. """
  1440. Serialize a mapping of arguments using this L{Command}'s
  1441. argument schema.
  1442. @param objects: a dict with keys similar to the names specified in
  1443. self.arguments, having values of the types that the Argument objects in
  1444. self.arguments can parse.
  1445. @param proto: an L{AMP}.
  1446. @return: An instance of this L{Command}'s C{commandType}.
  1447. """
  1448. allowedNames = set()
  1449. for (argName, ignored) in cls.arguments:
  1450. allowedNames.add(_wireNameToPythonIdentifier(argName))
  1451. for intendedArg in objects:
  1452. if intendedArg not in allowedNames:
  1453. raise InvalidSignature(
  1454. "%s is not a valid argument" % (intendedArg,))
  1455. return _objectsToStrings(objects, cls.arguments, cls.commandType(),
  1456. proto)
  1457. makeArguments = classmethod(makeArguments)
  1458. def parseResponse(cls, box, protocol):
  1459. """
  1460. Parse a mapping of serialized arguments using this
  1461. L{Command}'s response schema.
  1462. @param box: A mapping of response-argument names to the
  1463. serialized forms of those arguments.
  1464. @param protocol: The L{AMP} protocol.
  1465. @return: A mapping of response-argument names to the parsed
  1466. forms.
  1467. """
  1468. return _stringsToObjects(box, cls.response, protocol)
  1469. parseResponse = classmethod(parseResponse)
  1470. def parseArguments(cls, box, protocol):
  1471. """
  1472. Parse a mapping of serialized arguments using this
  1473. L{Command}'s argument schema.
  1474. @param box: A mapping of argument names to the seralized forms
  1475. of those arguments.
  1476. @param protocol: The L{AMP} protocol.
  1477. @return: A mapping of argument names to the parsed forms.
  1478. """
  1479. return _stringsToObjects(box, cls.arguments, protocol)
  1480. parseArguments = classmethod(parseArguments)
  1481. def responder(cls, methodfunc):
  1482. """
  1483. Declare a method to be a responder for a particular command.
  1484. This is a decorator.
  1485. Use like so::
  1486. class MyCommand(Command):
  1487. arguments = [('a', ...), ('b', ...)]
  1488. class MyProto(AMP):
  1489. def myFunMethod(self, a, b):
  1490. ...
  1491. MyCommand.responder(myFunMethod)
  1492. Notes: Although decorator syntax is not used within Twisted, this
  1493. function returns its argument and is therefore safe to use with
  1494. decorator syntax.
  1495. This is not thread safe. Don't declare AMP subclasses in other
  1496. threads. Don't declare responders outside the scope of AMP subclasses;
  1497. the behavior is undefined.
  1498. @param methodfunc: A function which will later become a method, which
  1499. has a keyword signature compatible with this command's L{argument} list
  1500. and returns a dictionary with a set of keys compatible with this
  1501. command's L{response} list.
  1502. @return: the methodfunc parameter.
  1503. """
  1504. CommandLocator._currentClassCommands.append((cls, methodfunc))
  1505. return methodfunc
  1506. responder = classmethod(responder)
  1507. # Our only instance method
  1508. def _doCommand(self, proto):
  1509. """
  1510. Encode and send this Command to the given protocol.
  1511. @param proto: an AMP, representing the connection to send to.
  1512. @return: a Deferred which will fire or error appropriately when the
  1513. other side responds to the command (or error if the connection is lost
  1514. before it is responded to).
  1515. """
  1516. def _massageError(error):
  1517. error.trap(RemoteAmpError)
  1518. rje = error.value
  1519. errorType = self.reverseErrors.get(rje.errorCode,
  1520. UnknownRemoteError)
  1521. return Failure(errorType(rje.description))
  1522. d = proto._sendBoxCommand(self.commandName,
  1523. self.makeArguments(self.structured, proto),
  1524. self.requiresAnswer)
  1525. if self.requiresAnswer:
  1526. d.addCallback(self.parseResponse, proto)
  1527. d.addErrback(_massageError)
  1528. return d
  1529. if _PY3:
  1530. # Python 3 ignores the __metaclass__ attribute and has instead new syntax
  1531. # for setting the metaclass. Unfortunately it's not valid Python 2 syntax
  1532. # so we work-around it by recreating Command using the metaclass here.
  1533. Command = Command.__metaclass__("Command", (Command, ), {})
  1534. class _NoCertificate:
  1535. """
  1536. This is for peers which don't want to use a local certificate. Used by
  1537. AMP because AMP's internal language is all about certificates and this
  1538. duck-types in the appropriate place; this API isn't really stable though,
  1539. so it's not exposed anywhere public.
  1540. For clients, it will use ephemeral DH keys, or whatever the default is for
  1541. certificate-less clients in OpenSSL. For servers, it will generate a
  1542. temporary self-signed certificate with garbage values in the DN and use
  1543. that.
  1544. """
  1545. def __init__(self, client):
  1546. """
  1547. Create a _NoCertificate which either is or isn't for the client side of
  1548. the connection.
  1549. @param client: True if we are a client and should truly have no
  1550. certificate and be anonymous, False if we are a server and actually
  1551. have to generate a temporary certificate.
  1552. @type client: bool
  1553. """
  1554. self.client = client
  1555. def options(self, *authorities):
  1556. """
  1557. Behaves like L{twisted.internet.ssl.PrivateCertificate.options}().
  1558. """
  1559. if not self.client:
  1560. # do some crud with sslverify to generate a temporary self-signed
  1561. # certificate. This is SLOOOWWWWW so it is only in the absolute
  1562. # worst, most naive case.
  1563. # We have to do this because OpenSSL will not let both the server
  1564. # and client be anonymous.
  1565. sharedDN = DN(CN='TEMPORARY CERTIFICATE')
  1566. key = KeyPair.generate()
  1567. cr = key.certificateRequest(sharedDN)
  1568. sscrd = key.signCertificateRequest(sharedDN, cr, lambda dn: True, 1)
  1569. cert = key.newCertificate(sscrd)
  1570. return cert.options(*authorities)
  1571. options = dict()
  1572. if authorities:
  1573. options.update(dict(verify=True,
  1574. requireCertificate=True,
  1575. caCerts=[auth.original for auth in authorities]))
  1576. occo = CertificateOptions(**options)
  1577. return occo
  1578. class _TLSBox(AmpBox):
  1579. """
  1580. I am an AmpBox that, upon being sent, initiates a TLS connection.
  1581. """
  1582. __slots__ = []
  1583. def __init__(self):
  1584. if ssl is None:
  1585. raise RemoteAmpError(b"TLS_ERROR", "TLS not available")
  1586. AmpBox.__init__(self)
  1587. def _keyprop(k, default):
  1588. return property(lambda self: self.get(k, default))
  1589. # These properties are described in startTLS
  1590. certificate = _keyprop(b'tls_localCertificate', _NoCertificate(False))
  1591. verify = _keyprop(b'tls_verifyAuthorities', None)
  1592. def _sendTo(self, proto):
  1593. """
  1594. Send my encoded value to the protocol, then initiate TLS.
  1595. """
  1596. ab = AmpBox(self)
  1597. for k in [b'tls_localCertificate',
  1598. b'tls_verifyAuthorities']:
  1599. ab.pop(k, None)
  1600. ab._sendTo(proto)
  1601. proto._startTLS(self.certificate, self.verify)
  1602. class _LocalArgument(String):
  1603. """
  1604. Local arguments are never actually relayed across the wire. This is just a
  1605. shim so that StartTLS can pretend to have some arguments: if arguments
  1606. acquire documentation properties, replace this with something nicer later.
  1607. """
  1608. def fromBox(self, name, strings, objects, proto):
  1609. pass
  1610. class StartTLS(Command):
  1611. """
  1612. Use, or subclass, me to implement a command that starts TLS.
  1613. Callers of StartTLS may pass several special arguments, which affect the
  1614. TLS negotiation:
  1615. - tls_localCertificate: This is a
  1616. twisted.internet.ssl.PrivateCertificate which will be used to secure
  1617. the side of the connection it is returned on.
  1618. - tls_verifyAuthorities: This is a list of
  1619. twisted.internet.ssl.Certificate objects that will be used as the
  1620. certificate authorities to verify our peer's certificate.
  1621. Each of those special parameters may also be present as a key in the
  1622. response dictionary.
  1623. """
  1624. arguments = [(b"tls_localCertificate", _LocalArgument(optional=True)),
  1625. (b"tls_verifyAuthorities", _LocalArgument(optional=True))]
  1626. response = [(b"tls_localCertificate", _LocalArgument(optional=True)),
  1627. (b"tls_verifyAuthorities", _LocalArgument(optional=True))]
  1628. responseType = _TLSBox
  1629. def __init__(self, **kw):
  1630. """
  1631. Create a StartTLS command. (This is private. Use AMP.callRemote.)
  1632. @param tls_localCertificate: the PrivateCertificate object to use to
  1633. secure the connection. If it's None, or unspecified, an ephemeral DH
  1634. key is used instead.
  1635. @param tls_verifyAuthorities: a list of Certificate objects which
  1636. represent root certificates to verify our peer with.
  1637. """
  1638. if ssl is None:
  1639. raise RuntimeError("TLS not available.")
  1640. self.certificate = kw.pop('tls_localCertificate', _NoCertificate(True))
  1641. self.authorities = kw.pop('tls_verifyAuthorities', None)
  1642. Command.__init__(self, **kw)
  1643. def _doCommand(self, proto):
  1644. """
  1645. When a StartTLS command is sent, prepare to start TLS, but don't actually
  1646. do it; wait for the acknowledgement, then initiate the TLS handshake.
  1647. """
  1648. d = Command._doCommand(self, proto)
  1649. proto._prepareTLS(self.certificate, self.authorities)
  1650. # XXX before we get back to user code we are going to start TLS...
  1651. def actuallystart(response):
  1652. proto._startTLS(self.certificate, self.authorities)
  1653. return response
  1654. d.addCallback(actuallystart)
  1655. return d
  1656. class ProtocolSwitchCommand(Command):
  1657. """
  1658. Use this command to switch from something Amp-derived to a different
  1659. protocol mid-connection. This can be useful to use amp as the
  1660. connection-startup negotiation phase. Since TLS is a different layer
  1661. entirely, you can use Amp to negotiate the security parameters of your
  1662. connection, then switch to a different protocol, and the connection will
  1663. remain secured.
  1664. """
  1665. def __init__(self, _protoToSwitchToFactory, **kw):
  1666. """
  1667. Create a ProtocolSwitchCommand.
  1668. @param _protoToSwitchToFactory: a ProtocolFactory which will generate
  1669. the Protocol to switch to.
  1670. @param kw: Keyword arguments, encoded and handled normally as
  1671. L{Command} would.
  1672. """
  1673. self.protoToSwitchToFactory = _protoToSwitchToFactory
  1674. super(ProtocolSwitchCommand, self).__init__(**kw)
  1675. def makeResponse(cls, innerProto, proto):
  1676. return _SwitchBox(innerProto)
  1677. makeResponse = classmethod(makeResponse)
  1678. def _doCommand(self, proto):
  1679. """
  1680. When we emit a ProtocolSwitchCommand, lock the protocol, but don't actually
  1681. switch to the new protocol unless an acknowledgement is received. If
  1682. an error is received, switch back.
  1683. """
  1684. d = super(ProtocolSwitchCommand, self)._doCommand(proto)
  1685. proto._lockForSwitch()
  1686. def switchNow(ign):
  1687. innerProto = self.protoToSwitchToFactory.buildProtocol(
  1688. proto.transport.getPeer())
  1689. proto._switchTo(innerProto, self.protoToSwitchToFactory)
  1690. return ign
  1691. def handle(ign):
  1692. proto._unlockFromSwitch()
  1693. self.protoToSwitchToFactory.clientConnectionFailed(
  1694. None, Failure(CONNECTION_LOST))
  1695. return ign
  1696. return d.addCallbacks(switchNow, handle)
  1697. @implementer(IFileDescriptorReceiver)
  1698. class _DescriptorExchanger(object):
  1699. """
  1700. L{_DescriptorExchanger} is a mixin for L{BinaryBoxProtocol} which adds
  1701. support for receiving file descriptors, a feature offered by
  1702. L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>}.
  1703. @ivar _descriptors: Temporary storage for all file descriptors received.
  1704. Values in this dictionary are the file descriptors (as integers). Keys
  1705. in this dictionary are ordinals giving the order in which each
  1706. descriptor was received. The ordering information is used to allow
  1707. L{Descriptor} to determine which is the correct descriptor for any
  1708. particular usage of that argument type.
  1709. @type _descriptors: C{dict}
  1710. @ivar _sendingDescriptorCounter: A no-argument callable which returns the
  1711. ordinals, starting from 0. This is used to construct values for
  1712. C{_sendFileDescriptor}.
  1713. @ivar _receivingDescriptorCounter: A no-argument callable which returns the
  1714. ordinals, starting from 0. This is used to construct values for
  1715. C{fileDescriptorReceived}.
  1716. """
  1717. def __init__(self):
  1718. self._descriptors = {}
  1719. self._getDescriptor = self._descriptors.pop
  1720. self._sendingDescriptorCounter = partial(next, count())
  1721. self._receivingDescriptorCounter = partial(next, count())
  1722. def _sendFileDescriptor(self, descriptor):
  1723. """
  1724. Assign and return the next ordinal to the given descriptor after sending
  1725. the descriptor over this protocol's transport.
  1726. """
  1727. self.transport.sendFileDescriptor(descriptor)
  1728. return self._sendingDescriptorCounter()
  1729. def fileDescriptorReceived(self, descriptor):
  1730. """
  1731. Collect received file descriptors to be claimed later by L{Descriptor}.
  1732. @param descriptor: The received file descriptor.
  1733. @type descriptor: C{int}
  1734. """
  1735. self._descriptors[self._receivingDescriptorCounter()] = descriptor
  1736. @implementer(IBoxSender)
  1737. class BinaryBoxProtocol(StatefulStringProtocol, Int16StringReceiver,
  1738. _DescriptorExchanger):
  1739. """
  1740. A protocol for receiving L{AmpBox}es - key/value pairs - via length-prefixed
  1741. strings. A box is composed of:
  1742. - any number of key-value pairs, described by:
  1743. - a 2-byte network-endian packed key length (of which the first
  1744. byte must be null, and the second must be non-null: i.e. the
  1745. value of the length must be 1-255)
  1746. - a key, comprised of that many bytes
  1747. - a 2-byte network-endian unsigned value length (up to the maximum
  1748. of 65535)
  1749. - a value, comprised of that many bytes
  1750. - 2 null bytes
  1751. In other words, an even number of strings prefixed with packed unsigned
  1752. 16-bit integers, and then a 0-length string to indicate the end of the box.
  1753. This protocol also implements 2 extra private bits of functionality related
  1754. to the byte boundaries between messages; it can start TLS between two given
  1755. boxes or switch to an entirely different protocol. However, due to some
  1756. tricky elements of the implementation, the public interface to this
  1757. functionality is L{ProtocolSwitchCommand} and L{StartTLS}.
  1758. @ivar _keyLengthLimitExceeded: A flag which is only true when the
  1759. connection is being closed because a key length prefix which was longer
  1760. than allowed by the protocol was received.
  1761. @ivar boxReceiver: an L{IBoxReceiver} provider, whose
  1762. L{IBoxReceiver.ampBoxReceived} method will be invoked for each
  1763. L{AmpBox} that is received.
  1764. """
  1765. _justStartedTLS = False
  1766. _startingTLSBuffer = None
  1767. _locked = False
  1768. _currentKey = None
  1769. _currentBox = None
  1770. _keyLengthLimitExceeded = False
  1771. hostCertificate = None
  1772. noPeerCertificate = False # for tests
  1773. innerProtocol = None
  1774. innerProtocolClientFactory = None
  1775. def __init__(self, boxReceiver):
  1776. _DescriptorExchanger.__init__(self)
  1777. self.boxReceiver = boxReceiver
  1778. def _switchTo(self, newProto, clientFactory=None):
  1779. """
  1780. Switch this BinaryBoxProtocol's transport to a new protocol. You need
  1781. to do this 'simultaneously' on both ends of a connection; the easiest
  1782. way to do this is to use a subclass of ProtocolSwitchCommand.
  1783. @param newProto: the new protocol instance to switch to.
  1784. @param clientFactory: the ClientFactory to send the
  1785. L{twisted.internet.protocol.ClientFactory.clientConnectionLost}
  1786. notification to.
  1787. """
  1788. # All the data that Int16Receiver has not yet dealt with belongs to our
  1789. # new protocol: luckily it's keeping that in a handy (although
  1790. # ostensibly internal) variable for us:
  1791. newProtoData = self.recvd
  1792. # We're quite possibly in the middle of a 'dataReceived' loop in
  1793. # Int16StringReceiver: let's make sure that the next iteration, the
  1794. # loop will break and not attempt to look at something that isn't a
  1795. # length prefix.
  1796. self.recvd = ''
  1797. # Finally, do the actual work of setting up the protocol and delivering
  1798. # its first chunk of data, if one is available.
  1799. self.innerProtocol = newProto
  1800. self.innerProtocolClientFactory = clientFactory
  1801. newProto.makeConnection(self.transport)
  1802. if newProtoData:
  1803. newProto.dataReceived(newProtoData)
  1804. def sendBox(self, box):
  1805. """
  1806. Send a amp.Box to my peer.
  1807. Note: transport.write is never called outside of this method.
  1808. @param box: an AmpBox.
  1809. @raise ProtocolSwitched: if the protocol has previously been switched.
  1810. @raise ConnectionLost: if the connection has previously been lost.
  1811. """
  1812. if self._locked:
  1813. raise ProtocolSwitched(
  1814. "This connection has switched: no AMP traffic allowed.")
  1815. if self.transport is None:
  1816. raise ConnectionLost()
  1817. if self._startingTLSBuffer is not None:
  1818. self._startingTLSBuffer.append(box)
  1819. else:
  1820. self.transport.write(box.serialize())
  1821. def makeConnection(self, transport):
  1822. """
  1823. Notify L{boxReceiver} that it is about to receive boxes from this
  1824. protocol by invoking L{IBoxReceiver.startReceivingBoxes}.
  1825. """
  1826. self.transport = transport
  1827. self.boxReceiver.startReceivingBoxes(self)
  1828. self.connectionMade()
  1829. def dataReceived(self, data):
  1830. """
  1831. Either parse incoming data as L{AmpBox}es or relay it to our nested
  1832. protocol.
  1833. """
  1834. if self._justStartedTLS:
  1835. self._justStartedTLS = False
  1836. # If we already have an inner protocol, then we don't deliver data to
  1837. # the protocol parser any more; we just hand it off.
  1838. if self.innerProtocol is not None:
  1839. self.innerProtocol.dataReceived(data)
  1840. return
  1841. return Int16StringReceiver.dataReceived(self, data)
  1842. def connectionLost(self, reason):
  1843. """
  1844. The connection was lost; notify any nested protocol.
  1845. """
  1846. if self.innerProtocol is not None:
  1847. self.innerProtocol.connectionLost(reason)
  1848. if self.innerProtocolClientFactory is not None:
  1849. self.innerProtocolClientFactory.clientConnectionLost(None, reason)
  1850. if self._keyLengthLimitExceeded:
  1851. failReason = Failure(TooLong(True, False, None, None))
  1852. elif reason.check(ConnectionClosed) and self._justStartedTLS:
  1853. # We just started TLS and haven't received any data. This means
  1854. # the other connection didn't like our cert (although they may not
  1855. # have told us why - later Twisted should make 'reason' into a TLS
  1856. # error.)
  1857. failReason = PeerVerifyError(
  1858. "Peer rejected our certificate for an unknown reason.")
  1859. else:
  1860. failReason = reason
  1861. self.boxReceiver.stopReceivingBoxes(failReason)
  1862. # The longest key allowed
  1863. _MAX_KEY_LENGTH = 255
  1864. # The longest value allowed (this is somewhat redundant, as longer values
  1865. # cannot be encoded - ah well).
  1866. _MAX_VALUE_LENGTH = 65535
  1867. # The first thing received is a key.
  1868. MAX_LENGTH = _MAX_KEY_LENGTH
  1869. def proto_init(self, string):
  1870. """
  1871. String received in the 'init' state.
  1872. """
  1873. self._currentBox = AmpBox()
  1874. return self.proto_key(string)
  1875. def proto_key(self, string):
  1876. """
  1877. String received in the 'key' state. If the key is empty, a complete
  1878. box has been received.
  1879. """
  1880. if string:
  1881. self._currentKey = string
  1882. self.MAX_LENGTH = self._MAX_VALUE_LENGTH
  1883. return 'value'
  1884. else:
  1885. self.boxReceiver.ampBoxReceived(self._currentBox)
  1886. self._currentBox = None
  1887. return 'init'
  1888. def proto_value(self, string):
  1889. """
  1890. String received in the 'value' state.
  1891. """
  1892. self._currentBox[self._currentKey] = string
  1893. self._currentKey = None
  1894. self.MAX_LENGTH = self._MAX_KEY_LENGTH
  1895. return 'key'
  1896. def lengthLimitExceeded(self, length):
  1897. """
  1898. The key length limit was exceeded. Disconnect the transport and make
  1899. sure a meaningful exception is reported.
  1900. """
  1901. self._keyLengthLimitExceeded = True
  1902. self.transport.loseConnection()
  1903. def _lockForSwitch(self):
  1904. """
  1905. Lock this binary protocol so that no further boxes may be sent. This
  1906. is used when sending a request to switch underlying protocols. You
  1907. probably want to subclass ProtocolSwitchCommand rather than calling
  1908. this directly.
  1909. """
  1910. self._locked = True
  1911. def _unlockFromSwitch(self):
  1912. """
  1913. Unlock this locked binary protocol so that further boxes may be sent
  1914. again. This is used after an attempt to switch protocols has failed
  1915. for some reason.
  1916. """
  1917. if self.innerProtocol is not None:
  1918. raise ProtocolSwitched("Protocol already switched. Cannot unlock.")
  1919. self._locked = False
  1920. def _prepareTLS(self, certificate, verifyAuthorities):
  1921. """
  1922. Used by StartTLSCommand to put us into the state where we don't
  1923. actually send things that get sent, instead we buffer them. see
  1924. L{_sendBoxCommand}.
  1925. """
  1926. self._startingTLSBuffer = []
  1927. if self.hostCertificate is not None:
  1928. raise OnlyOneTLS(
  1929. "Previously authenticated connection between %s and %s "
  1930. "is trying to re-establish as %s" % (
  1931. self.hostCertificate,
  1932. self.peerCertificate,
  1933. (certificate, verifyAuthorities)))
  1934. def _startTLS(self, certificate, verifyAuthorities):
  1935. """
  1936. Used by TLSBox to initiate the SSL handshake.
  1937. @param certificate: a L{twisted.internet.ssl.PrivateCertificate} for
  1938. use locally.
  1939. @param verifyAuthorities: L{twisted.internet.ssl.Certificate} instances
  1940. representing certificate authorities which will verify our peer.
  1941. """
  1942. self.hostCertificate = certificate
  1943. self._justStartedTLS = True
  1944. if verifyAuthorities is None:
  1945. verifyAuthorities = ()
  1946. self.transport.startTLS(certificate.options(*verifyAuthorities))
  1947. stlsb = self._startingTLSBuffer
  1948. if stlsb is not None:
  1949. self._startingTLSBuffer = None
  1950. for box in stlsb:
  1951. self.sendBox(box)
  1952. def _getPeerCertificate(self):
  1953. if self.noPeerCertificate:
  1954. return None
  1955. return Certificate.peerFromTransport(self.transport)
  1956. peerCertificate = property(_getPeerCertificate)
  1957. def unhandledError(self, failure):
  1958. """
  1959. The buck stops here. This error was completely unhandled, time to
  1960. terminate the connection.
  1961. """
  1962. log.err(
  1963. failure,
  1964. "Amp server or network failure unhandled by client application. "
  1965. "Dropping connection! To avoid, add errbacks to ALL remote "
  1966. "commands!")
  1967. if self.transport is not None:
  1968. self.transport.loseConnection()
  1969. def _defaultStartTLSResponder(self):
  1970. """
  1971. The default TLS responder doesn't specify any certificate or anything.
  1972. From a security perspective, it's little better than a plain-text
  1973. connection - but it is still a *bit* better, so it's included for
  1974. convenience.
  1975. You probably want to override this by providing your own StartTLS.responder.
  1976. """
  1977. return {}
  1978. StartTLS.responder(_defaultStartTLSResponder)
  1979. class AMP(BinaryBoxProtocol, BoxDispatcher,
  1980. CommandLocator, SimpleStringLocator):
  1981. """
  1982. This protocol is an AMP connection. See the module docstring for protocol
  1983. details.
  1984. """
  1985. _ampInitialized = False
  1986. def __init__(self, boxReceiver=None, locator=None):
  1987. # For backwards compatibility. When AMP did not separate parsing logic
  1988. # (L{BinaryBoxProtocol}), request-response logic (L{BoxDispatcher}) and
  1989. # command routing (L{CommandLocator}), it did not have a constructor.
  1990. # Now it does, so old subclasses might have defined their own that did
  1991. # not upcall. If this flag isn't set, we'll call the constructor in
  1992. # makeConnection before anything actually happens.
  1993. self._ampInitialized = True
  1994. if boxReceiver is None:
  1995. boxReceiver = self
  1996. if locator is None:
  1997. locator = self
  1998. BoxDispatcher.__init__(self, locator)
  1999. BinaryBoxProtocol.__init__(self, boxReceiver)
  2000. def locateResponder(self, name):
  2001. """
  2002. Unify the implementations of L{CommandLocator} and
  2003. L{SimpleStringLocator} to perform both kinds of dispatch, preferring
  2004. L{CommandLocator}.
  2005. @type name: C{bytes}
  2006. """
  2007. firstResponder = CommandLocator.locateResponder(self, name)
  2008. if firstResponder is not None:
  2009. return firstResponder
  2010. secondResponder = SimpleStringLocator.locateResponder(self, name)
  2011. return secondResponder
  2012. def __repr__(self):
  2013. """
  2014. A verbose string representation which gives us information about this
  2015. AMP connection.
  2016. """
  2017. if self.innerProtocol is not None:
  2018. innerRepr = ' inner %r' % (self.innerProtocol,)
  2019. else:
  2020. innerRepr = ''
  2021. return '<%s%s at 0x%x>' % (
  2022. self.__class__.__name__, innerRepr, id(self))
  2023. def makeConnection(self, transport):
  2024. """
  2025. Emit a helpful log message when the connection is made.
  2026. """
  2027. if not self._ampInitialized:
  2028. # See comment in the constructor re: backward compatibility. I
  2029. # should probably emit a deprecation warning here.
  2030. AMP.__init__(self)
  2031. # Save these so we can emit a similar log message in L{connectionLost}.
  2032. self._transportPeer = transport.getPeer()
  2033. self._transportHost = transport.getHost()
  2034. log.msg("%s connection established (HOST:%s PEER:%s)" % (
  2035. self.__class__.__name__,
  2036. self._transportHost,
  2037. self._transportPeer))
  2038. BinaryBoxProtocol.makeConnection(self, transport)
  2039. def connectionLost(self, reason):
  2040. """
  2041. Emit a helpful log message when the connection is lost.
  2042. """
  2043. log.msg("%s connection lost (HOST:%s PEER:%s)" %
  2044. (self.__class__.__name__,
  2045. self._transportHost,
  2046. self._transportPeer))
  2047. BinaryBoxProtocol.connectionLost(self, reason)
  2048. self.transport = None
  2049. class _ParserHelper:
  2050. """
  2051. A box receiver which records all boxes received.
  2052. """
  2053. def __init__(self):
  2054. self.boxes = []
  2055. def getPeer(self):
  2056. return 'string'
  2057. def getHost(self):
  2058. return 'string'
  2059. disconnecting = False
  2060. def startReceivingBoxes(self, sender):
  2061. """
  2062. No initialization is required.
  2063. """
  2064. def ampBoxReceived(self, box):
  2065. self.boxes.append(box)
  2066. # Synchronous helpers
  2067. def parse(cls, fileObj):
  2068. """
  2069. Parse some amp data stored in a file.
  2070. @param fileObj: a file-like object.
  2071. @return: a list of AmpBoxes encoded in the given file.
  2072. """
  2073. parserHelper = cls()
  2074. bbp = BinaryBoxProtocol(boxReceiver=parserHelper)
  2075. bbp.makeConnection(parserHelper)
  2076. bbp.dataReceived(fileObj.read())
  2077. return parserHelper.boxes
  2078. parse = classmethod(parse)
  2079. def parseString(cls, data):
  2080. """
  2081. Parse some amp data stored in a string.
  2082. @param data: a str holding some amp-encoded data.
  2083. @return: a list of AmpBoxes encoded in the given string.
  2084. """
  2085. return cls.parse(BytesIO(data))
  2086. parseString = classmethod(parseString)
  2087. parse = _ParserHelper.parse
  2088. parseString = _ParserHelper.parseString
  2089. def _stringsToObjects(strings, arglist, proto):
  2090. """
  2091. Convert an AmpBox to a dictionary of python objects, converting through a
  2092. given arglist.
  2093. @param strings: an AmpBox (or dict of strings)
  2094. @param arglist: a list of 2-tuples of strings and Argument objects, as
  2095. described in L{Command.arguments}.
  2096. @param proto: an L{AMP} instance.
  2097. @return: the converted dictionary mapping names to argument objects.
  2098. """
  2099. objects = {}
  2100. myStrings = strings.copy()
  2101. for argname, argparser in arglist:
  2102. argparser.fromBox(argname, myStrings, objects, proto)
  2103. return objects
  2104. def _objectsToStrings(objects, arglist, strings, proto):
  2105. """
  2106. Convert a dictionary of python objects to an AmpBox, converting through a
  2107. given arglist.
  2108. @param objects: a dict mapping names to python objects
  2109. @param arglist: a list of 2-tuples of strings and Argument objects, as
  2110. described in L{Command.arguments}.
  2111. @param strings: [OUT PARAMETER] An object providing the L{dict}
  2112. interface which will be populated with serialized data.
  2113. @param proto: an L{AMP} instance.
  2114. @return: The converted dictionary mapping names to encoded argument
  2115. strings (identical to C{strings}).
  2116. """
  2117. myObjects = objects.copy()
  2118. for argname, argparser in arglist:
  2119. argparser.toBox(argname, strings, myObjects, proto)
  2120. return strings
  2121. class Decimal(Argument):
  2122. """
  2123. Encodes C{decimal.Decimal} instances.
  2124. There are several ways in which a decimal value might be encoded.
  2125. Special values are encoded as special strings::
  2126. - Positive infinity is encoded as C{"Infinity"}
  2127. - Negative infinity is encoded as C{"-Infinity"}
  2128. - Quiet not-a-number is encoded as either C{"NaN"} or C{"-NaN"}
  2129. - Signalling not-a-number is encoded as either C{"sNaN"} or C{"-sNaN"}
  2130. Normal values are encoded using the base ten string representation, using
  2131. engineering notation to indicate magnitude without precision, and "normal"
  2132. digits to indicate precision. For example::
  2133. - C{"1"} represents the value I{1} with precision to one place.
  2134. - C{"-1"} represents the value I{-1} with precision to one place.
  2135. - C{"1.0"} represents the value I{1} with precision to two places.
  2136. - C{"10"} represents the value I{10} with precision to two places.
  2137. - C{"1E+2"} represents the value I{10} with precision to one place.
  2138. - C{"1E-1"} represents the value I{0.1} with precision to one place.
  2139. - C{"1.5E+2"} represents the value I{15} with precision to two places.
  2140. U{http://speleotrove.com/decimal/} should be considered the authoritative
  2141. specification for the format.
  2142. """
  2143. def fromString(self, inString):
  2144. inString = nativeString(inString)
  2145. return decimal.Decimal(inString)
  2146. def toString(self, inObject):
  2147. """
  2148. Serialize a C{decimal.Decimal} instance to the specified wire format.
  2149. """
  2150. if isinstance(inObject, decimal.Decimal):
  2151. # Hopefully decimal.Decimal.__str__ actually does what we want.
  2152. return str(inObject).encode("ascii")
  2153. raise ValueError(
  2154. "amp.Decimal can only encode instances of decimal.Decimal")
  2155. class DateTime(Argument):
  2156. """
  2157. Encodes C{datetime.datetime} instances.
  2158. Wire format: '%04i-%02i-%02iT%02i:%02i:%02i.%06i%s%02i:%02i'. Fields in
  2159. order are: year, month, day, hour, minute, second, microsecond, timezone
  2160. direction (+ or -), timezone hour, timezone minute. Encoded string is
  2161. always exactly 32 characters long. This format is compatible with ISO 8601,
  2162. but that does not mean all ISO 8601 dates can be accepted.
  2163. Also, note that the datetime module's notion of a "timezone" can be
  2164. complex, but the wire format includes only a fixed offset, so the
  2165. conversion is not lossless. A lossless transmission of a C{datetime} instance
  2166. is not feasible since the receiving end would require a Python interpreter.
  2167. @ivar _positions: A sequence of slices giving the positions of various
  2168. interesting parts of the wire format.
  2169. """
  2170. _positions = [
  2171. slice(0, 4), slice(5, 7), slice(8, 10), # year, month, day
  2172. slice(11, 13), slice(14, 16), slice(17, 19), # hour, minute, second
  2173. slice(20, 26), # microsecond
  2174. # intentionally skip timezone direction, as it is not an integer
  2175. slice(27, 29), slice(30, 32) # timezone hour, timezone minute
  2176. ]
  2177. def fromString(self, s):
  2178. """
  2179. Parse a string containing a date and time in the wire format into a
  2180. C{datetime.datetime} instance.
  2181. """
  2182. s = nativeString(s)
  2183. if len(s) != 32:
  2184. raise ValueError('invalid date format %r' % (s,))
  2185. values = [int(s[p]) for p in self._positions]
  2186. sign = s[26]
  2187. timezone = _FixedOffsetTZInfo.fromSignHoursMinutes(sign, *values[7:])
  2188. values[7:] = [timezone]
  2189. return datetime.datetime(*values)
  2190. def toString(self, i):
  2191. """
  2192. Serialize a C{datetime.datetime} instance to a string in the specified
  2193. wire format.
  2194. """
  2195. offset = i.utcoffset()
  2196. if offset is None:
  2197. raise ValueError(
  2198. 'amp.DateTime cannot serialize naive datetime instances. '
  2199. 'You may find amp.utc useful.')
  2200. minutesOffset = (offset.days * 86400 + offset.seconds) // 60
  2201. if minutesOffset > 0:
  2202. sign = '+'
  2203. else:
  2204. sign = '-'
  2205. # strftime has no way to format the microseconds, or put a ':' in the
  2206. # timezone. Surprise!
  2207. # Python 3.4 cannot do % interpolation on byte strings so we pack into
  2208. # an explicitly Unicode string then encode as ASCII.
  2209. packed = u'%04i-%02i-%02iT%02i:%02i:%02i.%06i%s%02i:%02i' % (
  2210. i.year,
  2211. i.month,
  2212. i.day,
  2213. i.hour,
  2214. i.minute,
  2215. i.second,
  2216. i.microsecond,
  2217. sign,
  2218. abs(minutesOffset) // 60,
  2219. abs(minutesOffset) % 60)
  2220. return packed.encode("ascii")