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

5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894
  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. return fail(self._failAllReason)
  665. box[COMMAND] = command
  666. tag = self._nextTag()
  667. if requiresAnswer:
  668. box[ASK] = tag
  669. box._sendTo(self.boxSender)
  670. if requiresAnswer:
  671. result = self._outstandingRequests[tag] = Deferred()
  672. else:
  673. result = None
  674. return result
  675. def callRemoteString(self, command, requiresAnswer=True, **kw):
  676. """
  677. This is a low-level API, designed only for optimizing simple messages
  678. for which the overhead of parsing is too great.
  679. @param command: a C{bytes} naming the command.
  680. @param kw: arguments to the amp box.
  681. @param requiresAnswer: a boolean. Defaults to True. If True, return a
  682. Deferred which will fire when the other side responds to this command.
  683. If False, return None and do not ask the other side for acknowledgement.
  684. @return: a Deferred which fires the AmpBox that holds the response to
  685. this command, or None, as specified by requiresAnswer.
  686. """
  687. box = Box(kw)
  688. return self._sendBoxCommand(command, box, requiresAnswer)
  689. def callRemote(self, commandType, *a, **kw):
  690. """
  691. This is the primary high-level API for sending messages via AMP. Invoke it
  692. with a command and appropriate arguments to send a message to this
  693. connection's peer.
  694. @param commandType: a subclass of Command.
  695. @type commandType: L{type}
  696. @param a: Positional (special) parameters taken by the command.
  697. Positional parameters will typically not be sent over the wire. The
  698. only command included with AMP which uses positional parameters is
  699. L{ProtocolSwitchCommand}, which takes the protocol that will be
  700. switched to as its first argument.
  701. @param kw: Keyword arguments taken by the command. These are the
  702. arguments declared in the command's 'arguments' attribute. They will
  703. be encoded and sent to the peer as arguments for the L{commandType}.
  704. @return: If L{commandType} has a C{requiresAnswer} attribute set to
  705. L{False}, then return L{None}. Otherwise, return a L{Deferred} which
  706. fires with a dictionary of objects representing the result of this
  707. call. Additionally, this L{Deferred} may fail with an exception
  708. representing a connection failure, with L{UnknownRemoteError} if the
  709. other end of the connection fails for an unknown reason, or with any
  710. error specified as a key in L{commandType}'s C{errors} dictionary.
  711. """
  712. # XXX this takes command subclasses and not command objects on purpose.
  713. # There's really no reason to have all this back-and-forth between
  714. # command objects and the protocol, and the extra object being created
  715. # (the Command instance) is pointless. Command is kind of like
  716. # Interface, and should be more like it.
  717. # In other words, the fact that commandType is instantiated here is an
  718. # implementation detail. Don't rely on it.
  719. try:
  720. co = commandType(*a, **kw)
  721. except:
  722. return fail()
  723. return co._doCommand(self)
  724. def unhandledError(self, failure):
  725. """
  726. This is a terminal callback called after application code has had a
  727. chance to quash any errors.
  728. """
  729. return self.boxSender.unhandledError(failure)
  730. def _answerReceived(self, box):
  731. """
  732. An AMP box was received that answered a command previously sent with
  733. L{callRemote}.
  734. @param box: an AmpBox with a value for its L{ANSWER} key.
  735. """
  736. question = self._outstandingRequests.pop(box[ANSWER])
  737. question.addErrback(self.unhandledError)
  738. question.callback(box)
  739. def _errorReceived(self, box):
  740. """
  741. An AMP box was received that answered a command previously sent with
  742. L{callRemote}, with an error.
  743. @param box: an L{AmpBox} with a value for its L{ERROR}, L{ERROR_CODE},
  744. and L{ERROR_DESCRIPTION} keys.
  745. """
  746. question = self._outstandingRequests.pop(box[ERROR])
  747. question.addErrback(self.unhandledError)
  748. errorCode = box[ERROR_CODE]
  749. description = box[ERROR_DESCRIPTION]
  750. if isinstance(description, bytes):
  751. description = description.decode("utf-8", "replace")
  752. if errorCode in PROTOCOL_ERRORS:
  753. exc = PROTOCOL_ERRORS[errorCode](errorCode, description)
  754. else:
  755. exc = RemoteAmpError(errorCode, description)
  756. question.errback(Failure(exc))
  757. def _commandReceived(self, box):
  758. """
  759. @param box: an L{AmpBox} with a value for its L{COMMAND} and L{ASK}
  760. keys.
  761. """
  762. def formatAnswer(answerBox):
  763. answerBox[ANSWER] = box[ASK]
  764. return answerBox
  765. def formatError(error):
  766. if error.check(RemoteAmpError):
  767. code = error.value.errorCode
  768. desc = error.value.description
  769. if isinstance(desc, unicode):
  770. desc = desc.encode("utf-8", "replace")
  771. if error.value.fatal:
  772. errorBox = QuitBox()
  773. else:
  774. errorBox = AmpBox()
  775. else:
  776. errorBox = QuitBox()
  777. log.err(error) # here is where server-side logging happens
  778. # if the error isn't handled
  779. code = UNKNOWN_ERROR_CODE
  780. desc = b"Unknown Error"
  781. errorBox[ERROR] = box[ASK]
  782. errorBox[ERROR_DESCRIPTION] = desc
  783. errorBox[ERROR_CODE] = code
  784. return errorBox
  785. deferred = self.dispatchCommand(box)
  786. if ASK in box:
  787. deferred.addCallbacks(formatAnswer, formatError)
  788. deferred.addCallback(self._safeEmit)
  789. deferred.addErrback(self.unhandledError)
  790. def ampBoxReceived(self, box):
  791. """
  792. An AmpBox was received, representing a command, or an answer to a
  793. previously issued command (either successful or erroneous). Respond to
  794. it according to its contents.
  795. @param box: an AmpBox
  796. @raise NoEmptyBoxes: when a box is received that does not contain an
  797. '_answer', '_command' / '_ask', or '_error' key; i.e. one which does not
  798. fit into the command / response protocol defined by AMP.
  799. """
  800. if ANSWER in box:
  801. self._answerReceived(box)
  802. elif ERROR in box:
  803. self._errorReceived(box)
  804. elif COMMAND in box:
  805. self._commandReceived(box)
  806. else:
  807. raise NoEmptyBoxes(box)
  808. def _safeEmit(self, aBox):
  809. """
  810. Emit a box, ignoring L{ProtocolSwitched} and L{ConnectionLost} errors
  811. which cannot be usefully handled.
  812. """
  813. try:
  814. aBox._sendTo(self.boxSender)
  815. except (ProtocolSwitched, ConnectionLost):
  816. pass
  817. def dispatchCommand(self, box):
  818. """
  819. A box with a _command key was received.
  820. Dispatch it to a local handler call it.
  821. @param proto: an AMP instance.
  822. @param box: an AmpBox to be dispatched.
  823. """
  824. cmd = box[COMMAND]
  825. responder = self.locator.locateResponder(cmd)
  826. if responder is None:
  827. description = "Unhandled Command: %r" % (cmd,)
  828. return fail(RemoteAmpError(
  829. UNHANDLED_ERROR_CODE,
  830. description,
  831. False,
  832. local=Failure(UnhandledCommand())))
  833. return maybeDeferred(responder, box)
  834. @implementer(IResponderLocator)
  835. class CommandLocator:
  836. """
  837. A L{CommandLocator} is a collection of responders to AMP L{Command}s, with
  838. the help of the L{Command.responder} decorator.
  839. """
  840. class __metaclass__(type):
  841. """
  842. This metaclass keeps track of all of the Command.responder-decorated
  843. methods defined since the last CommandLocator subclass was defined. It
  844. assumes (usually correctly, but unfortunately not necessarily so) that
  845. those commands responders were all declared as methods of the class
  846. being defined. Note that this list can be incorrect if users use the
  847. Command.responder decorator outside the context of a CommandLocator
  848. class declaration.
  849. Command responders defined on subclasses are given precedence over
  850. those inherited from a base class.
  851. The Command.responder decorator explicitly cooperates with this
  852. metaclass.
  853. """
  854. _currentClassCommands = []
  855. def __new__(cls, name, bases, attrs):
  856. commands = cls._currentClassCommands[:]
  857. cls._currentClassCommands[:] = []
  858. cd = attrs['_commandDispatch'] = {}
  859. subcls = type.__new__(cls, name, bases, attrs)
  860. ancestors = list(subcls.__mro__[1:])
  861. ancestors.reverse()
  862. for ancestor in ancestors:
  863. cd.update(getattr(ancestor, '_commandDispatch', {}))
  864. for commandClass, responderFunc in commands:
  865. cd[commandClass.commandName] = (commandClass, responderFunc)
  866. if (bases and (
  867. subcls.lookupFunction != CommandLocator.lookupFunction)):
  868. def locateResponder(self, name):
  869. warnings.warn(
  870. "Override locateResponder, not lookupFunction.",
  871. category=PendingDeprecationWarning,
  872. stacklevel=2)
  873. return self.lookupFunction(name)
  874. subcls.locateResponder = locateResponder
  875. return subcls
  876. def _wrapWithSerialization(self, aCallable, command):
  877. """
  878. Wrap aCallable with its command's argument de-serialization
  879. and result serialization logic.
  880. @param aCallable: a callable with a 'command' attribute, designed to be
  881. called with keyword arguments.
  882. @param command: the command class whose serialization to use.
  883. @return: a 1-arg callable which, when invoked with an AmpBox, will
  884. deserialize the argument list and invoke appropriate user code for the
  885. callable's command, returning a Deferred which fires with the result or
  886. fails with an error.
  887. """
  888. def doit(box):
  889. kw = command.parseArguments(box, self)
  890. def checkKnownErrors(error):
  891. key = error.trap(*command.allErrors)
  892. code = command.allErrors[key]
  893. desc = str(error.value)
  894. return Failure(RemoteAmpError(
  895. code, desc, key in command.fatalErrors, local=error))
  896. def makeResponseFor(objects):
  897. try:
  898. return command.makeResponse(objects, self)
  899. except:
  900. # let's helpfully log this.
  901. originalFailure = Failure()
  902. raise BadLocalReturn(
  903. "%r returned %r and %r could not serialize it" % (
  904. aCallable,
  905. objects,
  906. command),
  907. originalFailure)
  908. return maybeDeferred(aCallable, **kw).addCallback(
  909. makeResponseFor).addErrback(
  910. checkKnownErrors)
  911. return doit
  912. def lookupFunction(self, name):
  913. """
  914. Deprecated synonym for L{CommandLocator.locateResponder}
  915. """
  916. if self.__class__.lookupFunction != CommandLocator.lookupFunction:
  917. return CommandLocator.locateResponder(self, name)
  918. else:
  919. warnings.warn("Call locateResponder, not lookupFunction.",
  920. category=PendingDeprecationWarning,
  921. stacklevel=2)
  922. return self.locateResponder(name)
  923. def locateResponder(self, name):
  924. """
  925. Locate a callable to invoke when executing the named command.
  926. @param name: the normalized name (from the wire) of the command.
  927. @type name: C{bytes}
  928. @return: a 1-argument function that takes a Box and returns a box or a
  929. Deferred which fires a Box, for handling the command identified by the
  930. given name, or None, if no appropriate responder can be found.
  931. """
  932. # Try to find a high-level method to invoke, and if we can't find one,
  933. # fall back to a low-level one.
  934. cd = self._commandDispatch
  935. if name in cd:
  936. commandClass, responderFunc = cd[name]
  937. if _PY3:
  938. responderMethod = types.MethodType(
  939. responderFunc, self)
  940. else:
  941. responderMethod = types.MethodType(
  942. responderFunc, self, self.__class__)
  943. return self._wrapWithSerialization(responderMethod, commandClass)
  944. if _PY3:
  945. # Python 3 ignores the __metaclass__ attribute and has instead new syntax
  946. # for setting the metaclass. Unfortunately it's not valid Python 2 syntax
  947. # so we work-around it by recreating CommandLocator using the metaclass
  948. # here.
  949. CommandLocator = CommandLocator.__metaclass__(
  950. "CommandLocator", (CommandLocator, ), {})
  951. @implementer(IResponderLocator)
  952. class SimpleStringLocator(object):
  953. """
  954. Implement the L{AMP.locateResponder} method to do simple, string-based
  955. dispatch.
  956. """
  957. baseDispatchPrefix = b'amp_'
  958. def locateResponder(self, name):
  959. """
  960. Locate a callable to invoke when executing the named command.
  961. @return: a function with the name C{"amp_" + name} on the same
  962. instance, or None if no such function exists.
  963. This function will then be called with the L{AmpBox} itself as an
  964. argument.
  965. @param name: the normalized name (from the wire) of the command.
  966. @type name: C{bytes}
  967. """
  968. fName = nativeString(self.baseDispatchPrefix + name.upper())
  969. return getattr(self, fName, None)
  970. PYTHON_KEYWORDS = [
  971. 'and', 'del', 'for', 'is', 'raise', 'assert', 'elif', 'from', 'lambda',
  972. 'return', 'break', 'else', 'global', 'not', 'try', 'class', 'except',
  973. 'if', 'or', 'while', 'continue', 'exec', 'import', 'pass', 'yield',
  974. 'def', 'finally', 'in', 'print']
  975. def _wireNameToPythonIdentifier(key):
  976. """
  977. (Private) Normalize an argument name from the wire for use with Python
  978. code. If the return value is going to be a python keyword it will be
  979. capitalized. If it contains any dashes they will be replaced with
  980. underscores.
  981. The rationale behind this method is that AMP should be an inherently
  982. multi-language protocol, so message keys may contain all manner of bizarre
  983. bytes. This is not a complete solution; there are still forms of arguments
  984. that this implementation will be unable to parse. However, Python
  985. identifiers share a huge raft of properties with identifiers from many
  986. other languages, so this is a 'good enough' effort for now. We deal
  987. explicitly with dashes because that is the most likely departure: Lisps
  988. commonly use dashes to separate method names, so protocols initially
  989. implemented in a lisp amp dialect may use dashes in argument or command
  990. names.
  991. @param key: a C{bytes}, looking something like 'foo-bar-baz' or 'from'
  992. @type key: C{bytes}
  993. @return: a native string which is a valid python identifier, looking
  994. something like 'foo_bar_baz' or 'From'.
  995. """
  996. lkey = nativeString(key.replace(b"-", b"_"))
  997. if lkey in PYTHON_KEYWORDS:
  998. return lkey.title()
  999. return lkey
  1000. @implementer(IArgumentType)
  1001. class Argument:
  1002. """
  1003. Base-class of all objects that take values from Amp packets and convert
  1004. them into objects for Python functions.
  1005. This implementation of L{IArgumentType} provides several higher-level
  1006. hooks for subclasses to override. See L{toString} and L{fromString}
  1007. which will be used to define the behavior of L{IArgumentType.toBox} and
  1008. L{IArgumentType.fromBox}, respectively.
  1009. """
  1010. optional = False
  1011. def __init__(self, optional=False):
  1012. """
  1013. Create an Argument.
  1014. @param optional: a boolean indicating whether this argument can be
  1015. omitted in the protocol.
  1016. """
  1017. self.optional = optional
  1018. def retrieve(self, d, name, proto):
  1019. """
  1020. Retrieve the given key from the given dictionary, removing it if found.
  1021. @param d: a dictionary.
  1022. @param name: a key in I{d}.
  1023. @param proto: an instance of an AMP.
  1024. @raise KeyError: if I am not optional and no value was found.
  1025. @return: d[name].
  1026. """
  1027. if self.optional:
  1028. value = d.get(name)
  1029. if value is not None:
  1030. del d[name]
  1031. else:
  1032. value = d.pop(name)
  1033. return value
  1034. def fromBox(self, name, strings, objects, proto):
  1035. """
  1036. Populate an 'out' dictionary with mapping names to Python values
  1037. decoded from an 'in' AmpBox mapping strings to string values.
  1038. @param name: the argument name to retrieve
  1039. @type name: C{bytes}
  1040. @param strings: The AmpBox to read string(s) from, a mapping of
  1041. argument names to string values.
  1042. @type strings: AmpBox
  1043. @param objects: The dictionary to write object(s) to, a mapping of
  1044. names to Python objects. Keys will be native strings.
  1045. @type objects: dict
  1046. @param proto: an AMP instance.
  1047. """
  1048. st = self.retrieve(strings, name, proto)
  1049. nk = _wireNameToPythonIdentifier(name)
  1050. if self.optional and st is None:
  1051. objects[nk] = None
  1052. else:
  1053. objects[nk] = self.fromStringProto(st, proto)
  1054. def toBox(self, name, strings, objects, proto):
  1055. """
  1056. Populate an 'out' AmpBox with strings encoded from an 'in' dictionary
  1057. mapping names to Python values.
  1058. @param name: the argument name to retrieve
  1059. @type name: C{bytes}
  1060. @param strings: The AmpBox to write string(s) to, a mapping of
  1061. argument names to string values.
  1062. @type strings: AmpBox
  1063. @param objects: The dictionary to read object(s) from, a mapping of
  1064. names to Python objects. Keys should be native strings.
  1065. @type objects: dict
  1066. @param proto: the protocol we are converting for.
  1067. @type proto: AMP
  1068. """
  1069. obj = self.retrieve(objects, _wireNameToPythonIdentifier(name), proto)
  1070. if self.optional and obj is None:
  1071. # strings[name] = None
  1072. pass
  1073. else:
  1074. strings[name] = self.toStringProto(obj, proto)
  1075. def fromStringProto(self, inString, proto):
  1076. """
  1077. Convert a string to a Python value.
  1078. @param inString: the string to convert.
  1079. @type inString: C{bytes}
  1080. @param proto: the protocol we are converting for.
  1081. @type proto: AMP
  1082. @return: a Python object.
  1083. """
  1084. return self.fromString(inString)
  1085. def toStringProto(self, inObject, proto):
  1086. """
  1087. Convert a Python object to a string.
  1088. @param inObject: the object to convert.
  1089. @param proto: the protocol we are converting for.
  1090. @type proto: AMP
  1091. """
  1092. return self.toString(inObject)
  1093. def fromString(self, inString):
  1094. """
  1095. Convert a string to a Python object. Subclasses must implement this.
  1096. @param inString: the string to convert.
  1097. @type inString: C{bytes}
  1098. @return: the decoded value from C{inString}
  1099. """
  1100. def toString(self, inObject):
  1101. """
  1102. Convert a Python object into a string for passing over the network.
  1103. @param inObject: an object of the type that this Argument is intended
  1104. to deal with.
  1105. @return: the wire encoding of inObject
  1106. @rtype: C{bytes}
  1107. """
  1108. class Integer(Argument):
  1109. """
  1110. Encode any integer values of any size on the wire as the string
  1111. representation.
  1112. Example: C{123} becomes C{"123"}
  1113. """
  1114. fromString = int
  1115. def toString(self, inObject):
  1116. return intToBytes(inObject)
  1117. class String(Argument):
  1118. """
  1119. Don't do any conversion at all; just pass through 'str'.
  1120. """
  1121. def toString(self, inObject):
  1122. return inObject
  1123. def fromString(self, inString):
  1124. return inString
  1125. class Float(Argument):
  1126. """
  1127. Encode floating-point values on the wire as their repr.
  1128. """
  1129. fromString = float
  1130. def toString(self, inString):
  1131. if not isinstance(inString, float):
  1132. raise ValueError("Bad float value %r" % (inString,))
  1133. return str(inString).encode('ascii')
  1134. class Boolean(Argument):
  1135. """
  1136. Encode True or False as "True" or "False" on the wire.
  1137. """
  1138. def fromString(self, inString):
  1139. if inString == b'True':
  1140. return True
  1141. elif inString == b'False':
  1142. return False
  1143. else:
  1144. raise TypeError("Bad boolean value: %r" % (inString,))
  1145. def toString(self, inObject):
  1146. if inObject:
  1147. return b'True'
  1148. else:
  1149. return b'False'
  1150. class Unicode(String):
  1151. """
  1152. Encode a unicode string on the wire as UTF-8.
  1153. """
  1154. def toString(self, inObject):
  1155. return String.toString(self, inObject.encode('utf-8'))
  1156. def fromString(self, inString):
  1157. return String.fromString(self, inString).decode('utf-8')
  1158. class Path(Unicode):
  1159. """
  1160. Encode and decode L{filepath.FilePath} instances as paths on the wire.
  1161. This is really intended for use with subprocess communication tools:
  1162. exchanging pathnames on different machines over a network is not generally
  1163. meaningful, but neither is it disallowed; you can use this to communicate
  1164. about NFS paths, for example.
  1165. """
  1166. def fromString(self, inString):
  1167. return filepath.FilePath(Unicode.fromString(self, inString))
  1168. def toString(self, inObject):
  1169. return Unicode.toString(self, inObject.asTextMode().path)
  1170. class ListOf(Argument):
  1171. """
  1172. Encode and decode lists of instances of a single other argument type.
  1173. For example, if you want to pass::
  1174. [3, 7, 9, 15]
  1175. You can create an argument like this::
  1176. ListOf(Integer())
  1177. The serialized form of the entire list is subject to the limit imposed by
  1178. L{MAX_VALUE_LENGTH}. List elements are represented as 16-bit length
  1179. prefixed strings. The argument type passed to the L{ListOf} initializer is
  1180. responsible for producing the serialized form of each element.
  1181. @ivar elementType: The L{Argument} instance used to encode and decode list
  1182. elements (note, not an arbitrary L{IArgumentType} implementation:
  1183. arguments must be implemented using only the C{fromString} and
  1184. C{toString} methods, not the C{fromBox} and C{toBox} methods).
  1185. @param optional: a boolean indicating whether this argument can be
  1186. omitted in the protocol.
  1187. @since: 10.0
  1188. """
  1189. def __init__(self, elementType, optional=False):
  1190. self.elementType = elementType
  1191. Argument.__init__(self, optional)
  1192. def fromString(self, inString):
  1193. """
  1194. Convert the serialized form of a list of instances of some type back
  1195. into that list.
  1196. """
  1197. strings = []
  1198. parser = Int16StringReceiver()
  1199. parser.stringReceived = strings.append
  1200. parser.dataReceived(inString)
  1201. elementFromString = self.elementType.fromString
  1202. return [elementFromString(string) for string in strings]
  1203. def toString(self, inObject):
  1204. """
  1205. Serialize the given list of objects to a single string.
  1206. """
  1207. strings = []
  1208. for obj in inObject:
  1209. serialized = self.elementType.toString(obj)
  1210. strings.append(pack('!H', len(serialized)))
  1211. strings.append(serialized)
  1212. return b''.join(strings)
  1213. class AmpList(Argument):
  1214. """
  1215. Convert a list of dictionaries into a list of AMP boxes on the wire.
  1216. For example, if you want to pass::
  1217. [{'a': 7, 'b': u'hello'}, {'a': 9, 'b': u'goodbye'}]
  1218. You might use an AmpList like this in your arguments or response list::
  1219. AmpList([('a', Integer()),
  1220. ('b', Unicode())])
  1221. """
  1222. def __init__(self, subargs, optional=False):
  1223. """
  1224. Create an AmpList.
  1225. @param subargs: a list of 2-tuples of ('name', argument) describing the
  1226. schema of the dictionaries in the sequence of amp boxes.
  1227. @type subargs: A C{list} of (C{bytes}, L{Argument}) tuples.
  1228. @param optional: a boolean indicating whether this argument can be
  1229. omitted in the protocol.
  1230. """
  1231. assert all(isinstance(name, bytes) for name, _ in subargs), (
  1232. "AmpList should be defined with a list of (name, argument) "
  1233. "tuples where `name' is a byte string, got: %r" % (subargs, ))
  1234. self.subargs = subargs
  1235. Argument.__init__(self, optional)
  1236. def fromStringProto(self, inString, proto):
  1237. boxes = parseString(inString)
  1238. values = [_stringsToObjects(box, self.subargs, proto)
  1239. for box in boxes]
  1240. return values
  1241. def toStringProto(self, inObject, proto):
  1242. return b''.join([_objectsToStrings(
  1243. objects, self.subargs, Box(), proto
  1244. ).serialize() for objects in inObject])
  1245. class Descriptor(Integer):
  1246. """
  1247. Encode and decode file descriptors for exchange over a UNIX domain socket.
  1248. This argument type requires an AMP connection set up over an
  1249. L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>} provider (for
  1250. example, the kind of connection created by
  1251. L{IReactorUNIX.connectUNIX<twisted.internet.interfaces.IReactorUNIX.connectUNIX>}
  1252. and L{UNIXClientEndpoint<twisted.internet.endpoints.UNIXClientEndpoint>}).
  1253. There is no correspondence between the integer value of the file descriptor
  1254. on the sending and receiving sides, therefore an alternate approach is taken
  1255. to matching up received descriptors with particular L{Descriptor}
  1256. parameters. The argument is encoded to an ordinal (unique per connection)
  1257. for inclusion in the AMP command or response box. The descriptor itself is
  1258. sent using
  1259. L{IUNIXTransport.sendFileDescriptor<twisted.internet.interfaces.IUNIXTransport.sendFileDescriptor>}.
  1260. The receiver uses the order in which file descriptors are received and the
  1261. ordinal value to come up with the received copy of the descriptor.
  1262. """
  1263. def fromStringProto(self, inString, proto):
  1264. """
  1265. Take a unique identifier associated with a file descriptor which must
  1266. have been received by now and use it to look up that descriptor in a
  1267. dictionary where they are kept.
  1268. @param inString: The base representation (as a byte string) of an
  1269. ordinal indicating which file descriptor corresponds to this usage
  1270. of this argument.
  1271. @type inString: C{str}
  1272. @param proto: The protocol used to receive this descriptor. This
  1273. protocol must be connected via a transport providing
  1274. L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>}.
  1275. @type proto: L{BinaryBoxProtocol}
  1276. @return: The file descriptor represented by C{inString}.
  1277. @rtype: C{int}
  1278. """
  1279. return proto._getDescriptor(int(inString))
  1280. def toStringProto(self, inObject, proto):
  1281. """
  1282. Send C{inObject}, an integer file descriptor, over C{proto}'s connection
  1283. and return a unique identifier which will allow the receiver to
  1284. associate the file descriptor with this argument.
  1285. @param inObject: A file descriptor to duplicate over an AMP connection
  1286. as the value for this argument.
  1287. @type inObject: C{int}
  1288. @param proto: The protocol which will be used to send this descriptor.
  1289. This protocol must be connected via a transport providing
  1290. L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>}.
  1291. @return: A byte string which can be used by the receiver to reconstruct
  1292. the file descriptor.
  1293. @type: C{str}
  1294. """
  1295. identifier = proto._sendFileDescriptor(inObject)
  1296. outString = Integer.toStringProto(self, identifier, proto)
  1297. return outString
  1298. class Command:
  1299. """
  1300. Subclass me to specify an AMP Command.
  1301. @cvar arguments: A list of 2-tuples of (name, Argument-subclass-instance),
  1302. specifying the names and values of the parameters which are required for
  1303. this command.
  1304. @cvar response: A list like L{arguments}, but instead used for the return
  1305. value.
  1306. @cvar errors: A mapping of subclasses of L{Exception} to wire-protocol tags
  1307. for errors represented as L{str}s. Responders which raise keys from
  1308. this dictionary will have the error translated to the corresponding tag
  1309. on the wire.
  1310. Invokers which receive Deferreds from invoking this command with
  1311. L{BoxDispatcher.callRemote} will potentially receive Failures with keys
  1312. from this mapping as their value.
  1313. This mapping is inherited; if you declare a command which handles
  1314. C{FooError} as 'FOO_ERROR', then subclass it and specify C{BarError} as
  1315. 'BAR_ERROR', responders to the subclass may raise either C{FooError} or
  1316. C{BarError}, and invokers must be able to deal with either of those
  1317. exceptions.
  1318. @cvar fatalErrors: like 'errors', but errors in this list will always
  1319. terminate the connection, despite being of a recognizable error type.
  1320. @cvar commandType: The type of Box used to issue commands; useful only for
  1321. protocol-modifying behavior like startTLS or protocol switching. Defaults
  1322. to a plain vanilla L{Box}.
  1323. @cvar responseType: The type of Box used to respond to this command; only
  1324. useful for protocol-modifying behavior like startTLS or protocol switching.
  1325. Defaults to a plain vanilla L{Box}.
  1326. @ivar requiresAnswer: a boolean; defaults to True. Set it to False on your
  1327. subclass if you want callRemote to return None. Note: this is a hint only
  1328. to the client side of the protocol. The return-type of a command responder
  1329. method must always be a dictionary adhering to the contract specified by
  1330. L{response}, because clients are always free to request a response if they
  1331. want one.
  1332. """
  1333. class __metaclass__(type):
  1334. """
  1335. Metaclass hack to establish reverse-mappings for 'errors' and
  1336. 'fatalErrors' as class vars.
  1337. """
  1338. def __new__(cls, name, bases, attrs):
  1339. reverseErrors = attrs['reverseErrors'] = {}
  1340. er = attrs['allErrors'] = {}
  1341. if 'commandName' not in attrs:
  1342. if _PY3:
  1343. attrs['commandName'] = name.encode("ascii")
  1344. else:
  1345. attrs['commandName'] = name
  1346. newtype = type.__new__(cls, name, bases, attrs)
  1347. if not isinstance(newtype.commandName, bytes):
  1348. raise TypeError(
  1349. "Command names must be byte strings, got: %r"
  1350. % (newtype.commandName, ))
  1351. for name, _ in newtype.arguments:
  1352. if not isinstance(name, bytes):
  1353. raise TypeError(
  1354. "Argument names must be byte strings, got: %r"
  1355. % (name, ))
  1356. for name, _ in newtype.response:
  1357. if not isinstance(name, bytes):
  1358. raise TypeError(
  1359. "Response names must be byte strings, got: %r"
  1360. % (name, ))
  1361. errors = {}
  1362. fatalErrors = {}
  1363. accumulateClassDict(newtype, 'errors', errors)
  1364. accumulateClassDict(newtype, 'fatalErrors', fatalErrors)
  1365. if not isinstance(newtype.errors, dict):
  1366. newtype.errors = dict(newtype.errors)
  1367. if not isinstance(newtype.fatalErrors, dict):
  1368. newtype.fatalErrors = dict(newtype.fatalErrors)
  1369. for v, k in iteritems(errors):
  1370. reverseErrors[k] = v
  1371. er[v] = k
  1372. for v, k in iteritems(fatalErrors):
  1373. reverseErrors[k] = v
  1374. er[v] = k
  1375. for _, name in iteritems(newtype.errors):
  1376. if not isinstance(name, bytes):
  1377. raise TypeError(
  1378. "Error names must be byte strings, got: %r"
  1379. % (name, ))
  1380. for _, name in iteritems(newtype.fatalErrors):
  1381. if not isinstance(name, bytes):
  1382. raise TypeError(
  1383. "Fatal error names must be byte strings, got: %r"
  1384. % (name, ))
  1385. return newtype
  1386. arguments = []
  1387. response = []
  1388. extra = []
  1389. errors = {}
  1390. fatalErrors = {}
  1391. commandType = Box
  1392. responseType = Box
  1393. requiresAnswer = True
  1394. def __init__(self, **kw):
  1395. """
  1396. Create an instance of this command with specified values for its
  1397. parameters.
  1398. In Python 3, keyword arguments MUST be Unicode/native strings whereas
  1399. in Python 2 they could be either byte strings or Unicode strings.
  1400. A L{Command}'s arguments are defined in its schema using C{bytes}
  1401. names. The values for those arguments are plucked from the keyword
  1402. arguments using the name returned from L{_wireNameToPythonIdentifier}.
  1403. In other words, keyword arguments should be named using the
  1404. Python-side equivalent of the on-wire (C{bytes}) name.
  1405. @param kw: a dict containing an appropriate value for each name
  1406. specified in the L{arguments} attribute of my class.
  1407. @raise InvalidSignature: if you forgot any required arguments.
  1408. """
  1409. self.structured = kw
  1410. forgotten = []
  1411. for name, arg in self.arguments:
  1412. pythonName = _wireNameToPythonIdentifier(name)
  1413. if pythonName not in self.structured and not arg.optional:
  1414. forgotten.append(pythonName)
  1415. if forgotten:
  1416. raise InvalidSignature("forgot %s for %s" % (
  1417. ', '.join(forgotten), self.commandName))
  1418. forgotten = []
  1419. def makeResponse(cls, objects, proto):
  1420. """
  1421. Serialize a mapping of arguments using this L{Command}'s
  1422. response schema.
  1423. @param objects: a dict with keys matching the names specified in
  1424. self.response, having values of the types that the Argument objects in
  1425. self.response can format.
  1426. @param proto: an L{AMP}.
  1427. @return: an L{AmpBox}.
  1428. """
  1429. try:
  1430. responseType = cls.responseType()
  1431. except:
  1432. return fail()
  1433. return _objectsToStrings(objects, cls.response, responseType, proto)
  1434. makeResponse = classmethod(makeResponse)
  1435. def makeArguments(cls, objects, proto):
  1436. """
  1437. Serialize a mapping of arguments using this L{Command}'s
  1438. argument schema.
  1439. @param objects: a dict with keys similar to the names specified in
  1440. self.arguments, having values of the types that the Argument objects in
  1441. self.arguments can parse.
  1442. @param proto: an L{AMP}.
  1443. @return: An instance of this L{Command}'s C{commandType}.
  1444. """
  1445. allowedNames = set()
  1446. for (argName, ignored) in cls.arguments:
  1447. allowedNames.add(_wireNameToPythonIdentifier(argName))
  1448. for intendedArg in objects:
  1449. if intendedArg not in allowedNames:
  1450. raise InvalidSignature(
  1451. "%s is not a valid argument" % (intendedArg,))
  1452. return _objectsToStrings(objects, cls.arguments, cls.commandType(),
  1453. proto)
  1454. makeArguments = classmethod(makeArguments)
  1455. def parseResponse(cls, box, protocol):
  1456. """
  1457. Parse a mapping of serialized arguments using this
  1458. L{Command}'s response schema.
  1459. @param box: A mapping of response-argument names to the
  1460. serialized forms of those arguments.
  1461. @param protocol: The L{AMP} protocol.
  1462. @return: A mapping of response-argument names to the parsed
  1463. forms.
  1464. """
  1465. return _stringsToObjects(box, cls.response, protocol)
  1466. parseResponse = classmethod(parseResponse)
  1467. def parseArguments(cls, box, protocol):
  1468. """
  1469. Parse a mapping of serialized arguments using this
  1470. L{Command}'s argument schema.
  1471. @param box: A mapping of argument names to the seralized forms
  1472. of those arguments.
  1473. @param protocol: The L{AMP} protocol.
  1474. @return: A mapping of argument names to the parsed forms.
  1475. """
  1476. return _stringsToObjects(box, cls.arguments, protocol)
  1477. parseArguments = classmethod(parseArguments)
  1478. def responder(cls, methodfunc):
  1479. """
  1480. Declare a method to be a responder for a particular command.
  1481. This is a decorator.
  1482. Use like so::
  1483. class MyCommand(Command):
  1484. arguments = [('a', ...), ('b', ...)]
  1485. class MyProto(AMP):
  1486. def myFunMethod(self, a, b):
  1487. ...
  1488. MyCommand.responder(myFunMethod)
  1489. Notes: Although decorator syntax is not used within Twisted, this
  1490. function returns its argument and is therefore safe to use with
  1491. decorator syntax.
  1492. This is not thread safe. Don't declare AMP subclasses in other
  1493. threads. Don't declare responders outside the scope of AMP subclasses;
  1494. the behavior is undefined.
  1495. @param methodfunc: A function which will later become a method, which
  1496. has a keyword signature compatible with this command's L{argument} list
  1497. and returns a dictionary with a set of keys compatible with this
  1498. command's L{response} list.
  1499. @return: the methodfunc parameter.
  1500. """
  1501. CommandLocator._currentClassCommands.append((cls, methodfunc))
  1502. return methodfunc
  1503. responder = classmethod(responder)
  1504. # Our only instance method
  1505. def _doCommand(self, proto):
  1506. """
  1507. Encode and send this Command to the given protocol.
  1508. @param proto: an AMP, representing the connection to send to.
  1509. @return: a Deferred which will fire or error appropriately when the
  1510. other side responds to the command (or error if the connection is lost
  1511. before it is responded to).
  1512. """
  1513. def _massageError(error):
  1514. error.trap(RemoteAmpError)
  1515. rje = error.value
  1516. errorType = self.reverseErrors.get(rje.errorCode,
  1517. UnknownRemoteError)
  1518. return Failure(errorType(rje.description))
  1519. d = proto._sendBoxCommand(self.commandName,
  1520. self.makeArguments(self.structured, proto),
  1521. self.requiresAnswer)
  1522. if self.requiresAnswer:
  1523. d.addCallback(self.parseResponse, proto)
  1524. d.addErrback(_massageError)
  1525. return d
  1526. if _PY3:
  1527. # Python 3 ignores the __metaclass__ attribute and has instead new syntax
  1528. # for setting the metaclass. Unfortunately it's not valid Python 2 syntax
  1529. # so we work-around it by recreating Command using the metaclass here.
  1530. Command = Command.__metaclass__("Command", (Command, ), {})
  1531. class _NoCertificate:
  1532. """
  1533. This is for peers which don't want to use a local certificate. Used by
  1534. AMP because AMP's internal language is all about certificates and this
  1535. duck-types in the appropriate place; this API isn't really stable though,
  1536. so it's not exposed anywhere public.
  1537. For clients, it will use ephemeral DH keys, or whatever the default is for
  1538. certificate-less clients in OpenSSL. For servers, it will generate a
  1539. temporary self-signed certificate with garbage values in the DN and use
  1540. that.
  1541. """
  1542. def __init__(self, client):
  1543. """
  1544. Create a _NoCertificate which either is or isn't for the client side of
  1545. the connection.
  1546. @param client: True if we are a client and should truly have no
  1547. certificate and be anonymous, False if we are a server and actually
  1548. have to generate a temporary certificate.
  1549. @type client: bool
  1550. """
  1551. self.client = client
  1552. def options(self, *authorities):
  1553. """
  1554. Behaves like L{twisted.internet.ssl.PrivateCertificate.options}().
  1555. """
  1556. if not self.client:
  1557. # do some crud with sslverify to generate a temporary self-signed
  1558. # certificate. This is SLOOOWWWWW so it is only in the absolute
  1559. # worst, most naive case.
  1560. # We have to do this because OpenSSL will not let both the server
  1561. # and client be anonymous.
  1562. sharedDN = DN(CN='TEMPORARY CERTIFICATE')
  1563. key = KeyPair.generate()
  1564. cr = key.certificateRequest(sharedDN)
  1565. sscrd = key.signCertificateRequest(sharedDN, cr, lambda dn: True, 1)
  1566. cert = key.newCertificate(sscrd)
  1567. return cert.options(*authorities)
  1568. options = dict()
  1569. if authorities:
  1570. options.update(dict(verify=True,
  1571. requireCertificate=True,
  1572. caCerts=[auth.original for auth in authorities]))
  1573. occo = CertificateOptions(**options)
  1574. return occo
  1575. class _TLSBox(AmpBox):
  1576. """
  1577. I am an AmpBox that, upon being sent, initiates a TLS connection.
  1578. """
  1579. __slots__ = []
  1580. def __init__(self):
  1581. if ssl is None:
  1582. raise RemoteAmpError(b"TLS_ERROR", "TLS not available")
  1583. AmpBox.__init__(self)
  1584. def _keyprop(k, default):
  1585. return property(lambda self: self.get(k, default))
  1586. # These properties are described in startTLS
  1587. certificate = _keyprop(b'tls_localCertificate', _NoCertificate(False))
  1588. verify = _keyprop(b'tls_verifyAuthorities', None)
  1589. def _sendTo(self, proto):
  1590. """
  1591. Send my encoded value to the protocol, then initiate TLS.
  1592. """
  1593. ab = AmpBox(self)
  1594. for k in [b'tls_localCertificate',
  1595. b'tls_verifyAuthorities']:
  1596. ab.pop(k, None)
  1597. ab._sendTo(proto)
  1598. proto._startTLS(self.certificate, self.verify)
  1599. class _LocalArgument(String):
  1600. """
  1601. Local arguments are never actually relayed across the wire. This is just a
  1602. shim so that StartTLS can pretend to have some arguments: if arguments
  1603. acquire documentation properties, replace this with something nicer later.
  1604. """
  1605. def fromBox(self, name, strings, objects, proto):
  1606. pass
  1607. class StartTLS(Command):
  1608. """
  1609. Use, or subclass, me to implement a command that starts TLS.
  1610. Callers of StartTLS may pass several special arguments, which affect the
  1611. TLS negotiation:
  1612. - tls_localCertificate: This is a
  1613. twisted.internet.ssl.PrivateCertificate which will be used to secure
  1614. the side of the connection it is returned on.
  1615. - tls_verifyAuthorities: This is a list of
  1616. twisted.internet.ssl.Certificate objects that will be used as the
  1617. certificate authorities to verify our peer's certificate.
  1618. Each of those special parameters may also be present as a key in the
  1619. response dictionary.
  1620. """
  1621. arguments = [(b"tls_localCertificate", _LocalArgument(optional=True)),
  1622. (b"tls_verifyAuthorities", _LocalArgument(optional=True))]
  1623. response = [(b"tls_localCertificate", _LocalArgument(optional=True)),
  1624. (b"tls_verifyAuthorities", _LocalArgument(optional=True))]
  1625. responseType = _TLSBox
  1626. def __init__(self, **kw):
  1627. """
  1628. Create a StartTLS command. (This is private. Use AMP.callRemote.)
  1629. @param tls_localCertificate: the PrivateCertificate object to use to
  1630. secure the connection. If it's None, or unspecified, an ephemeral DH
  1631. key is used instead.
  1632. @param tls_verifyAuthorities: a list of Certificate objects which
  1633. represent root certificates to verify our peer with.
  1634. """
  1635. if ssl is None:
  1636. raise RuntimeError("TLS not available.")
  1637. self.certificate = kw.pop('tls_localCertificate', _NoCertificate(True))
  1638. self.authorities = kw.pop('tls_verifyAuthorities', None)
  1639. Command.__init__(self, **kw)
  1640. def _doCommand(self, proto):
  1641. """
  1642. When a StartTLS command is sent, prepare to start TLS, but don't actually
  1643. do it; wait for the acknowledgement, then initiate the TLS handshake.
  1644. """
  1645. d = Command._doCommand(self, proto)
  1646. proto._prepareTLS(self.certificate, self.authorities)
  1647. # XXX before we get back to user code we are going to start TLS...
  1648. def actuallystart(response):
  1649. proto._startTLS(self.certificate, self.authorities)
  1650. return response
  1651. d.addCallback(actuallystart)
  1652. return d
  1653. class ProtocolSwitchCommand(Command):
  1654. """
  1655. Use this command to switch from something Amp-derived to a different
  1656. protocol mid-connection. This can be useful to use amp as the
  1657. connection-startup negotiation phase. Since TLS is a different layer
  1658. entirely, you can use Amp to negotiate the security parameters of your
  1659. connection, then switch to a different protocol, and the connection will
  1660. remain secured.
  1661. """
  1662. def __init__(self, _protoToSwitchToFactory, **kw):
  1663. """
  1664. Create a ProtocolSwitchCommand.
  1665. @param _protoToSwitchToFactory: a ProtocolFactory which will generate
  1666. the Protocol to switch to.
  1667. @param kw: Keyword arguments, encoded and handled normally as
  1668. L{Command} would.
  1669. """
  1670. self.protoToSwitchToFactory = _protoToSwitchToFactory
  1671. super(ProtocolSwitchCommand, self).__init__(**kw)
  1672. def makeResponse(cls, innerProto, proto):
  1673. return _SwitchBox(innerProto)
  1674. makeResponse = classmethod(makeResponse)
  1675. def _doCommand(self, proto):
  1676. """
  1677. When we emit a ProtocolSwitchCommand, lock the protocol, but don't actually
  1678. switch to the new protocol unless an acknowledgement is received. If
  1679. an error is received, switch back.
  1680. """
  1681. d = super(ProtocolSwitchCommand, self)._doCommand(proto)
  1682. proto._lockForSwitch()
  1683. def switchNow(ign):
  1684. innerProto = self.protoToSwitchToFactory.buildProtocol(
  1685. proto.transport.getPeer())
  1686. proto._switchTo(innerProto, self.protoToSwitchToFactory)
  1687. return ign
  1688. def handle(ign):
  1689. proto._unlockFromSwitch()
  1690. self.protoToSwitchToFactory.clientConnectionFailed(
  1691. None, Failure(CONNECTION_LOST))
  1692. return ign
  1693. return d.addCallbacks(switchNow, handle)
  1694. @implementer(IFileDescriptorReceiver)
  1695. class _DescriptorExchanger(object):
  1696. """
  1697. L{_DescriptorExchanger} is a mixin for L{BinaryBoxProtocol} which adds
  1698. support for receiving file descriptors, a feature offered by
  1699. L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>}.
  1700. @ivar _descriptors: Temporary storage for all file descriptors received.
  1701. Values in this dictionary are the file descriptors (as integers). Keys
  1702. in this dictionary are ordinals giving the order in which each
  1703. descriptor was received. The ordering information is used to allow
  1704. L{Descriptor} to determine which is the correct descriptor for any
  1705. particular usage of that argument type.
  1706. @type _descriptors: C{dict}
  1707. @ivar _sendingDescriptorCounter: A no-argument callable which returns the
  1708. ordinals, starting from 0. This is used to construct values for
  1709. C{_sendFileDescriptor}.
  1710. @ivar _receivingDescriptorCounter: A no-argument callable which returns the
  1711. ordinals, starting from 0. This is used to construct values for
  1712. C{fileDescriptorReceived}.
  1713. """
  1714. def __init__(self):
  1715. self._descriptors = {}
  1716. self._getDescriptor = self._descriptors.pop
  1717. self._sendingDescriptorCounter = partial(next, count())
  1718. self._receivingDescriptorCounter = partial(next, count())
  1719. def _sendFileDescriptor(self, descriptor):
  1720. """
  1721. Assign and return the next ordinal to the given descriptor after sending
  1722. the descriptor over this protocol's transport.
  1723. """
  1724. self.transport.sendFileDescriptor(descriptor)
  1725. return self._sendingDescriptorCounter()
  1726. def fileDescriptorReceived(self, descriptor):
  1727. """
  1728. Collect received file descriptors to be claimed later by L{Descriptor}.
  1729. @param descriptor: The received file descriptor.
  1730. @type descriptor: C{int}
  1731. """
  1732. self._descriptors[self._receivingDescriptorCounter()] = descriptor
  1733. @implementer(IBoxSender)
  1734. class BinaryBoxProtocol(StatefulStringProtocol, Int16StringReceiver,
  1735. _DescriptorExchanger):
  1736. """
  1737. A protocol for receiving L{AmpBox}es - key/value pairs - via length-prefixed
  1738. strings. A box is composed of:
  1739. - any number of key-value pairs, described by:
  1740. - a 2-byte network-endian packed key length (of which the first
  1741. byte must be null, and the second must be non-null: i.e. the
  1742. value of the length must be 1-255)
  1743. - a key, comprised of that many bytes
  1744. - a 2-byte network-endian unsigned value length (up to the maximum
  1745. of 65535)
  1746. - a value, comprised of that many bytes
  1747. - 2 null bytes
  1748. In other words, an even number of strings prefixed with packed unsigned
  1749. 16-bit integers, and then a 0-length string to indicate the end of the box.
  1750. This protocol also implements 2 extra private bits of functionality related
  1751. to the byte boundaries between messages; it can start TLS between two given
  1752. boxes or switch to an entirely different protocol. However, due to some
  1753. tricky elements of the implementation, the public interface to this
  1754. functionality is L{ProtocolSwitchCommand} and L{StartTLS}.
  1755. @ivar _keyLengthLimitExceeded: A flag which is only true when the
  1756. connection is being closed because a key length prefix which was longer
  1757. than allowed by the protocol was received.
  1758. @ivar boxReceiver: an L{IBoxReceiver} provider, whose
  1759. L{IBoxReceiver.ampBoxReceived} method will be invoked for each
  1760. L{AmpBox} that is received.
  1761. """
  1762. _justStartedTLS = False
  1763. _startingTLSBuffer = None
  1764. _locked = False
  1765. _currentKey = None
  1766. _currentBox = None
  1767. _keyLengthLimitExceeded = False
  1768. hostCertificate = None
  1769. noPeerCertificate = False # for tests
  1770. innerProtocol = None
  1771. innerProtocolClientFactory = None
  1772. def __init__(self, boxReceiver):
  1773. _DescriptorExchanger.__init__(self)
  1774. self.boxReceiver = boxReceiver
  1775. def _switchTo(self, newProto, clientFactory=None):
  1776. """
  1777. Switch this BinaryBoxProtocol's transport to a new protocol. You need
  1778. to do this 'simultaneously' on both ends of a connection; the easiest
  1779. way to do this is to use a subclass of ProtocolSwitchCommand.
  1780. @param newProto: the new protocol instance to switch to.
  1781. @param clientFactory: the ClientFactory to send the
  1782. L{twisted.internet.protocol.ClientFactory.clientConnectionLost}
  1783. notification to.
  1784. """
  1785. # All the data that Int16Receiver has not yet dealt with belongs to our
  1786. # new protocol: luckily it's keeping that in a handy (although
  1787. # ostensibly internal) variable for us:
  1788. newProtoData = self.recvd
  1789. # We're quite possibly in the middle of a 'dataReceived' loop in
  1790. # Int16StringReceiver: let's make sure that the next iteration, the
  1791. # loop will break and not attempt to look at something that isn't a
  1792. # length prefix.
  1793. self.recvd = ''
  1794. # Finally, do the actual work of setting up the protocol and delivering
  1795. # its first chunk of data, if one is available.
  1796. self.innerProtocol = newProto
  1797. self.innerProtocolClientFactory = clientFactory
  1798. newProto.makeConnection(self.transport)
  1799. if newProtoData:
  1800. newProto.dataReceived(newProtoData)
  1801. def sendBox(self, box):
  1802. """
  1803. Send a amp.Box to my peer.
  1804. Note: transport.write is never called outside of this method.
  1805. @param box: an AmpBox.
  1806. @raise ProtocolSwitched: if the protocol has previously been switched.
  1807. @raise ConnectionLost: if the connection has previously been lost.
  1808. """
  1809. if self._locked:
  1810. raise ProtocolSwitched(
  1811. "This connection has switched: no AMP traffic allowed.")
  1812. if self.transport is None:
  1813. raise ConnectionLost()
  1814. if self._startingTLSBuffer is not None:
  1815. self._startingTLSBuffer.append(box)
  1816. else:
  1817. self.transport.write(box.serialize())
  1818. def makeConnection(self, transport):
  1819. """
  1820. Notify L{boxReceiver} that it is about to receive boxes from this
  1821. protocol by invoking L{IBoxReceiver.startReceivingBoxes}.
  1822. """
  1823. self.transport = transport
  1824. self.boxReceiver.startReceivingBoxes(self)
  1825. self.connectionMade()
  1826. def dataReceived(self, data):
  1827. """
  1828. Either parse incoming data as L{AmpBox}es or relay it to our nested
  1829. protocol.
  1830. """
  1831. if self._justStartedTLS:
  1832. self._justStartedTLS = False
  1833. # If we already have an inner protocol, then we don't deliver data to
  1834. # the protocol parser any more; we just hand it off.
  1835. if self.innerProtocol is not None:
  1836. self.innerProtocol.dataReceived(data)
  1837. return
  1838. return Int16StringReceiver.dataReceived(self, data)
  1839. def connectionLost(self, reason):
  1840. """
  1841. The connection was lost; notify any nested protocol.
  1842. """
  1843. if self.innerProtocol is not None:
  1844. self.innerProtocol.connectionLost(reason)
  1845. if self.innerProtocolClientFactory is not None:
  1846. self.innerProtocolClientFactory.clientConnectionLost(None, reason)
  1847. if self._keyLengthLimitExceeded:
  1848. failReason = Failure(TooLong(True, False, None, None))
  1849. elif reason.check(ConnectionClosed) and self._justStartedTLS:
  1850. # We just started TLS and haven't received any data. This means
  1851. # the other connection didn't like our cert (although they may not
  1852. # have told us why - later Twisted should make 'reason' into a TLS
  1853. # error.)
  1854. failReason = PeerVerifyError(
  1855. "Peer rejected our certificate for an unknown reason.")
  1856. else:
  1857. failReason = reason
  1858. self.boxReceiver.stopReceivingBoxes(failReason)
  1859. # The longest key allowed
  1860. _MAX_KEY_LENGTH = 255
  1861. # The longest value allowed (this is somewhat redundant, as longer values
  1862. # cannot be encoded - ah well).
  1863. _MAX_VALUE_LENGTH = 65535
  1864. # The first thing received is a key.
  1865. MAX_LENGTH = _MAX_KEY_LENGTH
  1866. def proto_init(self, string):
  1867. """
  1868. String received in the 'init' state.
  1869. """
  1870. self._currentBox = AmpBox()
  1871. return self.proto_key(string)
  1872. def proto_key(self, string):
  1873. """
  1874. String received in the 'key' state. If the key is empty, a complete
  1875. box has been received.
  1876. """
  1877. if string:
  1878. self._currentKey = string
  1879. self.MAX_LENGTH = self._MAX_VALUE_LENGTH
  1880. return 'value'
  1881. else:
  1882. self.boxReceiver.ampBoxReceived(self._currentBox)
  1883. self._currentBox = None
  1884. return 'init'
  1885. def proto_value(self, string):
  1886. """
  1887. String received in the 'value' state.
  1888. """
  1889. self._currentBox[self._currentKey] = string
  1890. self._currentKey = None
  1891. self.MAX_LENGTH = self._MAX_KEY_LENGTH
  1892. return 'key'
  1893. def lengthLimitExceeded(self, length):
  1894. """
  1895. The key length limit was exceeded. Disconnect the transport and make
  1896. sure a meaningful exception is reported.
  1897. """
  1898. self._keyLengthLimitExceeded = True
  1899. self.transport.loseConnection()
  1900. def _lockForSwitch(self):
  1901. """
  1902. Lock this binary protocol so that no further boxes may be sent. This
  1903. is used when sending a request to switch underlying protocols. You
  1904. probably want to subclass ProtocolSwitchCommand rather than calling
  1905. this directly.
  1906. """
  1907. self._locked = True
  1908. def _unlockFromSwitch(self):
  1909. """
  1910. Unlock this locked binary protocol so that further boxes may be sent
  1911. again. This is used after an attempt to switch protocols has failed
  1912. for some reason.
  1913. """
  1914. if self.innerProtocol is not None:
  1915. raise ProtocolSwitched("Protocol already switched. Cannot unlock.")
  1916. self._locked = False
  1917. def _prepareTLS(self, certificate, verifyAuthorities):
  1918. """
  1919. Used by StartTLSCommand to put us into the state where we don't
  1920. actually send things that get sent, instead we buffer them. see
  1921. L{_sendBoxCommand}.
  1922. """
  1923. self._startingTLSBuffer = []
  1924. if self.hostCertificate is not None:
  1925. raise OnlyOneTLS(
  1926. "Previously authenticated connection between %s and %s "
  1927. "is trying to re-establish as %s" % (
  1928. self.hostCertificate,
  1929. self.peerCertificate,
  1930. (certificate, verifyAuthorities)))
  1931. def _startTLS(self, certificate, verifyAuthorities):
  1932. """
  1933. Used by TLSBox to initiate the SSL handshake.
  1934. @param certificate: a L{twisted.internet.ssl.PrivateCertificate} for
  1935. use locally.
  1936. @param verifyAuthorities: L{twisted.internet.ssl.Certificate} instances
  1937. representing certificate authorities which will verify our peer.
  1938. """
  1939. self.hostCertificate = certificate
  1940. self._justStartedTLS = True
  1941. if verifyAuthorities is None:
  1942. verifyAuthorities = ()
  1943. self.transport.startTLS(certificate.options(*verifyAuthorities))
  1944. stlsb = self._startingTLSBuffer
  1945. if stlsb is not None:
  1946. self._startingTLSBuffer = None
  1947. for box in stlsb:
  1948. self.sendBox(box)
  1949. def _getPeerCertificate(self):
  1950. if self.noPeerCertificate:
  1951. return None
  1952. return Certificate.peerFromTransport(self.transport)
  1953. peerCertificate = property(_getPeerCertificate)
  1954. def unhandledError(self, failure):
  1955. """
  1956. The buck stops here. This error was completely unhandled, time to
  1957. terminate the connection.
  1958. """
  1959. log.err(
  1960. failure,
  1961. "Amp server or network failure unhandled by client application. "
  1962. "Dropping connection! To avoid, add errbacks to ALL remote "
  1963. "commands!")
  1964. if self.transport is not None:
  1965. self.transport.loseConnection()
  1966. def _defaultStartTLSResponder(self):
  1967. """
  1968. The default TLS responder doesn't specify any certificate or anything.
  1969. From a security perspective, it's little better than a plain-text
  1970. connection - but it is still a *bit* better, so it's included for
  1971. convenience.
  1972. You probably want to override this by providing your own StartTLS.responder.
  1973. """
  1974. return {}
  1975. StartTLS.responder(_defaultStartTLSResponder)
  1976. class AMP(BinaryBoxProtocol, BoxDispatcher,
  1977. CommandLocator, SimpleStringLocator):
  1978. """
  1979. This protocol is an AMP connection. See the module docstring for protocol
  1980. details.
  1981. """
  1982. _ampInitialized = False
  1983. def __init__(self, boxReceiver=None, locator=None):
  1984. # For backwards compatibility. When AMP did not separate parsing logic
  1985. # (L{BinaryBoxProtocol}), request-response logic (L{BoxDispatcher}) and
  1986. # command routing (L{CommandLocator}), it did not have a constructor.
  1987. # Now it does, so old subclasses might have defined their own that did
  1988. # not upcall. If this flag isn't set, we'll call the constructor in
  1989. # makeConnection before anything actually happens.
  1990. self._ampInitialized = True
  1991. if boxReceiver is None:
  1992. boxReceiver = self
  1993. if locator is None:
  1994. locator = self
  1995. BoxDispatcher.__init__(self, locator)
  1996. BinaryBoxProtocol.__init__(self, boxReceiver)
  1997. def locateResponder(self, name):
  1998. """
  1999. Unify the implementations of L{CommandLocator} and
  2000. L{SimpleStringLocator} to perform both kinds of dispatch, preferring
  2001. L{CommandLocator}.
  2002. @type name: C{bytes}
  2003. """
  2004. firstResponder = CommandLocator.locateResponder(self, name)
  2005. if firstResponder is not None:
  2006. return firstResponder
  2007. secondResponder = SimpleStringLocator.locateResponder(self, name)
  2008. return secondResponder
  2009. def __repr__(self):
  2010. """
  2011. A verbose string representation which gives us information about this
  2012. AMP connection.
  2013. """
  2014. if self.innerProtocol is not None:
  2015. innerRepr = ' inner %r' % (self.innerProtocol,)
  2016. else:
  2017. innerRepr = ''
  2018. return '<%s%s at 0x%x>' % (
  2019. self.__class__.__name__, innerRepr, id(self))
  2020. def makeConnection(self, transport):
  2021. """
  2022. Emit a helpful log message when the connection is made.
  2023. """
  2024. if not self._ampInitialized:
  2025. # See comment in the constructor re: backward compatibility. I
  2026. # should probably emit a deprecation warning here.
  2027. AMP.__init__(self)
  2028. # Save these so we can emit a similar log message in L{connectionLost}.
  2029. self._transportPeer = transport.getPeer()
  2030. self._transportHost = transport.getHost()
  2031. log.msg("%s connection established (HOST:%s PEER:%s)" % (
  2032. self.__class__.__name__,
  2033. self._transportHost,
  2034. self._transportPeer))
  2035. BinaryBoxProtocol.makeConnection(self, transport)
  2036. def connectionLost(self, reason):
  2037. """
  2038. Emit a helpful log message when the connection is lost.
  2039. """
  2040. log.msg("%s connection lost (HOST:%s PEER:%s)" %
  2041. (self.__class__.__name__,
  2042. self._transportHost,
  2043. self._transportPeer))
  2044. BinaryBoxProtocol.connectionLost(self, reason)
  2045. self.transport = None
  2046. class _ParserHelper:
  2047. """
  2048. A box receiver which records all boxes received.
  2049. """
  2050. def __init__(self):
  2051. self.boxes = []
  2052. def getPeer(self):
  2053. return 'string'
  2054. def getHost(self):
  2055. return 'string'
  2056. disconnecting = False
  2057. def startReceivingBoxes(self, sender):
  2058. """
  2059. No initialization is required.
  2060. """
  2061. def ampBoxReceived(self, box):
  2062. self.boxes.append(box)
  2063. # Synchronous helpers
  2064. def parse(cls, fileObj):
  2065. """
  2066. Parse some amp data stored in a file.
  2067. @param fileObj: a file-like object.
  2068. @return: a list of AmpBoxes encoded in the given file.
  2069. """
  2070. parserHelper = cls()
  2071. bbp = BinaryBoxProtocol(boxReceiver=parserHelper)
  2072. bbp.makeConnection(parserHelper)
  2073. bbp.dataReceived(fileObj.read())
  2074. return parserHelper.boxes
  2075. parse = classmethod(parse)
  2076. def parseString(cls, data):
  2077. """
  2078. Parse some amp data stored in a string.
  2079. @param data: a str holding some amp-encoded data.
  2080. @return: a list of AmpBoxes encoded in the given string.
  2081. """
  2082. return cls.parse(BytesIO(data))
  2083. parseString = classmethod(parseString)
  2084. parse = _ParserHelper.parse
  2085. parseString = _ParserHelper.parseString
  2086. def _stringsToObjects(strings, arglist, proto):
  2087. """
  2088. Convert an AmpBox to a dictionary of python objects, converting through a
  2089. given arglist.
  2090. @param strings: an AmpBox (or dict of strings)
  2091. @param arglist: a list of 2-tuples of strings and Argument objects, as
  2092. described in L{Command.arguments}.
  2093. @param proto: an L{AMP} instance.
  2094. @return: the converted dictionary mapping names to argument objects.
  2095. """
  2096. objects = {}
  2097. myStrings = strings.copy()
  2098. for argname, argparser in arglist:
  2099. argparser.fromBox(argname, myStrings, objects, proto)
  2100. return objects
  2101. def _objectsToStrings(objects, arglist, strings, proto):
  2102. """
  2103. Convert a dictionary of python objects to an AmpBox, converting through a
  2104. given arglist.
  2105. @param objects: a dict mapping names to python objects
  2106. @param arglist: a list of 2-tuples of strings and Argument objects, as
  2107. described in L{Command.arguments}.
  2108. @param strings: [OUT PARAMETER] An object providing the L{dict}
  2109. interface which will be populated with serialized data.
  2110. @param proto: an L{AMP} instance.
  2111. @return: The converted dictionary mapping names to encoded argument
  2112. strings (identical to C{strings}).
  2113. """
  2114. myObjects = objects.copy()
  2115. for argname, argparser in arglist:
  2116. argparser.toBox(argname, strings, myObjects, proto)
  2117. return strings
  2118. class Decimal(Argument):
  2119. """
  2120. Encodes C{decimal.Decimal} instances.
  2121. There are several ways in which a decimal value might be encoded.
  2122. Special values are encoded as special strings::
  2123. - Positive infinity is encoded as C{"Infinity"}
  2124. - Negative infinity is encoded as C{"-Infinity"}
  2125. - Quiet not-a-number is encoded as either C{"NaN"} or C{"-NaN"}
  2126. - Signalling not-a-number is encoded as either C{"sNaN"} or C{"-sNaN"}
  2127. Normal values are encoded using the base ten string representation, using
  2128. engineering notation to indicate magnitude without precision, and "normal"
  2129. digits to indicate precision. For example::
  2130. - C{"1"} represents the value I{1} with precision to one place.
  2131. - C{"-1"} represents the value I{-1} with precision to one place.
  2132. - C{"1.0"} represents the value I{1} with precision to two places.
  2133. - C{"10"} represents the value I{10} with precision to two places.
  2134. - C{"1E+2"} represents the value I{10} with precision to one place.
  2135. - C{"1E-1"} represents the value I{0.1} with precision to one place.
  2136. - C{"1.5E+2"} represents the value I{15} with precision to two places.
  2137. U{http://speleotrove.com/decimal/} should be considered the authoritative
  2138. specification for the format.
  2139. """
  2140. def fromString(self, inString):
  2141. inString = nativeString(inString)
  2142. return decimal.Decimal(inString)
  2143. def toString(self, inObject):
  2144. """
  2145. Serialize a C{decimal.Decimal} instance to the specified wire format.
  2146. """
  2147. if isinstance(inObject, decimal.Decimal):
  2148. # Hopefully decimal.Decimal.__str__ actually does what we want.
  2149. return str(inObject).encode("ascii")
  2150. raise ValueError(
  2151. "amp.Decimal can only encode instances of decimal.Decimal")
  2152. class DateTime(Argument):
  2153. """
  2154. Encodes C{datetime.datetime} instances.
  2155. Wire format: '%04i-%02i-%02iT%02i:%02i:%02i.%06i%s%02i:%02i'. Fields in
  2156. order are: year, month, day, hour, minute, second, microsecond, timezone
  2157. direction (+ or -), timezone hour, timezone minute. Encoded string is
  2158. always exactly 32 characters long. This format is compatible with ISO 8601,
  2159. but that does not mean all ISO 8601 dates can be accepted.
  2160. Also, note that the datetime module's notion of a "timezone" can be
  2161. complex, but the wire format includes only a fixed offset, so the
  2162. conversion is not lossless. A lossless transmission of a C{datetime} instance
  2163. is not feasible since the receiving end would require a Python interpreter.
  2164. @ivar _positions: A sequence of slices giving the positions of various
  2165. interesting parts of the wire format.
  2166. """
  2167. _positions = [
  2168. slice(0, 4), slice(5, 7), slice(8, 10), # year, month, day
  2169. slice(11, 13), slice(14, 16), slice(17, 19), # hour, minute, second
  2170. slice(20, 26), # microsecond
  2171. # intentionally skip timezone direction, as it is not an integer
  2172. slice(27, 29), slice(30, 32) # timezone hour, timezone minute
  2173. ]
  2174. def fromString(self, s):
  2175. """
  2176. Parse a string containing a date and time in the wire format into a
  2177. C{datetime.datetime} instance.
  2178. """
  2179. s = nativeString(s)
  2180. if len(s) != 32:
  2181. raise ValueError('invalid date format %r' % (s,))
  2182. values = [int(s[p]) for p in self._positions]
  2183. sign = s[26]
  2184. timezone = _FixedOffsetTZInfo.fromSignHoursMinutes(sign, *values[7:])
  2185. values[7:] = [timezone]
  2186. return datetime.datetime(*values)
  2187. def toString(self, i):
  2188. """
  2189. Serialize a C{datetime.datetime} instance to a string in the specified
  2190. wire format.
  2191. """
  2192. offset = i.utcoffset()
  2193. if offset is None:
  2194. raise ValueError(
  2195. 'amp.DateTime cannot serialize naive datetime instances. '
  2196. 'You may find amp.utc useful.')
  2197. minutesOffset = (offset.days * 86400 + offset.seconds) // 60
  2198. if minutesOffset > 0:
  2199. sign = '+'
  2200. else:
  2201. sign = '-'
  2202. # strftime has no way to format the microseconds, or put a ':' in the
  2203. # timezone. Surprise!
  2204. # Python 3.4 cannot do % interpolation on byte strings so we pack into
  2205. # an explicitly Unicode string then encode as ASCII.
  2206. packed = u'%04i-%02i-%02iT%02i:%02i:%02i.%06i%s%02i:%02i' % (
  2207. i.year,
  2208. i.month,
  2209. i.day,
  2210. i.hour,
  2211. i.minute,
  2212. i.second,
  2213. i.microsecond,
  2214. sign,
  2215. abs(minutesOffset) // 60,
  2216. abs(minutesOffset) % 60)
  2217. return packed.encode("ascii")