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