src/pEpEngine.c
author vb
Wed, 25 Jun 2014 18:44:58 +0200
changeset 0 16f27efbef98
child 8 26cc9f0228f4
permissions -rw-r--r--
initial commit
     1 #define PEP_ENGINE_VERSION "0.4.0"
     2 
     3 // this is 20 safewords with 79 chars max
     4 #define MAX_SAFEWORDS_SPACE (20 * 80)
     5 
     6 // XML parameters string
     7 #define PARMS_MAX 32768
     8 
     9 // maximum busy wait time in ms
    10 #define BUSY_WAIT_TIME 5000
    11 
    12 // maximum line length for reading gpg.conf
    13 #define MAX_LINELENGTH 1024
    14 
    15 // default keyserver
    16 #define DEFAULT_KEYSERVER "hkp://keys.gnupg.net"
    17 
    18 #ifdef WIN32
    19 #include "platform_windows.h"
    20 #define LOCAL_DB windoze_local_db()
    21 #define SYSTEM_DB windoze_system_db()
    22 #define LIBGPGME "libgpgme-11.dll"
    23 #else // UNIX
    24 #define _POSIX_C_SOURCE 200809L
    25 #include <dlfcn.h>
    26 #include "platform_unix.h"
    27 #define LOCAL_DB unix_local_db()
    28 #ifndef SYSTEM_DB
    29 #define SYSTEM_DB "/usr/share/pEp/system.db"
    30 #endif
    31 #ifndef LIBGPGME
    32 #define LIBGPGME "libgpgme-pthread.so"
    33 #endif
    34 #endif
    35 
    36 #include <locale.h>
    37 #include <stdlib.h>
    38 #include <string.h>
    39 #include <assert.h>
    40 #include <stdio.h>
    41 
    42 #ifndef NDEBUG
    43 #include <stdio.h>
    44 #endif
    45 
    46 #include <gpgme.h>
    47 #include "sqlite3.h"
    48 
    49 #define _EXPORT_PEP_ENGINE_DLL
    50 #include "pEpEngine.h"
    51 
    52 #define NOT_IMPLEMENTED assert(0)
    53 
    54 // init
    55 
    56 typedef const char * (*gpgme_check_version_t)(const char*);
    57 typedef gpgme_error_t (*gpgme_set_locale_t)(gpgme_ctx_t CTX, int CATEGORY,
    58         const char *VALUE);
    59 typedef gpgme_error_t (*gpgme_new_t)(gpgme_ctx_t *CTX);
    60 typedef void (*gpgme_release_t)(gpgme_ctx_t CTX);
    61 typedef gpgme_error_t (*gpgme_set_protocol_t)(gpgme_ctx_t CTX,
    62         gpgme_protocol_t PROTO);
    63 typedef void (*gpgme_set_armor_t)(gpgme_ctx_t CTX, int YES);
    64 
    65 // data
    66 
    67 typedef gpgme_error_t (*gpgme_data_new_t)(gpgme_data_t *DH);
    68 typedef gpgme_error_t (*gpgme_data_new_from_mem_t)(gpgme_data_t *DH,
    69         const char *BUFFER, size_t SIZE, int COPY);
    70 typedef void (*gpgme_data_release_t)(gpgme_data_t DH);
    71 typedef gpgme_data_type_t (*gpgme_data_identify_t)(gpgme_data_t DH);
    72 typedef size_t (*gpgme_data_seek_t)(gpgme_data_t DH, size_t OFFSET,
    73         int WHENCE);
    74 typedef size_t (*gpgme_data_read_t)(gpgme_data_t DH, void *BUFFER,
    75         size_t LENGTH);
    76 
    77 // encrypt and decrypt
    78 
    79 typedef gpgme_error_t (*gpgme_op_decrypt_t)(gpgme_ctx_t CTX,
    80         gpgme_data_t CIPHER, gpgme_data_t PLAIN);
    81 typedef gpgme_error_t (*gpgme_op_verify_t)(gpgme_ctx_t CTX, gpgme_data_t SIG,
    82         gpgme_data_t SIGNED_TEXT, gpgme_data_t PLAIN);
    83 typedef gpgme_error_t (*gpgme_op_decrypt_verify_t)(gpgme_ctx_t CTX,
    84         gpgme_data_t CIPHER, gpgme_data_t PLAIN);
    85 typedef gpgme_decrypt_result_t (*gpgme_op_decrypt_result_t)(gpgme_ctx_t CTX);
    86 typedef gpgme_error_t (*gpgme_op_encrypt_sign_t)(gpgme_ctx_t CTX,
    87         gpgme_key_t RECP[], gpgme_encrypt_flags_t FLAGS, gpgme_data_t PLAIN,
    88         gpgme_data_t CIPHER);
    89 typedef gpgme_verify_result_t (*gpgme_op_verify_result_t)(gpgme_ctx_t CTX);
    90 
    91 // keys
    92 
    93 typedef gpgme_error_t (*gpgme_get_key_t)(gpgme_ctx_t CTX, const char *FPR,
    94         gpgme_key_t *R_KEY, int SECRET);
    95 typedef gpgme_error_t (*gpgme_op_genkey_t)(gpgme_ctx_t CTX, const char *PARMS,
    96         gpgme_data_t PUBLIC, gpgme_data_t SECRET);
    97 typedef gpgme_genkey_result_t (*gpgme_op_genkey_result_t)(gpgme_ctx_t CTX);
    98 typedef gpgme_error_t (*gpgme_op_delete_t)(gpgme_ctx_t CTX,
    99         const gpgme_key_t KEY, int ALLOW_SECRET);
   100 typedef gpgme_error_t (*gpgme_op_import_t)(gpgme_ctx_t CTX,
   101         gpgme_data_t KEYDATA);
   102 typedef gpgme_error_t (*gpgme_op_export_t)(gpgme_ctx_t CTX,
   103         const char *PATTERN, gpgme_export_mode_t MODE, gpgme_data_t KEYDATA);
   104 typedef gpgme_error_t (*gpgme_set_keylist_mode_t)(gpgme_ctx_t CTX,
   105         gpgme_keylist_mode_t MODE);
   106 typedef gpgme_keylist_mode_t (*gpgme_get_keylist_mode_t)(gpgme_ctx_t CTX);
   107 typedef gpgme_error_t (*gpgme_op_keylist_start_t)(gpgme_ctx_t CTX,
   108         const char *PATTERN, int SECRET_ONLY);
   109 typedef gpgme_error_t (*gpgme_op_keylist_next_t)(gpgme_ctx_t CTX,
   110         gpgme_key_t *R_KEY);
   111 typedef gpgme_error_t (*gpgme_op_keylist_end_t)(gpgme_ctx_t CTX);
   112 typedef gpgme_error_t (*gpgme_op_import_keys_t)(gpgme_ctx_t CTX,
   113         gpgme_key_t *KEYS);
   114 typedef void (*gpgme_key_ref_t)(gpgme_key_t KEY);
   115 typedef void (*gpgme_key_unref_t)(gpgme_key_t KEY);
   116 
   117 typedef struct {
   118 	const char *version;
   119     const char *passphrase;
   120 	void * gpgme;
   121 	gpgme_ctx_t ctx;
   122 
   123 	sqlite3 *db;
   124 	sqlite3 *system_db;
   125 
   126 	sqlite3_stmt *log;
   127 	sqlite3_stmt *safeword;
   128 	sqlite3_stmt *get_identity;
   129 	sqlite3_stmt *set_person;
   130 	sqlite3_stmt *set_pgp_keypair;
   131 	sqlite3_stmt *set_identity;
   132 	sqlite3_stmt *set_trust;
   133 
   134 	gpgme_check_version_t gpgme_check;
   135 	gpgme_set_locale_t gpgme_set_locale;
   136 	gpgme_new_t gpgme_new;
   137 	gpgme_release_t gpgme_release;
   138 	gpgme_set_protocol_t gpgme_set_protocol;
   139 	gpgme_set_armor_t gpgme_set_armor;
   140 
   141 	gpgme_data_new_t gpgme_data_new;
   142 	gpgme_data_new_from_mem_t gpgme_data_new_from_mem;
   143 	gpgme_data_release_t gpgme_data_release;
   144 	gpgme_data_identify_t gpgme_data_identify;
   145 	gpgme_data_seek_t gpgme_data_seek;
   146 	gpgme_data_read_t gpgme_data_read;
   147 
   148 	gpgme_op_decrypt_t gpgme_op_decrypt;
   149 	gpgme_op_verify_t gpgme_op_verify;
   150 	gpgme_op_decrypt_verify_t gpgme_op_decrypt_verify;
   151 	gpgme_op_decrypt_result_t gpgme_op_decrypt_result;
   152 	gpgme_op_encrypt_sign_t gpgme_op_encrypt_sign;
   153 	gpgme_op_verify_result_t gpgme_op_verify_result;
   154 
   155 	gpgme_get_key_t gpgme_get_key;
   156 	gpgme_op_genkey_t gpgme_op_genkey;
   157     gpgme_op_genkey_result_t gpgme_op_genkey_result;
   158     gpgme_op_delete_t gpgme_op_delete;
   159     gpgme_op_import_t gpgme_op_import;
   160     gpgme_op_export_t gpgme_op_export;
   161     gpgme_set_keylist_mode_t gpgme_set_keylist_mode;
   162     gpgme_get_keylist_mode_t gpgme_get_keylist_mode;
   163     gpgme_op_keylist_start_t gpgme_op_keylist_start;
   164     gpgme_op_keylist_next_t gpgme_op_keylist_next;
   165     gpgme_op_keylist_end_t gpgme_op_keylist_end;
   166     gpgme_op_import_keys_t gpgme_op_import_keys;
   167     gpgme_key_ref_t gpgme_key_ref;
   168     gpgme_key_unref_t gpgme_key_unref;
   169 } pEpSession;
   170 
   171 static bool ensure_keyserver()
   172 {
   173     static char buf[MAX_LINELENGTH];
   174     int n;
   175     FILE *f = fopen(gpg_conf(), "r");
   176 
   177     if (f != NULL) {
   178         while (!feof(f)) {
   179             char * s = fgets(buf, MAX_LINELENGTH, f);
   180             if (s && !feof(f)) {
   181                 char * t = strtok(s, " ");
   182                 if (t && strcmp(t, "keyserver") == 0)
   183                 {
   184                     fclose(f);
   185                     return true;
   186                 }
   187             }
   188         }
   189         f = freopen(gpg_conf(), "a", f);
   190     }
   191     else {
   192         f = fopen(gpg_conf(), "w");
   193     }
   194 
   195     assert(f);
   196     if (f == NULL)
   197         return false;
   198 
   199     n = fprintf(f, "keyserver %s\n", DEFAULT_KEYSERVER);
   200     assert(n >= 0);
   201     fclose(f);
   202 
   203     return true;
   204 }
   205 
   206 DYNAMIC_API PEP_STATUS init(PEP_SESSION *session)
   207 {
   208 	gpgme_error_t gpgme_error;
   209 	int int_result;
   210 	const char *sql_log;
   211 	const char *sql_safeword;
   212 	const char *sql_get_identity;
   213 	const char *sql_set_person;
   214 	const char *sql_set_pgp_keypair;
   215 	const char *sql_set_identity;
   216 	const char *sql_set_trust;
   217     bool bResult;
   218 
   219 	assert(sqlite3_threadsafe());
   220 	if (!sqlite3_threadsafe())
   221 		return PEP_INIT_SQLITE3_WITHOUT_MUTEX;
   222 
   223 	assert(session);
   224 	*session = NULL;
   225 
   226     pEpSession *_session = (pEpSession *) calloc(1, sizeof(pEpSession));
   227 	assert(_session);
   228 	if (_session == NULL)
   229 		return PEP_OUT_OF_MEMORY;
   230 	
   231 	_session->version = PEP_ENGINE_VERSION;
   232 
   233     bResult = ensure_keyserver();
   234     assert(bResult);
   235 
   236     // to do: implement something useful
   237     _session->passphrase = "";
   238 
   239 	_session->gpgme = dlopen(LIBGPGME, RTLD_LAZY);
   240 	if (_session->gpgme == NULL) {
   241 		free(_session);
   242 		return PEP_INIT_CANNOT_LOAD_GPGME;
   243 	}
   244 
   245 	_session->gpgme_set_locale
   246         = (gpgme_set_locale_t) (intptr_t) dlsym(_session->gpgme,
   247                 "gpgme_set_locale");
   248 	assert(_session->gpgme_set_locale);
   249 
   250 	_session->gpgme_check
   251         = (gpgme_check_version_t) (intptr_t) dlsym(_session->gpgme,
   252                 "gpgme_check_version");
   253 	assert(_session->gpgme_check);
   254 
   255 	_session->gpgme_new
   256         = (gpgme_new_t) (intptr_t) dlsym(_session->gpgme, "gpgme_new");
   257 	assert(_session->gpgme_new);
   258 
   259 	_session->gpgme_release
   260         = (gpgme_release_t) (intptr_t) dlsym(_session->gpgme, "gpgme_release");
   261 	assert(_session->gpgme_release);
   262 
   263 	_session->gpgme_set_protocol
   264         = (gpgme_set_protocol_t) (intptr_t) dlsym(_session->gpgme,
   265                 "gpgme_set_protocol");
   266 	assert(_session->gpgme_set_protocol);
   267 
   268 	_session->gpgme_set_armor
   269         = (gpgme_set_armor_t) (intptr_t) dlsym(_session->gpgme,
   270                 "gpgme_set_armor");
   271 	assert(_session->gpgme_set_armor);
   272 
   273 	_session->gpgme_data_new
   274         = (gpgme_data_new_t) (intptr_t) dlsym(_session->gpgme,
   275                 "gpgme_data_new");
   276 	assert(_session->gpgme_data_new);
   277 
   278 	_session->gpgme_data_new_from_mem
   279         = (gpgme_data_new_from_mem_t) (intptr_t) dlsym(_session->gpgme,
   280                 "gpgme_data_new_from_mem");
   281 	assert(_session->gpgme_data_new_from_mem);
   282 
   283 	_session->gpgme_data_release
   284         = (gpgme_data_release_t) (intptr_t) dlsym(_session->gpgme,
   285                 "gpgme_data_release");
   286 	assert(_session->gpgme_data_release);
   287 
   288 	_session->gpgme_data_identify
   289         = (gpgme_data_identify_t) (intptr_t) dlsym(_session->gpgme,
   290                 "gpgme_data_identify");
   291 	assert(_session->gpgme_data_identify);
   292 
   293 	_session->gpgme_data_seek
   294         = (gpgme_data_seek_t) (intptr_t) dlsym(_session->gpgme,
   295                 "gpgme_data_seek");
   296 	assert(_session->gpgme_data_seek);
   297 
   298 	_session->gpgme_data_read
   299         = (gpgme_data_read_t) (intptr_t) dlsym(_session->gpgme,
   300                 "gpgme_data_read");
   301 	assert(_session->gpgme_data_read);
   302 
   303 	_session->gpgme_op_decrypt
   304         = (gpgme_op_decrypt_t) (intptr_t) dlsym(_session->gpgme,
   305                 "gpgme_op_decrypt");
   306 	assert(_session->gpgme_op_decrypt);
   307 
   308 	_session->gpgme_op_verify
   309         = (gpgme_op_verify_t) (intptr_t) dlsym(_session->gpgme,
   310                 "gpgme_op_verify");
   311 	assert(_session->gpgme_op_verify);
   312 
   313 	_session->gpgme_op_decrypt_verify
   314         = (gpgme_op_decrypt_verify_t) (intptr_t) dlsym(_session->gpgme,
   315                 "gpgme_op_decrypt_verify");
   316 	assert(_session->gpgme_op_decrypt_verify);
   317 
   318 	_session->gpgme_op_decrypt_result
   319         = (gpgme_op_decrypt_result_t) (intptr_t) dlsym(_session->gpgme,
   320                 "gpgme_op_decrypt_result");
   321 	assert(_session->gpgme_op_decrypt_result);
   322 
   323 	_session->gpgme_op_encrypt_sign
   324         = (gpgme_op_encrypt_sign_t) (intptr_t) dlsym(_session->gpgme,
   325                 "gpgme_op_encrypt_sign");
   326 	assert(_session->gpgme_op_encrypt_sign);
   327 
   328 	_session->gpgme_op_verify_result
   329         = (gpgme_op_verify_result_t) (intptr_t) dlsym(_session->gpgme,
   330                 "gpgme_op_verify_result");
   331 	assert(_session->gpgme_op_verify_result);
   332 	
   333 	_session->gpgme_get_key
   334         = (gpgme_get_key_t) (intptr_t) dlsym(_session->gpgme, "gpgme_get_key");
   335 	assert(_session->gpgme_get_key);
   336 
   337 	_session->gpgme_op_genkey
   338         = (gpgme_op_genkey_t) (intptr_t) dlsym(_session->gpgme,
   339                 "gpgme_op_genkey");
   340 	assert(_session->gpgme_op_genkey);
   341 
   342 	_session->gpgme_op_genkey_result
   343         = (gpgme_op_genkey_result_t) (intptr_t) dlsym(_session->gpgme,
   344                 "gpgme_op_genkey_result");
   345 	assert(_session->gpgme_op_genkey_result);
   346 
   347     _session->gpgme_op_delete = (gpgme_op_delete_t) (intptr_t)
   348         dlsym(_session->gpgme, "gpgme_op_delete");
   349 	assert(_session->gpgme_op_delete);
   350 
   351     _session->gpgme_op_import = (gpgme_op_import_t) (intptr_t)
   352         dlsym(_session->gpgme, "gpgme_op_import");
   353 	assert(_session->gpgme_op_import);
   354 
   355     _session->gpgme_op_export = (gpgme_op_export_t) (intptr_t)
   356         dlsym(_session->gpgme, "gpgme_op_export");
   357 	assert(_session->gpgme_op_export);
   358 
   359     _session->gpgme_set_keylist_mode = (gpgme_set_keylist_mode_t) (intptr_t)
   360         dlsym(_session->gpgme, "gpgme_set_keylist_mode");
   361 	assert(_session->gpgme_set_keylist_mode);
   362 
   363     _session->gpgme_get_keylist_mode = (gpgme_get_keylist_mode_t) (intptr_t)
   364         dlsym(_session->gpgme, "gpgme_get_keylist_mode");
   365 	assert(_session->gpgme_get_keylist_mode);
   366 
   367     _session->gpgme_op_keylist_start = (gpgme_op_keylist_start_t) (intptr_t)
   368         dlsym(_session->gpgme, "gpgme_op_keylist_start");
   369 	assert(_session->gpgme_op_keylist_start);
   370 
   371     _session->gpgme_op_keylist_next = (gpgme_op_keylist_next_t) (intptr_t)
   372         dlsym(_session->gpgme, "gpgme_op_keylist_next");
   373 	assert(_session->gpgme_op_keylist_next);
   374 
   375     _session->gpgme_op_keylist_end = (gpgme_op_keylist_end_t) (intptr_t)
   376         dlsym(_session->gpgme, "gpgme_op_keylist_end");
   377 	assert(_session->gpgme_op_keylist_end);
   378 
   379     _session->gpgme_op_import_keys = (gpgme_op_import_keys_t) (intptr_t)
   380         dlsym(_session->gpgme, "gpgme_op_import_keys");
   381 	assert(_session->gpgme_op_import_keys);
   382 
   383     _session->gpgme_key_ref = (gpgme_key_ref_t) (intptr_t)
   384         dlsym(_session->gpgme, "gpgme_key_ref");
   385 	assert(_session->gpgme_key_ref);
   386 
   387     _session->gpgme_key_unref = (gpgme_key_unref_t) (intptr_t)
   388         dlsym(_session->gpgme, "gpgme_key_unref");
   389 	assert(_session->gpgme_key_unref);
   390 
   391 	setlocale(LC_ALL, "");
   392 	_session->version = _session->gpgme_check(NULL);
   393 	_session->gpgme_set_locale(NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
   394 
   395 	gpgme_error = _session->gpgme_new(&_session->ctx);
   396 	if (gpgme_error != GPG_ERR_NO_ERROR) {
   397 		dlclose(_session->gpgme);
   398 		free(_session);
   399 		return PEP_INIT_GPGME_INIT_FAILED;
   400 	}
   401 
   402     gpgme_error = _session->gpgme_set_protocol(_session->ctx,
   403             GPGME_PROTOCOL_OpenPGP);
   404 	assert(gpgme_error == GPG_ERR_NO_ERROR);
   405 
   406 	_session->gpgme_set_armor(_session->ctx, 1);
   407 
   408     assert(LOCAL_DB);
   409     if (LOCAL_DB == NULL) {
   410 		_session->gpgme_release(_session->ctx);
   411 		dlclose(_session->gpgme);
   412         free(_session);
   413         return PEP_INIT_CANNOT_OPEN_DB;
   414     }
   415 
   416 	int_result = sqlite3_open_v2(
   417 			LOCAL_DB,
   418 			&_session->db,
   419 			SQLITE_OPEN_READWRITE
   420 				| SQLITE_OPEN_CREATE
   421 				| SQLITE_OPEN_FULLMUTEX
   422 				| SQLITE_OPEN_PRIVATECACHE,
   423 			NULL 
   424 		);
   425 
   426 	if (int_result != SQLITE_OK) {
   427 		sqlite3_close_v2(_session->db);
   428 		_session->gpgme_release(_session->ctx);
   429 		dlclose(_session->gpgme);
   430 		free(_session);
   431 		return PEP_INIT_CANNOT_OPEN_DB;
   432 	}
   433 
   434 	sqlite3_busy_timeout(_session->db, BUSY_WAIT_TIME);
   435 
   436     assert(SYSTEM_DB);
   437     if (SYSTEM_DB == NULL) {
   438 		sqlite3_close_v2(_session->db);
   439 		_session->gpgme_release(_session->ctx);
   440 		dlclose(_session->gpgme);
   441 		free(_session);
   442 		return PEP_INIT_CANNOT_OPEN_SYSTEM_DB;
   443     }
   444 
   445 	int_result = sqlite3_open_v2(
   446 			SYSTEM_DB, &_session->system_db,
   447 			SQLITE_OPEN_READONLY
   448 				| SQLITE_OPEN_FULLMUTEX
   449 				| SQLITE_OPEN_SHAREDCACHE,
   450 			NULL
   451 		);
   452 
   453 	if (int_result != SQLITE_OK) {
   454 		sqlite3_close_v2(_session->system_db);
   455 		sqlite3_close_v2(_session->db);
   456 		_session->gpgme_release(_session->ctx);
   457 		dlclose(_session->gpgme);
   458 		free(_session);
   459 		return PEP_INIT_CANNOT_OPEN_SYSTEM_DB;
   460 	}
   461 
   462 	sqlite3_busy_timeout(_session->system_db, 1000);
   463 
   464 	int_result = sqlite3_exec(
   465 		_session->db,
   466 			"create table if not exists version_info ("
   467 			"	id integer primary key,"
   468 			"	timestamp integer default (datetime('now')) ,"
   469 			"	version text,"
   470 			"	comment text"
   471 			");"
   472 			"create table if not exists log ("
   473 			"	timestamp integer default (datetime('now')) ,"
   474 			"	title text not null,"
   475 			"	entity text not null,"
   476 			"	description text,"
   477 			"	comment text"
   478 			");"
   479 			"create index if not exists log_timestamp on log ("
   480 			"	timestamp"
   481 			");"
   482 			"create table if not exists pgp_keypair ("
   483 			"	fpr text primary key,"
   484 			"	public_id text unique,"
   485 			"   private_id text,"
   486 			"	created integer,"
   487 			"	expires integer,"
   488 			"	comment text"
   489 			");"
   490             "create index if not exists pgp_keypair_expires on pgp_keypair ("
   491 			"	expires"
   492 			");"
   493 			"create table if not exists person ("
   494 			"	id text primary key,"
   495 			"	username text not null,"
   496 			"	main_key_id text"
   497 			"		references pgp_keypair (fpr)"
   498 			"		on delete set null,"
   499 			"   lang text,"
   500 			"	comment text"
   501 			");"
   502 			"create table if not exists identity ("
   503 			"	address text primary key,"
   504 			"	user_id text"
   505 			"		references person (id)"
   506 			"		on delete cascade,"
   507 			"	main_key_id text"
   508 			"		references pgp_keypair (fpr)"
   509 			"		on delete set null,"
   510 			"	comment text"
   511 			");"
   512             "create table if not exists trust ("
   513             "   user_id text not null"
   514             "       references person (id)"
   515 			"		on delete cascade,"
   516             "   pgp_keypair_fpr text not null"
   517             "       references pgp_keypair (fpr)"
   518             "       on delete cascade,"
   519             "   comm_type integer not null,"
   520 			"	comment text"
   521             ");"
   522             "create unique index if not exists trust_index on trust ("
   523             "   user_id,"
   524             "   pgp_keypair_fpr"
   525             ");",
   526 		NULL,
   527 		NULL,
   528 		NULL
   529 	);
   530 	assert(int_result == SQLITE_OK);
   531 
   532 	int_result = sqlite3_exec(
   533 		_session->db,
   534         "insert or replace into version_info (id, version) values (1, '1.0');",
   535 		NULL,
   536 		NULL,
   537 		NULL
   538 	);
   539 	assert(int_result == SQLITE_OK);
   540 
   541 	sql_log = "insert into log (title, entity, description, comment)"
   542 			  "values (?1, ?2, ?3, ?4);";
   543     int_result = sqlite3_prepare_v2(_session->db, sql_log, strlen(sql_log),
   544             &_session->log, NULL);
   545 	assert(int_result == SQLITE_OK);
   546 
   547 	sql_safeword = "select id, word from wordlist where lang = lower(?1)"
   548                    "and id = ?2 ;";
   549     int_result = sqlite3_prepare_v2(_session->system_db, sql_safeword,
   550             strlen(sql_safeword), &_session->safeword, NULL);
   551 	assert(int_result == SQLITE_OK);
   552 
   553 	sql_get_identity =	"select fpr, identity.user_id, username, comm_type, lang"
   554                         "   from identity"
   555 						"   join person on id = identity.user_id"
   556 						"   join pgp_keypair on fpr = identity.main_key_id"
   557                         "   join trust on id = trust.user_id"
   558                         "       and pgp_keypair_fpr = identity.main_key_id"
   559 						"   where address = ?1 ;";
   560 
   561     int_result = sqlite3_prepare_v2(_session->db, sql_get_identity,
   562             strlen(sql_get_identity), &_session->get_identity, NULL);
   563 	assert(int_result == SQLITE_OK);
   564 
   565 	sql_set_person = "insert or replace into person (id, username, lang)"
   566                      "values (?1, ?2, ?3) ;";
   567 	sql_set_pgp_keypair = "insert or replace into pgp_keypair (fpr)"
   568                           "values (?1) ;";
   569     sql_set_identity = "insert or replace into identity (address, main_key_id,"
   570                        "user_id) values (?1, ?2, ?3) ;";
   571     sql_set_trust = "insert or replace into trust (user_id, pgp_keypair_fpr, comm_type)"
   572                         "values (?1, ?2, ?3) ;";
   573 	
   574     int_result = sqlite3_prepare_v2(_session->db, sql_set_person,
   575             strlen(sql_set_person), &_session->set_person, NULL);
   576     assert(int_result == SQLITE_OK);
   577     int_result = sqlite3_prepare_v2(_session->db, sql_set_pgp_keypair,
   578             strlen(sql_set_pgp_keypair), &_session->set_pgp_keypair, NULL);
   579 	assert(int_result == SQLITE_OK);
   580     int_result = sqlite3_prepare_v2(_session->db, sql_set_identity,
   581             strlen(sql_set_identity), &_session->set_identity, NULL);
   582 	assert(int_result == SQLITE_OK);
   583     int_result = sqlite3_prepare_v2(_session->db, sql_set_trust,
   584             strlen(sql_set_trust), &_session->set_trust, NULL);
   585 	assert(int_result == SQLITE_OK);
   586 
   587 	sqlite3_reset(_session->log);
   588     sqlite3_bind_text(_session->log, 1, "init", -1, SQLITE_STATIC);
   589     sqlite3_bind_text(_session->log, 2, "pEp " PEP_ENGINE_VERSION, -1,
   590             SQLITE_STATIC);
   591 	do {
   592 		int_result = sqlite3_step(_session->log);
   593 		assert(int_result == SQLITE_DONE || int_result == SQLITE_BUSY);
   594 	} while (int_result == SQLITE_BUSY);
   595     sqlite3_reset(_session->log);
   596 
   597 	*session = (void *) _session;
   598 	return PEP_STATUS_OK;
   599 }
   600 
   601 DYNAMIC_API void release(PEP_SESSION session)
   602 {
   603 	assert(session);
   604 	pEpSession *_session = (pEpSession *) session;
   605 
   606 	if (_session) {
   607 		if (_session->db) {
   608 			sqlite3_finalize(_session->safeword);
   609 			sqlite3_finalize(_session->log);
   610 			sqlite3_finalize(_session->get_identity);
   611 			sqlite3_finalize(_session->set_identity);
   612 			sqlite3_close_v2(_session->db);
   613 			sqlite3_close_v2(_session->system_db);
   614 		}
   615 		if (_session->ctx)
   616 			_session->gpgme_release(_session->ctx);
   617 		dlclose(_session->gpgme);
   618 	}
   619 	free(_session);
   620 }
   621 
   622 stringlist_t *new_stringlist(const char *value)
   623 {
   624     stringlist_t *result = (stringlist_t *) calloc(1, sizeof(stringlist_t));
   625     if (result && value) {
   626         result->value = strdup(value);
   627         assert(result->value);
   628         if (result->value == 0) {
   629             free(result);
   630             return NULL;
   631         }
   632     }
   633     return result;
   634 }
   635 
   636 stringlist_t *stringlist_add(stringlist_t *stringlist, const char *value)
   637 {
   638     assert(value);
   639 
   640     if (stringlist == NULL)
   641         return new_stringlist(value);
   642 
   643     if (stringlist->next != NULL)
   644         return stringlist_add(stringlist->next, value);
   645 
   646     if (stringlist->value == NULL) {
   647         stringlist->value = strdup(value);
   648         assert(stringlist->value);
   649         if (stringlist->value == NULL)
   650             return NULL;
   651         return stringlist;
   652     }
   653 
   654     stringlist->next = new_stringlist(value);
   655     assert(stringlist->next);
   656     if (stringlist->next == NULL)
   657         return NULL;
   658 
   659     return stringlist->next;
   660 }
   661 
   662 int stringlist_length(const stringlist_t *stringlist)
   663 {
   664     int len = 1;
   665     stringlist_t *_stringlist;
   666 
   667     assert(stringlist);
   668 
   669     if (stringlist->value == NULL)
   670         return 0;
   671 
   672     for (_stringlist=stringlist->next; _stringlist!=NULL; _stringlist=_stringlist->next)
   673         len += 1;
   674 
   675     return len;
   676 }
   677 
   678 void free_stringlist(stringlist_t *stringlist)
   679 {
   680     if (stringlist) {
   681         free_stringlist(stringlist->next);
   682         free(stringlist->value);
   683         free(stringlist);
   684     }
   685 }
   686 
   687 DYNAMIC_API PEP_STATUS decrypt_and_verify(
   688         PEP_SESSION session, const char *ctext, size_t csize,
   689         char **ptext, size_t *psize, stringlist_t **keylist
   690     )
   691 {
   692 	pEpSession *_session = (pEpSession *) session;
   693 
   694 	PEP_STATUS result;
   695 	gpgme_error_t gpgme_error;
   696 	gpgme_data_t cipher, plain;
   697 	gpgme_data_type_t dt;
   698 
   699 	stringlist_t *_keylist = NULL;
   700 	int i_key = 0;
   701 
   702 	assert(_session);
   703 	assert(ctext);
   704 	assert(csize);
   705 	assert(ptext);
   706 	assert(psize);
   707 	assert(keylist);
   708 
   709 	*ptext = NULL;
   710 	*psize = 0;
   711 	*keylist = NULL;
   712 
   713     gpgme_error = _session->gpgme_data_new_from_mem(&cipher, ctext, csize, 0);
   714 	assert(gpgme_error == GPG_ERR_NO_ERROR);
   715 	if (gpgme_error != GPG_ERR_NO_ERROR) {
   716 		if (gpgme_error == GPG_ERR_ENOMEM)
   717 			return PEP_OUT_OF_MEMORY;
   718 		else
   719 			return PEP_UNKNOWN_ERROR;
   720 	}
   721 
   722 	gpgme_error = _session->gpgme_data_new(&plain);
   723 	assert(gpgme_error == GPG_ERR_NO_ERROR);
   724 	if (gpgme_error != GPG_ERR_NO_ERROR) {
   725 		_session->gpgme_data_release(cipher);
   726 		if (gpgme_error == GPG_ERR_ENOMEM)
   727 			return PEP_OUT_OF_MEMORY;
   728 		else
   729 			return PEP_UNKNOWN_ERROR;
   730 	}
   731 
   732 	dt = _session->gpgme_data_identify(cipher);
   733 	switch (dt) {
   734 	case GPGME_DATA_TYPE_PGP_SIGNED:
   735 	case GPGME_DATA_TYPE_PGP_OTHER:
   736         gpgme_error = _session->gpgme_op_decrypt_verify(_session->ctx, cipher,
   737                 plain);
   738 		assert(gpgme_error != GPG_ERR_INV_VALUE);
   739 		assert(gpgme_error != GPG_ERR_NO_DATA);
   740 
   741 		switch (gpgme_error) {
   742 		case GPG_ERR_NO_ERROR:
   743 			{
   744 				gpgme_verify_result_t gpgme_verify_result;
   745                 char *_buffer = NULL;
   746 				size_t reading;
   747                 size_t length = _session->gpgme_data_seek(plain, 0, SEEK_END);
   748                 gpgme_signature_t gpgme_signature;
   749 
   750 				assert(length != -1);
   751 				_session->gpgme_data_seek(plain, 0, SEEK_SET);
   752 
   753 				// TODO: make things less memory consuming
   754                 // the following algorithm allocates memory for the complete
   755                 // text
   756 
   757                 _buffer = malloc(length + 1);
   758                 assert(_buffer);
   759                 if (_buffer == NULL) {
   760                     _session->gpgme_data_release(plain);
   761                     _session->gpgme_data_release(cipher);
   762                     return PEP_OUT_OF_MEMORY;
   763                 }
   764 
   765                 reading = _session->gpgme_data_read(plain, _buffer, length);
   766 				assert(length == reading);
   767 
   768                 gpgme_verify_result =
   769                     _session->gpgme_op_verify_result(_session->ctx);
   770 				assert(gpgme_verify_result);
   771                 gpgme_signature = gpgme_verify_result->signatures;
   772 
   773 				if (gpgme_signature) {
   774                     stringlist_t *k;
   775                     _keylist = new_stringlist(NULL);
   776                     assert(_keylist);
   777                     if (_keylist == NULL) {
   778 						_session->gpgme_data_release(plain);
   779 						_session->gpgme_data_release(cipher);
   780                         free(_buffer);
   781                         return PEP_OUT_OF_MEMORY;
   782                     }
   783                     k = _keylist;
   784 
   785                     result = PEP_DECRYPTED_AND_VERIFIED;
   786 					do {
   787                         switch (gpgme_signature->status) {
   788                         case GPG_ERR_NO_ERROR:
   789                             k = stringlist_add(k, gpgme_signature->fpr);
   790                             break;
   791                         case GPG_ERR_CERT_REVOKED:
   792                         case GPG_ERR_BAD_SIGNATURE:
   793                             result = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
   794                             break;
   795                         case GPG_ERR_SIG_EXPIRED:
   796                         case GPG_ERR_KEY_EXPIRED:
   797                         case GPG_ERR_NO_PUBKEY:
   798                             k = stringlist_add(k, gpgme_signature->fpr);
   799                             if (result == PEP_DECRYPTED_AND_VERIFIED)
   800                                 result = PEP_DECRYPTED;
   801                             break;
   802                         case GPG_ERR_GENERAL:
   803                             break;
   804                         default:
   805                             if (result == PEP_DECRYPTED_AND_VERIFIED)
   806                                 result = PEP_DECRYPTED;
   807                             break;
   808                         }
   809 					} while ((gpgme_signature = gpgme_signature->next));
   810 				} else {
   811 					result = PEP_DECRYPTED;
   812 				}
   813 
   814 				if (result == PEP_DECRYPTED_AND_VERIFIED
   815                         || result == PEP_DECRYPTED) {
   816 					*ptext = _buffer;
   817 					*psize = reading;
   818                     (*ptext)[*psize] = 0; // safeguard for naive users
   819 					*keylist = _keylist;
   820 				}
   821                 else {
   822                     free_stringlist(_keylist);
   823                     free(_buffer);
   824 	            }
   825 				break;
   826 			}
   827 		case GPG_ERR_DECRYPT_FAILED:
   828 			result = PEP_DECRYPT_WRONG_FORMAT;
   829 			break;
   830 		case GPG_ERR_BAD_PASSPHRASE:
   831 			NOT_IMPLEMENTED;
   832 		default:
   833 			result = PEP_CANNOT_DECRYPT_UNKNOWN;
   834 		}
   835 		break;
   836 
   837 	default:
   838 		result = PEP_DECRYPT_WRONG_FORMAT;
   839 	}
   840 
   841 	_session->gpgme_data_release(plain);
   842 	_session->gpgme_data_release(cipher);
   843 	return result;
   844 }
   845 
   846 DYNAMIC_API PEP_STATUS verify_text(
   847         PEP_SESSION session, const char *text, size_t size,
   848         const char *signature, size_t sig_size, stringlist_t **keylist
   849     )
   850 {
   851 	pEpSession *_session = (pEpSession *) session;
   852 
   853 	PEP_STATUS result;
   854 	gpgme_error_t gpgme_error;
   855 	gpgme_data_t d_text, d_sig;
   856     stringlist_t *_keylist;
   857 
   858     assert(session);
   859     assert(text);
   860     assert(size);
   861     assert(signature);
   862     assert(sig_size);
   863     assert(keylist);
   864 
   865     *keylist = NULL;
   866 
   867     gpgme_error = _session->gpgme_data_new_from_mem(&d_text, text, size, 0);
   868 	assert(gpgme_error == GPG_ERR_NO_ERROR);
   869 	if (gpgme_error != GPG_ERR_NO_ERROR) {
   870 		if (gpgme_error == GPG_ERR_ENOMEM)
   871 			return PEP_OUT_OF_MEMORY;
   872 		else
   873 			return PEP_UNKNOWN_ERROR;
   874 	}
   875 
   876     gpgme_error = _session->gpgme_data_new_from_mem(&d_sig, signature, sig_size, 0);
   877 	assert(gpgme_error == GPG_ERR_NO_ERROR);
   878 	if (gpgme_error != GPG_ERR_NO_ERROR) {
   879 		_session->gpgme_data_release(d_text);
   880 		if (gpgme_error == GPG_ERR_ENOMEM)
   881 			return PEP_OUT_OF_MEMORY;
   882 		else
   883 			return PEP_UNKNOWN_ERROR;
   884 	}
   885 
   886     gpgme_error = _session->gpgme_op_verify(_session->ctx, d_sig, d_text, NULL);
   887     assert(gpgme_error != GPG_ERR_INV_VALUE);
   888 
   889     switch (gpgme_error) {
   890     case GPG_ERR_NO_ERROR:
   891         {
   892             gpgme_verify_result_t gpgme_verify_result;
   893             gpgme_signature_t gpgme_signature;
   894 
   895             gpgme_verify_result =
   896                 _session->gpgme_op_verify_result(_session->ctx);
   897             assert(gpgme_verify_result);
   898             gpgme_signature = gpgme_verify_result->signatures;
   899 
   900             if (gpgme_signature) {
   901                 stringlist_t *k;
   902                 _keylist = new_stringlist(NULL);
   903                 assert(_keylist);
   904                 if (_keylist == NULL) {
   905                     _session->gpgme_data_release(d_text);
   906                     _session->gpgme_data_release(d_sig);
   907                     return PEP_OUT_OF_MEMORY;
   908                 }
   909                 k = _keylist;
   910 
   911                 result = PEP_VERIFIED;
   912                 do {
   913                     k = stringlist_add(k, gpgme_signature->fpr);
   914                     if (k == NULL) {
   915                         free_stringlist(_keylist);
   916                         _session->gpgme_data_release(d_text);
   917                         _session->gpgme_data_release(d_sig);
   918                         return PEP_OUT_OF_MEMORY;
   919                     }
   920                     if (gpgme_signature->summary & GPGME_SIGSUM_RED) {
   921                         if (gpgme_signature->summary & GPGME_SIGSUM_KEY_EXPIRED
   922                                 || gpgme_signature->summary & GPGME_SIGSUM_SIG_EXPIRED) {
   923                             if (result == PEP_VERIFIED
   924                                     || result == PEP_VERIFIED_AND_TRUSTED)
   925                                 result = PEP_UNENCRYPTED;
   926                         }
   927                         else {
   928                             result = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
   929                             break;
   930                         }
   931                     }
   932                     else {
   933                         if (gpgme_signature->summary & GPGME_SIGSUM_VALID) {
   934                             if (result == PEP_VERIFIED)
   935                                 result = PEP_VERIFIED_AND_TRUSTED;
   936                         }
   937                         if (gpgme_signature->summary & GPGME_SIGSUM_GREEN) {
   938                             // good
   939                         }
   940                         else if (gpgme_signature->summary & GPGME_SIGSUM_KEY_MISSING) {
   941                             result = PEP_VERIFY_NO_KEY;
   942                         }
   943                         else if (gpgme_signature->summary & GPGME_SIGSUM_SYS_ERROR) {
   944                             if (result == PEP_VERIFIED
   945                                     || result == PEP_VERIFIED_AND_TRUSTED)
   946                                 result = PEP_UNENCRYPTED;
   947                         }
   948                         else {
   949                             // do nothing
   950                         }
   951                     }
   952                 } while ((gpgme_signature = gpgme_signature->next));
   953                 *keylist = _keylist;
   954             } else {
   955                 result = PEP_UNENCRYPTED;
   956             }
   957             break;
   958         }
   959         break;
   960     case GPG_ERR_NO_DATA:
   961         result = PEP_DECRYPT_WRONG_FORMAT;
   962         break;
   963     case GPG_ERR_INV_VALUE:
   964     default:
   965         result = PEP_UNKNOWN_ERROR;
   966         break;
   967     }
   968 
   969     _session->gpgme_data_release(d_text);
   970     _session->gpgme_data_release(d_sig);
   971 
   972     return result;
   973 }
   974 
   975 DYNAMIC_API PEP_STATUS encrypt_and_sign(
   976         PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
   977         size_t psize, char **ctext, size_t *csize
   978     )
   979 {
   980 	pEpSession *_session = (pEpSession *) session;
   981 
   982 	PEP_STATUS result;
   983 	gpgme_error_t gpgme_error;
   984 	gpgme_data_t plain, cipher;
   985 	gpgme_key_t *rcpt;
   986 	gpgme_encrypt_flags_t flags;
   987 	const stringlist_t *_keylist;
   988     int i, j;
   989 
   990 	assert(_session);
   991 	assert(keylist);
   992 	assert(ptext);
   993 	assert(psize);
   994 	assert(ctext);
   995 	assert(csize);
   996 
   997 	*ctext = NULL;
   998 	*csize = 0;
   999 
  1000     gpgme_error = _session->gpgme_data_new_from_mem(&plain, ptext, psize, 0);
  1001 	assert(gpgme_error == GPG_ERR_NO_ERROR);
  1002 	if (gpgme_error != GPG_ERR_NO_ERROR) {
  1003 		if (gpgme_error == GPG_ERR_ENOMEM)
  1004 			return PEP_OUT_OF_MEMORY;
  1005 		else
  1006 			return PEP_UNKNOWN_ERROR;
  1007 	}
  1008 
  1009 	gpgme_error = _session->gpgme_data_new(&cipher);
  1010 	assert(gpgme_error == GPG_ERR_NO_ERROR);
  1011 	if (gpgme_error != GPG_ERR_NO_ERROR) {
  1012 		_session->gpgme_data_release(plain);
  1013 		if (gpgme_error == GPG_ERR_ENOMEM)
  1014 			return PEP_OUT_OF_MEMORY;
  1015 		else
  1016 			return PEP_UNKNOWN_ERROR;
  1017 	}
  1018 
  1019     rcpt = (gpgme_key_t *) calloc(stringlist_length(keylist) + 1,
  1020             sizeof(gpgme_key_t));
  1021 	assert(rcpt);
  1022 	if (rcpt == NULL) {
  1023 		_session->gpgme_data_release(plain);
  1024 		_session->gpgme_data_release(cipher);
  1025 		return PEP_OUT_OF_MEMORY;
  1026 	}
  1027 
  1028     for (_keylist=keylist, i=0; _keylist!=NULL; _keylist=_keylist->next, i++) {
  1029 		assert(_keylist->value);
  1030         gpgme_error = _session->gpgme_get_key(_session->ctx, _keylist->value,
  1031                 &rcpt[i], 0);
  1032 		assert(gpgme_error != GPG_ERR_ENOMEM);
  1033 
  1034 		switch (gpgme_error) {
  1035 		case GPG_ERR_ENOMEM:
  1036             for (j=0; j<i; j++)
  1037                 _session->gpgme_key_unref(rcpt[j]);
  1038 			free(rcpt);
  1039 			_session->gpgme_data_release(plain);
  1040 			_session->gpgme_data_release(cipher);
  1041 			return PEP_OUT_OF_MEMORY;
  1042 		case GPG_ERR_NO_ERROR:
  1043 			break;
  1044 		case GPG_ERR_EOF:
  1045             for (j=0; j<i; j++)
  1046                 _session->gpgme_key_unref(rcpt[j]);
  1047 			free(rcpt);
  1048 			_session->gpgme_data_release(plain);
  1049 			_session->gpgme_data_release(cipher);
  1050 			return PEP_KEY_NOT_FOUND;
  1051 		case GPG_ERR_AMBIGUOUS_NAME:
  1052             for (j=0; j<i; j++)
  1053                 _session->gpgme_key_unref(rcpt[j]);
  1054 			free(rcpt);
  1055 			_session->gpgme_data_release(plain);
  1056 			_session->gpgme_data_release(cipher);
  1057 			return PEP_KEY_HAS_AMBIG_NAME;
  1058         default: // GPG_ERR_INV_VALUE if CTX or R_KEY is not a valid pointer or
  1059                  // FPR is not a fingerprint or key ID
  1060             for (j=0; j<i; j++)
  1061                 _session->gpgme_key_unref(rcpt[j]);
  1062 			free(rcpt);
  1063 			_session->gpgme_data_release(plain);
  1064 			_session->gpgme_data_release(cipher);
  1065 			return PEP_GET_KEY_FAILED;
  1066 		}
  1067 	}
  1068 
  1069 	// TODO: remove that and replace with proper key management
  1070 	flags  = GPGME_ENCRYPT_ALWAYS_TRUST;
  1071 
  1072     gpgme_error = _session->gpgme_op_encrypt_sign(_session->ctx, rcpt, flags,
  1073             plain, cipher);
  1074 	switch (gpgme_error) {
  1075 	case GPG_ERR_NO_ERROR:
  1076 		{
  1077             char *_buffer = NULL;
  1078 			size_t reading;
  1079             size_t length = _session->gpgme_data_seek(cipher, 0, SEEK_END);
  1080             assert(length != -1);
  1081 			_session->gpgme_data_seek(cipher, 0, SEEK_SET);
  1082 
  1083 			// TODO: make things less memory consuming
  1084             // the following algorithm allocates a buffer for the complete text
  1085 
  1086             _buffer = (char *) malloc(length + 1);
  1087             assert(_buffer);
  1088             if (_buffer == NULL) {
  1089                 for (j=0; j<stringlist_length(keylist); j++)
  1090                     _session->gpgme_key_unref(rcpt[j]);
  1091                 free(rcpt);
  1092                 _session->gpgme_data_release(plain);
  1093                 _session->gpgme_data_release(cipher);
  1094                 return PEP_OUT_OF_MEMORY;
  1095             }
  1096 
  1097             reading = _session->gpgme_data_read(cipher, _buffer, length);
  1098 			assert(length == reading);
  1099 
  1100 			*ctext = _buffer;
  1101 			*csize = reading;
  1102 			(*ctext)[*csize] = 0; // safeguard for naive users
  1103 			result = PEP_STATUS_OK;
  1104 			break;
  1105 		}
  1106 	default:
  1107 		result = PEP_UNKNOWN_ERROR;
  1108 	}
  1109 
  1110     for (j=0; j<stringlist_length(keylist); j++)
  1111         _session->gpgme_key_unref(rcpt[j]);
  1112 	free(rcpt);
  1113 	_session->gpgme_data_release(plain);
  1114 	_session->gpgme_data_release(cipher);
  1115 	return result;
  1116 }
  1117 
  1118 DYNAMIC_API PEP_STATUS log_event(
  1119         PEP_SESSION session, const char *title, const char *entity,
  1120         const char *description, const char *comment
  1121     )
  1122 {
  1123 	pEpSession *_session = (pEpSession *) session;
  1124 	PEP_STATUS status = PEP_STATUS_OK;
  1125 	int result;
  1126 
  1127 	assert(_session);
  1128 	assert(title);
  1129 	assert(entity);
  1130 
  1131 	sqlite3_reset(_session->log);
  1132 	sqlite3_bind_text(_session->log, 1, title, -1, SQLITE_STATIC);
  1133 	sqlite3_bind_text(_session->log, 2, entity, -1, SQLITE_STATIC);
  1134 	if (description)
  1135         sqlite3_bind_text(_session->log, 3, description, -1, SQLITE_STATIC);
  1136 	else
  1137 		sqlite3_bind_null(_session->log, 3);
  1138 	if (comment)
  1139 		sqlite3_bind_text(_session->log, 4, comment, -1, SQLITE_STATIC);
  1140 	else
  1141 		sqlite3_bind_null(_session->log, 4);
  1142 	do {
  1143 		result = sqlite3_step(_session->log);
  1144 		assert(result == SQLITE_DONE || result == SQLITE_BUSY);
  1145 		if (result != SQLITE_DONE && result != SQLITE_BUSY)
  1146 			status = PEP_UNKNOWN_ERROR;
  1147 	} while (result == SQLITE_BUSY);
  1148 	sqlite3_reset(_session->log);
  1149 
  1150 	return status;
  1151 }
  1152 
  1153 DYNAMIC_API PEP_STATUS safeword(
  1154             PEP_SESSION session, uint16_t value, const char *lang,
  1155             char **word, size_t *wsize
  1156         )
  1157 {
  1158 	pEpSession *_session = (pEpSession *) session;
  1159 	PEP_STATUS status = PEP_STATUS_OK;
  1160 	int result;
  1161 
  1162 	assert(_session);
  1163 	assert(word);
  1164 	assert(wsize);
  1165 
  1166 	*word = NULL;
  1167 	*wsize = 0;
  1168 
  1169 	if (lang == NULL)
  1170 		lang = "en";
  1171 
  1172 	assert((lang[0] >= 'A' && lang[0] <= 'Z')
  1173             || (lang[0] >= 'a' && lang[0] <= 'z'));
  1174 	assert((lang[1] >= 'A' && lang[1] <= 'Z')
  1175             || (lang[1] >= 'a' && lang[1] <= 'z'));
  1176 	assert(lang[2] == 0);
  1177 
  1178 	sqlite3_reset(_session->safeword);
  1179     sqlite3_bind_text(_session->safeword, 1, lang, -1, SQLITE_STATIC);
  1180 	sqlite3_bind_int(_session->safeword, 2, value);
  1181 
  1182 	result = sqlite3_step(_session->safeword);
  1183 	if (result == SQLITE_ROW) {
  1184         *word = strdup((const char *) sqlite3_column_text(_session->safeword,
  1185                     1));
  1186 		if (*word)
  1187             *wsize = sqlite3_column_bytes(_session->safeword, 1);
  1188 		else
  1189 			status = PEP_SAFEWORD_NOT_FOUND;
  1190 	} else
  1191 		status = PEP_SAFEWORD_NOT_FOUND;
  1192 
  1193 	sqlite3_reset(_session->safeword);
  1194 	return status;
  1195 }
  1196 
  1197 DYNAMIC_API PEP_STATUS safewords(
  1198         PEP_SESSION session, const char *fingerprint, const char *lang,
  1199         char **words, size_t *wsize, int max_words
  1200     )
  1201 {
  1202 	const char *source = fingerprint;
  1203 	char *buffer = calloc(1, MAX_SAFEWORDS_SPACE);
  1204 	char *dest = buffer;
  1205 	size_t fsize;
  1206     PEP_STATUS _status;
  1207 
  1208 	assert(session);
  1209 	assert(fingerprint);
  1210 	assert(words);
  1211 	assert(wsize);
  1212 	assert(max_words >= 0);
  1213 
  1214 	*words = NULL;
  1215 	*wsize = 0;
  1216 
  1217     assert(buffer);
  1218     if (buffer == NULL)
  1219         return PEP_OUT_OF_MEMORY;
  1220 
  1221 	fsize = strlen(fingerprint);
  1222 
  1223 	if (lang == NULL)
  1224 		lang = "en";
  1225 
  1226 	assert((lang[0] >= 'A' && lang[0] <= 'Z')
  1227             || (lang[0] >= 'a' && lang[0] <= 'z'));
  1228 	assert((lang[1] >= 'A' && lang[1] <= 'Z')
  1229             || (lang[1] >= 'a' && lang[1] <= 'z'));
  1230 	assert(lang[2] == 0);
  1231 
  1232 	int n_words = 0;
  1233 	while (source < fingerprint + fsize) {
  1234 		uint16_t value;
  1235 		char *word;
  1236 		size_t _wsize;
  1237 		int j;
  1238 
  1239         for (value=0, j=0; j < 4 && source < fingerprint + fsize; ) {
  1240 			if (*source >= 'a' && *source <= 'f')
  1241 				value += (*source - 'a' + 10) << (3 - j++) * 4;
  1242 			else if (*source >= 'A' && *source <= 'F')
  1243 				value += (*source - 'A' + 10) << (3 - j++) * 4;
  1244 			else if (*source >= '0' && *source <= '9')
  1245 				value += (*source - '0') << (3 - j++) * 4;
  1246 			
  1247 			source++;
  1248 		}
  1249 
  1250 		_status = safeword(session, value, lang, &word, &_wsize);
  1251         if (_status == PEP_OUT_OF_MEMORY) {
  1252             free(buffer);
  1253             return PEP_OUT_OF_MEMORY;
  1254         }
  1255 		if (word == NULL) {
  1256             free(buffer);
  1257 			return PEP_SAFEWORD_NOT_FOUND;
  1258         }
  1259 
  1260 		if (dest + _wsize < buffer + MAX_SAFEWORDS_SPACE - 1) {
  1261 			strncpy(dest, word, _wsize);
  1262             free(word);
  1263 			dest += _wsize;
  1264 		}
  1265 		else {
  1266             free(word);
  1267 			break; // buffer full
  1268         }
  1269 
  1270 		if (source < fingerprint + fsize
  1271                 && dest + _wsize < buffer + MAX_SAFEWORDS_SPACE - 1)
  1272 			*dest++ = ' ';
  1273 
  1274 		++n_words;
  1275 		if (max_words && n_words >= max_words)
  1276 			break;
  1277 	}
  1278 
  1279 	*words = buffer;
  1280 	*wsize = dest - buffer;
  1281 	return PEP_STATUS_OK;
  1282 }
  1283 
  1284 pEp_identity *new_identity(
  1285         const char *address, const char *fpr, const char *user_id,
  1286         const char *username
  1287     )
  1288 {
  1289     pEp_identity *result = calloc(1, sizeof(pEp_identity));
  1290     assert(result);
  1291     if (result) {
  1292         if (address) {
  1293             result->address = strdup(address);
  1294             assert(result->address);
  1295             if (result->address == NULL) {
  1296                 free(result);
  1297                 return NULL;
  1298             }
  1299             result->address_size = strlen(address);
  1300         }
  1301         if (fpr) {
  1302             result->fpr = strdup(fpr);
  1303             assert(result->fpr);
  1304             if (result->fpr == NULL) {
  1305                 free_identity(result);
  1306                 return NULL;
  1307             }
  1308             result->fpr_size = strlen(fpr);
  1309         }
  1310         if (user_id) {
  1311             result->user_id = strdup(user_id);
  1312             assert(result->user_id);
  1313             if (result->user_id == NULL) {
  1314                 free_identity(result);
  1315                 return NULL;
  1316             }
  1317             result->user_id_size = strlen(user_id);
  1318         }
  1319         if (username) {
  1320             result->username = strdup(username);
  1321             assert(result->username);
  1322             if (result->username == NULL) {
  1323                 free_identity(result);
  1324                 return NULL;
  1325             }
  1326             result->username_size = strlen(username);
  1327         }
  1328         result->struct_size = sizeof(pEp_identity);
  1329     }
  1330     return result;
  1331 }
  1332 
  1333 void free_identity(pEp_identity *identity)
  1334 {
  1335     if (identity) {
  1336         free(identity->address);
  1337         free(identity->fpr);
  1338         free(identity->user_id);
  1339         free(identity->username);
  1340         free(identity);
  1341     }
  1342 }
  1343 
  1344 DYNAMIC_API PEP_STATUS get_identity(
  1345         PEP_SESSION session, const char *address,
  1346         pEp_identity **identity
  1347     )
  1348 {
  1349 	pEpSession *_session = (pEpSession *) session;
  1350 	PEP_STATUS status = PEP_STATUS_OK;
  1351 	static pEp_identity *_identity;
  1352 	int result;
  1353 	const char *_lang;
  1354 
  1355 	assert(session);
  1356 	assert(address);
  1357 
  1358     sqlite3_reset(_session->get_identity);
  1359     sqlite3_bind_text(_session->get_identity, 1, address, -1, SQLITE_STATIC);
  1360 
  1361     result = sqlite3_step(_session->get_identity);
  1362 	switch (result) {
  1363 	case SQLITE_ROW:
  1364         _identity = new_identity(
  1365                 address,
  1366                 (const char *) sqlite3_column_text(_session->get_identity, 0),
  1367                 (const char *) sqlite3_column_text(_session->get_identity, 1),
  1368                 (const char *) sqlite3_column_text(_session->get_identity, 2)
  1369                 );
  1370         assert(_identity);
  1371         if (_identity == NULL)
  1372             return PEP_OUT_OF_MEMORY;
  1373 
  1374         _identity->comm_type = (PEP_comm_type) sqlite3_column_int(_session->get_identity, 3);
  1375         _lang = (const char *) sqlite3_column_text(_session->get_identity, 4);
  1376         if (_lang && _lang[0]) {
  1377 			assert(_lang[0] >= 'a' && _lang[0] <= 'z');
  1378 			assert(_lang[1] >= 'a' && _lang[1] <= 'z');
  1379 			assert(_lang[2] == 0);
  1380 			_identity->lang[0] = _lang[0];
  1381 			_identity->lang[1] = _lang[1];
  1382             _identity->lang[2] = 0;
  1383 		}
  1384 		*identity = _identity;
  1385 		break;
  1386 	default:
  1387         status = PEP_CANNOT_FIND_IDENTITY;
  1388 		*identity = NULL;
  1389 	}
  1390 
  1391     sqlite3_reset(_session->get_identity);
  1392 	return status;
  1393 }
  1394 
  1395 DYNAMIC_API PEP_STATUS set_identity(
  1396         PEP_SESSION session, const pEp_identity *identity
  1397     )
  1398 {
  1399 	pEpSession *_session = (pEpSession *) session;
  1400 	int result;
  1401 
  1402 	assert(session);
  1403 	assert(identity);
  1404 	assert(identity->address);
  1405 	assert(identity->fpr);
  1406 	assert(identity->user_id);
  1407 	assert(identity->username);
  1408 
  1409 	sqlite3_exec(_session->db, "BEGIN ;", NULL, NULL, NULL);
  1410 
  1411 	sqlite3_reset(_session->set_person);
  1412     sqlite3_bind_text(_session->set_person, 1, identity->user_id, -1,
  1413             SQLITE_STATIC);
  1414     sqlite3_bind_text(_session->set_person, 2, identity->username, -1,
  1415             SQLITE_STATIC);
  1416 	if (identity->lang[0])
  1417         sqlite3_bind_text(_session->set_person, 3, identity->lang, 1,
  1418                 SQLITE_STATIC);
  1419 	else
  1420 		sqlite3_bind_null(_session->set_person, 3);
  1421 	result = sqlite3_step(_session->set_person);
  1422 	sqlite3_reset(_session->set_person);
  1423 	if (result != SQLITE_DONE) {
  1424 		sqlite3_exec(_session->db, "ROLLBACK ;", NULL, NULL, NULL);
  1425 		return PEP_CANNOT_SET_PERSON;
  1426 	}
  1427 
  1428 	sqlite3_reset(_session->set_pgp_keypair);
  1429     sqlite3_bind_text(_session->set_pgp_keypair, 1, identity->fpr, -1,
  1430             SQLITE_STATIC);
  1431 	result = sqlite3_step(_session->set_pgp_keypair);
  1432 	sqlite3_reset(_session->set_pgp_keypair);
  1433 	if (result != SQLITE_DONE) {
  1434 		sqlite3_exec(_session->db, "ROLLBACK ;", NULL, NULL, NULL);
  1435 		return PEP_CANNOT_SET_PGP_KEYPAIR;
  1436 	}
  1437 
  1438 	sqlite3_reset(_session->set_identity);
  1439     sqlite3_bind_text(_session->set_identity, 1, identity->address, -1,
  1440             SQLITE_STATIC);
  1441     sqlite3_bind_text(_session->set_identity, 2, identity->fpr, -1,
  1442             SQLITE_STATIC);
  1443     sqlite3_bind_text(_session->set_identity, 3, identity->user_id, -1,
  1444             SQLITE_STATIC);
  1445 	result = sqlite3_step(_session->set_identity);
  1446 	sqlite3_reset(_session->set_identity);
  1447 	if (result != SQLITE_DONE) {
  1448 		sqlite3_exec(_session->db, "ROLLBACK ;", NULL, NULL, NULL);
  1449 		return PEP_CANNOT_SET_IDENTITY;
  1450 	}
  1451 
  1452 	sqlite3_reset(_session->set_trust);
  1453     sqlite3_bind_text(_session->set_trust, 1, identity->user_id, -1,
  1454             SQLITE_STATIC);
  1455     sqlite3_bind_text(_session->set_trust, 2, identity->fpr, -1,
  1456             SQLITE_STATIC);
  1457 	sqlite3_bind_int(_session->set_trust, 3, identity->comm_type);
  1458 	result = sqlite3_step(_session->set_trust);
  1459 	sqlite3_reset(_session->set_trust);
  1460 	if (result != SQLITE_DONE) {
  1461 		sqlite3_exec(_session->db, "ROLLBACK ;", NULL, NULL, NULL);
  1462 		return PEP_CANNOT_SET_IDENTITY;
  1463 	}
  1464 
  1465     result = sqlite3_exec(_session->db, "COMMIT ;", NULL, NULL, NULL);
  1466 	if (result == SQLITE_OK)
  1467 		return PEP_STATUS_OK;
  1468 	else
  1469 		return PEP_COMMIT_FAILED;
  1470 }
  1471 
  1472 DYNAMIC_API PEP_STATUS generate_keypair(
  1473         PEP_SESSION session, pEp_identity *identity
  1474     )
  1475 {
  1476 	pEpSession *_session = (pEpSession *) session;
  1477 	gpgme_error_t gpgme_error;
  1478     char *parms;
  1479     const char *template =
  1480         "<GnupgKeyParms format=\"internal\">\n"
  1481         "Key-Type: RSA\n"
  1482         "Key-Length: 4096\n"
  1483         "Name-Real: %s\n"
  1484         "Name-Email: %s\n"
  1485         /* "Passphrase: %s\n" */
  1486         "Expire-Date: 1y\n"
  1487         "</GnupgKeyParms>\n";
  1488     int result;
  1489     gpgme_genkey_result_t gpgme_genkey_result;
  1490 
  1491     assert(session);
  1492     assert(identity);
  1493     assert(identity->address);
  1494     assert(identity->fpr == NULL);
  1495     assert(identity->username);
  1496     
  1497     parms = calloc(1, PARMS_MAX);
  1498     assert(parms);
  1499     if (parms == NULL)
  1500         return PEP_OUT_OF_MEMORY;
  1501 
  1502     result = snprintf(parms, PARMS_MAX, template, identity->username,
  1503             identity->address); // , _session->passphrase);
  1504     assert(result < PARMS_MAX);
  1505     if (result >= PARMS_MAX) {
  1506         free(parms);
  1507         return PEP_BUFFER_TOO_SMALL;
  1508     }
  1509 
  1510     gpgme_error = _session->gpgme_op_genkey(_session->ctx, parms, NULL, NULL);
  1511     free(parms);
  1512 
  1513     switch (gpgme_error) {
  1514     case GPG_ERR_NO_ERROR:
  1515         break;
  1516     case GPG_ERR_INV_VALUE:
  1517         return PEP_ILLEGAL_VALUE;
  1518     case GPG_ERR_GENERAL:
  1519         return PEP_CANNOT_CREATE_KEY;
  1520     default:
  1521         assert(0);
  1522         return PEP_UNKNOWN_ERROR;
  1523     }
  1524 
  1525     gpgme_genkey_result = _session->gpgme_op_genkey_result(_session->ctx);
  1526     assert(gpgme_genkey_result);
  1527     assert(gpgme_genkey_result->fpr);
  1528 
  1529     identity->fpr = strdup(gpgme_genkey_result->fpr);
  1530 
  1531     return PEP_STATUS_OK;
  1532 }
  1533 
  1534 PEP_STATUS delete_keypair(PEP_SESSION session, const char *fpr)
  1535 {
  1536 	pEpSession *_session = (pEpSession *) session;
  1537 	gpgme_error_t gpgme_error;
  1538     gpgme_key_t key;
  1539 
  1540     assert(session);
  1541     assert(fpr);
  1542 
  1543     gpgme_error = _session->gpgme_get_key(_session->ctx, fpr, &key, 0);
  1544     assert(gpgme_error != GPG_ERR_ENOMEM);
  1545     switch (gpgme_error) {
  1546     case GPG_ERR_NO_ERROR:
  1547         break;
  1548     case GPG_ERR_EOF:
  1549         return PEP_KEY_NOT_FOUND;
  1550     case GPG_ERR_INV_VALUE:
  1551         return PEP_ILLEGAL_VALUE;
  1552     case GPG_ERR_AMBIGUOUS_NAME:
  1553         return PEP_KEY_HAS_AMBIG_NAME;
  1554     case GPG_ERR_ENOMEM:
  1555         return PEP_OUT_OF_MEMORY;
  1556     default:
  1557         assert(0);
  1558         return PEP_UNKNOWN_ERROR;
  1559     }
  1560 
  1561     gpgme_error = _session->gpgme_op_delete(_session->ctx, key, 1);
  1562     _session->gpgme_key_unref(key);
  1563     switch (gpgme_error) {
  1564     case GPG_ERR_NO_ERROR:
  1565         break;
  1566     case GPG_ERR_INV_VALUE:
  1567         assert(0);
  1568         return PEP_UNKNOWN_ERROR;
  1569     case GPG_ERR_NO_PUBKEY:
  1570         assert(0);
  1571         return PEP_KEY_NOT_FOUND;
  1572     case GPG_ERR_AMBIGUOUS_NAME:
  1573         assert(0);
  1574         return PEP_KEY_HAS_AMBIG_NAME;
  1575     default:
  1576         assert(0);
  1577         return PEP_UNKNOWN_ERROR;
  1578     }
  1579 
  1580     return PEP_STATUS_OK;
  1581 }
  1582 
  1583 PEP_STATUS import_key(PEP_SESSION session, const char *key_data, size_t size)
  1584 {
  1585 	pEpSession *_session = (pEpSession *) session;
  1586 	gpgme_error_t gpgme_error;
  1587     gpgme_data_t dh;
  1588 
  1589     assert(session);
  1590     assert(key_data);
  1591 
  1592     gpgme_error = _session->gpgme_data_new_from_mem(&dh, key_data, size, 0);
  1593     assert(gpgme_error != GPG_ERR_ENOMEM);
  1594     switch (gpgme_error) {
  1595     case GPG_ERR_NO_ERROR:
  1596         break;
  1597     case GPG_ERR_ENOMEM:
  1598         return PEP_OUT_OF_MEMORY;
  1599     case GPG_ERR_INV_VALUE:
  1600         assert(0);
  1601         return PEP_UNKNOWN_ERROR;
  1602     default:
  1603         assert(0);
  1604         return PEP_UNKNOWN_ERROR;
  1605     }
  1606 
  1607     gpgme_error = _session->gpgme_op_import(_session->ctx, dh);
  1608     switch (gpgme_error) {
  1609     case GPG_ERR_NO_ERROR:
  1610         break;
  1611     case GPG_ERR_INV_VALUE:
  1612         assert(0);
  1613         _session->gpgme_data_release(dh);
  1614         return PEP_UNKNOWN_ERROR;
  1615     case GPG_ERR_NO_DATA:
  1616         _session->gpgme_data_release(dh);
  1617         return PEP_ILLEGAL_VALUE;
  1618     default:
  1619         assert(0);
  1620         _session->gpgme_data_release(dh);
  1621         return PEP_UNKNOWN_ERROR;
  1622     }
  1623 
  1624     _session->gpgme_data_release(dh);
  1625     return PEP_STATUS_OK;
  1626 }
  1627 
  1628 PEP_STATUS export_key(
  1629         PEP_SESSION session, const char *fpr, char **key_data, size_t *size
  1630     )
  1631 {
  1632 	pEpSession *_session = (pEpSession *) session;
  1633 	gpgme_error_t gpgme_error;
  1634     gpgme_data_t dh;
  1635     size_t _size;
  1636     char *buffer;
  1637     int reading;
  1638 
  1639     assert(session);
  1640     assert(fpr);
  1641     assert(key_data);
  1642     assert(size);
  1643 
  1644     gpgme_error = _session->gpgme_data_new(&dh);
  1645     assert(gpgme_error != GPG_ERR_ENOMEM);
  1646     switch (gpgme_error) {
  1647     case GPG_ERR_NO_ERROR:
  1648         break;
  1649     case GPG_ERR_ENOMEM:
  1650         return PEP_OUT_OF_MEMORY;
  1651     case GPG_ERR_INV_VALUE:
  1652         assert(0);
  1653         return PEP_UNKNOWN_ERROR;
  1654     default:
  1655         assert(0);
  1656         return PEP_UNKNOWN_ERROR;
  1657     }
  1658 
  1659     gpgme_error = _session->gpgme_op_export(_session->ctx, fpr,
  1660             GPGME_EXPORT_MODE_MINIMAL, dh);
  1661     switch (gpgme_error) {
  1662     case GPG_ERR_NO_ERROR:
  1663         break;
  1664     case GPG_ERR_EOF:
  1665         _session->gpgme_data_release(dh);
  1666         return PEP_KEY_NOT_FOUND;
  1667     case GPG_ERR_INV_VALUE:
  1668         assert(0);
  1669         _session->gpgme_data_release(dh);
  1670         return PEP_UNKNOWN_ERROR;
  1671     default:
  1672         assert(0);
  1673         _session->gpgme_data_release(dh);
  1674         return PEP_UNKNOWN_ERROR;
  1675     };
  1676 
  1677     _size = _session->gpgme_data_seek(dh, 0, SEEK_END);
  1678     assert(_size != -1);
  1679     _session->gpgme_data_seek(dh, 0, SEEK_SET);
  1680 
  1681     buffer = malloc(_size + 1);
  1682     assert(buffer);
  1683     if (buffer == NULL) {
  1684         _session->gpgme_data_release(dh);
  1685         return PEP_OUT_OF_MEMORY;
  1686     }
  1687 
  1688     reading = _session->gpgme_data_read(dh, buffer, _size);
  1689     assert(_size == reading);
  1690 
  1691     // safeguard for the naive user
  1692     buffer[_size] = 0;
  1693 
  1694     *key_data = buffer;
  1695     *size = _size;
  1696 
  1697     _session->gpgme_data_release(dh);
  1698     return PEP_STATUS_OK;
  1699 }
  1700 
  1701 static void _switch_mode(pEpSession *_session, gpgme_keylist_mode_t remove_mode,
  1702         gpgme_keylist_mode_t add_mode)
  1703 {
  1704 	gpgme_error_t gpgme_error;
  1705     gpgme_keylist_mode_t mode;
  1706 
  1707     mode = _session->gpgme_get_keylist_mode(_session->ctx);
  1708 
  1709     mode &= ~remove_mode;
  1710     mode |= add_mode;
  1711 
  1712     gpgme_error = _session->gpgme_set_keylist_mode(_session->ctx, mode);
  1713     assert(gpgme_error == GPG_ERR_NO_ERROR);
  1714 }
  1715 
  1716 PEP_STATUS recv_key(PEP_SESSION session, const char *pattern)
  1717 {
  1718 	pEpSession *_session = (pEpSession *) session;
  1719 	gpgme_error_t gpgme_error;
  1720     gpgme_key_t key;
  1721 
  1722     assert(session);
  1723     assert(pattern);
  1724 
  1725     _switch_mode(_session, GPGME_KEYLIST_MODE_LOCAL, GPGME_KEYLIST_MODE_EXTERN);
  1726 
  1727     gpgme_error = _session->gpgme_op_keylist_start(_session->ctx, pattern, 0);
  1728     switch (gpgme_error) {
  1729     case GPG_ERR_NO_ERROR:
  1730         break;
  1731     case GPG_ERR_INV_VALUE:
  1732         assert(0);
  1733         _switch_mode(_session, GPGME_KEYLIST_MODE_EXTERN,
  1734                 GPGME_KEYLIST_MODE_LOCAL);
  1735         return PEP_UNKNOWN_ERROR;
  1736     default:
  1737         _switch_mode(_session, GPGME_KEYLIST_MODE_EXTERN,
  1738                 GPGME_KEYLIST_MODE_LOCAL);
  1739         return PEP_GET_KEY_FAILED;
  1740     };
  1741 
  1742     do {
  1743         gpgme_error = _session->gpgme_op_keylist_next(_session->ctx, &key);
  1744         assert(gpgme_error != GPG_ERR_INV_VALUE);
  1745         switch (gpgme_error) {
  1746         case GPG_ERR_EOF:
  1747             break;
  1748         case GPG_ERR_NO_ERROR:
  1749             {
  1750                 gpgme_error_t gpgme_error;
  1751                 gpgme_key_t keys[2];
  1752 
  1753                 keys[0] = key;
  1754                 keys[1] = NULL;
  1755 
  1756                 gpgme_error = _session->gpgme_op_import_keys(_session->ctx, keys);
  1757                 _session->gpgme_key_unref(key);
  1758                 assert(gpgme_error != GPG_ERR_INV_VALUE);
  1759                 assert(gpgme_error != GPG_ERR_CONFLICT);
  1760             }
  1761             break;
  1762         case GPG_ERR_ENOMEM:
  1763             _switch_mode(_session, GPGME_KEYLIST_MODE_EXTERN,
  1764                     GPGME_KEYLIST_MODE_LOCAL);
  1765             _session->gpgme_op_keylist_end(_session->ctx);
  1766             return PEP_OUT_OF_MEMORY;
  1767         default:
  1768             // BUG: GPGME returns an illegal value instead of GPG_ERR_EOF after
  1769             // reading first key
  1770 #ifndef NDEBUG
  1771             fprintf(stderr, "warning: unknown result 0x%x of"
  1772                     " gpgme_op_keylist_next()\n", gpgme_error);
  1773 #endif
  1774             gpgme_error = GPG_ERR_EOF;
  1775             break;
  1776         };
  1777     } while (gpgme_error != GPG_ERR_EOF);
  1778 
  1779     _session->gpgme_op_keylist_end(_session->ctx);
  1780     _switch_mode(_session, GPGME_KEYLIST_MODE_EXTERN,
  1781             GPGME_KEYLIST_MODE_LOCAL);
  1782     return PEP_STATUS_OK;
  1783 }
  1784 
  1785 DYNAMIC_API PEP_STATUS find_keys(
  1786         PEP_SESSION session, const char *pattern, stringlist_t **keylist
  1787     )
  1788 {
  1789 	pEpSession *_session = (pEpSession *) session;
  1790 	gpgme_error_t gpgme_error;
  1791     gpgme_key_t key;
  1792     stringlist_t *_keylist;
  1793     char *fpr;
  1794 
  1795     assert(session);
  1796     assert(pattern);
  1797     assert(keylist);
  1798 
  1799     *keylist = NULL;
  1800 
  1801     gpgme_error = _session->gpgme_op_keylist_start(_session->ctx, pattern, 0);
  1802     switch (gpgme_error) {
  1803     case GPG_ERR_NO_ERROR:
  1804         break;
  1805     case GPG_ERR_INV_VALUE:
  1806         assert(0);
  1807         return PEP_UNKNOWN_ERROR;
  1808     default:
  1809         return PEP_GET_KEY_FAILED;
  1810     };
  1811 
  1812     _keylist = new_stringlist(NULL);
  1813     stringlist_t *_k = _keylist;
  1814 
  1815     do {
  1816         gpgme_error = _session->gpgme_op_keylist_next(_session->ctx, &key);
  1817         assert(gpgme_error != GPG_ERR_INV_VALUE);
  1818         switch (gpgme_error) {
  1819         case GPG_ERR_EOF:
  1820             break;
  1821         case GPG_ERR_NO_ERROR:
  1822             assert(key);
  1823             assert(key->subkeys);
  1824             fpr = key->subkeys->fpr;
  1825             assert(fpr);
  1826             _k = stringlist_add(_k, fpr);
  1827             assert(_k);
  1828             if (_k != NULL)
  1829                 break;
  1830         case GPG_ERR_ENOMEM:
  1831             free_stringlist(_keylist);
  1832             _session->gpgme_op_keylist_end(_session->ctx);
  1833             return PEP_OUT_OF_MEMORY;
  1834         default:
  1835             // BUG: GPGME returns an illegal value instead of GPG_ERR_EOF after
  1836             // reading first key
  1837 #ifndef NDEBUG
  1838             fprintf(stderr, "warning: unknown result 0x%x of"
  1839                     " gpgme_op_keylist_next()\n", gpgme_error);
  1840 #endif
  1841             gpgme_error = GPG_ERR_EOF;
  1842             break;
  1843         };
  1844     } while (gpgme_error != GPG_ERR_EOF);
  1845 
  1846     _session->gpgme_op_keylist_end(_session->ctx);
  1847     *keylist = _keylist;
  1848     return PEP_STATUS_OK;
  1849 }
  1850 
  1851 PEP_STATUS send_key(PEP_SESSION session, const char *pattern)
  1852 {
  1853 	pEpSession *_session = (pEpSession *) session;
  1854 	gpgme_error_t gpgme_error;
  1855 
  1856     gpgme_error = _session->gpgme_op_export(_session->ctx, pattern,
  1857             GPGME_EXPORT_MODE_EXTERN, NULL);
  1858     assert(gpgme_error != GPG_ERR_INV_VALUE);
  1859     if (gpgme_error == GPG_ERR_NO_ERROR)
  1860         return PEP_STATUS_OK;
  1861     else
  1862         return PEP_CANNOT_SEND_KEY;
  1863 }
  1864 
  1865 void pEp_free(void *p)
  1866 {
  1867     free(p);
  1868 }
  1869