3 \j@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 ZdddZejdZddZfddZZS) GpgmeWrapperz>Base wrapper class Not to be instantiated directly. cCsd|_||_dS)N)_callback_excinfowrapped)selfrr/usr/lib64/python3.6/core.py__init__3szGpgmeWrapper.__init__csdjtt|j|jS)Nz <{}/{!r}>)formatsuperr __repr__r)r) __class__rrr7szGpgmeWrapper.__repr__csPdjtjjg}fddjD}|r@|jdjdj|djdj|S)Nz{}.{}csg|]}t|r|qSr)getattr).0f)rrr =sz(GpgmeWrapper.__str__..z({}) z<{}>)r__name__r_boolean_propertiesappendjoin)rZaccflagsr)rr__str__;s zGpgmeWrapper.__str__cCstt|jS)N)hashreprr)rrrr__hash__CszGpgmeWrapper.__hash__cCs$|dkr 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. N)NotImplementedError)rrrr_ctypeLszGpgmeWrapper._ctypecCs tdS)zgThe common prefix of c functions wrapped by this class Must be set by child classes. N)r')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.N)r')rnamerrr _errorcheck^szGpgmeWrapper._errorcheckFNcsttdj|j|ttdj|j|fdd}fdd}t||dj|d}t|j|||rv||t|n||SdS) Nz{}get_{}z{}set_{}cst|jS)N)boolr)slf)get_funcrrgetlsz1GpgmeWrapper.__wrap_boolean_property..getcs|jt|dS)N)rr,)r-value)set_funcrrset_osz2GpgmeWrapper.__wrap_boolean_property..set_z{} flag)doc)rrrr)propertysetattrrr,)rkeyZdo_setr0r/r2pr)r.r1rZ__wrap_boolean_propertyhs  z$GpgmeWrapper.__wrap_boolean_propertyz$gpgme_([^(]*)\(([^,]*), (.*\) -> .*)cs|ddksjdkrdS|jkr.j|Sj|ttjr\fddn fddjjdtd}|_t j |fd d }||_|S) z7On-the-fly generation of wrapper methods and propertiesr_Ncs*|jf|}|jr tj|t|S)N)rr rgpg_raise_callback_exceptionr)r-argsresult)funcr*rr _funcwraps z+GpgmeWrapper.__getattr__.._funcwrapcs$|jf|}|jr tj||S)N)rr rr9)r-r:r;)r<rrr=s z\2.\1(\3__doc__csf|S)Nr)r:)r=rrrwrappersz)GpgmeWrapper.__getattr__..wrapper) r)r$_GpgmeWrapper__wrap_boolean_propertyrrr+_munge_docstringsubr>r5r)rr6r3r?r)r=r<r*rr __getattr__|s      zGpgmeWrapper.__getattr__cs0||jkr|j|d|ntt|j||dS)z#On-the-fly generation of propertiesTN)rr@rr __setattr__)rr6r0)rrrrDs zGpgmeWrapper.__setattr__)FN)r __module__ __qualname__r>rrr!r$r&r4r(r)r+setrr@recompilerArCrD __classcell__rr)rrr ,s    (r c s<eZdZdZdddgejejddffdd ZddZdd Z gd ddddddd f d d Z dgd dZ dej fddZ ddgfddZddZdhddZdiddZdjddZddejjjdfddZdkddZdld d!Zd"d#Zd$d%Zdmd&d'Zd(d)Zdnd*d+Zdod,d-Zed.d/Zej d0d/Zed1d2Z!e!j d3d2Z!ed4d5Z"e"j d6d5Z"ed7d8Z#e#j d9d8Z#d:Z$d;Z%dd?d@hZ'dAdBZ(dCdDZ)dEdFZ*dGdHZ+dIdJZ,dpdKdLZ-dMdNZ.dOdPZ/dqdQdRZ0dSdTZ1drdUdVZ2dWdXZ3dsdYdZZ4d[d\Z5ed]d^Z6d_d`Z7dtdadbZ8dcddZ9dedfZ:Z;S)uContextaContext 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|_n0tj} ttj| tj| }tj| d|_tt|j |||_ ||_ ||_ ||_ ||_||_||_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_prrKrarmortextmodeofflinesigners pinentry_modeprotocolhome_dir) rrNrOrPrQrRrSrrTtmp)rrrrs  zContext.__init__cCs&|s |dkrdS|jdtj|jS)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 dj|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}))r)rrrrrszContext.__repr__Tc s|r|nt} d} | |tjO} | | tjO} | |tjO} | | tjO} | | tjO} dk r|j} t|dd}tj |_dfdd }|j |zy*|r|j || || n|j || || Wnt jk r|}z|j}|r|jnd}|j|| ||f}|jt jkr.|jr.t j|j|j|d|jt jkrb|j}|jrbt j|j|j|d||_|WYdd}~XnXWddk r| |_|r|j |ddX|j}|j st|r|jnd}| s|j st|j|| ||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_cbcsS)Nr)hintdescprev_badhook) passphraserr passphrase_cb(sz&Context.encrypt..passphrase_cb)errorresultsr)N)Datar ZENCRYPT_ALWAYS_TRUSTZENCRYPT_NO_ENCRYPT_TOZENCRYPT_PREPAREZENCRYPT_EXPECT_SIGNZENCRYPT_NO_COMPRESSrRrPINENTRY_MODE_LOOPBACKset_passphrase_cbZop_encrypt_signZ op_encryptr rZop_encrypt_resultop_sign_resultr\getcodeZUNUSABLE_PUBKEYZinvalid_recipientsZInvalidRecipientsrdUNUSABLE_SECKEYinvalid_signersInvalidSignersreAssertionError)r plaintextZ recipientssignrZrbZ always_trustZadd_encrypt_toZprepareZ expect_signcompress ciphertextr old_pinentry_modeold_passphrase_cbrcer;Z sig_resultrer)rbrencryptsZ*   zContext.encryptcs<d}d}|r|nt}dk rP|j}t|dd} tj|_dfdd } |j| zyVt|trd|}n$|dkrtj dt dd}n|}d}|r|j ||n |j ||WnXt jk r} z8|j} |r|j} nd} |j||| | f| _| WYdd} ~ XnXWddk r.||_| r.|j| d dX|j} |rH|j} nd} |j||| | f}| jrvt j| j|d |r8ttd d | j| _|dk r8g}x|D]x}d}x\|jD]R}xB| jD]8}|jtj@d krܐq|jr|j|jkrd}PqW|rPqW|s|j|qW|r8t 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 FNr]csS)Nr)r^r_r`ra)rbrrrcsz&Context.decrypt..passphrase_cbzTctx.decrypt called with verify=None, should be bool or iterable (treating as False).)categoryTr)recSs |jtjkS)N)statusr NO_ERROR)srrrsz!Context.decrypt..r)N)rfrRrr rgrh isinstancer,warningswarnDeprecationWarningZop_decrypt_verifyZ op_decryptr rZop_decrypt_resultop_verify_resultr\reZunsupported_algorithmZUnsupportedAlgorithmlistfilter signaturessubkeyssummary SIGSUM_VALIDcan_signfprrMissingSignatures)rrrrZrbverifyZdo_sig_verificationZ required_keysrorsrtrcrur;Z verify_resultremissingr6oksubkeysigr)rbrdecryptTs|#          zContext.decryptcCs|r|nt}y|j|||Wnrtjk r}zT|j|||jf}|jtjkrx|djrxtj |dj|j |d||_ |WYdd}~XnX|j}|j st |j|||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 r)rdreN) rfZop_signr rr\rirjrkrlrmrdrern)rr[rZmodeZ signeddatarurer;rrrrps   z Context.signc CsT|r d}n|r|nt}y&|r.|j||dn|j|d|Wn>tjk r|}z |j|||jf|_|WYdd}~XnX|j|||jf}tdd|djDrtj |d|dt }xr|D]j} d} xR| j D]H} x<|djD].} | j t j@dkrq| jr| j| jkrd} PqW| rPqW| s|j| qW|rPtj|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|]}|jtjkVqdS)N)rxr ry)rrzrrr sz!Context.verify..r)reFrT)rfZ op_verifyr rr\rreanyrZ BadSignaturesrrrr rrrrr) rZ signed_dataZ signaturerZrr[rurerr6rrrrrrrs>  zContext.verifycCsy.|j||j}|jdkr&tj}ntj}Wntk r}zl|tjkrd|j dkr\tj }qtj }nB|t krt |ddkrtj}n$|t krt |ddkrtj }ntj}WYdd}~XnX|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)rr[r;rxruZ import_resultrrr key_import3s(      zContext.key_importcCstt}d}y(|j||||jdtj|j}Wn&tk rX}z |}WYdd}~XnXt|dkrl|}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)rf op_exportrVrWrXrYrlen)rpatternr[r pk_resultrur;rrr key_exportbs  zContext.key_exportcCsvt}tj}y(|j||||jdtj|j}Wn&tk rZ}z |}WYdd}~XnXt |dkrn|}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) rfrZGPGME_EXPORT_MODE_MINIMALrrVrWrXrYrr)rrr[rrrur;rrrkey_export_minimals  zContext.key_export_minimalcCsvt}tj}y(|j||||jdtj|j}Wn&tk rZ}z |}WYdd}~XnXt |dkrn|}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) rfrZGPGME_EXPORT_MODE_SECRETrrVrWrXrYrr)rrr[rZ sk_resultrur;rrrkey_export_secrets  zContext.key_export_secretccsh|s|j||j||n t|ts0t|d}|j|d|j}x|rZ|V|j}qFW|jdS)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_startr|rfZop_keylist_from_data_startop_keylist_nextop_keylist_end)rrsecretrsourcer6rrrkeylists     zContext.keylistrc stjr<|j} t|dd} tj|_dfdd } |j| z|j||d|d|rXtjj nd|rftjj ndB|rvtjj ndB|rtjj ndBdkrtjj ndB|rdntjjB| rtjjndBWdtjr| |_| r|j| ddX|jS)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 r]NcsS)Nr)r^r_r`ra)rbrrrc5sz)Context.create_key..passphrase_cbrr)N)r is_a_stringrRrr rgrhZ op_createkeycreateSIGNENCRZCERTAUTHNOPASSWDNOEXPIREZFORCEop_genkey_result)rZuserid algorithm expires_inexpiresrprvZcertify authenticaterbforcersrtrcr)rbr create_keys(;   b zContext.create_keyc stjr<|j} t|dd} tj|_dfdd } |j| zf|j||d||rVtjj nd|rdtjj ndB|rttjj ndBdkrtjj ndB|rdntjj BWdtjr| |_| r|j| ddX|jS)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 r]NcsS)Nr)r^r_r`ra)rbrrrcsz,Context.create_subkey..passphrase_cbrr)N)r rrRrr rgrhZop_createsubkeyrrrrrrr) rr6rrrrprvrrbrsrtrcr)rbr create_subkeyPs&6   B zContext.create_subkeycCs|j||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_adduid)rr6uidrrr key_add_uids zContext.key_add_uidcCs|j||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_revuid)rr6rrrrkey_revoke_uids zContext.key_revoke_uidcCsbd}|dks.tj|rn|tjjO}dj|}|s>|tjjO}|rN|tjjO}|j||||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 ZkeysignZLFSEPrrLOCALZ op_keysign)rr6ZuidsrZlocalr rrrkey_signs    zContext.key_signcCs|j||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)rr6Zpolicyrrrkey_tofu_policys zContext.key_tofu_policyc Cstj|st|tr|}ndjdd|D}tj}tj|j||rRt j ||fnd|rft j ||fnd|rzt j ||fnd|}|j rtj |t |tj|}tj||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 rcss|]}tj|VqdS)N)r Zpercent_escape)rrrrrrsz*Context.assuan_transact..Nr)r rr|bytesrrnew_gpgme_error_t_pZgpgme_op_assuan_transact_extrweakrefrefr r9rgpgme_error_t_p_valuedelete_gpgme_error_t_pr) rZcommandZdata_cbZ inquire_cbZ status_cbcmdZerrptrerrrxrrrassuan_transacts   zContext.assuan_transactcCsr|dkrtd|dkrt}|r4tj|||f}ntj||f}tj|j||||}|jrftj|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) ValueErrorrfrrrZgpgme_op_interactrr r9r)rr6r<rZr fnc_valueZ opaquedatar;rrrinteract"s zContext.interactcsfddtjDS)zKeys used for signingcsg|]}j|qSr)Z signers_enum)ri)rrrrFsz#Context.signers..)rangeZ signers_count)rr)rrrQCszContext.signersc CsD|j}|jyx|D]}|j|qWWn||_YnXdS)N)rQZ signers_clearZ signers_add)rrQoldr6rrrrQHs cCs|jS)z Pinentry mode)Zget_pinentry_mode)rrrrrRSszContext.pinentry_modecCs|j|dS)N)Zset_pinentry_mode)rr0rrrrRXscCs|jS)zProtocol to use)Z get_protocol)rrrrrS\szContext.protocolcCsttj||j|dS)N)rrgpgme_engine_check_versionZ set_protocol)rr0rrrrSascCs|jjS)zEngine's home directory) engine_inforT)rrrrrTfszContext.home_dircCs|j|j|ddS)N)rT)set_engine_inforS)rr0rrrrTksZ gpgme_ctx_tZgpgme_cCs|jdr|jd p|dkS)z?This function should list all functions returning gpgme_error_tZ gpgme_op_Z_resultrMgpgme_set_ctx_flaggpgme_set_protocolgpgme_set_sub_protocolgpgme_set_keylist_modegpgme_set_pinentry_modegpgme_set_localegpgme_ctx_set_engine_infogpgme_signers_addgpgme_sig_notation_addgpgme_set_sender gpgme_cancelgpgme_cancel_async gpgme_get_keygpgme_get_sig_key>rrrrrrrrrrrrrrMr) startswithendswith)rr*rrrr+rs zContext._errorcheckrNrOrPcCsHtsdS|j|j|j|jrD|jrDtjrDtj|jd|_dS)N)r _free_passcb_free_progresscb_free_statuscbrLrZ gpgme_release)rrrr__del__s zContext.__del__cCs|S)Nr)rrrr __enter__szContext.__enter__cCs |jdS)N)r)rtyper0tbrrr__exit__szContext.__exit__cos8|j|||j}x|r*|V|j}qW|jdS)N)rrr)rr:kwargsr6rrrop_keylist_alls   zContext.op_keylist_allcCstj}y ttj|j|tj|}Wn:tjk rb}zd}|jtj krR|WYdd}~XnXtj ||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 tj|S)N)rgpgme_key_unref)rrrrr{sz)Context.op_keylist_next..) rnew_gpgme_key_t_prZgpgme_op_keylist_nextrgpgme_key_t_p_valuer rrjEOFdelete_gpgme_key_t_pr)rptrr6excprrrrs  zContext.op_keylist_nextcCstj}yttj|j|||Wn@tjk rb}z"|jtjkrNtj ||WYdd}~XnXtj |}tj ||st dd|_ |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 tj|S)N)rr)rrrrr{sz!Context.get_key..)rrrrrr rrjrZ KeyNotFoundrrrnr)rrrrrur6rrrget_keys    zContext.get_keycos8|j|||j}x|r*|V|j}qW|jdS)N)Zop_trustlist_startop_trustlist_nextZop_trustlist_end)rr:rtrustrrrop_trustlist_alls   zContext.op_trustlist_allcCsptj}y ttj|j|tj|}Wn8tjk r`}zd}|jtj krPWYdd}~XnXtj ||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 rrjrZdelete_gpgme_trust_item_t_p)rrrrrrrrs zContext.op_trustlist_nextcCsF|dkrd}n(|dkr&tj||f}ntj|||f}tj||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_cb)rr<rahookdatarrrrhs zContext.set_passphrase_cbcCstjr|jddS)N)rrrh)rrrrrszContext._free_passcbcCsF|dkrd}n(|dkr&tj||f}ntj|||f}tj||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_cb)rr<rarrrrset_progress_cbs zContext.set_progress_cbcCstjr|jddS)N)rrr)rrrrrszContext._free_progresscbcCsF|dkrd}n(|dkr&tj||f}ntj|||f}tj||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_cb)rr<rarrrr set_status_cbs zContext.set_status_cbcCstjr|jddS)N)rrr)rrrrr-szContext._free_statuscbcs4|jfdd|jD}t|dks,t|dS)z,Configuration of the engine currently in usecsg|]}|jkr|qSr)rS)rr)r7rrr5sz'Context.engine_info..rr)rSget_engine_inforrn)rZinfosr)r7rr1szContext.engine_infocCs tj|jS)zGet engine configuration Returns information about all configured and installed engines. Returns: infos -- a list of engine infos )rZgpgme_ctx_get_engine_infor)rrrrr9s zContext.get_engine_infocCs|j|||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_namerTrrrrEs zContext.set_engine_infocCs8tj}tj|j||tj|}tj|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)rhangrrxrrrwaitRs   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.)rw)rZr)r}r~rr)rr6r<routrrrop_edit_s  zContext.op_edit)NNT)N)N)N) NrTFFFFNF)NrTFFFN)NFF)NNN)NrN)F)N)N)N)NN)r ZPINENTRY_MODE_DEFAULTZPROTOCOL_OpenPGPrr\rrvrZSIG_MODE_NORMALrprrrrrrrrrrrrrrrrr4rQsetterrRrSrTr(r)r+rrrrrrrrrrhrrrrrrrrrrrJrr)rrrKs    Y v+>/ " # * # S K  ) . !             rKcseZdZdZdZdZddZd'fdd Zd d Zd d Z ddZ ddZ ddZ d(ddZ d)ddZd*ddZddZddZddZd d!Zd"d#Zd,d%d&ZZS)-rfaJData 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_c Cs|d kS) z?This function should list all functions returning gpgme_error_tgpgme_data_readgpgme_data_writegpgme_data_seekgpgme_data_releasegpgme_data_release_and_get_memgpgme_data_get_encodinggpgme_data_get_file_namegpgme_data_set_flaggpgme_data_identify> rrr r rr rrrr)rr*rrrr+szData._errorcheckNTcstt|jdd|_|dk r*|j|nr|dk r@|j||n\|dk rh|dk rh|dk rh|j|||n4|dk rtj|r|j ||q|j |n|j 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) rrfrZdata_cbs new_from_cbs new_from_memnew_from_filepartr r new_from_file new_from_fdnew)rstringroffsetlengthZcbscopy)rrrrs/   z Data.__init__cCsFtsdS|jdk r:tjr:tj|j|jr4tj|d|_|jdS)N)rrrr r9 _free_datacbs)rrrrrs  z Data.__del__cCs|S)Nr)rrrrrszData.__enter__cCs |jdS)N)r)rrr0rrrrrsz Data.__exit__cCs d|_dS)N)Z _data_cbs)rrrrrszData._free_datacbscCs0tj}ttj|tj||_tj|dS)N)rnew_gpgme_data_t_prZgpgme_data_newgpgme_data_t_p_valuerdelete_gpgme_data_t_p)rrUrrrrs zData.newcCs:tj}ttj||t||tj||_tj|dS)N)rrrZgpgme_data_new_from_memrrrr)rrrrUrrrr s  zData.new_from_memcCstj}yttj|||WnFtjk rd}z(|jtjkrP| rPtdn|WYdd}~XnXtj ||_ tj |dS)Nz#delayed reads are not yet supported) rrrZgpgme_data_new_from_filer rrjZ INV_VALUErrrr)rfilenamerrUrurrrrs  zData.new_from_filecCsdtj}|dk r(tj||||||f}ntj|||||f}tj|||tj||_tj|dS)N)rrrrZgpg_data_new_from_cbsrrr)rZread_cbZwrite_cbZseek_cbZ release_cbrarUrrrrr s  zData.new_from_cbscCstj}d}d}tj|r |}n6tj|j|j}|dkrVtdtt |t|ft tj |||||tj ||_ tj|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)rrrrrUrfprrrrs    zData.new_from_filepartcCs6tj}ttj||jtj||_tj|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)rrrUrrrr-s zData.new_from_fdcCs|j|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)r)rrrrrnew_from_stream8szData.new_from_streamcCs|j|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)rrrrrnew_from_estream>szData.new_from_estreamcCs4tj|j|}|dkr0|jr(tj|ntj|S)zkWrite buffer given as string or bytes. If a string is given, it is implicitly encoded using UTF-8.r)rrrr r9rZ fromSyserror)rbufferZwrittenrrrwriteDs  z Data.writerc Cs|dkr dS|dkrLytj|j|}Wn |jr@tj|nYnX|Sg}xPytj|jd}Wn |jr~tj|nYnXt|dkrP|j|qRWdj|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.riN)rrrr r9rrr)rsizer;ZchunksrrrrYPs,   z Data.read)NNNNNT)T)T)N)r&)rrErFr>r(r)r+rrrrrrr rr rrrr r"rYrJrr)rrrfps0:     rfcCs tj|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_stringts r'cCs tj|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_name)algorrrpubkey_algo_names r)cCs tj|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_name)r(rrrhash_algo_names r*cCs tj|S)ztGet protocol description Get the string describing protocol PROTO. Returns: proto - a string )rZgpgme_get_protocol_name)rrrrget_protocol_names r+cCs tj|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 r,cCs tj|S)N)rZgpgme_check_version)versionrrr check_versionsr.c Cs.yttj|dStjk r(dSXdS)NTF)rrrr r)rrrrengine_check_versions r/c CsNtj}yttj|tj|}Wntjk r>d}YnXtj||S)N)rZnew_gpgme_engine_info_t_prZgpgme_get_engine_infoZgpgme_engine_info_t_p_valuer rZdelete_gpgme_engine_info_t_p)rinforrrrs  rcCsttj|||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)rrrTrrrrsrcCsttjd||dS)z(Sets the default locale used by contextsN)rrr)rwr0rrr set_localesr1cCsLtj}tjd||}tj|}tj||dkrsJ    M