src/pEpEngine.c
author vb
Wed, 30 Jul 2014 16:02:49 +0200
changeset 9 41e66a54f03e
parent 8 26cc9f0228f4
child 10 ead888e73384
permissions -rw-r--r--
update_identity() into pEpComAdapter
get_key_rating() added
     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 			result = PEP_CANNOT_DECRYPT_UNKNOWN;
   842 		}
   843 		break;
   844 
   845 	default:
   846 		result = PEP_DECRYPT_WRONG_FORMAT;
   847 	}
   848 
   849 	_session->gpgme_data_release(plain);
   850 	_session->gpgme_data_release(cipher);
   851 	return result;
   852 }
   853 
   854 DYNAMIC_API PEP_STATUS verify_text(
   855         PEP_SESSION session, const char *text, size_t size,
   856         const char *signature, size_t sig_size, stringlist_t **keylist
   857     )
   858 {
   859 	pEpSession *_session = (pEpSession *) session;
   860 
   861 	PEP_STATUS result;
   862 	gpgme_error_t gpgme_error;
   863 	gpgme_data_t d_text, d_sig;
   864     stringlist_t *_keylist;
   865 
   866     assert(session);
   867     assert(text);
   868     assert(size);
   869     assert(signature);
   870     assert(sig_size);
   871     assert(keylist);
   872 
   873     *keylist = NULL;
   874 
   875     gpgme_error = _session->gpgme_data_new_from_mem(&d_text, text, size, 0);
   876 	assert(gpgme_error == GPG_ERR_NO_ERROR);
   877 	if (gpgme_error != GPG_ERR_NO_ERROR) {
   878 		if (gpgme_error == GPG_ERR_ENOMEM)
   879 			return PEP_OUT_OF_MEMORY;
   880 		else
   881 			return PEP_UNKNOWN_ERROR;
   882 	}
   883 
   884     gpgme_error = _session->gpgme_data_new_from_mem(&d_sig, signature, sig_size, 0);
   885 	assert(gpgme_error == GPG_ERR_NO_ERROR);
   886 	if (gpgme_error != GPG_ERR_NO_ERROR) {
   887 		_session->gpgme_data_release(d_text);
   888 		if (gpgme_error == GPG_ERR_ENOMEM)
   889 			return PEP_OUT_OF_MEMORY;
   890 		else
   891 			return PEP_UNKNOWN_ERROR;
   892 	}
   893 
   894     gpgme_error = _session->gpgme_op_verify(_session->ctx, d_sig, d_text, NULL);
   895     assert(gpgme_error != GPG_ERR_INV_VALUE);
   896 
   897     switch (gpgme_error) {
   898     case GPG_ERR_NO_ERROR:
   899         {
   900             gpgme_verify_result_t gpgme_verify_result;
   901             gpgme_signature_t gpgme_signature;
   902 
   903             gpgme_verify_result =
   904                 _session->gpgme_op_verify_result(_session->ctx);
   905             assert(gpgme_verify_result);
   906             gpgme_signature = gpgme_verify_result->signatures;
   907 
   908             if (gpgme_signature) {
   909                 stringlist_t *k;
   910                 _keylist = new_stringlist(NULL);
   911                 assert(_keylist);
   912                 if (_keylist == NULL) {
   913                     _session->gpgme_data_release(d_text);
   914                     _session->gpgme_data_release(d_sig);
   915                     return PEP_OUT_OF_MEMORY;
   916                 }
   917                 k = _keylist;
   918 
   919                 result = PEP_VERIFIED;
   920                 do {
   921                     k = stringlist_add(k, gpgme_signature->fpr);
   922                     if (k == NULL) {
   923                         free_stringlist(_keylist);
   924                         _session->gpgme_data_release(d_text);
   925                         _session->gpgme_data_release(d_sig);
   926                         return PEP_OUT_OF_MEMORY;
   927                     }
   928                     if (gpgme_signature->summary & GPGME_SIGSUM_RED) {
   929                         if (gpgme_signature->summary & GPGME_SIGSUM_KEY_EXPIRED
   930                                 || gpgme_signature->summary & GPGME_SIGSUM_SIG_EXPIRED) {
   931                             if (result == PEP_VERIFIED
   932                                     || result == PEP_VERIFIED_AND_TRUSTED)
   933                                 result = PEP_UNENCRYPTED;
   934                         }
   935                         else {
   936                             result = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
   937                             break;
   938                         }
   939                     }
   940                     else {
   941                         if (gpgme_signature->summary & GPGME_SIGSUM_VALID) {
   942                             if (result == PEP_VERIFIED)
   943                                 result = PEP_VERIFIED_AND_TRUSTED;
   944                         }
   945                         if (gpgme_signature->summary & GPGME_SIGSUM_GREEN) {
   946                             // good
   947                         }
   948                         else if (gpgme_signature->summary & GPGME_SIGSUM_KEY_MISSING) {
   949                             result = PEP_VERIFY_NO_KEY;
   950                         }
   951                         else if (gpgme_signature->summary & GPGME_SIGSUM_SYS_ERROR) {
   952                             if (result == PEP_VERIFIED
   953                                     || result == PEP_VERIFIED_AND_TRUSTED)
   954                                 result = PEP_UNENCRYPTED;
   955                         }
   956                         else {
   957                             // do nothing
   958                         }
   959                     }
   960                 } while ((gpgme_signature = gpgme_signature->next));
   961                 *keylist = _keylist;
   962             } else {
   963                 result = PEP_UNENCRYPTED;
   964             }
   965             break;
   966         }
   967         break;
   968     case GPG_ERR_NO_DATA:
   969         result = PEP_DECRYPT_WRONG_FORMAT;
   970         break;
   971     case GPG_ERR_INV_VALUE:
   972     default:
   973         result = PEP_UNKNOWN_ERROR;
   974         break;
   975     }
   976 
   977     _session->gpgme_data_release(d_text);
   978     _session->gpgme_data_release(d_sig);
   979 
   980     return result;
   981 }
   982 
   983 DYNAMIC_API PEP_STATUS encrypt_and_sign(
   984         PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
   985         size_t psize, char **ctext, size_t *csize
   986     )
   987 {
   988 	pEpSession *_session = (pEpSession *) session;
   989 
   990 	PEP_STATUS result;
   991 	gpgme_error_t gpgme_error;
   992 	gpgme_data_t plain, cipher;
   993 	gpgme_key_t *rcpt;
   994 	gpgme_encrypt_flags_t flags;
   995 	const stringlist_t *_keylist;
   996     int i, j;
   997 
   998 	assert(_session);
   999 	assert(keylist);
  1000 	assert(ptext);
  1001 	assert(psize);
  1002 	assert(ctext);
  1003 	assert(csize);
  1004 
  1005 	*ctext = NULL;
  1006 	*csize = 0;
  1007 
  1008     gpgme_error = _session->gpgme_data_new_from_mem(&plain, ptext, psize, 0);
  1009 	assert(gpgme_error == GPG_ERR_NO_ERROR);
  1010 	if (gpgme_error != GPG_ERR_NO_ERROR) {
  1011 		if (gpgme_error == GPG_ERR_ENOMEM)
  1012 			return PEP_OUT_OF_MEMORY;
  1013 		else
  1014 			return PEP_UNKNOWN_ERROR;
  1015 	}
  1016 
  1017 	gpgme_error = _session->gpgme_data_new(&cipher);
  1018 	assert(gpgme_error == GPG_ERR_NO_ERROR);
  1019 	if (gpgme_error != GPG_ERR_NO_ERROR) {
  1020 		_session->gpgme_data_release(plain);
  1021 		if (gpgme_error == GPG_ERR_ENOMEM)
  1022 			return PEP_OUT_OF_MEMORY;
  1023 		else
  1024 			return PEP_UNKNOWN_ERROR;
  1025 	}
  1026 
  1027     rcpt = (gpgme_key_t *) calloc(stringlist_length(keylist) + 1,
  1028             sizeof(gpgme_key_t));
  1029 	assert(rcpt);
  1030 	if (rcpt == NULL) {
  1031 		_session->gpgme_data_release(plain);
  1032 		_session->gpgme_data_release(cipher);
  1033 		return PEP_OUT_OF_MEMORY;
  1034 	}
  1035 
  1036     for (_keylist=keylist, i=0; _keylist!=NULL; _keylist=_keylist->next, i++) {
  1037 		assert(_keylist->value);
  1038         gpgme_error = _session->gpgme_get_key(_session->ctx, _keylist->value,
  1039                 &rcpt[i], 0);
  1040 		assert(gpgme_error != GPG_ERR_ENOMEM);
  1041 
  1042 		switch (gpgme_error) {
  1043 		case GPG_ERR_ENOMEM:
  1044             for (j=0; j<i; j++)
  1045                 _session->gpgme_key_unref(rcpt[j]);
  1046 			free(rcpt);
  1047 			_session->gpgme_data_release(plain);
  1048 			_session->gpgme_data_release(cipher);
  1049 			return PEP_OUT_OF_MEMORY;
  1050 		case GPG_ERR_NO_ERROR:
  1051 			break;
  1052 		case GPG_ERR_EOF:
  1053             for (j=0; j<i; j++)
  1054                 _session->gpgme_key_unref(rcpt[j]);
  1055 			free(rcpt);
  1056 			_session->gpgme_data_release(plain);
  1057 			_session->gpgme_data_release(cipher);
  1058 			return PEP_KEY_NOT_FOUND;
  1059 		case GPG_ERR_AMBIGUOUS_NAME:
  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_KEY_HAS_AMBIG_NAME;
  1066         default: // GPG_ERR_INV_VALUE if CTX or R_KEY is not a valid pointer or
  1067                  // FPR is not a fingerprint or key ID
  1068             for (j=0; j<i; j++)
  1069                 _session->gpgme_key_unref(rcpt[j]);
  1070 			free(rcpt);
  1071 			_session->gpgme_data_release(plain);
  1072 			_session->gpgme_data_release(cipher);
  1073 			return PEP_GET_KEY_FAILED;
  1074 		}
  1075 	}
  1076 
  1077 	// TODO: remove that and replace with proper key management
  1078 	flags  = GPGME_ENCRYPT_ALWAYS_TRUST;
  1079 
  1080     gpgme_error = _session->gpgme_op_encrypt_sign(_session->ctx, rcpt, flags,
  1081             plain, cipher);
  1082 	switch (gpgme_error) {
  1083 	case GPG_ERR_NO_ERROR:
  1084 		{
  1085             char *_buffer = NULL;
  1086 			size_t reading;
  1087             size_t length = _session->gpgme_data_seek(cipher, 0, SEEK_END);
  1088             assert(length != -1);
  1089 			_session->gpgme_data_seek(cipher, 0, SEEK_SET);
  1090 
  1091 			// TODO: make things less memory consuming
  1092             // the following algorithm allocates a buffer for the complete text
  1093 
  1094             _buffer = (char *) malloc(length + 1);
  1095             assert(_buffer);
  1096             if (_buffer == NULL) {
  1097                 for (j=0; j<stringlist_length(keylist); j++)
  1098                     _session->gpgme_key_unref(rcpt[j]);
  1099                 free(rcpt);
  1100                 _session->gpgme_data_release(plain);
  1101                 _session->gpgme_data_release(cipher);
  1102                 return PEP_OUT_OF_MEMORY;
  1103             }
  1104 
  1105             reading = _session->gpgme_data_read(cipher, _buffer, length);
  1106 			assert(length == reading);
  1107 
  1108 			*ctext = _buffer;
  1109 			*csize = reading;
  1110 			(*ctext)[*csize] = 0; // safeguard for naive users
  1111 			result = PEP_STATUS_OK;
  1112 			break;
  1113 		}
  1114 	default:
  1115 		result = PEP_UNKNOWN_ERROR;
  1116 	}
  1117 
  1118     for (j=0; j<stringlist_length(keylist); j++)
  1119         _session->gpgme_key_unref(rcpt[j]);
  1120 	free(rcpt);
  1121 	_session->gpgme_data_release(plain);
  1122 	_session->gpgme_data_release(cipher);
  1123 	return result;
  1124 }
  1125 
  1126 DYNAMIC_API PEP_STATUS log_event(
  1127         PEP_SESSION session, const char *title, const char *entity,
  1128         const char *description, const char *comment
  1129     )
  1130 {
  1131 	pEpSession *_session = (pEpSession *) session;
  1132 	PEP_STATUS status = PEP_STATUS_OK;
  1133 	int result;
  1134 
  1135 	assert(_session);
  1136 	assert(title);
  1137 	assert(entity);
  1138 
  1139 	sqlite3_reset(_session->log);
  1140 	sqlite3_bind_text(_session->log, 1, title, -1, SQLITE_STATIC);
  1141 	sqlite3_bind_text(_session->log, 2, entity, -1, SQLITE_STATIC);
  1142 	if (description)
  1143         sqlite3_bind_text(_session->log, 3, description, -1, SQLITE_STATIC);
  1144 	else
  1145 		sqlite3_bind_null(_session->log, 3);
  1146 	if (comment)
  1147 		sqlite3_bind_text(_session->log, 4, comment, -1, SQLITE_STATIC);
  1148 	else
  1149 		sqlite3_bind_null(_session->log, 4);
  1150 	do {
  1151 		result = sqlite3_step(_session->log);
  1152 		assert(result == SQLITE_DONE || result == SQLITE_BUSY);
  1153 		if (result != SQLITE_DONE && result != SQLITE_BUSY)
  1154 			status = PEP_UNKNOWN_ERROR;
  1155 	} while (result == SQLITE_BUSY);
  1156 	sqlite3_reset(_session->log);
  1157 
  1158 	return status;
  1159 }
  1160 
  1161 DYNAMIC_API PEP_STATUS safeword(
  1162             PEP_SESSION session, uint16_t value, const char *lang,
  1163             char **word, size_t *wsize
  1164         )
  1165 {
  1166 	pEpSession *_session = (pEpSession *) session;
  1167 	PEP_STATUS status = PEP_STATUS_OK;
  1168 	int result;
  1169 
  1170 	assert(_session);
  1171 	assert(word);
  1172 	assert(wsize);
  1173 
  1174 	*word = NULL;
  1175 	*wsize = 0;
  1176 
  1177 	if (lang == NULL)
  1178 		lang = "en";
  1179 
  1180 	assert((lang[0] >= 'A' && lang[0] <= 'Z')
  1181             || (lang[0] >= 'a' && lang[0] <= 'z'));
  1182 	assert((lang[1] >= 'A' && lang[1] <= 'Z')
  1183             || (lang[1] >= 'a' && lang[1] <= 'z'));
  1184 	assert(lang[2] == 0);
  1185 
  1186 	sqlite3_reset(_session->safeword);
  1187     sqlite3_bind_text(_session->safeword, 1, lang, -1, SQLITE_STATIC);
  1188 	sqlite3_bind_int(_session->safeword, 2, value);
  1189 
  1190 	result = sqlite3_step(_session->safeword);
  1191 	if (result == SQLITE_ROW) {
  1192         *word = strdup((const char *) sqlite3_column_text(_session->safeword,
  1193                     1));
  1194 		if (*word)
  1195             *wsize = sqlite3_column_bytes(_session->safeword, 1);
  1196 		else
  1197 			status = PEP_SAFEWORD_NOT_FOUND;
  1198 	} else
  1199 		status = PEP_SAFEWORD_NOT_FOUND;
  1200 
  1201 	sqlite3_reset(_session->safeword);
  1202 	return status;
  1203 }
  1204 
  1205 DYNAMIC_API PEP_STATUS safewords(
  1206         PEP_SESSION session, const char *fingerprint, const char *lang,
  1207         char **words, size_t *wsize, int max_words
  1208     )
  1209 {
  1210 	const char *source = fingerprint;
  1211 	char *buffer = calloc(1, MAX_SAFEWORDS_SPACE);
  1212 	char *dest = buffer;
  1213 	size_t fsize;
  1214     PEP_STATUS _status;
  1215 
  1216 	assert(session);
  1217 	assert(fingerprint);
  1218 	assert(words);
  1219 	assert(wsize);
  1220 	assert(max_words >= 0);
  1221 
  1222 	*words = NULL;
  1223 	*wsize = 0;
  1224 
  1225     assert(buffer);
  1226     if (buffer == NULL)
  1227         return PEP_OUT_OF_MEMORY;
  1228 
  1229 	fsize = strlen(fingerprint);
  1230 
  1231 	if (lang == NULL)
  1232 		lang = "en";
  1233 
  1234 	assert((lang[0] >= 'A' && lang[0] <= 'Z')
  1235             || (lang[0] >= 'a' && lang[0] <= 'z'));
  1236 	assert((lang[1] >= 'A' && lang[1] <= 'Z')
  1237             || (lang[1] >= 'a' && lang[1] <= 'z'));
  1238 	assert(lang[2] == 0);
  1239 
  1240 	int n_words = 0;
  1241 	while (source < fingerprint + fsize) {
  1242 		uint16_t value;
  1243 		char *word;
  1244 		size_t _wsize;
  1245 		int j;
  1246 
  1247         for (value=0, j=0; j < 4 && source < fingerprint + fsize; ) {
  1248 			if (*source >= 'a' && *source <= 'f')
  1249 				value += (*source - 'a' + 10) << (3 - j++) * 4;
  1250 			else if (*source >= 'A' && *source <= 'F')
  1251 				value += (*source - 'A' + 10) << (3 - j++) * 4;
  1252 			else if (*source >= '0' && *source <= '9')
  1253 				value += (*source - '0') << (3 - j++) * 4;
  1254 			
  1255 			source++;
  1256 		}
  1257 
  1258 		_status = safeword(session, value, lang, &word, &_wsize);
  1259         if (_status == PEP_OUT_OF_MEMORY) {
  1260             free(buffer);
  1261             return PEP_OUT_OF_MEMORY;
  1262         }
  1263 		if (word == NULL) {
  1264             free(buffer);
  1265 			return PEP_SAFEWORD_NOT_FOUND;
  1266         }
  1267 
  1268 		if (dest + _wsize < buffer + MAX_SAFEWORDS_SPACE - 1) {
  1269 			strncpy(dest, word, _wsize);
  1270             free(word);
  1271 			dest += _wsize;
  1272 		}
  1273 		else {
  1274             free(word);
  1275 			break; // buffer full
  1276         }
  1277 
  1278 		if (source < fingerprint + fsize
  1279                 && dest + _wsize < buffer + MAX_SAFEWORDS_SPACE - 1)
  1280 			*dest++ = ' ';
  1281 
  1282 		++n_words;
  1283 		if (max_words && n_words >= max_words)
  1284 			break;
  1285 	}
  1286 
  1287 	*words = buffer;
  1288 	*wsize = dest - buffer;
  1289 	return PEP_STATUS_OK;
  1290 }
  1291 
  1292 pEp_identity *new_identity(
  1293         const char *address, const char *fpr, const char *user_id,
  1294         const char *username
  1295     )
  1296 {
  1297     pEp_identity *result = calloc(1, sizeof(pEp_identity));
  1298     assert(result);
  1299     if (result) {
  1300         if (address) {
  1301             result->address = strdup(address);
  1302             assert(result->address);
  1303             if (result->address == NULL) {
  1304                 free(result);
  1305                 return NULL;
  1306             }
  1307             result->address_size = strlen(address);
  1308         }
  1309         if (fpr) {
  1310             result->fpr = strdup(fpr);
  1311             assert(result->fpr);
  1312             if (result->fpr == NULL) {
  1313                 free_identity(result);
  1314                 return NULL;
  1315             }
  1316             result->fpr_size = strlen(fpr);
  1317         }
  1318         if (user_id) {
  1319             result->user_id = strdup(user_id);
  1320             assert(result->user_id);
  1321             if (result->user_id == NULL) {
  1322                 free_identity(result);
  1323                 return NULL;
  1324             }
  1325             result->user_id_size = strlen(user_id);
  1326         }
  1327         if (username) {
  1328             result->username = strdup(username);
  1329             assert(result->username);
  1330             if (result->username == NULL) {
  1331                 free_identity(result);
  1332                 return NULL;
  1333             }
  1334             result->username_size = strlen(username);
  1335         }
  1336         result->struct_size = sizeof(pEp_identity);
  1337     }
  1338     return result;
  1339 }
  1340 
  1341 void free_identity(pEp_identity *identity)
  1342 {
  1343     if (identity) {
  1344         free(identity->address);
  1345         free(identity->fpr);
  1346         free(identity->user_id);
  1347         free(identity->username);
  1348         free(identity);
  1349     }
  1350 }
  1351 
  1352 DYNAMIC_API PEP_STATUS get_identity(
  1353         PEP_SESSION session, const char *address,
  1354         pEp_identity **identity
  1355     )
  1356 {
  1357 	pEpSession *_session = (pEpSession *) session;
  1358 	PEP_STATUS status = PEP_STATUS_OK;
  1359 	static pEp_identity *_identity;
  1360 	int result;
  1361 	const char *_lang;
  1362 
  1363 	assert(session);
  1364 	assert(address);
  1365     assert(address[0]);
  1366 
  1367     sqlite3_reset(_session->get_identity);
  1368     sqlite3_bind_text(_session->get_identity, 1, address, -1, SQLITE_STATIC);
  1369 
  1370     result = sqlite3_step(_session->get_identity);
  1371 	switch (result) {
  1372 	case SQLITE_ROW:
  1373         _identity = new_identity(
  1374                 address,
  1375                 (const char *) sqlite3_column_text(_session->get_identity, 0),
  1376                 (const char *) sqlite3_column_text(_session->get_identity, 1),
  1377                 (const char *) sqlite3_column_text(_session->get_identity, 2)
  1378                 );
  1379         assert(_identity);
  1380         if (_identity == NULL)
  1381             return PEP_OUT_OF_MEMORY;
  1382 
  1383         _identity->comm_type = (PEP_comm_type) sqlite3_column_int(_session->get_identity, 3);
  1384         _lang = (const char *) sqlite3_column_text(_session->get_identity, 4);
  1385         if (_lang && _lang[0]) {
  1386 			assert(_lang[0] >= 'a' && _lang[0] <= 'z');
  1387 			assert(_lang[1] >= 'a' && _lang[1] <= 'z');
  1388 			assert(_lang[2] == 0);
  1389 			_identity->lang[0] = _lang[0];
  1390 			_identity->lang[1] = _lang[1];
  1391             _identity->lang[2] = 0;
  1392 		}
  1393 		*identity = _identity;
  1394 		break;
  1395 	default:
  1396         status = PEP_CANNOT_FIND_IDENTITY;
  1397 		*identity = NULL;
  1398 	}
  1399 
  1400     sqlite3_reset(_session->get_identity);
  1401 	return status;
  1402 }
  1403 
  1404 DYNAMIC_API PEP_STATUS set_identity(
  1405         PEP_SESSION session, const pEp_identity *identity
  1406     )
  1407 {
  1408 	pEpSession *_session = (pEpSession *) session;
  1409 	int result;
  1410 
  1411 	assert(session);
  1412 	assert(identity);
  1413 	assert(identity->address);
  1414 	assert(identity->fpr);
  1415 	assert(identity->user_id);
  1416 	assert(identity->username);
  1417 
  1418 	sqlite3_exec(_session->db, "BEGIN ;", NULL, NULL, NULL);
  1419 
  1420 	sqlite3_reset(_session->set_person);
  1421     sqlite3_bind_text(_session->set_person, 1, identity->user_id, -1,
  1422             SQLITE_STATIC);
  1423     sqlite3_bind_text(_session->set_person, 2, identity->username, -1,
  1424             SQLITE_STATIC);
  1425 	if (identity->lang[0])
  1426         sqlite3_bind_text(_session->set_person, 3, identity->lang, 1,
  1427                 SQLITE_STATIC);
  1428 	else
  1429 		sqlite3_bind_null(_session->set_person, 3);
  1430 	result = sqlite3_step(_session->set_person);
  1431 	sqlite3_reset(_session->set_person);
  1432 	if (result != SQLITE_DONE) {
  1433 		sqlite3_exec(_session->db, "ROLLBACK ;", NULL, NULL, NULL);
  1434 		return PEP_CANNOT_SET_PERSON;
  1435 	}
  1436 
  1437 	sqlite3_reset(_session->set_pgp_keypair);
  1438     sqlite3_bind_text(_session->set_pgp_keypair, 1, identity->fpr, -1,
  1439             SQLITE_STATIC);
  1440 	result = sqlite3_step(_session->set_pgp_keypair);
  1441 	sqlite3_reset(_session->set_pgp_keypair);
  1442 	if (result != SQLITE_DONE) {
  1443 		sqlite3_exec(_session->db, "ROLLBACK ;", NULL, NULL, NULL);
  1444 		return PEP_CANNOT_SET_PGP_KEYPAIR;
  1445 	}
  1446 
  1447 	sqlite3_reset(_session->set_identity);
  1448     sqlite3_bind_text(_session->set_identity, 1, identity->address, -1,
  1449             SQLITE_STATIC);
  1450     sqlite3_bind_text(_session->set_identity, 2, identity->fpr, -1,
  1451             SQLITE_STATIC);
  1452     sqlite3_bind_text(_session->set_identity, 3, identity->user_id, -1,
  1453             SQLITE_STATIC);
  1454 	result = sqlite3_step(_session->set_identity);
  1455 	sqlite3_reset(_session->set_identity);
  1456 	if (result != SQLITE_DONE) {
  1457 		sqlite3_exec(_session->db, "ROLLBACK ;", NULL, NULL, NULL);
  1458 		return PEP_CANNOT_SET_IDENTITY;
  1459 	}
  1460 
  1461 	sqlite3_reset(_session->set_trust);
  1462     sqlite3_bind_text(_session->set_trust, 1, identity->user_id, -1,
  1463             SQLITE_STATIC);
  1464     sqlite3_bind_text(_session->set_trust, 2, identity->fpr, -1,
  1465             SQLITE_STATIC);
  1466 	sqlite3_bind_int(_session->set_trust, 3, identity->comm_type);
  1467 	result = sqlite3_step(_session->set_trust);
  1468 	sqlite3_reset(_session->set_trust);
  1469 	if (result != SQLITE_DONE) {
  1470 		sqlite3_exec(_session->db, "ROLLBACK ;", NULL, NULL, NULL);
  1471 		return PEP_CANNOT_SET_IDENTITY;
  1472 	}
  1473 
  1474     result = sqlite3_exec(_session->db, "COMMIT ;", NULL, NULL, NULL);
  1475 	if (result == SQLITE_OK)
  1476 		return PEP_STATUS_OK;
  1477 	else
  1478 		return PEP_COMMIT_FAILED;
  1479 }
  1480 
  1481 DYNAMIC_API PEP_STATUS generate_keypair(
  1482         PEP_SESSION session, pEp_identity *identity
  1483     )
  1484 {
  1485 	pEpSession *_session = (pEpSession *) session;
  1486 	gpgme_error_t gpgme_error;
  1487     char *parms;
  1488     const char *template =
  1489         "<GnupgKeyParms format=\"internal\">\n"
  1490         "Key-Type: RSA\n"
  1491         "Key-Length: 4096\n"
  1492         "Name-Real: %s\n"
  1493         "Name-Email: %s\n"
  1494         /* "Passphrase: %s\n" */
  1495         "Expire-Date: 1y\n"
  1496         "</GnupgKeyParms>\n";
  1497     int result;
  1498     gpgme_genkey_result_t gpgme_genkey_result;
  1499 
  1500     assert(session);
  1501     assert(identity);
  1502     assert(identity->address);
  1503     assert(identity->fpr == NULL);
  1504     assert(identity->username);
  1505     
  1506     parms = calloc(1, PARMS_MAX);
  1507     assert(parms);
  1508     if (parms == NULL)
  1509         return PEP_OUT_OF_MEMORY;
  1510 
  1511     result = snprintf(parms, PARMS_MAX, template, identity->username,
  1512             identity->address); // , _session->passphrase);
  1513     assert(result < PARMS_MAX);
  1514     if (result >= PARMS_MAX) {
  1515         free(parms);
  1516         return PEP_BUFFER_TOO_SMALL;
  1517     }
  1518 
  1519     gpgme_error = _session->gpgme_op_genkey(_session->ctx, parms, NULL, NULL);
  1520     free(parms);
  1521 
  1522     switch (gpgme_error) {
  1523     case GPG_ERR_NO_ERROR:
  1524         break;
  1525     case GPG_ERR_INV_VALUE:
  1526         return PEP_ILLEGAL_VALUE;
  1527     case GPG_ERR_GENERAL:
  1528         return PEP_CANNOT_CREATE_KEY;
  1529     default:
  1530         assert(0);
  1531         return PEP_UNKNOWN_ERROR;
  1532     }
  1533 
  1534     gpgme_genkey_result = _session->gpgme_op_genkey_result(_session->ctx);
  1535     assert(gpgme_genkey_result);
  1536     assert(gpgme_genkey_result->fpr);
  1537 
  1538     identity->fpr = strdup(gpgme_genkey_result->fpr);
  1539 
  1540     return PEP_STATUS_OK;
  1541 }
  1542 
  1543 PEP_STATUS delete_keypair(PEP_SESSION session, const char *fpr)
  1544 {
  1545 	pEpSession *_session = (pEpSession *) session;
  1546 	gpgme_error_t gpgme_error;
  1547     gpgme_key_t key;
  1548 
  1549     assert(session);
  1550     assert(fpr);
  1551 
  1552     gpgme_error = _session->gpgme_get_key(_session->ctx, fpr, &key, 0);
  1553     assert(gpgme_error != GPG_ERR_ENOMEM);
  1554     switch (gpgme_error) {
  1555     case GPG_ERR_NO_ERROR:
  1556         break;
  1557     case GPG_ERR_EOF:
  1558         return PEP_KEY_NOT_FOUND;
  1559     case GPG_ERR_INV_VALUE:
  1560         return PEP_ILLEGAL_VALUE;
  1561     case GPG_ERR_AMBIGUOUS_NAME:
  1562         return PEP_KEY_HAS_AMBIG_NAME;
  1563     case GPG_ERR_ENOMEM:
  1564         return PEP_OUT_OF_MEMORY;
  1565     default:
  1566         assert(0);
  1567         return PEP_UNKNOWN_ERROR;
  1568     }
  1569 
  1570     gpgme_error = _session->gpgme_op_delete(_session->ctx, key, 1);
  1571     _session->gpgme_key_unref(key);
  1572     switch (gpgme_error) {
  1573     case GPG_ERR_NO_ERROR:
  1574         break;
  1575     case GPG_ERR_INV_VALUE:
  1576         assert(0);
  1577         return PEP_UNKNOWN_ERROR;
  1578     case GPG_ERR_NO_PUBKEY:
  1579         assert(0);
  1580         return PEP_KEY_NOT_FOUND;
  1581     case GPG_ERR_AMBIGUOUS_NAME:
  1582         assert(0);
  1583         return PEP_KEY_HAS_AMBIG_NAME;
  1584     default:
  1585         assert(0);
  1586         return PEP_UNKNOWN_ERROR;
  1587     }
  1588 
  1589     return PEP_STATUS_OK;
  1590 }
  1591 
  1592 PEP_STATUS import_key(PEP_SESSION session, const char *key_data, size_t size)
  1593 {
  1594 	pEpSession *_session = (pEpSession *) session;
  1595 	gpgme_error_t gpgme_error;
  1596     gpgme_data_t dh;
  1597 
  1598     assert(session);
  1599     assert(key_data);
  1600 
  1601     gpgme_error = _session->gpgme_data_new_from_mem(&dh, key_data, size, 0);
  1602     assert(gpgme_error != GPG_ERR_ENOMEM);
  1603     switch (gpgme_error) {
  1604     case GPG_ERR_NO_ERROR:
  1605         break;
  1606     case GPG_ERR_ENOMEM:
  1607         return PEP_OUT_OF_MEMORY;
  1608     case GPG_ERR_INV_VALUE:
  1609         assert(0);
  1610         return PEP_UNKNOWN_ERROR;
  1611     default:
  1612         assert(0);
  1613         return PEP_UNKNOWN_ERROR;
  1614     }
  1615 
  1616     gpgme_error = _session->gpgme_op_import(_session->ctx, dh);
  1617     switch (gpgme_error) {
  1618     case GPG_ERR_NO_ERROR:
  1619         break;
  1620     case GPG_ERR_INV_VALUE:
  1621         assert(0);
  1622         _session->gpgme_data_release(dh);
  1623         return PEP_UNKNOWN_ERROR;
  1624     case GPG_ERR_NO_DATA:
  1625         _session->gpgme_data_release(dh);
  1626         return PEP_ILLEGAL_VALUE;
  1627     default:
  1628         assert(0);
  1629         _session->gpgme_data_release(dh);
  1630         return PEP_UNKNOWN_ERROR;
  1631     }
  1632 
  1633     _session->gpgme_data_release(dh);
  1634     return PEP_STATUS_OK;
  1635 }
  1636 
  1637 PEP_STATUS export_key(
  1638         PEP_SESSION session, const char *fpr, char **key_data, size_t *size
  1639     )
  1640 {
  1641 	pEpSession *_session = (pEpSession *) session;
  1642 	gpgme_error_t gpgme_error;
  1643     gpgme_data_t dh;
  1644     size_t _size;
  1645     char *buffer;
  1646     int reading;
  1647 
  1648     assert(session);
  1649     assert(fpr);
  1650     assert(key_data);
  1651     assert(size);
  1652 
  1653     gpgme_error = _session->gpgme_data_new(&dh);
  1654     assert(gpgme_error != GPG_ERR_ENOMEM);
  1655     switch (gpgme_error) {
  1656     case GPG_ERR_NO_ERROR:
  1657         break;
  1658     case GPG_ERR_ENOMEM:
  1659         return PEP_OUT_OF_MEMORY;
  1660     case GPG_ERR_INV_VALUE:
  1661         assert(0);
  1662         return PEP_UNKNOWN_ERROR;
  1663     default:
  1664         assert(0);
  1665         return PEP_UNKNOWN_ERROR;
  1666     }
  1667 
  1668     gpgme_error = _session->gpgme_op_export(_session->ctx, fpr,
  1669             GPGME_EXPORT_MODE_MINIMAL, dh);
  1670     switch (gpgme_error) {
  1671     case GPG_ERR_NO_ERROR:
  1672         break;
  1673     case GPG_ERR_EOF:
  1674         _session->gpgme_data_release(dh);
  1675         return PEP_KEY_NOT_FOUND;
  1676     case GPG_ERR_INV_VALUE:
  1677         assert(0);
  1678         _session->gpgme_data_release(dh);
  1679         return PEP_UNKNOWN_ERROR;
  1680     default:
  1681         assert(0);
  1682         _session->gpgme_data_release(dh);
  1683         return PEP_UNKNOWN_ERROR;
  1684     };
  1685 
  1686     _size = _session->gpgme_data_seek(dh, 0, SEEK_END);
  1687     assert(_size != -1);
  1688     _session->gpgme_data_seek(dh, 0, SEEK_SET);
  1689 
  1690     buffer = malloc(_size + 1);
  1691     assert(buffer);
  1692     if (buffer == NULL) {
  1693         _session->gpgme_data_release(dh);
  1694         return PEP_OUT_OF_MEMORY;
  1695     }
  1696 
  1697     reading = _session->gpgme_data_read(dh, buffer, _size);
  1698     assert(_size == reading);
  1699 
  1700     // safeguard for the naive user
  1701     buffer[_size] = 0;
  1702 
  1703     *key_data = buffer;
  1704     *size = _size;
  1705 
  1706     _session->gpgme_data_release(dh);
  1707     return PEP_STATUS_OK;
  1708 }
  1709 
  1710 static void _switch_mode(pEpSession *_session, gpgme_keylist_mode_t remove_mode,
  1711         gpgme_keylist_mode_t add_mode)
  1712 {
  1713 	gpgme_error_t gpgme_error;
  1714     gpgme_keylist_mode_t mode;
  1715 
  1716     mode = _session->gpgme_get_keylist_mode(_session->ctx);
  1717 
  1718     mode &= ~remove_mode;
  1719     mode |= add_mode;
  1720 
  1721     gpgme_error = _session->gpgme_set_keylist_mode(_session->ctx, mode);
  1722     assert(gpgme_error == GPG_ERR_NO_ERROR);
  1723 }
  1724 
  1725 PEP_STATUS recv_key(PEP_SESSION session, const char *pattern)
  1726 {
  1727 	pEpSession *_session = (pEpSession *) session;
  1728 	gpgme_error_t gpgme_error;
  1729     gpgme_key_t key;
  1730 
  1731     assert(session);
  1732     assert(pattern);
  1733 
  1734     _switch_mode(_session, GPGME_KEYLIST_MODE_LOCAL, GPGME_KEYLIST_MODE_EXTERN);
  1735 
  1736     gpgme_error = _session->gpgme_op_keylist_start(_session->ctx, pattern, 0);
  1737     switch (gpgme_error) {
  1738     case GPG_ERR_NO_ERROR:
  1739         break;
  1740     case GPG_ERR_INV_VALUE:
  1741         assert(0);
  1742         _switch_mode(_session, GPGME_KEYLIST_MODE_EXTERN,
  1743                 GPGME_KEYLIST_MODE_LOCAL);
  1744         return PEP_UNKNOWN_ERROR;
  1745     default:
  1746         _switch_mode(_session, GPGME_KEYLIST_MODE_EXTERN,
  1747                 GPGME_KEYLIST_MODE_LOCAL);
  1748         return PEP_GET_KEY_FAILED;
  1749     };
  1750 
  1751     do {
  1752         gpgme_error = _session->gpgme_op_keylist_next(_session->ctx, &key);
  1753         assert(gpgme_error != GPG_ERR_INV_VALUE);
  1754         switch (gpgme_error) {
  1755         case GPG_ERR_EOF:
  1756             break;
  1757         case GPG_ERR_NO_ERROR:
  1758             {
  1759                 gpgme_error_t gpgme_error;
  1760                 gpgme_key_t keys[2];
  1761 
  1762                 keys[0] = key;
  1763                 keys[1] = NULL;
  1764 
  1765                 gpgme_error = _session->gpgme_op_import_keys(_session->ctx, keys);
  1766                 _session->gpgme_key_unref(key);
  1767                 assert(gpgme_error != GPG_ERR_INV_VALUE);
  1768                 assert(gpgme_error != GPG_ERR_CONFLICT);
  1769             }
  1770             break;
  1771         case GPG_ERR_ENOMEM:
  1772             _switch_mode(_session, GPGME_KEYLIST_MODE_EXTERN,
  1773                     GPGME_KEYLIST_MODE_LOCAL);
  1774             _session->gpgme_op_keylist_end(_session->ctx);
  1775             return PEP_OUT_OF_MEMORY;
  1776         default:
  1777             // BUG: GPGME returns an illegal value instead of GPG_ERR_EOF after
  1778             // reading first key
  1779 #ifndef NDEBUG
  1780             fprintf(stderr, "warning: unknown result 0x%x of"
  1781                     " gpgme_op_keylist_next()\n", gpgme_error);
  1782 #endif
  1783             gpgme_error = GPG_ERR_EOF;
  1784             break;
  1785         };
  1786     } while (gpgme_error != GPG_ERR_EOF);
  1787 
  1788     _session->gpgme_op_keylist_end(_session->ctx);
  1789     _switch_mode(_session, GPGME_KEYLIST_MODE_EXTERN,
  1790             GPGME_KEYLIST_MODE_LOCAL);
  1791     return PEP_STATUS_OK;
  1792 }
  1793 
  1794 DYNAMIC_API PEP_STATUS find_keys(
  1795         PEP_SESSION session, const char *pattern, stringlist_t **keylist
  1796     )
  1797 {
  1798 	pEpSession *_session = (pEpSession *) session;
  1799 	gpgme_error_t gpgme_error;
  1800     gpgme_key_t key;
  1801     stringlist_t *_keylist;
  1802     char *fpr;
  1803 
  1804     assert(session);
  1805     assert(pattern);
  1806     assert(keylist);
  1807 
  1808     *keylist = NULL;
  1809 
  1810     gpgme_error = _session->gpgme_op_keylist_start(_session->ctx, pattern, 0);
  1811     switch (gpgme_error) {
  1812     case GPG_ERR_NO_ERROR:
  1813         break;
  1814     case GPG_ERR_INV_VALUE:
  1815         assert(0);
  1816         return PEP_UNKNOWN_ERROR;
  1817     default:
  1818         return PEP_GET_KEY_FAILED;
  1819     };
  1820 
  1821     _keylist = new_stringlist(NULL);
  1822     stringlist_t *_k = _keylist;
  1823 
  1824     do {
  1825         gpgme_error = _session->gpgme_op_keylist_next(_session->ctx, &key);
  1826         assert(gpgme_error != GPG_ERR_INV_VALUE);
  1827         switch (gpgme_error) {
  1828         case GPG_ERR_EOF:
  1829             break;
  1830         case GPG_ERR_NO_ERROR:
  1831             assert(key);
  1832             assert(key->subkeys);
  1833             fpr = key->subkeys->fpr;
  1834             assert(fpr);
  1835             _k = stringlist_add(_k, fpr);
  1836             assert(_k);
  1837             if (_k != NULL)
  1838                 break;
  1839         case GPG_ERR_ENOMEM:
  1840             free_stringlist(_keylist);
  1841             _session->gpgme_op_keylist_end(_session->ctx);
  1842             return PEP_OUT_OF_MEMORY;
  1843         default:
  1844             // BUG: GPGME returns an illegal value instead of GPG_ERR_EOF after
  1845             // reading first key
  1846 #ifndef NDEBUG
  1847             fprintf(stderr, "warning: unknown result 0x%x of"
  1848                     " gpgme_op_keylist_next()\n", gpgme_error);
  1849 #endif
  1850             gpgme_error = GPG_ERR_EOF;
  1851             break;
  1852         };
  1853     } while (gpgme_error != GPG_ERR_EOF);
  1854 
  1855     _session->gpgme_op_keylist_end(_session->ctx);
  1856     *keylist = _keylist;
  1857     return PEP_STATUS_OK;
  1858 }
  1859 
  1860 PEP_STATUS send_key(PEP_SESSION session, const char *pattern)
  1861 {
  1862 	pEpSession *_session = (pEpSession *) session;
  1863 	gpgme_error_t gpgme_error;
  1864 
  1865     assert(session);
  1866     assert(pattern);
  1867 
  1868     gpgme_error = _session->gpgme_op_export(_session->ctx, pattern,
  1869             GPGME_EXPORT_MODE_EXTERN, NULL);
  1870     assert(gpgme_error != GPG_ERR_INV_VALUE);
  1871     if (gpgme_error == GPG_ERR_NO_ERROR)
  1872         return PEP_STATUS_OK;
  1873     else
  1874         return PEP_CANNOT_SEND_KEY;
  1875 }
  1876 
  1877 void pEp_free(void *p)
  1878 {
  1879     free(p);
  1880 }
  1881 
  1882 DYNAMIC_API PEP_STATUS get_trust(PEP_SESSION session, pEp_identity *identity)
  1883 {
  1884     pEpSession *_session = (pEpSession *) session;
  1885     PEP_STATUS status = PEP_STATUS_OK;
  1886     int result;
  1887 
  1888     assert(session);
  1889     assert(identity);
  1890     assert(identity->user_id);
  1891     assert(identity->user_id[0]);
  1892     assert(identity->fpr);
  1893     assert(identity->fpr[0]);
  1894 
  1895     identity->comm_type = PEP_ct_unknown;
  1896 
  1897     sqlite3_reset(_session->get_trust);
  1898     sqlite3_bind_text(_session->get_trust, 1, identity->user_id, -1, SQLITE_STATIC);
  1899     sqlite3_bind_text(_session->get_trust, 2, identity->fpr, -1, SQLITE_STATIC);
  1900 
  1901     result = sqlite3_step(_session->get_trust);
  1902     switch (result) {
  1903     case SQLITE_ROW: {
  1904         const char * user_id = (const char *) sqlite3_column_text(_session->get_trust, 1);
  1905         int comm_type = (PEP_comm_type) sqlite3_column_int(_session->get_trust, 2);
  1906 
  1907         if (strcmp(user_id, identity->user_id) != 0) {
  1908             free(identity->user_id);
  1909             identity->user_id = strdup(user_id);
  1910             assert(identity->user_id);
  1911             if (identity->user_id == NULL)
  1912                 return PEP_OUT_OF_MEMORY;
  1913         }
  1914         identity->comm_type = comm_type;
  1915         break;
  1916     }
  1917  
  1918     default:
  1919         status = PEP_CANNOT_FIND_IDENTITY;
  1920     }
  1921 
  1922     sqlite3_reset(_session->get_trust);
  1923     return status;
  1924 }
  1925 
  1926 DYNAMIC_API PEP_STATUS get_key_rating(
  1927     PEP_SESSION session,
  1928     const char *fpr,
  1929     PEP_comm_type *comm_type
  1930     )
  1931 {
  1932     pEpSession *_session = (pEpSession *) session;
  1933     PEP_STATUS status = PEP_STATUS_OK;
  1934     gpgme_error_t gpgme_error;
  1935     gpgme_key_t key;
  1936 
  1937     assert(session);
  1938     assert(fpr);
  1939     assert(comm_type);
  1940     
  1941     *comm_type = PEP_ct_unknown;
  1942 
  1943     gpgme_error = _session->gpgme_op_keylist_start(_session->ctx, fpr, 0);
  1944     switch (gpgme_error) {
  1945     case GPG_ERR_NO_ERROR:
  1946         break;
  1947     case GPG_ERR_INV_VALUE:
  1948         assert(0);
  1949         return PEP_UNKNOWN_ERROR;
  1950     default:
  1951         return PEP_GET_KEY_FAILED;
  1952     };
  1953 
  1954     gpgme_error = _session->gpgme_op_keylist_next(_session->ctx, &key);
  1955     assert(gpgme_error != GPG_ERR_INV_VALUE);
  1956 
  1957     switch (key->protocol) {
  1958     case GPGME_PROTOCOL_OpenPGP:
  1959     case GPGME_PROTOCOL_DEFAULT:
  1960         *comm_type = PEP_ct_OpenPGP_unconfirmed;
  1961         break;
  1962     case GPGME_PROTOCOL_CMS:
  1963         *comm_type = PEP_ct_CMS_unconfirmed;
  1964         break;
  1965     default:
  1966         *comm_type = PEP_ct_unknown;
  1967         _session->gpgme_op_keylist_end(_session->ctx);
  1968         return PEP_STATUS_OK;
  1969     }
  1970 
  1971     switch (gpgme_error) {
  1972     case GPG_ERR_EOF:
  1973         break;
  1974     case GPG_ERR_NO_ERROR:
  1975         assert(key);
  1976         assert(key->subkeys);
  1977         for (gpgme_subkey_t sk = key->subkeys; sk != NULL; sk = sk->next) {
  1978             if (sk->length < 1024)
  1979                 *comm_type = PEP_ct_key_too_short;
  1980             else if (
  1981                 (
  1982                        (sk->pubkey_algo == GPGME_PK_RSA)
  1983                     || (sk->pubkey_algo == GPGME_PK_RSA_E)
  1984                     || (sk->pubkey_algo == GPGME_PK_RSA_S)
  1985                 )
  1986                 && sk->length == 1024
  1987             )
  1988                 *comm_type = PEP_ct_OpenPGP_1024_RSA_unconfirmed;
  1989 
  1990             if (sk->invalid) {
  1991                 *comm_type = PEP_ct_key_b0rken;
  1992                 break;
  1993             }
  1994             if (sk->expired) {
  1995                 *comm_type = PEP_ct_key_expired;
  1996                 break;
  1997             }
  1998             if (sk->revoked) {
  1999                 *comm_type = PEP_ct_key_revoked;
  2000                 break;
  2001             }
  2002         }
  2003         break;
  2004     case GPG_ERR_ENOMEM:
  2005         _session->gpgme_op_keylist_end(_session->ctx);
  2006         return PEP_OUT_OF_MEMORY;
  2007     default:
  2008         // BUG: GPGME returns an illegal value instead of GPG_ERR_EOF after
  2009         // reading first key
  2010 #ifndef NDEBUG
  2011         fprintf(stderr, "warning: unknown result 0x%x of"
  2012             " gpgme_op_keylist_next()\n", gpgme_error);
  2013 #endif
  2014         gpgme_error = GPG_ERR_EOF;
  2015         break;
  2016     };
  2017 
  2018     _session->gpgme_op_keylist_end(_session->ctx);
  2019 
  2020     return status;
  2021 }