o ]`@sddlmZmZmZddlZddlZddlZddlZddlm Z ddl m Z m Z ddlm Z ddlm Z ddlmZ[[[ Gd d d eZGd d d eZGd ddeZddZddZddZddZddZd%ddZeddZddZd%dd Zd!d"Zd#d$ZdS)&)absolute_importprint_functionunicode_literalsN)gpgme) errorcheck GPGMEError) constants)errors)utilcseZdZdZddZfddZddZdd Zd d Ze d d Z e ddZ ddZ e ZdddZedZddZfddZZS) GpgmeWrapperz>Base wrapper class Not to be instantiated directly. cCsd|_||_dSN)_callback_excinfowrapped)selfrr*/usr/lib/python3/dist-packages/gpg/core.py__init__3s zGpgmeWrapper.__init__csdtt||jS)Nz <{}/{!r}>)formatsuperr __repr__rr __class__rrr7szGpgmeWrapper.__repr__csPdtjjg}fddjD}|r |dd|dd|S)Nz{}.{}csg|] }t|r|qSr)getattr.0frrr =z(GpgmeWrapper.__str__..z({}) z<{}>)r__name__r_boolean_propertiesappendjoin)raccflagsrrr__str__;s zGpgmeWrapper.__str__cCstt|jSr )hashreprrrrrr__hash__CzGpgmeWrapper.__hash__cCs |durdSt|jt|jkS)NF)r)r)rotherrrr__eq__FszGpgmeWrapper.__eq__cCt)z]The name of the c type wrapped by this class Must be set by child classes. NotImplementedErrorrrrr_ctypeLzGpgmeWrapper._ctypecCr.)zgThe common prefix of c functions wrapped by this class Must be set by child classes. r/rrrr_cprefixUr2zGpgmeWrapper._cprefixcCr.)zMust be implemented by child classes. This function must return a trueish value for all c functions returning gpgme_error_t.r/rnamerrr _errorcheck^szGpgmeWrapper._errorcheckFNcsttd|j|ttd|j|fdd}fdd}t||d|d}t|j|||r<||t|dS||S) Nz{}get_{}z{}set_{}cst|jSr )boolr)slf)get_funcrrgetlr+z1GpgmeWrapper.__wrap_boolean_property..getcs|jt|dSr )rr7)r8value)set_funcrrset_osz2GpgmeWrapper.__wrap_boolean_property..set_z{} flag)doc)rrrr3propertysetattrrr7)rkeydo_setr;r:r=pr)r9r<r__wrap_boolean_propertyhs  z$GpgmeWrapper.__wrap_boolean_propertyz$gpgme_([^(]*)\(([^,]*), (.*\) -> .*)cs|ddks jdur dS|jvr|Sj|ttr.fddnfddtd}|rCjd|}nd}|_t j |fd d }||_|S) z7On-the-fly generation of wrapper methods and propertiesr_Ncs,|jg|R}|jrt|t|Sr )rrrgpg_raise_callback_exceptionrr8argsresult)funcr5rr _funcwraps  z+GpgmeWrapper.__getattr__.._funcwrapcs&|jg|R}|jrt||Sr )rrrrFrG)rJrrrKs __doc__z\2.\1(\3csg|RSr r)rH)rKrrrwrappersz)GpgmeWrapper.__getattr__..wrapper) r3r"$_GpgmeWrapper__wrap_boolean_propertyrrr6_munge_docstringsubrLr@r)rrAdoc_origr>rMr)rKrJr5rr __getattr__|s$       zGpgmeWrapper.__getattr__cs2||jvr||d|dStt|||dS)z#On-the-fly generation of propertiesTN)r"rNrr __setattr__)rrAr;rrrrSs zGpgmeWrapper.__setattr__)FN)r! __module__ __qualname__rLrrr'r*r-r?r1r3r6setr"rNrecompilerOrRrS __classcell__rrrrr ,s$     -r c s`eZdZdZdddgejejddffdd ZddZdd Z gd ddddddd f d d Z ded dZ dej fddZ ddgfddZddZdfddZdfddZdfddZddejjjdfddZ        dgddZ      dhd d!Zd"d#Zd$d%Zdid&d'Zd(d)Z   djd*d+Zdkd,d-Zed.d/Zej d0d/Zed1d2Z!e!j d3d2Z!ed4d5Z"e"j d6d5Z"ed7d8Z#e#j d9d8Z#d:Z$d;Z%dZ'd?d@Z(dAdBZ)dCdDZ*dEdFZ+dGdHZ,dldIdJZ-dKdLZ.dMdNZ/dfdOdPZ0dQdRZ1dfdSdTZ2dUdVZ3dfdWdXZ4dYdZZ5ed[d\Z6d]d^Z7dmd_d`Z8dadbZ9dcddZ:Z;S)nContextaContext for cryptographic operations All cryptographic operations in GPGME are performed within a context, which contains the internal state of the operation as well as configuration parameters. By using several contexts you can run several cryptographic operations in parallel, with different configuration. Access to a context must be synchronized. FNc sz|rd|_nt} tt| t| }t| d|_tt| |||_ ||_ ||_ ||_ ||_||_||_dS)aConstruct a context object Keyword arguments: armor -- enable ASCII armoring (default False) textmode -- enable canonical text mode (default False) offline -- do not contact external key sources (default False) signers -- list of keys used for signing (default []) pinentry_mode -- pinentry mode (default PINENTRY_MODE_DEFAULT) protocol -- protocol to use (default PROTOCOL_OpenPGP) home_dir -- state directory (default is the engine default) FTN)ownrnew_gpgme_ctx_t_pr gpgme_newgpgme_ctx_t_p_valuedelete_gpgme_ctx_t_prrZrarmortextmodeofflinesigners pinentry_modeprotocolhome_dir) rr`rarbrcrdrerrftmprrrrs   zContext.__init__cCs&|s|durdS|dtj|S)zxRead helper Helper function to retrieve the results of an operation, or None if SINK is given. Nr)seekosSEEK_SETread)rsinkdatarrr__read__s zContext.__read__cCs d|S)NzContext(armor={0.armor}, textmode={0.textmode}, offline={0.offline}, signers={0.signers}, pinentry_mode={0.pinentry_mode}, protocol={0.protocol}, home_dir={0.home_dir}))rrrrrrszContext.__repr__Tc  s|r|nt} d} | |tjO} | | tjO} | |tjO} | | tjO} | | tjO} durK|j} t|dd}tj |_dfdd }| |z}z|rX| || || n| || || WnSt jy}zF|}|rt|nd}||| ||f}|t jkr|jrt j|j|j|d|t jkr|}|jrt j|j|j|d||_|d}~wwWdur| |_|r|j |ddndur| |_|r|j |ddwww|}|jrJ|r|nd}|r|jrJ||| ||fS) a%Encrypt data Encrypt the given plaintext for the given recipients. If the list of recipients is empty, the data is encrypted symmetrically with a passphrase. The passphrase can be given as parameter, using a callback registered at the context, or out-of-band via pinentry. Keyword arguments: recipients -- list of keys to encrypt to sign -- sign plaintext (default True) sink -- write result to sink instead of returning it passphrase -- for symmetric encryption always_trust -- always trust the keys (default False) add_encrypt_to -- encrypt to configured additional keys (default False) prepare -- (ui) prepare for encryption (default False) expect_sign -- (ui) prepare for signing (default False) compress -- compress plaintext (default True) Returns: ciphertext -- the encrypted data (or None if sink is given) result -- additional information about the encryption sign_result -- additional information about the signature(s) Raises: InvalidRecipients -- if encryption using a particular key failed InvalidSigners -- if signing using a particular key failed GPGMEError -- as signaled by the underlying library rN_passphrase_cbcSr rhintdescprev_badhook passphraserr passphrase_cb-z&Context.encrypt..passphrase_cberrorresultsrr )Datar ENCRYPT_ALWAYS_TRUSTENCRYPT_NO_ENCRYPT_TOENCRYPT_PREPAREENCRYPT_EXPECT_SIGNENCRYPT_NO_COMPRESSrdrPINENTRY_MODE_LOOPBACKset_passphrase_cbop_encrypt_sign op_encryptr rop_encrypt_resultop_sign_resultrngetcodeUNUSABLE_PUBKEYinvalid_recipientsInvalidRecipientsr{UNUSABLE_SECKEYinvalid_signersInvalidSignersr|)r plaintext recipientssignrlrw always_trustadd_encrypt_toprepare expect_signcompress ciphertextr&old_pinentry_modeold_passphrase_cbrxerI sig_resultr|rrvrencryptst*   zContext.encryptc s>d}d}|r|nt}dur(|j} t|dd} tj|_dfdd } || zfz+t|tr2|}n|dur@tj dt dd}n|}d}|rM| ||n| ||Wn&t jyz} z|} |rh|}nd}|||| |f| _| d} ~ wwWdur| |_| r|j| d dndur| |_| r|j| d dwww|} |r|}nd}|||| |f}| jrt j| j|d |r|rttd d |j|_|durg}|D]3}d}|jD]#}|jD]}|jtj@d krq|jr|j|jkrd}|rnq|s||q|rt j|||d |S)a=Decrypt data Decrypt the given ciphertext and verify any signatures. If VERIFY is an iterable of keys, the ciphertext must be signed by all those keys, otherwise a MissingSignatures error is raised. Note: if VERIFY is an empty iterable, that is treated the same as passing verify=True (that is, verify signatures and return data about any valid signatures found, but no signatures are required and no MissingSignatures error will be raised). The filter_signatures argument can be used to force this function to return signatures that are not fully trusted - for example because they were made by unknown keys. If the ciphertext is symmetrically encrypted using a passphrase, that passphrase can be given as parameter, using a callback registered at the context, or out-of-band via pinentry. Keyword arguments: sink -- write result to sink instead of returning it passphrase -- for symmetric decryption verify -- check signatures (boolean or iterable of keys, see above) (default True) filter_signatures -- if this function should filter out signatures that are not completely OK (default True) Returns: plaintext -- the decrypted data (or None if sink is given) result -- additional information about the decryption verify_result -- additional information about the valid signature(s) found Raises: UnsupportedAlgorithm -- if an unsupported algorithm was used MissingSignatures -- if expected signatures are missing or bad GPGMEError -- as signaled by the underlying library FNrocrpr rrqrvrrrxryz&Context.decrypt..passphrase_cbzTctx.decrypt called with verify=None, should be bool or iterable (treating as False).categoryTrr|cSs |jtjkSr statusr NO_ERROR)srrrs z!Context.decrypt..rr )r}rdrr rr isinstancer7warningswarnDeprecationWarningop_decrypt_verify op_decryptr rop_decrypt_resultop_verify_resultrnr|unsupported_algorithmUnsupportedAlgorithmlistfilter signaturessubkeyssummary SIGSUM_VALIDcan_signfprr#MissingSignatures)rrrlrwverifyfilter_signaturesdo_sig_verification required_keysrrrrxrrI verify_resultr|missingrAoksubkeysigrrvrdecryptYs)           zContext.decryptc Cs|r|nt}z ||||Wn4tjyD}z'||||f}|tjkr;|djr;tj |dj|j |d||_ |d}~ww|}|jrNJ||||fS)aSign data Sign the given data with either the configured default local key, or the 'signers' keys of this context. Keyword arguments: mode -- signature mode (default: normal, see below) sink -- write result to sink instead of returning it Returns: either signed_data -- encoded data and signature (normal mode) signature -- only the signature data (detached mode) cleartext -- data and signature as text (cleartext mode) (or None if sink is given) result -- additional information about the signature(s) Raises: InvalidSigners -- if signing using a particular key failed GPGMEError -- as signaled by the underlying library rrzN) r}op_signr rrnrrrrrr{r|)rrmrlmode signeddatarr|rIrrrrs&  z Context.signc Cs@|rd}n|r |nt}z|r|||dn||d|Wntjy9}z ||||f|_|d}~ww||||f}tdd|djDrYtj |d|dt }|D]3} d} | j D]$} |djD]} | j t j@dkrwql| jr| j| jkrd} nql| rnqe| s|| q^|rtj|d||d|S) aVerify signatures Verify signatures over data. If VERIFY is an iterable of keys, the ciphertext must be signed by all those keys, otherwise an error is raised. Keyword arguments: signature -- detached signature data sink -- write result to sink instead of returning it Returns: data -- the plain data (or None if sink is given, or we verified a detached signature) result -- additional information about the signature(s) Raises: BadSignatures -- if a bad signature is encountered MissingSignatures -- if expected signatures are missing or bad GPGMEError -- as signaled by the underlying library Ncss|] }|jtjkVqdSr r)rrrrr 'sz!Context.verify..rrFrT)r} op_verifyr rrnrr|anyr BadSignaturesrrrr rrrr#r) r signed_data signaturerlrrmrr|rrArrrrrrrsL   zContext.verifyc Csz|||}|jdkrtj}ntj}WnEty\}z9|tjkr1|j dkr-tj }n%tj }n!|t kr@t |ddur@tj}n|t krOt |ddurOtj }ntj}WYd}~nd}~ww|tjkrf|}|S|}|S)aImport data Imports the given data into the Context. Returns: -- an object describing the results of imported or updated keys Raises: TypeError -- Very rarely. GPGMEError -- as signaled by the underlying library: Import status errors, when they occur, will usually be of NODATA. NO_PUBKEY indicates something managed to run the function without any arguments, while an argument of None triggers the first NODATA of errors.GPGME in the exception. rzNo datadecodeTencodeN) op_importop_import_result consideredr STATUS_IMPORT_PROBLEMSTATUS_KEY_CONSIDERED Exceptionr rcode_str STATUS_NODATASTATUS_FILE_ERROR TypeErrorhasattrSTATUS_NO_PUBKEY STATUS_ERROR)rrmrIrr import_resultrrr key_import>s0     zContext.key_importc Cslt}d}z|||||dtj|}Wnty'}z|d}~wwt|dkr2|}|Sd}|S)aQExport keys. Exports public keys matching the pattern specified. If no pattern is specified then exports all available keys. Keyword arguments: pattern -- return keys matching pattern (default: all keys) Returns: -- A key block containing one or more OpenPGP keys in either ASCII armoured or binary format as determined by the Context(). If there are no matching keys it returns None. Raises: GPGMEError -- as signaled by the underlying library. rN)r} op_exportrhrirjrkrlenrpatternrmr pk_resultrrIrrr key_exportms  zContext.key_exportc Cnt}tj}z|||||dtj|}Wnty(}z|d}~wwt |dkr3|}|Sd}|S)ayExport keys. Exports public keys matching the pattern specified in a minimised format. If no pattern is specified then exports all available keys. Keyword arguments: pattern -- return keys matching pattern (default: all keys) Returns: -- A key block containing one or more minimised OpenPGP keys in either ASCII armoured or binary format as determined by the Context(). If there are no matching keys it returns None. Raises: GPGMEError -- as signaled by the underlying library. rN) r}rGPGME_EXPORT_MODE_MINIMALrrhrirjrkrrrrrrkey_export_minimals  zContext.key_export_minimalc Cr)aExport secret keys. Exports secret keys matching the pattern specified. If no pattern is specified then exports or attempts to export all available secret keys. IMPORTANT: Each secret key to be exported will prompt for its passphrase via an invocation of pinentry and gpg-agent. If the passphrase is not entered or does not match then no data will be exported. This is the same result as when specifying a pattern that is not matched by the available keys. Keyword arguments: pattern -- return keys matching pattern (default: all keys) Returns: -- On success a key block containing one or more OpenPGP secret keys in either ASCII armoured or binary format as determined by the Context(). -- On failure while not raising an exception, returns None. Raises: GPGMEError -- as signaled by the underlying library. rN) r}rGPGME_EXPORT_MODE_SECRETrrhrirjrkrr)rrrmr sk_resultrrIrrrkey_export_secrets  zContext.key_export_secretccsh|s|||||nt|tst|d}||d|}|r.|V|}|s%|dS)aList keys Keyword arguments: pattern -- return keys matching pattern (default: all keys) secret -- return only secret keys (default: False) mode -- keylist mode (default: list local keys) source -- read keys from source instead from the keyring (all other options are ignored in this case) Returns: -- an iterator returning key objects Raises: GPGMEError -- as signaled by the underlying library )filerN)set_keylist_modeop_keylist_startrr}op_keylist_from_data_startop_keylist_nextop_keylist_end)rrsecretrsourcerArrrkeylists     zContext.keylistrc  str|j} t|dd} tj|_dfdd } || zZ|||d|d|r,tjj nd|r3tjj ndB|r;tjj ndB|rCtjj ndBdurMtjj ndB|rSdntjjB| r]tjjndBWtru| |_| ru|j| dd|Str| |_| r|j| ddwww)a Create a primary key Create a primary key for the user id USERID. ALGORITHM may be used to specify the public key encryption algorithm for the new key. By default, a reasonable default is chosen. You may use "future-default" to select an algorithm that will be the default in a future implementation of the engine. ALGORITHM may be a string like "rsa", or "rsa2048" to explicitly request an algorithm and a key size. EXPIRES_IN specifies the expiration time of the key in number of seconds since the keys creation. By default, a reasonable expiration time is chosen. If you want to create a key that does not expire, use the keyword argument EXPIRES. SIGN, ENCRYPT, CERTIFY, and AUTHENTICATE can be used to request the capabilities of the new key. If you don't request any, a reasonable set of capabilities is selected, and in case of OpenPGP, a subkey with a reasonable set of capabilities is created. If PASSPHRASE is None (the default), then the key will not be protected with a passphrase. If PASSPHRASE is a string, it will be used to protect the key. If PASSPHRASE is True, the passphrase must be supplied using a passphrase callback or out-of-band with a pinentry. Keyword arguments: algorithm -- public key algorithm, see above (default: reasonable) expires_in -- expiration time in seconds (default: reasonable) expires -- whether or not the key should expire (default: True) sign -- request the signing capability (see above) encrypt -- request the encryption capability (see above) certify -- request the certification capability (see above) authenticate -- request the authentication capability (see above) passphrase -- protect the key with a passphrase (default: no passphrase) force -- force key creation even if a key with the same userid exists (default: False) Returns: -- an object describing the result of the key creation Raises: GPGMEError -- as signaled by the underlying library roNcrpr rrqrvrrrx@ryz)Context.create_key..passphrase_cbrrr )r is_a_stringrdrr rr op_createkeycreateSIGNENCRCERTAUTHNOPASSWDNOEXPIREFORCEop_genkey_result)ruserid algorithm expires_inexpiresrrcertify authenticaterwforcerrrxrrvr create_keysL ;    zContext.create_keyc str|j} t|dd} tj|_dfdd } || zI|||d||r+tjj nd|r2tjj ndB|r:tjj ndBdurDtjj ndB|rJdntjj BWtrd| |_| rd|j| dd|Str|| |_| r}|j| ddwww)a@Create a subkey Create a subkey for the given KEY. As subkeys are a concept of OpenPGP, calling this is only valid for the OpenPGP protocol. ALGORITHM may be used to specify the public key encryption algorithm for the new subkey. By default, a reasonable default is chosen. You may use "future-default" to select an algorithm that will be the default in a future implementation of the engine. ALGORITHM may be a string like "rsa", or "rsa2048" to explicitly request an algorithm and a key size. EXPIRES_IN specifies the expiration time of the subkey in number of seconds since the subkeys creation. By default, a reasonable expiration time is chosen. If you want to create a subkey that does not expire, use the keyword argument EXPIRES. SIGN, ENCRYPT, and AUTHENTICATE can be used to request the capabilities of the new subkey. If you don't request any, an encryption subkey is generated. If PASSPHRASE is None (the default), then the subkey will not be protected with a passphrase. If PASSPHRASE is a string, it will be used to protect the subkey. If PASSPHRASE is True, the passphrase must be supplied using a passphrase callback or out-of-band with a pinentry. Keyword arguments: algorithm -- public key algorithm, see above (default: reasonable) expires_in -- expiration time in seconds (default: reasonable) expires -- whether or not the subkey should expire (default: True) sign -- request the signing capability (see above) encrypt -- request the encryption capability (see above) authenticate -- request the authentication capability (see above) passphrase -- protect the subkey with a passphrase (default: no passphrase) Returns: -- an object describing the result of the subkey creation Raises: GPGMEError -- as signaled by the underlying library roNcrpr rrqrvrrrxryz,Context.create_subkey..passphrase_cbrrr )r rrdrr rrop_createsubkeyrrrrrrr) rrArrrrrrrwrrrxrrvr create_subkey[sB 6    zContext.create_subkeycC|||ddS)zAdd a UID Add the uid UID to the given KEY. Calling this function is only valid for the OpenPGP protocol. Raises: GPGMEError -- as signaled by the underlying library rN) op_adduidrrAuidrrr key_add_uid zContext.key_add_uidcCr)zRevoke a UID Revoke the uid UID from the given KEY. Calling this function is only valid for the OpenPGP protocol. Raises: GPGMEError -- as signaled by the underlying library rN) op_revuidr rrrkey_revoke_uidr zContext.key_revoke_uidcCsbd}|dus t|r n |tjjO}d|}|s|tjjO}|r'|tjjO}|||||dS)aSign a key Sign a key with the current set of signing keys. Calling this function is only valid for the OpenPGP protocol. If UIDS is None (the default), then all UIDs are signed. If it is a string, then only the matching UID is signed. If it is a list of strings, then all matching UIDs are signed. Note that a case-sensitive exact string comparison is done. EXPIRES_IN specifies the expiration time of the signature in seconds. If EXPIRES_IN is False, the signature does not expire. Keyword arguments: uids -- user ids to sign, see above (default: sign all) expires_in -- validity period of the signature in seconds (default: do not expire) local -- create a local, non-exportable signature (default: False) Raises: GPGMEError -- as signaled by the underlying library rN ) r rr keysignLFSEPr$rLOCAL op_keysign)rrAuidsrlocalr&rrrkey_signs    zContext.key_signcCs|||dS)zSet a keys' TOFU policy Set the TOFU policy associated with KEY to POLICY. Calling this function is only valid for the OpenPGP protocol. Raises: GPGMEError -- as signaled by the underlying library N)op_tofu_policy)rrApolicyrrrkey_tofu_policys zContext.key_tofu_policyc Cst|s t|tr |}n ddd|D}t}t|j||r)t ||fnd|r3t ||fnd|r=t ||fnd|}|j rIt |t |t|}t||dkr_t|SdS)aIssue a raw assuan command This function can be used to issue a raw assuan command to the engine. If command is a string or bytes, it will be used as-is. If it is an iterable of strings, it will be properly escaped and joined into an well-formed assuan command. Keyword arguments: data_cb -- a callback receiving data lines inquire_cb -- a callback providing more information status_cb -- a callback receiving status lines Returns: result -- the result of command as GPGMEError Raises: GPGMEError -- as signaled by the underlying library r css|]}t|VqdSr )r percent_escaperrrrrsz*Context.assuan_transact..Nr)r rrbytesr$rnew_gpgme_error_t_pgpgme_op_assuan_transact_extrweakrefrefrrFrgpgme_error_t_p_valuedelete_gpgme_error_t_pr) rcommanddata_cb inquire_cb status_cbcmderrptrerrrrrrassuan_transacts,   zContext.assuan_transactcCsr|durtd|durt}|rt|||f}nt||f}t|j||||}|jr3t|t |dS)aInteract with the engine This method can be used to edit keys and cards interactively. KEY is the key to edit, FUNC is called repeatedly with two unicode arguments, 'keyword' and 'args'. See the GPGME manual for details. Keyword arguments: sink -- if given, additional output is written here flags -- use constants.INTERACT_CARD to edit a card Raises: GPGMEError -- as signaled by the underlying library NzFirst argument cannot be None) ValueErrorr}rrrgpgme_op_interactrrrFr)rrArJrlr& fnc_value opaquedatarIrrrinteract-s  zContext.interactcsfddtDS)zKeys used for signingcsg|]}|qSr) signers_enumrirrrrQsz#Context.signers..)range signers_countrrrrrcNszContext.signerscCs8|j}|z |D]}||q WdS||_r )rc signers_clear signers_add)rrcoldrArrrrcSs cC|S)z Pinentry mode)get_pinentry_moderrrrrd^zContext.pinentry_modecCs||dSr )set_pinentry_moderr;rrrrdcscCr7)zProtocol to use) get_protocolrrrrregr9zContext.protocolcCstt|||dSr )rrgpgme_engine_check_version set_protocolr;rrrrelscCs|jjS)zEngine's home directory) engine_inforfrrrrrfqr9zContext.home_dircCs|j|j|ddS)N)rf)set_engine_inforer;rrrrfvs gpgme_ctx_tgpgme_cCs|dr |d p|dvS)?This function should list all functions returning gpgme_error_t gpgme_op__result>r] gpgme_cancel gpgme_get_keygpgme_set_localegpgme_set_sendergpgme_get_sig_keygpgme_signers_addgpgme_cancel_asyncgpgme_set_ctx_flaggpgme_set_protocolgpgme_set_keylist_modegpgme_set_sub_protocolgpgme_sig_notation_addgpgme_set_pinentry_modegpgme_ctx_set_engine_info) startswithendswithr4rrrr6}s zContext._errorcheck>r`rbracCsTtsdS||||jr$|jr&tjr(t|jd|_dSdSdSdSr )r _free_passcb_free_progresscb_free_statuscbr[r gpgme_releaserrrr__del__s   zContext.__del__cC|Sr rrrrr __enter__ryzContext.__enter__cC |dSr rZrtyper;tbrrr__exit__ zContext.__exit__co<|j|i||}|r|V|}|s|dSr )rrr)rrHkwargsrArrrop_keylist_all zContext.op_keylist_allc Cst}ztt|j|t|}Wntjy2}zd}|tj kr(|WYd}~nd}~wwt ||rAdd|_ |SdS)z~Returns the next key in the list created by a call to op_keylist_start(). The object returned is of type Key.NcS t|Sr rgpgme_key_unrefrrrrr z)Context.op_keylist_next..) rnew_gpgme_key_t_prgpgme_op_keylist_nextrgpgme_key_t_p_valuer rrEOFdelete_gpgme_key_t_prZ)rptrrAexcprrrrs    zContext.op_keylist_nextc Cst}z tt|j|||Wntjy,}z|tjkr&t ||d}~wwt |}t ||s;Jdd|_ |S)a&Get a key given a fingerprint Keyword arguments: secret -- to request a secret key Returns: -- the matching key Raises: KeyError -- if the key was not found GPGMEError -- as signaled by the underlying library NcSrhr rirrrrrrkz!Context.get_key..) rrlrrGrr rrro KeyNotFoundrnrprZ)rrrrqrrArrrget_keys    zContext.get_keycordr )op_trustlist_startop_trustlist_nextop_trustlist_end)rrHretrustrrrop_trustlist_allrgzContext.op_trustlist_allc Csrt}ztt|j|t|}Wntjy1}zd}|tj kr'WYd}~nd}~wwt ||S)zReturns the next trust item in the list created by a call to op_trustlist_start(). The object returned is of type TrustItem.N) rnew_gpgme_trust_item_t_prgpgme_op_trustlist_nextrgpgme_trust_item_t_p_valuer rrrodelete_gpgme_trust_item_t_p)rrqrxrrrrrrvs  zContext.op_trustlist_nextcCF|durd}n|durt||f}nt|||f}t||dS)a*Sets the passphrase callback to the function specified by func. When the system needs a passphrase, it will call func with three args: hint, a string describing the key it needs the passphrase for; desc, a string describing the passphrase it needs; prev_bad, a boolean equal True if this is a call made after unsuccessful previous attempt. If hook has a value other than None it will be passed into the func as a forth argument. Please see the GPGME manual for more information. N)rrrgpg_set_passphrase_cbrrJruhookdatarrrrs zContext.set_passphrase_cbcCtjr |ddSdSr )rrrrrrrrVzContext._free_passcbcCr~)aSets the progress meter callback to the function specified by FUNC. If FUNC is None, the callback will be cleared. This function will be called to provide an interactive update of the system's progress. The function will be called with three arguments, type, total, and current. If HOOK is not None, it will be supplied as fourth argument. Please see the GPGME manual for more information. N)rrrgpg_set_progress_cbrrrrset_progress_cb s  zContext.set_progress_cbcCrr )rrrrrrrrW rzContext._free_progresscbcCr~)aPSets the status callback to the function specified by FUNC. If FUNC is None, the callback will be cleared. The function will be called with two arguments, keyword and args. If HOOK is not None, it will be supplied as third argument. Please see the GPGME manual for more information. N)rrrgpg_set_status_cbrrrr set_status_cb$s  zContext.set_status_cbcCrr )rrrrrrrrX8rzContext._free_statuscbcs4|jfdd|D}t|dksJ|dS)z,Configuration of the engine currently in usecsg|] }|jkr|qSr)rer0rCrrr@rz'Context.engine_info..rr)reget_engine_infor)rinfosrrrr?<szContext.engine_infocCs t|jS)zGet engine configuration Returns information about all configured and installed engines. Returns: infos -- a list of engine infos )rgpgme_ctx_get_engine_inforrrrrrDs zContext.get_engine_infocCs||||dS)a6Change engine configuration Changes the configuration of the crypto engine implementing the protocol 'proto' for the context. Keyword arguments: file_name -- engine program file name (unchanged if None) home_dir -- configuration directory (unchanged if None) N)ctx_set_engine_info)rproto file_namerfrrrr@Ps zContext.set_engine_infocCs8t}t|j||t|}t|t|dS)zWait for asynchronous call to finish. Wait forever if hang is True. Raises an exception on errors. Please read the GPGME manual for more information. N)rr gpgme_waitrr r!r)rhangrqrrrrwait]s    z Context.waitcCs tjdtd|j||||dS)aStart key editing using supplied callback function Note: This interface is deprecated and will be removed with GPGME 1.8. Please use .interact instead. Furthermore, we implement this using gpgme_op_interact, so callbacks will get called with string keywords instead of numeric status messages. Code that is using constants.STATUS_X or constants.status.X will continue to work, whereas code using magic numbers will break as a result. z"Call to deprecated method op_edit.r)rlr,)rrrr.)rrArJr,outrrrop_editjs zContext.op_edit)NNTTr ) NrTFFFFNF)NrTFFFN)NFF)NNN)NrN)F)NN) / " #* ' ] S ) 2!                 rZcseZdZdZdZdZddZ      d'fdd Zd d Zd d Z ddZ ddZ ddZ d(ddZ d(ddZd)ddZddZddZddZd d!Zd"d#Zd*d%d&ZZS)+r}aJData buffer A lot of data has to be exchanged between the user and the crypto engine, like plaintext messages, ciphertext, signatures and information about the keys. The technical details about exchanging the data information are completely abstracted by GPGME. The user provides and receives the data via `gpgme_data_t' objects, regardless of the communication protocol between GPGME and the crypto engine in use. This Data class is the implementation of the GpgmeData objects. Please see the information about __init__ for instantiation. gpgme_data_t gpgme_data_cCs|dvS)rC> gpgme_data_readgpgme_data_seekgpgme_data_writegpgme_data_releasegpgme_data_identifygpgme_data_set_flaggpgme_data_get_encodinggpgme_data_get_file_namegpgme_data_release_and_get_memrr4rrrr6szData._errorcheckNTcstt|dd|_|dur|j|dS|dur"|||dS|dur7|dur7|dur7||||dS|durOt|rH| ||dS| |dS| dS)aInitialize a new gpgme_data_t object. If no args are specified, make it an empty object. If string alone is specified, initialize it with the data contained there. If file, offset, and length are all specified, file must be either a filename or a file-like object, and the object will be initialized by reading the specified chunk from the file. If cbs is specified, it MUST be a tuple of the form: (read_cb, write_cb, seek_cb, release_cb[, hook]) where the first four items are functions implementing reading, writing, seeking the data, and releasing any resources once the data object is deallocated. The functions must match the following prototypes: def read(amount, hook=None): return def write(data, hook=None): return def seek(offset, whence, hook=None): return def release(hook=None): The functions may be bound methods. In that case, you can simply use the 'self' reference instead of using a hook. If file is specified without any other arguments, then it must be a filename, and the object will be initialized from that file. N) rr}rdata_cbs new_from_cbs new_from_memnew_from_filepartr r new_from_file new_from_fdnew)rstringroffsetlengthcbscopyrrrrs/  z Data.__init__cCsFtsdS|jdurtjrt|j|jrt|d|_|dSr )rrrrrF _free_datacbsrrrrrZs   z Data.__del__cCr[r rrrrrr\ryzData.__enter__cCr]r r^r_rrrrbrcz Data.__exit__cCs d|_dSr ) _data_cbsrrrrr zData._free_datacbscCs0t}tt|t||_t|dSr )rnew_gpgme_data_t_prgpgme_data_newgpgme_data_t_p_valuerdelete_gpgme_data_t_p)rrgrrrrs zData.newcCs:t}tt||t||t||_t|dSr )rrrgpgme_data_new_from_memrrrr)rrrrgrrrrs  zData.new_from_memc Csrt}z tt|||Wntjy+}z|tjkr%|s%td|d}~wwt ||_ t |dS)Nz#delayed reads are not yet supported) rrrgpgme_data_new_from_filer rr INV_VALUEr*rrr)rfilenamerrgrrrrrs zData.new_from_filecCsdt}|durt||||||f}n t|||||f}t|||t||_t|dSr )rrrrgpg_data_new_from_cbsrrr)rread_cbwrite_cbseek_cb release_cbrurgrrrrrs zData.new_from_cbscCst}d}d}t|r|}nt||j}|dur+tdtt |t|ft t |||||t ||_ t|dS)zThis wraps the GPGME gpgme_data_new_from_filepart() function. The argument "file" may be: * a string specifying a file name, or * a file-like object supporting the fileno() and the mode attribute. Nz"Failed to open file from %s arg %s)rrr rfdopenfilenorr*strr`rgpgme_data_new_from_filepartrrr)rrrrrgrfprrrrs&    zData.new_from_filepartcCs6t}tt||t||_t|dS)zThis wraps the GPGME gpgme_data_new_from_fd() function. The argument "file" must be a file-like object, supporting the fileno() method. N)rrrgpgme_data_new_from_fdrrrr)rrrgrrrr8s zData.new_from_fdcC||dS)zThis wrap around gpgme_data_new_from_stream is an alias for new_from_fd() method since in python there's no difference between file stream and file descriptor.N)rrrrrrnew_from_streamCzData.new_from_streamcCr)zThis wrap around gpgme_data_new_from_estream is an alias for new_from_fd() method since in python there's no difference between file stream and file descriptor, but using fd broke.N)rrrrrnew_from_estreamIrzData.new_from_estreamcCs6t|j|}|dkr|jrt||St|S)zkWrite buffer given as string or bytes. If a string is given, it is implicitly encoded using UTF-8.r)rrrrrFr fromSyserror)rbufferwrittenrrrwriteOs z Data.writecCs|dkrdS|dkr$z t|j|}W|S|jr#t|Y|Sg} z t|jd}Wn|jr=t|nYt|dkrFn||q'd|S)zRead at most size bytes, returned as bytes. If the size argument is negative or omitted, read until EOF is reached. Returns the data read, or the empty string if there was no data to read before EOF was reached.rTi)rrrrrFrr#r$)rsizerIchunksrrrrk[s2     z Data.read)NNNNNT)Tr )r)r!rTrUrLr1r3r6rrZr\rbrrrrrrrrrrrkrYrrrrr}{s4@       r}cCrh)zReturn short algorithm string Return a public key algorithm string (e.g. "rsa2048") for a given SUBKEY. Returns: algo - a string )rgpgme_pubkey_algo_string)rrrrpubkey_algo_string rcCrh)zReturn name of public key algorithm Return the name of the public key algorithm for a given numeric algorithm id ALGO (cf. RFC4880). Returns: algo - a string )rgpgme_pubkey_algo_namealgorrrpubkey_algo_namerrcCrh)zReturn name of hash algorithm Return the name of the hash algorithm for a given numeric algorithm id ALGO (cf. RFC4880). Returns: algo - a string )rgpgme_hash_algo_namerrrrhash_algo_namerrcCrh)ztGet protocol description Get the string describing protocol PROTO. Returns: proto - a string )rgpgme_get_protocol_namerrrrget_protocol_name rcCrh)zReturn the address spec Return the addr-spec (cf. RFC2822 section 4.3) from a user id UID. Returns: addr_spec - a string )rgpgme_addrspec_from_uid)r rrraddrspec_from_uidrrcCrhr )rgpgme_check_version)versionrrr check_versionrrcCs,z tt|WdStjyYdSw)NTF)rrr=r rrrrrengine_check_versions rcCsLt}ztt|t|}Wn tjyd}Ynwt||Sr )rnew_gpgme_engine_info_t_prgpgme_get_engine_infogpgme_engine_info_t_p_valuer rdelete_gpgme_engine_info_t_p)rqinforrrrs rcCstt|||dS)a#Changes the default configuration of the crypto engine implementing the protocol 'proto'. 'file_name' is the file name of the executable program implementing this protocol. 'home_dir' is the directory name of the configuration directory (engine's default is used if omitted).N)rrgpgme_set_engine_info)rrrfrrrr@sr@cCsttd||dS)z(Sets the default locale used by contextsN)rrrH)rr;rrr set_localesrcCsRt}td||}t|}t||dur!t|||fSt|}||fS)aFWait for asynchronous call on any Context to finish. Wait forever if hang is True. For finished anynch calls it returns a tuple (status, context): status - status return by asnynchronous call. context - context which caused this call to return. Please read the GPGME manual of more information.N)rrrr r!rrZ)rrqcontextrrrrrs   rr ) __future__rrrrWrirrrrr rrr r objectr rZr}rrrrrrrrr@rrrrrrsN     S