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