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