amp.py 95 KB

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