a x_@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/lib64/python3.9/site-packages/gpg/core.py__init__3szGpgmeWrapper.__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)rZaccflagsrrr__str__;s zGpgmeWrapper.__str__cCstt|jSr )hashreprrrrrr__hash__CszGpgmeWrapper.__hash__cCs$|dur dSt|jt|jkSdS)NF)r(r)rotherrrr__eq__FszGpgmeWrapper.__eq__cCs tdS)z]The name of the c type wrapped by this class Must be set by child classes. NNotImplementedErrorrrrr_ctypeLszGpgmeWrapper._ctypecCs tdS)zgThe common prefix of c functions wrapped by this class Must be set by child classes. Nr,rrrr_cprefixUszGpgmeWrapper._cprefixcCs tdS)zMust be implemented by child classes. This function must return a trueish value for all c functions returning gpgme_error_t.Nr,rnamerrr _errorcheck^szGpgmeWrapper._errorcheckFNcsttd|j|ttd|j|fdd}fdd}t||d|d}t|j|||rv||t|n||SdS) Nz{}get_{}z{}set_{}cst|jSr )boolr)slf)get_funcrrgetlsz1GpgmeWrapper.__wrap_boolean_property..getcs|jt|dSr )rr3)r4value)set_funcrrset_osz2GpgmeWrapper.__wrap_boolean_property..set_z{} flag)doc)rrrr/propertysetattrrr3)rkeyZdo_setr7r6r9pr)r5r8rZ__wrap_boolean_propertyhs  z$GpgmeWrapper.__wrap_boolean_propertyz$gpgme_([^(]*)\(([^,]*), (.*\) -> .*)cs|ddksjdurdS|jvr.|Sj|ttr\fddn fddtd}|rjd|}nd}|_t j |fd d }||_|S) z7On-the-fly generation of wrapper methods and propertiesr_Ncs,|jg|R}|jr"t|t|Sr )rrrgpg_raise_callback_exceptionrr4argsresult)funcr1rr _funcwraps z+GpgmeWrapper.__getattr__.._funcwrapcs&|jg|R}|jr"t||Sr )rrrr@rA)rDrrrEs __doc__z\2.\1(\3csg|RSr r)rB)rErrrwrappersz)GpgmeWrapper.__getattr__..wrapper) r/r"$_GpgmeWrapper__wrap_boolean_propertyrrr2_munge_docstringsubrFr<r)rr=Zdoc_origr:rGr)rErDr1rr __getattr__|s$       zGpgmeWrapper.__getattr__cs0||jvr||d|ntt|||dS)z#On-the-fly generation of propertiesTN)r"rHrr __setattr__)rr=r7rrrrLs zGpgmeWrapper.__setattr__)FN)r! __module__ __qualname__rFrrr&r)r+r;r.r/r2setr"rHrecompilerIrKrL __classcell__rrrrr ,s      -r c s:eZdZdZdddgejejddffdd ZddZdd Z gd ddddddd f d d Z ded dZ dej fddZ ddgfddZddZdfddZdgddZdhddZddejjjdfddZdiddZdjd d!Zd"d#Zd$d%Zdkd&d'Zd(d)Zdld*d+Zdmd,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,dndIdJZ-dKdLZ.dMdNZ/dodOdPZ0dQdRZ1dpdSdTZ2dUdVZ3dqdWdXZ4dYdZZ5ed[d\Z6d]d^Z7drd_d`Z8dadbZ9dcddZ:Z;S)sContextaContext 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|r d|_n0t} 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)ownrZnew_gpgme_ctx_t_pr gpgme_newZgpgme_ctx_t_p_valueZdelete_gpgme_ctx_t_prrSrarmortextmodeofflinesigners pinentry_modeprotocolhome_dir) rrVrWrXrYrZr[rr\tmprrrrs  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} dur|j} t|dd}tj |_dfdd }| |zz*|r| || || n| || || Wnt jy}z|}|r|nd}||| ||f}|t jkr.|jr.t j|j|j|d|t jkrb|}|jrbt j|j|j|d||_|WYd}~n d}~00Wdur| |_|r|j |ddn*dur| |_|r|j |dd0|}|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_cbcsSr rhintZdescZprev_badhook passphraserr passphrase_cb-sz&Context.encrypt..passphrase_cberrorresultsr)N)Datar ZENCRYPT_ALWAYS_TRUSTZENCRYPT_NO_ENCRYPT_TOZENCRYPT_PREPAREZENCRYPT_EXPECT_SIGNZENCRYPT_NO_COMPRESSrZrPINENTRY_MODE_LOOPBACKset_passphrase_cbZop_encrypt_signZ op_encryptr rZop_encrypt_resultop_sign_resultrdgetcodeZUNUSABLE_PUBKEYZinvalid_recipientsZInvalidRecipientsrmUNUSABLE_SECKEYinvalid_signersInvalidSignersrn)r plaintextZ recipientssignrbrjZ always_trustZadd_encrypt_toZprepareZ expect_signcompress ciphertextr%old_pinentry_modeold_passphrase_cbrkerCZ sig_resultrnrrirencryptsf*     zContext.encryptc sbd}d}|r|nt}durP|j}t|dd} tj|_dfdd } || zzVt|trd|}n$|durtj dt dd}n|}d}|r| ||n | ||WnZt jy} z>|} |r|} nd} |||| | f| _| WYd} ~ n d} ~ 00WdurZ||_| rZ|j| d dn*durX||_| rX|j| d d0|} |rr|} nd} |||| | f}| jrt j| j|d |r^ttd d | j| _|dur^g}|D]x}d}|jD]V}| jD]<}|jtj@d krq|jr|j|jkrd}q$q|rq4q|s||q|r^t j| ||d |S)aDecrypt 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). 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) 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 FNrecsSr rrfrirrrksz&Context.decrypt..passphrase_cbzTctx.decrypt called with verify=None, should be bool or iterable (treating as False).categoryTrrncSs |jtjkSr statusr ZNO_ERROR)srrrrz!Context.decrypt..r)N)rorZrr rprq isinstancer3warningswarnDeprecationWarningZop_decrypt_verifyZ op_decryptr rZop_decrypt_resultop_verify_resultrdrnZunsupported_algorithmZUnsupportedAlgorithmlistfilter signaturessubkeyssummary SIGSUM_VALIDcan_signfprr#MissingSignatures)rrzrbrjverifyZdo_sig_verification required_keysrwr{r|rkr}rCZ verify_resultrnmissingr=oksubkeysigrrirdecryptYs#            zContext.decryptc Cs|r|nt}z||||Wnttjy}zZ||||f}|tjkrv|djrvtj |dj|j |d||_ |WYd}~n d}~00|}|jrJ||||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 rrlN) roZop_signr rrdrrrsrtrurvrmrn)rrcrbmodeZ signeddatar}rnrCrrrrxs"  z Context.signc CsR|r d}n|r|nt}z&|r.|||dn||d|Wn@tjy~}z&||||f|_|WYd}~n d}~00||||f}tdd|djDrtj |d|dt }|D]j} d} | j D]L} |djD]2} | j t j@dkrq| jr| j| jkrd} qq| rq$q| s|| q|rNtj|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 !rz!Context.verify..rrFrT)roZ op_verifyr rrdrrnanyrZ BadSignaturesrrrr rrrr#r) rZ signed_dataZ signaturerbrrcr}rnrr=rrrrrrrs@   zContext.verifyc Csz.|||}|jdkr&tj}ntj}Wnty}zr|tjkrb|j dkrZtj }qtj }nB|t krt |ddurtj}n$|t krt |ddurtj }ntj}WYd}~n d}~00|tjkr|}n|}|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)Z op_importZop_import_resultZ consideredr ZSTATUS_IMPORT_PROBLEMZSTATUS_KEY_CONSIDERED Exceptionr rZcode_strZ STATUS_NODATAZSTATUS_FILE_ERROR TypeErrorhasattrZSTATUS_NO_PUBKEYZ STATUS_ERROR)rrcrCrr}Z import_resultrrr key_import8s(      zContext.key_importc Csvt}d}z(|||||dtj|}Wn(tyZ}z|WYd}~n d}~00t|dkrn|}nd}|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)ro op_exportr^r_r`rarlenrpatternrcrZ pk_resultr}rCrrr key_exportgs  zContext.key_exportc Csxt}tj}z(|||||dtj|}Wn(ty\}z|WYd}~n d}~00t |dkrp|}nd}|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) rorZGPGME_EXPORT_MODE_MINIMALrr^r_r`rarrrrrrkey_export_minimals  zContext.key_export_minimalc Csxt}tj}z(|||||dtj|}Wn(ty\}z|WYd}~n d}~00t |dkrp|}nd}|S)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) rorZGPGME_EXPORT_MODE_SECRETrr^r_r`rarr)rrrcrZ sk_resultr}rCrrrkey_export_secrets  zContext.key_export_secretccsd|s|||||n t|ts0t|d}||d|}|rX|V|}qD|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)Zset_keylist_modeop_keylist_startrroZop_keylist_from_data_startop_keylist_nextop_keylist_end)rrsecretrsourcer=rrrkeylists     zContext.keylistrc  s tr<|j} t|dd} tj|_dfdd } || z|||d|d|rXtjj nd|rftjj ndB|rvtjj ndB|rtjj ndBdurtjj ndB|rdntjjB| rtjjndBWtr| |_| r|j| ddn,tr| |_| r|j| dd0|S)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 reNcsSr rrfrirrrk:sz)Context.create_key..passphrase_cbrr)N)r is_a_stringrZrr rprqZ op_createkeycreateSIGNENCRZCERTAUTHNOPASSWDNOEXPIREZFORCEop_genkey_result)rZuserid algorithm expires_inexpiresrxr~Zcertify authenticaterjforcer{r|rkrrir create_keysH;     zContext.create_keyc str<|j} t|dd} tj|_dfdd } || z|||d||rVtjj nd|rdtjj ndB|rttjj ndBdurtjj ndB|rdntjj BWtr| |_| r|j| ddn(tr| |_| r|j| dd0|S)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 reNcsSr rrfrirrrksz,Context.create_subkey..passphrase_cbrr)N)r rrZrr rprqZop_createsubkeyrrrrrrr) rr=rrrrxr~rrjr{r|rkrrir create_subkeyUs>6     zContext.create_subkeycCs|||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)Z op_adduidrr=uidrrr key_add_uids zContext.key_add_uidcCs|||ddS)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)Z op_revuidrrrrkey_revoke_uids zContext.key_revoke_uidcCsbd}|dus.t|rn|tjjO}d|}|s>|tjjO}|rN|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 ZkeysignZLFSEPr$rLOCALZ op_keysign)rr=Zuidsrlocalr%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)Zop_tofu_policy)rr=Zpolicyrrrkey_tofu_policys zContext.key_tofu_policyc Cst|st|tr|}nddd|D}t}t|j||rRt ||fnd|rft ||fnd|rzt ||fnd|}|j rt |t |t|}t||dkrt|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 Zpercent_escaperrrrrrz*Context.assuan_transact..Nr)r rrbytesr$rnew_gpgme_error_t_pZgpgme_op_assuan_transact_extrweakrefrefrr@rgpgme_error_t_p_valuedelete_gpgme_error_t_pr) rZcommandZdata_cbZ inquire_cbZ status_cbcmdZerrptrerrrrrrassuan_transacts,   zContext.assuan_transactcCsr|durtd|durt}|r4t|||f}nt||f}t|j||||}|jrft|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) ValueErrorrorrrZgpgme_op_interactrrr@r)rr=rDrbr% fnc_valueZ opaquedatarCrrrinteract's zContext.interactcsfddtDS)zKeys used for signingcsg|]}|qSr)Z signers_enumrirrrrKrz#Context.signers..)rangeZ signers_countrrrrrYHszContext.signerscCs@|j}|z|D]}||qWn||_Yn0dSr )rYZ signers_clearZ signers_add)rrYoldr=rrrrYMscCs|S)z Pinentry mode)Zget_pinentry_moderrrrrZXszContext.pinentry_modecCs||dSr )Zset_pinentry_moderr7rrrrZ]scCs|S)zProtocol to use)Z get_protocolrrrrr[aszContext.protocolcCstt|||dSr )rrgpgme_engine_check_versionZ set_protocolrrrrr[fscCs|jjS)zEngine's home directory) engine_infor\rrrrr\kszContext.home_dircCs|j|j|ddS)N)r\)set_engine_infor[rrrrr\psZ gpgme_ctx_tZgpgme_cCs|dr|d p|dvS)?This function should list all functions returning gpgme_error_tZ gpgme_op_Z_result>Zgpgme_set_keylist_modeZgpgme_set_senderZgpgme_ctx_set_engine_infoZgpgme_set_sub_protocolZgpgme_get_sig_keyrUZgpgme_signers_addgpgme_set_locale gpgme_get_keyZ gpgme_cancelZgpgme_set_pinentry_modeZgpgme_sig_notation_addZgpgme_set_protocolZgpgme_cancel_asyncZgpgme_set_ctx_flag) startswithendswithr0rrrr2ws  zContext._errorcheck>rVrXrWcCsHtsdS||||jrD|jrDtjrDt|jd|_dSr )r _free_passcb_free_progresscb_free_statuscbrTrZ gpgme_releaserrrr__del__s zContext.__del__cCs|Sr rrrrr __enter__szContext.__enter__cCs |dSr rrtyper7tbrrr__exit__szContext.__exit__cos8|j|i||}|r,|V|}q|dSr )rrr)rrBkwargsr=rrrop_keylist_alls  zContext.op_keylist_allc Cst}z tt|j|t|}Wn<tjyd}z"d}|tj krP|WYd}~n d}~00t ||rdd|_ |SdS)z~Returns the next key in the list created by a call to op_keylist_start(). The object returned is of type Key.NcSs t|Sr rZgpgme_key_unrefrrrrrrz)Context.op_keylist_next..) rnew_gpgme_key_t_prZgpgme_op_keylist_nextrgpgme_key_t_p_valuer rrsEOFdelete_gpgme_key_t_pr)rptrr=excprrrrs  zContext.op_keylist_nextc Cst}ztt|j|||WnBtjyd}z(|tjkrLt ||WYd}~n d}~00t |}t ||sJdd|_ |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 NcSs t|Sr rrrrrrrz!Context.get_key..) rrrrrr rrsrZ KeyNotFoundrrr)rrrrr}r=rrrget_keys    zContext.get_keycos8|j|i||}|r,|V|}q|dSr )Zop_trustlist_startop_trustlist_nextZop_trustlist_end)rrBrtrustrrrop_trustlist_alls  zContext.op_trustlist_allc Csrt}z tt|j|t|}Wn:tjyb}z d}|tj krNWYd}~n d}~00t ||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) rZnew_gpgme_trust_item_t_prZgpgme_op_trustlist_nextrZgpgme_trust_item_t_p_valuer rrsrZdelete_gpgme_trust_item_t_p)rrrrrrrrs zContext.op_trustlist_nextcCsF|durd}n(|dur&t||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_cbrrDrhhookdatarrrrqs zContext.set_passphrase_cbcCstjr|ddSr )rrrqrrrrrszContext._free_passcbcCsF|durd}n(|dur&t||f}nt|||f}t||dS)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_cbs zContext.set_progress_cbcCstjr|ddSr )rrrrrrrrszContext._free_progresscbcCsF|durd}n(|dur&t||f}nt|||f}t||dS)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_cbs zContext.set_status_cbcCstjr|ddSr )rrrrrrrr2szContext._free_statuscbcs4|jfdd|D}t|dks,J|dS)z,Configuration of the engine currently in usecsg|]}|jkr|qSr)r[rr>rrr:rz'Context.engine_info..rr)r[get_engine_infor)rZinfosrrrr6szContext.engine_infocCs t|jS)zGet engine configuration Returns information about all configured and installed engines. Returns: infos -- a list of engine infos )rZgpgme_ctx_get_engine_inforrrrrr>s 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)Zctx_set_engine_info)rproto file_namer\rrrrJs 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_waitrrrr)rhangrrrrrwaitWs   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)rbr)rrrr)rr=rDroutrrrop_editds zContext.op_edit)NNT)N)N)N) NrTFFFFNF)NrTFFFN)NFF)NNN)NrN)F)N)N)N)NN)/ " # * ' ] S  ) 2 !                rScseZdZdZdZdZddZd'fdd Zd d Zd d Z ddZ ddZ ddZ d(ddZ d)ddZd*ddZddZddZddZd d!Zd"d#Zd+d%d&ZZS),roaJData 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. Z gpgme_data_tZ gpgme_data_cCs|dvS)r> gpgme_data_readZgpgme_data_release_and_get_memZgpgme_data_get_encodinggpgme_data_releasegpgme_data_writeZgpgme_data_seekZgpgme_data_set_flagZgpgme_data_identifyZgpgme_data_get_file_namerr0rrrr2szData._errorcheckNTcstt|dd|_|dur*|j|nr|dur@|||n\|durh|durh|durh||||n4|durt|r| ||q| |n| 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) rrorZdata_cbs new_from_cbs new_from_memnew_from_filepartr r new_from_file new_from_fdnew)rstringroffsetlengthZcbscopyrrrrs/   z Data.__init__cCsFtsdS|jdur:tjr:t|j|jr4t|d|_|dSr )rrr rr@ _free_datacbsrrrrrs  z Data.__del__cCs|Sr rrrrrrszData.__enter__cCs |dSr rrrrrrsz Data.__exit__cCs d|_dSr )Z _data_cbsrrrrrszData._free_datacbscCs0t}tt|t||_t|dSr )rnew_gpgme_data_t_prZgpgme_data_newgpgme_data_t_p_valuerdelete_gpgme_data_t_p)rr]rrrrs zData.newcCs:t}tt||t||t||_t|dSr )rrrZgpgme_data_new_from_memrrrr)rrrr]rrrrs  zData.new_from_memc Cst}ztt|||WnFtjyd}z,|tjkrL|sLtdn|WYd}~n d}~00t ||_ t |dS)Nz#delayed reads are not yet supported) rrrZgpgme_data_new_from_filer rrsZ INV_VALUErrrr)rfilenamerr]r}rrrrs  zData.new_from_filecCsdt}|dur(t||||||f}nt|||||f}t|||t||_t|dSr )rrrrZgpg_data_new_from_cbsrrr)rZread_cbZwrite_cbZseek_cbZ release_cbrhr]rrrrr s zData.new_from_cbscCst}d}d}t|r |}n6t||j}|durVtdtt |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 rfdopenfilenorrstrrrZgpgme_data_new_from_filepartrrr)rrrrr]rfprrrrs&    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)rrrZgpgme_data_new_from_fdrrrr)rrr]rrrr2s zData.new_from_fdcCs||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_stream=szData.new_from_streamcCs||dS)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)r"r!rrrnew_from_estreamCszData.new_from_estreamcCs4t|j|}|dkr0|jr(t|nt|S)zkWrite buffer given as string or bytes. If a string is given, it is implicitly encoded using UTF-8.r)rr rrr@rZ fromSyserror)rbufferZwrittenrrrwriteIs  z Data.writecCs|dkr dS|dkrLzt|j|}Wn |jr@t|nYn0|Sg}zt|jd}Wn |jr|t|nYn0t|dkrq||qPd|SdS)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.rirN)rr rrr@rr#r$)rsizerCchunksrrrraUs*    z Data.read)NNNNNT)T)T)N)r&)r!rMrNrFr.r/r2rrrrrrrrrrrr"r#r%rarRrrrrrous2@     rocCs t|S)zReturn short algorithm string Return a public key algorithm string (e.g. "rsa2048") for a given SUBKEY. Returns: algo - a string )rZgpgme_pubkey_algo_string)rrrrpubkey_algo_stringys r*cCs t|S)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 )rZgpgme_pubkey_algo_nameZalgorrrpubkey_algo_names r,cCs t|S)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 )rZgpgme_hash_algo_namer+rrrhash_algo_names r-cCs t|S)ztGet protocol description Get the string describing protocol PROTO. Returns: proto - a string )rZgpgme_get_protocol_namerrrrget_protocol_names r/cCs t|S)zReturn the address spec Return the addr-spec (cf. RFC2822 section 4.3) from a user id UID. Returns: addr_spec - a string )rZgpgme_addrspec_from_uid)rrrraddrspec_from_uids r0cCs t|Sr )rZgpgme_check_version)versionrrr check_versionsr2cCs0ztt|WdStjy*YdS0dS)NTF)rrrr rr.rrrengine_check_versions r3cCsLt}ztt|t|}Wntjy<d}Yn0t||Sr )rZnew_gpgme_engine_info_t_prZgpgme_get_engine_infoZgpgme_engine_info_t_p_valuer rZdelete_gpgme_engine_info_t_p)rinforrrrs  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)rrZgpgme_set_engine_info)rrr\rrrrsrcCsttd||dS)z(Sets the default locale used by contextsN)rrr)rr7rrr set_localesr5cCsLt}td||}t|}t||dursJ    M