Filename: dc_aheader.c ```c #include #include "dc_context.h" #include "dc_aheader.h" #include "dc_apeerstate.h" #include "dc_mimeparser.h" /** * Empty an Autocrypt-header object and free all data associated with it. * * @private @memberof dc_aheader_t * @param aheader The Autocrypt-header object. If you pass NULL here, the function does nothing. * @return None. */ void dc_aheader_empty(dc_aheader_t* aheader) { if (aheader==NULL) { return; } aheader->prefer_encrypt = 0; free(aheader->addr); aheader->addr = NULL; if (aheader->public_key->binary) { dc_key_unref(aheader->public_key); aheader->public_key = dc_key_new(); } } /******************************************************************************* * Render Autocrypt Header ******************************************************************************/ /** * @memberof dc_aheader_t */ char* dc_aheader_render(const dc_aheader_t* aheader) { int success = 0; char* keybase64_wrapped = NULL; dc_strbuilder_t ret; dc_strbuilder_init(&ret, 0); if (aheader==NULL || aheader->addr==NULL || aheader->public_key->binary==NULL || aheader->public_key->type!=DC_KEY_PUBLIC) { goto cleanup; } dc_strbuilder_cat(&ret, "addr="); dc_strbuilder_cat(&ret, aheader->addr); dc_strbuilder_cat(&ret, "; "); if (aheader->prefer_encrypt==DC_PE_MUTUAL) { dc_strbuilder_cat(&ret, "prefer-encrypt=mutual; "); } dc_strbuilder_cat(&ret, "keydata= "); /* the trailing space together with dc_insert_breaks() allows a proper transport */ /* adds a whitespace every 78 characters, this allows libEtPan to wrap the lines according to RFC 5322 (which may insert a linebreak before every whitespace) */ if ((keybase64_wrapped = dc_key_render_base64(aheader->public_key, 78, " ", 0/*no checksum*/))==NULL) { goto cleanup; } dc_strbuilder_cat(&ret, keybase64_wrapped); success = 1; cleanup: if (!success) { free(ret.buf); ret.buf = NULL; } free(keybase64_wrapped); return ret.buf; /* NULL on errors, this may happen for various reasons */ } /******************************************************************************* * Parse Autocrypt Header ******************************************************************************/ static int add_attribute(dc_aheader_t* aheader, const char* name, const char* value /*may be NULL*/) { /* returns 0 if the attribute will result in an invalid header, 1 if the attribute is okay */ if (strcasecmp(name, "addr")==0) { if (value==NULL || !dc_may_be_valid_addr(value) || aheader->addr /* email already given */) { return 0; } aheader->addr = dc_addr_normalize(value); return 1; } #if 0 /* autocrypt 11/2017 no longer uses the type attribute and it will make the autocrypt header invalid */ else if (strcasecmp(name, "type")==0) { if (value==NULL) { return 0; /* attribute with no value results in an invalid header */ } if (strcasecmp(value, "1")==0 || strcasecmp(value, "0" /*deprecated*/)==0 || strcasecmp(value, "p" /*deprecated*/)==0) { return 1; /* PGP-type */ } return 0; /* unknown types result in an invalid header */ } #endif else if (strcasecmp(name, "prefer-encrypt")==0) { if (value && strcasecmp(value, "mutual")==0) { aheader->prefer_encrypt = DC_PE_MUTUAL; return 1; } return 1; /* An Autocrypt level 0 client that sees the attribute with any other value (or that does not see the attribute at all) should interpret the value as nopreference.*/ } else if (strcasecmp(name, "keydata")==0) { if (value==NULL || aheader->public_key->binary || aheader->public_key->bytes) { return 0; /* there is already a k*/ } return dc_key_set_from_base64(aheader->public_key, value, DC_KEY_PUBLIC); } else if (name[0]=='_') { /* Autocrypt-Level0: unknown attributes starting with an underscore can be safely ignored */ return 1; } /* Autocrypt-Level0: unknown attribute, treat the header as invalid */ return 0; } /** * @memberof dc_aheader_t */ int dc_aheader_set_from_string(dc_aheader_t* aheader, const char* header_str__) { /* according to RFC 5322 (Internet Message Format), the given string may contain `\r\n` before any whitespace. we can ignore this issue as (a) no key or value is expected to contain spaces, (b) for the key, non-base64-characters are ignored and (c) for parsing, we ignore `\r\n` as well as tabs for spaces */ #define AHEADER_WS "\t\r\n " char* header_str = NULL; char* p = NULL; char* beg_attr_name = NULL; char* after_attr_name = NULL; char* beg_attr_value = NULL; int success = 0; dc_aheader_empty(aheader); if (aheader==NULL || header_str__==NULL) { goto cleanup; } aheader->prefer_encrypt = DC_PE_NOPREFERENCE; /* value to use if the prefer-encrypted header is missing */ header_str = dc_strdup(header_str__); p = header_str; while (*p) { p += strspn(p, AHEADER_WS "=;"); /* forward to first attribute name beginning */ beg_attr_name = p; beg_attr_value = NULL; p += strcspn(p, AHEADER_WS "=;"); /* get end of attribute name (an attribute may have no value) */ if (p!=beg_attr_name) { /* attribute found */ after_attr_name = p; p += strspn(p, AHEADER_WS); /* skip whitespace between attribute name and possible `=` */ if (*p=='=') { p += strspn(p, AHEADER_WS "="); /* skip spaces and equal signs */ /* read unquoted attribute value until the first semicolon */ beg_attr_value = p; p += strcspn(p, ";"); if (*p!='\0') { *p = '\0'; p++; } dc_trim(beg_attr_value); } else { p += strspn(p, AHEADER_WS ";"); } *after_attr_name = '\0'; if (!add_attribute(aheader, beg_attr_name, beg_attr_value)) { goto cleanup; /* a bad attribute makes the whole header invalid */ } } } /* all needed data found? */ if (aheader->addr && aheader->public_key->binary) { success = 1; } cleanup: free(header_str); if (!success) { dc_aheader_empty(aheader); } return success; } /******************************************************************************* * Main interface ******************************************************************************/ /** * @memberof dc_aheader_t */ dc_aheader_t* dc_aheader_new() { dc_aheader_t* aheader = NULL; if ((aheader=calloc(1, sizeof(dc_aheader_t)))==NULL) { exit(37); /* cannot allocate little memory, unrecoverable error */ } aheader->public_key = dc_key_new(); return aheader; } /** * @memberof dc_aheader_t */ void dc_aheader_unref(dc_aheader_t* aheader) { if (aheader==NULL) { return; } free(aheader->addr); dc_key_unref(aheader->public_key); free(aheader); } /** * @memberof dc_aheader_t */ dc_aheader_t* dc_aheader_new_from_imffields(const char* wanted_from, const struct mailimf_fields* header) { clistiter* cur = NULL; dc_aheader_t* fine_header = NULL; if (wanted_from==NULL || header==NULL) { return 0; } for (cur = clist_begin(header->fld_list); cur!=NULL ; cur=clist_next(cur)) { struct mailimf_field* field = (struct mailimf_field*)clist_content(cur); if (field && field->fld_type==MAILIMF_FIELD_OPTIONAL_FIELD) { struct mailimf_optional_field* optional_field = field->fld_data.fld_optional_field; if (optional_field && optional_field->fld_name && strcasecmp(optional_field->fld_name, "Autocrypt")==0) { /* header found, check if it is valid and matched the wanted address */ dc_aheader_t* test = dc_aheader_new(); if (!dc_aheader_set_from_string(test, optional_field->fld_value) || dc_addr_cmp(test->addr, wanted_from)!=0) { dc_aheader_unref(test); test = NULL; } if (fine_header==NULL) { fine_header = test; /* may still be NULL */ } else if (test) { dc_aheader_unref(fine_header); dc_aheader_unref(test); return NULL; /* more than one valid header for the same address results in an error, see Autocrypt Level 1 */ } } } } return fine_header; /* may be NULL */ } ``` Filename: dc_apeerstate.c ```c #include "dc_context.h" #include "dc_apeerstate.h" #include "dc_aheader.h" #include "dc_hash.h" /******************************************************************************* * dc_apeerstate_t represents the state of an Autocrypt peer - Load/save ******************************************************************************/ static void dc_apeerstate_empty(dc_apeerstate_t* peerstate) { if (peerstate==NULL) { return; } peerstate->last_seen = 0; peerstate->last_seen_autocrypt = 0; peerstate->prefer_encrypt = 0; peerstate->to_save = 0; free(peerstate->addr); peerstate->addr = NULL; free(peerstate->public_key_fingerprint); peerstate->public_key_fingerprint = NULL; free(peerstate->gossip_key_fingerprint); peerstate->gossip_key_fingerprint = NULL; free(peerstate->verified_key_fingerprint); peerstate->verified_key_fingerprint = NULL; dc_key_unref(peerstate->public_key); peerstate->public_key = NULL; peerstate->gossip_timestamp = 0; dc_key_unref(peerstate->gossip_key); peerstate->gossip_key = NULL; dc_key_unref(peerstate->verified_key); peerstate->verified_key = NULL; peerstate->degrade_event = 0; } static void dc_apeerstate_set_from_stmt(dc_apeerstate_t* peerstate, sqlite3_stmt* stmt) { #define PEERSTATE_FIELDS "addr, last_seen, last_seen_autocrypt, prefer_encrypted, public_key, gossip_timestamp, gossip_key, public_key_fingerprint, gossip_key_fingerprint, verified_key, verified_key_fingerprint" peerstate->addr = dc_strdup((char*)sqlite3_column_text (stmt, 0)); peerstate->last_seen = sqlite3_column_int64 (stmt, 1); peerstate->last_seen_autocrypt = sqlite3_column_int64 (stmt, 2); peerstate->prefer_encrypt = sqlite3_column_int (stmt, 3); #define PUBLIC_KEY_COL 4 peerstate->gossip_timestamp = sqlite3_column_int (stmt, 5); #define GOSSIP_KEY_COL 6 peerstate->public_key_fingerprint = dc_strdup((char*)sqlite3_column_text (stmt, 7)); peerstate->gossip_key_fingerprint = dc_strdup((char*)sqlite3_column_text (stmt, 8)); #define VERIFIED_KEY_COL 9 peerstate->verified_key_fingerprint = dc_strdup((char*)sqlite3_column_text(stmt, 10)); if (sqlite3_column_type(stmt, PUBLIC_KEY_COL)!=SQLITE_NULL) { peerstate->public_key = dc_key_new(); dc_key_set_from_stmt(peerstate->public_key, stmt, PUBLIC_KEY_COL, DC_KEY_PUBLIC); } if (sqlite3_column_type(stmt, GOSSIP_KEY_COL)!=SQLITE_NULL) { peerstate->gossip_key = dc_key_new(); dc_key_set_from_stmt(peerstate->gossip_key, stmt, GOSSIP_KEY_COL, DC_KEY_PUBLIC); } if (sqlite3_column_type(stmt, VERIFIED_KEY_COL)!=SQLITE_NULL) { peerstate->verified_key = dc_key_new(); dc_key_set_from_stmt(peerstate->verified_key, stmt, VERIFIED_KEY_COL, DC_KEY_PUBLIC); } } int dc_apeerstate_load_by_addr(dc_apeerstate_t* peerstate, dc_sqlite3_t* sql, const char* addr) { int success = 0; sqlite3_stmt* stmt = NULL; if (peerstate==NULL || sql==NULL || addr==NULL) { goto cleanup; } dc_apeerstate_empty(peerstate); stmt = dc_sqlite3_prepare(sql, "SELECT " PEERSTATE_FIELDS " FROM acpeerstates " " WHERE addr=? COLLATE NOCASE;"); sqlite3_bind_text(stmt, 1, addr, -1, SQLITE_STATIC); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } dc_apeerstate_set_from_stmt(peerstate, stmt); success = 1; cleanup: sqlite3_finalize(stmt); return success; } int dc_apeerstate_load_by_fingerprint(dc_apeerstate_t* peerstate, dc_sqlite3_t* sql, const char* fingerprint) { int success = 0; sqlite3_stmt* stmt = NULL; if (peerstate==NULL || sql==NULL || fingerprint==NULL) { goto cleanup; } dc_apeerstate_empty(peerstate); stmt = dc_sqlite3_prepare(sql, "SELECT " PEERSTATE_FIELDS " FROM acpeerstates " " WHERE public_key_fingerprint=? COLLATE NOCASE " " OR gossip_key_fingerprint=? COLLATE NOCASE " " ORDER BY public_key_fingerprint=? DESC;"); // if for, any reasons, different peers have the same key, prefer the peer with the correct public key. should not happen, however. sqlite3_bind_text(stmt, 1, fingerprint, -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 2, fingerprint, -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 3, fingerprint, -1, SQLITE_STATIC); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } dc_apeerstate_set_from_stmt(peerstate, stmt); success = 1; cleanup: sqlite3_finalize(stmt); return success; } int dc_apeerstate_save_to_db(const dc_apeerstate_t* peerstate, dc_sqlite3_t* sql, int create) { int success = 0; sqlite3_stmt* stmt = NULL; if (peerstate==NULL || sql==NULL || peerstate->addr==NULL) { return 0; } if (create) { stmt = dc_sqlite3_prepare(sql, "INSERT INTO acpeerstates (addr) VALUES(?);"); sqlite3_bind_text(stmt, 1, peerstate->addr, -1, SQLITE_STATIC); sqlite3_step(stmt); sqlite3_finalize(stmt); stmt = NULL; } if ((peerstate->to_save&DC_SAVE_ALL) || create) { stmt = dc_sqlite3_prepare(sql, "UPDATE acpeerstates " " SET last_seen=?, last_seen_autocrypt=?, prefer_encrypted=?, " " public_key=?, gossip_timestamp=?, gossip_key=?, public_key_fingerprint=?, gossip_key_fingerprint=?, verified_key=?, verified_key_fingerprint=? " " WHERE addr=?;"); sqlite3_bind_int64(stmt, 1, peerstate->last_seen); sqlite3_bind_int64(stmt, 2, peerstate->last_seen_autocrypt); sqlite3_bind_int64(stmt, 3, peerstate->prefer_encrypt); sqlite3_bind_blob (stmt, 4, peerstate->public_key? peerstate->public_key->binary : NULL/*results in sqlite3_bind_null()*/, peerstate->public_key? peerstate->public_key->bytes : 0, SQLITE_STATIC); sqlite3_bind_int64(stmt, 5, peerstate->gossip_timestamp); sqlite3_bind_blob (stmt, 6, peerstate->gossip_key? peerstate->gossip_key->binary : NULL/*results in sqlite3_bind_null()*/, peerstate->gossip_key? peerstate->gossip_key->bytes : 0, SQLITE_STATIC); sqlite3_bind_text (stmt, 7, peerstate->public_key_fingerprint, -1, SQLITE_STATIC); sqlite3_bind_text (stmt, 8, peerstate->gossip_key_fingerprint, -1, SQLITE_STATIC); sqlite3_bind_blob (stmt, 9, peerstate->verified_key? peerstate->verified_key->binary : NULL/*results in sqlite3_bind_null()*/, peerstate->verified_key? peerstate->verified_key->bytes : 0, SQLITE_STATIC); sqlite3_bind_text (stmt,10, peerstate->verified_key_fingerprint, -1, SQLITE_STATIC); sqlite3_bind_text (stmt,11, peerstate->addr, -1, SQLITE_STATIC); if (sqlite3_step(stmt)!=SQLITE_DONE) { goto cleanup; } sqlite3_finalize(stmt); stmt = NULL; } else if (peerstate->to_save&DC_SAVE_TIMESTAMPS) { stmt = dc_sqlite3_prepare(sql, "UPDATE acpeerstates SET last_seen=?, last_seen_autocrypt=?, gossip_timestamp=? WHERE addr=?;"); sqlite3_bind_int64(stmt, 1, peerstate->last_seen); sqlite3_bind_int64(stmt, 2, peerstate->last_seen_autocrypt); sqlite3_bind_int64(stmt, 3, peerstate->gossip_timestamp); sqlite3_bind_text (stmt, 4, peerstate->addr, -1, SQLITE_STATIC); if (sqlite3_step(stmt)!=SQLITE_DONE) { goto cleanup; } sqlite3_finalize(stmt); stmt = NULL; } if ((peerstate->to_save&DC_SAVE_ALL) || create) { dc_reset_gossiped_timestamp(peerstate->context, 0); } success = 1; cleanup: sqlite3_finalize(stmt); return success; } /******************************************************************************* * Main interface ******************************************************************************/ dc_apeerstate_t* dc_apeerstate_new(dc_context_t* context) { dc_apeerstate_t* peerstate = NULL; if ((peerstate=calloc(1, sizeof(dc_apeerstate_t)))==NULL) { exit(43); /* cannot allocate little memory, unrecoverable error */ } peerstate->context = context; return peerstate; } void dc_apeerstate_unref(dc_apeerstate_t* peerstate) { dc_apeerstate_empty(peerstate); free(peerstate); } /** * Render an Autocrypt-Gossip header value. The contained key is either * public_key or gossip_key if public_key is NULL. * * @memberof dc_apeerstate_t * @param peerstate The peerstate object. * @return String that can be be used directly in an `Autocrypt-Gossip:` statement, * `Autocrypt-Gossip:` is _not_ included in the returned string. If there * is not key for the peer that can be gossiped, NULL is returned. */ char* dc_apeerstate_render_gossip_header(const dc_apeerstate_t* peerstate, int min_verified) { char* ret = NULL; dc_aheader_t* autocryptheader = dc_aheader_new(); if (peerstate==NULL || peerstate->addr==NULL) { goto cleanup; } autocryptheader->prefer_encrypt = DC_PE_NOPREFERENCE; /* the spec says, we SHOULD NOT gossip this flag */ autocryptheader->addr = dc_strdup(peerstate->addr); autocryptheader->public_key = dc_key_ref(dc_apeerstate_peek_key(peerstate, min_verified)); /* may be NULL */ ret = dc_aheader_render(autocryptheader); cleanup: dc_aheader_unref(autocryptheader); return ret; } /** * Return either public_key or gossip_key if public_key is null or not verified. * The function does not check if the keys are valid but the caller can assume * the returned key has data. * * This function does not do the Autocrypt encryption recommendation; it just * returns a key that can be used. * * @memberof dc_apeerstate_t * @param peerstate The peerstate object. * @param min_verified The minimal verification criterion the key should match. * Typically either DC_NOT_VERIFIED (0) if there is no need for the key being verified * or DC_BIDIRECT_VERIFIED (2) for bidirectional verification requirement. * @return public_key or gossip_key, NULL if nothing is available. * the returned pointer MUST NOT be unref()'d. */ dc_key_t* dc_apeerstate_peek_key(const dc_apeerstate_t* peerstate, int min_verified) { if ( peerstate==NULL || (peerstate->public_key && (peerstate->public_key->binary==NULL || peerstate->public_key->bytes<=0)) || (peerstate->gossip_key && (peerstate->gossip_key->binary==NULL || peerstate->gossip_key->bytes<=0)) || (peerstate->verified_key && (peerstate->verified_key->binary==NULL || peerstate->verified_key->bytes<=0))) { return NULL; } if (min_verified) { return peerstate->verified_key; } if (peerstate->public_key) { return peerstate->public_key; } return peerstate->gossip_key; } /******************************************************************************* * Change state ******************************************************************************/ int dc_apeerstate_init_from_header(dc_apeerstate_t* peerstate, const dc_aheader_t* header, time_t message_time) { if (peerstate==NULL || header==NULL) { return 0; } dc_apeerstate_empty(peerstate); peerstate->addr = dc_strdup(header->addr); peerstate->last_seen = message_time; peerstate->last_seen_autocrypt = message_time; peerstate->to_save |= DC_SAVE_ALL; peerstate->prefer_encrypt = header->prefer_encrypt; peerstate->public_key = dc_key_new(); dc_key_set_from_key(peerstate->public_key, header->public_key); dc_apeerstate_recalc_fingerprint(peerstate); return 1; } int dc_apeerstate_init_from_gossip(dc_apeerstate_t* peerstate, const dc_aheader_t* gossip_header, time_t message_time) { if (peerstate==NULL || gossip_header==NULL) { return 0; } dc_apeerstate_empty(peerstate); peerstate->addr = dc_strdup(gossip_header->addr); peerstate->gossip_timestamp = message_time; peerstate->to_save |= DC_SAVE_ALL; peerstate->gossip_key = dc_key_new(); dc_key_set_from_key(peerstate->gossip_key, gossip_header->public_key); dc_apeerstate_recalc_fingerprint(peerstate); return 1; } int dc_apeerstate_degrade_encryption(dc_apeerstate_t* peerstate, time_t message_time) { if (peerstate==NULL) { return 0; } if (peerstate->prefer_encrypt==DC_PE_MUTUAL) { peerstate->degrade_event |= DC_DE_ENCRYPTION_PAUSED; } peerstate->prefer_encrypt = DC_PE_RESET; peerstate->last_seen = message_time; /*last_seen_autocrypt is not updated as there was not Autocrypt:-header seen*/ peerstate->to_save |= DC_SAVE_ALL; return 1; } void dc_apeerstate_apply_header(dc_apeerstate_t* peerstate, const dc_aheader_t* header, time_t message_time) { if (peerstate==NULL || header==NULL || peerstate->addr==NULL || header->addr==NULL || header->public_key->binary==NULL || strcasecmp(peerstate->addr, header->addr)!=0) { return; } if (message_time > peerstate->last_seen_autocrypt) { peerstate->last_seen = message_time; peerstate->last_seen_autocrypt = message_time; peerstate->to_save |= DC_SAVE_TIMESTAMPS; if ((header->prefer_encrypt==DC_PE_MUTUAL || header->prefer_encrypt==DC_PE_NOPREFERENCE) /*this also switches from DC_PE_RESET to DC_PE_NOPREFERENCE, which is just fine as the function is only called _if_ the Autocrypt:-header is preset at all */ && header->prefer_encrypt!=peerstate->prefer_encrypt) { if (peerstate->prefer_encrypt==DC_PE_MUTUAL && header->prefer_encrypt!=DC_PE_MUTUAL) { peerstate->degrade_event |= DC_DE_ENCRYPTION_PAUSED; } peerstate->prefer_encrypt = header->prefer_encrypt; peerstate->to_save |= DC_SAVE_ALL; } if (peerstate->public_key==NULL) { peerstate->public_key = dc_key_new(); } if (!dc_key_equals(peerstate->public_key, header->public_key)) { dc_key_set_from_key(peerstate->public_key, header->public_key); dc_apeerstate_recalc_fingerprint(peerstate); peerstate->to_save |= DC_SAVE_ALL; } } } void dc_apeerstate_apply_gossip(dc_apeerstate_t* peerstate, const dc_aheader_t* gossip_header, time_t message_time) { if (peerstate==NULL || gossip_header==NULL || peerstate->addr==NULL || gossip_header->addr==NULL || gossip_header->public_key->binary==NULL || strcasecmp(peerstate->addr, gossip_header->addr)!=0) { return; } if (message_time > peerstate->gossip_timestamp) { peerstate->gossip_timestamp = message_time; peerstate->to_save |= DC_SAVE_TIMESTAMPS; if (peerstate->gossip_key==NULL) { peerstate->gossip_key = dc_key_new(); } if (!dc_key_equals(peerstate->gossip_key, gossip_header->public_key)) { dc_key_set_from_key(peerstate->gossip_key, gossip_header->public_key); dc_apeerstate_recalc_fingerprint(peerstate); peerstate->to_save |= DC_SAVE_ALL; } } } /** * Recalculate the fingerprints for the keys. * * If the fingerprint has changed, the verified-state is reset. * * An explicit call to this function from outside this class is only needed * for database updates; the dc_apeerstate_init_*() and dc_apeerstate_apply_*() * functions update the fingerprint automatically as needed. * * @memberof dc_apeerstate_t */ int dc_apeerstate_recalc_fingerprint(dc_apeerstate_t* peerstate) { int success = 0; char* old_public_fingerprint = NULL; char* old_gossip_fingerprint = NULL; if (peerstate==NULL) { goto cleanup; } if (peerstate->public_key) { old_public_fingerprint = peerstate->public_key_fingerprint; peerstate->public_key_fingerprint = dc_key_get_fingerprint(peerstate->public_key); /* returns the empty string for errors, however, this should be saved as well as it represents an erroneous key */ if (old_public_fingerprint==NULL || old_public_fingerprint[0]==0 || peerstate->public_key_fingerprint==NULL || peerstate->public_key_fingerprint[0]==0 || strcasecmp(old_public_fingerprint, peerstate->public_key_fingerprint)!=0) { peerstate->to_save |= DC_SAVE_ALL; if (old_public_fingerprint && old_public_fingerprint[0]) { // no degrade event when we recveive just the initial fingerprint peerstate->degrade_event |= DC_DE_FINGERPRINT_CHANGED; } } } if (peerstate->gossip_key) { old_gossip_fingerprint = peerstate->gossip_key_fingerprint; peerstate->gossip_key_fingerprint = dc_key_get_fingerprint(peerstate->gossip_key); /* returns the empty string for errors, however, this should be saved as well as it represents an erroneous key */ if (old_gossip_fingerprint==NULL || old_gossip_fingerprint[0]==0 || peerstate->gossip_key_fingerprint==NULL || peerstate->gossip_key_fingerprint[0]==0 || strcasecmp(old_gossip_fingerprint, peerstate->gossip_key_fingerprint)!=0) { peerstate->to_save |= DC_SAVE_ALL; if (old_gossip_fingerprint && old_gossip_fingerprint[0]) { // no degrade event when we recveive just the initial fingerprint peerstate->degrade_event |= DC_DE_FINGERPRINT_CHANGED; } } } success = 1; cleanup: free(old_public_fingerprint); free(old_gossip_fingerprint); return success; } /** * If the fingerprint of the peerstate equals the given fingerprint, the * peerstate is marked as being verified. * * The given fingerprint is present only to ensure the peer has not changed * between fingerprint comparison and calling this function. * * @memberof dc_apeerstate_t * @param peerstate The peerstate object. * @param which_key Which key should be marked as being verified? DC_PS_GOSSIP_KEY (1) or DC_PS_PUBLIC_KEY (2) * @param fingerprint Fingerprint expected in the object * @param verified DC_BIDIRECT_VERIFIED (2): contact verified in both directions * @return 1=the given fingerprint is equal to the peer's fingerprint and * the verified-state is set; you should call dc_apeerstate_save_to_db() * to permanently store this state. * 0=the given fingerprint is not eqial to the peer's fingerprint, * verified-state not changed. */ int dc_apeerstate_set_verified(dc_apeerstate_t* peerstate, int which_key, const char* fingerprint, int verified) { int success = 0; if (peerstate==NULL || (which_key!=DC_PS_GOSSIP_KEY && which_key!=DC_PS_PUBLIC_KEY) || (verified!=DC_BIDIRECT_VERIFIED)) { goto cleanup; } if (which_key==DC_PS_PUBLIC_KEY && peerstate->public_key_fingerprint!=NULL && peerstate->public_key_fingerprint[0]!=0 && fingerprint[0]!=0 && strcasecmp(peerstate->public_key_fingerprint, fingerprint)==0) { peerstate->to_save |= DC_SAVE_ALL; peerstate->verified_key = dc_key_ref(peerstate->public_key); peerstate->verified_key_fingerprint = dc_strdup(peerstate->public_key_fingerprint); success = 1; } if (which_key==DC_PS_GOSSIP_KEY && peerstate->gossip_key_fingerprint!=NULL && peerstate->gossip_key_fingerprint[0]!=0 && fingerprint[0]!=0 && strcasecmp(peerstate->gossip_key_fingerprint, fingerprint)==0) { peerstate->to_save |= DC_SAVE_ALL; peerstate->verified_key = dc_key_ref(peerstate->gossip_key); peerstate->verified_key_fingerprint = dc_strdup(peerstate->gossip_key_fingerprint); success = 1; } cleanup: return success; } int dc_apeerstate_has_verified_key(const dc_apeerstate_t* peerstate, const dc_hash_t* fingerprints) { if (peerstate==NULL || fingerprints==NULL) { return 0; } if (peerstate->verified_key && peerstate->verified_key_fingerprint && dc_hash_find_str(fingerprints, peerstate->verified_key_fingerprint)) { return 1; } return 0; } ``` Filename: dc_array.c ```c #include "dc_context.h" #include "dc_array.h" #define DC_ARRAY_MAGIC 0x000a11aa /** * Create an array object in memory. * * @private @memberof dc_array_t * @param context The context object that should be stored in the array object. May be NULL. * @param type 0 for a standard array of int or one of DC_ARRAY_*. * @param initsize Initial maximal size of the array. If you add more items, the internal data pointer is reallocated. * @return New array object of the requested size, the data should be set directly. */ dc_array_t* dc_array_new_typed(dc_context_t* context, int type, size_t initsize) { dc_array_t* array = NULL; array = (dc_array_t*) calloc(1, sizeof(dc_array_t)); if (array==NULL) { exit(47); } array->magic = DC_ARRAY_MAGIC; array->context = context; array->count = 0; array->allocated = initsize<1? 1 : initsize; array->type = type; array->array = malloc(array->allocated * sizeof(uintptr_t)); if (array->array==NULL) { exit(48); } return array; } dc_array_t* dc_array_new(dc_context_t* context, size_t initsize) { return dc_array_new_typed(context, 0, initsize); } /** * Free an array object. Does not free any data items. * * @memberof dc_array_t * @param array The array object to free, * created eg. by dc_get_chatlist(), dc_get_contacts() and so on. * If NULL is given, nothing is done. * @return None. */ void dc_array_unref(dc_array_t* array) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC) { return; } if (array->type==DC_ARRAY_LOCATIONS) { dc_array_free_ptr(array); } free(array->array); array->magic = 0; free(array); } /** * Calls free() for each item and sets the item to 0 afterwards. * The array object itself is not deleted and the size of the array stays the same. * * @private @memberof dc_array_t * @param array The array object. * @return None. */ void dc_array_free_ptr(dc_array_t* array) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC) { return; } for (size_t i = 0; icount; i++) { if (array->type==DC_ARRAY_LOCATIONS) { free(((struct _dc_location*)array->array[i])->marker); } free((void*)array->array[i]); array->array[i] = 0; } } /** * Duplicates the array, take care if the array contains pointers to objects, take care to free them only once afterwards! * If the array only contains integers, you are always save. * * @private @memberof dc_array_t * @param array The array object. * @return The duplicated array. */ dc_array_t* dc_array_duplicate(const dc_array_t* array) { dc_array_t* ret = NULL; if (array==NULL || array->magic!=DC_ARRAY_MAGIC) { return NULL; } ret = dc_array_new(array->context, array->allocated); ret->count = array->count; memcpy(ret->array, array->array, array->count * sizeof(uintptr_t)); return ret; } static int cmp_intptr_t(const void* p1, const void* p2) { uintptr_t v1 = *(uintptr_t*)p1; uintptr_t v2 = *(uintptr_t*)p2; return (v1v2)? 1 : 0); /* CAVE: do not use v1-v2 as the uintptr_t may be 64bit and the return value may be 32bit only... */ } /** * Sort the array, assuming it contains unsigned integers. * * @private @memberof dc_array_t * @param array The array object. * @return The duplicated array. */ void dc_array_sort_ids(dc_array_t* array) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || array->count <= 1) { return; } qsort(array->array, array->count, sizeof(uintptr_t), cmp_intptr_t); } static int cmp_strings_t(const void* p1, const void* p2) { const char* v1 = *(const char **)p1; const char* v2 = *(const char **)p2; return strcmp(v1, v2); } /** * Sort the array, assuming it contains pointers to strings. * * @private @memberof dc_array_t * @param array The array object. * @return The duplicated array. */ void dc_array_sort_strings(dc_array_t* array) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || array->count <= 1) { return; } qsort(array->array, array->count, sizeof(char*), cmp_strings_t); } /** * Empty an array object. Allocated data is not freed by this function, only the count is set to null. * * @private @memberof dc_array_t * @param array The array object to empty. * @return None. */ void dc_array_empty(dc_array_t* array) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC) { return; } array->count = 0; } /** * Add an unsigned integer to the array. * After calling this function the size of the array grows by one. * It is okay to add the ID 0, event in this case, the array grows by one. * * @param array The array to add the item to. * @param item The item to add. * @return None. */ void dc_array_add_uint(dc_array_t* array, uintptr_t item) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC) { return; } if (array->count==array->allocated) { int newsize = (array->allocated * 2) + 10; if ((array->array=realloc(array->array, newsize*sizeof(uintptr_t)))==NULL) { exit(49); } array->allocated = newsize; } array->array[array->count] = item; array->count++; } /** * Add an ID to the array. * After calling this function the size of the array grows by one. * It is okay to add the ID 0, event in this case, the array grows by one. * * @param array The array to add the item to. * @param item The item to add. * @return None. */ void dc_array_add_id(dc_array_t* array, uint32_t item) { dc_array_add_uint(array, item); } /** * Add an pointer to the array. * After calling this function the size of the array grows by one. * It is okay to add the ID 0, event in this case, the array grows by one. * * @param array The array to add the item to. * @param item The item to add. * @return None. */ void dc_array_add_ptr(dc_array_t* array, void* item) { dc_array_add_uint(array, (uintptr_t)item); } /** * Find out the number of items in an array. * * @memberof dc_array_t * @param array The array object. * @return Returns the number of items in a dc_array_t object. 0 on errors or if the array is empty. */ size_t dc_array_get_cnt(const dc_array_t* array) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC) { return 0; } return array->count; } /** * Get the item at the given index as an unsigned integer. * The size of the integer is always larget enough to hold a pointer. * * @memberof dc_array_t * @param array The array object. * @param index Index of the item to get. Must be between 0 and dc_array_get_cnt()-1. * @return Returns the item at the given index. Returns 0 on errors or if the array is empty. */ uintptr_t dc_array_get_uint(const dc_array_t* array, size_t index) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || index>=array->count) { return 0; } return array->array[index]; } /** * Get the item at the given index as an ID. * * @memberof dc_array_t * @param array The array object. * @param index Index of the item to get. Must be between 0 and dc_array_get_cnt()-1. * @return Returns the item at the given index. Returns 0 on errors or if the array is empty. */ uint32_t dc_array_get_id(const dc_array_t* array, size_t index) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || index>=array->count) { return 0; } if (array->type==DC_ARRAY_LOCATIONS) { return ((struct _dc_location*)array->array[index])->location_id; } return (uint32_t)array->array[index]; } /** * Get the item at the given index as an ID. * * @memberof dc_array_t * @param array The array object. * @param index Index of the item to get. Must be between 0 and dc_array_get_cnt()-1. * @return Returns the item at the given index. Returns 0 on errors or if the array is empty. */ void* dc_array_get_ptr(const dc_array_t* array, size_t index) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || index>=array->count) { return 0; } return (void*)array->array[index]; } /** * Return the latitude of the item at the given index. * * @memberof dc_array_t * @param array The array object. * @param index Index of the item. Must be between 0 and dc_array_get_cnt()-1. * @return Latitude of the item at the given index. * 0.0 if there is no latitude bound to the given item, */ double dc_array_get_latitude(const dc_array_t* array, size_t index) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || index>=array->count || array->type!=DC_ARRAY_LOCATIONS || array->array[index]==0 ) { return 0; } return ((struct _dc_location*)array->array[index])->latitude; } /** * Return the longitude of the item at the given index. * * @memberof dc_array_t * @param array The array object. * @param index Index of the item. Must be between 0 and dc_array_get_cnt()-1. * @return Latitude of the item at the given index. * 0.0 if there is no longitude bound to the given item, */ double dc_array_get_longitude(const dc_array_t* array, size_t index) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || index>=array->count || array->type!=DC_ARRAY_LOCATIONS || array->array[index]==0 ) { return 0; } return ((struct _dc_location*)array->array[index])->longitude; } /** * Return the accuracy of the item at the given index. * See dc_set_location() for more information about the accuracy. * * @memberof dc_array_t * @param array The array object. * @param index Index of the item. Must be between 0 and dc_array_get_cnt()-1. * @return Accuracy of the item at the given index. * 0.0 if there is no longitude bound to the given item, */ double dc_array_get_accuracy(const dc_array_t* array, size_t index) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || index>=array->count || array->type!=DC_ARRAY_LOCATIONS || array->array[index]==0 ) { return 0; } return ((struct _dc_location*)array->array[index])->accuracy; } /** * Return the timestamp of the item at the given index. * * @memberof dc_array_t * @param array The array object. * @param index Index of the item. Must be between 0 and dc_array_get_cnt()-1. * @return Timestamp of the item at the given index. * 0 if there is no timestamp bound to the given item, */ time_t dc_array_get_timestamp(const dc_array_t* array, size_t index) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || index>=array->count || array->type!=DC_ARRAY_LOCATIONS || array->array[index]==0 ) { return 0; } return ((struct _dc_location*)array->array[index])->timestamp; } /** * Return the message-id of the item at the given index. * * @memberof dc_array_t * @param array The array object. * @param index Index of the item. Must be between 0 and dc_array_get_cnt()-1. * @return Message-id of the item at the given index. * 0 if there is no message-id bound to the given item, */ uint32_t dc_array_get_msg_id(const dc_array_t* array, size_t index) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || index>=array->count || array->type!=DC_ARRAY_LOCATIONS || array->array[index]==0 ) { return 0; } return ((struct _dc_location*)array->array[index])->msg_id; } /** * Return the chat-id of the item at the given index. * * @memberof dc_array_t * @param array The array object. * @param index Index of the item. Must be between 0 and dc_array_get_cnt()-1. * @return Chat-id of the item at the given index. * 0 if there is no chat-id bound to the given item, */ uint32_t dc_array_get_chat_id(const dc_array_t* array, size_t index) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || index>=array->count || array->type!=DC_ARRAY_LOCATIONS || array->array[index]==0 ) { return 0; } return ((struct _dc_location*)array->array[index])->chat_id; } /** * Return the contact-id of the item at the given index. * * @memberof dc_array_t * @param array The array object. * @param index Index of the item. Must be between 0 and dc_array_get_cnt()-1. * @return Contact-id of the item at the given index. * 0 if there is no contact-id bound to the given item, */ uint32_t dc_array_get_contact_id(const dc_array_t* array, size_t index) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || index>=array->count || array->type!=DC_ARRAY_LOCATIONS || array->array[index]==0 ) { return 0; } return ((struct _dc_location*)array->array[index])->contact_id; } /** * Return the marker-character of the item at the given index. * Marker-character are typically bound to locations * returned by dc_get_locations() * and are typically created by on-character-messages * which can also be an emoticon :) * * @memberof dc_array_t * @param array The array object. * @param index Index of the item. Must be between 0 and dc_array_get_cnt()-1. * @return Marker-character of the item at the given index. * NULL if there is no marker-character bound to the given item. * The returned value must be free()'d after usage. */ char* dc_array_get_marker(const dc_array_t* array, size_t index) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || index>=array->count || array->type!=DC_ARRAY_LOCATIONS || array->array[index]==0 ) { return 0; } return dc_strdup_keep_null(((struct _dc_location*)array->array[index])->marker); } /** * Return the independent-state of the location at the given index. * Independent locations do not belong to the track of the user. * * @memberof dc_array_t * @param array The array object. * @param index Index of the item. Must be between 0 and dc_array_get_cnt()-1. * @return 0=Location belongs to the track of the user, * 1=Location was reported independently. */ int dc_array_is_independent(const dc_array_t* array, size_t index) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC || index>=array->count || array->type!=DC_ARRAY_LOCATIONS || array->array[index]==0 ) { return 0; } return ((struct _dc_location*)array->array[index])->independent; } /** * Check if a given ID is present in an array. * * @private @memberof dc_array_t * @param array The array object to search in. * @param needle The ID to search for. * @param[out] ret_index If set, this will receive the index. Set to NULL if you're not interested in the index. * @return 1=ID is present in array, 0=ID not found. */ int dc_array_search_id(const dc_array_t* array, uint32_t needle, size_t* ret_index) { if (array==NULL || array->magic!=DC_ARRAY_MAGIC) { return 0; } uintptr_t* data = array->array; size_t i, cnt = array->count; for (i=0; imagic!=DC_ARRAY_MAGIC) { return NULL; } return array->array; } char* dc_arr_to_string(const uint32_t* arr, int cnt) { /* return comma-separated value-string from integer array */ char* ret = NULL; const char* sep = ","; if (arr==NULL || cnt <= 0) { return dc_strdup(""); } /* use a macro to allow using integers of different bitwidths */ #define INT_ARR_TO_STR(a, c) { \ int i; \ ret = malloc((c)*(11+strlen(sep))/*sign,10 digits,sep*/+1/*terminating zero*/); \ if (ret==NULL) { exit(35); } \ ret[0] = 0; \ for (i=0; i<(c); i++) { \ if (i) { \ strcat(ret, sep); \ } \ sprintf(&ret[strlen(ret)], "%lu", (unsigned long)(a)[i]); \ } \ } INT_ARR_TO_STR(arr, cnt); return ret; } char* dc_array_get_string(const dc_array_t* array, const char* sep) { char* ret = NULL; if (array==NULL || array->magic!=DC_ARRAY_MAGIC || sep==NULL) { return dc_strdup(""); } INT_ARR_TO_STR(array->array, array->count); return ret; } ``` Filename: dc_chat.c ```c #include #include "dc_context.h" #include "dc_job.h" #include "dc_smtp.h" #include "dc_imap.h" #include "dc_mimefactory.h" #include "dc_apeerstate.h" #define DC_CHAT_MAGIC 0xc4a7c4a7 /** * Create a chat object in memory. * * @private @memberof dc_chat_t * @param context The context that should be stored in the chat object. * @return New and empty chat object, must be freed using dc_chat_unref(). */ dc_chat_t* dc_chat_new(dc_context_t* context) { dc_chat_t* chat = NULL; if (context==NULL || (chat=calloc(1, sizeof(dc_chat_t)))==NULL) { exit(14); /* cannot allocate little memory, unrecoverable error */ } chat->magic = DC_CHAT_MAGIC; chat->context = context; chat->type = DC_CHAT_TYPE_UNDEFINED; chat->param = dc_param_new(); return chat; } /** * Free a chat object. * * @memberof dc_chat_t * @param chat Chat object are returned eg. by dc_get_chat(). * If NULL is given, nothing is done. * @return None. */ void dc_chat_unref(dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return; } dc_chat_empty(chat); dc_param_unref(chat->param); chat->magic = 0; free(chat); } /** * Empty a chat object. * * @private @memberof dc_chat_t * @param chat The chat object to empty. * @return None. */ void dc_chat_empty(dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return; } free(chat->name); chat->name = NULL; chat->type = DC_CHAT_TYPE_UNDEFINED; chat->id = 0; free(chat->grpid); chat->grpid = NULL; chat->blocked = 0; chat->gossiped_timestamp = 0; dc_param_set_packed(chat->param, NULL); } /** * Get chat ID. The chat ID is the ID under which the chat is filed in the database. * * Special IDs: * - DC_CHAT_ID_DEADDROP (1) - Virtual chat containing messages which senders are not confirmed by the user. * - DC_CHAT_ID_STARRED (5) - Virtual chat containing all starred messages- * - DC_CHAT_ID_ARCHIVED_LINK (6) - A link at the end of the chatlist, if present the UI should show the button "Archived chats"- * * "Normal" chat IDs are larger than these special IDs (larger than DC_CHAT_ID_LAST_SPECIAL). * * @memberof dc_chat_t * @param chat The chat object. * @return Chat ID. 0 on errors. */ uint32_t dc_chat_get_id(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return 0; } return chat->id; } /** * Get chat type. * * Currently, there are two chat types: * * - DC_CHAT_TYPE_SINGLE (100) - a normal chat is a chat with a single contact, * chats_contacts contains one record for the user. DC_CONTACT_ID_SELF * (see dc_contact_t::id) is added _only_ for a self talk. * * - DC_CHAT_TYPE_GROUP (120) - a group chat, chats_contacts contain all group * members, incl. DC_CONTACT_ID_SELF * * - DC_CHAT_TYPE_VERIFIED_GROUP (130) - a verified group chat. In verified groups, * all members are verified and encryption is always active and cannot be disabled. * * @memberof dc_chat_t * @param chat The chat object. * @return Chat type. */ int dc_chat_get_type(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return DC_CHAT_TYPE_UNDEFINED; } return chat->type; } /** * Get name of a chat. For one-to-one chats, this is the name of the contact. * For group chats, this is the name given eg. to dc_create_group_chat() or * received by a group-creation message. * * To change the name, use dc_set_chat_name() * * See also: dc_chat_get_subtitle() * * @memberof dc_chat_t * @param chat The chat object. * @return Chat name as a string. Must be free()'d after usage. Never NULL. */ char* dc_chat_get_name(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return dc_strdup("Err"); } return dc_strdup(chat->name); } /** * Get a subtitle for a chat. The subtitle is eg. the email-address or the * number of group members. * * See also: dc_chat_get_name() * * @memberof dc_chat_t * @param chat The chat object to calulate the subtitle for. * @return Subtitle as a string. Must be free()'d after usage. Never NULL. */ char* dc_chat_get_subtitle(const dc_chat_t* chat) { /* returns either the address or the number of chat members */ char* ret = NULL; if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return dc_strdup("Err"); } if (chat->type==DC_CHAT_TYPE_SINGLE && dc_param_exists(chat->param, DC_PARAM_SELFTALK)) { ret = dc_stock_str(chat->context, DC_STR_SELFTALK_SUBTITLE); } else if (chat->type==DC_CHAT_TYPE_SINGLE) { int r; sqlite3_stmt* stmt = dc_sqlite3_prepare(chat->context->sql, "SELECT c.addr FROM chats_contacts cc " " LEFT JOIN contacts c ON c.id=cc.contact_id " " WHERE cc.chat_id=?;"); sqlite3_bind_int(stmt, 1, chat->id); r = sqlite3_step(stmt); if (r==SQLITE_ROW) { ret = dc_strdup((const char*)sqlite3_column_text(stmt, 0)); } sqlite3_finalize(stmt); } else if (DC_CHAT_TYPE_IS_MULTI(chat->type)) { int cnt = 0; if (chat->id==DC_CHAT_ID_DEADDROP) { ret = dc_stock_str(chat->context, DC_STR_DEADDROP); /* typically, the subtitle for the deaddropn is not displayed at all */ } else { cnt = dc_get_chat_contact_cnt(chat->context, chat->id); ret = dc_stock_str_repl_int(chat->context, DC_STR_MEMBER, cnt /*SELF is included in group chats (if not removed)*/); } } return ret? ret : dc_strdup("Err"); } /** * Get the chat's profile image. * For groups, this is the image set by any group member * using dc_set_chat_profile_image(). * For normal chats, this is the image set by each remote user on their own * using dc_set_config(context, "selfavatar", image). * * @memberof dc_chat_t * @param chat The chat object. * @return Path and file if the profile image, if any. * NULL otherwise. * Must be free()'d after usage. */ char* dc_chat_get_profile_image(const dc_chat_t* chat) { char* image_rel = NULL; char* image_abs = NULL; dc_array_t* contacts = NULL; dc_contact_t* contact = NULL; if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { goto cleanup; } image_rel = dc_param_get(chat->param, DC_PARAM_PROFILE_IMAGE, NULL); if (image_rel && image_rel[0]) { image_abs = dc_get_abs_path(chat->context, image_rel); } else if(chat->type==DC_CHAT_TYPE_SINGLE) { contacts = dc_get_chat_contacts(chat->context, chat->id); if (contacts->count >= 1) { contact = dc_get_contact(chat->context, contacts->array[0]); image_abs = dc_contact_get_profile_image(contact); } } cleanup: free(image_rel); dc_array_unref(contacts); dc_contact_unref(contact); return image_abs; } /** * Get a color for the chat. * For 1:1 chats, the color is calculated from the contact's email address. * Otherwise, the chat name is used. * The color can be used for an fallback avatar with white initials * as well as for headlines in bubbles of group chats. * * @memberof dc_chat_t * @param chat The chat object. * @return Color as 0x00rrggbb with rr=red, gg=green, bb=blue * each in the range 0-255. */ uint32_t dc_chat_get_color(const dc_chat_t* chat) { uint32_t color = 0; dc_array_t* contacts = NULL; dc_contact_t* contact = NULL; if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { goto cleanup; } if(chat->type==DC_CHAT_TYPE_SINGLE) { contacts = dc_get_chat_contacts(chat->context, chat->id); if (contacts->count >= 1) { contact = dc_get_contact(chat->context, contacts->array[0]); color = dc_str_to_color(contact->addr); } } else { color = dc_str_to_color(chat->name); } cleanup: dc_array_unref(contacts); dc_contact_unref(contact); return color; } /** * Get archived state. * * - 0 = normal chat, not archived, not sticky. * - 1 = chat archived * - 2 = chat sticky (reserved for future use, if you do not support this value, just treat the chat as a normal one) * * To archive or unarchive chats, use dc_archive_chat(). * If chats are archived, this should be shown in the UI by a little icon or text, * eg. the search will also return archived chats. * * @memberof dc_chat_t * @param chat The chat object. * @return Archived state. */ int dc_chat_get_archived(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return 0; } return chat->archived; } /** * Check if a group chat is still unpromoted. * * After the creation with dc_create_group_chat() the chat is usually unpromoted * until the first call to dc_send_text_msg() or another sending function. * * With unpromoted chats, members can be added * and settings can be modified without the need of special status messages being sent. * * While the core takes care of the unpromoted state on its own, * checking the state from the UI side may be useful to decide whether a hint as * "Send the first message to allow others to reply within the group" * should be shown to the user or not. * * @memberof dc_chat_t * @param chat The chat object. * @return 1=chat is still unpromoted, no message was ever send to the chat, * 0=chat is not unpromoted, messages were send and/or received * or the chat is not group chat. */ int dc_chat_is_unpromoted(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return 0; } return dc_param_get_int(chat->param, DC_PARAM_UNPROMOTED, 0); } /** * Check if a chat is verified. Verified chats contain only verified members * and encryption is alwasy enabled. Verified chats are created using * dc_create_group_chat() by setting the 'verified' parameter to true. * * @memberof dc_chat_t * @param chat The chat object. * @return 1=chat verified, 0=chat is not verified */ int dc_chat_is_verified(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return 0; } return (chat->type==DC_CHAT_TYPE_VERIFIED_GROUP); } /** * Check if a chat is a self talk. Self talks are normal chats with * the only contact DC_CONTACT_ID_SELF. * * @memberof dc_chat_t * @param chat The chat object. * @return 1=chat is self talk, 0=chat is no self talk */ int dc_chat_is_self_talk(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return 0; } return dc_param_exists(chat->param, DC_PARAM_SELFTALK); } /** * Check if locations are sent to the chat * at the time the object was created using dc_get_chat(). * To check if locations are sent to _any_ chat, * use dc_is_sending_locations_to_chat(). * * @memberof dc_chat_t * @param chat The chat object. * @return 1=locations are sent to chat, 0=no locations are sent to chat */ int dc_chat_is_sending_locations(const dc_chat_t* chat) { if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { return 0; } return chat->is_sending_locations; } int dc_chat_update_param(dc_chat_t* chat) { int success = 0; sqlite3_stmt* stmt = dc_sqlite3_prepare(chat->context->sql, "UPDATE chats SET param=? WHERE id=?"); sqlite3_bind_text(stmt, 1, chat->param->packed, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 2, chat->id); success = (sqlite3_step(stmt)==SQLITE_DONE)? 1 : 0; sqlite3_finalize(stmt); return success; } static int set_from_stmt(dc_chat_t* chat, sqlite3_stmt* row) { int row_offset = 0; if (chat==NULL || chat->magic!=DC_CHAT_MAGIC || row==NULL) { return 0; } dc_chat_empty(chat); #define CHAT_FIELDS " c.id,c.type,c.name, c.grpid,c.param,c.archived, c.blocked, c.gossiped_timestamp, c.locations_send_until " chat->id = sqlite3_column_int (row, row_offset++); /* the columns are defined in CHAT_FIELDS */ chat->type = sqlite3_column_int (row, row_offset++); chat->name = dc_strdup((char*)sqlite3_column_text (row, row_offset++)); chat->grpid = dc_strdup((char*)sqlite3_column_text (row, row_offset++)); dc_param_set_packed(chat->param, (char*)sqlite3_column_text (row, row_offset++)); chat->archived = sqlite3_column_int (row, row_offset++); chat->blocked = sqlite3_column_int (row, row_offset++); chat->gossiped_timestamp = sqlite3_column_int64(row, row_offset++); chat->is_sending_locations = (sqlite3_column_int64(row, row_offset++)>time(NULL)); /* correct the title of some special groups */ if (chat->id==DC_CHAT_ID_DEADDROP) { free(chat->name); chat->name = dc_stock_str(chat->context, DC_STR_DEADDROP); } else if (chat->id==DC_CHAT_ID_ARCHIVED_LINK) { free(chat->name); char* tempname = dc_stock_str(chat->context, DC_STR_ARCHIVEDCHATS); chat->name = dc_mprintf("%s (%i)", tempname, dc_get_archived_cnt(chat->context)); free(tempname); } else if (chat->id==DC_CHAT_ID_STARRED) { free(chat->name); chat->name = dc_stock_str(chat->context, DC_STR_STARREDMSGS); } else if (dc_param_exists(chat->param, DC_PARAM_SELFTALK)) { free(chat->name); chat->name = dc_stock_str(chat->context, DC_STR_SELF); } return row_offset; /* success, return the next row offset */ } /** * Load a chat from the database to the chat object. * * @private @memberof dc_chat_t * @param chat The chat object that should be filled with the data from the database. * Existing data are free()'d before using dc_chat_empty(). * @param chat_id Chat ID that should be loaded from the database. * @return 1=success, 0=error. */ int dc_chat_load_from_db(dc_chat_t* chat, uint32_t chat_id) { int success = 0; sqlite3_stmt* stmt = NULL; if (chat==NULL || chat->magic!=DC_CHAT_MAGIC) { goto cleanup; } dc_chat_empty(chat); stmt = dc_sqlite3_prepare(chat->context->sql, "SELECT " CHAT_FIELDS " FROM chats c WHERE c.id=?;"); sqlite3_bind_int(stmt, 1, chat_id); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } if (!set_from_stmt(chat, stmt)) { goto cleanup; } success = 1; cleanup: sqlite3_finalize(stmt); return success; } void dc_set_gossiped_timestamp(dc_context_t* context, uint32_t chat_id, time_t timestamp) { sqlite3_stmt* stmt = NULL; if (chat_id) { dc_log_info(context, 0, "set gossiped_timestamp for chat #%i to %i.", (int)chat_id, (int)timestamp); stmt = dc_sqlite3_prepare(context->sql, "UPDATE chats SET gossiped_timestamp=? WHERE id=?;"); sqlite3_bind_int64(stmt, 1, timestamp); sqlite3_bind_int (stmt, 2, chat_id); } else { dc_log_info(context, 0, "set gossiped_timestamp for all chats to %i.", (int)timestamp); stmt = dc_sqlite3_prepare(context->sql, "UPDATE chats SET gossiped_timestamp=?;"); sqlite3_bind_int64(stmt, 1, timestamp); } sqlite3_step(stmt); sqlite3_finalize(stmt); } void dc_reset_gossiped_timestamp(dc_context_t* context, uint32_t chat_id) { dc_set_gossiped_timestamp(context, chat_id, 0); } /******************************************************************************* * Context functions to work with chats ******************************************************************************/ size_t dc_get_chat_cnt(dc_context_t* context) { size_t ret = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || context->sql->cobj==NULL) { goto cleanup; /* no database, no chats - this is no error (needed eg. for information) */ } stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM chats WHERE id>" DC_STRINGIFY(DC_CHAT_ID_LAST_SPECIAL) " AND blocked=0;"); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } ret = sqlite3_column_int(stmt, 0); cleanup: sqlite3_finalize(stmt); return ret; } int dc_add_to_chat_contacts_table(dc_context_t* context, uint32_t chat_id, uint32_t contact_id) { /* add a contact to a chat; the function does not check the type or if any of the record exist or are already added to the chat! */ int ret = 0; sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "INSERT INTO chats_contacts (chat_id, contact_id) VALUES(?, ?)"); sqlite3_bind_int(stmt, 1, chat_id); sqlite3_bind_int(stmt, 2, contact_id); ret = (sqlite3_step(stmt)==SQLITE_DONE)? 1 : 0; sqlite3_finalize(stmt); return ret; } /** * Get chat object by a chat ID. * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id The ID of the chat to get the chat object for. * @return A chat object of the type dc_chat_t, * must be freed using dc_chat_unref() when done. * On errors, NULL is returned. */ dc_chat_t* dc_get_chat(dc_context_t* context, uint32_t chat_id) { int success = 0; dc_chat_t* obj = dc_chat_new(context); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (!dc_chat_load_from_db(obj, chat_id)) { goto cleanup; } success = 1; cleanup: if (success) { return obj; } else { dc_chat_unref(obj); return NULL; } } /** * Mark all messages in a chat as _noticed_. * _Noticed_ messages are no longer _fresh_ and do not count as being unseen * but are still waiting for being marked as "seen" using dc_markseen_msgs() * (IMAP/MDNs is not done for noticed messages). * * Calling this function usually results in the event #DC_EVENT_MSGS_CHANGED. * See also dc_marknoticed_all_chats(), dc_marknoticed_contact() and dc_markseen_msgs(). * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id The chat ID of which all messages should be marked as being noticed. * @return None. */ void dc_marknoticed_chat(dc_context_t* context, uint32_t chat_id) { sqlite3_stmt* check = NULL; sqlite3_stmt* update = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } // as there is no thread-safe way to find out the affected rows // and as we want to send the event only on changes, // we first check if there is sth. to update. // there is a chance of a race condition, // however, this would result in an additional event only. check = dc_sqlite3_prepare(context->sql, "SELECT id FROM msgs " " WHERE chat_id=? AND state=" DC_STRINGIFY(DC_STATE_IN_FRESH) ";"); sqlite3_bind_int(check, 1, chat_id); if (sqlite3_step(check)!=SQLITE_ROW) { goto cleanup; } update = dc_sqlite3_prepare(context->sql, "UPDATE msgs " " SET state=" DC_STRINGIFY(DC_STATE_IN_NOTICED) " WHERE chat_id=? AND state=" DC_STRINGIFY(DC_STATE_IN_FRESH) ";"); sqlite3_bind_int(update, 1, chat_id); sqlite3_step(update); context->cb(context, DC_EVENT_MSGS_CHANGED, 0, 0); cleanup: sqlite3_finalize(check); sqlite3_finalize(update); } /** * Same as dc_marknoticed_chat() but for _all_ chats. * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @return None. */ void dc_marknoticed_all_chats(dc_context_t* context) { sqlite3_stmt* check = NULL; sqlite3_stmt* update = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } check = dc_sqlite3_prepare(context->sql, "SELECT id FROM msgs " " WHERE state=" DC_STRINGIFY(DC_STATE_IN_FRESH) ";"); if (sqlite3_step(check)!=SQLITE_ROW) { goto cleanup; } update = dc_sqlite3_prepare(context->sql, "UPDATE msgs " " SET state=" DC_STRINGIFY(DC_STATE_IN_NOTICED) " WHERE state=" DC_STRINGIFY(DC_STATE_IN_FRESH) ";"); sqlite3_step(update); context->cb(context, DC_EVENT_MSGS_CHANGED, 0, 0); cleanup: sqlite3_finalize(check); sqlite3_finalize(update); } /** * Check, if there is a normal chat with a given contact. * To get the chat messages, use dc_get_chat_msgs(). * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param contact_id The contact ID to check. * @return If there is a normal chat with the given contact_id, this chat_id is * returned. If there is no normal chat with the contact_id, the function * returns 0. */ uint32_t dc_get_chat_id_by_contact_id(dc_context_t* context, uint32_t contact_id) { uint32_t chat_id = 0; int chat_id_blocked = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return 0; } dc_lookup_real_nchat_by_contact_id(context, contact_id, &chat_id, &chat_id_blocked); return chat_id_blocked? 0 : chat_id; /* from outside view, chats only existing in the deaddrop do not exist */ } uint32_t dc_get_chat_id_by_grpid(dc_context_t* context, const char* grpid, int* ret_blocked, int* ret_verified) { uint32_t chat_id = 0; sqlite3_stmt* stmt = NULL; if(ret_blocked) { *ret_blocked = 0; } if(ret_verified) { *ret_verified = 0; } if (context==NULL || grpid==NULL) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT id, blocked, type FROM chats WHERE grpid=?;"); sqlite3_bind_text (stmt, 1, grpid, -1, SQLITE_STATIC); if (sqlite3_step(stmt)==SQLITE_ROW) { chat_id = sqlite3_column_int(stmt, 0); if(ret_blocked) { *ret_blocked = sqlite3_column_int(stmt, 1); } if(ret_verified) { *ret_verified = (sqlite3_column_int(stmt, 2)==DC_CHAT_TYPE_VERIFIED_GROUP); } } cleanup: sqlite3_finalize(stmt); return chat_id; } /** * Create a normal chat with a single user. To create group chats, * see dc_create_group_chat(). * * If a chat already exists, this ID is returned, otherwise a new chat is created; * this new chat may already contain messages, eg. from the deaddrop, to get the * chat messages, use dc_get_chat_msgs(). * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param contact_id The contact ID to create the chat for. If there is already * a chat with this contact, the already existing ID is returned. * @return The created or reused chat ID on success. 0 on errors. */ uint32_t dc_create_chat_by_contact_id(dc_context_t* context, uint32_t contact_id) { uint32_t chat_id = 0; int chat_blocked = 0; int send_event = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return 0; } dc_lookup_real_nchat_by_contact_id(context, contact_id, &chat_id, &chat_blocked); if (chat_id) { if (chat_blocked) { dc_unblock_chat(context, chat_id); /* unblock chat (typically move it from the deaddrop to view) */ send_event = 1; } goto cleanup; /* success */ } if (0==dc_real_contact_exists(context, contact_id) && contact_id!=DC_CONTACT_ID_SELF) { dc_log_warning(context, 0, "Cannot create chat, contact %i does not exist.", (int)contact_id); goto cleanup; } dc_create_or_lookup_nchat_by_contact_id(context, contact_id, DC_CHAT_NOT_BLOCKED, &chat_id, NULL); if (chat_id) { send_event = 1; } dc_scaleup_contact_origin(context, contact_id, DC_ORIGIN_CREATE_CHAT); cleanup: if (send_event) { context->cb(context, DC_EVENT_MSGS_CHANGED, 0, 0); } return chat_id; } /** * Create a normal chat or a group chat by a messages ID that comes typically * from the deaddrop, DC_CHAT_ID_DEADDROP (1). * * If the given message ID already belongs to a normal chat or to a group chat, * the chat ID of this chat is returned and no new chat is created. * If a new chat is created, the given message ID is moved to this chat, however, * there may be more messages moved to the chat from the deaddrop. To get the * chat messages, use dc_get_chat_msgs(). * * If the user is asked before creation, he should be * asked whether he wants to chat with the _contact_ belonging to the message; * the group names may be really weird when taken from the subject of implicit * groups and this may look confusing. * * Moreover, this function also scales up the origin of the contact belonging * to the message and, depending on the contacts origin, messages from the * same group may be shown or not - so, all in all, it is fine to show the * contact name only. * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param msg_id The message ID to create the chat for. * @return The created or reused chat ID on success. 0 on errors. */ uint32_t dc_create_chat_by_msg_id(dc_context_t* context, uint32_t msg_id) { uint32_t chat_id = 0; int send_event = 0; dc_msg_t* msg = dc_msg_new_untyped(context); dc_chat_t* chat = dc_chat_new(context); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (!dc_msg_load_from_db(msg, context, msg_id) || !dc_chat_load_from_db(chat, msg->chat_id) || chat->id<=DC_CHAT_ID_LAST_SPECIAL) { goto cleanup; } chat_id = chat->id; if (chat->blocked) { dc_unblock_chat(context, chat->id); send_event = 1; } dc_scaleup_contact_origin(context, msg->from_id, DC_ORIGIN_CREATE_CHAT); cleanup: dc_msg_unref(msg); dc_chat_unref(chat); if (send_event) { context->cb(context, DC_EVENT_MSGS_CHANGED, 0, 0); } return chat_id; } /** * Returns all message IDs of the given types in a chat. * Typically used to show a gallery. * The result must be dc_array_unref()'d * * The list is already sorted and starts with the oldest message. * Clients should not try to re-sort the list as this would be an expensive action * and would result in inconsistencies between clients. * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id The chat ID to get all messages with media from. * @param msg_type Specify a message type to query here, one of the DC_MSG_* constats. * @param msg_type2 Alternative message type to search for. 0 to skip. * @param msg_type3 Alternative message type to search for. 0 to skip. * @return An array with messages from the given chat ID that have the wanted message types. */ dc_array_t* dc_get_chat_media(dc_context_t* context, uint32_t chat_id, int msg_type, int msg_type2, int msg_type3) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return NULL; } dc_array_t* ret = dc_array_new(context, 100); sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "SELECT id FROM msgs WHERE chat_id=? AND (type=? OR type=? OR type=?) ORDER BY timestamp, id;"); sqlite3_bind_int(stmt, 1, chat_id); sqlite3_bind_int(stmt, 2, msg_type); sqlite3_bind_int(stmt, 3, msg_type2>0? msg_type2 : msg_type); sqlite3_bind_int(stmt, 4, msg_type3>0? msg_type3 : msg_type); while (sqlite3_step(stmt)==SQLITE_ROW) { dc_array_add_id(ret, sqlite3_column_int(stmt, 0)); } sqlite3_finalize(stmt); return ret; } /** * Search next/previous message based on a given message and a list of types. * The * Typically used to implement the "next" and "previous" buttons * in a gallery or in a media player. * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param curr_msg_id This is the current message * from which the next or previous message should be searched. * @param dir 1=get the next message, -1=get the previous one. * @param msg_type Message type to search for. * If 0, the message type from curr_msg_id is used. * @param msg_type2 Alternative message type to search for. 0 to skip. * @param msg_type3 Alternative message type to search for. 0 to skip. * @return Returns the message ID that should be played next. * The returned message is in the same chat as the given one * and has one of the given types. * Typically, this result is passed again to dc_get_next_media() * later on the next swipe. * If there is not next/previous message, the function returns 0. */ uint32_t dc_get_next_media(dc_context_t* context, uint32_t curr_msg_id, int dir, int msg_type, int msg_type2, int msg_type3) { uint32_t ret_msg_id = 0; dc_msg_t* msg = dc_msg_new_untyped(context); dc_array_t* list = NULL; int i = 0; int cnt = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (!dc_msg_load_from_db(msg, context, curr_msg_id)) { goto cleanup; } if ((list=dc_get_chat_media(context, msg->chat_id, msg_type>0? msg_type : msg->type, msg_type2, msg_type3))==NULL) { goto cleanup; } cnt = dc_array_get_cnt(list); for (i = 0; i < cnt; i++) { if (curr_msg_id==dc_array_get_id(list, i)) { if (dir > 0) { /* get the next message from the current position */ if (i+1 < cnt) { ret_msg_id = dc_array_get_id(list, i+1); } } else if (dir < 0) { /* get the previous message from the current position */ if (i-1 >= 0) { ret_msg_id = dc_array_get_id(list, i-1); } } break; } } cleanup: dc_array_unref(list); dc_msg_unref(msg); return ret_msg_id; } /** * Get contact IDs belonging to a chat. * * - for normal chats, the function always returns exactly one contact, * DC_CONTACT_ID_SELF is returned only for SELF-chats. * * - for group chats all members are returned, DC_CONTACT_ID_SELF is returned * explicitly as it may happen that oneself gets removed from a still existing * group * * - for the deaddrop, the list is empty * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id Chat ID to get the belonging contact IDs for. * @return An array of contact IDs belonging to the chat; must be freed using dc_array_unref() when done. */ dc_array_t* dc_get_chat_contacts(dc_context_t* context, uint32_t chat_id) { /* Normal chats do not include SELF. Group chats do (as it may happen that one is deleted from a groupchat but the chats stays visible, moreover, this makes displaying lists easier) */ dc_array_t* ret = dc_array_new(context, 100); sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (chat_id==DC_CHAT_ID_DEADDROP) { goto cleanup; /* we could also create a list for all contacts in the deaddrop by searching contacts belonging to chats with chats.blocked=2, however, currently this is not needed */ } stmt = dc_sqlite3_prepare(context->sql, "SELECT cc.contact_id FROM chats_contacts cc" " LEFT JOIN contacts c ON c.id=cc.contact_id" " WHERE cc.chat_id=?" " ORDER BY c.id=1, LOWER(c.name||c.addr), c.id;"); sqlite3_bind_int(stmt, 1, chat_id); while (sqlite3_step(stmt)==SQLITE_ROW) { dc_array_add_id(ret, sqlite3_column_int(stmt, 0)); } cleanup: sqlite3_finalize(stmt); return ret; } /** * Get all message IDs belonging to a chat. * * The list is already sorted and starts with the oldest message. * Clients should not try to re-sort the list as this would be an expensive action * and would result in inconsistencies between clients. * * Optionally, some special markers added to the ID-array may help to * implement virtual lists. * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id The chat ID of which the messages IDs should be queried. * @param flags If set to DC_GCM_ADDDAYMARKER, the marker DC_MSG_ID_DAYMARKER will * be added before each day (regarding the local timezone). Set this to 0 if you do not want this behaviour. * @param marker1before An optional message ID. If set, the id DC_MSG_ID_MARKER1 will be added just * before the given ID in the returned array. Set this to 0 if you do not want this behaviour. * @return Array of message IDs, must be dc_array_unref()'d when no longer used. */ dc_array_t* dc_get_chat_msgs(dc_context_t* context, uint32_t chat_id, uint32_t flags, uint32_t marker1before) { //clock_t start = clock(); int success = 0; dc_array_t* ret = dc_array_new(context, 512); sqlite3_stmt* stmt = NULL; uint32_t curr_id; time_t curr_local_timestamp; int curr_day, last_day = 0; long cnv_to_local = dc_gm2local_offset(); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || ret==NULL) { goto cleanup; } if (chat_id==DC_CHAT_ID_DEADDROP) { int show_emails = dc_sqlite3_get_config_int(context->sql, "show_emails", DC_SHOW_EMAILS_DEFAULT); stmt = dc_sqlite3_prepare(context->sql, "SELECT m.id, m.timestamp" " FROM msgs m" " LEFT JOIN chats ON m.chat_id=chats.id" " LEFT JOIN contacts ON m.from_id=contacts.id" " WHERE m.from_id!=" DC_STRINGIFY(DC_CONTACT_ID_SELF) " AND m.from_id!=" DC_STRINGIFY(DC_CONTACT_ID_DEVICE) " AND m.hidden=0 " " AND chats.blocked=" DC_STRINGIFY(DC_CHAT_DEADDROP_BLOCKED) " AND contacts.blocked=0" " AND m.msgrmsg>=? " " ORDER BY m.timestamp,m.id;"); /* the list starts with the oldest message*/ sqlite3_bind_int(stmt, 1, show_emails==DC_SHOW_EMAILS_ALL? 0 : 1); } else if (chat_id==DC_CHAT_ID_STARRED) { stmt = dc_sqlite3_prepare(context->sql, "SELECT m.id, m.timestamp" " FROM msgs m" " LEFT JOIN contacts ct ON m.from_id=ct.id" " WHERE m.starred=1 " " AND m.hidden=0 " " AND ct.blocked=0" " ORDER BY m.timestamp,m.id;"); /* the list starts with the oldest message*/ } else { stmt = dc_sqlite3_prepare(context->sql, "SELECT m.id, m.timestamp" " FROM msgs m" //" LEFT JOIN contacts ct ON m.from_id=ct.id" " WHERE m.chat_id=? " " AND m.hidden=0 " //" AND ct.blocked=0" -- we hide blocked-contacts from starred and deaddrop, but we have to show them in groups (otherwise it may be hard to follow conversation, wa and tg do the same. however, maybe this needs discussion some time :) " ORDER BY m.timestamp,m.id;"); /* the list starts with the oldest message*/ sqlite3_bind_int(stmt, 1, chat_id); } while (sqlite3_step(stmt)==SQLITE_ROW) { curr_id = sqlite3_column_int(stmt, 0); /* add user marker */ if (curr_id==marker1before) { dc_array_add_id(ret, DC_MSG_ID_MARKER1); } /* add daymarker, if needed */ if (flags&DC_GCM_ADDDAYMARKER) { curr_local_timestamp = (time_t)sqlite3_column_int64(stmt, 1) + cnv_to_local; curr_day = curr_local_timestamp/DC_SECONDS_PER_DAY; if (curr_day!=last_day) { dc_array_add_id(ret, DC_MSG_ID_DAYMARKER); last_day = curr_day; } } dc_array_add_id(ret, curr_id); } success = 1; cleanup: sqlite3_finalize(stmt); //dc_log_info(context, 0, "Message list for chat #%i created in %.3f ms.", chat_id, (double)(clock()-start)*1000.0/CLOCKS_PER_SEC); if (success) { return ret; } else { if (ret) { dc_array_unref(ret); } return NULL; } } static uint32_t get_draft_msg_id(dc_context_t* context, uint32_t chat_id) { uint32_t draft_msg_id = 0; sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "SELECT id FROM msgs WHERE chat_id=? AND state=?;"); sqlite3_bind_int(stmt, 1, chat_id); sqlite3_bind_int(stmt, 2, DC_STATE_OUT_DRAFT); if (sqlite3_step(stmt)==SQLITE_ROW) { draft_msg_id = sqlite3_column_int(stmt, 0); } sqlite3_finalize(stmt); return draft_msg_id; } static int set_draft_raw(dc_context_t* context, uint32_t chat_id, dc_msg_t* msg) { // similar to as dc_set_draft() but does not emit an event sqlite3_stmt* stmt = NULL; char* pathNfilename = NULL; uint32_t prev_draft_msg_id = 0; int sth_changed = 0; // delete old draft prev_draft_msg_id = get_draft_msg_id(context, chat_id); if (prev_draft_msg_id) { dc_delete_msg_from_db(context, prev_draft_msg_id); sth_changed = 1; } // save new draft if (msg==NULL) { goto cleanup; } else if (msg->type==DC_MSG_TEXT) { if (msg->text==NULL || msg->text[0]==0) { goto cleanup; } } else if (DC_MSG_NEEDS_ATTACHMENT(msg->type)) { pathNfilename = dc_param_get(msg->param, DC_PARAM_FILE, NULL); if (pathNfilename==NULL) { goto cleanup; } if (dc_msg_is_increation(msg) && !dc_is_blobdir_path(context, pathNfilename)) { goto cleanup; } if (!dc_make_rel_and_copy(context, &pathNfilename)) { goto cleanup; } dc_param_set(msg->param, DC_PARAM_FILE, pathNfilename); } else { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "INSERT INTO msgs (chat_id, from_id, timestamp," " type, state, txt, param, hidden)" " VALUES (?,?,?, ?,?,?,?,?);"); sqlite3_bind_int (stmt, 1, chat_id); sqlite3_bind_int (stmt, 2, DC_CONTACT_ID_SELF); sqlite3_bind_int64(stmt, 3, time(NULL)); sqlite3_bind_int (stmt, 4, msg->type); sqlite3_bind_int (stmt, 5, DC_STATE_OUT_DRAFT); sqlite3_bind_text (stmt, 6, msg->text? msg->text : "", -1, SQLITE_STATIC); sqlite3_bind_text (stmt, 7, msg->param->packed, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 8, 1); if (sqlite3_step(stmt)!=SQLITE_DONE) { goto cleanup; } sth_changed = 1; cleanup: sqlite3_finalize(stmt); free(pathNfilename); return sth_changed; } /** * Save a draft for a chat in the database. * * The UI should call this function if the user has prepared a message * and exits the compose window without clicking the "send" button before. * When the user later opens the same chat again, * the UI can load the draft using dc_get_draft() * allowing the user to continue editing and sending. * * Drafts are considered when sorting messages * and are also returned eg. by dc_chatlist_get_summary(). * * Each chat can have its own draft but only one draft per chat is possible. * * If the draft is modified, an #DC_EVENT_MSGS_CHANGED will be sent. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param chat_id The chat ID to save the draft for. * @param msg The message to save as a draft. * Existing draft will be overwritten. * NULL deletes the existing draft, if any, without sending it. * Currently, also non-text-messages * will delete the existing drafts. * @return None. */ void dc_set_draft(dc_context_t* context, uint32_t chat_id, dc_msg_t* msg) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { return; } if (set_draft_raw(context, chat_id, msg)) { context->cb(context, DC_EVENT_MSGS_CHANGED, chat_id, 0); } } /** * Get draft for a chat, if any. * See dc_set_draft() for more details about drafts. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param chat_id The chat ID to get the draft for. * @return Message object. * Can be passed directly to dc_send_msg(). * Must be freed using dc_msg_unref() after usage. * If there is no draft, NULL is returned. */ dc_msg_t* dc_get_draft(dc_context_t* context, uint32_t chat_id) { uint32_t draft_msg_id = 0; dc_msg_t* draft_msg = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { return NULL; } draft_msg_id = get_draft_msg_id(context, chat_id); if (draft_msg_id==0) { return NULL; } draft_msg = dc_msg_new_untyped(context); if (!dc_msg_load_from_db(draft_msg, context, draft_msg_id)) { dc_msg_unref(draft_msg); return NULL; } return draft_msg; } void dc_lookup_real_nchat_by_contact_id(dc_context_t* context, uint32_t contact_id, uint32_t* ret_chat_id, int* ret_chat_blocked) { /* checks for "real" chats or self-chat */ sqlite3_stmt* stmt = NULL; if (ret_chat_id) { *ret_chat_id = 0; } if (ret_chat_blocked) { *ret_chat_blocked = 0; } if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || context->sql->cobj==NULL) { return; /* no database, no chats - this is no error (needed eg. for information) */ } stmt = dc_sqlite3_prepare(context->sql, "SELECT c.id, c.blocked" " FROM chats c" " INNER JOIN chats_contacts j ON c.id=j.chat_id" " WHERE c.type=" DC_STRINGIFY(DC_CHAT_TYPE_SINGLE) " AND c.id>" DC_STRINGIFY(DC_CHAT_ID_LAST_SPECIAL) " AND j.contact_id=?;"); sqlite3_bind_int(stmt, 1, contact_id); if (sqlite3_step(stmt)==SQLITE_ROW) { if (ret_chat_id) { *ret_chat_id = sqlite3_column_int(stmt, 0); } if (ret_chat_blocked) { *ret_chat_blocked = sqlite3_column_int(stmt, 1); } } sqlite3_finalize(stmt); } void dc_create_or_lookup_nchat_by_contact_id(dc_context_t* context, uint32_t contact_id, int create_blocked, uint32_t* ret_chat_id, int* ret_chat_blocked) { uint32_t chat_id = 0; int chat_blocked = 0; dc_contact_t* contact = NULL; char* chat_name = NULL; char* q = NULL; sqlite3_stmt* stmt = NULL; if (ret_chat_id) { *ret_chat_id = 0; } if (ret_chat_blocked) { *ret_chat_blocked = 0; } if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || context->sql->cobj==NULL) { return; /* database not opened - error */ } if (contact_id==0) { return; } dc_lookup_real_nchat_by_contact_id(context, contact_id, &chat_id, &chat_blocked); if (chat_id!=0) { if (ret_chat_id) { *ret_chat_id = chat_id; } if (ret_chat_blocked) { *ret_chat_blocked = chat_blocked; } return; /* soon success */ } /* get fine chat name */ contact = dc_contact_new(context); if (!dc_contact_load_from_db(contact, context->sql, contact_id)) { goto cleanup; } chat_name = (contact->name&&contact->name[0])? contact->name : contact->addr; /* create chat record; the grpid is only used to make dc_sqlite3_get_rowid() work (we cannot use last_insert_id() due multi-threading) */ q = sqlite3_mprintf("INSERT INTO chats (type, name, param, blocked, grpid) VALUES(%i, %Q, %Q, %i, %Q)", DC_CHAT_TYPE_SINGLE, chat_name, contact_id==DC_CONTACT_ID_SELF? "K=1" : "", create_blocked, contact->addr); assert( DC_PARAM_SELFTALK=='K'); stmt = dc_sqlite3_prepare(context->sql, q); if (stmt==NULL) { goto cleanup; } if (sqlite3_step(stmt)!=SQLITE_DONE) { goto cleanup; } chat_id = dc_sqlite3_get_rowid(context->sql, "chats", "grpid", contact->addr); sqlite3_free(q); q = NULL; sqlite3_finalize(stmt); stmt = NULL; /* add contact IDs to the new chat record (may be replaced by dc_add_to_chat_contacts_table()) */ q = sqlite3_mprintf("INSERT INTO chats_contacts (chat_id, contact_id) VALUES(%i, %i)", chat_id, contact_id); stmt = dc_sqlite3_prepare(context->sql, q); if (sqlite3_step(stmt)!=SQLITE_DONE) { goto cleanup; } sqlite3_free(q); q = NULL; sqlite3_finalize(stmt); stmt = NULL; cleanup: sqlite3_free(q); sqlite3_finalize(stmt); dc_contact_unref(contact); if (ret_chat_id) { *ret_chat_id = chat_id; } if (ret_chat_blocked) { *ret_chat_blocked = create_blocked; } } /** * Get the total number of messages in a chat. * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id The ID of the chat to count the messages for. * @return Number of total messages in the given chat. 0 for errors or empty chats. */ int dc_get_msg_cnt(dc_context_t* context, uint32_t chat_id) { int ret = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM msgs WHERE chat_id=?;"); sqlite3_bind_int(stmt, 1, chat_id); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } ret = sqlite3_column_int(stmt, 0); cleanup: sqlite3_finalize(stmt); return ret; } void dc_unarchive_chat(dc_context_t* context, uint32_t chat_id) { sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "UPDATE chats SET archived=0 WHERE id=?"); sqlite3_bind_int (stmt, 1, chat_id); sqlite3_step(stmt); sqlite3_finalize(stmt); } /** * Get the number of _fresh_ messages in a chat. Typically used to implement * a badge with a number in the chatlist. * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id The ID of the chat to count the messages for. * @return Number of fresh messages in the given chat. 0 for errors or if there are no fresh messages. */ int dc_get_fresh_msg_cnt(dc_context_t* context, uint32_t chat_id) { int ret = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM msgs " " WHERE state=" DC_STRINGIFY(DC_STATE_IN_FRESH) " AND hidden=0 " " AND chat_id=?;"); /* we have an index over the state-column, this should be sufficient as there are typically only few fresh messages */ sqlite3_bind_int(stmt, 1, chat_id); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } ret = sqlite3_column_int(stmt, 0); cleanup: sqlite3_finalize(stmt); return ret; } /** * Archive or unarchive a chat. * * Archived chats are not included in the default chatlist returned * by dc_get_chatlist(). Instead, if there are _any_ archived chats, * the pseudo-chat with the chat_id DC_CHAT_ID_ARCHIVED_LINK will be added the the * end of the chatlist. * * - To get a list of archived chats, use dc_get_chatlist() with the flag DC_GCL_ARCHIVED_ONLY. * - To find out the archived state of a given chat, use dc_chat_get_archived() * - Messages in archived chats are marked as being noticed, so they do not count as "fresh" * - Calling this function usually results in the event #DC_EVENT_MSGS_CHANGED * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id The ID of the chat to archive or unarchive. * @param archive 1=archive chat, 0=unarchive chat, all other values are reserved for future use * @return None. */ void dc_archive_chat(dc_context_t* context, uint32_t chat_id, int archive) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_id<=DC_CHAT_ID_LAST_SPECIAL || (archive!=0 && archive!=1)) { return; } if (archive) { sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "UPDATE msgs SET state=" DC_STRINGIFY(DC_STATE_IN_NOTICED) " WHERE chat_id=? AND state=" DC_STRINGIFY(DC_STATE_IN_FRESH) ";"); sqlite3_bind_int(stmt, 1, chat_id); sqlite3_step(stmt); sqlite3_finalize(stmt); } sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "UPDATE chats SET archived=? WHERE id=?;"); sqlite3_bind_int (stmt, 1, archive); sqlite3_bind_int (stmt, 2, chat_id); sqlite3_step(stmt); sqlite3_finalize(stmt); context->cb(context, DC_EVENT_MSGS_CHANGED, 0, 0); } void dc_block_chat(dc_context_t* context, uint32_t chat_id, int new_blocking) { sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } stmt = dc_sqlite3_prepare(context->sql, "UPDATE chats SET blocked=? WHERE id=?;"); sqlite3_bind_int(stmt, 1, new_blocking); sqlite3_bind_int(stmt, 2, chat_id); sqlite3_step(stmt); sqlite3_finalize(stmt); } void dc_unblock_chat(dc_context_t* context, uint32_t chat_id) { dc_block_chat(context, chat_id, DC_CHAT_NOT_BLOCKED); } /** * Delete a chat. * * Messages are deleted from the device and the chat database entry is deleted. * After that, the event #DC_EVENT_MSGS_CHANGED is posted. * * Things that are _not_ done implicitly: * * - Messages are **not deleted from the server**. * - The chat or the contact is **not blocked**, so new messages from the user/the group may appear * and the user may create the chat again. * - **Groups are not left** - this would * be unexpected as (1) deleting a normal chat also does not prevent new mails * from arriving, (2) leaving a group requires sending a message to * all group members - especially for groups not used for a longer time, this is * really unexpected when deletion results in contacting all members again, * (3) only leaving groups is also a valid usecase. * * To leave a chat explicitly, use dc_remove_contact_from_chat() with * chat_id=DC_CONTACT_ID_SELF) * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id The ID of the chat to delete. * @return None. */ void dc_delete_chat(dc_context_t* context, uint32_t chat_id) { /* Up to 2017-11-02 deleting a group also implied leaving it, see above why we have changed this. */ int pending_transaction = 0; dc_chat_t* obj = dc_chat_new(context); char* q3 = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { goto cleanup; } if (!dc_chat_load_from_db(obj, chat_id)) { goto cleanup; } dc_sqlite3_begin_transaction(context->sql); pending_transaction = 1; q3 = sqlite3_mprintf("DELETE FROM msgs_mdns WHERE msg_id IN (SELECT id FROM msgs WHERE chat_id=%i);", chat_id); if (!dc_sqlite3_execute(context->sql, q3)) { goto cleanup; } sqlite3_free(q3); q3 = NULL; q3 = sqlite3_mprintf("DELETE FROM msgs WHERE chat_id=%i;", chat_id); if (!dc_sqlite3_execute(context->sql, q3)) { goto cleanup; } sqlite3_free(q3); q3 = NULL; q3 = sqlite3_mprintf("DELETE FROM chats_contacts WHERE chat_id=%i;", chat_id); if (!dc_sqlite3_execute(context->sql, q3)) { goto cleanup; } sqlite3_free(q3); q3 = NULL; q3 = sqlite3_mprintf("DELETE FROM chats WHERE id=%i;", chat_id); if (!dc_sqlite3_execute(context->sql, q3)) { goto cleanup; } sqlite3_free(q3); q3 = NULL; dc_sqlite3_commit(context->sql); pending_transaction = 0; context->cb(context, DC_EVENT_MSGS_CHANGED, 0, 0); dc_job_kill_action(context, DC_JOB_HOUSEKEEPING); dc_job_add(context, DC_JOB_HOUSEKEEPING, 0, NULL, DC_HOUSEKEEPING_DELAY_SEC); cleanup: if (pending_transaction) { dc_sqlite3_rollback(context->sql); } dc_chat_unref(obj); sqlite3_free(q3); } /******************************************************************************* * Handle Group Chats ******************************************************************************/ #define IS_SELF_IN_GROUP (dc_is_contact_in_chat(context, chat_id, DC_CONTACT_ID_SELF)==1) #define DO_SEND_STATUS_MAILS (dc_param_get_int(chat->param, DC_PARAM_UNPROMOTED, 0)==0) int dc_is_group_explicitly_left(dc_context_t* context, const char* grpid) { sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "SELECT id FROM leftgrps WHERE grpid=?;"); sqlite3_bind_text (stmt, 1, grpid, -1, SQLITE_STATIC); int ret = (sqlite3_step(stmt)==SQLITE_ROW); sqlite3_finalize(stmt); return ret; } void dc_set_group_explicitly_left(dc_context_t* context, const char* grpid) { if (!dc_is_group_explicitly_left(context, grpid)) { sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "INSERT INTO leftgrps (grpid) VALUES(?);"); sqlite3_bind_text (stmt, 1, grpid, -1, SQLITE_STATIC); sqlite3_step(stmt); sqlite3_finalize(stmt); } } static int real_group_exists(dc_context_t* context, uint32_t chat_id) { // check if a group or a verified group exists under the given ID sqlite3_stmt* stmt = NULL; int ret = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || context->sql->cobj==NULL || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { return 0; } stmt = dc_sqlite3_prepare(context->sql, "SELECT id FROM chats " " WHERE id=? " " AND (type=" DC_STRINGIFY(DC_CHAT_TYPE_GROUP) " OR type=" DC_STRINGIFY(DC_CHAT_TYPE_VERIFIED_GROUP) ");"); sqlite3_bind_int(stmt, 1, chat_id); if (sqlite3_step(stmt)==SQLITE_ROW) { ret = 1; } sqlite3_finalize(stmt); return ret; } /** * Create a new group chat. * * After creation, * the draft of the chat is set to a default text, * the group has one member with the ID DC_CONTACT_ID_SELF * and is in _unpromoted_ state. * This means, you can add or remove members, change the name, * the group image and so on without messages being sent to all group members. * * This changes as soon as the first message is sent to the group members * and the group becomes _promoted_. * After that, all changes are synced with all group members * by sending status message. * * To check, if a chat is still unpromoted, you dc_chat_is_unpromoted(). * This may be useful if you want to show some help for just created groups. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param verified If set to 1 the function creates a secure verified group. * Only secure-verified members are allowed in these groups * and end-to-end-encryption is always enabled. * @param chat_name The name of the group chat to create. * The name may be changed later using dc_set_chat_name(). * To find out the name of a group later, see dc_chat_get_name() * @return The chat ID of the new group chat, 0 on errors. */ uint32_t dc_create_group_chat(dc_context_t* context, int verified, const char* chat_name) { uint32_t chat_id = 0; char* draft_txt = NULL; dc_msg_t* draft_msg = NULL; char* grpid = NULL; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_name==NULL || chat_name[0]==0) { return 0; } draft_txt = dc_stock_str_repl_string(context, DC_STR_NEWGROUPDRAFT, chat_name); grpid = dc_create_id(); stmt = dc_sqlite3_prepare(context->sql, "INSERT INTO chats (type, name, grpid, param) VALUES(?, ?, ?, 'U=1');" /*U=DC_PARAM_UNPROMOTED*/); sqlite3_bind_int (stmt, 1, verified? DC_CHAT_TYPE_VERIFIED_GROUP : DC_CHAT_TYPE_GROUP); sqlite3_bind_text (stmt, 2, chat_name, -1, SQLITE_STATIC); sqlite3_bind_text (stmt, 3, grpid, -1, SQLITE_STATIC); if ( sqlite3_step(stmt)!=SQLITE_DONE) { goto cleanup; } if ((chat_id=dc_sqlite3_get_rowid(context->sql, "chats", "grpid", grpid))==0) { goto cleanup; } if (!dc_add_to_chat_contacts_table(context, chat_id, DC_CONTACT_ID_SELF)) { goto cleanup; } draft_msg = dc_msg_new(context, DC_MSG_TEXT); dc_msg_set_text(draft_msg, draft_txt); set_draft_raw(context, chat_id, draft_msg); cleanup: sqlite3_finalize(stmt); free(draft_txt); dc_msg_unref(draft_msg); free(grpid); if (chat_id) { context->cb(context, DC_EVENT_MSGS_CHANGED, 0, 0); } return chat_id; } /** * Set group name. * * If the group is already _promoted_ (any message was sent to the group), * all group members are informed by a special status message that is sent automatically by this function. * * Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent. * * @memberof dc_context_t * @param chat_id The chat ID to set the name for. Must be a group chat. * @param new_name New name of the group. * @param context The context as created by dc_context_new(). * @return 1=success, 0=error */ int dc_set_chat_name(dc_context_t* context, uint32_t chat_id, const char* new_name) { /* the function only sets the names of group chats; normal chats get their names from the contacts */ int success = 0; dc_chat_t* chat = dc_chat_new(context); dc_msg_t* msg = dc_msg_new_untyped(context); char* q3 = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || new_name==NULL || new_name[0]==0 || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { goto cleanup; } if (0==real_group_exists(context, chat_id) || 0==dc_chat_load_from_db(chat, chat_id)) { goto cleanup; } if (strcmp(chat->name, new_name)==0) { success = 1; goto cleanup; /* name not modified */ } if (!IS_SELF_IN_GROUP) { dc_log_event(context, DC_EVENT_ERROR_SELF_NOT_IN_GROUP, 0, "Cannot set chat name; self not in group"); goto cleanup; /* we shoud respect this - whatever we send to the group, it gets discarded anyway! */ } q3 = sqlite3_mprintf("UPDATE chats SET name=%Q WHERE id=%i;", new_name, chat_id); if (!dc_sqlite3_execute(context->sql, q3)) { goto cleanup; } /* send a status mail to all group members, also needed for outself to allow multi-client */ if (DO_SEND_STATUS_MAILS) { msg->type = DC_MSG_TEXT; msg->text = dc_stock_system_msg(context, DC_STR_MSGGRPNAME, chat->name, new_name, DC_CONTACT_ID_SELF); dc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_GROUPNAME_CHANGED); dc_param_set (msg->param, DC_PARAM_CMD_ARG, chat->name); msg->id = dc_send_msg(context, chat_id, msg); context->cb(context, DC_EVENT_MSGS_CHANGED, chat_id, msg->id); } context->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0); success = 1; cleanup: sqlite3_free(q3); dc_chat_unref(chat); dc_msg_unref(msg); return success; } /** * Set group profile image. * * If the group is already _promoted_ (any message was sent to the group), * all group members are informed by a special status message that is sent automatically by this function. * * Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent. * * To find out the profile image of a chat, use dc_chat_get_profile_image() * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param chat_id The chat ID to set the image for. * @param new_image Full path of the image to use as the group image. If you pass NULL here, * the group image is deleted (for promoted groups, all members are informed about this change anyway). * @return 1=success, 0=error */ int dc_set_chat_profile_image(dc_context_t* context, uint32_t chat_id, const char* new_image /*NULL=remove image*/) { int success = 0; dc_chat_t* chat = dc_chat_new(context); dc_msg_t* msg = dc_msg_new_untyped(context); char* new_image_rel = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { goto cleanup; } if (0==real_group_exists(context, chat_id) || 0==dc_chat_load_from_db(chat, chat_id)) { goto cleanup; } if (!IS_SELF_IN_GROUP) { dc_log_event(context, DC_EVENT_ERROR_SELF_NOT_IN_GROUP, 0, "Cannot set chat profile image; self not in group."); goto cleanup; /* we shoud respect this - whatever we send to the group, it gets discarded anyway! */ } if (new_image) { new_image_rel = dc_strdup(new_image); if (!dc_make_rel_and_copy(context, &new_image_rel)) { goto cleanup; } } dc_param_set(chat->param, DC_PARAM_PROFILE_IMAGE, new_image_rel/*may be NULL*/); if (!dc_chat_update_param(chat)) { goto cleanup; } /* send a status mail to all group members, also needed for outself to allow multi-client */ if (DO_SEND_STATUS_MAILS) { dc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_GROUPIMAGE_CHANGED); dc_param_set (msg->param, DC_PARAM_CMD_ARG, new_image_rel); msg->type = DC_MSG_TEXT; msg->text = dc_stock_system_msg(context, new_image_rel? DC_STR_MSGGRPIMGCHANGED : DC_STR_MSGGRPIMGDELETED, NULL, NULL, DC_CONTACT_ID_SELF); msg->id = dc_send_msg(context, chat_id, msg); context->cb(context, DC_EVENT_MSGS_CHANGED, chat_id, msg->id); } context->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0); success = 1; cleanup: dc_chat_unref(chat); dc_msg_unref(msg); free(new_image_rel); return success; } int dc_get_chat_contact_cnt(dc_context_t* context, uint32_t chat_id) { int ret = 0; sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM chats_contacts WHERE chat_id=?;"); sqlite3_bind_int(stmt, 1, chat_id); if (sqlite3_step(stmt)==SQLITE_ROW) { ret = sqlite3_column_int(stmt, 0); } sqlite3_finalize(stmt); return ret; } /** * Check if a given contact ID is a member of a group chat. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param chat_id The chat ID to check. * @param contact_id The contact ID to check. To check if yourself is member * of the chat, pass DC_CONTACT_ID_SELF (1) here. * @return 1=contact ID is member of chat ID, 0=contact is not in chat */ int dc_is_contact_in_chat(dc_context_t* context, uint32_t chat_id, uint32_t contact_id) { /* this function works for group and for normal chats, however, it is more useful for group chats. DC_CONTACT_ID_SELF may be used to check, if the user itself is in a group chat (DC_CONTACT_ID_SELF is not added to normal chats) */ int ret = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT contact_id FROM chats_contacts WHERE chat_id=? AND contact_id=?;"); sqlite3_bind_int(stmt, 1, chat_id); sqlite3_bind_int(stmt, 2, contact_id); ret = (sqlite3_step(stmt)==SQLITE_ROW)? 1 : 0; cleanup: sqlite3_finalize(stmt); return ret; } int dc_add_contact_to_chat_ex(dc_context_t* context, uint32_t chat_id, uint32_t contact_id, int flags) { int success = 0; dc_contact_t* contact = dc_get_contact(context, contact_id); dc_chat_t* chat = dc_chat_new(context); dc_msg_t* msg = dc_msg_new_untyped(context); char* self_addr = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || contact==NULL || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { goto cleanup; } dc_reset_gossiped_timestamp(context, chat_id); if (0==real_group_exists(context, chat_id) /*this also makes sure, not contacts are added to special or normal chats*/ || (0==dc_real_contact_exists(context, contact_id) && contact_id!=DC_CONTACT_ID_SELF) || 0==dc_chat_load_from_db(chat, chat_id)) { goto cleanup; } if (!IS_SELF_IN_GROUP) { dc_log_event(context, DC_EVENT_ERROR_SELF_NOT_IN_GROUP, 0, "Cannot add contact to group; self not in group."); goto cleanup; /* we shoud respect this - whatever we send to the group, it gets discarded anyway! */ } if ((flags&DC_FROM_HANDSHAKE) && dc_param_get_int(chat->param, DC_PARAM_UNPROMOTED, 0)==1) { // after a handshake, force sending the `Chat-Group-Member-Added` message dc_param_set(chat->param, DC_PARAM_UNPROMOTED, NULL); dc_chat_update_param(chat); } self_addr = dc_sqlite3_get_config(context->sql, "configured_addr", ""); if (strcasecmp(contact->addr, self_addr)==0) { goto cleanup; /* ourself is added using DC_CONTACT_ID_SELF, do not add it explicitly. if SELF is not in the group, members cannot be added at all. */ } if (dc_is_contact_in_chat(context, chat_id, contact_id)) { if (!(flags&DC_FROM_HANDSHAKE)) { success = 1; goto cleanup; } // else continue and send status mail } else { if (chat->type==DC_CHAT_TYPE_VERIFIED_GROUP) { if (dc_contact_is_verified(contact)!=DC_BIDIRECT_VERIFIED) { dc_log_error(context, 0, "Only bidirectional verified contacts can be added to verified groups."); goto cleanup; } } if (0==dc_add_to_chat_contacts_table(context, chat_id, contact_id)) { goto cleanup; } } /* send a status mail to all group members */ if (DO_SEND_STATUS_MAILS) { msg->type = DC_MSG_TEXT; msg->text = dc_stock_system_msg(context, DC_STR_MSGADDMEMBER, contact->addr, NULL, DC_CONTACT_ID_SELF); dc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_MEMBER_ADDED_TO_GROUP); dc_param_set (msg->param, DC_PARAM_CMD_ARG, contact->addr); dc_param_set_int(msg->param, DC_PARAM_CMD_ARG2, flags); // combine the Secure-Join protocol headers with the Chat-Group-Member-Added header msg->id = dc_send_msg(context, chat_id, msg); context->cb(context, DC_EVENT_MSGS_CHANGED, chat_id, msg->id); } context->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0); success = 1; cleanup: dc_chat_unref(chat); dc_contact_unref(contact); dc_msg_unref(msg); free(self_addr); return success; } /** * Add a member to a group. * * If the group is already _promoted_ (any message was sent to the group), * all group members are informed by a special status message that is sent automatically by this function. * * If the group is a verified group, only verified contacts can be added to the group. * * Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param chat_id The chat ID to add the contact to. Must be a group chat. * @param contact_id The contact ID to add to the chat. * @return 1=member added to group, 0=error */ int dc_add_contact_to_chat(dc_context_t* context, uint32_t chat_id, uint32_t contact_id /*may be DC_CONTACT_ID_SELF*/) { return dc_add_contact_to_chat_ex(context, chat_id, contact_id, 0); } /** * Remove a member from a group. * * If the group is already _promoted_ (any message was sent to the group), * all group members are informed by a special status message that is sent automatically by this function. * * Sends out #DC_EVENT_CHAT_MODIFIED and #DC_EVENT_MSGS_CHANGED if a status message was sent. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param chat_id The chat ID to remove the contact from. Must be a group chat. * @param contact_id The contact ID to remove from the chat. * @return 1=member removed from group, 0=error */ int dc_remove_contact_from_chat(dc_context_t* context, uint32_t chat_id, uint32_t contact_id /*may be DC_CONTACT_ID_SELF*/) { int success = 0; dc_contact_t* contact = dc_get_contact(context, contact_id); dc_chat_t* chat = dc_chat_new(context); dc_msg_t* msg = dc_msg_new_untyped(context); char* q3 = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_id<=DC_CHAT_ID_LAST_SPECIAL || (contact_id<=DC_CONTACT_ID_LAST_SPECIAL && contact_id!=DC_CONTACT_ID_SELF)) { goto cleanup; /* we do not check if "contact_id" exists but just delete all records with the id from chats_contacts */ } /* this allows to delete pending references to deleted contacts. Of course, this should _not_ happen. */ if (0==real_group_exists(context, chat_id) || 0==dc_chat_load_from_db(chat, chat_id)) { goto cleanup; } if (!IS_SELF_IN_GROUP) { dc_log_event(context, DC_EVENT_ERROR_SELF_NOT_IN_GROUP, 0, "Cannot remove contact from chat; self not in group."); goto cleanup; /* we shoud respect this - whatever we send to the group, it gets discarded anyway! */ } /* send a status mail to all group members - we need to do this before we update the database - otherwise the !IS_SELF_IN_GROUP__-check in dc_chat_send_msg() will fail. */ if (contact) { if (DO_SEND_STATUS_MAILS) { msg->type = DC_MSG_TEXT; if (contact->id==DC_CONTACT_ID_SELF) { dc_set_group_explicitly_left(context, chat->grpid); msg->text = dc_stock_system_msg(context, DC_STR_MSGGROUPLEFT, NULL, NULL, DC_CONTACT_ID_SELF); } else { msg->text = dc_stock_system_msg(context, DC_STR_MSGDELMEMBER, contact->addr, NULL, DC_CONTACT_ID_SELF); } dc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_MEMBER_REMOVED_FROM_GROUP); dc_param_set (msg->param, DC_PARAM_CMD_ARG, contact->addr); msg->id = dc_send_msg(context, chat_id, msg); context->cb(context, DC_EVENT_MSGS_CHANGED, chat_id, msg->id); } } q3 = sqlite3_mprintf("DELETE FROM chats_contacts WHERE chat_id=%i AND contact_id=%i;", chat_id, contact_id); if (!dc_sqlite3_execute(context->sql, q3)) { goto cleanup; } context->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0); success = 1; cleanup: sqlite3_free(q3); dc_chat_unref(chat); dc_contact_unref(contact); dc_msg_unref(msg); return success; } /******************************************************************************* * Sending messages ******************************************************************************/ static int last_msg_in_chat_encrypted(dc_sqlite3_t* sql, uint32_t chat_id) { int last_is_encrypted = 0; sqlite3_stmt* stmt = dc_sqlite3_prepare(sql, "SELECT param " " FROM msgs " " WHERE timestamp=(SELECT MAX(timestamp) FROM msgs WHERE chat_id=?) " " ORDER BY id DESC;"); sqlite3_bind_int(stmt, 1, chat_id); if (sqlite3_step(stmt)==SQLITE_ROW) { dc_param_t* msg_param = dc_param_new(); dc_param_set_packed(msg_param, (char*)sqlite3_column_text(stmt, 0)); if (dc_param_exists(msg_param, DC_PARAM_GUARANTEE_E2EE)) { last_is_encrypted = 1; } dc_param_unref(msg_param); } sqlite3_finalize(stmt); return last_is_encrypted; } static int get_parent_mime_headers(const dc_chat_t* chat, char** parent_rfc724_mid, char** parent_in_reply_to, char** parent_references) { int success = 0; sqlite3_stmt* stmt = NULL; if (chat==NULL || parent_rfc724_mid==NULL || parent_in_reply_to==NULL || parent_references==NULL) { goto cleanup; } // use the last messsage of another user in the group as the parent stmt = dc_sqlite3_prepare(chat->context->sql, "SELECT rfc724_mid, mime_in_reply_to, mime_references" " FROM msgs" " WHERE chat_id=? AND timestamp=(SELECT max(timestamp) FROM msgs WHERE chat_id=? AND from_id!=?);"); sqlite3_bind_int (stmt, 1, chat->id); sqlite3_bind_int (stmt, 2, chat->id); sqlite3_bind_int (stmt, 3, DC_CONTACT_ID_SELF); if (sqlite3_step(stmt)==SQLITE_ROW) { *parent_rfc724_mid = dc_strdup((const char*)sqlite3_column_text(stmt, 0)); *parent_in_reply_to = dc_strdup((const char*)sqlite3_column_text(stmt, 1)); *parent_references = dc_strdup((const char*)sqlite3_column_text(stmt, 2)); success = 1; } sqlite3_finalize(stmt); stmt = NULL; if (!success) { // there are no messages of other users - use the first message if SELF as parent stmt = dc_sqlite3_prepare(chat->context->sql, "SELECT rfc724_mid, mime_in_reply_to, mime_references" " FROM msgs" " WHERE chat_id=? AND timestamp=(SELECT min(timestamp) FROM msgs WHERE chat_id=? AND from_id==?);"); sqlite3_bind_int (stmt, 1, chat->id); sqlite3_bind_int (stmt, 2, chat->id); sqlite3_bind_int (stmt, 3, DC_CONTACT_ID_SELF); if (sqlite3_step(stmt)==SQLITE_ROW) { *parent_rfc724_mid = dc_strdup((const char*)sqlite3_column_text(stmt, 0)); *parent_in_reply_to = dc_strdup((const char*)sqlite3_column_text(stmt, 1)); *parent_references = dc_strdup((const char*)sqlite3_column_text(stmt, 2)); success = 1; } } cleanup: sqlite3_finalize(stmt); return success; } static uint32_t prepare_msg_raw(dc_context_t* context, dc_chat_t* chat, const dc_msg_t* msg, time_t timestamp) { char* parent_rfc724_mid = NULL; char* parent_references = NULL; char* parent_in_reply_to = NULL; char* new_rfc724_mid = NULL; char* new_references = NULL; char* new_in_reply_to = NULL; sqlite3_stmt* stmt = NULL; uint32_t msg_id = 0; uint32_t to_id = 0; uint32_t location_id = 0; if (!DC_CHAT_TYPE_CAN_SEND(chat->type)) { dc_log_error(context, 0, "Cannot send to chat type #%i.", chat->type); goto cleanup; } if (DC_CHAT_TYPE_IS_MULTI(chat->type) && !dc_is_contact_in_chat(context, chat->id, DC_CONTACT_ID_SELF)) { dc_log_event(context, DC_EVENT_ERROR_SELF_NOT_IN_GROUP, 0, "Cannot send message; self not in group."); goto cleanup; } { char* from = dc_sqlite3_get_config(context->sql, "configured_addr", NULL); if (from==NULL) { dc_log_error(context, 0, "Cannot send message, not configured."); goto cleanup; } new_rfc724_mid = dc_create_outgoing_rfc724_mid(DC_CHAT_TYPE_IS_MULTI(chat->type)? chat->grpid : NULL, from); free(from); } if (chat->type==DC_CHAT_TYPE_SINGLE) { stmt = dc_sqlite3_prepare(context->sql, "SELECT contact_id FROM chats_contacts WHERE chat_id=?;"); sqlite3_bind_int(stmt, 1, chat->id); if (sqlite3_step(stmt)!=SQLITE_ROW) { dc_log_error(context, 0, "Cannot send message, contact for chat #%i not found.", chat->id); goto cleanup; } to_id = sqlite3_column_int(stmt, 0); sqlite3_finalize(stmt); stmt = NULL; } else if (DC_CHAT_TYPE_IS_MULTI(chat->type)) { if (dc_param_get_int(chat->param, DC_PARAM_UNPROMOTED, 0)==1) { /* mark group as being no longer unpromoted */ dc_param_set(chat->param, DC_PARAM_UNPROMOTED, NULL); dc_chat_update_param(chat); } } /* check if we can guarantee E2EE for this message. if we guarantee E2EE, and circumstances change so that E2EE is no longer available at a later point (reset, changed settings), we do not send the message out at all */ int do_guarantee_e2ee = 0; int e2ee_enabled = dc_sqlite3_get_config_int(context->sql, "e2ee_enabled", DC_E2EE_DEFAULT_ENABLED); if (e2ee_enabled && dc_param_get_int(msg->param, DC_PARAM_FORCE_PLAINTEXT, 0)==0) { int can_encrypt = 1, all_mutual = 1; /* be optimistic */ stmt = dc_sqlite3_prepare(context->sql, "SELECT ps.prefer_encrypted, c.addr" " FROM chats_contacts cc " " LEFT JOIN contacts c ON cc.contact_id=c.id " " LEFT JOIN acpeerstates ps ON c.addr=ps.addr " " WHERE cc.chat_id=? " /* take care that this statement returns NULL rows if there is no peerstates for a chat member! */ " AND cc.contact_id>" DC_STRINGIFY(DC_CONTACT_ID_LAST_SPECIAL) ";"); /* for DC_PARAM_SELFTALK this statement does not return any row */ sqlite3_bind_int(stmt, 1, chat->id); while (sqlite3_step(stmt)==SQLITE_ROW) { if (sqlite3_column_type(stmt, 0)==SQLITE_NULL) { dc_log_info(context, 0, "[autocrypt] no peerstate for %s", sqlite3_column_text(stmt, 1)); can_encrypt = 0; all_mutual = 0; } else { /* the peerstate exist, so we have either public_key or gossip_key and can encrypt potentially */ int prefer_encrypted = sqlite3_column_int(stmt, 0); if (prefer_encrypted!=DC_PE_MUTUAL) { dc_log_info(context, 0, "[autocrypt] peerstate for %s is %s", sqlite3_column_text(stmt, 1), prefer_encrypted==DC_PE_NOPREFERENCE? "NOPREFERENCE" : "RESET"); all_mutual = 0; } } } sqlite3_finalize(stmt); stmt = NULL; if (can_encrypt) { if (all_mutual) { do_guarantee_e2ee = 1; } else { if (last_msg_in_chat_encrypted(context->sql, chat->id)) { do_guarantee_e2ee = 1; } } } } if (do_guarantee_e2ee) { dc_param_set_int(msg->param, DC_PARAM_GUARANTEE_E2EE, 1); } dc_param_set(msg->param, DC_PARAM_ERRONEOUS_E2EE, NULL); /* reset eg. on forwarding */ // set "In-Reply-To:" to identify the message to which the composed message is a reply; // set "References:" to identify the "thread" of the conversation; // both according to RFC 5322 3.6.4, page 25 // // as self-talks are mainly used to transfer data between devices, // we do not set In-Reply-To/References in this case. if (!dc_chat_is_self_talk(chat) && get_parent_mime_headers(chat, &parent_rfc724_mid, &parent_in_reply_to, &parent_references)) { if (parent_rfc724_mid && parent_rfc724_mid[0]) { new_in_reply_to = dc_strdup(parent_rfc724_mid); } // the whole list of messages referenced may be huge; // only use the oldest and and the parent message if (parent_references) { char* space = NULL; if ((space=strchr(parent_references, ' '))!=NULL) { *space = 0; } } if (parent_references && parent_references[0] && parent_rfc724_mid && parent_rfc724_mid[0]) { // angle brackets are added by the mimefactory later new_references = dc_mprintf("%s %s", parent_references, parent_rfc724_mid); } else if (parent_references && parent_references[0]) { new_references = dc_strdup(parent_references); } else if (parent_in_reply_to && parent_in_reply_to[0] && parent_rfc724_mid && parent_rfc724_mid[0]) { new_references = dc_mprintf("%s %s", parent_in_reply_to, parent_rfc724_mid); } else if (parent_in_reply_to && parent_in_reply_to[0]) { new_references = dc_strdup(parent_in_reply_to); } } /* add independent location to database */ if (dc_param_exists(msg->param, DC_PARAM_SET_LATITUDE)) { stmt = dc_sqlite3_prepare(context->sql, "INSERT INTO locations " " (timestamp,from_id,chat_id, latitude,longitude,independent)" " VALUES (?,?,?, ?,?,1);"); sqlite3_bind_int64 (stmt, 1, timestamp); sqlite3_bind_int (stmt, 2, DC_CONTACT_ID_SELF); sqlite3_bind_int (stmt, 3, chat->id); sqlite3_bind_double(stmt, 4, dc_param_get_float(msg->param, DC_PARAM_SET_LATITUDE, 0.0)); sqlite3_bind_double(stmt, 5, dc_param_get_float(msg->param, DC_PARAM_SET_LONGITUDE, 0.0)); sqlite3_step(stmt); sqlite3_finalize(stmt); stmt = NULL; location_id = dc_sqlite3_get_rowid2(context->sql, "locations", "timestamp", timestamp, "from_id", DC_CONTACT_ID_SELF); } /* add message to the database */ stmt = dc_sqlite3_prepare(context->sql, "INSERT INTO msgs (rfc724_mid, chat_id, from_id, to_id, timestamp," " type, state, txt, param, hidden," " mime_in_reply_to, mime_references, location_id)" " VALUES (?,?,?,?,?, ?,?,?,?,?, ?,?,?);"); sqlite3_bind_text (stmt, 1, new_rfc724_mid, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 2, chat->id); sqlite3_bind_int (stmt, 3, DC_CONTACT_ID_SELF); sqlite3_bind_int (stmt, 4, to_id); sqlite3_bind_int64(stmt, 5, timestamp); sqlite3_bind_int (stmt, 6, msg->type); sqlite3_bind_int (stmt, 7, msg->state); sqlite3_bind_text (stmt, 8, msg->text? msg->text : "", -1, SQLITE_STATIC); sqlite3_bind_text (stmt, 9, msg->param->packed, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 10, msg->hidden); sqlite3_bind_text (stmt, 11, new_in_reply_to, -1, SQLITE_STATIC); sqlite3_bind_text (stmt, 12, new_references, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 13, location_id); if (sqlite3_step(stmt)!=SQLITE_DONE) { dc_log_error(context, 0, "Cannot send message, cannot insert to database.", chat->id); goto cleanup; } msg_id = dc_sqlite3_get_rowid(context->sql, "msgs", "rfc724_mid", new_rfc724_mid); cleanup: free(parent_rfc724_mid); free(parent_in_reply_to); free(parent_references); free(new_rfc724_mid); free(new_in_reply_to); free(new_references); sqlite3_finalize(stmt); return msg_id; } static uint32_t prepare_msg_common(dc_context_t* context, uint32_t chat_id, dc_msg_t* msg) { char* pathNfilename = NULL; dc_chat_t* chat = NULL; msg->id = 0; msg->context = context; if (msg->type==DC_MSG_TEXT) { ; /* the caller should check if the message text is empty */ } else if (DC_MSG_NEEDS_ATTACHMENT(msg->type)) { pathNfilename = dc_param_get(msg->param, DC_PARAM_FILE, NULL); if (pathNfilename==NULL) { dc_log_error(context, 0, "Attachment missing for message of type #%i.", (int)msg->type); goto cleanup; } if (msg->state==DC_STATE_OUT_PREPARING && !dc_is_blobdir_path(context, pathNfilename)) { dc_log_error(context, 0, "Files must be created in the blob-directory."); goto cleanup; } if (!dc_make_rel_and_copy(context, &pathNfilename)) { goto cleanup; } dc_param_set(msg->param, DC_PARAM_FILE, pathNfilename); if (msg->type==DC_MSG_FILE || msg->type==DC_MSG_IMAGE) { /* Correct the type, take care not to correct already very special formats as GIF or VOICE. Typical conversions: - from FILE to AUDIO/VIDEO/IMAGE - from FILE/IMAGE to GIF */ int better_type = 0; char* better_mime = NULL; dc_msg_guess_msgtype_from_suffix(pathNfilename, &better_type, &better_mime); if (better_type) { msg->type = better_type; dc_param_set(msg->param, DC_PARAM_MIMETYPE, better_mime); } free(better_mime); } else if (!dc_param_exists(msg->param, DC_PARAM_MIMETYPE)) { char* better_mime = NULL; dc_msg_guess_msgtype_from_suffix(pathNfilename, NULL, &better_mime); dc_param_set(msg->param, DC_PARAM_MIMETYPE, better_mime); free(better_mime); } dc_log_info(context, 0, "Attaching \"%s\" for message type #%i.", pathNfilename, (int)msg->type); } else { dc_log_error(context, 0, "Cannot send messages of type #%i.", (int)msg->type); /* should not happen */ goto cleanup; } dc_unarchive_chat(context, chat_id); context->smtp->log_connect_errors = 1; chat = dc_chat_new(context); if (dc_chat_load_from_db(chat, chat_id)) { /* ensure the message is in a valid state */ if (msg->state!=DC_STATE_OUT_PREPARING) msg->state = DC_STATE_OUT_PENDING; msg->id = prepare_msg_raw(context, chat, msg, dc_create_smeared_timestamp(context)); msg->chat_id = chat_id; /* potential error already logged */ } cleanup: dc_chat_unref(chat); free(pathNfilename); return msg->id; } /** * Prepare a message for sending. * * Call this function if the file to be sent is still in creation. * Once you're done with creating the file, call dc_send_msg() as usual * and the message will really be sent. * * This is useful as the user can already send the next messages while * e.g. the recoding of a video is not yet finished. Or the user can even forward * the message with the file being still in creation to other groups. * * Files being sent with the increation-method must be placed in the * blob directory, see dc_get_blobdir(). * If the increation-method is not used - which is probably the normal case - * dc_send_msg() copies the file to the blob directory if it is not yet there. * To distinguish the two cases, msg->state must be set properly. The easiest * way to ensure this is to re-use the same object for both calls. * * Example: * ~~~ * dc_msg_t* msg = dc_msg_new(context, DC_MSG_VIDEO); * dc_msg_set_file(msg, "/file/to/send.mp4", NULL); * dc_prepare_msg(context, chat_id, msg); * // ... after /file/to/send.mp4 is ready: * dc_send_msg(context, chat_id, msg); * ~~~ * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id Chat ID to send the message to. * @param msg Message object to send to the chat defined by the chat ID. * On succcess, msg_id and state of the object are set up, * The function does not take ownership of the object, * so you have to free it using dc_msg_unref() as usual. * @return The ID of the message that is being prepared. */ uint32_t dc_prepare_msg(dc_context_t* context, uint32_t chat_id, dc_msg_t* msg) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg==NULL || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { return 0; } msg->state = DC_STATE_OUT_PREPARING; uint32_t msg_id = prepare_msg_common(context, chat_id, msg); context->cb(context, DC_EVENT_MSGS_CHANGED, msg->chat_id, msg->id); if (dc_param_exists(msg->param, DC_PARAM_SET_LATITUDE)) { context->cb(context, DC_EVENT_LOCATION_CHANGED, DC_CONTACT_ID_SELF, 0); } return msg_id; } /** * Send a message defined by a dc_msg_t object to a chat. * * Sends the event #DC_EVENT_MSGS_CHANGED on succcess. * However, this does not imply, the message really reached the recipient - * sending may be delayed eg. due to network problems. However, from your * view, you're done with the message. Sooner or later it will find its way. * * Example: * ~~~ * dc_msg_t* msg = dc_msg_new(context, DC_MSG_IMAGE); * dc_msg_set_file(msg, "/file/to/send.jpg", NULL); * dc_send_msg(context, chat_id, msg); * ~~~ * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id Chat ID to send the message to. * If dc_prepare_msg() was called before, this parameter can be 0. * @param msg Message object to send to the chat defined by the chat ID. * On succcess, msg_id of the object is set up, * The function does not take ownership of the object, * so you have to free it using dc_msg_unref() as usual. * @return The ID of the message that is about to be sent. 0 in case of errors. */ uint32_t dc_send_msg(dc_context_t* context, uint32_t chat_id, dc_msg_t* msg) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg==NULL) { return 0; } // automatically prepare normal messages if (msg->state!=DC_STATE_OUT_PREPARING) { if (!prepare_msg_common(context, chat_id, msg)) { return 0; }; } // update message state of separately prepared messages else { if (chat_id!=0 && chat_id!=msg->chat_id) { return 0; } dc_update_msg_state(context, msg->id, DC_STATE_OUT_PENDING); } // create message file and submit SMTP job if (!dc_job_send_msg(context, msg->id)) { return 0; } context->cb(context, DC_EVENT_MSGS_CHANGED, msg->chat_id, msg->id); if (dc_param_exists(msg->param, DC_PARAM_SET_LATITUDE)) { context->cb(context, DC_EVENT_LOCATION_CHANGED, DC_CONTACT_ID_SELF, 0); } // recursively send any forwarded copies if (!chat_id) { char* forwards = dc_param_get(msg->param, DC_PARAM_PREP_FORWARDS, NULL); if (forwards) { char* p = forwards; while (*p) { int32_t id = strtol(p, &p, 10); if (!id) break; // avoid hanging if user tampers with db dc_msg_t* copy = dc_get_msg(context, id); if (copy) { dc_send_msg(context, 0, copy); } dc_msg_unref(copy); } dc_param_set(msg->param, DC_PARAM_PREP_FORWARDS, NULL); dc_msg_save_param_to_disk(msg); } free(forwards); } return msg->id; } /** * Send a simple text message a given chat. * * Sends the event #DC_EVENT_MSGS_CHANGED on succcess. * However, this does not imply, the message really reached the recipient - * sending may be delayed eg. due to network problems. However, from your * view, you're done with the message. Sooner or later it will find its way. * * See also dc_send_msg(). * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id Chat ID to send the text message to. * @param text_to_send Text to send to the chat defined by the chat ID. * Passing an empty text here causes an empty text to be sent, * it's up to the caller to handle this if undesired. * Passing NULL as the text causes the function to return 0. * @return The ID of the message that is about being sent. */ uint32_t dc_send_text_msg(dc_context_t* context, uint32_t chat_id, const char* text_to_send) { dc_msg_t* msg = dc_msg_new(context, DC_MSG_TEXT); uint32_t ret = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_id<=DC_CHAT_ID_LAST_SPECIAL || text_to_send==NULL) { goto cleanup; } msg->text = dc_strdup(text_to_send); ret = dc_send_msg(context, chat_id, msg); cleanup: dc_msg_unref(msg); return ret; } /* * Log a device message. * Such a message is typically shown in the "middle" of the chat, the user can check this using dc_msg_is_info(). * Texts are typically "Alice has added Bob to the group" or "Alice fingerprint verified." */ void dc_add_device_msg(dc_context_t* context, uint32_t chat_id, const char* text) { uint32_t msg_id = 0; sqlite3_stmt* stmt = NULL; char* rfc724_mid = dc_create_outgoing_rfc724_mid(NULL, "@device"); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || text==NULL) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "INSERT INTO msgs (chat_id,from_id,to_id, timestamp,type,state, txt,rfc724_mid) VALUES (?,?,?, ?,?,?, ?,?);"); sqlite3_bind_int (stmt, 1, chat_id); sqlite3_bind_int (stmt, 2, DC_CONTACT_ID_DEVICE); sqlite3_bind_int (stmt, 3, DC_CONTACT_ID_DEVICE); sqlite3_bind_int64(stmt, 4, dc_create_smeared_timestamp(context)); sqlite3_bind_int (stmt, 5, DC_MSG_TEXT); sqlite3_bind_int (stmt, 6, DC_STATE_IN_NOTICED); sqlite3_bind_text (stmt, 7, text, -1, SQLITE_STATIC); sqlite3_bind_text (stmt, 8, rfc724_mid, -1, SQLITE_STATIC); if (sqlite3_step(stmt)!=SQLITE_DONE) { goto cleanup; } msg_id = dc_sqlite3_get_rowid(context->sql, "msgs", "rfc724_mid", rfc724_mid); context->cb(context, DC_EVENT_MSGS_CHANGED, chat_id, msg_id); cleanup: free(rfc724_mid); sqlite3_finalize(stmt); } /** * Forward messages to another chat. * * @memberof dc_context_t * @param context The context object as created by dc_context_new() * @param msg_ids An array of uint32_t containing all message IDs that should be forwarded * @param msg_cnt The number of messages IDs in the msg_ids array * @param chat_id The destination chat ID. * @return None. */ void dc_forward_msgs(dc_context_t* context, const uint32_t* msg_ids, int msg_cnt, uint32_t chat_id) { dc_msg_t* msg = dc_msg_new_untyped(context); dc_chat_t* chat = dc_chat_new(context); dc_contact_t* contact = dc_contact_new(context); int transaction_pending = 0; carray* created_db_entries = carray_new(16); char* idsstr = NULL; char* q3 = NULL; sqlite3_stmt* stmt = NULL; time_t curr_timestamp = 0; dc_param_t* original_param = dc_param_new(); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg_ids==NULL || msg_cnt<=0 || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { goto cleanup; } dc_sqlite3_begin_transaction(context->sql); transaction_pending = 1; dc_unarchive_chat(context, chat_id); context->smtp->log_connect_errors = 1; if (!dc_chat_load_from_db(chat, chat_id)) { goto cleanup; } curr_timestamp = dc_create_smeared_timestamps(context, msg_cnt); idsstr = dc_arr_to_string(msg_ids, msg_cnt); q3 = sqlite3_mprintf("SELECT id FROM msgs WHERE id IN(%s) ORDER BY timestamp,id", idsstr); stmt = dc_sqlite3_prepare(context->sql, q3); while (sqlite3_step(stmt)==SQLITE_ROW) { int src_msg_id = sqlite3_column_int(stmt, 0); if (!dc_msg_load_from_db(msg, context, src_msg_id)) { goto cleanup; } dc_param_set_packed(original_param, msg->param->packed); // do not mark own messages as being forwarded. // this allows sort of broadcasting // by just forwarding messages to other chats. if (msg->from_id!=DC_CONTACT_ID_SELF) { dc_param_set_int(msg->param, DC_PARAM_FORWARDED, 1); } dc_param_set(msg->param, DC_PARAM_GUARANTEE_E2EE, NULL); dc_param_set(msg->param, DC_PARAM_FORCE_PLAINTEXT, NULL); dc_param_set(msg->param, DC_PARAM_CMD, NULL); uint32_t new_msg_id; // PREPARING messages can't be forwarded immediately if (msg->state==DC_STATE_OUT_PREPARING) { new_msg_id = prepare_msg_raw(context, chat, msg, curr_timestamp++); // to update the original message, perform in-place surgery // on msg to avoid copying the entire structure, text, etc. dc_param_t* save_param = msg->param; msg->param = original_param; msg->id = src_msg_id; { // append new id to the original's param. char* old_fwd = dc_param_get(msg->param, DC_PARAM_PREP_FORWARDS, ""); char* new_fwd = dc_mprintf("%s %d", old_fwd, new_msg_id); dc_param_set(msg->param, DC_PARAM_PREP_FORWARDS, new_fwd); dc_msg_save_param_to_disk(msg); free(new_fwd); free(old_fwd); } msg->param = save_param; } else { msg->state = DC_STATE_OUT_PENDING; new_msg_id = prepare_msg_raw(context, chat, msg, curr_timestamp++); dc_job_send_msg(context, new_msg_id); } carray_add(created_db_entries, (void*)(uintptr_t)chat_id, NULL); carray_add(created_db_entries, (void*)(uintptr_t)new_msg_id, NULL); } dc_sqlite3_commit(context->sql); transaction_pending = 0; cleanup: if (transaction_pending) { dc_sqlite3_rollback(context->sql); } if (created_db_entries) { size_t i, icnt = carray_count(created_db_entries); for (i = 0; i < icnt; i += 2) { context->cb(context, DC_EVENT_MSGS_CHANGED, (uintptr_t)carray_get(created_db_entries, i), (uintptr_t)carray_get(created_db_entries, i+1)); } carray_free(created_db_entries); } dc_contact_unref(contact); dc_msg_unref(msg); dc_chat_unref(chat); sqlite3_finalize(stmt); free(idsstr); sqlite3_free(q3); dc_param_unref(original_param); } ``` Filename: dc_chatlist.c ```c #include "dc_context.h" #define DC_CHATLIST_MAGIC 0xc4a71157 /** * Create a chatlist object in memory. * * @private @memberof dc_chatlist_t * @param context The context that should be stored in the chatlist object. * @return New and empty chatlist object, must be freed using dc_chatlist_unref(). */ dc_chatlist_t* dc_chatlist_new(dc_context_t* context) { dc_chatlist_t* chatlist = NULL; if ((chatlist=calloc(1, sizeof(dc_chatlist_t)))==NULL) { exit(20); } chatlist->magic = DC_CHATLIST_MAGIC; chatlist->context = context; if ((chatlist->chatNlastmsg_ids=dc_array_new(context, 128))==NULL) { exit(32); } return chatlist; } /** * Free a chatlist object. * * @memberof dc_chatlist_t * @param chatlist The chatlist object to free, created eg. by dc_get_chatlist(), dc_search_msgs(). * If NULL is given, nothing is done. * @return None. */ void dc_chatlist_unref(dc_chatlist_t* chatlist) { if (chatlist==NULL || chatlist->magic!=DC_CHATLIST_MAGIC) { return; } dc_chatlist_empty(chatlist); dc_array_unref(chatlist->chatNlastmsg_ids); chatlist->magic = 0; free(chatlist); } /** * Empty a chatlist object. * * @private @memberof dc_chatlist_t * @param chatlist The chatlist object to empty. * @return None. */ void dc_chatlist_empty(dc_chatlist_t* chatlist) { if (chatlist==NULL || chatlist->magic!=DC_CHATLIST_MAGIC) { return; } chatlist->cnt = 0; dc_array_empty(chatlist->chatNlastmsg_ids); } /** * Find out the number of chats in a chatlist. * * @memberof dc_chatlist_t * @param chatlist The chatlist object as created eg. by dc_get_chatlist(). * @return Returns the number of items in a dc_chatlist_t object. 0 on errors or if the list is empty. */ size_t dc_chatlist_get_cnt(const dc_chatlist_t* chatlist) { if (chatlist==NULL || chatlist->magic!=DC_CHATLIST_MAGIC) { return 0; } return chatlist->cnt; } /** * Get a single chat ID of a chatlist. * * To get the message object from the message ID, use dc_get_chat(). * * @memberof dc_chatlist_t * @param chatlist The chatlist object as created eg. by dc_get_chatlist(). * @param index The index to get the chat ID for. * @return Returns the chat_id of the item at the given index. Index must be between * 0 and dc_chatlist_get_cnt()-1. */ uint32_t dc_chatlist_get_chat_id(const dc_chatlist_t* chatlist, size_t index) { if (chatlist==NULL || chatlist->magic!=DC_CHATLIST_MAGIC || chatlist->chatNlastmsg_ids==NULL || index>=chatlist->cnt) { return 0; } return dc_array_get_id(chatlist->chatNlastmsg_ids, index*DC_CHATLIST_IDS_PER_RESULT); } /** * Get a single message ID of a chatlist. * * To get the message object from the message ID, use dc_get_msg(). * * @memberof dc_chatlist_t * @param chatlist The chatlist object as created eg. by dc_get_chatlist(). * @param index The index to get the chat ID for. * @return Returns the message_id of the item at the given index. Index must be between * 0 and dc_chatlist_get_cnt()-1. If there is no message at the given index (eg. the chat may be empty), 0 is returned. */ uint32_t dc_chatlist_get_msg_id(const dc_chatlist_t* chatlist, size_t index) { if (chatlist==NULL || chatlist->magic!=DC_CHATLIST_MAGIC || chatlist->chatNlastmsg_ids==NULL || index>=chatlist->cnt) { return 0; } return dc_array_get_id(chatlist->chatNlastmsg_ids, index*DC_CHATLIST_IDS_PER_RESULT+1); } /** * Get a summary for a chatlist index. * * The summary is returned by a dc_lot_t object with the following fields: * * - dc_lot_t::text1: contains the username or the strings "Me", "Draft" and so on. * The string may be colored by having a look at text1_meaning. * If there is no such name or it should not be displayed, the element is NULL. * * - dc_lot_t::text1_meaning: one of DC_TEXT1_USERNAME, DC_TEXT1_SELF or DC_TEXT1_DRAFT. * Typically used to show dc_lot_t::text1 with different colors. 0 if not applicable. * * - dc_lot_t::text2: contains an excerpt of the message text or strings as * "No messages". May be NULL of there is no such text (eg. for the archive link) * * - dc_lot_t::timestamp: the timestamp of the message. 0 if not applicable. * * - dc_lot_t::state: The state of the message as one of the DC_STATE_* constants (see #dc_msg_get_state()). 0 if not applicable. * * @memberof dc_chatlist_t * @param chatlist The chatlist to query as returned eg. from dc_get_chatlist(). * @param index The index to query in the chatlist. * @param chat To speed up things, pass an already available chat object here. * If the chat object is not yet available, it is faster to pass NULL. * @return The summary as an dc_lot_t object. Must be freed using dc_lot_unref(). NULL is never returned. */ dc_lot_t* dc_chatlist_get_summary(const dc_chatlist_t* chatlist, size_t index, dc_chat_t* chat /*may be NULL*/) { /* The summary is created by the chat, not by the last message. This is because we may want to display drafts here or stuff as "is typing". Also, sth. as "No messages" would not work if the summary comes from a message. */ dc_lot_t* ret = dc_lot_new(); /* the function never returns NULL */ uint32_t lastmsg_id = 0; dc_msg_t* lastmsg = NULL; dc_contact_t* lastcontact = NULL; dc_chat_t* chat_to_delete = NULL; if (chatlist==NULL || chatlist->magic!=DC_CHATLIST_MAGIC || index>=chatlist->cnt) { ret->text2 = dc_strdup("ErrBadChatlistIndex"); goto cleanup; } lastmsg_id = dc_array_get_id(chatlist->chatNlastmsg_ids, index*DC_CHATLIST_IDS_PER_RESULT+1); if (chat==NULL) { chat = dc_chat_new(chatlist->context); chat_to_delete = chat; if (!dc_chat_load_from_db(chat, dc_array_get_id(chatlist->chatNlastmsg_ids, index*DC_CHATLIST_IDS_PER_RESULT))) { ret->text2 = dc_strdup("ErrCannotReadChat"); goto cleanup; } } if (lastmsg_id) { lastmsg = dc_msg_new_untyped(chatlist->context); dc_msg_load_from_db(lastmsg, chatlist->context, lastmsg_id); if (lastmsg->from_id!=DC_CONTACT_ID_SELF && DC_CHAT_TYPE_IS_MULTI(chat->type)) { lastcontact = dc_contact_new(chatlist->context); dc_contact_load_from_db(lastcontact, chatlist->context->sql, lastmsg->from_id); } } if (chat->id==DC_CHAT_ID_ARCHIVED_LINK) { ret->text2 = dc_strdup(NULL); } else if (lastmsg==NULL || lastmsg->from_id==0) { /* no messages */ ret->text2 = dc_stock_str(chatlist->context, DC_STR_NOMESSAGES); } else { /* show the last message */ dc_lot_fill(ret, lastmsg, chat, lastcontact, chatlist->context); } cleanup: dc_msg_unref(lastmsg); dc_contact_unref(lastcontact); dc_chat_unref(chat_to_delete); return ret; } /** * Helper function to get the associated context object. * * @memberof dc_chatlist_t * @param chatlist The chatlist object to empty. * @return Context object associated with the chatlist. NULL if none or on errors. */ dc_context_t* dc_chatlist_get_context(dc_chatlist_t* chatlist) { if (chatlist==NULL || chatlist->magic!=DC_CHATLIST_MAGIC) { return NULL; } return chatlist->context; } static uint32_t get_last_deaddrop_fresh_msg(dc_context_t* context) { uint32_t ret = 0; sqlite3_stmt* stmt = NULL; stmt = dc_sqlite3_prepare(context->sql, "SELECT m.id " " FROM msgs m " " LEFT JOIN chats c ON c.id=m.chat_id " " WHERE m.state=" DC_STRINGIFY(DC_STATE_IN_FRESH) " AND m.hidden=0 " " AND c.blocked=" DC_STRINGIFY(DC_CHAT_DEADDROP_BLOCKED) " ORDER BY m.timestamp DESC, m.id DESC;"); /* we have an index over the state-column, this should be sufficient as there are typically only few fresh messages */ if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } ret = sqlite3_column_int(stmt, 0); cleanup: sqlite3_finalize(stmt); return ret; } /** * Load a chatlist from the database to the chatlist object. * * @private @memberof dc_chatlist_t */ static int dc_chatlist_load_from_db(dc_chatlist_t* chatlist, int listflags, const char* query__, uint32_t query_contact_id) { //clock_t start = clock(); int success = 0; int add_archived_link_item = 0; sqlite3_stmt* stmt = NULL; char* strLikeCmd = NULL; char* query = NULL; if (chatlist==NULL || chatlist->magic!=DC_CHATLIST_MAGIC || chatlist->context==NULL) { goto cleanup; } dc_chatlist_empty(chatlist); // select with left join and minimum: // - the inner select must use `hidden` and _not_ `m.hidden` // which would refer the outer select and take a lot of time // - `GROUP BY` is needed several messages may have the same timestamp // - the list starts with the newest chats #define QUR1 "SELECT c.id, m.id FROM chats c " \ " LEFT JOIN msgs m " \ " ON c.id=m.chat_id " \ " AND m.timestamp=( " \ "SELECT MAX(timestamp) " \ " FROM msgs " \ " WHERE chat_id=c.id " \ " AND (hidden=0 OR (hidden=1 AND state=" DC_STRINGIFY(DC_STATE_OUT_DRAFT) ")))" \ " WHERE c.id>" DC_STRINGIFY(DC_CHAT_ID_LAST_SPECIAL) \ " AND c.blocked=0" #define QUR2 " GROUP BY c.id " \ " ORDER BY IFNULL(m.timestamp,0) DESC, m.id DESC;" // nb: the query currently shows messages from blocked contacts in groups. // however, for normal-groups, this is okay as the message is also returned by dc_get_chat_msgs() // (otherwise it would be hard to follow conversations, wa and tg do the same) // for the deaddrop, however, they should really be hidden, however, _currently_ the deaddrop is not // shown at all permanent in the chatlist. if (query_contact_id) { // show chats shared with a given contact stmt = dc_sqlite3_prepare(chatlist->context->sql, QUR1 " AND c.id IN(SELECT chat_id FROM chats_contacts WHERE contact_id=?) " QUR2); sqlite3_bind_int(stmt, 1, query_contact_id); } else if (listflags & DC_GCL_ARCHIVED_ONLY) { /* show archived chats */ stmt = dc_sqlite3_prepare(chatlist->context->sql, QUR1 " AND c.archived=1 " QUR2); } else if (query__==NULL) { /* show normal chatlist */ if (!(listflags & DC_GCL_NO_SPECIALS)) { uint32_t last_deaddrop_fresh_msg_id = get_last_deaddrop_fresh_msg(chatlist->context); if (last_deaddrop_fresh_msg_id > 0) { dc_array_add_id(chatlist->chatNlastmsg_ids, DC_CHAT_ID_DEADDROP); /* show deaddrop with the last fresh message */ dc_array_add_id(chatlist->chatNlastmsg_ids, last_deaddrop_fresh_msg_id); } add_archived_link_item = 1; } stmt = dc_sqlite3_prepare(chatlist->context->sql, QUR1 " AND c.archived=0 " QUR2); } else { /* show chatlist filtered by a search string, this includes archived and unarchived */ query = dc_strdup(query__); dc_trim(query); if (query[0]==0) { success = 1; /*empty result*/ goto cleanup; } strLikeCmd = dc_mprintf("%%%s%%", query); stmt = dc_sqlite3_prepare(chatlist->context->sql, QUR1 " AND c.name LIKE ? " QUR2); sqlite3_bind_text(stmt, 1, strLikeCmd, -1, SQLITE_STATIC); } while (sqlite3_step(stmt)==SQLITE_ROW) { dc_array_add_id(chatlist->chatNlastmsg_ids, sqlite3_column_int(stmt, 0)); dc_array_add_id(chatlist->chatNlastmsg_ids, sqlite3_column_int(stmt, 1)); } if (add_archived_link_item && dc_get_archived_cnt(chatlist->context)>0) { if (dc_array_get_cnt(chatlist->chatNlastmsg_ids)==0 && (listflags & DC_GCL_ADD_ALLDONE_HINT)) { dc_array_add_id(chatlist->chatNlastmsg_ids, DC_CHAT_ID_ALLDONE_HINT); dc_array_add_id(chatlist->chatNlastmsg_ids, 0); } dc_array_add_id(chatlist->chatNlastmsg_ids, DC_CHAT_ID_ARCHIVED_LINK); dc_array_add_id(chatlist->chatNlastmsg_ids, 0); } chatlist->cnt = dc_array_get_cnt(chatlist->chatNlastmsg_ids)/DC_CHATLIST_IDS_PER_RESULT; success = 1; cleanup: //dc_log_info(chatlist->context, 0, "Chatlist for search \"%s\" created in %.3f ms.", query__?query__:"", (double)(clock()-start)*1000.0/CLOCKS_PER_SEC); sqlite3_finalize(stmt); free(query); free(strLikeCmd); return success; } /******************************************************************************* * Context functions to work with chatlists ******************************************************************************/ int dc_get_archived_cnt(dc_context_t* context) { int ret = 0; sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM chats WHERE blocked=0 AND archived=1;"); if (sqlite3_step(stmt)==SQLITE_ROW) { ret = sqlite3_column_int(stmt, 0); } sqlite3_finalize(stmt); return ret; } /** * Get a list of chats. * The list can be filtered by query parameters. * * The list is already sorted and starts with the most recent chat in use. * The sorting takes care of invalid sending dates, drafts and chats without messages. * Clients should not try to re-sort the list as this would be an expensive action * and would result in inconsistencies between clients. * * To get information about each entry, use eg. dc_chatlist_get_summary(). * * By default, the function adds some special entries to the list. * These special entries can be identified by the ID returned by dc_chatlist_get_chat_id(): * - DC_CHAT_ID_DEADDROP (1) - this special chat is present if there are * messages from addresses that have no relationship to the configured account. * The last of these messages is represented by DC_CHAT_ID_DEADDROP and you can retrieve details * about it with dc_chatlist_get_msg_id(). Typically, the UI asks the user "Do you want to chat with NAME?" * and offers the options "Yes" (call dc_create_chat_by_msg_id()), "Never" (call dc_block_contact()) * or "Not now". * The UI can also offer a "Close" button that calls dc_marknoticed_contact() then. * - DC_CHAT_ID_ARCHIVED_LINK (6) - this special chat is present if the user has * archived _any_ chat using dc_archive_chat(). The UI should show a link as * "Show archived chats", if the user clicks this item, the UI should show a * list of all archived chats that can be created by this function hen using * the DC_GCL_ARCHIVED_ONLY flag. * - DC_CHAT_ID_ALLDONE_HINT (7) - this special chat is present * if DC_GCL_ADD_ALLDONE_HINT is added to listflags * and if there are only archived chats. * * @memberof dc_context_t * @param context The context object as returned by dc_context_new() * @param listflags A combination of flags: * - if the flag DC_GCL_ARCHIVED_ONLY is set, only archived chats are returned. * if DC_GCL_ARCHIVED_ONLY is not set, only unarchived chats are returned and * the pseudo-chat DC_CHAT_ID_ARCHIVED_LINK is added if there are _any_ archived * chats * - if the flag DC_GCL_NO_SPECIALS is set, deaddrop and archive link are not added * to the list (may be used eg. for selecting chats on forwarding, the flag is * not needed when DC_GCL_ARCHIVED_ONLY is already set) * - if the flag DC_GCL_ADD_ALLDONE_HINT is set, DC_CHAT_ID_ALLDONE_HINT * is added as needed. * @param query_str An optional query for filtering the list. Only chats matching this query * are returned. Give NULL for no filtering. * @param query_id An optional contact ID for filtering the list. Only chats including this contact ID * are returned. Give 0 for no filtering. * @return A chatlist as an dc_chatlist_t object. * On errors, NULL is returned. * Must be freed using dc_chatlist_unref() when no longer used. * * See also: dc_get_chat_msgs() to get the messages of a single chat. */ dc_chatlist_t* dc_get_chatlist(dc_context_t* context, int listflags, const char* query_str, uint32_t query_id) { int success = 0; dc_chatlist_t* obj = dc_chatlist_new(context); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (!dc_chatlist_load_from_db(obj, listflags, query_str, query_id)) { goto cleanup; } success = 1; cleanup: if (success) { return obj; } else { dc_chatlist_unref(obj); return NULL; } } ``` Filename: dc_configure.c ```c #include #include #include "dc_context.h" #include "dc_loginparam.h" #include "dc_imap.h" #include "dc_smtp.h" #include "dc_saxparser.h" #include "dc_job.h" #include "dc_oauth2.h" /******************************************************************************* * Connect to configured account ******************************************************************************/ int dc_connect_to_configured_imap(dc_context_t* context, dc_imap_t* imap) { int ret_connected = DC_NOT_CONNECTED; dc_loginparam_t* param = dc_loginparam_new(); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || imap==NULL) { dc_log_warning(imap->context, 0, "Cannot connect to IMAP: Bad parameters."); goto cleanup; } if (dc_imap_is_connected(imap)) { ret_connected = DC_ALREADY_CONNECTED; goto cleanup; } if (dc_sqlite3_get_config_int(imap->context->sql, "configured", 0)==0) { dc_log_warning(imap->context, 0, "Not configured, cannot connect."); goto cleanup; } dc_loginparam_read(param, imap->context->sql, "configured_" /*the trailing underscore is correct*/); if (!dc_imap_connect(imap, param)) { goto cleanup; } ret_connected = DC_JUST_CONNECTED; cleanup: dc_loginparam_unref(param); return ret_connected; } /******************************************************************************* * Thunderbird's Autoconfigure ******************************************************************************/ /* documentation: https://developer.mozilla.org/en-US/docs/Mozilla/Thunderbird/Autoconfiguration */ typedef struct moz_autoconfigure_t { const dc_loginparam_t* in; char* in_emaildomain; char* in_emaillocalpart; dc_loginparam_t* out; int out_imap_set; int out_smtp_set; /* currently, we assume there is only one emailProvider tag in the file, see example at https://wiki.mozilla.org/Thunderbird:Autoconfiguration:ConfigFileFormat moreover, we assume, the returned domains match the one queried. I've not seen another example (bp). However, _if_ the assumptions are wrong, we can add a first saxparser-pass that searches for the correct domain and the second pass will look for the index found. */ #define MOZ_SERVER_IMAP 1 #define MOZ_SERVER_SMTP 2 int tag_server; #define MOZ_HOSTNAME 10 #define MOZ_PORT 11 #define MOZ_USERNAME 12 #define MOZ_SOCKETTYPE 13 int tag_config; } moz_autoconfigure_t; static char* read_autoconf_file(dc_context_t* context, const char* url) { char* filecontent = NULL; dc_log_info(context, 0, "Testing %s ...", url); filecontent = (char*)context->cb(context, DC_EVENT_HTTP_GET, (uintptr_t)url, 0); if (filecontent==NULL || filecontent[0]==0) { free(filecontent); dc_log_info(context, 0, "Can't read file."); /* this is not a warning or an error, we're just testing */ return NULL; } return filecontent; } static void moz_autoconfigure_starttag_cb(void* userdata, const char* tag, char** attr) { moz_autoconfigure_t* moz_ac = (moz_autoconfigure_t*)userdata; const char* p1 = NULL; if (strcmp(tag, "incomingserver")==0) { moz_ac->tag_server = (moz_ac->out_imap_set==0 && (p1=dc_attr_find(attr, "type"))!=NULL && strcasecmp(p1, "imap")==0)? MOZ_SERVER_IMAP : 0; moz_ac->tag_config = 0; } else if (strcmp(tag, "outgoingserver")==0) { moz_ac->tag_server = moz_ac->out_smtp_set==0? MOZ_SERVER_SMTP : 0; moz_ac->tag_config = 0; } else if (strcmp(tag, "hostname")==0) { moz_ac->tag_config = MOZ_HOSTNAME; } else if (strcmp(tag, "port")==0 ) { moz_ac->tag_config = MOZ_PORT; } else if (strcmp(tag, "sockettype")==0) { moz_ac->tag_config = MOZ_SOCKETTYPE; } else if (strcmp(tag, "username")==0) { moz_ac->tag_config = MOZ_USERNAME; } } static void moz_autoconfigure_text_cb(void* userdata, const char* text, int len) { moz_autoconfigure_t* moz_ac = (moz_autoconfigure_t*)userdata; char* val = dc_strdup(text); dc_trim(val); dc_str_replace(&val, "%EMAILADDRESS%", moz_ac->in->addr); dc_str_replace(&val, "%EMAILLOCALPART%", moz_ac->in_emaillocalpart); dc_str_replace(&val, "%EMAILDOMAIN%", moz_ac->in_emaildomain); if (moz_ac->tag_server==MOZ_SERVER_IMAP) { switch (moz_ac->tag_config) { case MOZ_HOSTNAME: free(moz_ac->out->mail_server); moz_ac->out->mail_server = val; val = NULL; break; case MOZ_PORT: moz_ac->out->mail_port = atoi(val); break; case MOZ_USERNAME: free(moz_ac->out->mail_user); moz_ac->out->mail_user = val; val = NULL; break; case MOZ_SOCKETTYPE: if (strcasecmp(val, "ssl")==0) { moz_ac->out->server_flags |=DC_LP_IMAP_SOCKET_SSL; } if (strcasecmp(val, "starttls")==0) { moz_ac->out->server_flags |=DC_LP_IMAP_SOCKET_STARTTLS; } if (strcasecmp(val, "plain")==0) { moz_ac->out->server_flags |=DC_LP_IMAP_SOCKET_PLAIN; } break; } } else if (moz_ac->tag_server==MOZ_SERVER_SMTP) { switch (moz_ac->tag_config) { case MOZ_HOSTNAME: free(moz_ac->out->send_server); moz_ac->out->send_server = val; val = NULL; break; case MOZ_PORT: moz_ac->out->send_port = atoi(val); break; case MOZ_USERNAME: free(moz_ac->out->send_user); moz_ac->out->send_user = val; val = NULL; break; case MOZ_SOCKETTYPE: if (strcasecmp(val, "ssl")==0) { moz_ac->out->server_flags |=DC_LP_SMTP_SOCKET_SSL; } if (strcasecmp(val, "starttls")==0) { moz_ac->out->server_flags |=DC_LP_SMTP_SOCKET_STARTTLS; } if (strcasecmp(val, "plain")==0) { moz_ac->out->server_flags |=DC_LP_SMTP_SOCKET_PLAIN; } break; } } free(val); } static void moz_autoconfigure_endtag_cb(void* userdata, const char* tag) { moz_autoconfigure_t* moz_ac = (moz_autoconfigure_t*)userdata; if (strcmp(tag, "incomingserver")==0) { moz_ac->tag_server = 0; moz_ac->tag_config = 0; moz_ac->out_imap_set = 1; } else if (strcmp(tag, "outgoingserver")==0) { moz_ac->tag_server = 0; moz_ac->tag_config = 0; moz_ac->out_smtp_set = 1; } else { moz_ac->tag_config = 0; } } static dc_loginparam_t* moz_autoconfigure(dc_context_t* context, const char* url, const dc_loginparam_t* param_in) { char* xml_raw = NULL; moz_autoconfigure_t moz_ac; memset(&moz_ac, 0, sizeof(moz_autoconfigure_t)); if ((xml_raw=read_autoconf_file(context, url))==NULL) { goto cleanup; } moz_ac.in = param_in; moz_ac.in_emaillocalpart = dc_strdup(param_in->addr); char* p = strchr(moz_ac.in_emaillocalpart, '@'); if (p==NULL) { goto cleanup; } *p = 0; moz_ac.in_emaildomain = dc_strdup(p+1); moz_ac.out = dc_loginparam_new(); dc_saxparser_t saxparser; dc_saxparser_init (&saxparser, &moz_ac); dc_saxparser_set_tag_handler (&saxparser, moz_autoconfigure_starttag_cb, moz_autoconfigure_endtag_cb); dc_saxparser_set_text_handler(&saxparser, moz_autoconfigure_text_cb); dc_saxparser_parse (&saxparser, xml_raw); if (moz_ac.out->mail_server==NULL || moz_ac.out->mail_port ==0 || moz_ac.out->send_server==NULL || moz_ac.out->send_port ==0) { { char* r = dc_loginparam_get_readable(moz_ac.out); dc_log_warning(context, 0, "Bad or incomplete autoconfig: %s", r); free(r); } dc_loginparam_unref(moz_ac.out); /* autoconfig failed for the given URL */ moz_ac.out = NULL; goto cleanup; } cleanup: free(xml_raw); free(moz_ac.in_emaildomain); free(moz_ac.in_emaillocalpart); return moz_ac.out; /* may be NULL */ } /******************************************************************************* * Outlook's Autodiscover ******************************************************************************/ typedef struct outlk_autodiscover_t { const dc_loginparam_t* in; dc_loginparam_t* out; int out_imap_set; int out_smtp_set; /* file format: https://msdn.microsoft.com/en-us/library/bb204278(v=exchg.80).aspx */ #define OUTLK_TYPE 1 #define OUTLK_SERVER 2 #define OUTLK_PORT 3 #define OUTLK_SSL 4 #define OUTLK_REDIRECTURL 5 #define _OUTLK_CNT_ 6 int tag_config; char* config[_OUTLK_CNT_]; char* redirect; } outlk_autodiscover_t; static void outlk_clean_config(outlk_autodiscover_t* outlk_ad) { int i; for (i = 0; i < _OUTLK_CNT_; i++) { free(outlk_ad->config[i]); outlk_ad->config[i] = NULL; } } static void outlk_autodiscover_starttag_cb(void* userdata, const char* tag, char** attr) { outlk_autodiscover_t* outlk_ad = (outlk_autodiscover_t*)userdata; if (strcmp(tag, "protocol")==0) { outlk_clean_config(outlk_ad); } /* this also cleans "redirecturl", however, this is not problem as the protocol block is only valid for action "settings". */ else if (strcmp(tag, "type")==0) { outlk_ad->tag_config = OUTLK_TYPE; } else if (strcmp(tag, "server")==0) { outlk_ad->tag_config = OUTLK_SERVER; } else if (strcmp(tag, "port")==0) { outlk_ad->tag_config = OUTLK_PORT; } else if (strcmp(tag, "ssl")==0) { outlk_ad->tag_config = OUTLK_SSL; } else if (strcmp(tag, "redirecturl")==0) { outlk_ad->tag_config = OUTLK_REDIRECTURL; } } static void outlk_autodiscover_text_cb(void* userdata, const char* text, int len) { outlk_autodiscover_t* outlk_ad = (outlk_autodiscover_t*)userdata; char* val = dc_strdup(text); dc_trim(val); free(outlk_ad->config[outlk_ad->tag_config]); outlk_ad->config[outlk_ad->tag_config] = val; } static void outlk_autodiscover_endtag_cb(void* userdata, const char* tag) { outlk_autodiscover_t* outlk_ad = (outlk_autodiscover_t*)userdata; if (strcmp(tag, "protocol")==0) { /* copy collected confituration to out (we have to delay this as we do not know when the tag appears in the sax-stream) */ if (outlk_ad->config[OUTLK_TYPE]) { int port = dc_atoi_null_is_0(outlk_ad->config[OUTLK_PORT]), ssl_on = (outlk_ad->config[OUTLK_SSL] && strcasecmp(outlk_ad->config[OUTLK_SSL], "on")==0), ssl_off = (outlk_ad->config[OUTLK_SSL] && strcasecmp(outlk_ad->config[OUTLK_SSL], "off")==0); if (strcasecmp(outlk_ad->config[OUTLK_TYPE], "imap")==0 && outlk_ad->out_imap_set==0) { outlk_ad->out->mail_server = dc_strdup_keep_null(outlk_ad->config[OUTLK_SERVER]); outlk_ad->out->mail_port = port; if (ssl_on) { outlk_ad->out->server_flags |= DC_LP_IMAP_SOCKET_SSL; } else if (ssl_off) { outlk_ad->out->server_flags |= DC_LP_IMAP_SOCKET_PLAIN; } outlk_ad->out_imap_set = 1; } else if (strcasecmp(outlk_ad->config[OUTLK_TYPE], "smtp")==0 && outlk_ad->out_smtp_set==0) { outlk_ad->out->send_server = dc_strdup_keep_null(outlk_ad->config[OUTLK_SERVER]); outlk_ad->out->send_port = port; if (ssl_on) { outlk_ad->out->server_flags |= DC_LP_SMTP_SOCKET_SSL; } else if (ssl_off) { outlk_ad->out->server_flags |= DC_LP_SMTP_SOCKET_PLAIN; } outlk_ad->out_smtp_set = 1; } } outlk_clean_config(outlk_ad); } outlk_ad->tag_config = 0; } static dc_loginparam_t* outlk_autodiscover(dc_context_t* context, const char* url__, const dc_loginparam_t* param_in) { char* xml_raw = NULL; char* url = dc_strdup(url__); outlk_autodiscover_t outlk_ad; int i; for (i = 0; i < 10 /* follow up to 10 xml-redirects (http-redirects are followed in read_autoconf_file() */; i++) { memset(&outlk_ad, 0, sizeof(outlk_autodiscover_t)); if ((xml_raw=read_autoconf_file(context, url))==NULL) { goto cleanup; } outlk_ad.in = param_in; outlk_ad.out = dc_loginparam_new(); dc_saxparser_t saxparser; dc_saxparser_init (&saxparser, &outlk_ad); dc_saxparser_set_tag_handler (&saxparser, outlk_autodiscover_starttag_cb, outlk_autodiscover_endtag_cb); dc_saxparser_set_text_handler(&saxparser, outlk_autodiscover_text_cb); dc_saxparser_parse (&saxparser, xml_raw); if (outlk_ad.config[OUTLK_REDIRECTURL] && outlk_ad.config[OUTLK_REDIRECTURL][0]) { free(url); url = dc_strdup(outlk_ad.config[OUTLK_REDIRECTURL]); dc_loginparam_unref(outlk_ad.out); outlk_clean_config(&outlk_ad); free(xml_raw); xml_raw = NULL; } else { break; } } if (outlk_ad.out->mail_server==NULL || outlk_ad.out->mail_port ==0 || outlk_ad.out->send_server==NULL || outlk_ad.out->send_port ==0) { { char* r = dc_loginparam_get_readable(outlk_ad.out); dc_log_warning(context, 0, "Bad or incomplete autoconfig: %s", r); free(r); } dc_loginparam_unref(outlk_ad.out); /* autoconfig failed for the given URL */ outlk_ad.out = NULL; goto cleanup; } cleanup: free(url); free(xml_raw); outlk_clean_config(&outlk_ad); return outlk_ad.out; /* may be NULL */ } /******************************************************************************* * Configure folders ******************************************************************************/ typedef struct dc_imapfolder_t { char* name_to_select; char* name_utf8; #define MEANING_UNKNOWN 0 #define MEANING_SENT_OBJECTS 1 #define MEANING_OTHER_KNOWN 2 int meaning; } dc_imapfolder_t; static int get_folder_meaning(struct mailimap_mbx_list_flags* flags) { int ret_meaning = MEANING_UNKNOWN; // We check for flags if we get some // (LIST may also return some, see https://tools.ietf.org/html/rfc6154 ) if (flags) { clistiter* iter2; for (iter2=clist_begin(flags->mbf_oflags); iter2!=NULL; iter2=clist_next(iter2)) { struct mailimap_mbx_list_oflag* oflag = (struct mailimap_mbx_list_oflag*)clist_content(iter2); switch (oflag->of_type) { case MAILIMAP_MBX_LIST_OFLAG_FLAG_EXT: if (strcasecmp(oflag->of_flag_ext, "spam")==0 || strcasecmp(oflag->of_flag_ext, "trash")==0 || strcasecmp(oflag->of_flag_ext, "drafts")==0 || strcasecmp(oflag->of_flag_ext, "junk")==0) { ret_meaning = MEANING_OTHER_KNOWN; } else if (strcasecmp(oflag->of_flag_ext, "sent")==0) { ret_meaning = MEANING_SENT_OBJECTS; } break; } } } return ret_meaning; } static int get_folder_meaning_by_name(const char* folder_name) { // try to get the folder meaning by the name of the folder. // only used if the server does not support XLIST. int ret_meaning = MEANING_UNKNOWN; // TODO: lots languages missing - maybe there is a list somewhere on other MUAs? // however, if we fail to find out the sent-folder, // only watching this folder is not working. at least, this is no show stopper. // CAVE: if possible, take care not to add a name here that is "sent" in one language // but sth. different in others - a hard job. static const char* sent_names = ",sent,sent objects,gesendet,"; char* lower = dc_mprintf(",%s,", folder_name); dc_strlower_in_place(lower); if (strstr(sent_names, lower)!=NULL) { ret_meaning = MEANING_SENT_OBJECTS; } free(lower); return ret_meaning; } static clist* list_folders(dc_imap_t* imap) { clist* imap_list = NULL; clistiter* iter1 = NULL; clist * ret_list = clist_new(); int r = 0; int xlist_works = 0; if (imap==NULL || imap->etpan==NULL) { goto cleanup; } // the "*" also returns all subdirectories; // so the resulting foldernames may contain // foldernames with delimiters as "folder/subdir/subsubdir" // // when switching to XLIST: at least my server claims // that it support XLIST but does not return folder flags. // so, if we did not get a _single_ flag, sth. seems not to work. if (imap->has_xlist) { r = mailimap_xlist(imap->etpan, "", "*", &imap_list); } else { r = mailimap_list(imap->etpan, "", "*", &imap_list); } if (dc_imap_is_error(imap, r) || imap_list==NULL) { imap_list = NULL; dc_log_warning(imap->context, 0, "Cannot get folder list."); goto cleanup; } if (clist_count(imap_list)<=0) { dc_log_warning(imap->context, 0, "Folder list is empty."); goto cleanup; } // default IMAP delimiter if none is returned by the list command imap->imap_delimiter = '.'; for (iter1 = clist_begin(imap_list); iter1!=NULL ; iter1 = clist_next(iter1)) { struct mailimap_mailbox_list* imap_folder = (struct mailimap_mailbox_list*)clist_content(iter1); if (imap_folder->mb_delimiter) { imap->imap_delimiter = imap_folder->mb_delimiter; } dc_imapfolder_t* ret_folder = calloc(1, sizeof(dc_imapfolder_t)); if (strcasecmp(imap_folder->mb_name, "INBOX")==0) { // Force upper case INBOX. Servers may return any case, however, // all variants MUST lead to the same INBOX, see RFC 3501 5.1 ret_folder->name_to_select = dc_strdup("INBOX"); } else { ret_folder->name_to_select = dc_strdup(imap_folder->mb_name); } ret_folder->name_utf8 = dc_decode_modified_utf7(imap_folder->mb_name, 0); ret_folder->meaning = get_folder_meaning(imap_folder->mb_flag); if (ret_folder->meaning==MEANING_OTHER_KNOWN || ret_folder->meaning==MEANING_SENT_OBJECTS /*INBOX is no hint for a working XLIST*/) { xlist_works = 1; } clist_append(ret_list, (void*)ret_folder); } // at least my own server claims that it support XLIST // but does not return folder flags. if (!xlist_works) { for (iter1 = clist_begin(ret_list); iter1!=NULL ; iter1 = clist_next(iter1)) { dc_imapfolder_t* ret_folder = (struct dc_imapfolder_t*)clist_content(iter1); ret_folder->meaning = get_folder_meaning_by_name(ret_folder->name_utf8); } } cleanup: if (imap_list) { mailimap_list_result_free(imap_list); } return ret_list; } static void free_folders(clist* folders) { if (folders) { clistiter* iter1; for (iter1 = clist_begin(folders); iter1!=NULL ; iter1 = clist_next(iter1)) { dc_imapfolder_t* ret_folder = (struct dc_imapfolder_t*)clist_content(iter1); free(ret_folder->name_to_select); free(ret_folder->name_utf8); free(ret_folder); } clist_free(folders); } } void dc_configure_folders(dc_context_t* context, dc_imap_t* imap, int flags) { #define DC_DEF_MVBOX "DeltaChat" clist* folder_list = NULL; clistiter* iter; char* mvbox_folder = NULL; char* sentbox_folder = NULL; char* fallback_folder = NULL; if (imap==NULL || imap->etpan==NULL) { goto cleanup; } dc_log_info(context, 0, "Configuring IMAP-folders."); // this sets imap->imap_delimiter as side-effect folder_list = list_folders(imap); // MVBOX-folder exists? maybe under INBOX? fallback_folder = dc_mprintf("INBOX%c%s", imap->imap_delimiter, DC_DEF_MVBOX); for (iter=clist_begin(folder_list); iter!=NULL; iter=clist_next(iter)) { dc_imapfolder_t* folder = (struct dc_imapfolder_t*)clist_content(iter); if (strcmp(folder->name_utf8, DC_DEF_MVBOX)==0 || strcmp(folder->name_utf8, fallback_folder)==0) { if (mvbox_folder==NULL) { mvbox_folder = dc_strdup(folder->name_to_select); } } if (folder->meaning==MEANING_SENT_OBJECTS) { if(sentbox_folder==NULL) { sentbox_folder = dc_strdup(folder->name_to_select); } } } // create folder if not exist if (mvbox_folder==NULL && (flags&DC_CREATE_MVBOX)) { dc_log_info(context, 0, "Creating MVBOX-folder \"%s\"...", DC_DEF_MVBOX); int r = mailimap_create(imap->etpan, DC_DEF_MVBOX); if (dc_imap_is_error(imap, r)) { dc_log_warning(context, 0, "Cannot create MVBOX-folder, using trying INBOX subfolder."); r = mailimap_create(imap->etpan, fallback_folder); if (dc_imap_is_error(imap, r)) { /* continue on errors, we'll just use a different folder then */ dc_log_warning(context, 0, "Cannot create MVBOX-folder."); } else { mvbox_folder = dc_strdup(fallback_folder); dc_log_info(context, 0, "MVBOX-folder created as INBOX subfolder."); } } else { mvbox_folder = dc_strdup(DC_DEF_MVBOX); dc_log_info(context, 0, "MVBOX-folder created."); } // SUBSCRIBE is needed to make the folder visible to the LSUB command // that may be used by other MUAs to list folders. // for the LIST command, the folder is always visible. mailimap_subscribe(imap->etpan, mvbox_folder); } // remember the configuration, mvbox_folder may be NULL dc_sqlite3_set_config_int(context->sql, "folders_configured", DC_FOLDERS_CONFIGURED_VERSION); dc_sqlite3_set_config(context->sql, "configured_mvbox_folder", mvbox_folder); dc_sqlite3_set_config(context->sql, "configured_sentbox_folder", sentbox_folder); cleanup: free_folders(folder_list); free(mvbox_folder); free(fallback_folder); } /******************************************************************************* * Configure ******************************************************************************/ void dc_job_do_DC_JOB_CONFIGURE_IMAP(dc_context_t* context, dc_job_t* job) { int success = 0; int imap_connected_here = 0; int smtp_connected_here = 0; int ongoing_allocated_here = 0; char* mvbox_folder = NULL; dc_loginparam_t* param = NULL; char* param_domain = NULL; /* just a pointer inside param, must not be freed! */ char* param_addr_urlencoded = NULL; dc_loginparam_t* param_autoconfig = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (!dc_alloc_ongoing(context)) { goto cleanup; } ongoing_allocated_here = 1; #define PROGRESS(p) \ if (context->shall_stop_ongoing) { goto cleanup; } \ context->cb(context, DC_EVENT_CONFIGURE_PROGRESS, (p)<1? 1 : ((p)>999? 999 : (p)), 0); if (!dc_sqlite3_is_open(context->sql)) { dc_log_error(context, 0, "Cannot configure, database not opened."); goto cleanup; } dc_imap_disconnect(context->inbox); dc_imap_disconnect(context->sentbox_thread.imap); dc_imap_disconnect(context->mvbox_thread.imap); dc_smtp_disconnect(context->smtp); //dc_sqlite3_set_config_int(context->sql, "configured", 0); -- NO: we do _not_ reset this flag if it was set once; otherwise the user won't get back to his chats (as an alternative, we could change the UI). Moreover, and not changeable in the UI, we use this flag to check if we shall search for backups. context->smtp->log_connect_errors = 1; context->inbox->log_connect_errors = 1; context->sentbox_thread.imap->log_connect_errors = 1; context->mvbox_thread.imap->log_connect_errors = 1; dc_log_info(context, 0, "Configure ..."); PROGRESS(0) /* 1. Load the parameters and check email-address and password **************************************************************************/ param = dc_loginparam_new(); dc_loginparam_read(param, context->sql, ""); if (param->addr==NULL) { dc_log_error(context, 0, "Please enter the email address."); goto cleanup; } dc_trim(param->addr); if (param->server_flags & DC_LP_AUTH_OAUTH2) { // the used oauth2 addr may differ, check this. // if dc_get_oauth2_addr() is not available in the oauth2 implementation, // just use the given one. PROGRESS(10) char* oauth2_addr = dc_get_oauth2_addr(context, param->addr, param->mail_pw); if (oauth2_addr) { free(param->addr); param->addr = oauth2_addr; dc_sqlite3_set_config(context->sql, "addr", param->addr); } PROGRESS(20) } param_domain = strchr(param->addr, '@'); if (param_domain==NULL || param_domain[0]==0) { dc_log_error(context, 0, "Bad email-address."); goto cleanup; } param_domain++; param_addr_urlencoded = dc_urlencode(param->addr); /* if no password is given, assume an empty password. (in general, unset values are NULL, not the empty string, this allows to use eg. empty user names or empty passwords) */ if (param->mail_pw==NULL) { param->mail_pw = dc_strdup(NULL); } PROGRESS(200) /* 2. Autoconfig **************************************************************************/ if (param->mail_server ==NULL && param->mail_port ==0 /*&¶m->mail_user ==NULL -- the user can enter a loginname which is used by autoconfig then */ && param->send_server ==NULL && param->send_port ==0 && param->send_user ==NULL /*&¶m->send_pw ==NULL -- the password cannot be auto-configured and is no criterion for autoconfig or not */ && (param->server_flags & (~DC_LP_AUTH_OAUTH2))==0 /* flags but OAuth2 avoid autoconfig */ ) { int keep_flags = param->server_flags & DC_LP_AUTH_OAUTH2; /* A. Search configurations from the domain used in the email-address, prefer encrypted */ if (param_autoconfig==NULL) { char* url = dc_mprintf("https://autoconfig.%s/mail/config-v1.1.xml?emailaddress=%s", param_domain, param_addr_urlencoded); param_autoconfig = moz_autoconfigure(context, url, param); free(url); PROGRESS(300) } if (param_autoconfig==NULL) { char* url = dc_mprintf("https://%s/.well-known/autoconfig/mail/config-v1.1.xml?emailaddress=%s", param_domain, param_addr_urlencoded); // the doc does not mention `emailaddress=`, however, Thunderbird adds it, see https://releases.mozilla.org/pub/thunderbird/ , which makes some sense param_autoconfig = moz_autoconfigure(context, url, param); free(url); PROGRESS(310) } for (int i = 0; i <= 1; i++) { if (param_autoconfig==NULL) { char* url = dc_mprintf("https://%s%s/autodiscover/autodiscover.xml", i==0?"":"autodiscover.", param_domain); /* Outlook uses always SSL but different domains */ param_autoconfig = outlk_autodiscover(context, url, param); free(url); PROGRESS(320+i*10) } } if (param_autoconfig==NULL) { char* url = dc_mprintf("http://autoconfig.%s/mail/config-v1.1.xml?emailaddress=%s", param_domain, param_addr_urlencoded); param_autoconfig = moz_autoconfigure(context, url, param); free(url); PROGRESS(340) } if (param_autoconfig==NULL) { char* url = dc_mprintf("http://%s/.well-known/autoconfig/mail/config-v1.1.xml", param_domain); // do not transfer the email-address unencrypted param_autoconfig = moz_autoconfigure(context, url, param); free(url); PROGRESS(350) } /* B. If we have no configuration yet, search configuration in Thunderbird's centeral database */ if (param_autoconfig==NULL) { char* url = dc_mprintf("https://autoconfig.thunderbird.net/v1.1/%s", param_domain); /* always SSL for Thunderbird's database */ param_autoconfig = moz_autoconfigure(context, url, param); free(url); PROGRESS(500) } /* C. Do we have any result? */ if (param_autoconfig) { { char* r = dc_loginparam_get_readable(param_autoconfig); dc_log_info(context, 0, "Got autoconfig: %s", r); free(r); } if (param_autoconfig->mail_user) { free(param->mail_user); param->mail_user= dc_strdup_keep_null(param_autoconfig->mail_user); } param->mail_server = dc_strdup_keep_null(param_autoconfig->mail_server); /* all other values are always NULL when entering autoconfig */ param->mail_port = param_autoconfig->mail_port; param->send_server = dc_strdup_keep_null(param_autoconfig->send_server); param->send_port = param_autoconfig->send_port; param->send_user = dc_strdup_keep_null(param_autoconfig->send_user); param->server_flags = param_autoconfig->server_flags; /* althoug param_autoconfig's data are no longer needed from, it is important to keep the object as we may enter "deep guessing" if we could not read a configuration */ } param->server_flags |= keep_flags; } /* 2. Fill missing fields with defaults **************************************************************************/ #define TYPICAL_IMAP_SSL_PORT 993 /* our default */ #define TYPICAL_IMAP_STARTTLS_PORT 143 /* not used very often but eg. by posteo.de, default for PLAIN */ #define TYPICAL_SMTP_SSL_PORT 465 /* our default */ #define TYPICAL_SMTP_STARTTLS_PORT 587 /* also used very often, SSL:STARTTLS is maybe 50:50 */ #define TYPICAL_SMTP_PLAIN_PORT 25 if (param->mail_server==NULL) { param->mail_server = dc_mprintf("imap.%s", param_domain); } if (param->mail_port==0) { param->mail_port = (param->server_flags&(DC_LP_IMAP_SOCKET_STARTTLS|DC_LP_IMAP_SOCKET_PLAIN))? TYPICAL_IMAP_STARTTLS_PORT : TYPICAL_IMAP_SSL_PORT; } if (param->mail_user==NULL) { param->mail_user = dc_strdup(param->addr); } if (param->send_server==NULL && param->mail_server) { param->send_server = dc_strdup(param->mail_server); if (strncmp(param->send_server, "imap.", 5)==0) { memcpy(param->send_server, "smtp", 4); } } if (param->send_port==0) { param->send_port = (param->server_flags&DC_LP_SMTP_SOCKET_STARTTLS)? TYPICAL_SMTP_STARTTLS_PORT : ((param->server_flags&DC_LP_SMTP_SOCKET_PLAIN)? TYPICAL_SMTP_PLAIN_PORT : TYPICAL_SMTP_SSL_PORT); } if (param->send_user==NULL && param->mail_user) { param->send_user = dc_strdup(param->mail_user); } if (param->send_pw==NULL && param->mail_pw) { param->send_pw = dc_strdup(param->mail_pw); } if (!dc_exactly_one_bit_set(param->server_flags&DC_LP_AUTH_FLAGS)) { param->server_flags &= ~DC_LP_AUTH_FLAGS; param->server_flags |= DC_LP_AUTH_NORMAL; } if (!dc_exactly_one_bit_set(param->server_flags&DC_LP_IMAP_SOCKET_FLAGS)) { param->server_flags &= ~DC_LP_IMAP_SOCKET_FLAGS; param->server_flags |= (param->send_port==TYPICAL_IMAP_STARTTLS_PORT? DC_LP_IMAP_SOCKET_STARTTLS : DC_LP_IMAP_SOCKET_SSL); } if (!dc_exactly_one_bit_set(param->server_flags&DC_LP_SMTP_SOCKET_FLAGS)) { param->server_flags &= ~DC_LP_SMTP_SOCKET_FLAGS; param->server_flags |= ( param->send_port==TYPICAL_SMTP_STARTTLS_PORT? DC_LP_SMTP_SOCKET_STARTTLS : (param->send_port==TYPICAL_SMTP_PLAIN_PORT? DC_LP_SMTP_SOCKET_PLAIN: DC_LP_SMTP_SOCKET_SSL)); } /* do we have a complete configuration? */ if (param->addr ==NULL || param->mail_server ==NULL || param->mail_port ==0 || param->mail_user ==NULL || param->mail_pw ==NULL || param->send_server ==NULL || param->send_port ==0 || param->send_user ==NULL || param->send_pw ==NULL || param->server_flags==0) { dc_log_error(context, 0, "Account settings incomplete."); goto cleanup; } PROGRESS(600) /* try to connect to IMAP - if we did not got an autoconfig, do some further tries with different settings and username variations */ for (int username_variation=0; username_variation<=1; username_variation++) { // probe given settings, SSL/993 by default { char* r = dc_loginparam_get_readable(param); dc_log_info(context, 0, "Trying: %s", r); free(r); } if (dc_imap_connect(context->inbox, param)) { break; } if (param_autoconfig) { goto cleanup; } // probe STARTTLS/993 PROGRESS(650+username_variation*30) param->server_flags &= ~DC_LP_IMAP_SOCKET_FLAGS; param->server_flags |= DC_LP_IMAP_SOCKET_STARTTLS; { char* r = dc_loginparam_get_readable(param); dc_log_info(context, 0, "Trying: %s", r); free(r); } if (dc_imap_connect(context->inbox, param)) { break; } // probe STARTTLS/143 PROGRESS(660+username_variation*30) param->mail_port = TYPICAL_IMAP_STARTTLS_PORT; { char* r = dc_loginparam_get_readable(param); dc_log_info(context, 0, "Trying: %s", r); free(r); } if (dc_imap_connect(context->inbox, param)) { break; } else if (username_variation) { goto cleanup; } // next probe round with only the localpart of the email-address as the loginname PROGRESS(670+username_variation*30) param->server_flags &= ~DC_LP_IMAP_SOCKET_FLAGS; param->server_flags |= DC_LP_IMAP_SOCKET_SSL; param->mail_port = TYPICAL_IMAP_SSL_PORT; char* at = strchr(param->mail_user, '@'); if (at) { *at = 0; } at = strchr(param->send_user, '@'); if (at) { *at = 0; } } imap_connected_here = 1; PROGRESS(800) /* try to connect to SMTP - if we did not got an autoconfig, the first try was SSL-465 and we do a second try with STARTTLS-587 */ if (!dc_smtp_connect(context->smtp, param)) { if (param_autoconfig) { goto cleanup; } PROGRESS(850) param->server_flags &= ~DC_LP_SMTP_SOCKET_FLAGS; param->server_flags |= DC_LP_SMTP_SOCKET_STARTTLS; param->send_port = TYPICAL_SMTP_STARTTLS_PORT; { char* r = dc_loginparam_get_readable(param); dc_log_info(context, 0, "Trying: %s", r); free(r); } if (!dc_smtp_connect(context->smtp, param)) { PROGRESS(860) param->server_flags &= ~DC_LP_SMTP_SOCKET_FLAGS; param->server_flags |= DC_LP_SMTP_SOCKET_STARTTLS; param->send_port = TYPICAL_SMTP_PLAIN_PORT; { char* r = dc_loginparam_get_readable(param); dc_log_info(context, 0, "Trying: %s", r); free(r); } if (!dc_smtp_connect(context->smtp, param)) { goto cleanup; } } } smtp_connected_here = 1; PROGRESS(900) int flags = ( dc_sqlite3_get_config_int(context->sql, "mvbox_watch", DC_MVBOX_WATCH_DEFAULT) || dc_sqlite3_get_config_int(context->sql, "mvbox_move", DC_MVBOX_MOVE_DEFAULT) ) ? DC_CREATE_MVBOX : 0; dc_configure_folders(context, context->inbox, flags); PROGRESS(910); /* configuration success - write back the configured parameters with the "configured_" prefix; also write the "configured"-flag */ dc_loginparam_write(param, context->sql, "configured_" /*the trailing underscore is correct*/); dc_sqlite3_set_config_int(context->sql, "configured", 1); PROGRESS(920) // we generate the keypair just now - we could also postpone this until the first message is sent, however, // this may result in a unexpected and annoying delay when the user sends his very first message // (~30 seconds on a Moto G4 play) and might looks as if message sending is always that slow. dc_ensure_secret_key_exists(context); success = 1; dc_log_info(context, 0, "Configure completed."); PROGRESS(940) cleanup: if (imap_connected_here) { dc_imap_disconnect(context->inbox); } if (smtp_connected_here) { dc_smtp_disconnect(context->smtp); } dc_loginparam_unref(param); dc_loginparam_unref(param_autoconfig); free(param_addr_urlencoded); if (ongoing_allocated_here) { dc_free_ongoing(context); } free(mvbox_folder); context->cb(context, DC_EVENT_CONFIGURE_PROGRESS, success? 1000 : 0, 0); } /** * Configure a context. * For this purpose, the function creates a job * that is executed in the IMAP-thread then; * this requires to call dc_perform_imap_jobs() regularly. * If the context is already configured, * this function will try to change the configuration. * * - Before you call this function, * you must set at least `addr` and `mail_pw` using dc_set_config(). * * - Use `mail_user` to use a different user name than `addr` * and `send_pw` to use a different password for the SMTP server. * * - If _no_ more options are specified, * the function **uses autoconfigure/autodiscover** * to get the full configuration from well-known URLs. * * - If _more_ options as `mail_server`, `mail_port`, `send_server`, * `send_port`, `send_user` or `server_flags` are specified, * **autoconfigure/autodiscover is skipped**. * * While dc_configure() returns immediately, * the started configuration-job may take a while. * * During configuration, #DC_EVENT_CONFIGURE_PROGRESS events are emmited; * they indicate a successful configuration as well as errors * and may be used to create a progress bar. * * Additional calls to dc_configure() while a config-job is running are ignored. * To interrupt a configuration prematurely, use dc_stop_ongoing_process(); * this is not needed if #DC_EVENT_CONFIGURE_PROGRESS reports success. * * On a successfull configuration, * the core makes a copy of the parameters mentioned above: * the original parameters as are never modified by the core. * * UI-implementors should keep this in mind - * eg. if the UI wants to prefill a configure-edit-dialog with these parameters, * the UI should reset them if the user cancels the dialog * after a configure-attempts has failed. * Otherwise the parameters may not reflect the current configuation. * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). * @return None. * * There is no need to call dc_configure() on every program start, * the configuration result is saved in the database * and you can use the connection directly: * * ~~~ * if (!dc_is_configured(context)) { * dc_configure(context); * // wait for progress events * } * ~~~ */ void dc_configure(dc_context_t* context) { if (dc_has_ongoing(context)) { dc_log_warning(context, 0, "There is already another ongoing process running."); return; } dc_job_kill_action(context, DC_JOB_CONFIGURE_IMAP); dc_job_add(context, DC_JOB_CONFIGURE_IMAP, 0, NULL, 0); // results in a call to dc_configure_job() } /** * Check if the context is already configured. * * Typically, for unconfigured accounts, the user is prompted * to enter some settings and dc_configure() is called in a thread then. * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). * @return 1=context is configured and can be used; * 0=context is not configured and a configuration by dc_configure() is required. */ int dc_is_configured(const dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return 0; } return dc_sqlite3_get_config_int(context->sql, "configured", 0)? 1 : 0; } /* * Check if there is an ongoing process. */ int dc_has_ongoing(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return 0; } return (context->ongoing_running || context->shall_stop_ongoing==0)? 1 : 0; } /* * Request an ongoing process to start. * Returns 0=process started, 1=not started, there is running another process */ int dc_alloc_ongoing(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return 0; } if (dc_has_ongoing(context)) { dc_log_warning(context, 0, "There is already another ongoing process running."); return 0; } context->ongoing_running = 1; context->shall_stop_ongoing = 0; return 1; } /* * Frees the process allocated with dc_alloc_ongoing() - independingly of dc_shall_stop_ongoing. * If dc_alloc_ongoing() fails, this function MUST NOT be called. */ void dc_free_ongoing(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } context->ongoing_running = 0; context->shall_stop_ongoing = 1; /* avoids dc_stop_ongoing_process() to stop the thread */ } /** * Signal an ongoing process to stop. * * After that, dc_stop_ongoing_process() returns _without_ waiting * for the ongoing process to return. * * The ongoing process will return ASAP then, however, it may * still take a moment. If in doubt, the caller may also decide to kill the * thread after a few seconds; eg. the process may hang in a * function not under the control of the core (eg. #DC_EVENT_HTTP_GET). Another * reason for dc_stop_ongoing_process() not to wait is that otherwise it * would be GUI-blocking and should be started in another thread then; this * would make things even more complicated. * * Typical ongoing processes are started by dc_configure(), * dc_initiate_key_transfer() or dc_imex(). As there is always at most only * one onging process at the same time, there is no need to define _which_ process to exit. * * @memberof dc_context_t * @param context The context object. * @return None. */ void dc_stop_ongoing_process(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } if (context->ongoing_running && context->shall_stop_ongoing==0) { dc_log_info(context, 0, "Signaling the ongoing process to stop ASAP."); context->shall_stop_ongoing = 1; } else { dc_log_info(context, 0, "No ongoing process to stop."); } } ``` Filename: dc_context.c ```c #include #include #include #include #include #include #include "dc_context.h" #include "dc_imap.h" #include "dc_smtp.h" #include "dc_openssl.h" #include "dc_mimefactory.h" #include "dc_tools.h" #include "dc_job.h" #include "dc_key.h" #include "dc_pgp.h" #include "dc_apeerstate.h" static const char* config_keys[] = { "addr" ,"mail_server" ,"mail_user" ,"mail_pw" ,"mail_port" ,"send_server" ,"send_user" ,"send_pw" ,"send_port" ,"server_flags" ,"imap_folder" // deprecated ,"displayname" ,"selfstatus" ,"selfavatar" ,"e2ee_enabled" ,"mdns_enabled" ,"inbox_watch" ,"sentbox_watch" ,"mvbox_watch" ,"mvbox_move" ,"show_emails" ,"save_mime_headers" ,"configured_addr" ,"configured_mail_server" ,"configured_mail_user" ,"configured_mail_pw" ,"configured_mail_port" ,"configured_send_server" ,"configured_send_user" ,"configured_send_pw" ,"configured_send_port" ,"configured_server_flags" ,"configured" }; static const char* sys_config_keys[] = { "sys.version" ,"sys.msgsize_max_recommended" ,"sys.config_keys" }; #define str_array_len(a) (sizeof(a)/sizeof(char*)) /** * A callback function that is used if no user-defined callback is given to dc_context_new(). * The callback function simply returns 0 which is safe for every event. * * @private @memberof dc_context_t */ static uintptr_t cb_dummy(dc_context_t* context, int event, uintptr_t data1, uintptr_t data2) { return 0; } /** * The following three callback are given to dc_imap_new() to read/write configuration * and to handle received messages. As the imap-functions are typically used in * a separate user-thread, also these functions may be called from a different thread. * * @private @memberof dc_context_t */ static char* cb_get_config(dc_imap_t* imap, const char* key, const char* def) { dc_context_t* context = (dc_context_t*)imap->userData; return dc_sqlite3_get_config(context->sql, key, def); } static void cb_set_config(dc_imap_t* imap, const char* key, const char* value) { dc_context_t* context = (dc_context_t*)imap->userData; dc_sqlite3_set_config(context->sql, key, value); } static int cb_precheck_imf(dc_imap_t* imap, const char* rfc724_mid, const char* server_folder, uint32_t server_uid) { int rfc724_mid_exists = 0; uint32_t msg_id = 0; char* old_server_folder = NULL; uint32_t old_server_uid = 0; int mark_seen = 0; msg_id = dc_rfc724_mid_exists(imap->context, rfc724_mid, &old_server_folder, &old_server_uid); if (msg_id!=0) { rfc724_mid_exists = 1; if (old_server_folder[0]==0 && old_server_uid==0) { dc_log_info(imap->context, 0, "[move] detected bbc-self %s", rfc724_mid); mark_seen = 1; } else if (strcmp(old_server_folder, server_folder)!=0) { dc_log_info(imap->context, 0, "[move] detected moved message %s", rfc724_mid); dc_update_msg_move_state(imap->context, rfc724_mid, DC_MOVE_STATE_STAY); } if (strcmp(old_server_folder, server_folder)!=0 || old_server_uid!=server_uid) { dc_update_server_uid(imap->context, rfc724_mid, server_folder, server_uid); } dc_do_heuristics_moves(imap->context, server_folder, msg_id); if (mark_seen) { dc_job_add(imap->context, DC_JOB_MARKSEEN_MSG_ON_IMAP, msg_id, NULL, 0); } } // TODO: also optimize for already processed report/mdn Message-IDs. // this happens regulary as eg. mdns are typically read from the INBOX, // moved to MVBOX and popping up from there. // when modifying tables for this purpose, maybe also target #112 (mdn cleanup) free(old_server_folder); return rfc724_mid_exists; } static void cb_receive_imf(dc_imap_t* imap, const char* imf_raw_not_terminated, size_t imf_raw_bytes, const char* server_folder, uint32_t server_uid, uint32_t flags) { dc_context_t* context = (dc_context_t*)imap->userData; dc_receive_imf(context, imf_raw_not_terminated, imf_raw_bytes, server_folder, server_uid, flags); } /** * Create a new context object. After creation it is usually * opened, connected and mails are fetched. * * @memberof dc_context_t * @param cb a callback function that is called for events (update, * state changes etc.) and to get some information from the client (eg. translation * for a given string). * See @ref DC_EVENT for a list of possible events that may be passed to the callback. * - The callback MAY be called from _any_ thread, not only the main/GUI thread! * - The callback MUST NOT call any dc_* and related functions unless stated * otherwise! * - The callback SHOULD return _fast_, for GUI updates etc. you should * post yourself an asynchronous message to your GUI thread, if needed. * - If not mentioned otherweise, the callback should return 0. * @param userdata can be used by the client for any purpuse. He finds it * later in dc_get_userdata(). * @param os_name is only for decorative use * and is shown eg. in the `X-Mailer:` header * in the form "Delta Chat Core /". * You can give the name of the app, the operating system, * the used environment and/or the version here. * It is okay to give NULL, in this case `X-Mailer:` header * is set to "Delta Chat Core ". * @return A context object with some public members. * The object must be passed to the other context functions * and must be freed using dc_context_unref() after usage. */ dc_context_t* dc_context_new(dc_callback_t cb, void* userdata, const char* os_name) { dc_context_t* context = NULL; if ((context=calloc(1, sizeof(dc_context_t)))==NULL) { exit(23); /* cannot allocate little memory, unrecoverable error */ } pthread_mutex_init(&context->smear_critical, NULL); pthread_mutex_init(&context->bobs_qr_critical, NULL); pthread_mutex_init(&context->inboxidle_condmutex, NULL); dc_jobthread_init(&context->sentbox_thread, context, "SENTBOX", "configured_sentbox_folder"); dc_jobthread_init(&context->mvbox_thread, context, "MVBOX", "configured_mvbox_folder"); pthread_mutex_init(&context->smtpidle_condmutex, NULL); pthread_cond_init(&context->smtpidle_cond, NULL); pthread_mutex_init(&context->oauth2_critical, NULL); context->magic = DC_CONTEXT_MAGIC; context->userdata = userdata; context->cb = cb? cb : cb_dummy; context->os_name = dc_strdup_keep_null(os_name); context->shall_stop_ongoing = 1; /* the value 1 avoids dc_stop_ongoing_process() from stopping already stopped threads */ dc_openssl_init(); // OpenSSL is used by libEtPan and by netpgp, init before using these parts. dc_pgp_init(); context->sql = dc_sqlite3_new(context); dc_job_kill_action(context, DC_JOB_EMPTY_SERVER); context->inbox = dc_imap_new(cb_get_config, cb_set_config, cb_precheck_imf, cb_receive_imf, (void*)context, context); context->sentbox_thread.imap = dc_imap_new(cb_get_config, cb_set_config, cb_precheck_imf, cb_receive_imf, (void*)context, context); context->mvbox_thread.imap = dc_imap_new(cb_get_config, cb_set_config, cb_precheck_imf, cb_receive_imf, (void*)context, context); context->smtp = dc_smtp_new(context); /* Random-seed. An additional seed with more random data is done just before key generation (the timespan between this call and the key generation time is typically random. Moreover, later, we add a hash of the first message data to the random-seed (it would be okay to seed with even more sensible data, the seed values cannot be recovered from the PRNG output, see OpenSSL's RAND_seed()) */ uintptr_t seed[5]; seed[0] = (uintptr_t)time(NULL); /* time */ seed[1] = (uintptr_t)seed; /* stack */ seed[2] = (uintptr_t)context; /* heap */ seed[3] = (uintptr_t)pthread_self(); /* thread ID */ seed[4] = (uintptr_t)getpid(); /* process ID */ dc_pgp_rand_seed(context, seed, sizeof(seed)); return context; } /** * Free a context object. * If app runs can only be terminated by a forced kill, this may be superfluous. * Before the context object is freed, connections to SMTP, IMAP and database * are closed. You can also do this explicitly by calling dc_close() on your own * before calling dc_context_unref(). * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). * If NULL is given, nothing is done. * @return None. */ void dc_context_unref(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } dc_pgp_exit(); if (dc_is_open(context)) { dc_close(context); } dc_imap_unref(context->inbox); dc_imap_unref(context->sentbox_thread.imap); dc_imap_unref(context->mvbox_thread.imap); dc_smtp_unref(context->smtp); dc_sqlite3_unref(context->sql); dc_openssl_exit(); pthread_mutex_destroy(&context->smear_critical); pthread_mutex_destroy(&context->bobs_qr_critical); pthread_mutex_destroy(&context->inboxidle_condmutex); dc_jobthread_exit(&context->sentbox_thread); dc_jobthread_exit(&context->mvbox_thread); pthread_cond_destroy(&context->smtpidle_cond); pthread_mutex_destroy(&context->smtpidle_condmutex); pthread_mutex_destroy(&context->oauth2_critical); free(context->os_name); context->magic = 0; free(context); } /** * Get user data associated with a context object. * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). * @return User data, this is the second parameter given to dc_context_new(). */ void* dc_get_userdata(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return NULL; } return context->userdata; } /** * Open context database. If the given file does not exist, it is * created and can be set up using dc_set_config() afterwards. * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). * @param dbfile The file to use to store the database, something like `~/file` won't * work on all systems, if in doubt, use absolute paths. * @param blobdir A directory to store the blobs in; a trailing slash is not needed. * If you pass NULL or the empty string, deltachat-core creates a directory * beside _dbfile_ with the same name and the suffix `-blobs`. * @return 1 on success, 0 on failure * eg. if the file is not writable * or if there is already a database opened for the context. */ int dc_open(dc_context_t* context, const char* dbfile, const char* blobdir) { int success = 0; if (dc_is_open(context)) { return 0; // a cleanup would close the database } if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || dbfile==NULL) { goto cleanup; } context->dbfile = dc_strdup(dbfile); /* set blob-directory (to avoid double slashes, the given directory should not end with an slash) */ if (blobdir && blobdir[0]) { context->blobdir = dc_strdup(blobdir); dc_ensure_no_slash(context->blobdir); } else { context->blobdir = dc_mprintf("%s-blobs", dbfile); dc_create_folder(context, context->blobdir); } /* Create/open sqlite database, this may already use the blobdir */ if (!dc_sqlite3_open(context->sql, dbfile, 0)) { goto cleanup; } success = 1; cleanup: if (!success) { dc_close(context); } return success; } /** * Close context database opened by dc_open(). * Before this, connections to SMTP and IMAP are closed; these connections * are started automatically as needed eg. by sending for fetching messages. * This function is also implicitly called by dc_context_unref(). * Multiple calls to this functions are okay, the function takes care not * to free objects twice. * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). * @return None. */ void dc_close(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } dc_imap_disconnect(context->inbox); dc_imap_disconnect(context->sentbox_thread.imap); dc_imap_disconnect(context->mvbox_thread.imap); dc_smtp_disconnect(context->smtp); if (dc_sqlite3_is_open(context->sql)) { dc_sqlite3_close(context->sql); } free(context->dbfile); context->dbfile = NULL; free(context->blobdir); context->blobdir = NULL; } /** * Check if the context database is open. * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). * @return 0=context is not open, 1=context is open. */ int dc_is_open(const dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return 0; /* error - database not opened */ } return dc_sqlite3_is_open(context->sql); } /** * Get the blob directory. * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). * @return Blob directory associated with the context object, empty string if unset or on errors. NULL is never returned. * The returned string must be free()'d. */ char* dc_get_blobdir(const dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return dc_strdup(NULL); } return dc_strdup(context->blobdir); } /******************************************************************************* * INI-handling, Information ******************************************************************************/ static int is_settable_config_key(const char* key) { for (int i = 0; i < str_array_len(config_keys); i++) { if (strcmp(key, config_keys[i]) == 0) { return 1; } } return 0; } static int is_gettable_config_key(const char* key) { for (int i = 0; i < str_array_len(sys_config_keys); i++) { if (strcmp(key, sys_config_keys[i]) == 0) { return 1; } } return is_settable_config_key(key); } static char* get_config_keys_str() { dc_strbuilder_t ret; dc_strbuilder_init(&ret, 0); for (int i = 0; i < str_array_len(config_keys); i++) { if (strlen(ret.buf) > 0) { dc_strbuilder_cat(&ret, " "); } dc_strbuilder_cat(&ret, config_keys[i]); } for (int i = 0; i < str_array_len(sys_config_keys); i++) { if (strlen(ret.buf) > 0) { dc_strbuilder_cat(&ret, " "); } dc_strbuilder_cat(&ret, sys_config_keys[i]); } return ret.buf; } static char* get_sys_config_str(const char* key) { if (strcmp(key, "sys.version")==0) { return dc_strdup(DC_VERSION_STR); } else if (strcmp(key, "sys.msgsize_max_recommended")==0) { return dc_mprintf("%i", DC_MSGSIZE_MAX_RECOMMENDED); } else if (strcmp(key, "sys.config_keys")==0) { return get_config_keys_str(); } else { return dc_strdup(NULL); } } /** * Configure the context. The configuration is handled by key=value pairs as: * * - `addr` = address to display (always needed) * - `mail_server` = IMAP-server, guessed if left out * - `mail_user` = IMAP-username, guessed if left out * - `mail_pw` = IMAP-password (always needed) * - `mail_port` = IMAP-port, guessed if left out * - `send_server` = SMTP-server, guessed if left out * - `send_user` = SMTP-user, guessed if left out * - `send_pw` = SMTP-password, guessed if left out * - `send_port` = SMTP-port, guessed if left out * - `server_flags` = IMAP-/SMTP-flags as a combination of @ref DC_LP flags, guessed if left out * - `displayname` = Own name to use when sending messages. MUAs are allowed to spread this way eg. using CC, defaults to empty * - `selfstatus` = Own status to display eg. in email footers, defaults to a standard text * - `selfavatar` = File containing avatar. Will be copied to blob directory. * NULL to remove the avatar. * It is planned for future versions * to send this image together with the next messages. * - `e2ee_enabled` = 0=no end-to-end-encryption, 1=prefer end-to-end-encryption (default) * - `mdns_enabled` = 0=do not send or request read receipts, * 1=send and request read receipts (default) * - `inbox_watch` = 1=watch `INBOX`-folder for changes (default), * 0=do not watch the `INBOX`-folder * - `sentbox_watch`= 1=watch `Sent`-folder for changes (default), * 0=do not watch the `Sent`-folder * - `mvbox_watch` = 1=watch `DeltaChat`-folder for changes (default), * 0=do not watch the `DeltaChat`-folder * - `mvbox_move` = 1=heuristically detect chat-messages * and move them to the `DeltaChat`-folder, * 0=do not move chat-messages * - `show_emails` = DC_SHOW_EMAILS_OFF (0)= * show direct replies to chats only (default), * DC_SHOW_EMAILS_ACCEPTED_CONTACTS (1)= * also show all mails of confirmed contacts, * DC_SHOW_EMAILS_ALL (2)= * also show mails of unconfirmed contacts in the deaddrop. * - `save_mime_headers` = 1=save mime headers * and make dc_get_mime_headers() work for subsequent calls, * 0=do not save mime headers (default) * * If you want to retrieve a value, use dc_get_config(). * * @memberof dc_context_t * @param context The context object * @param key The option to change, see above. * @param value The value to save for "key" * @return 0=failure, 1=success */ int dc_set_config(dc_context_t* context, const char* key, const char* value) { int ret = 0; char* rel_path = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || key==NULL || !is_settable_config_key(key)) { /* "value" may be NULL */ return 0; } if (strcmp(key, "selfavatar")==0 && value) { rel_path = dc_strdup(value); if (!dc_make_rel_and_copy(context, &rel_path)) { goto cleanup; } ret = dc_sqlite3_set_config(context->sql, key, rel_path); } else if(strcmp(key, "inbox_watch")==0) { ret = dc_sqlite3_set_config(context->sql, key, value); dc_interrupt_imap_idle(context); // force idle() to be called again with the new mode } else if(strcmp(key, "sentbox_watch")==0) { ret = dc_sqlite3_set_config(context->sql, key, value); dc_interrupt_sentbox_idle(context); // force idle() to be called again with the new mode } else if(strcmp(key, "mvbox_watch")==0) { ret = dc_sqlite3_set_config(context->sql, key, value); dc_interrupt_mvbox_idle(context); // force idle() to be called again with the new mode } else if (strcmp(key, "selfstatus")==0) { // if the status text equals to the default, // store it as NULL to support future updatates of this text char* def = dc_stock_str(context, DC_STR_STATUSLINE); ret = dc_sqlite3_set_config(context->sql, key, (value==NULL || strcmp(value, def)==0)? NULL : value); free(def); } else { ret = dc_sqlite3_set_config(context->sql, key, value); } cleanup: free(rel_path); return ret; } /** * Get a configuration option. * The configuration option is set by dc_set_config() or by the library itself. * * Beside the options shown at dc_set_config(), * this function can be used to query some global system values: * * - `sys.version` = get the version string eg. as `1.2.3` or as `1.2.3special4` * - `sys.msgsize_max_recommended` = maximal recommended attachment size in bytes. * All possible overheads are already subtracted and this value can be used eg. for direct comparison * with the size of a file the user wants to attach. If an attachment is larger than this value, * an error (no warning as it should be shown to the user) is logged but the attachment is sent anyway. * - `sys.config_keys` = get a space-separated list of all config-keys available. * The config-keys are the keys that can be passed to the parameter `key` of this function. * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). For querying system values, this can be NULL. * @param key The key to query. * @return Returns current value of "key", if "key" is unset, the default value is returned. * The returned value must be free()'d, NULL is never returned. */ char* dc_get_config(dc_context_t* context, const char* key) { char* value = NULL; if (key && key[0]=='s' && key[1]=='y' && key[2]=='s' && key[3]=='.') { return get_sys_config_str(key); } if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || key==NULL || !is_gettable_config_key(key)) { return dc_strdup(""); } if (strcmp(key, "selfavatar")==0) { char* rel_path = dc_sqlite3_get_config(context->sql, key, NULL); if (rel_path) { value = dc_get_abs_path(context, rel_path); free(rel_path); } } else { value = dc_sqlite3_get_config(context->sql, key, NULL); } if (value==NULL) { // no value yet, use default value if (strcmp(key, "e2ee_enabled")==0) { value = dc_mprintf("%i", DC_E2EE_DEFAULT_ENABLED); } else if (strcmp(key, "mdns_enabled")==0) { value = dc_mprintf("%i", DC_MDNS_DEFAULT_ENABLED); } else if (strcmp(key, "imap_folder")==0) { value = dc_strdup("INBOX"); } else if (strcmp(key, "inbox_watch")==0) { value = dc_mprintf("%i", DC_INBOX_WATCH_DEFAULT); } else if (strcmp(key, "sentbox_watch")==0) { value = dc_mprintf("%i", DC_SENTBOX_WATCH_DEFAULT); } else if (strcmp(key, "mvbox_watch")==0) { value = dc_mprintf("%i", DC_MVBOX_WATCH_DEFAULT); } else if (strcmp(key, "mvbox_move")==0) { value = dc_mprintf("%i", DC_MVBOX_MOVE_DEFAULT); } else if (strcmp(key, "show_emails")==0) { value = dc_mprintf("%i", DC_SHOW_EMAILS_DEFAULT); } else if (strcmp(key, "selfstatus")==0) { value = dc_stock_str(context, DC_STR_STATUSLINE); } else { value = dc_mprintf(""); } } return value; } /** * Tool to check if a folder is equal to the configured INBOX. * @private @memberof dc_context_t */ int dc_is_inbox(dc_context_t* context, const char* folder_name) { int is_inbox = 0; if (folder_name) { is_inbox = strcasecmp("INBOX", folder_name)==0? 1 : 0; } return is_inbox; } /** * Tool to check if a folder is equal to the configured sent-folder. * @private @memberof dc_context_t */ int dc_is_sentbox(dc_context_t* context, const char* folder_name) { char* sentbox_name = dc_sqlite3_get_config(context->sql, "configured_sentbox_folder", NULL); int is_sentbox = 0; if (sentbox_name && folder_name) { is_sentbox = strcasecmp(sentbox_name, folder_name)==0? 1 : 0; } free(sentbox_name); return is_sentbox; } /** * Tool to check if a folder is equal to the configured sent-folder. * @private @memberof dc_context_t */ int dc_is_mvbox(dc_context_t* context, const char* folder_name) { char* mvbox_name = dc_sqlite3_get_config(context->sql, "configured_mvbox_folder", NULL); int is_mvbox = 0; if (mvbox_name && folder_name) { is_mvbox = strcasecmp(mvbox_name, folder_name)==0? 1 : 0; } free(mvbox_name); return is_mvbox; } /** * Find out the version of the Delta Chat core library. * Deprecated, use dc_get_config() instread * * @private @memberof dc_context_t * @return String with version number as `major.minor.revision`. The return value must be free()'d. */ char* dc_get_version_str(void) { return dc_strdup(DC_VERSION_STR); } /** * Get information about the context. * The information is returned by a multi-line string * and contains information about the current configuration. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return String which must be free()'d after usage. Never returns NULL. */ char* dc_get_info(dc_context_t* context) { const char* unset = "0"; char* displayname = NULL; char* temp = NULL; char* l_readable_str = NULL; char* l2_readable_str = NULL; char* fingerprint_str = NULL; dc_loginparam_t* l = NULL; dc_loginparam_t* l2 = NULL; int inbox_watch = 0; int sentbox_watch = 0; int mvbox_watch = 0; int mvbox_move = 0; int folders_configured = 0; char* configured_sentbox_folder = NULL; char* configured_mvbox_folder = NULL; int contacts = 0; int chats = 0; int real_msgs = 0; int deaddrop_msgs = 0; int is_configured = 0; int dbversion = 0; int show_emails = 0; int mdns_enabled = 0; int e2ee_enabled = 0; int prv_key_cnt = 0; int pub_key_cnt = 0; dc_key_t* self_public = dc_key_new(); int rpgp_enabled = 0; #ifdef DC_USE_RPGP rpgp_enabled = 1; #endif dc_strbuilder_t ret; dc_strbuilder_init(&ret, 0); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return dc_strdup("ErrBadPtr"); } /* read data (all pointers may be NULL!) */ l = dc_loginparam_new(); l2 = dc_loginparam_new(); dc_loginparam_read(l, context->sql, ""); dc_loginparam_read(l2, context->sql, "configured_" /*the trailing underscore is correct*/); displayname = dc_sqlite3_get_config(context->sql, "displayname", NULL); chats = dc_get_chat_cnt(context); real_msgs = dc_get_real_msg_cnt(context); deaddrop_msgs = dc_get_deaddrop_msg_cnt(context); contacts = dc_get_real_contact_cnt(context); is_configured = dc_sqlite3_get_config_int(context->sql, "configured", 0); dbversion = dc_sqlite3_get_config_int(context->sql, "dbversion", 0); e2ee_enabled = dc_sqlite3_get_config_int(context->sql, "e2ee_enabled", DC_E2EE_DEFAULT_ENABLED); show_emails = dc_sqlite3_get_config_int(context->sql, "show_emails", DC_SHOW_EMAILS_DEFAULT); mdns_enabled = dc_sqlite3_get_config_int(context->sql, "mdns_enabled", DC_MDNS_DEFAULT_ENABLED); sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM keypairs;"); sqlite3_step(stmt); prv_key_cnt = sqlite3_column_int(stmt, 0); sqlite3_finalize(stmt); stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM acpeerstates;"); sqlite3_step(stmt); pub_key_cnt = sqlite3_column_int(stmt, 0); sqlite3_finalize(stmt); if (dc_key_load_self_public(self_public, l2->addr, context->sql)) { fingerprint_str = dc_key_get_fingerprint(self_public); } else { fingerprint_str = dc_strdup(""); } l_readable_str = dc_loginparam_get_readable(l); l2_readable_str = dc_loginparam_get_readable(l2); inbox_watch = dc_sqlite3_get_config_int(context->sql, "inbox_watch", DC_INBOX_WATCH_DEFAULT); sentbox_watch = dc_sqlite3_get_config_int(context->sql, "sentbox_watch", DC_SENTBOX_WATCH_DEFAULT); mvbox_watch = dc_sqlite3_get_config_int(context->sql, "mvbox_watch", DC_MVBOX_WATCH_DEFAULT); mvbox_move = dc_sqlite3_get_config_int(context->sql, "mvbox_move", DC_MVBOX_MOVE_DEFAULT); folders_configured = dc_sqlite3_get_config_int(context->sql, "folders_configured", 0); configured_sentbox_folder = dc_sqlite3_get_config(context->sql, "configured_sentbox_folder", ""); configured_mvbox_folder = dc_sqlite3_get_config(context->sql, "configured_mvbox_folder", ""); temp = dc_mprintf( "deltachat_core_version=v%s\n" "sqlite_version=%s\n" "sqlite_thread_safe=%i\n" "libetpan_version=%i.%i\n" "openssl_version=%i.%i.%i%c\n" "rpgp_enabled=%i\n" "compile_date=" __DATE__ ", " __TIME__ "\n" "arch=%i\n" "number_of_chats=%i\n" "number_of_chat_messages=%i\n" "messages_in_contact_requests=%i\n" "number_of_contacts=%i\n" "database_dir=%s\n" "database_version=%i\n" "blobdir=%s\n" "display_name=%s\n" "is_configured=%i\n" "entered_account_settings=%s\n" "used_account_settings=%s\n" "inbox_watch=%i\n" "sentbox_watch=%i\n" "mvbox_watch=%i\n" "mvbox_move=%i\n" "folders_configured=%i\n" "configured_sentbox_folder=%s\n" "configured_mvbox_folder=%s\n" "show_emails=%i\n" "mdns_enabled=%i\n" "e2ee_enabled=%i\n" "private_key_count=%i\n" "public_key_count=%i\n" "fingerprint=%s\n" , DC_VERSION_STR , SQLITE_VERSION , sqlite3_threadsafe() , libetpan_get_version_major(), libetpan_get_version_minor() , (int)(OPENSSL_VERSION_NUMBER>>28), (int)(OPENSSL_VERSION_NUMBER>>20)&0xFF, (int)(OPENSSL_VERSION_NUMBER>>12)&0xFF, (char)('a'-1+((OPENSSL_VERSION_NUMBER>>4)&0xFF)) , rpgp_enabled , sizeof(void*)*8 , chats , real_msgs , deaddrop_msgs , contacts , context->dbfile? context->dbfile : unset , dbversion , context->blobdir? context->blobdir : unset , displayname? displayname : unset , is_configured , l_readable_str , l2_readable_str , inbox_watch , sentbox_watch , mvbox_watch , mvbox_move , folders_configured , configured_sentbox_folder , configured_mvbox_folder , show_emails , mdns_enabled , e2ee_enabled , prv_key_cnt , pub_key_cnt , fingerprint_str ); dc_strbuilder_cat(&ret, temp); free(temp); /* free data */ dc_loginparam_unref(l); dc_loginparam_unref(l2); free(displayname); free(l_readable_str); free(l2_readable_str); free(configured_sentbox_folder); free(configured_mvbox_folder); free(fingerprint_str); dc_key_unref(self_public); return ret.buf; /* must be freed by the caller */ } /******************************************************************************* * Search ******************************************************************************/ /** * Returns the message IDs of all _fresh_ messages of any chat. * Typically used for implementing notification summaries. * The list is already sorted and starts with the most recent fresh message. * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @return Array of message IDs, must be dc_array_unref()'d when no longer used. * On errors, the list is empty. NULL is never returned. */ dc_array_t* dc_get_fresh_msgs(dc_context_t* context) { int show_deaddrop = 0; dc_array_t* ret = dc_array_new(context, 128); sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || ret==NULL) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT m.id" " FROM msgs m" " LEFT JOIN contacts ct ON m.from_id=ct.id" " LEFT JOIN chats c ON m.chat_id=c.id" " WHERE m.state=?" " AND m.hidden=0" " AND m.chat_id>?" " AND ct.blocked=0" " AND (c.blocked=0 OR c.blocked=?)" " ORDER BY m.timestamp DESC,m.id DESC;"); sqlite3_bind_int(stmt, 1, DC_STATE_IN_FRESH); sqlite3_bind_int(stmt, 2, DC_CHAT_ID_LAST_SPECIAL); sqlite3_bind_int(stmt, 3, show_deaddrop? DC_CHAT_DEADDROP_BLOCKED : 0); while (sqlite3_step(stmt)==SQLITE_ROW) { dc_array_add_id(ret, sqlite3_column_int(stmt, 0)); } cleanup: sqlite3_finalize(stmt); return ret; } /** * Search messages containing the given query string. * Searching can be done globally (chat_id=0) or in a specified chat only (chat_id * set). * * Global chat results are typically displayed using dc_msg_get_summary(), chat * search results may just hilite the corresponding messages and present a * prev/next button. * * @memberof dc_context_t * @param context The context object as returned from dc_context_new(). * @param chat_id ID of the chat to search messages in. * Set this to 0 for a global search. * @param query The query to search for. * @return An array of message IDs. Must be freed using dc_array_unref() when no longer needed. * If nothing can be found, the function returns NULL. */ dc_array_t* dc_search_msgs(dc_context_t* context, uint32_t chat_id, const char* query) { //clock_t start = clock(); int success = 0; dc_array_t* ret = dc_array_new(context, 100); char* strLikeInText = NULL; char* strLikeBeg = NULL; char* real_query = NULL; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || ret==NULL || query==NULL) { goto cleanup; } real_query = dc_strdup(query); dc_trim(real_query); if (real_query[0]==0) { success = 1; /*empty result*/ goto cleanup; } strLikeInText = dc_mprintf("%%%s%%", real_query); strLikeBeg = dc_mprintf("%s%%", real_query); /*for the name search, we use "Name%" which is fast as it can use the index ("%Name%" could not). */ /* Incremental search with "LIKE %query%" cannot take advantages from any index ("query%" could for COLLATE NOCASE indexes, see http://www.sqlite.org/optoverview.html#like_opt) An alternative may be the FULLTEXT sqlite stuff, however, this does not really help with incremental search. An extra table with all words and a COLLATE NOCASE indexes may help, however, this must be updated all the time and probably consumes more time than we can save in tenthousands of searches. For now, we just expect the following query to be fast enough :-) */ if (chat_id) { stmt = dc_sqlite3_prepare(context->sql, "SELECT m.id, m.timestamp FROM msgs m" " LEFT JOIN contacts ct ON m.from_id=ct.id" " WHERE m.chat_id=? " " AND m.hidden=0 " " AND ct.blocked=0 AND (txt LIKE ? OR ct.name LIKE ?)" " ORDER BY m.timestamp,m.id;"); /* chats starts with the oldest message*/ sqlite3_bind_int (stmt, 1, chat_id); sqlite3_bind_text(stmt, 2, strLikeInText, -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 3, strLikeBeg, -1, SQLITE_STATIC); } else { int show_deaddrop = 0;//dc_sqlite3_get_config_int(context->sql, "show_deaddrop", 0); stmt = dc_sqlite3_prepare(context->sql, "SELECT m.id, m.timestamp FROM msgs m" " LEFT JOIN contacts ct ON m.from_id=ct.id" " LEFT JOIN chats c ON m.chat_id=c.id" " WHERE m.chat_id>" DC_STRINGIFY(DC_CHAT_ID_LAST_SPECIAL) " AND m.hidden=0 " " AND (c.blocked=0 OR c.blocked=?)" " AND ct.blocked=0 AND (m.txt LIKE ? OR ct.name LIKE ?)" " ORDER BY m.timestamp DESC,m.id DESC;"); /* chat overview starts with the newest message*/ sqlite3_bind_int (stmt, 1, show_deaddrop? DC_CHAT_DEADDROP_BLOCKED : 0); sqlite3_bind_text(stmt, 2, strLikeInText, -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 3, strLikeBeg, -1, SQLITE_STATIC); } while (sqlite3_step(stmt)==SQLITE_ROW) { dc_array_add_id(ret, sqlite3_column_int(stmt, 0)); } success = 1; cleanup: free(strLikeInText); free(strLikeBeg); free(real_query); sqlite3_finalize(stmt); //dc_log_info(context, 0, "Message list for search \"%s\" in chat #%i created in %.3f ms.", query, chat_id, (double)(clock()-start)*1000.0/CLOCKS_PER_SEC); if (success) { return ret; } else { if (ret) { dc_array_unref(ret); } return NULL; } } ``` Filename: dc_dehtml.c ```c #include #include #include "dc_context.h" #include "dc_dehtml.h" #include "dc_saxparser.h" #include "dc_tools.h" #include "dc_strbuilder.h" typedef struct dehtml_t { dc_strbuilder_t strbuilder; #define DO_NOT_ADD 0 #define DO_ADD_REMOVE_LINEENDS 1 #define DO_ADD_PRESERVE_LINEENDS 2 int add_text; char* last_href; } dehtml_t; static void dehtml_starttag_cb(void* userdata, const char* tag, char** attr) { dehtml_t* dehtml = (dehtml_t*)userdata; if (strcmp(tag, "p")==0 || strcmp(tag, "div")==0 || strcmp(tag, "table")==0 || strcmp(tag, "td")==0) { dc_strbuilder_cat(&dehtml->strbuilder, "\n\n"); dehtml->add_text = DO_ADD_REMOVE_LINEENDS; } else if (strcmp(tag, "br")==0) { dc_strbuilder_cat(&dehtml->strbuilder, "\n"); dehtml->add_text = DO_ADD_REMOVE_LINEENDS; } else if (strcmp(tag, "style")==0 || strcmp(tag, "script")==0 || strcmp(tag, "title")==0) { dehtml->add_text = DO_NOT_ADD; } else if (strcmp(tag, "pre")==0) { dc_strbuilder_cat(&dehtml->strbuilder, "\n\n"); dehtml->add_text = DO_ADD_PRESERVE_LINEENDS; } else if (strcmp(tag, "a")==0) { free(dehtml->last_href); dehtml->last_href = dc_strdup_keep_null(dc_attr_find(attr, "href")); if (dehtml->last_href) { dc_strbuilder_cat(&dehtml->strbuilder, "["); } } else if (strcmp(tag, "b")==0 || strcmp(tag, "strong")==0) { dc_strbuilder_cat(&dehtml->strbuilder, "*"); } else if (strcmp(tag, "i")==0 || strcmp(tag, "em")==0) { dc_strbuilder_cat(&dehtml->strbuilder, "_"); } } static void dehtml_text_cb(void* userdata, const char* text, int len) { dehtml_t* dehtml = (dehtml_t*)userdata; if (dehtml->add_text != DO_NOT_ADD) { char* last_added = dc_strbuilder_cat(&dehtml->strbuilder, text); if (dehtml->add_text==DO_ADD_REMOVE_LINEENDS) { unsigned char* p = (unsigned char*)last_added; while (*p) { if (*p=='\n') { int last_is_lineend = 1; /* avoid converting `text1
\ntext2` to `text1\n text2` (`\r` is removed later) */ const unsigned char* p2 = p-1; while (p2>=(const unsigned char*)dehtml->strbuilder.buf) { if (*p2=='\r') { } else if (*p2=='\n') { break; } else { last_is_lineend = 0; break; } p2--; } *p = last_is_lineend? '\r' : ' '; } p++; } } } } static void dehtml_endtag_cb(void* userdata, const char* tag) { dehtml_t* dehtml = (dehtml_t*)userdata; if (strcmp(tag, "p")==0 || strcmp(tag, "div")==0 || strcmp(tag, "table")==0 || strcmp(tag, "td")==0 || strcmp(tag, "style")==0 || strcmp(tag, "script")==0 || strcmp(tag, "title")==0 || strcmp(tag, "pre")==0) { dc_strbuilder_cat(&dehtml->strbuilder, "\n\n"); /* do not expect an starting block element (which, of course, should come right now) */ dehtml->add_text = DO_ADD_REMOVE_LINEENDS; } else if (strcmp(tag, "a")==0) { if (dehtml->last_href) { dc_strbuilder_cat(&dehtml->strbuilder, "]("); dc_strbuilder_cat(&dehtml->strbuilder, dehtml->last_href); dc_strbuilder_cat(&dehtml->strbuilder, ")"); free(dehtml->last_href); dehtml->last_href = NULL; } } else if (strcmp(tag, "b")==0 || strcmp(tag, "strong")==0) { dc_strbuilder_cat(&dehtml->strbuilder, "*"); } else if (strcmp(tag, "i")==0 || strcmp(tag, "em")==0) { dc_strbuilder_cat(&dehtml->strbuilder, "_"); } } char* dc_dehtml(char* buf_terminated) { dc_trim(buf_terminated); if (buf_terminated[0]==0) { return dc_strdup(""); /* support at least empty HTML-messages; for empty messages, we'll replace the message by the subject later */ } else { dehtml_t dehtml; dc_saxparser_t saxparser; memset(&dehtml, 0, sizeof(dehtml_t)); dehtml.add_text = DO_ADD_REMOVE_LINEENDS; dc_strbuilder_init(&dehtml.strbuilder, strlen(buf_terminated)); dc_saxparser_init(&saxparser, &dehtml); dc_saxparser_set_tag_handler(&saxparser, dehtml_starttag_cb, dehtml_endtag_cb); dc_saxparser_set_text_handler(&saxparser, dehtml_text_cb); dc_saxparser_parse(&saxparser, buf_terminated); free(dehtml.last_href); return dehtml.strbuilder.buf; } } ``` Filename: dc_e2ee.c ```c #include "dc_context.h" #include "dc_pgp.h" #include "dc_aheader.h" #include "dc_keyring.h" #include "dc_mimeparser.h" #include "dc_apeerstate.h" /******************************************************************************* * Tools ******************************************************************************/ static struct mailmime* new_data_part(void* data, size_t data_bytes, char* default_content_type, int default_encoding) { //char basename_buf[PATH_MAX]; struct mailmime_mechanism * encoding; struct mailmime_content * content; struct mailmime * mime; //int r; //char * dup_filename; struct mailmime_fields * mime_fields; int encoding_type; char * content_type_str; int do_encoding; /*if (filename!=NULL) { strncpy(basename_buf, filename, PATH_MAX); libetpan_basename(basename_buf); }*/ encoding = NULL; /* default content-type */ if (default_content_type==NULL) content_type_str = "application/octet-stream"; else content_type_str = default_content_type; content = mailmime_content_new_with_str(content_type_str); if (content==NULL) { goto free_content; } do_encoding = 1; if (content->ct_type->tp_type==MAILMIME_TYPE_COMPOSITE_TYPE) { struct mailmime_composite_type * composite; composite = content->ct_type->tp_data.tp_composite_type; switch (composite->ct_type) { case MAILMIME_COMPOSITE_TYPE_MESSAGE: if (strcasecmp(content->ct_subtype, "rfc822")==0) do_encoding = 0; break; case MAILMIME_COMPOSITE_TYPE_MULTIPART: do_encoding = 0; break; } } if (do_encoding) { if (default_encoding==-1) encoding_type = MAILMIME_MECHANISM_BASE64; else encoding_type = default_encoding; /* default Content-Transfer-Encoding */ encoding = mailmime_mechanism_new(encoding_type, NULL); if (encoding==NULL) { goto free_content; } } mime_fields = mailmime_fields_new_with_data(encoding, NULL, NULL, NULL, NULL); if (mime_fields==NULL) { goto free_content; } mime = mailmime_new_empty(content, mime_fields); if (mime==NULL) { goto free_mime_fields; } /*if ((filename!=NULL) && (mime->mm_type==MAILMIME_SINGLE)) { // duplicates the file so that the file can be deleted when // the MIME part is done dup_filename = dup_file(privacy, filename); if (dup_filename==NULL) { goto free_mime; } r = mailmime_set_body_file(mime, dup_filename); if (r!=MAILIMF_NO_ERROR) { free(dup_filename); goto free_mime; } }*/ if (data!=NULL && data_bytes>0 && mime->mm_type==MAILMIME_SINGLE) { mailmime_set_body_text(mime, data, data_bytes); } return mime; // free_mime: //mailmime_free(mime); goto err; free_mime_fields: mailmime_fields_free(mime_fields); mailmime_content_free(content); goto err; free_content: if (encoding!=NULL) mailmime_mechanism_free(encoding); if (content!=NULL) mailmime_content_free(content); err: return NULL; } /** * Check if a MIME structure contains a multipart/report part. * * As reports are often unencrypted, we do not reset the Autocrypt header in * this case. * * However, Delta Chat itself has no problem with encrypted multipart/report * parts and MUAs should be encouraged to encrpyt multipart/reports as well so * that we could use the normal Autocrypt processing. * * @private * @param mime The mime struture to check * @return 1=multipart/report found in MIME, 0=no multipart/report found */ static int contains_report(struct mailmime* mime) { if (mime->mm_type==MAILMIME_MULTIPLE) { if (mime->mm_content_type->ct_type->tp_type==MAILMIME_TYPE_COMPOSITE_TYPE && mime->mm_content_type->ct_type->tp_data.tp_composite_type->ct_type==MAILMIME_COMPOSITE_TYPE_MULTIPART && strcmp(mime->mm_content_type->ct_subtype, "report")==0) { return 1; } clistiter* cur; for (cur=clist_begin(mime->mm_data.mm_multipart.mm_mp_list); cur!=NULL; cur=clist_next(cur)) { if (contains_report((struct mailmime*)clist_content(cur))) { return 1; } } } else if (mime->mm_type==MAILMIME_MESSAGE) { if (contains_report(mime->mm_data.mm_message.mm_msg_mime)) { return 1; } } return 0; } /******************************************************************************* * Generate Keypairs ******************************************************************************/ static int load_or_generate_self_public_key(dc_context_t* context, dc_key_t* public_key, const char* self_addr, struct mailmime* random_data_mime /*for an extra-seed of the random generator. For speed reasons, only give _available_ pointers here, do not create any data - in very most cases, the key is not generated!*/) { static int s_in_key_creation = 0; /* avoid double creation (we unlock the database during creation) */ int key_created = 0; int success = 0, key_creation_here = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || public_key==NULL) { goto cleanup; } if (!dc_key_load_self_public(public_key, self_addr, context->sql)) { /* create the keypair - this may take a moment, however, as this is in a thread, this is no big deal */ if (s_in_key_creation) { goto cleanup; } key_creation_here = 1; s_in_key_creation = 1; /* seed the random generator */ { uintptr_t seed[4]; seed[0] = (uintptr_t)time(NULL); /* time */ seed[1] = (uintptr_t)seed; /* stack */ seed[2] = (uintptr_t)public_key; /* heap */ seed[3] = (uintptr_t)pthread_self(); /* thread ID */ dc_pgp_rand_seed(context, seed, sizeof(seed)); if (random_data_mime) { MMAPString* random_data_mmap = NULL; int col = 0; if ((random_data_mmap=mmap_string_new(""))==NULL) { goto cleanup; } mailmime_write_mem(random_data_mmap, &col, random_data_mime); dc_pgp_rand_seed(context, random_data_mmap->str, random_data_mmap->len); mmap_string_free(random_data_mmap); } } { dc_key_t* private_key = dc_key_new(); clock_t start = clock(); dc_log_info(context, 0, "Generating keypair with %i bits, e=%i ...", DC_KEYGEN_BITS, DC_KEYGEN_E); /* The public key must contain the following: - a signing-capable primary key Kp - a user id - a self signature - an encryption-capable subkey Ke - a binding signature over Ke by Kp (see https://autocrypt.readthedocs.io/en/latest/level0.html#type-p-openpgp-based-key-data)*/ key_created = dc_pgp_create_keypair(context, self_addr, public_key, private_key); if (!key_created) { dc_log_warning(context, 0, "Cannot create keypair."); goto cleanup; } if (!dc_pgp_is_valid_key(context, public_key) || !dc_pgp_is_valid_key(context, private_key)) { dc_log_warning(context, 0, "Generated keys are not valid."); goto cleanup; } if (!dc_key_save_self_keypair(public_key, private_key, self_addr, 1/*set default*/, context->sql)) { dc_log_warning(context, 0, "Cannot save keypair."); goto cleanup; } dc_log_info(context, 0, "Keypair generated in %.3f s.", (double)(clock()-start)/CLOCKS_PER_SEC); dc_key_unref(private_key); } } success = 1; cleanup: if (key_creation_here) { s_in_key_creation = 0; } return success; } int dc_ensure_secret_key_exists(dc_context_t* context) { /* normally, the key is generated as soon as the first mail is send (this is to gain some extra-random-seed by the message content and the timespan between program start and message sending) */ int success = 0; dc_key_t* public_key = dc_key_new(); char* self_addr = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || public_key==NULL) { goto cleanup; } if ((self_addr=dc_sqlite3_get_config(context->sql, "configured_addr", NULL))==NULL) { dc_log_warning(context, 0, "Cannot ensure secret key if context is not configured."); goto cleanup; } if (!load_or_generate_self_public_key(context, public_key, self_addr, NULL/*no random text data for seeding available*/)) { goto cleanup; } success = 1; cleanup: dc_key_unref(public_key); free(self_addr); return success; } /******************************************************************************* * Encrypt ******************************************************************************/ void dc_e2ee_encrypt(dc_context_t* context, const clist* recipients_addr, int force_unencrypted, int e2ee_guaranteed, /*set if e2ee was possible on sending time; we should not degrade to transport*/ int min_verified, int do_gossip, struct mailmime* in_out_message, dc_e2ee_helper_t* helper) { int col = 0; int do_encrypt = 0; dc_aheader_t* autocryptheader = dc_aheader_new(); struct mailimf_fields* imffields_unprotected = NULL; /*just a pointer into mailmime structure, must not be freed*/ dc_keyring_t* keyring = dc_keyring_new(); dc_key_t* sign_key = dc_key_new(); MMAPString* plain = mmap_string_new(""); char* ctext = NULL; size_t ctext_bytes = 0; dc_array_t* peerstates = dc_array_new(NULL, 10); if (helper) { memset(helper, 0, sizeof(dc_e2ee_helper_t)); } if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || recipients_addr==NULL || in_out_message==NULL || in_out_message->mm_parent /* libEtPan's pgp_encrypt_mime() takes the parent as the new root. We just expect the root as being given to this function. */ || autocryptheader==NULL || keyring==NULL || sign_key==NULL || plain==NULL || helper==NULL) { goto cleanup; } /* init autocrypt header from db */ autocryptheader->prefer_encrypt = DC_PE_NOPREFERENCE; if (dc_sqlite3_get_config_int(context->sql, "e2ee_enabled", DC_E2EE_DEFAULT_ENABLED)) { autocryptheader->prefer_encrypt = DC_PE_MUTUAL; } autocryptheader->addr = dc_sqlite3_get_config(context->sql, "configured_addr", NULL); if (autocryptheader->addr==NULL) { goto cleanup; } if (!load_or_generate_self_public_key(context, autocryptheader->public_key, autocryptheader->addr, in_out_message/*only for random-seed*/)) { goto cleanup; } /* load peerstate information etc. */ if (autocryptheader->prefer_encrypt==DC_PE_MUTUAL || e2ee_guaranteed) { do_encrypt = 1; clistiter* iter1; for (iter1 = clist_begin(recipients_addr); iter1!=NULL ; iter1=clist_next(iter1)) { const char* recipient_addr = clist_content(iter1); dc_apeerstate_t* peerstate = dc_apeerstate_new(context); dc_key_t* key_to_use = NULL; if (strcasecmp(recipient_addr, autocryptheader->addr)==0) { ; // encrypt to SELF, this key is added below } else if (dc_apeerstate_load_by_addr(peerstate, context->sql, recipient_addr) && (key_to_use=dc_apeerstate_peek_key(peerstate, min_verified))!=NULL && (peerstate->prefer_encrypt==DC_PE_MUTUAL || e2ee_guaranteed)) { dc_keyring_add(keyring, key_to_use); /* we always add all recipients (even on IMAP upload) as otherwise forwarding may fail */ dc_array_add_ptr(peerstates, peerstate); } else { dc_apeerstate_unref(peerstate); do_encrypt = 0; break; /* if we cannot encrypt to a single recipient, we cannot encrypt the message at all */ } } } if (do_encrypt) { dc_keyring_add(keyring, autocryptheader->public_key); /* we always add ourself as otherwise forwarded messages are not readable */ if (!dc_key_load_self_private(sign_key, autocryptheader->addr, context->sql)) { do_encrypt = 0; } } if (force_unencrypted) { do_encrypt = 0; } if ((imffields_unprotected=mailmime_find_mailimf_fields(in_out_message))==NULL) { goto cleanup; } /* encrypt message, if possible */ if (do_encrypt) { /* prepare part to encrypt */ mailprivacy_prepare_mime(in_out_message); /* encode quoted printable all text parts */ struct mailmime* part_to_encrypt = in_out_message->mm_data.mm_message.mm_msg_mime; part_to_encrypt->mm_parent = NULL; struct mailimf_fields* imffields_encrypted = mailimf_fields_new_empty(); struct mailmime* message_to_encrypt = mailmime_new(MAILMIME_MESSAGE, NULL, 0, mailmime_fields_new_empty(), /* mailmime_new_message_data() calls mailmime_fields_new_with_version() which would add the unwanted MIME-Version:-header */ mailmime_get_content_message(), NULL, NULL, NULL, NULL, imffields_encrypted, part_to_encrypt); /* gossip keys */ if (do_gossip) { int iCnt = dc_array_get_cnt(peerstates); if (iCnt > 1) { for (int i = 0; i < iCnt; i++) { char* p = dc_apeerstate_render_gossip_header((dc_apeerstate_t*)dc_array_get_ptr(peerstates, i), min_verified); if (p) { mailimf_fields_add(imffields_encrypted, mailimf_field_new_custom(strdup("Autocrypt-Gossip"), p/*takes ownership*/)); } } } } /* memoryhole headers */ clistiter* cur = clist_begin(imffields_unprotected->fld_list); while (cur!=NULL) { int move_to_encrypted = 0; struct mailimf_field* field = (struct mailimf_field*)clist_content(cur); if (field) { if (field->fld_type==MAILIMF_FIELD_SUBJECT) { move_to_encrypted = 1; } else if (field->fld_type==MAILIMF_FIELD_OPTIONAL_FIELD) { struct mailimf_optional_field* opt_field = field->fld_data.fld_optional_field; if (opt_field && opt_field->fld_name) { if ( strncmp(opt_field->fld_name, "Secure-Join", 11)==0 || (strncmp(opt_field->fld_name, "Chat-", 5)==0 && strcmp(opt_field->fld_name, "Chat-Version")!=0)/*Chat-Version may be used for filtering and is not added to the encrypted part, however, this is subject to change*/) { move_to_encrypted = 1; } } } } if (move_to_encrypted) { mailimf_fields_add(imffields_encrypted, field); cur = clist_delete(imffields_unprotected->fld_list, cur); } else { cur = clist_next(cur); } } struct mailimf_subject* subject = mailimf_subject_new(dc_strdup("...")); mailimf_fields_add(imffields_unprotected, mailimf_field_new(MAILIMF_FIELD_SUBJECT, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, subject, NULL, NULL, NULL)); clist_append(part_to_encrypt->mm_content_type->ct_parameters, mailmime_param_new_with_data("protected-headers", "v1")); /* convert part to encrypt to plain text */ mailmime_write_mem(plain, &col, message_to_encrypt); if (plain->str==NULL || plain->len<=0) { goto cleanup; } //char* t1=dc_null_terminate(plain->str,plain->len);printf("PLAIN:\n%s\n",t1);free(t1); // DEBUG OUTPUT if (!dc_pgp_pk_encrypt(context, plain->str, plain->len, keyring, sign_key, 1/*use_armor*/, (void**)&ctext, &ctext_bytes)) { goto cleanup; } helper->cdata_to_free = ctext; //char* t2=dc_null_terminate(ctext,ctext_bytes);printf("ENCRYPTED:\n%s\n",t2);free(t2); // DEBUG OUTPUT /* create MIME-structure that will contain the encrypted text */ struct mailmime* encrypted_part = new_data_part(NULL, 0, "multipart/encrypted", -1); struct mailmime_content* content = encrypted_part->mm_content_type; clist_append(content->ct_parameters, mailmime_param_new_with_data("protocol", "application/pgp-encrypted")); static char version_content[] = "Version: 1\r\n"; struct mailmime* version_mime = new_data_part(version_content, strlen(version_content), "application/pgp-encrypted", MAILMIME_MECHANISM_7BIT); mailmime_smart_add_part(encrypted_part, version_mime); struct mailmime* ctext_part = new_data_part(ctext, ctext_bytes, "application/octet-stream", MAILMIME_MECHANISM_7BIT); mailmime_smart_add_part(encrypted_part, ctext_part); /* replace the original MIME-structure by the encrypted MIME-structure */ in_out_message->mm_data.mm_message.mm_msg_mime = encrypted_part; encrypted_part->mm_parent = in_out_message; mailmime_free(message_to_encrypt); //MMAPString* t3=mmap_string_new("");mailmime_write_mem(t3,&col,in_out_message);char* t4=dc_null_terminate(t3->str,t3->len); printf("ENCRYPTED+MIME_ENCODED:\n%s\n",t4);free(t4);mmap_string_free(t3); // DEBUG OUTPUT helper->encryption_successfull = 1; } char* p = dc_aheader_render(autocryptheader); if (p==NULL) { goto cleanup; } mailimf_fields_add(imffields_unprotected, mailimf_field_new_custom(strdup("Autocrypt"), p/*takes ownership of pointer*/)); cleanup: dc_aheader_unref(autocryptheader); dc_keyring_unref(keyring); dc_key_unref(sign_key); if (plain) { mmap_string_free(plain); } for (int i=dc_array_get_cnt(peerstates)-1; i>=0; i--) { dc_apeerstate_unref((dc_apeerstate_t*)dc_array_get_ptr(peerstates, i)); } dc_array_unref(peerstates); } void dc_e2ee_thanks(dc_e2ee_helper_t* helper) { if (helper==NULL) { return; } free(helper->cdata_to_free); helper->cdata_to_free = NULL; if (helper->gossipped_addr) { dc_hash_clear(helper->gossipped_addr); free(helper->gossipped_addr); helper->gossipped_addr = NULL; } if (helper->signatures) { dc_hash_clear(helper->signatures); free(helper->signatures); helper->signatures = NULL; } } /******************************************************************************* * Decrypt ******************************************************************************/ static int has_decrypted_pgp_armor(const char* str__, int str_bytes) { const unsigned char* str_end = (const unsigned char*)str__+str_bytes; const unsigned char* p=(const unsigned char*)str__; while (p < str_end) { if (*p > ' ') { break; } p++; str_bytes--; } if (str_bytes>27 && strncmp((const char*)p, "-----BEGIN PGP MESSAGE-----", 27)==0) { return 1; } return 0; } static int decrypt_part(dc_context_t* context, struct mailmime* mime, const dc_keyring_t* private_keyring, const dc_keyring_t* public_keyring_for_validate, /*may be NULL*/ dc_hash_t* ret_valid_signatures, struct mailmime** ret_decrypted_mime) { struct mailmime_data* mime_data = NULL; int mime_transfer_encoding = MAILMIME_MECHANISM_BINARY; char* transfer_decoding_buffer = NULL; /* mmap_string_unref()'d if set */ const char* decoded_data = NULL; /* must not be free()'d */ size_t decoded_data_bytes = 0; void* plain_buf = NULL; size_t plain_bytes = 0; int sth_decrypted = 0; *ret_decrypted_mime = NULL; /* get data pointer from `mime` */ mime_data = mime->mm_data.mm_single; if (mime_data->dt_type!=MAILMIME_DATA_TEXT /* MAILMIME_DATA_FILE indicates, the data is in a file; AFAIK this is not used on parsing */ || mime_data->dt_data.dt_text.dt_data==NULL || mime_data->dt_data.dt_text.dt_length <= 0) { goto cleanup; } /* check headers in `mime` */ if (mime->mm_mime_fields!=NULL) { clistiter* cur; for (cur = clist_begin(mime->mm_mime_fields->fld_list); cur!=NULL; cur = clist_next(cur)) { struct mailmime_field* field = (struct mailmime_field*)clist_content(cur); if (field) { if (field->fld_type==MAILMIME_FIELD_TRANSFER_ENCODING && field->fld_data.fld_encoding) { mime_transfer_encoding = field->fld_data.fld_encoding->enc_type; } } } } /* regard `Content-Transfer-Encoding:` */ if (mime_transfer_encoding==MAILMIME_MECHANISM_7BIT || mime_transfer_encoding==MAILMIME_MECHANISM_8BIT || mime_transfer_encoding==MAILMIME_MECHANISM_BINARY) { decoded_data = mime_data->dt_data.dt_text.dt_data; decoded_data_bytes = mime_data->dt_data.dt_text.dt_length; if (decoded_data==NULL || decoded_data_bytes <= 0) { goto cleanup; /* no error - but no data */ } } else { int r; size_t current_index = 0; r = mailmime_part_parse(mime_data->dt_data.dt_text.dt_data, mime_data->dt_data.dt_text.dt_length, ¤t_index, mime_transfer_encoding, &transfer_decoding_buffer, &decoded_data_bytes); if (r!=MAILIMF_NO_ERROR || transfer_decoding_buffer==NULL || decoded_data_bytes <= 0) { goto cleanup; } decoded_data = transfer_decoding_buffer; } /* encrypted, decoded data in decoded_data now ... */ if (!has_decrypted_pgp_armor(decoded_data, decoded_data_bytes)) { goto cleanup; } dc_hash_t* add_signatures = dc_hash_cnt(ret_valid_signatures)<=0? ret_valid_signatures : NULL; /*if we already have fingerprints, do not add more; this ensures, only the fingerprints from the outer-most part are collected */ if (!dc_pgp_pk_decrypt(context, decoded_data, decoded_data_bytes, private_keyring, public_keyring_for_validate, 1, &plain_buf, &plain_bytes, add_signatures) || plain_buf==NULL || plain_bytes<=0) { goto cleanup; } //{char* t1=dc_null_terminate(plain_buf,plain_bytes);printf("\n**********\n%s\n**********\n",t1);free(t1);} { size_t index = 0; struct mailmime* decrypted_mime = NULL; if (mailmime_parse(plain_buf, plain_bytes, &index, &decrypted_mime)!=MAIL_NO_ERROR || decrypted_mime==NULL) { if(decrypted_mime) {mailmime_free(decrypted_mime);} goto cleanup; } //mailmime_print(decrypted_mime); *ret_decrypted_mime = decrypted_mime; sth_decrypted = 1; } //mailmime_substitute(mime, new_mime); //s. mailprivacy_gnupg.c::pgp_decrypt() cleanup: if (transfer_decoding_buffer) { mmap_string_unref(transfer_decoding_buffer); } return sth_decrypted; } static int decrypt_recursive(dc_context_t* context, struct mailmime* mime, const dc_keyring_t* private_keyring, const dc_keyring_t* public_keyring_for_validate, dc_hash_t* ret_valid_signatures, struct mailimf_fields** ret_gossip_headers, int* ret_has_unencrypted_parts) { struct mailmime_content* ct = NULL; clistiter* cur = NULL; if (context==NULL || mime==NULL) { return 0; } if (mime->mm_type==MAILMIME_MULTIPLE) { ct = mime->mm_content_type; if (ct && ct->ct_subtype && strcmp(ct->ct_subtype, "encrypted")==0) { /* decrypt "multipart/encrypted" -- child parts are eg. "application/pgp-encrypted" (uninteresting, version only), "application/octet-stream" (the interesting data part) and optional, unencrypted help files */ for (cur=clist_begin(mime->mm_data.mm_multipart.mm_mp_list); cur!=NULL; cur=clist_next(cur)) { struct mailmime* decrypted_mime = NULL; if (decrypt_part(context, (struct mailmime*)clist_content(cur), private_keyring, public_keyring_for_validate, ret_valid_signatures, &decrypted_mime)) { /* remember the header containing potentially Autocrypt-Gossip */ if (*ret_gossip_headers==NULL /* use the outermost decrypted part */ && dc_hash_cnt(ret_valid_signatures) > 0 /* do not trust the gossipped keys when the message cannot be validated eg. due to a bad signature */) { size_t dummy = 0; struct mailimf_fields* test = NULL; if (mailimf_envelope_and_optional_fields_parse(decrypted_mime->mm_mime_start, decrypted_mime->mm_length, &dummy, &test)==MAILIMF_NO_ERROR && test) { *ret_gossip_headers = test; } } /* replace encrypted mime structure by decrypted one */ mailmime_substitute(mime, decrypted_mime); mailmime_free(mime); return 1; /* sth. decrypted, start over from root searching for encrypted parts */ } } *ret_has_unencrypted_parts = 1; // there is a part that could not be decrypted } else { for (cur=clist_begin(mime->mm_data.mm_multipart.mm_mp_list); cur!=NULL; cur=clist_next(cur)) { if (decrypt_recursive(context, (struct mailmime*)clist_content(cur), private_keyring, public_keyring_for_validate, ret_valid_signatures, ret_gossip_headers, ret_has_unencrypted_parts)) { return 1; /* sth. decrypted, start over from root searching for encrypted parts */ } } } } else if (mime->mm_type==MAILMIME_MESSAGE) { if (decrypt_recursive(context, mime->mm_data.mm_message.mm_msg_mime, private_keyring, public_keyring_for_validate, ret_valid_signatures, ret_gossip_headers, ret_has_unencrypted_parts)) { return 1; /* sth. decrypted, start over from root searching for encrypted parts */ } } else { *ret_has_unencrypted_parts = 1; // there is a part that was not encrypted at all. in combination with otherwise encrypted mails, this is a problem. } return 0; } static dc_hash_t* update_gossip_peerstates(dc_context_t* context, time_t message_time, struct mailimf_fields* imffields, const struct mailimf_fields* gossip_headers) { clistiter* cur1 = NULL; dc_hash_t* recipients = NULL; dc_hash_t* gossipped_addr = NULL; for (cur1 = clist_begin(gossip_headers->fld_list); cur1!=NULL ; cur1=clist_next(cur1)) { struct mailimf_field* field = (struct mailimf_field*)clist_content(cur1); if (field->fld_type==MAILIMF_FIELD_OPTIONAL_FIELD) { const struct mailimf_optional_field* optional_field = field->fld_data.fld_optional_field; if (optional_field && optional_field->fld_name && strcasecmp(optional_field->fld_name, "Autocrypt-Gossip")==0) { dc_aheader_t* gossip_header = dc_aheader_new(); if (dc_aheader_set_from_string(gossip_header, optional_field->fld_value) && dc_pgp_is_valid_key(context, gossip_header->public_key)) { /* found an Autocrypt-Gossip entry, create recipents list and check if addr matches */ if (recipients==NULL) { recipients = mailimf_get_recipients(imffields); } if (dc_hash_find(recipients, gossip_header->addr, strlen(gossip_header->addr))) { /* valid recipient: update peerstate */ dc_apeerstate_t* peerstate = dc_apeerstate_new(context); if (!dc_apeerstate_load_by_addr(peerstate, context->sql, gossip_header->addr)) { dc_apeerstate_init_from_gossip(peerstate, gossip_header, message_time); dc_apeerstate_save_to_db(peerstate, context->sql, 1/*create*/); } else { dc_apeerstate_apply_gossip(peerstate, gossip_header, message_time); dc_apeerstate_save_to_db(peerstate, context->sql, 0/*do not create*/); } if (peerstate->degrade_event) { dc_handle_degrade_event(context, peerstate); } dc_apeerstate_unref(peerstate); // collect all gossipped addresses; we need them later to mark them as being // verified when used in a verified group by a verified sender if (gossipped_addr==NULL) { gossipped_addr = malloc(sizeof(dc_hash_t)); dc_hash_init(gossipped_addr, DC_HASH_STRING, 1/*copy key*/); } dc_hash_insert(gossipped_addr, gossip_header->addr, strlen(gossip_header->addr), (void*)1); } else { dc_log_info(context, 0, "Ignoring gossipped \"%s\" as the address is not in To/Cc list.", gossip_header->addr); } } dc_aheader_unref(gossip_header); } } } if (recipients) { dc_hash_clear(recipients); free(recipients); } return gossipped_addr; } void dc_e2ee_decrypt(dc_context_t* context, struct mailmime* in_out_message, dc_e2ee_helper_t* helper) { /* return values: 0=nothing to decrypt/cannot decrypt, 1=sth. decrypted (to detect parts that could not be decrypted, simply look for left "multipart/encrypted" MIME types */ struct mailimf_fields* imffields = mailmime_find_mailimf_fields(in_out_message); /*just a pointer into mailmime structure, must not be freed*/ dc_aheader_t* autocryptheader = NULL; time_t message_time = 0; dc_apeerstate_t* peerstate = dc_apeerstate_new(context); char* from = NULL; char* self_addr = NULL; dc_keyring_t* private_keyring = dc_keyring_new(); dc_keyring_t* public_keyring_for_validate = dc_keyring_new(); struct mailimf_fields* gossip_headers = NULL; if (helper) { memset(helper, 0, sizeof(dc_e2ee_helper_t)); } if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || in_out_message==NULL || helper==NULL || imffields==NULL) { goto cleanup; } /* Autocrypt preparations: - Set message_time and from (both may be unset) - Get the autocrypt header, if any. - Do not abort on errors - we should try at last the decyption below */ if (imffields) { struct mailimf_field* field = mailimf_find_field(imffields, MAILIMF_FIELD_FROM); if (field && field->fld_data.fld_from) { from = mailimf_find_first_addr(field->fld_data.fld_from->frm_mb_list); } field = mailimf_find_field(imffields, MAILIMF_FIELD_ORIG_DATE); if (field && field->fld_data.fld_orig_date) { struct mailimf_orig_date* orig_date = field->fld_data.fld_orig_date; if (orig_date) { message_time = dc_timestamp_from_date(orig_date->dt_date_time); /* is not yet checked against bad times! */ if (message_time!=DC_INVALID_TIMESTAMP && message_time > time(NULL)) { message_time = time(NULL); } } } } autocryptheader = dc_aheader_new_from_imffields(from, imffields); if (autocryptheader) { if (!dc_pgp_is_valid_key(context, autocryptheader->public_key)) { dc_aheader_unref(autocryptheader); autocryptheader = NULL; } } /* modify the peerstate (eg. if there is a peer but not autocrypt header, stop encryption) */ /* apply Autocrypt:-header */ if (message_time > 0 && from) { if (dc_apeerstate_load_by_addr(peerstate, context->sql, from)) { if (autocryptheader) { dc_apeerstate_apply_header(peerstate, autocryptheader, message_time); dc_apeerstate_save_to_db(peerstate, context->sql, 0/*no not create*/); } else { if (message_time > peerstate->last_seen_autocrypt && !contains_report(in_out_message) /*reports are ususally not encrpyted; do not degrade decryption then*/){ dc_apeerstate_degrade_encryption(peerstate, message_time); dc_apeerstate_save_to_db(peerstate, context->sql, 0/*no not create*/); } } } else if (autocryptheader) { dc_apeerstate_init_from_header(peerstate, autocryptheader, message_time); dc_apeerstate_save_to_db(peerstate, context->sql, 1/*create*/); } } /* load private key for decryption */ if ((self_addr=dc_sqlite3_get_config(context->sql, "configured_addr", NULL))==NULL) { goto cleanup; } if (!dc_keyring_load_self_private_for_decrypting(private_keyring, self_addr, context->sql)) { goto cleanup; } /* if not yet done, load peer with public key for verification (should be last as the peer may be modified above) */ if (peerstate->last_seen==0) { dc_apeerstate_load_by_addr(peerstate, context->sql, from); } if (peerstate->degrade_event) { dc_handle_degrade_event(context, peerstate); } // offer both, gossip and public, for signature validation. // the caller may check the signature fingerprints as needed later. dc_keyring_add(public_keyring_for_validate, peerstate->gossip_key); dc_keyring_add(public_keyring_for_validate, peerstate->public_key); /* finally, decrypt. If sth. was decrypted, decrypt_recursive() returns "true" and we start over to decrypt maybe just added parts. */ helper->signatures = malloc(sizeof(dc_hash_t)); dc_hash_init(helper->signatures, DC_HASH_STRING, 1/*copy key*/); int iterations = 0; while (iterations < 10) { int has_unencrypted_parts = 0; if (!decrypt_recursive(context, in_out_message, private_keyring, public_keyring_for_validate, helper->signatures, &gossip_headers, &has_unencrypted_parts)) { break; } // if we're here, sth. was encrypted. if we're on top-level, and there are no // additional unencrypted parts in the message the encryption was fine // (signature is handled separately and returned as `signatures`) if (iterations==0 && !has_unencrypted_parts) { helper->encrypted = 1; } iterations++; } /* check for Autocrypt-Gossip */ if (gossip_headers) { helper->gossipped_addr = update_gossip_peerstates(context, message_time, imffields, gossip_headers); } //mailmime_print(in_out_message); cleanup: if (gossip_headers) { mailimf_fields_free(gossip_headers); } dc_aheader_unref(autocryptheader); dc_apeerstate_unref(peerstate); dc_keyring_unref(private_keyring); dc_keyring_unref(public_keyring_for_validate); free(from); free(self_addr); } ``` Filename: dc_hash.c ```c #include #include #include #include #include #include "dc_context.h" #include "dc_hash.h" /* ** Based upon hash.c from sqlite which author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ #define Addr(X) ((uintptr_t)X) static void* sjhashMalloc(long bytes) { void* p=malloc(bytes); if (p) memset(p, 0, bytes); return p; } #define sjhashMallocRaw(a) malloc((a)) #define sjhashFree(a) free((a)) /* An array to map all upper-case characters into their corresponding * lower-case character. */ static const unsigned char sjhashUpperToLower[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, 252,253,254,255 }; /* Some systems have stricmp(). Others have strcasecmp(). Because * there is no consistency, we will define our own. */ static int sjhashStrNICmp(const char *zLeft, const char *zRight, int N) { register unsigned char *a, *b; a = (unsigned char *)zLeft; b = (unsigned char *)zRight; while (N-- > 0 && *a!=0 && sjhashUpperToLower[*a]==sjhashUpperToLower[*b]) { a++; b++; } return N<0 ? 0 : sjhashUpperToLower[*a] - sjhashUpperToLower[*b]; } /* This function computes a hash on the name of a keyword. * Case is not significant. */ static int sjhashNoCase(const char *z, int n) { int h = 0; if (n<=0) n = strlen(z); while (n > 0) { h = (h<<3) ^ h ^ sjhashUpperToLower[(unsigned char)*z++]; n--; } return h & 0x7fffffff; } /* Turn bulk memory into a hash table object by initializing the * fields of the Hash structure. * * "pNew" is a pointer to the hash table that is to be initialized. * keyClass is one of the constants SJHASH_INT, SJHASH_POINTER, * SJHASH_BINARY, or SJHASH_STRING. The value of keyClass * determines what kind of key the hash table will use. "copyKey" is * true if the hash table should make its own private copy of keys and * false if it should just use the supplied pointer. CopyKey only makes * sense for SJHASH_STRING and SJHASH_BINARY and is ignored * for other key classes. */ void dc_hash_init(dc_hash_t *pNew, int keyClass, int copyKey) { assert( pNew!=0); assert( keyClass>=DC_HASH_INT && keyClass<=DC_HASH_BINARY); pNew->keyClass = keyClass; if (keyClass==DC_HASH_POINTER || keyClass==DC_HASH_INT) copyKey = 0; pNew->copyKey = copyKey; pNew->first = 0; pNew->count = 0; pNew->htsize = 0; pNew->ht = 0; } /* Remove all entries from a hash table. Reclaim all memory. * Call this routine to delete a hash table or to reset a hash table * to the empty state. */ void dc_hash_clear(dc_hash_t *pH) { dc_hashelem_t *elem; /* For looping over all elements of the table */ if (pH == NULL) { return; } elem = pH->first; pH->first = 0; if (pH->ht) sjhashFree(pH->ht); pH->ht = 0; pH->htsize = 0; while (elem) { dc_hashelem_t *next_elem = elem->next; if (pH->copyKey && elem->pKey) { sjhashFree(elem->pKey); } sjhashFree(elem); elem = next_elem; } pH->count = 0; } /* Hash and comparison functions when the mode is SJHASH_INT */ static int intHash(const void *pKey, int nKey) { return nKey ^ (nKey<<8) ^ (nKey>>8); } static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2) { return n2 - n1; } /* Hash and comparison functions when the mode is SJHASH_POINTER */ static int ptrHash(const void *pKey, int nKey) { uintptr_t x = Addr(pKey); return x ^ (x<<8) ^ (x>>8); } static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2) { if (pKey1==pKey2) return 0; if (pKey1 0) { h = (h<<3) ^ h ^ *(z++); } return h & 0x7fffffff; } static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2) { if (n1!=n2) return 1; return memcmp(pKey1,pKey2,n1); } /* Return a pointer to the appropriate hash function given the key class. * * About the syntax: * The name of the function is "hashFunction". The function takes a * single parameter "keyClass". The return value of hashFunction() * is a pointer to another function. Specifically, the return value * of hashFunction() is a pointer to a function that takes two parameters * with types "const void*" and "int" and returns an "int". */ static int (*hashFunction(int keyClass))(const void*,int) { switch (keyClass) { case DC_HASH_INT: return &intHash; case DC_HASH_POINTER:return &ptrHash; case DC_HASH_STRING: return &strHash; case DC_HASH_BINARY: return &binHash;; default: break; } return 0; } /* Return a pointer to the appropriate hash function given the key class. */ static int (*compareFunction(int keyClass))(const void*,int,const void*,int) { switch (keyClass) { case DC_HASH_INT: return &intCompare; case DC_HASH_POINTER: return &ptrCompare; case DC_HASH_STRING: return &strCompare; case DC_HASH_BINARY: return &binCompare; default: break; } return 0; } /* Link an element into the hash table */ static void insertElement(dc_hash_t *pH, /* The complete hash table */ struct _ht *pEntry, /* The entry into which pNew is inserted */ dc_hashelem_t *pNew) /* The element to be inserted */ { dc_hashelem_t *pHead; /* First element already in pEntry */ pHead = pEntry->chain; if (pHead) { pNew->next = pHead; pNew->prev = pHead->prev; if (pHead->prev) { pHead->prev->next = pNew; } else { pH->first = pNew; } pHead->prev = pNew; } else { pNew->next = pH->first; if (pH->first) { pH->first->prev = pNew; } pNew->prev = 0; pH->first = pNew; } pEntry->count++; pEntry->chain = pNew; } /* Resize the hash table so that it cantains "new_size" buckets. * "new_size" must be a power of 2. The hash table might fail * to resize if sjhashMalloc() fails. */ static void rehash(dc_hash_t *pH, int new_size) { struct _ht *new_ht; /* The new hash table */ dc_hashelem_t *elem, *next_elem; /* For looping over existing elements */ int (*xHash)(const void*,int); /* The hash function */ assert( (new_size & (new_size-1))==0); new_ht = (struct _ht *)sjhashMalloc( new_size*sizeof(struct _ht)); if (new_ht==0) return; if (pH->ht) sjhashFree(pH->ht); pH->ht = new_ht; pH->htsize = new_size; xHash = hashFunction(pH->keyClass); for(elem=pH->first, pH->first=0; elem; elem = next_elem) { int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1); next_elem = elem->next; insertElement(pH, &new_ht[h], elem); } } /* This function (for internal use only) locates an element in an * hash table that matches the given key. The hash for this key has * already been computed and is passed as the 4th parameter. */ static dc_hashelem_t *findElementGivenHash(const dc_hash_t *pH, /* The pH to be searched */ const void *pKey, /* The key we are searching for */ int nKey, int h) /* The hash for this key. */ { dc_hashelem_t *elem; /* Used to loop thru the element list */ int count; /* Number of elements left to test */ int (*xCompare)(const void*,int,const void*,int); /* comparison function */ if (pH->ht) { struct _ht *pEntry = &pH->ht[h]; elem = pEntry->chain; count = pEntry->count; xCompare = compareFunction(pH->keyClass); while (count-- && elem) { if ((*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0) { return elem; } elem = elem->next; } } return 0; } /* Remove a single entry from the hash table given a pointer to that * element and a hash on the element's key. */ static void removeElementGivenHash(dc_hash_t *pH, /* The pH containing "elem" */ dc_hashelem_t* elem, /* The element to be removed from the pH */ int h) /* Hash value for the element */ { struct _ht *pEntry; if (elem->prev) { elem->prev->next = elem->next; } else { pH->first = elem->next; } if (elem->next) { elem->next->prev = elem->prev; } pEntry = &pH->ht[h]; if (pEntry->chain==elem) { pEntry->chain = elem->next; } pEntry->count--; if (pEntry->count<=0) { pEntry->chain = 0; } if (pH->copyKey && elem->pKey) { sjhashFree(elem->pKey); } sjhashFree( elem); pH->count--; } /* Attempt to locate an element of the hash table pH with a key * that matches pKey,nKey. Return the data for this element if it is * found, or NULL if there is no match. */ void* dc_hash_find(const dc_hash_t *pH, const void *pKey, int nKey) { int h; /* A hash on key */ dc_hashelem_t *elem; /* The element that matches key */ int (*xHash)(const void*,int); /* The hash function */ if (pH==0 || pH->ht==0) return 0; xHash = hashFunction(pH->keyClass); assert( xHash!=0); h = (*xHash)(pKey,nKey); assert( (pH->htsize & (pH->htsize-1))==0); elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1)); return elem ? elem->data : 0; } /* Insert an element into the hash table pH. The key is pKey,nKey * and the data is "data". * * If no element exists with a matching key, then a new * element is created. A copy of the key is made if the copyKey * flag is set. NULL is returned. * * If another element already exists with the same key, then the * new data replaces the old data and the old data is returned. * The key is not copied in this instance. If a malloc fails, then * the new data is returned and the hash table is unchanged. * * If the "data" parameter to this function is NULL, then the * element corresponding to "key" is removed from the hash table. */ void* dc_hash_insert(dc_hash_t *pH, const void *pKey, int nKey, void *data) { int hraw; /* Raw hash value of the key */ int h; /* the hash of the key modulo hash table size */ dc_hashelem_t *elem; /* Used to loop thru the element list */ dc_hashelem_t *new_elem; /* New element added to the pH */ int (*xHash)(const void*,int); /* The hash function */ assert( pH!=0); xHash = hashFunction(pH->keyClass); assert( xHash!=0); hraw = (*xHash)(pKey, nKey); assert( (pH->htsize & (pH->htsize-1))==0); h = hraw & (pH->htsize-1); elem = findElementGivenHash(pH,pKey,nKey,h); if (elem) { void *old_data = elem->data; if (data==0) { removeElementGivenHash(pH,elem,h); } else { elem->data = data; } return old_data; } if (data==0) return 0; new_elem = (dc_hashelem_t*)sjhashMalloc( sizeof(dc_hashelem_t)); if (new_elem==0) return data; if (pH->copyKey && pKey!=0) { new_elem->pKey = sjhashMallocRaw( nKey); if (new_elem->pKey==0) { sjhashFree(new_elem); return data; } memcpy((void*)new_elem->pKey, pKey, nKey); } else { new_elem->pKey = (void*)pKey; } new_elem->nKey = nKey; pH->count++; if (pH->htsize==0) { rehash(pH,8); if (pH->htsize==0) { pH->count = 0; sjhashFree(new_elem); return data; } } if (pH->count > pH->htsize) { rehash(pH,pH->htsize*2); } assert( pH->htsize>0); assert( (pH->htsize & (pH->htsize-1))==0); h = hraw & (pH->htsize-1); insertElement(pH, &pH->ht[h], new_elem); new_elem->data = data; return 0; } ``` Filename: dc_imap.c ```c #include #include #include #include #include #include "dc_context.h" #include "dc_imap.h" #include "dc_job.h" #include "dc_loginparam.h" #include "dc_oauth2.h" static int setup_handle_if_needed (dc_imap_t*); static void unsetup_handle (dc_imap_t*); #define FREE_SET(a) if((a)) { mailimap_set_free((a)); (a)=NULL; } #define FREE_FETCH_LIST(a) if((a)) { mailimap_fetch_list_free((a)); (a)=NULL; } /******************************************************************************* * Tools ******************************************************************************/ int dc_imap_is_error(dc_imap_t* imap, int code) { if (code==MAILIMAP_NO_ERROR /*0*/ || code==MAILIMAP_NO_ERROR_AUTHENTICATED /*1*/ || code==MAILIMAP_NO_ERROR_NON_AUTHENTICATED /*2*/) { return 0; } if (code==MAILIMAP_ERROR_STREAM /*4*/ || code==MAILIMAP_ERROR_PARSE /*5*/) { dc_log_info(imap->context, 0, "IMAP stream lost; we'll reconnect soon."); imap->should_reconnect = 1; } return 1; } static char* get_error_msg(dc_imap_t* imap, const char* what_failed, int code) { char* stock = NULL; dc_strbuilder_t msg; dc_strbuilder_init(&msg, 1000); switch (code) { case MAILIMAP_ERROR_LOGIN: stock = dc_stock_str_repl_string(imap->context, DC_STR_CANNOT_LOGIN, imap->imap_user); dc_strbuilder_cat(&msg, stock); break; default: dc_strbuilder_catf(&msg, "%s, IMAP-error #%i", what_failed, code); break; } free(stock); stock = NULL; if (imap->etpan->imap_response) { dc_strbuilder_cat(&msg, "\n\n"); stock = dc_stock_str_repl_string2(imap->context, DC_STR_SERVER_RESPONSE, imap->imap_server, imap->etpan->imap_response); dc_strbuilder_cat(&msg, stock); } free(stock); stock = NULL; return msg.buf; } static void get_config_lastseenuid(dc_imap_t* imap, const char* folder, uint32_t* uidvalidity, uint32_t* lastseenuid) { *uidvalidity = 0; *lastseenuid = 0; char* key = dc_mprintf("imap.mailbox.%s", folder); char* val1 = imap->get_config(imap, key, NULL), *val2 = NULL, *val3 = NULL; if (val1) { /* the entry has the format `imap.mailbox.=:` */ val2 = strchr(val1, ':'); if (val2) { *val2 = 0; val2++; val3 = strchr(val2, ':'); if (val3) { *val3 = 0; /* ignore everything bethind an optional second colon to allow future enhancements */ } *uidvalidity = atol(val1); *lastseenuid = atol(val2); } } free(val1); /* val2 and val3 are only pointers inside val1 and MUST NOT be free()'d */ free(key); } static void set_config_lastseenuid(dc_imap_t* imap, const char* folder, uint32_t uidvalidity, uint32_t lastseenuid) { char* key = dc_mprintf("imap.mailbox.%s", folder); char* val = dc_mprintf("%lu:%lu", uidvalidity, lastseenuid); imap->set_config(imap, key, val); free(val); free(key); } /******************************************************************************* * Handle folders ******************************************************************************/ static int select_folder(dc_imap_t* imap, const char* folder /*may be NULL*/) { if (imap==NULL) { return 0; } if (imap->etpan==NULL) { imap->selected_folder[0] = 0; imap->selected_folder_needs_expunge = 0; return 0; } /* if there is a new folder and the new folder is equal to the selected one, there's nothing to do. if there is _no_ new folder, we continue as we might want to expunge below. */ if (folder && folder[0] && strcmp(imap->selected_folder, folder)==0) { return 1; } /* deselect existing folder, if needed (it's also done implicitly by SELECT, however, without EXPUNGE then) */ if (imap->selected_folder_needs_expunge) { if (imap->selected_folder[0]) { dc_log_info(imap->context, 0, "Expunge messages in \"%s\".", imap->selected_folder); mailimap_close(imap->etpan); /* a CLOSE-SELECT is considerably faster than an EXPUNGE-SELECT, see https://tools.ietf.org/html/rfc3501#section-6.4.2 */ } imap->selected_folder_needs_expunge = 0; } /* select new folder */ if (folder) { int r = mailimap_select(imap->etpan, folder); if (dc_imap_is_error(imap, r) || imap->etpan->imap_selection_info==NULL) { dc_log_info(imap->context, 0, "Cannot select folder; code=%i, imap_response=%s", r, imap->etpan->imap_response? imap->etpan->imap_response : ""); imap->selected_folder[0] = 0; return 0; } } free(imap->selected_folder); imap->selected_folder = dc_strdup(folder); return 1; } /******************************************************************************* * Fetch Messages ******************************************************************************/ static uint32_t peek_uid(struct mailimap_msg_att* msg_att) { /* search the UID in a list of attributes returned by a FETCH command */ clistiter* iter1; for (iter1=clist_begin(msg_att->att_list); iter1!=NULL; iter1=clist_next(iter1)) { struct mailimap_msg_att_item* item = (struct mailimap_msg_att_item*)clist_content(iter1); if (item) { if (item->att_type==MAILIMAP_MSG_ATT_ITEM_STATIC) { if (item->att_data.att_static->att_type==MAILIMAP_MSG_ATT_UID) { return item->att_data.att_static->att_data.att_uid; } } } } return 0; } static char* unquote_rfc724_mid(const char* in) { /* remove < and > from the given message id */ char* out = dc_strdup(in); int out_len = strlen(out); if (out_len > 2) { if (out[0]=='<') { out[0] = ' '; } if (out[out_len-1]=='>') { out[out_len-1] = ' '; } dc_trim(out); } return out; } static const char* peek_rfc724_mid(struct mailimap_msg_att* msg_att) { if (msg_att==NULL) { return NULL; } /* search the UID in a list of attributes returned by a FETCH command */ clistiter* iter1; for (iter1=clist_begin(msg_att->att_list); iter1!=NULL; iter1=clist_next(iter1)) { struct mailimap_msg_att_item* item = (struct mailimap_msg_att_item*)clist_content(iter1); if (item) { if (item->att_type==MAILIMAP_MSG_ATT_ITEM_STATIC) { if (item->att_data.att_static->att_type==MAILIMAP_MSG_ATT_ENVELOPE) { struct mailimap_envelope* env = item->att_data.att_static->att_data.att_env; if (env && env->env_message_id) { return env->env_message_id; } } } } } return NULL; } static int peek_flag_keyword(struct mailimap_msg_att* msg_att, const char* flag_keyword) { /* search $MDNSent in a list of attributes returned by a FETCH command */ if (msg_att==NULL || msg_att->att_list==NULL || flag_keyword==NULL) { return 0; } clistiter *iter1, *iter2; for (iter1=clist_begin(msg_att->att_list); iter1!=NULL; iter1=clist_next(iter1)) { struct mailimap_msg_att_item* item = (struct mailimap_msg_att_item*)clist_content(iter1); if (item) { if (item->att_type==MAILIMAP_MSG_ATT_ITEM_DYNAMIC) { if (item->att_data.att_dyn->att_list /*I've seen NULL here ...*/) { for (iter2=clist_begin(item->att_data.att_dyn->att_list); iter2!=NULL ; iter2=clist_next(iter2)) { struct mailimap_flag_fetch* flag_fetch =(struct mailimap_flag_fetch*) clist_content(iter2); if (flag_fetch && flag_fetch->fl_type==MAILIMAP_FLAG_FETCH_OTHER) { struct mailimap_flag* flag = flag_fetch->fl_flag; if (flag) { if (flag->fl_type==MAILIMAP_FLAG_KEYWORD && flag->fl_data.fl_keyword!=NULL && strcmp(flag->fl_data.fl_keyword, flag_keyword)==0) { return 1; /* flag found */ } } } } } } } } return 0; } static void peek_body(struct mailimap_msg_att* msg_att, char** p_msg, size_t* p_msg_bytes, uint32_t* flags, int* deleted) { if (msg_att==NULL) { return; } /* search body & Co. in a list of attributes returned by a FETCH command */ clistiter *iter1, *iter2; for (iter1=clist_begin(msg_att->att_list); iter1!=NULL; iter1=clist_next(iter1)) { struct mailimap_msg_att_item* item = (struct mailimap_msg_att_item*)clist_content(iter1); if (item) { if (item->att_type==MAILIMAP_MSG_ATT_ITEM_DYNAMIC) { if (item->att_data.att_dyn->att_list /*I've seen NULL here ...*/) { for (iter2=clist_begin(item->att_data.att_dyn->att_list); iter2!=NULL ; iter2=clist_next(iter2)) { struct mailimap_flag_fetch* flag_fetch =(struct mailimap_flag_fetch*) clist_content(iter2); if (flag_fetch && flag_fetch->fl_type==MAILIMAP_FLAG_FETCH_OTHER) { struct mailimap_flag* flag = flag_fetch->fl_flag; if (flag) { if (flag->fl_type==MAILIMAP_FLAG_SEEN) { *flags |= DC_IMAP_SEEN; } else if (flag->fl_type==MAILIMAP_FLAG_DELETED) { *deleted = 1; } } } } } } else if (item->att_type==MAILIMAP_MSG_ATT_ITEM_STATIC) { if (item->att_data.att_static->att_type==MAILIMAP_MSG_ATT_BODY_SECTION) { *p_msg = item->att_data.att_static->att_data.att_body_section->sec_body_part; *p_msg_bytes = item->att_data.att_static->att_data.att_body_section->sec_length; } } } } } static int fetch_single_msg(dc_imap_t* imap, const char* folder, uint32_t server_uid) { /* the function returns: 0 the caller should try over again later or 1 if the messages should be treated as received, the caller should not try to read the message again (even if no database entries are returned) */ char* msg_content = NULL; size_t msg_bytes = 0; int r = 0; int retry_later = 0; int deleted = 0; uint32_t flags = 0; clist* fetch_result = NULL; clistiter* cur; if (imap==NULL) { goto cleanup; } if (imap->etpan==NULL) { goto cleanup; } { struct mailimap_set* set = mailimap_set_new_single(server_uid); r = mailimap_uid_fetch(imap->etpan, set, imap->fetch_type_body, &fetch_result); FREE_SET(set); } if (dc_imap_is_error(imap, r) || fetch_result==NULL) { fetch_result = NULL; dc_log_warning(imap->context, 0, "Error #%i on fetching message #%i from folder \"%s\"; retry=%i.", (int)r, (int)server_uid, folder, (int)imap->should_reconnect); if (imap->should_reconnect) { retry_later = 1; /* maybe we should also retry on other errors, however, we should check this carefully, as this may result in a dead lock! */ } goto cleanup; /* this is an error that should be recovered; the caller should try over later to fetch the message again (if there is no such message, we simply get an empty result) */ } if ((cur=clist_begin(fetch_result))==NULL) { dc_log_warning(imap->context, 0, "Message #%i does not exist in folder \"%s\".", (int)server_uid, folder); goto cleanup; /* server response is fine, however, there is no such message, do not try to fetch the message again */ } struct mailimap_msg_att* msg_att = (struct mailimap_msg_att*)clist_content(cur); peek_body(msg_att, &msg_content, &msg_bytes, &flags, &deleted); if (msg_content==NULL || msg_bytes <= 0 || deleted) { /* dc_log_warning(imap->context, 0, "Message #%i in folder \"%s\" is empty or deleted.", (int)server_uid, folder); -- this is a quite usual situation, do not print a warning */ goto cleanup; } imap->receive_imf(imap, msg_content, msg_bytes, folder, server_uid, flags); cleanup: FREE_FETCH_LIST(fetch_result); return retry_later? 0 : 1; } static int fetch_from_single_folder(dc_imap_t* imap, const char* folder) { int r; uint32_t uidvalidity = 0; uint32_t lastseenuid = 0; uint32_t new_lastseenuid = 0; clist* fetch_result = NULL; size_t read_cnt = 0; size_t read_errors = 0; clistiter* cur; struct mailimap_set* set = NULL; if (imap==NULL) { goto cleanup; } if (imap->etpan==NULL) { dc_log_info(imap->context, 0, "Cannot fetch from \"%s\" - not connected.", folder); goto cleanup; } if (select_folder(imap, folder)==0) { dc_log_warning(imap->context, 0, "Cannot select folder %s for fetching.", folder); goto cleanup; } /* compare last seen UIDVALIDITY against the current one */ get_config_lastseenuid(imap, folder, &uidvalidity, &lastseenuid); if (uidvalidity!=imap->etpan->imap_selection_info->sel_uidvalidity) { /* first time this folder is selected or UIDVALIDITY has changed, init lastseenuid and save it to config */ if (imap->etpan->imap_selection_info->sel_uidvalidity <= 0) { dc_log_error(imap->context, 0, "Cannot get UIDVALIDITY for folder \"%s\".", folder); goto cleanup; } if (imap->etpan->imap_selection_info->sel_has_exists) { if (imap->etpan->imap_selection_info->sel_exists <= 0) { dc_log_info(imap->context, 0, "Folder \"%s\" is empty.", folder); if(imap->etpan->imap_selection_info->sel_exists==0) { /* set lastseenuid=0 for empty folders. id we do not do this here, we'll miss the first message as we will get in here again and fetch from lastseenuid+1 then */ set_config_lastseenuid(imap, folder, imap->etpan->imap_selection_info->sel_uidvalidity, 0); } goto cleanup; } /* `FETCH (UID)` */ set = mailimap_set_new_single(imap->etpan->imap_selection_info->sel_exists); } else { /* `FETCH * (UID)` - according to RFC 3501, `*` represents the largest message sequence number; if the mailbox is empty, an error resp. an empty list is returned. */ dc_log_info(imap->context, 0, "EXISTS is missing for folder \"%s\", using fallback.", folder); set = mailimap_set_new_single(0); } r = mailimap_fetch(imap->etpan, set, imap->fetch_type_prefetch, &fetch_result); FREE_SET(set); if (dc_imap_is_error(imap, r) || fetch_result==NULL) { fetch_result = NULL; dc_log_info(imap->context, 0, "No result returned for folder \"%s\".", folder); goto cleanup; /* this might happen if the mailbox is empty an EXISTS does not work */ } if ((cur=clist_begin(fetch_result))==NULL) { dc_log_info(imap->context, 0, "Empty result returned for folder \"%s\".", folder); goto cleanup; /* this might happen if the mailbox is empty an EXISTS does not work */ } struct mailimap_msg_att* msg_att = (struct mailimap_msg_att*)clist_content(cur); lastseenuid = peek_uid(msg_att); FREE_FETCH_LIST(fetch_result); if (lastseenuid <= 0) { dc_log_error(imap->context, 0, "Cannot get largest UID for folder \"%s\"", folder); goto cleanup; } /* if the UIDVALIDITY has _changed_, decrease lastseenuid by one to avoid gaps (well add 1 below) */ if (uidvalidity > 0 && lastseenuid > 1) { lastseenuid -= 1; } /* store calculated uidvalidity/lastseenuid */ uidvalidity = imap->etpan->imap_selection_info->sel_uidvalidity; set_config_lastseenuid(imap, folder, uidvalidity, lastseenuid); dc_log_info(imap->context, 0, "lastseenuid initialized to %i for %s@%i", (int)lastseenuid, folder, (int)uidvalidity); } /* fetch messages with larger UID than the last one seen (`UID FETCH lastseenuid+1:*)`, see RFC 4549 */ /* CAVE: some servers return UID smaller or equal to the requested ones under some circumstances! */ set = mailimap_set_new_interval(lastseenuid+1, 0); r = mailimap_uid_fetch(imap->etpan, set, imap->fetch_type_prefetch, &fetch_result); FREE_SET(set); if (dc_imap_is_error(imap, r) || fetch_result==NULL) { fetch_result = NULL; if (r==MAILIMAP_ERROR_PROTOCOL) { dc_log_info(imap->context, 0, "Folder \"%s\" is empty", folder); goto cleanup; /* the folder is simply empty, this is no error */ } dc_log_warning(imap->context, 0, "Cannot fetch message list from folder \"%s\".", folder); goto cleanup; } /* go through all mails in folder (this is typically _fast_ as we already have the whole list) */ for (cur = clist_begin(fetch_result); cur!=NULL ; cur = clist_next(cur)) { struct mailimap_msg_att* msg_att = (struct mailimap_msg_att*)clist_content(cur); /* mailimap_msg_att is a list of attributes: list is a list of message attributes */ uint32_t cur_uid = peek_uid(msg_att); if (cur_uid > lastseenuid /* `UID FETCH :*` may include lastseenuid if "*"==lastseenuid - and also smaller uids may be returned! */) { char* rfc724_mid = unquote_rfc724_mid(peek_rfc724_mid(msg_att)); read_cnt++; if (!imap->precheck_imf(imap, rfc724_mid, folder, cur_uid)) { if (fetch_single_msg(imap, folder, cur_uid)==0/* 0=try again later*/) { dc_log_info(imap->context, 0, "Read error for message %s from \"%s\", trying over later.", rfc724_mid, folder); read_errors++; // with read_errors, lastseenuid is not written } } else { dc_log_info(imap->context, 0, "Skipping message %s from \"%s\" by precheck.", rfc724_mid, folder); } if (cur_uid > new_lastseenuid) { new_lastseenuid = cur_uid; } free(rfc724_mid); } } if (!read_errors && new_lastseenuid > 0) { // TODO: it might be better to increase the lastseenuid also on partial errors. // however, this requires to sort the list before going through it above. set_config_lastseenuid(imap, folder, uidvalidity, new_lastseenuid); } /* done */ cleanup: if (read_errors) { dc_log_warning(imap->context, 0, "%i mails read from \"%s\" with %i errors.", (int)read_cnt, folder, (int)read_errors); } else { dc_log_info(imap->context, 0, "%i mails read from \"%s\".", (int)read_cnt, folder); } FREE_FETCH_LIST(fetch_result); return read_cnt; } /******************************************************************************* * Watch thread ******************************************************************************/ int dc_imap_fetch(dc_imap_t* imap) { int success = 0; if (imap==NULL || !imap->connected) { goto cleanup; } setup_handle_if_needed(imap); // as during the fetch commands, new messages may arrive, we fetch until we do not // get any more. if IDLE is called directly after, there is only a small chance that // messages are missed and delayed until the next IDLE call while (fetch_from_single_folder(imap, imap->watch_folder) > 0) { ; } success = 1; cleanup: return success; } static void fake_idle(dc_imap_t* imap) { /* Idle using timeouts. This is also needed if we're not yet configured - in this case, we're waiting for a configure job */ time_t fake_idle_start_time = time(NULL); time_t seconds_to_wait = 0; dc_log_info(imap->context, 0, "IMAP-fake-IDLEing..."); int do_fake_idle = 1; while (do_fake_idle) { // wait a moment: every 5 seconds in the first 3 minutes after a new message, after that every 60 seconds seconds_to_wait = (time(NULL)-fake_idle_start_time < 3*60)? 5 : 60; pthread_mutex_lock(&imap->watch_condmutex); int r = 0; struct timespec wakeup_at; memset(&wakeup_at, 0, sizeof(wakeup_at)); wakeup_at.tv_sec = time(NULL)+seconds_to_wait; while (imap->watch_condflag==0 && r==0) { r = pthread_cond_timedwait(&imap->watch_cond, &imap->watch_condmutex, &wakeup_at); /* unlock mutex -> wait -> lock mutex */ if (imap->watch_condflag) { do_fake_idle = 0; } } imap->watch_condflag = 0; pthread_mutex_unlock(&imap->watch_condmutex); if (do_fake_idle==0) { return; } // check for new messages. fetch_from_single_folder() has the side-effect that messages // are also downloaded, however, typically this would take place in the FETCH command // following IDLE otherwise, so this seems okay here. if (setup_handle_if_needed(imap)) { // the handle may not be set up if configure is not yet done if (fetch_from_single_folder(imap, imap->watch_folder)) { do_fake_idle = 0; } } else { // if we cannot connect, set the starting time to a small value which will // result in larger timeouts (60 instead of 5 seconds) for re-checking the availablility of network. // to get the _exact_ moment of re-available network, the ui should call interrupt_idle() fake_idle_start_time = 0; } } } void dc_imap_idle(dc_imap_t* imap) { int r = 0; int r2 = 0; if (imap==NULL) { goto cleanup; } if (imap->can_idle) { setup_handle_if_needed(imap); if (imap->idle_set_up==0 && imap->etpan && imap->etpan->imap_stream) { r = mailstream_setup_idle(imap->etpan->imap_stream); if (dc_imap_is_error(imap, r)) { dc_log_warning(imap->context, 0, "IMAP-IDLE: Cannot setup."); fake_idle(imap); goto cleanup; } imap->idle_set_up = 1; } if (!imap->idle_set_up || !select_folder(imap, imap->watch_folder)) { dc_log_warning(imap->context, 0, "IMAP-IDLE not setup."); fake_idle(imap); goto cleanup; } r = mailimap_idle(imap->etpan); if (dc_imap_is_error(imap, r)) { dc_log_warning(imap->context, 0, "IMAP-IDLE: Cannot start."); fake_idle(imap); goto cleanup; } // most servers do not allow more than ~28 minutes; stay clearly below that. // a good value that is also used by other MUAs is 23 minutes. // if needed, the ui can call dc_imap_interrupt_idle() to trigger a reconnect. #define IDLE_DELAY_SECONDS (23*60) r = mailstream_wait_idle(imap->etpan->imap_stream, IDLE_DELAY_SECONDS); r2 = mailimap_idle_done(imap->etpan); if (r==MAILSTREAM_IDLE_ERROR /*0*/ || r==MAILSTREAM_IDLE_CANCELLED /*4*/) { dc_log_info(imap->context, 0, "IMAP-IDLE wait cancelled, r=%i, r2=%i; we'll reconnect soon.", r, r2); imap->should_reconnect = 1; } else if (r==MAILSTREAM_IDLE_INTERRUPTED /*1*/) { dc_log_info(imap->context, 0, "IMAP-IDLE interrupted."); } else if (r== MAILSTREAM_IDLE_HASDATA /*2*/) { dc_log_info(imap->context, 0, "IMAP-IDLE has data."); } else if (r==MAILSTREAM_IDLE_TIMEOUT /*3*/) { dc_log_info(imap->context, 0, "IMAP-IDLE timeout."); } else { dc_log_warning(imap->context, 0, "IMAP-IDLE returns unknown value r=%i, r2=%i.", r, r2); } } else { fake_idle(imap); } cleanup: ; } void dc_imap_interrupt_idle(dc_imap_t* imap) { if (imap==NULL) { return; } if (imap->can_idle) { if (imap->etpan && imap->etpan->imap_stream) { mailstream_interrupt_idle(imap->etpan->imap_stream); } } // always signal the fake-idle as it may be used if the real-idle is not available for any reasons (no network ...) pthread_mutex_lock(&imap->watch_condmutex); imap->watch_condflag = 1; pthread_cond_signal(&imap->watch_cond); pthread_mutex_unlock(&imap->watch_condmutex); } /******************************************************************************* * Setup handle ******************************************************************************/ static int setup_handle_if_needed(dc_imap_t* imap) { int r = 0; int success = 0; if (imap==NULL || imap->imap_server==NULL) { goto cleanup; } if (imap->should_reconnect) { unsetup_handle(imap); } if (imap->etpan) { success = 1; goto cleanup; } imap->etpan = mailimap_new(0, NULL); mailimap_set_timeout(imap->etpan, DC_IMAP_TIMEOUT_SEC); if (imap->server_flags&(DC_LP_IMAP_SOCKET_STARTTLS|DC_LP_IMAP_SOCKET_PLAIN)) { r = mailimap_socket_connect(imap->etpan, imap->imap_server, imap->imap_port); if (dc_imap_is_error(imap, r)) { dc_log_event_seq(imap->context, DC_EVENT_ERROR_NETWORK, &imap->log_connect_errors, "Could not connect to IMAP-server %s:%i. (Error #%i)", imap->imap_server, (int)imap->imap_port, (int)r); goto cleanup; } if (imap->server_flags&DC_LP_IMAP_SOCKET_STARTTLS) { r = mailimap_socket_starttls(imap->etpan); if (dc_imap_is_error(imap, r)) { dc_log_event_seq(imap->context, DC_EVENT_ERROR_NETWORK, &imap->log_connect_errors, "Could not connect to IMAP-server %s:%i using STARTTLS. (Error #%i)", imap->imap_server, (int)imap->imap_port, (int)r); goto cleanup; } dc_log_info(imap->context, 0, "IMAP-server %s:%i STARTTLS-connected.", imap->imap_server, (int)imap->imap_port); } else { dc_log_info(imap->context, 0, "IMAP-server %s:%i connected.", imap->imap_server, (int)imap->imap_port); } } else { r = mailimap_ssl_connect(imap->etpan, imap->imap_server, imap->imap_port); if (dc_imap_is_error(imap, r)) { dc_log_event_seq(imap->context, DC_EVENT_ERROR_NETWORK, &imap->log_connect_errors, "Could not connect to IMAP-server %s:%i using SSL. (Error #%i)", imap->imap_server, (int)imap->imap_port, (int)r); goto cleanup; } dc_log_info(imap->context, 0, "IMAP-server %s:%i SSL-connected.", imap->imap_server, (int)imap->imap_port); } /* from mailcore2/MCIMAPSession.cpp */ if (imap->server_flags&DC_LP_AUTH_OAUTH2) { // for DC_LP_AUTH_OAUTH2, user_pw is assumed to be the oauth_token dc_log_info(imap->context, 0, "IMAP-OAuth2 connect..."); char* access_token = dc_get_oauth2_access_token(imap->context, imap->addr, imap->imap_pw, 0); r = mailimap_oauth2_authenticate(imap->etpan, imap->imap_user, access_token); if (dc_imap_is_error(imap, r)) { free(access_token); access_token = dc_get_oauth2_access_token(imap->context, imap->addr, imap->imap_pw, DC_REGENERATE); r = mailimap_oauth2_authenticate(imap->etpan, imap->imap_user, access_token); } free(access_token); } else { /* DC_LP_AUTH_NORMAL or no auth flag set */ r = mailimap_login(imap->etpan, imap->imap_user, imap->imap_pw); } if (dc_imap_is_error(imap, r)) { char* msg = get_error_msg(imap, "Cannot login", r); dc_log_event_seq(imap->context, DC_EVENT_ERROR_NETWORK, &imap->log_connect_errors, "%s", msg); free(msg); goto cleanup; } dc_log_event(imap->context, DC_EVENT_IMAP_CONNECTED, 0, "IMAP-login as %s ok.", imap->imap_user); success = 1; cleanup: if (success==0) { unsetup_handle(imap); } imap->should_reconnect = 0; return success; } static void unsetup_handle(dc_imap_t* imap) { if (imap==NULL) { return; } if (imap->etpan) { if (imap->idle_set_up) { mailstream_unsetup_idle(imap->etpan->imap_stream); imap->idle_set_up = 0; } if (imap->etpan->imap_stream!=NULL) { mailstream_close(imap->etpan->imap_stream); /* not sure, if this is really needed, however, mailcore2 does the same */ imap->etpan->imap_stream = NULL; } mailimap_free(imap->etpan); imap->etpan = NULL; dc_log_info(imap->context, 0, "IMAP disconnected."); } imap->selected_folder[0] = 0; /* we leave sent_folder set; normally this does not change in a normal reconnect; we'll update this folder if we get errors */ } /******************************************************************************* * Connect/Disconnect ******************************************************************************/ static void free_connect_param(dc_imap_t* imap) { free(imap->addr); imap->addr = NULL; free(imap->imap_server); imap->imap_server = NULL; free(imap->imap_user); imap->imap_user = NULL; free(imap->imap_pw); imap->imap_pw = NULL; imap->watch_folder[0] = 0; imap->selected_folder[0] = 0; imap->imap_port = 0; imap->can_idle = 0; imap->has_xlist = 0; } int dc_imap_connect(dc_imap_t* imap, const dc_loginparam_t* lp) { int success = 0; if (imap==NULL || lp==NULL || lp->mail_server==NULL || lp->mail_user==NULL || lp->mail_pw==NULL) { return 0; } if (imap->connected) { success = 1; goto cleanup; } imap->addr = dc_strdup(lp->addr); imap->imap_server = dc_strdup(lp->mail_server); imap->imap_port = lp->mail_port; imap->imap_user = dc_strdup(lp->mail_user); imap->imap_pw = dc_strdup(lp->mail_pw); imap->server_flags = lp->server_flags; if (!setup_handle_if_needed(imap)) { goto cleanup; } /* we set the following flags here and not in setup_handle_if_needed() as they must not change during connection */ imap->can_idle = mailimap_has_idle(imap->etpan); imap->has_xlist = mailimap_has_xlist(imap->etpan); #ifdef __APPLE__ imap->can_idle = 0; // HACK to force iOS not to work IMAP-IDLE which does not work for now, see also (*) #endif if (!imap->skip_log_capabilities && imap->etpan->imap_connection_info && imap->etpan->imap_connection_info->imap_capability) { /* just log the whole capabilities list (the mailimap_has_*() function also use this list, so this is a good overview on problems) */ imap->skip_log_capabilities = 1; dc_strbuilder_t capinfostr; dc_strbuilder_init(&capinfostr, 0); clist* list = imap->etpan->imap_connection_info->imap_capability->cap_list; if (list) { clistiter* cur; for(cur = clist_begin(list) ; cur!=NULL ; cur = clist_next(cur)) { struct mailimap_capability * cap = clist_content(cur); if (cap && cap->cap_type==MAILIMAP_CAPABILITY_NAME) { dc_strbuilder_cat(&capinfostr, " "); dc_strbuilder_cat(&capinfostr, cap->cap_data.cap_name); } } } dc_log_info(imap->context, 0, "IMAP-capabilities:%s", capinfostr.buf); free(capinfostr.buf); } imap->connected = 1; success = 1; cleanup: if (success==0) { unsetup_handle(imap); free_connect_param(imap); } return success; } void dc_imap_disconnect(dc_imap_t* imap) { if (imap==NULL) { return; } if (imap->connected) { unsetup_handle(imap); free_connect_param(imap); imap->connected = 0; } } int dc_imap_is_connected(const dc_imap_t* imap) { return (imap && imap->connected); } void dc_imap_set_watch_folder(dc_imap_t* imap, const char* watch_folder) { if (imap==NULL || watch_folder==NULL) { return; } free(imap->watch_folder); imap->watch_folder = dc_strdup(watch_folder); } /******************************************************************************* * Main interface ******************************************************************************/ dc_imap_t* dc_imap_new(dc_get_config_t get_config, dc_set_config_t set_config, dc_precheck_imf_t precheck_imf, dc_receive_imf_t receive_imf, void* userData, dc_context_t* context) { dc_imap_t* imap = NULL; if ((imap=calloc(1, sizeof(dc_imap_t)))==NULL) { exit(25); /* cannot allocate little memory, unrecoverable error */ } imap->log_connect_errors = 1; imap->context = context; imap->get_config = get_config; imap->set_config = set_config; imap->precheck_imf = precheck_imf; imap->receive_imf = receive_imf; imap->userData = userData; pthread_mutex_init(&imap->watch_condmutex, NULL); pthread_cond_init(&imap->watch_cond, NULL); //imap->enter_watch_wait_time = 0; imap->watch_folder = calloc(1, 1); imap->selected_folder = calloc(1, 1); /* create some useful objects */ // object to fetch UID and Message-Id // // TODO: we're using `FETCH ... (... ENVELOPE)` currently, // mainly because peek_rfc724_mid() can handle this structure // and it is easier wrt to libEtPan. // however, if the other ENVELOPE fields are known to be not needed in the near future, // this could be changed to `FETCH ... (... BODY[HEADER.FIELDS (MESSAGE-ID)])` imap->fetch_type_prefetch = mailimap_fetch_type_new_fetch_att_list_empty(); mailimap_fetch_type_new_fetch_att_list_add(imap->fetch_type_prefetch, mailimap_fetch_att_new_uid()); mailimap_fetch_type_new_fetch_att_list_add(imap->fetch_type_prefetch, mailimap_fetch_att_new_envelope()); // object to fetch flags and body imap->fetch_type_body = mailimap_fetch_type_new_fetch_att_list_empty(); mailimap_fetch_type_new_fetch_att_list_add(imap->fetch_type_body, mailimap_fetch_att_new_flags()); mailimap_fetch_type_new_fetch_att_list_add(imap->fetch_type_body, mailimap_fetch_att_new_body_peek_section(mailimap_section_new(NULL))); // object to fetch flags only imap->fetch_type_flags = mailimap_fetch_type_new_fetch_att_list_empty(); mailimap_fetch_type_new_fetch_att_list_add(imap->fetch_type_flags, mailimap_fetch_att_new_flags()); return imap; } void dc_imap_unref(dc_imap_t* imap) { if (imap==NULL) { return; } dc_imap_disconnect(imap); pthread_cond_destroy(&imap->watch_cond); pthread_mutex_destroy(&imap->watch_condmutex); free(imap->watch_folder); free(imap->selected_folder); if (imap->fetch_type_prefetch) { mailimap_fetch_type_free(imap->fetch_type_prefetch); } if (imap->fetch_type_body) { mailimap_fetch_type_free(imap->fetch_type_body); } if (imap->fetch_type_flags) { mailimap_fetch_type_free(imap->fetch_type_flags); } free(imap); } static int add_flag(dc_imap_t* imap, uint32_t server_uid, struct mailimap_flag* flag) { int r = 0; struct mailimap_flag_list* flag_list = NULL; struct mailimap_store_att_flags* store_att_flags = NULL; struct mailimap_set* set = mailimap_set_new_single(server_uid); if (imap==NULL || imap->etpan==NULL) { goto cleanup; } flag_list = mailimap_flag_list_new_empty(); mailimap_flag_list_add(flag_list, flag); store_att_flags = mailimap_store_att_flags_new_add_flags(flag_list); /* FLAGS.SILENT does not return the new value */ r = mailimap_uid_store(imap->etpan, set, store_att_flags); if (dc_imap_is_error(imap, r)) { goto cleanup; } cleanup: if (store_att_flags) { mailimap_store_att_flags_free(store_att_flags); } FREE_SET(set); return imap->should_reconnect? 0 : 1; /* all non-connection states are treated as success - the mail may already be deleted or moved away on the server */ } dc_imap_res dc_imap_move(dc_imap_t* imap, const char* folder, uint32_t uid, const char* dest_folder, uint32_t* dest_uid) { dc_imap_res res = DC_RETRY_LATER; int r = 0; struct mailimap_set* set = mailimap_set_new_single(uid); uint32_t res_uid = 0; struct mailimap_set* res_setsrc = NULL; struct mailimap_set* res_setdest = NULL; if (imap==NULL || folder==NULL || uid==0 || dest_folder==NULL || dest_uid==NULL || set==NULL) { res = DC_FAILED; goto cleanup; } if (strcasecmp(folder, dest_folder)==0) { dc_log_info(imap->context, 0, "Skip moving message; message %s/%i is already in %s...", folder, (int)uid, dest_folder); res = DC_ALREADY_DONE; goto cleanup; } dc_log_info(imap->context, 0, "Moving message %s/%i to %s...", folder, (int)uid, dest_folder); if (select_folder(imap, folder)==0) { dc_log_warning(imap->context, 0, "Cannot select folder %s for moving message.", folder); goto cleanup; } /* TODO/TOCHECK: UIDPLUS extension may not be supported on servers; if in doubt, we can find out the resulting UID using "imap_selection_info->sel_uidnext" then */ r = mailimap_uidplus_uid_move(imap->etpan, set, dest_folder, &res_uid, &res_setsrc, &res_setdest); if (dc_imap_is_error(imap, r)) { FREE_SET(res_setsrc); FREE_SET(res_setdest); dc_log_info(imap->context, 0, "Cannot move message, fallback to COPY/DELETE %s/%i to %s...", folder, (int)uid, dest_folder); r = mailimap_uidplus_uid_copy(imap->etpan, set, dest_folder, &res_uid, &res_setsrc, &res_setdest); if (dc_imap_is_error(imap, r)) { dc_log_info(imap->context, 0, "Cannot copy message."); goto cleanup; } else { if (add_flag(imap, uid, mailimap_flag_new_deleted())==0) { dc_log_warning(imap->context, 0, "Cannot mark message as \"Deleted\"."); } // force an EXPUNGE resp. CLOSE for the selected folder imap->selected_folder_needs_expunge = 1; } } if (res_setdest) { clistiter* cur = clist_begin(res_setdest->set_list); if (cur!=NULL) { struct mailimap_set_item* item; item = clist_content(cur); *dest_uid = item->set_first; } } res = DC_SUCCESS; cleanup: FREE_SET(set); FREE_SET(res_setsrc); FREE_SET(res_setdest); return res==DC_RETRY_LATER? (imap->should_reconnect? DC_RETRY_LATER : DC_FAILED) : res; } dc_imap_res dc_imap_set_seen(dc_imap_t* imap, const char* folder, uint32_t uid) { dc_imap_res res = DC_RETRY_LATER; if (imap==NULL || folder==NULL || uid==0) { res = DC_FAILED; goto cleanup; } if (imap->etpan==NULL) { goto cleanup; } dc_log_info(imap->context, 0, "Marking message %s/%i as seen...", folder, (int)uid); if (select_folder(imap, folder)==0) { dc_log_warning(imap->context, 0, "Cannot select folder %s for setting SEEN flag.", folder); goto cleanup; } if (add_flag(imap, uid, mailimap_flag_new_seen())==0) { dc_log_warning(imap->context, 0, "Cannot mark message as seen."); goto cleanup; } res = DC_SUCCESS; cleanup: return res==DC_RETRY_LATER? (imap->should_reconnect? DC_RETRY_LATER : DC_FAILED) : res; } dc_imap_res dc_imap_set_mdnsent(dc_imap_t* imap, const char* folder, uint32_t uid) { // returns 0=job should be retried later, 1=job done, 2=job done and flag just set dc_imap_res res = DC_RETRY_LATER; struct mailimap_set* set = mailimap_set_new_single(uid); clist* fetch_result = NULL; if (imap==NULL || folder==NULL || uid==0 || set==NULL) { res = DC_FAILED; goto cleanup; } if (imap->etpan==NULL) { goto cleanup; } dc_log_info(imap->context, 0, "Marking message %s/%i as $MDNSent...", folder, (int)uid); if (select_folder(imap, folder)==0) { dc_log_warning(imap->context, 0, "Cannot select folder %s for setting $MDNSent flag.", folder); goto cleanup; } /* Check if the folder can handle the `$MDNSent` flag (see RFC 3503). If so, and not set: set the flags and return this information. If the folder cannot handle the `$MDNSent` flag, we risk duplicated MDNs; it's up to the receiving MUA to handle this then (eg. Delta Chat has no problem with this). */ int can_create_flag = 0; if (imap->etpan->imap_selection_info!=NULL && imap->etpan->imap_selection_info->sel_perm_flags!=NULL) { clistiter* iter; for (iter=clist_begin(imap->etpan->imap_selection_info->sel_perm_flags); iter!=NULL; iter=clist_next(iter)) { struct mailimap_flag_perm* fp = (struct mailimap_flag_perm*)clist_content(iter); if (fp) { if (fp->fl_type==MAILIMAP_FLAG_PERM_ALL) { can_create_flag = 1; break; } else if (fp->fl_type==MAILIMAP_FLAG_PERM_FLAG && fp->fl_flag) { struct mailimap_flag* fl = (struct mailimap_flag*)fp->fl_flag; if (fl->fl_type==MAILIMAP_FLAG_KEYWORD && fl->fl_data.fl_keyword && strcmp(fl->fl_data.fl_keyword, "$MDNSent")==0) { can_create_flag = 1; break; } } } } } if (can_create_flag) { int r = mailimap_uid_fetch(imap->etpan, set, imap->fetch_type_flags, &fetch_result); if (dc_imap_is_error(imap, r) || fetch_result==NULL) { fetch_result = NULL; goto cleanup; } clistiter* cur=clist_begin(fetch_result); if (cur==NULL) { goto cleanup; } if (peek_flag_keyword((struct mailimap_msg_att*)clist_content(cur), "$MDNSent")) { res = DC_ALREADY_DONE; } else { if (add_flag(imap, uid, mailimap_flag_new_flag_keyword(dc_strdup("$MDNSent")))==0) { goto cleanup; } res = DC_SUCCESS; } dc_log_info(imap->context, 0, res==DC_SUCCESS? "$MDNSent just set and MDN will be sent." : "$MDNSent already set and MDN already sent."); } else { res = DC_SUCCESS; dc_log_info(imap->context, 0, "Cannot store $MDNSent flags, risk sending duplicate MDN."); } cleanup: FREE_SET(set); FREE_FETCH_LIST(fetch_result); return res==DC_RETRY_LATER? (imap->should_reconnect? DC_RETRY_LATER : DC_FAILED) : res; } int dc_imap_delete_msg(dc_imap_t* imap, const char* rfc724_mid, const char* folder, uint32_t server_uid) { int success = 0; int r = 0; clist* fetch_result = NULL; char* is_rfc724_mid = NULL; char* new_folder = NULL; if (imap==NULL || rfc724_mid==NULL || folder==NULL || folder[0]==0 || server_uid==0) { success = 1; /* job done, do not try over */ goto cleanup; } dc_log_info(imap->context, 0, "Marking message \"%s\", %s/%i for deletion...", rfc724_mid, folder, (int)server_uid); if (select_folder(imap, folder)==0) { dc_log_warning(imap->context, 0, "Cannot select folder %s for deleting message.", folder); goto cleanup; } /* check if Folder+UID matches the Message-ID (to detect if the messages was moved around by other MUAs and in place of an UIDVALIDITY check) */ { clistiter* cur = NULL; const char* is_quoted_rfc724_mid = NULL; struct mailimap_set* set = mailimap_set_new_single(server_uid); r = mailimap_uid_fetch(imap->etpan, set, imap->fetch_type_prefetch, &fetch_result); FREE_SET(set); if (dc_imap_is_error(imap, r) || fetch_result==NULL) { fetch_result = NULL; dc_log_warning(imap->context, 0, "Cannot delete on IMAP, %s/%i not found.", folder, (int)server_uid); server_uid = 0; } if( (cur=clist_begin(fetch_result))==NULL || (is_quoted_rfc724_mid=peek_rfc724_mid((struct mailimap_msg_att*)clist_content(cur)))==NULL || (is_rfc724_mid=unquote_rfc724_mid(is_quoted_rfc724_mid))==NULL || strcmp(is_rfc724_mid, rfc724_mid)!=0) { dc_log_warning(imap->context, 0, "Cannot delete on IMAP, %s/%i does not match %s.", folder, (int)server_uid, rfc724_mid); server_uid = 0; } } /* mark the message for deletion */ if (add_flag(imap, server_uid, mailimap_flag_new_deleted())==0) { dc_log_warning(imap->context, 0, "Cannot mark message as \"Deleted\"."); /* maybe the message is already deleted */ goto cleanup; } /* force an EXPUNGE resp. CLOSE for the selected folder */ imap->selected_folder_needs_expunge = 1; success = 1; cleanup: FREE_FETCH_LIST(fetch_result); free(is_rfc724_mid); free(new_folder); return success? 1 : dc_imap_is_connected(imap); /* only return 0 on connection problems; we should try later again in this case */ } void dc_imap_empty_folder(dc_imap_t* imap, const char* folder) { struct mailimap_flag_list* flag_list = NULL; struct mailimap_store_att_flags* store_att_flags = NULL; struct mailimap_set* set = NULL; if (imap==NULL || folder==NULL || folder[0]==0) { goto cleanup; } dc_log_info(imap->context, 0, "Emptying folder \"%s\" ...", folder); if (select_folder(imap, folder)==0) { dc_log_warning(imap->context, 0, "Cannot select folder %s for emptying.", folder); goto cleanup; } set = mailimap_set_new_interval(1/*start with smallest uid*/, 0/*0=`*`=largets uid*/); flag_list = mailimap_flag_list_new_empty(); mailimap_flag_list_add(flag_list, mailimap_flag_new_deleted()); store_att_flags = mailimap_store_att_flags_new_add_flags(flag_list); /* FLAGS.SILENT does not return the new value */ mailimap_uid_store(imap->etpan, set, store_att_flags); imap->selected_folder_needs_expunge = 1; select_folder(imap, NULL); dc_log_info(imap->context, 0, "Emptying folder \"%s\" done.", folder); cleanup: if (store_att_flags) { mailimap_store_att_flags_free(store_att_flags); } FREE_SET(set); } ``` Filename: dc_imex.c ```c #include #include #include /* for sleep() */ #include #include #include "dc_context.h" #include "dc_mimeparser.h" #include "dc_loginparam.h" #include "dc_aheader.h" #include "dc_apeerstate.h" #include "dc_pgp.h" #include "dc_mimefactory.h" #include "dc_job.h" /** * @name Import/Export * @{ */ /******************************************************************************* * Autocrypt Key Transfer ******************************************************************************/ /** * Create an Autocrypt Setup Message. A complete Autocrypt Setup Message looks * like the following: * * To: me@mydomain.com * From: me@mydomain.com * Autocrypt-Setup-Message: v1 * Content-type: multipart/mixed; boundary="==break1==" * * --==break1== * Content-Type: text/plain * * This is the Autocrypt setup message. * * --==break1== * Content-Type: application/autocrypt-setup * Content-Disposition: attachment; filename="autocrypt-setup-message.html" * * * *

* This is the Autocrypt Setup File used to transfer keys between clients. *

*
 *     -----BEGIN PGP MESSAGE-----
 *     Version: BCPG v1.53
 *     Passphrase-Format: numeric9x4
 *     Passphrase-Begin: 12
 *
 *     hQIMAxC7JraDy7DVAQ//SK1NltM+r6uRf2BJEg+rnpmiwfAEIiopU0LeOQ6ysmZ0
 *     CLlfUKAcryaxndj4sBsxLllXWzlNiFDHWw4OOUEZAZd8YRbOPfVq2I8+W4jO3Moe
 *     -----END PGP MESSAGE-----
 *     
* * * --==break1==-- * * The encrypted message part contains: * * -----BEGIN PGP PRIVATE KEY BLOCK----- * Autocrypt-Prefer-Encrypt: mutual * * xcLYBFke7/8BCAD0TTmX9WJm9elc7/xrT4/lyzUDMLbuAuUqRINtCoUQPT2P3Snfx/jou1YcmjDgwT * Ny9ddjyLcdSKL/aR6qQ1UBvlC5xtriU/7hZV6OZEmW2ckF7UgGd6ajE+UEjUwJg2+eKxGWFGuZ1P7a * 4Av1NXLayZDsYa91RC5hCsj+umLN2s+68ps5pzLP3NoK2zIFGoCRncgGI/pTAVmYDirhVoKh14hCh5 * ..... * -----END PGP PRIVATE KEY BLOCK----- * * dc_render_setup_file() renders the body after the second * `-==break1==` in this example. * * @private @memberof dc_context_t * @param context The context object * @param passphrase The setup code that shall be used to encrypt the message. * Typically created by dc_create_setup_code(). * @return String with the HTML-code of the message on success, NULL on errors. * The returned value must be free()'d */ char* dc_render_setup_file(dc_context_t* context, const char* passphrase) { sqlite3_stmt* stmt = NULL; char* self_addr = NULL; dc_key_t* curr_private_key = dc_key_new(); char passphrase_begin[8]; char* encr_string = NULL; char* ret_setupfilecontent = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || passphrase==NULL || strlen(passphrase)<2 || curr_private_key==NULL) { goto cleanup; } strncpy(passphrase_begin, passphrase, 2); passphrase_begin[2] = 0; /* create the payload */ if (!dc_ensure_secret_key_exists(context)) { goto cleanup; } { self_addr = dc_sqlite3_get_config(context->sql, "configured_addr", NULL); dc_key_load_self_private(curr_private_key, self_addr, context->sql); int e2ee_enabled = dc_sqlite3_get_config_int(context->sql, "e2ee_enabled", DC_E2EE_DEFAULT_ENABLED); char* payload_key_asc = dc_key_render_asc(curr_private_key, e2ee_enabled? "Autocrypt-Prefer-Encrypt: mutual\r\n" : NULL); if (payload_key_asc==NULL) { goto cleanup; } if(!dc_pgp_symm_encrypt(context, passphrase, payload_key_asc, strlen(payload_key_asc), &encr_string)) { goto cleanup; } free(payload_key_asc); } /* add additional header to armored block */ #define LINEEND "\r\n" /* use the same lineends as the PGP armored data */ { char* replacement = dc_mprintf("-----BEGIN PGP MESSAGE-----" LINEEND "Passphrase-Format: numeric9x4" LINEEND "Passphrase-Begin: %s", passphrase_begin); dc_str_replace(&encr_string, "-----BEGIN PGP MESSAGE-----", replacement); free(replacement); } /* wrap HTML-commands with instructions around the encrypted payload */ { char* setup_message_title = dc_stock_str(context, DC_STR_AC_SETUP_MSG_SUBJECT); char* setup_message_body = dc_stock_str(context, DC_STR_AC_SETUP_MSG_BODY); dc_str_replace(&setup_message_body, "\r", NULL); dc_str_replace(&setup_message_body, "\n", "
"); ret_setupfilecontent = dc_mprintf( "" LINEEND "" LINEEND "" LINEEND "%s" LINEEND "" LINEEND "" LINEEND "

%s

" LINEEND "

%s

" LINEEND "
" LINEEND
					"%s" LINEEND
					"
" LINEEND "" LINEEND "" LINEEND, setup_message_title, setup_message_title, setup_message_body, encr_string); free(setup_message_title); free(setup_message_body); } cleanup: sqlite3_finalize(stmt); dc_key_unref(curr_private_key); free(encr_string); free(self_addr); return ret_setupfilecontent; } /** * Parse the given file content and extract the private key. * * @private @memberof dc_context_t * @param context The context object * @param passphrase The setup code that shall be used to decrypt the message. * May be created by dc_create_setup_code() on another device or by * a completely different app as Thunderbird/Enigmail or K-9. * @param filecontent The file content of the setup message, may be HTML. * May be created by dc_render_setup_code() on another device or by * a completely different app as Thunderbird/Enigmail or K-9. * @return The decrypted private key as armored-ascii-data or NULL on errors. * Must be dc_key_unref()'d. */ char* dc_decrypt_setup_file(dc_context_t* context, const char* passphrase, const char* filecontent) { char* fc_buf = NULL; const char* fc_headerline = NULL; const char* fc_base64 = NULL; char* binary = NULL; size_t binary_bytes = 0; size_t indx = 0; void* plain = NULL; size_t plain_bytes = 0; char* payload = NULL; /* extract base64 from filecontent */ fc_buf = dc_strdup(filecontent); if (!dc_split_armored_data(fc_buf, &fc_headerline, NULL, NULL, &fc_base64) || fc_headerline==NULL || strcmp(fc_headerline, "-----BEGIN PGP MESSAGE-----")!=0 || fc_base64==NULL) { goto cleanup; } /* convert base64 to binary */ if (mailmime_base64_body_parse(fc_base64, strlen(fc_base64), &indx, &binary/*must be freed using mmap_string_unref()*/, &binary_bytes)!=MAILIMF_NO_ERROR || binary==NULL || binary_bytes==0) { goto cleanup; } /* decrypt symmetrically */ if (!dc_pgp_symm_decrypt(context, passphrase, binary, binary_bytes, &plain, &plain_bytes)) { goto cleanup; } payload = strndup((const char*)plain, plain_bytes); cleanup: free(plain); free(fc_buf); if (binary) { mmap_string_unref(binary); } return payload; } /** * Create random setup code. * * The created "Autocrypt Level 1" setup code has the form `1234-1234-1234-1234-1234-1234-1234-1234-1234`. * Linebreaks and spaces are not added to the setup code, but the `-` are. * The setup code is typically given to dc_render_setup_file(). * * A higher-level function to initiate the key transfer is dc_initiate_key_transfer(). * * @private @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return Setup code, must be free()'d after usage. NULL on errors. */ char* dc_create_setup_code(dc_context_t* context) { #define CODE_ELEMS 9 uint16_t random_val = 0; int i = 0; dc_strbuilder_t ret; dc_strbuilder_init(&ret, 0); for (i = 0; i < CODE_ELEMS; i++) { do { if (!RAND_bytes((unsigned char*)&random_val, sizeof(uint16_t))) { dc_log_warning(context, 0, "Falling back to pseudo-number generation for the setup code."); RAND_pseudo_bytes((unsigned char*)&random_val, sizeof(uint16_t)); } } while (random_val > 60000); /* make sure the modulo below does not reduce entropy (range is 0..65535, a module 10000 would make appearing values <=535 one time more often than other values) */ random_val = random_val % 10000; /* force all blocks into the range 0..9999 */ dc_strbuilder_catf(&ret, "%s%04i", i?"-":"", (int)random_val); } return ret.buf; } /* Function remove all special characters from the given code and brings it to the 9x4 form */ char* dc_normalize_setup_code(dc_context_t* context, const char* in) { if (in==NULL) { return NULL; } dc_strbuilder_t out; dc_strbuilder_init(&out, 0); int outlen = 0; const char* p1 = in; while (*p1) { if (*p1 >= '0' && *p1 <= '9') { dc_strbuilder_catf(&out, "%c", *p1); outlen = strlen(out.buf); if (outlen==4 || outlen==9 || outlen==14 || outlen==19 || outlen==24 || outlen==29 || outlen==34 || outlen==39) { dc_strbuilder_cat(&out, "-"); } } p1++; } return out.buf; } /** * Initiate Autocrypt Setup Transfer. * Before starting the setup transfer with this function, the user should be asked: * * ~~~ * "An 'Autocrypt Setup Message' securely shares your end-to-end setup with other Autocrypt-compliant apps. * The setup will be encrypted by a setup code which is displayed here and must be typed on the other device. * ~~~ * * After that, this function should be called to send the Autocrypt Setup Message. * The function creates the setup message and waits until it is really sent. * As this may take a while, it is recommended to start the function in a separate thread; * to interrupt it, you can use dc_stop_ongoing_process(). * * After everything succeeded, the required setup code is returned in the following format: * * ~~~ * 1234-1234-1234-1234-1234-1234-1234-1234-1234 * ~~~ * * The setup code should be shown to the user then: * * ~~~ * "Your key has been sent to yourself. Switch to the other device and * open the setup message. You should be prompted for a setup code. Type * the following digits into the prompt: * * 1234 - 1234 - 1234 - * 1234 - 1234 - 1234 - * 1234 - 1234 - 1234 * * Once you're done, your other device will be ready to use Autocrypt." * ~~~ * * On the _other device_ you will call dc_continue_key_transfer() then * for setup messages identified by dc_msg_is_setupmessage(). * * For more details about the Autocrypt setup process, please refer to * https://autocrypt.org/en/latest/level1.html#autocrypt-setup-message * * @memberof dc_context_t * @param context The context object. * @return The setup code. Must be free()'d after usage. * On errors, eg. if the message could not be sent, NULL is returned. */ char* dc_initiate_key_transfer(dc_context_t* context) { int success = 0; char* setup_code = NULL; char* setup_file_content = NULL; char* setup_file_name = NULL; uint32_t chat_id = 0; dc_msg_t* msg = NULL; uint32_t msg_id = 0; if (!dc_alloc_ongoing(context)) { return 0; /* no cleanup as this would call dc_free_ongoing() */ } #define CHECK_EXIT if (context->shall_stop_ongoing) { goto cleanup; } if ((setup_code=dc_create_setup_code(context))==NULL) { /* this may require a keypair to be created. this may take a second ... */ goto cleanup; } CHECK_EXIT if ((setup_file_content=dc_render_setup_file(context, setup_code))==NULL) { /* encrypting may also take a while ... */ goto cleanup; } CHECK_EXIT if ((setup_file_name=dc_get_fine_pathNfilename(context, "$BLOBDIR", "autocrypt-setup-message.html"))==NULL || !dc_write_file(context, setup_file_name, setup_file_content, strlen(setup_file_content))) { goto cleanup; } if ((chat_id=dc_create_chat_by_contact_id(context, DC_CONTACT_ID_SELF))==0) { goto cleanup; } msg = dc_msg_new_untyped(context); msg->type = DC_MSG_FILE; dc_param_set (msg->param, DC_PARAM_FILE, setup_file_name); dc_param_set (msg->param, DC_PARAM_MIMETYPE, "application/autocrypt-setup"); dc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_AUTOCRYPT_SETUP_MESSAGE); dc_param_set_int(msg->param, DC_PARAM_FORCE_PLAINTEXT, DC_FP_NO_AUTOCRYPT_HEADER); CHECK_EXIT if ((msg_id = dc_send_msg(context, chat_id, msg))==0) { goto cleanup; } dc_msg_unref(msg); msg = NULL; /* wait until the message is really sent */ dc_log_info(context, 0, "Wait for setup message being sent ..."); while (1) { CHECK_EXIT sleep(1); msg = dc_get_msg(context, msg_id); if (dc_msg_is_sent(msg)) { break; } dc_msg_unref(msg); msg = NULL; } dc_log_info(context, 0, "... setup message sent."); success = 1; cleanup: if (!success) { free(setup_code); setup_code = NULL; } free(setup_file_name); free(setup_file_content); dc_msg_unref(msg); dc_free_ongoing(context); return setup_code; } static int set_self_key(dc_context_t* context, const char* armored, int set_default) { int success = 0; char* buf = NULL; const char* buf_headerline = NULL; // pointer inside buf, MUST NOT be free()'d const char* buf_preferencrypt = NULL; // - " - const char* buf_base64 = NULL; // - " - dc_key_t* private_key = dc_key_new(); dc_key_t* public_key = dc_key_new(); sqlite3_stmt* stmt = NULL; char* self_addr = NULL; buf = dc_strdup(armored); if (!dc_split_armored_data(buf, &buf_headerline, NULL, &buf_preferencrypt, &buf_base64) || strcmp(buf_headerline, "-----BEGIN PGP PRIVATE KEY BLOCK-----")!=0 || buf_base64==NULL) { dc_log_warning(context, 0, "File does not contain a private key."); /* do not log as error - this is quite normal after entering the bad setup code */ goto cleanup; } if (!dc_key_set_from_base64(private_key, buf_base64, DC_KEY_PRIVATE) || !dc_pgp_is_valid_key(context, private_key) || !dc_pgp_split_key(context, private_key, public_key)) { dc_log_error(context, 0, "File does not contain a valid private key."); goto cleanup; } /* add keypair; before this, delete other keypairs with the same binary key and reset defaults */ stmt = dc_sqlite3_prepare(context->sql, "DELETE FROM keypairs WHERE public_key=? OR private_key=?;"); sqlite3_bind_blob (stmt, 1, public_key->binary, public_key->bytes, SQLITE_STATIC); sqlite3_bind_blob (stmt, 2, private_key->binary, private_key->bytes, SQLITE_STATIC); sqlite3_step(stmt); sqlite3_finalize(stmt); stmt = NULL; if (set_default) { dc_sqlite3_execute(context->sql, "UPDATE keypairs SET is_default=0;"); /* if the new key should be the default key, all other should not */ } self_addr = dc_sqlite3_get_config(context->sql, "configured_addr", NULL); if (!dc_key_save_self_keypair(public_key, private_key, self_addr, set_default, context->sql)) { dc_log_error(context, 0, "Cannot save keypair."); goto cleanup; } /* if we also received an Autocrypt-Prefer-Encrypt header, handle this */ if (buf_preferencrypt) { if (strcmp(buf_preferencrypt, "nopreference")==0) { dc_sqlite3_set_config_int(context->sql, "e2ee_enabled", 0); } else if (strcmp(buf_preferencrypt, "mutual")==0) { dc_sqlite3_set_config_int(context->sql, "e2ee_enabled", 1); } } success = 1; cleanup: sqlite3_finalize(stmt); free(buf); free(self_addr); dc_key_unref(private_key); dc_key_unref(public_key); return success; } /** * Continue the Autocrypt Key Transfer on another device. * * If you have started the key transfer on another device using dc_initiate_key_transfer() * and you've detected a setup message with dc_msg_is_setupmessage(), you should prompt the * user for the setup code and call this function then. * * You can use dc_msg_get_setupcodebegin() to give the user a hint about the code (useful if the user * has created several messages and should not enter the wrong code). * * @memberof dc_context_t * @param context The context object. * @param msg_id ID of the setup message to decrypt. * @param setup_code Setup code entered by the user. This is the same setup code as returned from * dc_initiate_key_transfer() on the other device. * There is no need to format the string correctly, the function will remove all spaces and other characters and * insert the `-` characters at the correct places. * @return 1=key successfully decrypted and imported; both devices will use the same key now; * 0=key transfer failed eg. due to a bad setup code. */ int dc_continue_key_transfer(dc_context_t* context, uint32_t msg_id, const char* setup_code) { int success = 0; dc_msg_t* msg = NULL; char* filename = NULL; char* filecontent = NULL; size_t filebytes = 0; char* armored_key = NULL; char* norm_sc = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg_id <= DC_MSG_ID_LAST_SPECIAL || setup_code==NULL) { goto cleanup; } if ((msg=dc_get_msg(context, msg_id))==NULL || !dc_msg_is_setupmessage(msg) || (filename=dc_msg_get_file(msg))==NULL || filename[0]==0) { dc_log_error(context, 0, "Message is no Autocrypt Setup Message."); goto cleanup; } if (!dc_read_file(context, filename, (void**)&filecontent, &filebytes) || filecontent==NULL || filebytes <= 0) { dc_log_error(context, 0, "Cannot read Autocrypt Setup Message file."); goto cleanup; } if ((norm_sc = dc_normalize_setup_code(context, setup_code))==NULL) { dc_log_warning(context, 0, "Cannot normalize Setup Code."); goto cleanup; } if ((armored_key=dc_decrypt_setup_file(context, norm_sc, filecontent))==NULL) { dc_log_warning(context, 0, "Cannot decrypt Autocrypt Setup Message."); /* do not log as error - this is quite normal after entering the bad setup code */ goto cleanup; } if (!set_self_key(context, armored_key, 1/*set default*/)) { goto cleanup; /* error already logged */ } success = 1; cleanup: free(armored_key); free(filecontent); free(filename); dc_msg_unref(msg); free(norm_sc); return success; } /******************************************************************************* * Classic key export ******************************************************************************/ static int export_key_to_asc_file(dc_context_t* context, const char* dir, int id, const dc_key_t* key, int is_default) { int success = 0; char* file_name = NULL; if (is_default) { file_name = dc_mprintf("%s/%s-key-default.asc", dir, key->type==DC_KEY_PUBLIC? "public" : "private"); } else { file_name = dc_mprintf("%s/%s-key-%i.asc", dir, key->type==DC_KEY_PUBLIC? "public" : "private", id); } dc_log_info(context, 0, "Exporting key %s", file_name); dc_delete_file(context, file_name); if (!dc_key_render_asc_to_file(key, file_name, context)) { dc_log_error(context, 0, "Cannot write key to %s", file_name); goto cleanup; } context->cb(context, DC_EVENT_IMEX_FILE_WRITTEN, (uintptr_t)file_name, 0); success = 1; cleanup: free(file_name); return success; } static int export_self_keys(dc_context_t* context, const char* dir) { int success = 0; int export_errors = 0; sqlite3_stmt* stmt = NULL; int id = 0; int is_default = 0; dc_key_t* public_key = dc_key_new(); dc_key_t* private_key = dc_key_new(); if ((stmt=dc_sqlite3_prepare(context->sql, "SELECT id, public_key, private_key, is_default FROM keypairs;"))==NULL) { goto cleanup; } while (sqlite3_step(stmt)==SQLITE_ROW) { id = sqlite3_column_int( stmt, 0 ); dc_key_set_from_stmt(public_key, stmt, 1, DC_KEY_PUBLIC); dc_key_set_from_stmt(private_key, stmt, 2, DC_KEY_PRIVATE); is_default = sqlite3_column_int( stmt, 3 ); if(!export_key_to_asc_file(context, dir, id, public_key, is_default)) { export_errors++; } if (!export_key_to_asc_file(context, dir, id, private_key, is_default)) { export_errors++; } } if (export_errors==0) { success = 1; } cleanup: sqlite3_finalize(stmt); dc_key_unref(public_key); dc_key_unref(private_key); return success; } /******************************************************************************* * Classic key import ******************************************************************************/ static int import_self_keys(dc_context_t* context, const char* dir_name) { /* hint: even if we switch to import Autocrypt Setup Files, we should leave the possibility to import plain ASC keys, at least keys without a password, if we do not want to implement a password entry function. Importing ASC keys is useful to use keys in Delta Chat used by any other non-Autocrypt-PGP implementation. Maybe we should make the "default" key handlong also a little bit smarter (currently, the last imported key is the standard key unless it contains the string "legacy" in its name) */ int imported_cnt = 0; DIR* dir_handle = NULL; struct dirent* dir_entry = NULL; char* suffix = NULL; char* path_plus_name = NULL; int set_default = 0; char* buf = NULL; size_t buf_bytes = 0; const char* private_key = NULL; // a pointer inside buf, MUST NOT be free()'d char* buf2 = NULL; const char* buf2_headerline = NULL; // a pointer inside buf2, MUST NOT be free()'d if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || dir_name==NULL) { goto cleanup; } if ((dir_handle=opendir(dir_name))==NULL) { dc_log_error(context, 0, "Import: Cannot open directory \"%s\".", dir_name); goto cleanup; } while ((dir_entry=readdir(dir_handle))!=NULL) { free(suffix); suffix = dc_get_filesuffix_lc(dir_entry->d_name); if (suffix==NULL || strcmp(suffix, "asc")!=0) { continue; } free(path_plus_name); path_plus_name = dc_mprintf("%s/%s", dir_name, dir_entry->d_name/* name without path; may also be `.` or `..` */); dc_log_info(context, 0, "Checking: %s", path_plus_name); free(buf); buf = NULL; if (!dc_read_file(context, path_plus_name, (void**)&buf, &buf_bytes) || buf_bytes < 50) { continue; } private_key = buf; free(buf2); buf2 = dc_strdup(buf); if (dc_split_armored_data(buf2, &buf2_headerline, NULL, NULL, NULL) && strcmp(buf2_headerline, "-----BEGIN PGP PUBLIC KEY BLOCK-----")==0) { /* This file starts with a Public Key. * However some programs (Thunderbird/Enigmail) put public and private key * in the same file, so we check if there is a private key following */ private_key = strstr(buf, "-----BEGIN PGP PRIVATE KEY BLOCK"); if (private_key==NULL) { continue; /* this is no error but quite normal as we always export the public keys together with the private ones */ } } set_default = 1; if (strstr(dir_entry->d_name, "legacy")!=NULL) { dc_log_info(context, 0, "Treating \"%s\" as a legacy private key.", path_plus_name); set_default = 0; /* a key with "legacy" in its name is not made default; this may result in a keychain with _no_ default, however, this is no problem, as this will create a default key later */ } if (!set_self_key(context, private_key, set_default)) { continue; } imported_cnt++; } if (imported_cnt==0) { dc_log_error(context, 0, "No private keys found in \"%s\".", dir_name); goto cleanup; } cleanup: if (dir_handle) { closedir(dir_handle); } free(suffix); free(path_plus_name); free(buf); free(buf2); return imported_cnt; } /******************************************************************************* * Export backup ******************************************************************************/ /* the FILE_PROGRESS macro calls the callback with the permille of files processed. The macro avoids weird values of 0% or 100% while still working. */ #define FILE_PROGRESS \ processed_files_cnt++; \ int permille = (processed_files_cnt*1000)/total_files_cnt; \ if (permille < 10) { permille = 10; } \ if (permille > 990) { permille = 990; } \ context->cb(context, DC_EVENT_IMEX_PROGRESS, permille, 0); static int export_backup(dc_context_t* context, const char* dir) { int success = 0; int closed = 0; char* dest_pathNfilename = NULL; dc_sqlite3_t* dest_sql = NULL; time_t now = time(NULL); DIR* dir_handle = NULL; struct dirent* dir_entry = NULL; int prefix_len = strlen(DC_BAK_PREFIX); int suffix_len = strlen(DC_BAK_SUFFIX); char* curr_pathNfilename = NULL; void* buf = NULL; size_t buf_bytes = 0; sqlite3_stmt* stmt = NULL; int total_files_cnt = 0; int processed_files_cnt = 0; int delete_dest_file = 0; /* get a fine backup file name (the name includes the date so that multiple backup instances are possible) FIXME: we should write to a temporary file first and rename it on success. this would guarantee the backup is complete. however, currently it is not clear it the import exists in the long run (may be replaced by a restore-from-imap)*/ { struct tm* timeinfo; char buffer[256]; timeinfo = localtime(&now); strftime(buffer, 256, DC_BAK_PREFIX "-%Y-%m-%d." DC_BAK_SUFFIX, timeinfo); if ((dest_pathNfilename=dc_get_fine_pathNfilename(context, dir, buffer))==NULL) { dc_log_error(context, 0, "Cannot get backup file name."); goto cleanup; } } /* delete unreferenced files before export */ dc_housekeeping(context); /* vacuum before export; this fixed failed vacuum's on previous import */ dc_sqlite3_try_execute(context->sql, "VACUUM;"); /* temporary lock and close the source (we just make a copy of the whole file, this is the fastest and easiest approach) */ dc_sqlite3_close(context->sql); closed = 1; dc_log_info(context, 0, "Backup \"%s\" to \"%s\".", context->dbfile, dest_pathNfilename); if (!dc_copy_file(context, context->dbfile, dest_pathNfilename)) { goto cleanup; /* error already logged */ } dc_sqlite3_open(context->sql, context->dbfile, 0); closed = 0; /* add all files as blobs to the database copy (this does not require the source to be locked, neigher the destination as it is used only here) */ if ((dest_sql=dc_sqlite3_new(context/*for logging only*/))==NULL || !dc_sqlite3_open(dest_sql, dest_pathNfilename, 0)) { goto cleanup; /* error already logged */ } if (!dc_sqlite3_table_exists(dest_sql, "backup_blobs")) { if (!dc_sqlite3_execute(dest_sql, "CREATE TABLE backup_blobs (id INTEGER PRIMARY KEY, file_name, file_content);")) { goto cleanup; /* error already logged */ } } /* scan directory, pass 1: collect file info */ total_files_cnt = 0; if ((dir_handle=opendir(context->blobdir))==NULL) { dc_log_error(context, 0, "Backup: Cannot get info for blob-directory \"%s\".", context->blobdir); goto cleanup; } while ((dir_entry=readdir(dir_handle))!=NULL) { total_files_cnt++; } closedir(dir_handle); dir_handle = NULL; if (total_files_cnt>0) { /* scan directory, pass 2: copy files */ if ((dir_handle=opendir(context->blobdir))==NULL) { dc_log_error(context, 0, "Backup: Cannot copy from blob-directory \"%s\".", context->blobdir); goto cleanup; } stmt = dc_sqlite3_prepare(dest_sql, "INSERT INTO backup_blobs (file_name, file_content) VALUES (?, ?);"); while ((dir_entry=readdir(dir_handle))!=NULL) { if (context->shall_stop_ongoing) { delete_dest_file = 1; goto cleanup; } FILE_PROGRESS char* name = dir_entry->d_name; /* name without path; may also be `.` or `..` */ int name_len = strlen(name); if ((name_len==1 && name[0]=='.') || (name_len==2 && name[0]=='.' && name[1]=='.') || (name_len > prefix_len && strncmp(name, DC_BAK_PREFIX, prefix_len)==0 && name_len > suffix_len && strncmp(&name[name_len-suffix_len-1], "." DC_BAK_SUFFIX, suffix_len)==0)) { //dc_log_info(context, 0, "Backup: Skipping \"%s\".", name); continue; } //dc_log_info(context, 0, "Backup \"%s\".", name); free(curr_pathNfilename); curr_pathNfilename = dc_mprintf("%s/%s", context->blobdir, name); free(buf); if (!dc_read_file(context, curr_pathNfilename, &buf, &buf_bytes) || buf==NULL || buf_bytes<=0) { continue; } sqlite3_bind_text(stmt, 1, name, -1, SQLITE_STATIC); sqlite3_bind_blob(stmt, 2, buf, buf_bytes, SQLITE_STATIC); if (sqlite3_step(stmt)!=SQLITE_DONE) { dc_log_error(context, 0, "Disk full? Cannot add file \"%s\" to backup.", curr_pathNfilename); goto cleanup; /* this is not recoverable! writing to the sqlite database should work! */ } sqlite3_reset(stmt); } } else { dc_log_info(context, 0, "Backup: No files to copy.", context->blobdir); } /* done - set some special config values (do this last to avoid importing crashed backups) */ dc_sqlite3_set_config_int(dest_sql, "backup_time", now); context->cb(context, DC_EVENT_IMEX_FILE_WRITTEN, (uintptr_t)dest_pathNfilename, 0); success = 1; cleanup: if (dir_handle) { closedir(dir_handle); } if (closed) { dc_sqlite3_open(context->sql, context->dbfile, 0); } sqlite3_finalize(stmt); dc_sqlite3_close(dest_sql); dc_sqlite3_unref(dest_sql); if (delete_dest_file) { dc_delete_file(context, dest_pathNfilename); } free(dest_pathNfilename); free(curr_pathNfilename); free(buf); return success; } /******************************************************************************* * Import backup ******************************************************************************/ static int import_backup(dc_context_t* context, const char* backup_to_import) { int success = 0; int processed_files_cnt = 0; int total_files_cnt = 0; sqlite3_stmt* stmt = NULL; char* pathNfilename = NULL; char* repl_from = NULL; char* repl_to = NULL; dc_log_info(context, 0, "Import \"%s\" to \"%s\".", backup_to_import, context->dbfile); if (dc_is_configured(context)) { dc_log_error(context, 0, "Cannot import backups to accounts in use."); goto cleanup; } /* close and delete the original file - FIXME: we should import to a .bak file and rename it on success. however, currently it is not clear it the import exists in the long run (may be replaced by a restore-from-imap) */ if (dc_sqlite3_is_open(context->sql)) { dc_sqlite3_close(context->sql); } dc_delete_file(context, context->dbfile); if (dc_file_exist(context, context->dbfile)) { dc_log_error(context, 0, "Cannot import backups: Cannot delete the old file."); goto cleanup; } /* copy the database file */ if (!dc_copy_file(context, backup_to_import, context->dbfile)) { goto cleanup; /* error already logged */ } /* re-open copied database file */ if (!dc_sqlite3_open(context->sql, context->dbfile, 0)) { goto cleanup; } /* copy all blobs to files */ stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM backup_blobs;"); sqlite3_step(stmt); total_files_cnt = sqlite3_column_int(stmt, 0); sqlite3_finalize(stmt); stmt = NULL; stmt = dc_sqlite3_prepare(context->sql, "SELECT file_name, file_content FROM backup_blobs ORDER BY id;"); while (sqlite3_step(stmt)==SQLITE_ROW) { if (context->shall_stop_ongoing) { goto cleanup; } FILE_PROGRESS const char* file_name = (const char*)sqlite3_column_text (stmt, 0); int file_bytes = sqlite3_column_bytes(stmt, 1); const void* file_content = sqlite3_column_blob (stmt, 1); if (file_bytes > 0 && file_content) { free(pathNfilename); pathNfilename = dc_mprintf("%s/%s", context->blobdir, file_name); if (!dc_write_file(context, pathNfilename, file_content, file_bytes)) { dc_log_error(context, 0, "Storage full? Cannot write file %s with %i bytes.", pathNfilename, file_bytes); goto cleanup; /* otherwise the user may believe the stuff is imported correctly, but there are files missing ... */ } } } /* finalize/reset all statements - otherwise the table cannot be DROPped below */ sqlite3_finalize(stmt); stmt = 0; dc_sqlite3_execute(context->sql, "DROP TABLE backup_blobs;"); dc_sqlite3_try_execute(context->sql, "VACUUM;"); success = 1; cleanup: free(pathNfilename); free(repl_from); free(repl_to); sqlite3_finalize(stmt); return success; } /******************************************************************************* * Import/Export Thread and Main Interface ******************************************************************************/ /** * Import/export things. * For this purpose, the function creates a job that is executed in the IMAP-thread then; * this requires to call dc_perform_imap_jobs() regularly. * * What to do is defined by the _what_ parameter which may be one of the following: * * - **DC_IMEX_EXPORT_BACKUP** (11) - Export a backup to the directory given as `param1`. * The backup contains all contacts, chats, images and other data and device independent settings. * The backup does not contain device dependent settings as ringtones or LED notification settings. * The name of the backup is typically `delta-chat..bak`, if more than one backup is create on a day, * the format is `delta-chat.-.bak` * * - **DC_IMEX_IMPORT_BACKUP** (12) - `param1` is the file (not: directory) to import. The file is normally * created by DC_IMEX_EXPORT_BACKUP and detected by dc_imex_has_backup(). Importing a backup * is only possible as long as the context is not configured or used in another way. * * - **DC_IMEX_EXPORT_SELF_KEYS** (1) - Export all private keys and all public keys of the user to the * directory given as `param1`. The default key is written to the files `public-key-default.asc` * and `private-key-default.asc`, if there are more keys, they are written to files as * `public-key-.asc` and `private-key-.asc` * * - **DC_IMEX_IMPORT_SELF_KEYS** (2) - Import private keys found in the directory given as `param1`. * The last imported key is made the default keys unless its name contains the string `legacy`. Public keys are not imported. * * While dc_imex() returns immediately, the started job may take a while, * you can stop it using dc_stop_ongoing_process(). During execution of the job, * some events are sent out: * * - A number of #DC_EVENT_IMEX_PROGRESS events are sent and may be used to create * a progress bar or stuff like that. Moreover, you'll be informed when the imex-job is done. * * - For each file written on export, the function sends #DC_EVENT_IMEX_FILE_WRITTEN * * Only one import-/export-progress can run at the same time. * To cancel an import-/export-progress, use dc_stop_ongoing_process(). * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param what One of the DC_IMEX_* constants. * @param param1 Meaning depends on the DC_IMEX_* constants. If this parameter is a directory, it should not end with * a slash (otherwise you'll get double slashes when receiving #DC_EVENT_IMEX_FILE_WRITTEN). Set to NULL if not used. * @param param2 Meaning depends on the DC_IMEX_* constants. Set to NULL if not used. * @return None. */ void dc_imex(dc_context_t* context, int what, const char* param1, const char* param2) { dc_param_t* param = dc_param_new(); dc_param_set_int(param, DC_PARAM_CMD, what); dc_param_set (param, DC_PARAM_CMD_ARG, param1); dc_param_set (param, DC_PARAM_CMD_ARG2, param2); dc_job_kill_action(context, DC_JOB_IMEX_IMAP); dc_job_add(context, DC_JOB_IMEX_IMAP, 0, param->packed, 0); // results in a call to dc_job_do_DC_JOB_IMEX_IMAP() dc_param_unref(param); } void dc_job_do_DC_JOB_IMEX_IMAP(dc_context_t* context, dc_job_t* job) { int success = 0; int ongoing_allocated_here = 0; int what = 0; char* param1 = NULL; char* param2 = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || context->sql==NULL) { goto cleanup; } if (!dc_alloc_ongoing(context)) { goto cleanup; } ongoing_allocated_here = 1; what = dc_param_get_int(job->param, DC_PARAM_CMD, 0); param1 = dc_param_get (job->param, DC_PARAM_CMD_ARG, NULL); param2 = dc_param_get (job->param, DC_PARAM_CMD_ARG2, NULL); if (param1==NULL) { dc_log_error(context, 0, "No Import/export dir/file given."); goto cleanup; } dc_log_info(context, 0, "Import/export process started."); context->cb(context, DC_EVENT_IMEX_PROGRESS, 10, 0); if (!dc_sqlite3_is_open(context->sql)) { dc_log_error(context, 0, "Import/export: Database not opened."); goto cleanup; } if (what==DC_IMEX_EXPORT_SELF_KEYS || what==DC_IMEX_EXPORT_BACKUP) { /* before we export anything, make sure the private key exists */ if (!dc_ensure_secret_key_exists(context)) { dc_log_error(context, 0, "Import/export: Cannot create private key or private key not available."); goto cleanup; } /* also make sure, the directory for exporting exists */ dc_create_folder(context, param1); } switch (what) { case DC_IMEX_EXPORT_SELF_KEYS: if (!export_self_keys(context, param1)) { goto cleanup; } break; case DC_IMEX_IMPORT_SELF_KEYS: if (!import_self_keys(context, param1)) { goto cleanup; } break; case DC_IMEX_EXPORT_BACKUP: if (!export_backup(context, param1)) { goto cleanup; } break; case DC_IMEX_IMPORT_BACKUP: if (!import_backup(context, param1)) { goto cleanup; } break; default: goto cleanup; } dc_log_info(context, 0, "Import/export completed."); success = 1; cleanup: free(param1); free(param2); if (ongoing_allocated_here) { dc_free_ongoing(context); } context->cb(context, DC_EVENT_IMEX_PROGRESS, success? 1000 : 0, 0); } /** * Check if there is a backup file. * May only be used on fresh installations (eg. dc_is_configured() returns 0). * * Example: * * ~~~ * char dir[] = "/dir/to/search/backups/in"; * * void ask_user_for_credentials() * { * // - ask the user for email and password * // - save them using dc_set_config() * } * * int ask_user_whether_to_import() * { * // - inform the user that we've found a backup * // - ask if he want to import it * // - return 1 to import, 0 to skip * return 1; * } * * if (!dc_is_configured(context)) * { * char* file = NULL; * if ((file=dc_imex_has_backup(context, dir))!=NULL && ask_user_whether_to_import()) * { * dc_imex(context, DC_IMEX_IMPORT_BACKUP, file, NULL); * // connect * } * else * { * do { * ask_user_for_credentials(); * } * while (!configure_succeeded()) * } * free(file); * } * ~~~ * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param dir_name Directory to search backups in. * @return String with the backup file, typically given to dc_imex(), returned strings must be free()'d. * The function returns NULL if no backup was found. */ char* dc_imex_has_backup(dc_context_t* context, const char* dir_name) { char* ret = NULL; time_t ret_backup_time = 0; DIR* dir_handle = NULL; struct dirent* dir_entry = NULL; int prefix_len = strlen(DC_BAK_PREFIX); int suffix_len = strlen(DC_BAK_SUFFIX); char* curr_pathNfilename = NULL; dc_sqlite3_t* test_sql = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return NULL; } if ((dir_handle=opendir(dir_name))==NULL) { dc_log_info(context, 0, "Backup check: Cannot open directory \"%s\".", dir_name); /* this is not an error - eg. the directory may not exist or the user has not given us access to read data from the storage */ goto cleanup; } while ((dir_entry=readdir(dir_handle))!=NULL) { const char* name = dir_entry->d_name; /* name without path; may also be `.` or `..` */ int name_len = strlen(name); if (name_len > prefix_len && strncmp(name, DC_BAK_PREFIX, prefix_len)==0 && name_len > suffix_len && strncmp(&name[name_len-suffix_len-1], "." DC_BAK_SUFFIX, suffix_len)==0) { free(curr_pathNfilename); curr_pathNfilename = dc_mprintf("%s/%s", dir_name, name); dc_sqlite3_unref(test_sql); if ((test_sql=dc_sqlite3_new(context/*for logging only*/))!=NULL && dc_sqlite3_open(test_sql, curr_pathNfilename, DC_OPEN_READONLY)) { time_t curr_backup_time = dc_sqlite3_get_config_int(test_sql, "backup_time", 0); /* reading the backup time also checks if the database is readable and the table `config` exists */ if (curr_backup_time > 0 && curr_backup_time > ret_backup_time/*use the newest if there are multiple backup*/) { /* set return value to the tested database name */ free(ret); ret = curr_pathNfilename; ret_backup_time = curr_backup_time; curr_pathNfilename = NULL; } } } } cleanup: if (dir_handle) { closedir(dir_handle); } free(curr_pathNfilename); dc_sqlite3_unref(test_sql); return ret; } /** * Check if the user is authorized by the given password in some way. * This is to prompt for the password eg. before exporting keys/backup. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param test_pw Password to check. * @return 1=user is authorized, 0=user is not authorized. */ int dc_check_password(dc_context_t* context, const char* test_pw) { /* Check if the given password matches the configured mail_pw. This is to prompt the user before starting eg. an export; this is mainly to avoid doing people bad thinkgs if they have short access to the device. When we start supporting OAuth some day, we should think this over, maybe force the user to re-authenticate himself with the Android password. */ dc_loginparam_t* loginparam = dc_loginparam_new(); int success = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } dc_loginparam_read(loginparam, context->sql, "configured_"); if ((loginparam->mail_pw==NULL || loginparam->mail_pw[0]==0) && (test_pw==NULL || test_pw[0]==0)) { /* both empty or unset */ success = 1; } else if (loginparam->mail_pw==NULL || test_pw==NULL) { /* one set, the other not */ success = 0; } else if (strcmp(loginparam->mail_pw, test_pw)==0) { /* string-compared passwords are equal */ success = 1; } cleanup: dc_loginparam_unref(loginparam); return success; } /** * @} */ ``` Filename: dc_job.c ```c #include #include #include #include "dc_context.h" #include "dc_loginparam.h" #include "dc_job.h" #include "dc_imap.h" #include "dc_smtp.h" #include "dc_mimefactory.h" static void dc_send_mdn(dc_context_t* context, uint32_t msg_id); /******************************************************************************* * IMAP-jobs ******************************************************************************/ static int connect_to_inbox(dc_context_t* context) { int ret_connected = DC_NOT_CONNECTED; ret_connected = dc_connect_to_configured_imap(context, context->inbox); if (!ret_connected) { goto cleanup; } dc_imap_set_watch_folder(context->inbox, "INBOX"); cleanup: return ret_connected; } static void dc_job_do_DC_JOB_DELETE_MSG_ON_IMAP(dc_context_t* context, dc_job_t* job) { int delete_from_server = 1; dc_msg_t* msg = dc_msg_new_untyped(context); if (!dc_msg_load_from_db(msg, context, job->foreign_id) || msg->rfc724_mid==NULL || msg->rfc724_mid[0]==0 /* eg. device messages have no Message-ID */) { goto cleanup; } if (dc_rfc724_mid_cnt(context, msg->rfc724_mid)!=1) { dc_log_info(context, 0, "The message is deleted from the server when all parts are deleted."); delete_from_server = 0; } /* if this is the last existing part of the message, we delete the message from the server */ if (delete_from_server) { if (!dc_imap_is_connected(context->inbox)) { connect_to_inbox(context); if (!dc_imap_is_connected(context->inbox)) { dc_job_try_again_later(job, DC_STANDARD_DELAY, NULL); goto cleanup; } } if (!dc_imap_delete_msg(context->inbox, msg->rfc724_mid, msg->server_folder, msg->server_uid)) { dc_job_try_again_later(job, DC_AT_ONCE, NULL); goto cleanup; } } /* we delete the database entry ... - if the message is successfully removed from the server - or if there are other parts of the message in the database (in this case we have not deleted if from the server) (As long as the message is not removed from the IMAP-server, we need at least one database entry to avoid a re-download) */ dc_delete_msg_from_db(context, msg->id); cleanup: dc_msg_unref(msg); } static void dc_job_do_DC_JOB_EMPTY_SERVER(dc_context_t* context, dc_job_t* job) { char* mvbox_name = NULL; if (!dc_imap_is_connected(context->inbox)) { connect_to_inbox(context); if (!dc_imap_is_connected(context->inbox)) { goto cleanup; } } if (job->foreign_id&DC_EMPTY_MVBOX) { char* mvbox_name = dc_sqlite3_get_config(context->sql, "configured_mvbox_folder", NULL); if (mvbox_name && mvbox_name[0]) { dc_imap_empty_folder(context->inbox, mvbox_name); } } if (job->foreign_id&DC_EMPTY_INBOX) { dc_imap_empty_folder(context->inbox, "INBOX"); } cleanup: free(mvbox_name); } static void dc_job_do_DC_JOB_MOVE_MSG(dc_context_t* context, dc_job_t* job) { dc_msg_t* msg = dc_msg_new_untyped(context); char* dest_folder = NULL; uint32_t dest_uid = 0; if (!dc_imap_is_connected(context->inbox)) { connect_to_inbox(context); if (!dc_imap_is_connected(context->inbox)) { dc_job_try_again_later(job, DC_STANDARD_DELAY, NULL); goto cleanup; } } if (!dc_msg_load_from_db(msg, context, job->foreign_id)) { goto cleanup; } if (dc_sqlite3_get_config_int(context->sql, "folders_configured", 0)inbox, DC_CREATE_MVBOX); } dest_folder = dc_sqlite3_get_config(context->sql, "configured_mvbox_folder", NULL); switch (dc_imap_move(context->inbox, msg->server_folder, msg->server_uid, dest_folder, &dest_uid)) { case DC_FAILED: goto cleanup; case DC_RETRY_LATER: dc_job_try_again_later(job, DC_STANDARD_DELAY, NULL); break; case DC_ALREADY_DONE: break; case DC_SUCCESS: dc_update_server_uid(context, msg->rfc724_mid, dest_folder, dest_uid); break; } cleanup: free(dest_folder); dc_msg_unref(msg); } static void dc_job_do_DC_JOB_MARKSEEN_MSG_ON_IMAP(dc_context_t* context, dc_job_t* job) { dc_msg_t* msg = dc_msg_new_untyped(context); if (!dc_imap_is_connected(context->inbox)) { connect_to_inbox(context); if (!dc_imap_is_connected(context->inbox)) { dc_job_try_again_later(job, DC_STANDARD_DELAY, NULL); goto cleanup; } } if (!dc_msg_load_from_db(msg, context, job->foreign_id)) { goto cleanup; } switch (dc_imap_set_seen(context->inbox, msg->server_folder, msg->server_uid)) { case DC_FAILED: goto cleanup; case DC_RETRY_LATER: dc_job_try_again_later(job, DC_STANDARD_DELAY, NULL); goto cleanup; default: break; } if (dc_param_get_int(msg->param, DC_PARAM_WANTS_MDN, 0) && dc_sqlite3_get_config_int(context->sql, "mdns_enabled", DC_MDNS_DEFAULT_ENABLED)) { switch (dc_imap_set_mdnsent(context->inbox, msg->server_folder, msg->server_uid)) { case DC_FAILED: goto cleanup; case DC_RETRY_LATER: dc_job_try_again_later(job, DC_STANDARD_DELAY, NULL); goto cleanup; case DC_ALREADY_DONE: break; case DC_SUCCESS: dc_send_mdn(context, msg->id); break; } } cleanup: dc_msg_unref(msg); } static void dc_job_do_DC_JOB_MARKSEEN_MDN_ON_IMAP(dc_context_t* context, dc_job_t* job) { char* folder = dc_param_get(job->param, DC_PARAM_SERVER_FOLDER, NULL); uint32_t uid = dc_param_get_int(job->param, DC_PARAM_SERVER_UID, 0); char* dest_folder = NULL; uint32_t dest_uid = 0; if (!dc_imap_is_connected(context->inbox)) { connect_to_inbox(context); if (!dc_imap_is_connected(context->inbox)) { dc_job_try_again_later(job, DC_STANDARD_DELAY, NULL); goto cleanup; } } if (dc_imap_set_seen(context->inbox, folder, uid)==0) { dc_job_try_again_later(job, DC_STANDARD_DELAY, NULL); } if (dc_param_get_int(job->param, DC_PARAM_ALSO_MOVE, 0)) { if (dc_sqlite3_get_config_int(context->sql, "folders_configured", 0)inbox, DC_CREATE_MVBOX); } dest_folder = dc_sqlite3_get_config(context->sql, "configured_mvbox_folder", NULL); switch (dc_imap_move(context->inbox, folder, uid, dest_folder, &dest_uid)) { case DC_FAILED: goto cleanup; case DC_RETRY_LATER: dc_job_try_again_later(job, DC_STANDARD_DELAY, NULL); break; default: break; } } cleanup: free(folder); free(dest_folder); } /******************************************************************************* * SMTP-jobs ******************************************************************************/ /** * Store the MIME message in a file and send it later with a new SMTP job. * * @param context The context object as created by dc_context_new() * @param action One of the DC_JOB_SEND_ constants * @param mimefactory An instance of dc_mimefactory_t with a loaded and rendered message or MDN * @return 1=success, 0=error */ static int dc_add_smtp_job(dc_context_t* context, int action, dc_mimefactory_t* mimefactory) { char* pathNfilename = NULL; int success = 0; char* recipients = NULL; dc_param_t* param = dc_param_new(); // find a free file name in the blob directory pathNfilename = dc_get_fine_pathNfilename(context, "$BLOBDIR", mimefactory->rfc724_mid); if (!pathNfilename) { dc_log_error(context, 0, "Could not find free file name for message with ID <%s>.", mimefactory->rfc724_mid); goto cleanup; } // write the file if (!dc_write_file(context, pathNfilename, mimefactory->out->str, mimefactory->out->len)) { dc_log_error(context, 0, "Could not write message <%s> to \"%s\".", mimefactory->rfc724_mid, pathNfilename); goto cleanup; } // store recipients in job param recipients = dc_str_from_clist(mimefactory->recipients_addr, "\x1e"); dc_param_set(param, DC_PARAM_FILE, pathNfilename); dc_param_set(param, DC_PARAM_RECIPIENTS, recipients); dc_job_add(context, action, mimefactory->loaded==DC_MF_MSG_LOADED ? mimefactory->msg->id : 0, param->packed, 0); success = 1; cleanup: dc_param_unref(param); free(recipients); free(pathNfilename); return success; } /** * Create an SMTP job to send a message from the DB * * @param context The context object as created by dc_context_new() * @param msg_id The ID of the message to send * @return 1=success, 0=error */ int dc_job_send_msg(dc_context_t* context, uint32_t msg_id) { int success = 0; dc_mimefactory_t mimefactory; dc_mimefactory_init(&mimefactory, context); /* load message data */ if (!dc_mimefactory_load_msg(&mimefactory, msg_id) || mimefactory.from_addr==NULL) { dc_log_warning(context, 0, "Cannot load data to send, maybe the message is deleted in between."); goto cleanup; // no redo, no IMAP. moreover, as the data does not exist, there is no need in calling dc_set_msg_failed() } /* set width/height of images, if not yet done */ if (DC_MSG_NEEDS_ATTACHMENT(mimefactory.msg->type)) { char* pathNfilename = dc_param_get(mimefactory.msg->param, DC_PARAM_FILE, NULL); if (pathNfilename) { if ((mimefactory.msg->type==DC_MSG_IMAGE || mimefactory.msg->type==DC_MSG_GIF) && !dc_param_exists(mimefactory.msg->param, DC_PARAM_WIDTH)) { unsigned char* buf = NULL; size_t buf_bytes; uint32_t w, h; dc_param_set_int(mimefactory.msg->param, DC_PARAM_WIDTH, 0); dc_param_set_int(mimefactory.msg->param, DC_PARAM_HEIGHT, 0); if (dc_read_file(context, pathNfilename, (void**)&buf, &buf_bytes)) { if (dc_get_filemeta(buf, buf_bytes, &w, &h)) { dc_param_set_int(mimefactory.msg->param, DC_PARAM_WIDTH, w); dc_param_set_int(mimefactory.msg->param, DC_PARAM_HEIGHT, h); } } free(buf); dc_msg_save_param_to_disk(mimefactory.msg); } } free(pathNfilename); } /* create message */ { if (!dc_mimefactory_render(&mimefactory)) { dc_set_msg_failed(context, msg_id, mimefactory.error); goto cleanup; // no redo, no IMAP - this will also fail next time } /* have we guaranteed encryption but cannot fulfill it for any reason? Do not send the message then.*/ if (dc_param_get_int(mimefactory.msg->param, DC_PARAM_GUARANTEE_E2EE, 0) && !mimefactory.out_encrypted) { dc_set_msg_failed(context, msg_id, "End-to-end-encryption unavailable unexpectedly."); goto cleanup; /* unrecoverable */ } /* add SELF to the recipient list (it's no longer used elsewhere, so a copy of the whole list is needless) */ if (clist_search_string_nocase(mimefactory.recipients_addr, mimefactory.from_addr)==0) { clist_append(mimefactory.recipients_names, NULL); clist_append(mimefactory.recipients_addr, (void*)dc_strdup(mimefactory.from_addr)); } } dc_sqlite3_begin_transaction(context->sql); if (mimefactory.out_gossiped) { dc_set_gossiped_timestamp(context, mimefactory.msg->chat_id, time(NULL)); } if (mimefactory.out_last_added_location_id) { dc_set_kml_sent_timestamp(context, mimefactory.msg->chat_id, time(NULL)); if (!mimefactory.msg->hidden) { dc_set_msg_location_id(context, mimefactory.msg->id, mimefactory.out_last_added_location_id); } } if (mimefactory.out_encrypted && dc_param_get_int(mimefactory.msg->param, DC_PARAM_GUARANTEE_E2EE, 0)==0) { dc_param_set_int(mimefactory.msg->param, DC_PARAM_GUARANTEE_E2EE, 1); /* can upgrade to E2EE - fine! */ dc_msg_save_param_to_disk(mimefactory.msg); } // TODO: add to keyhistory dc_add_to_keyhistory(context, NULL, 0, NULL, NULL); dc_sqlite3_commit(context->sql); success = dc_add_smtp_job(context, DC_JOB_SEND_MSG_TO_SMTP, &mimefactory); cleanup: dc_mimefactory_empty(&mimefactory); return success; } static void dc_job_do_DC_JOB_SEND(dc_context_t* context, dc_job_t* job) { char* filename = NULL; void* buf = NULL; size_t buf_bytes = 0; char* recipients = NULL; clist* recipients_list = NULL; sqlite3_stmt* stmt = NULL; /* connect to SMTP server, if not yet done */ if (!dc_smtp_is_connected(context->smtp)) { dc_loginparam_t* loginparam = dc_loginparam_new(); dc_loginparam_read(loginparam, context->sql, "configured_"); int connected = dc_smtp_connect(context->smtp, loginparam); dc_loginparam_unref(loginparam); if (!connected) { dc_job_try_again_later(job, DC_STANDARD_DELAY, NULL); goto cleanup; } } /* load message data */ filename = dc_param_get(job->param, DC_PARAM_FILE, NULL); if (!filename) { dc_log_warning(context, 0, "Missing file name for job %d", job->job_id); goto cleanup; } if (!dc_read_file(context, filename, &buf, &buf_bytes)) { goto cleanup; } /* get the list of recipients */ recipients = dc_param_get(job->param, DC_PARAM_RECIPIENTS, NULL); if (!recipients) { dc_log_warning(context, 0, "Missing recipients for job %d", job->job_id); goto cleanup; } recipients_list = dc_str_to_clist(recipients, "\x1e"); /* if there is a msg-id and it does not exist in the db, cancel sending. this happends if dc_delete_msgs() was called before the generated mime was sent out */ if (job->foreign_id) { if(!dc_msg_exists(context, job->foreign_id)) { dc_log_warning(context, 0, "Message %i for job %i does not exist", job->foreign_id, job->job_id); goto cleanup; } } /* send message */ { if (!dc_smtp_send_msg(context->smtp, recipients_list, buf, buf_bytes)) { if (job->foreign_id && ( MAILSMTP_ERROR_EXCEED_STORAGE_ALLOCATION==context->smtp->error_etpan || MAILSMTP_ERROR_INSUFFICIENT_SYSTEM_STORAGE==context->smtp->error_etpan)) { dc_set_msg_failed(context, job->foreign_id, context->smtp->error); } else { dc_smtp_disconnect(context->smtp); dc_job_try_again_later(job, DC_AT_ONCE, context->smtp->error); } goto cleanup; } } /* delete the stores message file */ dc_delete_file(context, filename); /* an error still means the message is sent, so the rest continues */ /* done */ if (job->foreign_id) { dc_update_msg_state(context, job->foreign_id, DC_STATE_OUT_DELIVERED); /* find the chat ID */ stmt = dc_sqlite3_prepare(context->sql, "SELECT chat_id FROM msgs WHERE id=?"); sqlite3_bind_int(stmt, 1, job->foreign_id); /* a deleted message results in an event with chat_id==0, rather than no event at all */ int chat_id = sqlite3_step(stmt)==SQLITE_ROW ? sqlite3_column_int(stmt, 0) : 0; context->cb(context, DC_EVENT_MSG_DELIVERED, chat_id, job->foreign_id); } cleanup: sqlite3_finalize(stmt); if (recipients_list) { clist_free_content(recipients_list); clist_free(recipients_list); } free(recipients); free(buf); free(filename); } static void dc_send_mdn(dc_context_t* context, uint32_t msg_id) { dc_mimefactory_t mimefactory; dc_mimefactory_init(&mimefactory, context); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } if (!dc_mimefactory_load_mdn(&mimefactory, msg_id) || !dc_mimefactory_render(&mimefactory)) { goto cleanup; } //char* t1=dc_null_terminate(mimefactory.out->str,mimefactory.out->len);printf("~~~~~MDN~~~~~\n%s\n~~~~~/MDN~~~~~",t1);free(t1); // DEBUG OUTPUT dc_add_smtp_job(context, DC_JOB_SEND_MDN, &mimefactory); cleanup: dc_mimefactory_empty(&mimefactory); } static void dc_suspend_smtp_thread(dc_context_t* context, int suspend) { pthread_mutex_lock(&context->smtpidle_condmutex); context->smtp_suspended = suspend; pthread_mutex_unlock(&context->smtpidle_condmutex); // if the smtp-thread is currently in dc_perform_smtp_jobs(), // wait until the jobs are done. // this function is only needed during dc_configure(); // for simplicity, we do this by polling a variable. if (suspend) { while (1) { pthread_mutex_lock(&context->smtpidle_condmutex); if (context->smtp_doing_jobs==0) { pthread_mutex_unlock(&context->smtpidle_condmutex); return; } pthread_mutex_unlock(&context->smtpidle_condmutex); usleep(300*1000); } } } /******************************************************************************* * Tools ******************************************************************************/ static time_t get_backoff_time_offset(int c_tries) { #define MULTIPLY 60 #define JOB_RETRIES 17 // results in ~3 weeks for the last backoff timespan time_t N = (time_t)pow((double)2, c_tries - 1); N = N * MULTIPLY; time_t seconds = rand() % (N+1); if (seconds<1) { seconds = 1; } return seconds; } static time_t get_next_wakeup_time(dc_context_t* context, int thread) { time_t wakeup_time = 0; sqlite3_stmt* stmt = NULL; stmt = dc_sqlite3_prepare(context->sql, "SELECT MIN(desired_timestamp)" " FROM jobs" " WHERE thread=?;"); sqlite3_bind_int(stmt, 1, thread); if (sqlite3_step(stmt)==SQLITE_ROW) { wakeup_time = sqlite3_column_int(stmt, 0); } if (wakeup_time==0) { wakeup_time = time(NULL) + 10*60; } sqlite3_finalize(stmt); return wakeup_time; } int dc_job_action_exists(dc_context_t* context, int action) { int job_exists = 0; sqlite3_stmt* stmt = NULL; stmt = dc_sqlite3_prepare(context->sql, "SELECT id FROM jobs WHERE action=?;"); sqlite3_bind_int (stmt, 1, action); job_exists = (sqlite3_step(stmt)==SQLITE_ROW); sqlite3_finalize(stmt); return job_exists; } void dc_job_add(dc_context_t* context, int action, int foreign_id, const char* param, int delay_seconds) { time_t timestamp = time(NULL); sqlite3_stmt* stmt = NULL; int thread = 0; if (action >= DC_IMAP_THREAD && action < DC_IMAP_THREAD+1000) { thread = DC_IMAP_THREAD; } else if (action >= DC_SMTP_THREAD && action < DC_SMTP_THREAD+1000) { thread = DC_SMTP_THREAD; } else { return; } stmt = dc_sqlite3_prepare(context->sql, "INSERT INTO jobs (added_timestamp, thread, action, foreign_id, param, desired_timestamp) VALUES (?,?,?,?,?,?);"); sqlite3_bind_int64(stmt, 1, timestamp); sqlite3_bind_int (stmt, 2, thread); sqlite3_bind_int (stmt, 3, action); sqlite3_bind_int (stmt, 4, foreign_id); sqlite3_bind_text (stmt, 5, param? param : "", -1, SQLITE_STATIC); sqlite3_bind_int64(stmt, 6, timestamp+delay_seconds); sqlite3_step(stmt); sqlite3_finalize(stmt); if (thread==DC_IMAP_THREAD) { dc_interrupt_imap_idle(context); } else { dc_interrupt_smtp_idle(context); } } static void dc_job_update(dc_context_t* context, const dc_job_t* job) { sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "UPDATE jobs" " SET desired_timestamp=?, tries=?, param=?" " WHERE id=?;"); sqlite3_bind_int64(stmt, 1, job->desired_timestamp); sqlite3_bind_int64(stmt, 2, job->tries); sqlite3_bind_text (stmt, 3, job->param->packed, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 4, job->job_id); sqlite3_step(stmt); sqlite3_finalize(stmt); } static void dc_job_delete(dc_context_t* context, const dc_job_t* job) { sqlite3_stmt* delete_stmt = dc_sqlite3_prepare(context->sql, "DELETE FROM jobs WHERE id=?;"); sqlite3_bind_int(delete_stmt, 1, job->job_id); sqlite3_step(delete_stmt); sqlite3_finalize(delete_stmt); } void dc_job_try_again_later(dc_job_t* job, int try_again, const char* pending_error) { if (job==NULL) { return; } job->try_again = try_again; free(job->pending_error); job->pending_error = dc_strdup_keep_null(pending_error); } void dc_job_kill_action(dc_context_t* context, int action) { if (context==NULL) { return; } sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "DELETE FROM jobs WHERE action=?;"); sqlite3_bind_int(stmt, 1, action); sqlite3_step(stmt); sqlite3_finalize(stmt); } static void dc_job_perform(dc_context_t* context, int thread, int probe_network) { sqlite3_stmt* select_stmt = NULL; dc_job_t job; #define THREAD_STR (thread==DC_IMAP_THREAD? "INBOX" : "SMTP") #define IS_EXCLUSIVE_JOB (DC_JOB_CONFIGURE_IMAP==job.action || DC_JOB_IMEX_IMAP==job.action || DC_JOB_EMPTY_SERVER==job.action) memset(&job, 0, sizeof(dc_job_t)); job.param = dc_param_new(); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (probe_network==0) { // processing for first-try and after backoff-timeouts: // process jobs in the order they were added. #define FIELDS "id, action, foreign_id, param, added_timestamp, desired_timestamp, tries" select_stmt = dc_sqlite3_prepare(context->sql, "SELECT " FIELDS " FROM jobs" " WHERE thread=? AND desired_timestamp<=?" " ORDER BY action DESC, added_timestamp;"); sqlite3_bind_int64(select_stmt, 1, thread); sqlite3_bind_int64(select_stmt, 2, time(NULL)); } else { // processing after call to dc_maybe_network(): // process _all_ pending jobs that failed before // in the order of their backoff-times. select_stmt = dc_sqlite3_prepare(context->sql, "SELECT " FIELDS " FROM jobs" " WHERE thread=? AND tries>0" " ORDER BY desired_timestamp, action DESC;"); sqlite3_bind_int64(select_stmt, 1, thread); } while (sqlite3_step(select_stmt)==SQLITE_ROW) { job.job_id = sqlite3_column_int (select_stmt, 0); job.action = sqlite3_column_int (select_stmt, 1); job.foreign_id = sqlite3_column_int (select_stmt, 2); dc_param_set_packed(job.param, (char*)sqlite3_column_text (select_stmt, 3)); job.added_timestamp = sqlite3_column_int64(select_stmt, 4); job.desired_timestamp = sqlite3_column_int64(select_stmt, 5); job.tries = sqlite3_column_int (select_stmt, 6); dc_log_info(context, 0, "%s-job #%i, action %i started...", THREAD_STR, (int)job.job_id, (int)job.action); // some configuration jobs are "exclusive": // - they are always executed in the imap-thread and the smtp-thread is suspended during execution // - they may change the database handle change the database handle; we do not keep old pointers therefore // - they can be re-executed one time AT_ONCE, but they are not save in the database for later execution if (IS_EXCLUSIVE_JOB) { dc_job_kill_action(context, job.action); sqlite3_finalize(select_stmt); select_stmt = NULL; dc_jobthread_suspend(&context->sentbox_thread, 1); dc_jobthread_suspend(&context->mvbox_thread, 1); dc_suspend_smtp_thread(context, 1); } for (int tries = 0; tries <= 1; tries++) { job.try_again = DC_DONT_TRY_AGAIN; // this can be modified by a job using dc_job_try_again_later() switch (job.action) { case DC_JOB_SEND_MSG_TO_SMTP: dc_job_do_DC_JOB_SEND (context, &job); break; case DC_JOB_DELETE_MSG_ON_IMAP: dc_job_do_DC_JOB_DELETE_MSG_ON_IMAP (context, &job); break; case DC_JOB_MARKSEEN_MSG_ON_IMAP: dc_job_do_DC_JOB_MARKSEEN_MSG_ON_IMAP (context, &job); break; case DC_JOB_MARKSEEN_MDN_ON_IMAP: dc_job_do_DC_JOB_MARKSEEN_MDN_ON_IMAP (context, &job); break; case DC_JOB_MOVE_MSG: dc_job_do_DC_JOB_MOVE_MSG (context, &job); break; case DC_JOB_SEND_MDN: dc_job_do_DC_JOB_SEND (context, &job); break; case DC_JOB_CONFIGURE_IMAP: dc_job_do_DC_JOB_CONFIGURE_IMAP (context, &job); break; case DC_JOB_IMEX_IMAP: dc_job_do_DC_JOB_IMEX_IMAP (context, &job); break; case DC_JOB_MAYBE_SEND_LOCATIONS: dc_job_do_DC_JOB_MAYBE_SEND_LOCATIONS (context, &job); break; case DC_JOB_MAYBE_SEND_LOC_ENDED: dc_job_do_DC_JOB_MAYBE_SEND_LOC_ENDED (context, &job); break; case DC_JOB_EMPTY_SERVER: dc_job_do_DC_JOB_EMPTY_SERVER (context, &job); break; case DC_JOB_HOUSEKEEPING: dc_housekeeping (context); break; } if (job.try_again!=DC_AT_ONCE) { break; } } if (IS_EXCLUSIVE_JOB) { dc_jobthread_suspend(&context->sentbox_thread, 0); dc_jobthread_suspend(&context->mvbox_thread, 0); dc_suspend_smtp_thread(context, 0); goto cleanup; } else if (job.try_again==DC_INCREATION_POLL) { // just try over next loop unconditionally, the ui typically interrupts idle when the file (video) is ready dc_log_info(context, 0, "%s-job #%i not yet ready and will be delayed.", THREAD_STR, (int)job.job_id); } else if (job.try_again==DC_AT_ONCE || job.try_again==DC_STANDARD_DELAY) { int tries = job.tries + 1; if( tries < JOB_RETRIES ) { job.tries = tries; time_t time_offset = get_backoff_time_offset(tries); job.desired_timestamp = job.added_timestamp + time_offset; dc_job_update(context, &job); dc_log_info(context, 0, "%s-job #%i not succeeded on try #%i, retry in ADD_TIME+%i (in %i seconds).", THREAD_STR, (int)job.job_id, tries, time_offset, (job.added_timestamp+time_offset)-time(NULL)); if (thread==DC_SMTP_THREAD && tries<(JOB_RETRIES-1)) { pthread_mutex_lock(&context->smtpidle_condmutex); context->perform_smtp_jobs_needed = DC_JOBS_NEEDED_AVOID_DOS; pthread_mutex_unlock(&context->smtpidle_condmutex); } } else { if (job.action==DC_JOB_SEND_MSG_TO_SMTP) { // in all other cases, the messages is already sent dc_set_msg_failed(context, job.foreign_id, job.pending_error); } dc_job_delete(context, &job); } if (probe_network) { // on dc_maybe_network() we stop trying here; // these jobs are already tried once. // otherwise, we just continue with the next job // to give other jobs a chance being tried at least once. goto cleanup; } } else { dc_job_delete(context, &job); } } cleanup: dc_param_unref(job.param); free(job.pending_error); sqlite3_finalize(select_stmt); } /******************************************************************************* * User-functions handle IMAP-jobs from the IMAP-thread ******************************************************************************/ /** * Execute pending imap-jobs. * This function and dc_perform_imap_fetch() and dc_perform_imap_idle() * must be called from the same thread, typically in a loop. * * Example: * * void* imap_thread_func(void* context) * { * while (true) { * dc_perform_imap_jobs(context); * dc_perform_imap_fetch(context); * dc_perform_imap_idle(context); * } * } * * // start imap-thread that runs forever * pthread_t imap_thread; * pthread_create(&imap_thread, NULL, imap_thread_func, context); * * ... program runs ... * * // network becomes available again - * // the interrupt causes dc_perform_imap_idle() in the thread above * // to return so that jobs are executed and messages are fetched. * dc_maybe_network(context); * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_perform_imap_jobs(dc_context_t* context) { dc_log_info(context, 0, "INBOX-jobs started..."); pthread_mutex_lock(&context->inboxidle_condmutex); int probe_imap_network = context->probe_imap_network; context->probe_imap_network = 0; context->perform_inbox_jobs_needed = 0; pthread_mutex_unlock(&context->inboxidle_condmutex); dc_job_perform(context, DC_IMAP_THREAD, probe_imap_network); dc_log_info(context, 0, "INBOX-jobs ended."); } /** * Fetch new messages, if any. * This function and dc_perform_imap_jobs() and dc_perform_imap_idle() must be called from the same thread, * typically in a loop. * * See dc_perform_imap_jobs() for an example. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_perform_imap_fetch(dc_context_t* context) { clock_t start = clock(); if (!connect_to_inbox(context)) { return; } if (dc_sqlite3_get_config_int(context->sql, "inbox_watch", DC_INBOX_WATCH_DEFAULT)==0) { dc_log_info(context, 0, "INBOX-watch disabled."); return; } dc_log_info(context, 0, "INBOX-fetch started..."); dc_imap_fetch(context->inbox); if (context->inbox->should_reconnect) { dc_log_info(context, 0, "INBOX-fetch aborted, starting over..."); dc_imap_fetch(context->inbox); } dc_log_info(context, 0, "INBOX-fetch done in %.0f ms.", (double)(clock()-start)*1000.0/CLOCKS_PER_SEC); } /** * Wait for messages or jobs. * This function and dc_perform_imap_jobs() and dc_perform_imap_fetch() must be called from the same thread, * typically in a loop. * * You should call this function directly after calling dc_perform_imap_fetch(). * * See dc_perform_imap_jobs() for an example. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_perform_imap_idle(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } // also idle if connection fails because of not-configured, // no-network, whatever. dc_imap_idle() will handle this by the fake-idle and log a warning connect_to_inbox(context); pthread_mutex_lock(&context->inboxidle_condmutex); if (context->perform_inbox_jobs_needed) { dc_log_info(context, 0, "INBOX-IDLE will not be started because of waiting jobs."); pthread_mutex_unlock(&context->inboxidle_condmutex); return; } pthread_mutex_unlock(&context->inboxidle_condmutex); // TODO: optimisation: inbox_watch should also be regarded here to save some bytes. // however, the thread and the imap connection are needed even if inbox_watch is disabled // as the jobs are happending here. // anyway, the best way would be to switch this thread also to dc_jobthread_t // which has all the needed capabilities. dc_log_info(context, 0, "INBOX-IDLE started..."); dc_imap_idle(context->inbox); dc_log_info(context, 0, "INBOX-IDLE ended."); } /** * Interrupt waiting for imap-jobs. * If dc_perform_imap_jobs(), dc_perform_imap_fetch() and dc_perform_imap_idle() are called in a loop, * calling this function causes imap-jobs to be executed and messages to be fetched. * * dc_interrupt_imap_idle() does _not_ interrupt dc_perform_imap_jobs() or dc_perform_imap_fetch(). * If the imap-thread is inside one of these functions when dc_interrupt_imap_idle() is called, however, * the next call of the imap-thread to dc_perform_imap_idle() is interrupted immediately. * * Internally, this function is called whenever a imap-jobs should be processed * (delete message, markseen etc.). * * When you need to call this function just because to get jobs done after network changes, * use dc_maybe_network() instead. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_interrupt_imap_idle(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || context->inbox==NULL) { dc_log_warning(context, 0, "Interrupt IMAP-IDLE: Bad parameters."); return; } dc_log_info(context, 0, "Interrupting IMAP-IDLE..."); pthread_mutex_lock(&context->inboxidle_condmutex); // when this function is called, it might be that the idle-thread is in // perform_idle_jobs() instead of idle(). if so, added jobs will be performed after the _next_ idle-jobs loop. // setting the flag perform_imap_jobs_needed makes sure, idle() returns immediately in this case. context->perform_inbox_jobs_needed = 1; pthread_mutex_unlock(&context->inboxidle_condmutex); dc_imap_interrupt_idle(context->inbox); } /******************************************************************************* * User-functions to handle IMAP-jobs in the secondary IMAP-thread ******************************************************************************/ /** * Fetch new messages from the MVBOX, if any. * The MVBOX is a folder on the account where chat messages are moved to. * The moving is done to not disturb shared accounts that are used by both, * Delta Chat and a classical MUA. * * This function and dc_perform_mvbox_idle() * must be called from the same thread, typically in a loop. * * Example: * * void* mvbox_thread_func(void* context) * { * while (true) { * dc_perform_mvbox_fetch(context); * dc_perform_mvbox_idle(context); * } * } * * // start mvbox-thread that runs forever * pthread_t mvbox_thread; * pthread_create(&mvbox_thread, NULL, mvbox_thread_func, context); * * ... program runs ... * * // network becomes available again - * // the interrupt causes dc_perform_mvbox_idle() in the thread above * // to return so that and messages are fetched. * dc_maybe_network(context); * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_perform_mvbox_fetch(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } int use_network = dc_sqlite3_get_config_int(context->sql, "mvbox_watch", DC_MVBOX_WATCH_DEFAULT); dc_jobthread_fetch(&context->mvbox_thread, use_network); } /** * Wait for messages or jobs in the MVBOX-thread. * This function and dc_perform_mvbox_fetch(). * must be called from the same thread, typically in a loop. * * You should call this function directly after calling dc_perform_mvbox_fetch(). * * See dc_perform_mvbox_fetch() for an example. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_perform_mvbox_idle(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } int use_network = dc_sqlite3_get_config_int(context->sql, "mvbox_watch", DC_MVBOX_WATCH_DEFAULT); dc_jobthread_idle(&context->mvbox_thread, use_network); } /** * Interrupt waiting for MVBOX-fetch. * dc_interrupt_mvbox_idle() does _not_ interrupt dc_perform_mvbox_fetch(). * If the MVBOX-thread is inside this function when dc_interrupt_mvbox_idle() is called, however, * the next call of the MVBOX-thread to dc_perform_mvbox_idle() is interrupted immediately. * * Internally, this function is called whenever a imap-jobs should be processed. * * When you need to call this function just because to get jobs done after network changes, * use dc_maybe_network() instead. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_interrupt_mvbox_idle(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { dc_log_warning(context, 0, "Interrupt MVBOX-IDLE: Bad parameters."); return; } dc_jobthread_interrupt_idle(&context->mvbox_thread); } /******************************************************************************* * User-functions to handle IMAP-jobs in the Sendbox-IMAP-thread ******************************************************************************/ /** * Fetch new messages from the Sent folder, if any. * This function and dc_perform_sentbox_idle() * must be called from the same thread, typically in a loop. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_perform_sentbox_fetch(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } int use_network = dc_sqlite3_get_config_int(context->sql, "sentbox_watch", DC_SENTBOX_WATCH_DEFAULT); dc_jobthread_fetch(&context->sentbox_thread, use_network); } /** * Wait for messages or jobs in the SENTBOX-thread. * This function and dc_perform_sentbox_fetch() * must be called from the same thread, typically in a loop. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_perform_sentbox_idle(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } int use_network = dc_sqlite3_get_config_int(context->sql, "sentbox_watch", DC_SENTBOX_WATCH_DEFAULT); dc_jobthread_idle(&context->sentbox_thread, use_network); } /** * Interrupt waiting for messages or jobs in the SENTBOX-thread. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_interrupt_sentbox_idle(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { dc_log_warning(context, 0, "Interrupt SENT-IDLE: Bad parameters."); return; } dc_jobthread_interrupt_idle(&context->sentbox_thread); } /******************************************************************************* * User-functions handle SMTP-jobs from the SMTP-thread ******************************************************************************/ /** * Execute pending smtp-jobs. * This function and dc_perform_smtp_idle() must be called from the same thread, * typically in a loop. * * Example: * * void* smtp_thread_func(void* context) * { * while (true) { * dc_perform_smtp_jobs(context); * dc_perform_smtp_idle(context); * } * } * * // start smtp-thread that runs forever * pthread_t smtp_thread; * pthread_create(&smtp_thread, NULL, smtp_thread_func, context); * * ... program runs ... * * // network becomes available again - * // the interrupt causes dc_perform_smtp_idle() in the thread above * // to return so that jobs are executed * dc_maybe_network(context); * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_perform_smtp_jobs(dc_context_t* context) { pthread_mutex_lock(&context->smtpidle_condmutex); int probe_smtp_network = context->probe_smtp_network; context->probe_smtp_network = 0; context->perform_smtp_jobs_needed = 0; if (context->smtp_suspended) { dc_log_info(context, 0, "SMTP-jobs suspended."); pthread_mutex_unlock(&context->smtpidle_condmutex); return; } context->smtp_doing_jobs = 1; pthread_mutex_unlock(&context->smtpidle_condmutex); dc_log_info(context, 0, "SMTP-jobs started..."); dc_job_perform(context, DC_SMTP_THREAD, probe_smtp_network); dc_log_info(context, 0, "SMTP-jobs ended."); pthread_mutex_lock(&context->smtpidle_condmutex); context->smtp_doing_jobs = 0; pthread_mutex_unlock(&context->smtpidle_condmutex); } /** * Wait for smtp-jobs. * This function and dc_perform_smtp_jobs() must be called from the same thread, * typically in a loop. * * See dc_interrupt_smtp_idle() for an example. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_perform_smtp_idle(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { dc_log_warning(context, 0, "Cannot perform SMTP-idle: Bad parameters."); return; } dc_log_info(context, 0, "SMTP-idle started..."); pthread_mutex_lock(&context->smtpidle_condmutex); if (context->perform_smtp_jobs_needed==DC_JOBS_NEEDED_AT_ONCE) { dc_log_info(context, 0, "SMTP-idle will not be started because of waiting jobs."); } else { int r = 0; struct timespec wakeup_at; memset(&wakeup_at, 0, sizeof(wakeup_at)); wakeup_at.tv_sec = get_next_wakeup_time(context, DC_SMTP_THREAD)+1; while (context->smtpidle_condflag==0 && r==0) { r = pthread_cond_timedwait(&context->smtpidle_cond, &context->smtpidle_condmutex, &wakeup_at); // unlock mutex -> wait -> lock mutex } context->smtpidle_condflag = 0; } pthread_mutex_unlock(&context->smtpidle_condmutex); dc_log_info(context, 0, "SMTP-idle ended."); } /** * Interrupt waiting for smtp-jobs. * If dc_perform_smtp_jobs() and dc_perform_smtp_idle() are called in a loop, * calling this function causes jobs to be executed. * * dc_interrupt_smtp_idle() does _not_ interrupt dc_perform_smtp_jobs(). * If the smtp-thread is inside this function when dc_interrupt_smtp_idle() is called, however, * the next call of the smtp-thread to dc_perform_smtp_idle() is interrupted immediately. * * Internally, this function is called whenever a message is to be sent. * * When you need to call this function just because to get jobs done after network changes, * use dc_maybe_network() instead. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_interrupt_smtp_idle(dc_context_t* context) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { dc_log_warning(context, 0, "Interrupt SMTP-idle: Bad parameters."); return; } dc_log_info(context, 0, "Interrupting SMTP-idle..."); pthread_mutex_lock(&context->smtpidle_condmutex); // when this function is called, it might be that the smtp-thread is in // perform_smtp_jobs(). if so, added jobs will be performed after the _next_ idle-jobs loop. // setting the flag perform_smtp_jobs_needed makes sure, idle() returns immediately in this case. context->perform_smtp_jobs_needed = DC_JOBS_NEEDED_AT_ONCE; context->smtpidle_condflag = 1; pthread_cond_signal(&context->smtpidle_cond); pthread_mutex_unlock(&context->smtpidle_condmutex); } /** * This function can be called whenever there is a hint * that the network is available again. * The library will try to send pending messages out. * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @return None. */ void dc_maybe_network(dc_context_t* context) { // the following flags are forwarded to dc_job_perform() and make sure, // sending is tried independingly of retry-count or timeouts. // if the first messages comes through, the others are be retried as well. pthread_mutex_lock(&context->smtpidle_condmutex); context->probe_smtp_network = 1; pthread_mutex_unlock(&context->smtpidle_condmutex); pthread_mutex_lock(&context->inboxidle_condmutex); context->probe_imap_network = 1; pthread_mutex_unlock(&context->inboxidle_condmutex); dc_interrupt_smtp_idle(context); dc_interrupt_imap_idle(context); dc_interrupt_mvbox_idle(context); dc_interrupt_sentbox_idle(context); } void dc_empty_server(dc_context_t* context, int flags) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || (flags&(DC_EMPTY_INBOX|DC_EMPTY_MVBOX))==0) { return; } dc_job_kill_action(context, DC_JOB_EMPTY_SERVER); dc_job_add(context, DC_JOB_EMPTY_SERVER, flags, NULL, 0); } ``` Filename: dc_jobthread.c ```c #include #include #include "dc_context.h" #include "dc_imap.h" /******************************************************************************* * init, exit, suspend-for-configure ******************************************************************************/ void dc_jobthread_init(dc_jobthread_t* jobthread, dc_context_t* context, const char* name, const char* folder_config_name) { if (jobthread==NULL || context==NULL || name==NULL) { return; } jobthread->context = context; jobthread->name = dc_strdup(name); jobthread->folder_config_name = dc_strdup(folder_config_name); jobthread->imap = NULL; pthread_mutex_init(&jobthread->mutex, NULL); pthread_cond_init(&jobthread->idle_cond, NULL); jobthread->idle_condflag = 0; jobthread->jobs_needed = 0; jobthread->suspended = 0; jobthread->using_handle = 0; } void dc_jobthread_exit(dc_jobthread_t* jobthread) { if (jobthread==NULL) { return; } pthread_cond_destroy(&jobthread->idle_cond); pthread_mutex_destroy(&jobthread->mutex); free(jobthread->name); jobthread->name = NULL; free(jobthread->folder_config_name); jobthread->folder_config_name = NULL; } void dc_jobthread_suspend(dc_jobthread_t* jobthread, int suspend) { if (jobthread==NULL) { return; } if (suspend) { dc_log_info(jobthread->context, 0, "Suspending %s-thread.", jobthread->name); pthread_mutex_lock(&jobthread->mutex); jobthread->suspended = 1; pthread_mutex_unlock(&jobthread->mutex); dc_jobthread_interrupt_idle(jobthread); // wait until we're out of idle, // after that the handle won't be in use anymore while (1) { pthread_mutex_lock(&jobthread->mutex); if (jobthread->using_handle==0) { pthread_mutex_unlock(&jobthread->mutex); return; } pthread_mutex_unlock(&jobthread->mutex); usleep(300*1000); } } else { dc_log_info(jobthread->context, 0, "Unsuspending %s-thread.", jobthread->name); pthread_mutex_lock(&jobthread->mutex); jobthread->suspended = 0; jobthread->idle_condflag = 1; pthread_cond_signal(&jobthread->idle_cond); pthread_mutex_unlock(&jobthread->mutex); } } /******************************************************************************* * the typical fetch, idle, interrupt-idle ******************************************************************************/ static int connect_to_imap(dc_jobthread_t* jobthread) { int ret_connected = DC_NOT_CONNECTED; char* mvbox_name = NULL; if(dc_imap_is_connected(jobthread->imap)) { ret_connected = DC_ALREADY_CONNECTED; goto cleanup; } if (!(ret_connected=dc_connect_to_configured_imap(jobthread->context, jobthread->imap))) { goto cleanup; } if (dc_sqlite3_get_config_int(jobthread->context->sql, "folders_configured", 0)context, jobthread->imap, DC_CREATE_MVBOX); } mvbox_name = dc_sqlite3_get_config(jobthread->context->sql, jobthread->folder_config_name, NULL); if (mvbox_name==NULL) { dc_imap_disconnect(jobthread->imap); ret_connected = DC_NOT_CONNECTED; goto cleanup; } dc_imap_set_watch_folder(jobthread->imap, mvbox_name); cleanup: free(mvbox_name); return ret_connected; } void dc_jobthread_fetch(dc_jobthread_t* jobthread, int use_network) { if (jobthread==NULL) { return; } pthread_mutex_lock(&jobthread->mutex); if (jobthread->suspended) { pthread_mutex_unlock(&jobthread->mutex); return; } jobthread->using_handle = 1; pthread_mutex_unlock(&jobthread->mutex); if (!use_network || jobthread->imap==NULL) { goto cleanup; } clock_t start = clock(); if (!connect_to_imap(jobthread)) { goto cleanup; } dc_log_info(jobthread->context, 0, "%s-fetch started...", jobthread->name); dc_imap_fetch(jobthread->imap); if (jobthread->imap->should_reconnect) { dc_log_info(jobthread->context, 0, "%s-fetch aborted, starting over...", jobthread->name); dc_imap_fetch(jobthread->imap); } dc_log_info(jobthread->context, 0, "%s-fetch done in %.0f ms.", jobthread->name, (double)(clock()-start)*1000.0/CLOCKS_PER_SEC); cleanup: pthread_mutex_lock(&jobthread->mutex); jobthread->using_handle = 0; pthread_mutex_unlock(&jobthread->mutex); } void dc_jobthread_idle(dc_jobthread_t* jobthread, int use_network) { if (jobthread==NULL) { return; } pthread_mutex_lock(&jobthread->mutex); if (jobthread->jobs_needed) { dc_log_info(jobthread->context, 0, "%s-IDLE will not be started as it was interrupted while not ideling.", jobthread->name); jobthread->jobs_needed = 0; pthread_mutex_unlock(&jobthread->mutex); return; } if (jobthread->suspended) { while (jobthread->idle_condflag==0) { // unlock mutex -> wait -> lock mutex pthread_cond_wait(&jobthread->idle_cond, &jobthread->mutex); } jobthread->idle_condflag = 0; pthread_mutex_unlock(&jobthread->mutex); return; } jobthread->using_handle = 1; pthread_mutex_unlock(&jobthread->mutex); if (!use_network || jobthread->imap==NULL) { pthread_mutex_lock(&jobthread->mutex); jobthread->using_handle = 0; while (jobthread->idle_condflag==0) { // unlock mutex -> wait -> lock mutex pthread_cond_wait(&jobthread->idle_cond, &jobthread->mutex); } jobthread->idle_condflag = 0; pthread_mutex_unlock(&jobthread->mutex); return; } connect_to_imap(jobthread); dc_log_info(jobthread->context, 0, "%s-IDLE started...", jobthread->name); dc_imap_idle(jobthread->imap); dc_log_info(jobthread->context, 0, "%s-IDLE ended.", jobthread->name); pthread_mutex_lock(&jobthread->mutex); jobthread->using_handle = 0; pthread_mutex_unlock(&jobthread->mutex); } void dc_jobthread_interrupt_idle(dc_jobthread_t* jobthread) { if (jobthread==NULL) { return; } pthread_mutex_lock(&jobthread->mutex); // when we're not in idle, make sure not to enter it jobthread->jobs_needed = 1; pthread_mutex_unlock(&jobthread->mutex); dc_log_info(jobthread->context, 0, "Interrupting %s-IDLE...", jobthread->name); if (jobthread->imap) { dc_imap_interrupt_idle(jobthread->imap); } // in case we're not IMAP-ideling, also raise the signal pthread_mutex_lock(&jobthread->mutex); jobthread->idle_condflag = 1; pthread_cond_signal(&jobthread->idle_cond); pthread_mutex_unlock(&jobthread->mutex); } ``` Filename: dc_jsmn.c ```c /* Copyright (c) 2010 Serge A. Zaitsev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "dc_jsmn.h" /** * Allocates a fresh unused token from the token pool. */ static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, jsmntok_t *tokens, size_t num_tokens) { jsmntok_t *tok; if (parser->toknext >= num_tokens) { return NULL; } tok = &tokens[parser->toknext++]; tok->start = tok->end = -1; tok->size = 0; #ifdef JSMN_PARENT_LINKS tok->parent = -1; #endif return tok; } /** * Fills token type and boundaries. */ static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type, int start, int end) { token->type = type; token->start = start; token->end = end; token->size = 0; } /** * Fills next available token with JSON primitive. */ static int jsmn_parse_primitive(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, size_t num_tokens) { jsmntok_t *token; int start; start = parser->pos; for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { switch (js[parser->pos]) { #ifndef JSMN_STRICT /* In strict mode primitive must be followed by "," or "}" or "]" */ case ':': #endif case '\t' : case '\r' : case '\n' : case ' ' : case ',' : case ']' : case '}' : goto found; } if (js[parser->pos] < 32 || js[parser->pos] >= 127) { parser->pos = start; return JSMN_ERROR_INVAL; } } #ifdef JSMN_STRICT /* In strict mode primitive must be followed by a comma/object/array */ parser->pos = start; return JSMN_ERROR_PART; #endif found: if (tokens == NULL) { parser->pos--; return 0; } token = jsmn_alloc_token(parser, tokens, num_tokens); if (token == NULL) { parser->pos = start; return JSMN_ERROR_NOMEM; } jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos); #ifdef JSMN_PARENT_LINKS token->parent = parser->toksuper; #endif parser->pos--; return 0; } /** * Fills next token with JSON string. */ static int jsmn_parse_string(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, size_t num_tokens) { jsmntok_t *token; int start = parser->pos; parser->pos++; /* Skip starting quote */ for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { char c = js[parser->pos]; /* Quote: end of string */ if (c == '\"') { if (tokens == NULL) { return 0; } token = jsmn_alloc_token(parser, tokens, num_tokens); if (token == NULL) { parser->pos = start; return JSMN_ERROR_NOMEM; } jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos); #ifdef JSMN_PARENT_LINKS token->parent = parser->toksuper; #endif return 0; } /* Backslash: Quoted symbol expected */ if (c == '\\' && parser->pos + 1 < len) { int i; parser->pos++; switch (js[parser->pos]) { /* Allowed escaped symbols */ case '\"': case '/' : case '\\' : case 'b' : case 'f' : case 'r' : case 'n' : case 't' : break; /* Allows escaped symbol \uXXXX */ case 'u': parser->pos++; for(i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) { /* If it isn't a hex character we have an error */ if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */ (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */ (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */ parser->pos = start; return JSMN_ERROR_INVAL; } parser->pos++; } parser->pos--; break; /* Unexpected symbol */ default: parser->pos = start; return JSMN_ERROR_INVAL; } } } parser->pos = start; return JSMN_ERROR_PART; } /** * Parse JSON string and fill tokens. */ int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, unsigned int num_tokens) { int r; int i; jsmntok_t *token; int count = parser->toknext; for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { char c; jsmntype_t type; c = js[parser->pos]; switch (c) { case '{': case '[': count++; if (tokens == NULL) { break; } token = jsmn_alloc_token(parser, tokens, num_tokens); if (token == NULL) return JSMN_ERROR_NOMEM; if (parser->toksuper != -1) { tokens[parser->toksuper].size++; #ifdef JSMN_PARENT_LINKS token->parent = parser->toksuper; #endif } token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY); token->start = parser->pos; parser->toksuper = parser->toknext - 1; break; case '}': case ']': if (tokens == NULL) break; type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY); #ifdef JSMN_PARENT_LINKS if (parser->toknext < 1) { return JSMN_ERROR_INVAL; } token = &tokens[parser->toknext - 1]; for (;;) { if (token->start != -1 && token->end == -1) { if (token->type != type) { return JSMN_ERROR_INVAL; } token->end = parser->pos + 1; parser->toksuper = token->parent; break; } if (token->parent == -1) { if(token->type != type || parser->toksuper == -1) { return JSMN_ERROR_INVAL; } break; } token = &tokens[token->parent]; } #else for (i = parser->toknext - 1; i >= 0; i--) { token = &tokens[i]; if (token->start != -1 && token->end == -1) { if (token->type != type) { return JSMN_ERROR_INVAL; } parser->toksuper = -1; token->end = parser->pos + 1; break; } } /* Error if unmatched closing bracket */ if (i == -1) return JSMN_ERROR_INVAL; for (; i >= 0; i--) { token = &tokens[i]; if (token->start != -1 && token->end == -1) { parser->toksuper = i; break; } } #endif break; case '\"': r = jsmn_parse_string(parser, js, len, tokens, num_tokens); if (r < 0) return r; count++; if (parser->toksuper != -1 && tokens != NULL) tokens[parser->toksuper].size++; break; case '\t' : case '\r' : case '\n' : case ' ': break; case ':': parser->toksuper = parser->toknext - 1; break; case ',': if (tokens != NULL && parser->toksuper != -1 && tokens[parser->toksuper].type != JSMN_ARRAY && tokens[parser->toksuper].type != JSMN_OBJECT) { #ifdef JSMN_PARENT_LINKS parser->toksuper = tokens[parser->toksuper].parent; #else for (i = parser->toknext - 1; i >= 0; i--) { if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) { if (tokens[i].start != -1 && tokens[i].end == -1) { parser->toksuper = i; break; } } } #endif } break; #ifdef JSMN_STRICT /* In strict mode primitives are: numbers and booleans */ case '-': case '0': case '1' : case '2': case '3' : case '4': case '5': case '6': case '7' : case '8': case '9': case 't': case 'f': case 'n' : /* And they must not be keys of the object */ if (tokens != NULL && parser->toksuper != -1) { jsmntok_t *t = &tokens[parser->toksuper]; if (t->type == JSMN_OBJECT || (t->type == JSMN_STRING && t->size != 0)) { return JSMN_ERROR_INVAL; } } #else /* In non-strict mode every unquoted value is a primitive */ default: #endif r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens); if (r < 0) return r; count++; if (parser->toksuper != -1 && tokens != NULL) tokens[parser->toksuper].size++; break; #ifdef JSMN_STRICT /* Unexpected char in strict mode */ default: return JSMN_ERROR_INVAL; #endif } } if (tokens != NULL) { for (i = parser->toknext - 1; i >= 0; i--) { /* Unmatched opened object or array */ if (tokens[i].start != -1 && tokens[i].end == -1) { return JSMN_ERROR_PART; } } } return count; } /** * Creates a new parser based over a given buffer with an array of tokens * available. */ void jsmn_init(jsmn_parser *parser) { parser->pos = 0; parser->toknext = 0; parser->toksuper = -1; } ``` Filename: dc_key.c ```c #include #include #include "dc_context.h" #include "dc_key.h" #include "dc_pgp.h" #include "dc_tools.h" void dc_wipe_secret_mem(void* buf, size_t buf_bytes) { /* wipe private keys or othere secrets with zeros so that secrets are no longer in RAM */ if (buf==NULL || buf_bytes <= 0) { return; } memset(buf, 0x00, buf_bytes); } static void dc_key_empty(dc_key_t* key) /* only use before calling setters; take care when using this function together with reference counting, prefer new objects instead */ { if (key==NULL) { return; } if (key->type==DC_KEY_PRIVATE) { dc_wipe_secret_mem(key->binary, key->bytes); } free(key->binary); key->binary = NULL; key->bytes = 0; key->type = DC_KEY_PUBLIC; } dc_key_t* dc_key_new() { dc_key_t* key; if ((key=calloc(1, sizeof(dc_key_t)))==NULL) { exit(44); /* cannot allocate little memory, unrecoverable error */ } key->_m_heap_refcnt = 1; return key; } dc_key_t* dc_key_ref(dc_key_t* key) { if (key==NULL) { return NULL; } key->_m_heap_refcnt++; return key; } void dc_key_unref(dc_key_t* key) { if (key==NULL) { return; } key->_m_heap_refcnt--; if (key->_m_heap_refcnt != 0) { return; } dc_key_empty(key); free(key); } int dc_key_set_from_binary(dc_key_t* key, const void* data, int bytes, int type) { dc_key_empty(key); if (key==NULL || data==NULL || bytes <= 0) { return 0; } key->binary = malloc(bytes); if (key->binary==NULL) { exit(40); } memcpy(key->binary, data, bytes); key->bytes = bytes; key->type = type; return 1; } int dc_key_set_from_key(dc_key_t* key, const dc_key_t* o) { dc_key_empty(key); if (key==NULL || o==NULL) { return 0; } return dc_key_set_from_binary(key, o->binary, o->bytes, o->type); } int dc_key_set_from_stmt(dc_key_t* key, sqlite3_stmt* stmt, int index, int type) { dc_key_empty(key); if (key==NULL || stmt==NULL) { return 0; } return dc_key_set_from_binary(key, (unsigned char*)sqlite3_column_blob(stmt, index), sqlite3_column_bytes(stmt, index), type); } int dc_key_set_from_base64(dc_key_t* key, const char* base64, int type) { size_t indx = 0, result_len = 0; char* result = NULL; dc_key_empty(key); if (key==NULL || base64==NULL) { return 0; } if (mailmime_base64_body_parse(base64, strlen(base64), &indx, &result/*must be freed using mmap_string_unref()*/, &result_len)!=MAILIMF_NO_ERROR || result==NULL || result_len==0) { return 0; /* bad key */ } dc_key_set_from_binary(key, result, result_len, type); mmap_string_unref(result); return 1; } int dc_key_set_from_file(dc_key_t* key, const char* pathNfilename, dc_context_t* context) { char* buf = NULL; const char* headerline = NULL; // just pointer inside buf, must not be freed const char* base64 = NULL; // - " - size_t buf_bytes = 0; int type = -1; int success = 0; dc_key_empty(key); if (key==NULL || pathNfilename==NULL) { goto cleanup; } if (!dc_read_file(context, pathNfilename, (void**)&buf, &buf_bytes) || buf_bytes < 50) { goto cleanup; /* error is already loged */ } if (!dc_split_armored_data(buf, &headerline, NULL, NULL, &base64) || headerline==NULL || base64==NULL) { goto cleanup; } if (strcmp(headerline, "-----BEGIN PGP PUBLIC KEY BLOCK-----")==0) { type = DC_KEY_PUBLIC; } else if (strcmp(headerline, "-----BEGIN PGP PRIVATE KEY BLOCK-----")==0) { type = DC_KEY_PRIVATE; } else { dc_log_warning(context, 0, "Header missing for key \"%s\".", pathNfilename); goto cleanup; } if (!dc_key_set_from_base64(key, base64, type)) { dc_log_warning(context, 0, "Bad data in key \"%s\".", pathNfilename); goto cleanup; } success = 1; cleanup: free(buf); return success; } int dc_key_equals(const dc_key_t* key, const dc_key_t* o) { if (key==NULL || o==NULL || key->binary==NULL || key->bytes<=0 || o->binary==NULL || o->bytes<=0) { return 0; /*error*/ } if (key->bytes != o->bytes) { return 0; /*different size -> the keys cannot be equal*/ } if (key->type != o->type) { return 0; /* cannot compare public with private keys */ } return memcmp(key->binary, o->binary, o->bytes)==0? 1 : 0; } /******************************************************************************* * Save/Load keys ******************************************************************************/ int dc_key_save_self_keypair(const dc_key_t* public_key, const dc_key_t* private_key, const char* addr, int is_default, dc_sqlite3_t* sql) { int success = 0; sqlite3_stmt* stmt = NULL; if (public_key==NULL || private_key==NULL || addr==NULL || sql==NULL || public_key->binary==NULL || private_key->binary==NULL) { goto cleanup; } stmt = dc_sqlite3_prepare(sql, "INSERT INTO keypairs (addr, is_default, public_key, private_key, created) VALUES (?,?,?,?,?);"); sqlite3_bind_text (stmt, 1, addr, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 2, is_default); sqlite3_bind_blob (stmt, 3, public_key->binary, public_key->bytes, SQLITE_STATIC); sqlite3_bind_blob (stmt, 4, private_key->binary, private_key->bytes, SQLITE_STATIC); sqlite3_bind_int64(stmt, 5, time(NULL)); if (sqlite3_step(stmt)!=SQLITE_DONE) { goto cleanup; } success = 1; cleanup: sqlite3_finalize(stmt); return success; } int dc_key_load_self_public(dc_key_t* key, const char* self_addr, dc_sqlite3_t* sql) { int success = 0; sqlite3_stmt* stmt = NULL; if (key==NULL || self_addr==NULL || sql==NULL) { goto cleanup; } dc_key_empty(key); stmt = dc_sqlite3_prepare(sql, "SELECT public_key FROM keypairs WHERE addr=? AND is_default=1;"); sqlite3_bind_text (stmt, 1, self_addr, -1, SQLITE_STATIC); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } dc_key_set_from_stmt(key, stmt, 0, DC_KEY_PUBLIC); success = 1; cleanup: sqlite3_finalize(stmt); return success; } int dc_key_load_self_private(dc_key_t* key, const char* self_addr, dc_sqlite3_t* sql) { int success = 0; sqlite3_stmt* stmt = NULL; if (key==NULL || self_addr==NULL || sql==NULL) { goto cleanup; } dc_key_empty(key); stmt = dc_sqlite3_prepare(sql, "SELECT private_key FROM keypairs WHERE addr=? AND is_default=1;"); sqlite3_bind_text (stmt, 1, self_addr, -1, SQLITE_STATIC); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } dc_key_set_from_stmt(key, stmt, 0, DC_KEY_PRIVATE); success = 1; cleanup: sqlite3_finalize(stmt); return success; } /******************************************************************************* * Render keys ******************************************************************************/ static long crc_octets(const unsigned char *octets, size_t len) { #define CRC24_INIT 0xB704CEL #define CRC24_POLY 0x1864CFBL long crc = CRC24_INIT; while (len--) { crc ^= (*octets++) << 16; for (int i = 0; i < 8; i++) { crc <<= 1; if (crc & 0x1000000) crc ^= CRC24_POLY; } } return crc & 0xFFFFFFL; } char* dc_render_base64(const void* buf, size_t buf_bytes, int break_every, const char* break_chars, int add_checksum /*0=no checksum, 1=add without break, 2=add with break_chars*/) { char* ret = NULL; if (buf==NULL || buf_bytes<=0) { goto cleanup; } if ((ret = encode_base64((const char*)buf, buf_bytes))==NULL) { goto cleanup; } #if 0 if (add_checksum==1/*appended checksum*/) { long checksum = crc_octets(buf, buf_bytes); uint8_t c[3]; c[0] = (uint8_t)((checksum >> 16)&0xFF); c[1] = (uint8_t)((checksum >> 8)&0xFF); c[2] = (uint8_t)((checksum)&0xFF); char* c64 = encode_base64((const char*)c, 3); char* temp = ret; ret = dc_mprintf("%s=%s", temp, c64); free(temp); free(c64); } #endif if (break_every>0) { char* temp = ret; ret = dc_insert_breaks(temp, break_every, break_chars); free(temp); } if (add_checksum==2/*checksum with break character*/) { long checksum = crc_octets(buf, buf_bytes); uint8_t c[3]; c[0] = (uint8_t)((checksum >> 16)&0xFF); c[1] = (uint8_t)((checksum >> 8)&0xFF); c[2] = (uint8_t)((checksum)&0xFF); char* c64 = encode_base64((const char*)c, 3); char* temp = ret; ret = dc_mprintf("%s%s=%s", temp, break_chars, c64); free(temp); free(c64); } cleanup: return ret; } char* dc_key_render_base64(const dc_key_t* key, int break_every, const char* break_chars, int add_checksum) { if (key==NULL) { return NULL; } return dc_render_base64(key->binary, key->bytes, break_every, break_chars, add_checksum); } char* dc_key_render_asc(const dc_key_t* key, const char* add_header_lines /*must be terminated by \r\n*/) { /* see RFC 4880, 6.2. Forming ASCII Armor, https://tools.ietf.org/html/rfc4880#section-6.2 */ char* base64 = NULL; char* ret = NULL; if (key==NULL) { goto cleanup; } if ((base64=dc_key_render_base64(key, 76, "\r\n", 2/*checksum in new line*/))==NULL) { /* RFC: The encoded output stream must be represented in lines of no more than 76 characters each. */ goto cleanup; } ret = dc_mprintf("-----BEGIN PGP %s KEY BLOCK-----\r\n%s\r\n%s\r\n-----END PGP %s KEY BLOCK-----\r\n", key->type==DC_KEY_PUBLIC? "PUBLIC" : "PRIVATE", add_header_lines? add_header_lines : "", base64, key->type==DC_KEY_PUBLIC? "PUBLIC" : "PRIVATE"); cleanup: free(base64); return ret; } int dc_key_render_asc_to_file(const dc_key_t* key, const char* file, dc_context_t* context /* for logging only */) { int success = 0; char* file_content = NULL; if (key==NULL || file==NULL || context==NULL) { goto cleanup; } file_content = dc_key_render_asc(key, NULL); if (file_content==NULL) { goto cleanup; } if (!dc_write_file(context, file, file_content, strlen(file_content))) { dc_log_error(context, 0, "Cannot write key to %s", file); goto cleanup; } success = 1; cleanup: free(file_content); return success; } /* make a fingerprint human-readable */ char* dc_format_fingerprint(const char* fingerprint) { int i = 0; int fingerprint_len = strlen(fingerprint); dc_strbuilder_t ret; dc_strbuilder_init(&ret, 0); while (fingerprint[i]) { dc_strbuilder_catf(&ret, "%c", fingerprint[i]); i++; if (i!=fingerprint_len) { if (i%20==0) { dc_strbuilder_cat(&ret, "\n"); } else if (i%4==0) { dc_strbuilder_cat(&ret, " "); } } } return ret.buf; } /* bring a human-readable or otherwise formatted fingerprint back to the 40-characters-uppercase-hex format */ char* dc_normalize_fingerprint(const char* in) { if (in==NULL) { return NULL; } dc_strbuilder_t out; dc_strbuilder_init(&out, 0); const char* p1 = in; while (*p1) { if ((*p1 >= '0' && *p1 <= '9') || (*p1 >= 'A' && *p1 <= 'F') || (*p1 >= 'a' && *p1 <= 'f')) { dc_strbuilder_catf(&out, "%c", toupper(*p1)); /* make uppercase which is needed as we do not search case-insensitive, see comment in dc_sqlite3.c */ } p1++; } return out.buf; } char* dc_key_get_fingerprint(const dc_key_t* key) { uint8_t* fingerprint_buf = NULL; size_t fingerprint_bytes = 0; char* fingerprint_hex = NULL; if (key==NULL) { goto cleanup; } if (!dc_pgp_calc_fingerprint(key, &fingerprint_buf, &fingerprint_bytes)) { goto cleanup; } fingerprint_hex = dc_binary_to_uc_hex(fingerprint_buf, fingerprint_bytes); cleanup: free(fingerprint_buf); return fingerprint_hex? fingerprint_hex : dc_strdup(NULL); } char* dc_key_get_formatted_fingerprint(const dc_key_t* key) { char* rawhex = dc_key_get_fingerprint(key); char* formatted = dc_format_fingerprint(rawhex); free(rawhex); return formatted; } ``` Filename: dc_keyhistory.c ```c #include "dc_context.h" void dc_add_to_keyhistory(dc_context_t* context, const char* rfc724_mid, time_t sending_time, const char* addr, const char* fingerprint) { // TODO } ``` Filename: dc_keyring.c ```c #include #include "dc_context.h" #include "dc_key.h" #include "dc_keyring.h" #include "dc_tools.h" dc_keyring_t* dc_keyring_new() { dc_keyring_t* keyring; if ((keyring=calloc(1, sizeof(dc_keyring_t)))==NULL) { exit(42); /* cannot allocate little memory, unrecoverable error */ } return keyring; } void dc_keyring_unref(dc_keyring_t* keyring) { if (keyring == NULL) { return; } for (int i = 0; i < keyring->count; i++) { dc_key_unref(keyring->keys[i]); } free(keyring->keys); free(keyring); } void dc_keyring_add(dc_keyring_t* keyring, dc_key_t* to_add) { if (keyring==NULL || to_add==NULL) { return; } /* expand array, if needed */ if (keyring->count == keyring->allocated) { int newsize = (keyring->allocated * 2) + 10; if ((keyring->keys=realloc(keyring->keys, newsize*sizeof(dc_key_t*)))==NULL) { exit(41); } keyring->allocated = newsize; } keyring->keys[keyring->count] = dc_key_ref(to_add); keyring->count++; } int dc_keyring_load_self_private_for_decrypting(dc_keyring_t* keyring, const char* self_addr, dc_sqlite3_t* sql) { if (keyring==NULL || self_addr==NULL || sql==NULL) { return 0; } sqlite3_stmt* stmt = dc_sqlite3_prepare(sql, "SELECT private_key FROM keypairs ORDER BY addr=? DESC, is_default DESC;"); sqlite3_bind_text (stmt, 1, self_addr, -1, SQLITE_STATIC); while (sqlite3_step(stmt) == SQLITE_ROW) { dc_key_t* key = dc_key_new(); if (dc_key_set_from_stmt(key, stmt, 0, DC_KEY_PRIVATE)) { dc_keyring_add(keyring, key); } dc_key_unref(key); /* unref in any case, dc_keyring_add() adds its own reference */ } sqlite3_finalize(stmt); return 1; } ``` Filename: dc_location.c ```c #include "dc_context.h" #include "dc_saxparser.h" #include "dc_mimefactory.h" /******************************************************************************* * create kml-files ******************************************************************************/ static char* get_kml_timestamp(time_t utc) { // Returns a string formatted as YYYY-MM-DDTHH:MM:SSZ. The trailing `Z` indicates UTC. struct tm wanted_struct; memcpy(&wanted_struct, gmtime(&utc), sizeof(struct tm)); return dc_mprintf("%04i-%02i-%02iT%02i:%02i:%02iZ", (int)wanted_struct.tm_year+1900, (int)wanted_struct.tm_mon+1, (int)wanted_struct.tm_mday, (int)wanted_struct.tm_hour, (int)wanted_struct.tm_min, (int)wanted_struct.tm_sec); } char* dc_get_location_kml(dc_context_t* context, uint32_t chat_id, uint32_t* last_added_location_id) { int success = 0; sqlite3_stmt* stmt = NULL; char* self_addr = NULL; time_t now = time(NULL); time_t locations_send_begin = 0; time_t locations_send_until = 0; time_t locations_last_sent = 0; int location_count = 0; dc_strbuilder_t ret; dc_strbuilder_init(&ret, 1000); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } // get info about the contact and the chat self_addr = dc_sqlite3_get_config(context->sql, "configured_addr", ""); stmt = dc_sqlite3_prepare(context->sql, "SELECT locations_send_begin, locations_send_until, locations_last_sent" " FROM chats " " WHERE id=?;"); sqlite3_bind_int(stmt, 1, chat_id); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } locations_send_begin = sqlite3_column_int64(stmt, 0); locations_send_until = sqlite3_column_int64(stmt, 1); locations_last_sent = sqlite3_column_int64(stmt, 2); sqlite3_finalize(stmt); stmt = NULL; if (locations_send_begin==0 || now>locations_send_until) { goto cleanup; } // build kml file dc_strbuilder_catf(&ret, "\n" "\n" "\n", self_addr); stmt = dc_sqlite3_prepare(context->sql, "SELECT id, latitude, longitude, accuracy, timestamp " " FROM locations " " WHERE from_id=? " " AND timestamp>=? " " AND (timestamp>=? OR timestamp=(SELECT MAX(timestamp) FROM locations WHERE from_id=?)) " " AND independent=0 " " GROUP BY timestamp " " ORDER BY timestamp;"); sqlite3_bind_int (stmt, 1, DC_CONTACT_ID_SELF); sqlite3_bind_int64 (stmt, 2, locations_send_begin); sqlite3_bind_int64 (stmt, 3, locations_last_sent); sqlite3_bind_int (stmt, 4, DC_CONTACT_ID_SELF); while (sqlite3_step(stmt)==SQLITE_ROW) { uint32_t location_id = sqlite3_column_int(stmt, 0); char* latitude = dc_ftoa(sqlite3_column_double(stmt, 1)); char* longitude = dc_ftoa(sqlite3_column_double(stmt, 2)); char* accuracy = dc_ftoa(sqlite3_column_double(stmt, 3)); char* timestamp = get_kml_timestamp(sqlite3_column_int64 (stmt, 4)); dc_strbuilder_catf(&ret, "" "%s" "%s,%s" "\n", timestamp, accuracy, longitude, // reverse order! latitude); location_count++; if (last_added_location_id) { *last_added_location_id = location_id; } free(latitude); free(longitude); free(accuracy); free(timestamp); } if (location_count==0) { goto cleanup; } dc_strbuilder_cat(&ret, "\n" ""); success = 1; cleanup: sqlite3_finalize(stmt); free(self_addr); if (!success) { free(ret.buf); } return success? ret.buf : NULL; } char* dc_get_message_kml(dc_context_t* context, time_t timestamp, double latitude, double longitude) { char* timestamp_str = NULL; char* latitude_str = NULL; char* longitude_str = NULL; char* ret = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } timestamp_str = get_kml_timestamp(timestamp); latitude_str = dc_ftoa(latitude); longitude_str = dc_ftoa(longitude); ret = dc_mprintf( "\n" "\n" "\n" "" "%s" "%s,%s" "\n" "\n" "", timestamp_str, longitude_str, // reverse order! latitude_str); cleanup: free(latitude_str); free(longitude_str); free(timestamp_str); return ret; } void dc_set_kml_sent_timestamp(dc_context_t* context, uint32_t chat_id, time_t timestamp) { sqlite3_stmt* stmt = NULL; stmt = dc_sqlite3_prepare(context->sql, "UPDATE chats SET locations_last_sent=? WHERE id=?;"); sqlite3_bind_int64(stmt, 1, timestamp); sqlite3_bind_int (stmt, 2, chat_id); sqlite3_step(stmt); sqlite3_finalize(stmt); } void dc_set_msg_location_id(dc_context_t* context, uint32_t msg_id, uint32_t location_id) { sqlite3_stmt* stmt = NULL; stmt = dc_sqlite3_prepare(context->sql, "UPDATE msgs SET location_id=? WHERE id=?;"); sqlite3_bind_int64(stmt, 1, location_id); sqlite3_bind_int (stmt, 2, msg_id); sqlite3_step(stmt); sqlite3_finalize(stmt); } /******************************************************************************* * parse kml-files ******************************************************************************/ #define TAG_PLACEMARK 0x01 #define TAG_TIMESTAMP 0x02 #define TAG_WHEN 0x04 #define TAG_POINT 0x08 #define TAG_COORDINATES 0x10 static void kml_starttag_cb(void* userdata, const char* tag, char** attr) { dc_kml_t* kml = (dc_kml_t*)userdata; if (strcmp(tag, "document")==0) { const char* addr = dc_attr_find(attr, "addr"); if (addr) { kml->addr = dc_strdup(addr); } } else if (strcmp(tag, "placemark")==0) { kml->tag = TAG_PLACEMARK; kml->curr.timestamp = 0; kml->curr.latitude = 0; kml->curr.longitude = 0.0; kml->curr.accuracy = 0.0; } else if (strcmp(tag, "timestamp")==0 && kml->tag&TAG_PLACEMARK) { kml->tag = TAG_PLACEMARK|TAG_TIMESTAMP; } else if (strcmp(tag, "when")==0 && kml->tag&TAG_TIMESTAMP) { kml->tag = TAG_PLACEMARK|TAG_TIMESTAMP|TAG_WHEN; } else if (strcmp(tag, "point")==0 && kml->tag&TAG_PLACEMARK) { kml->tag = TAG_PLACEMARK|TAG_POINT; } else if (strcmp(tag, "coordinates")==0 && kml->tag&TAG_POINT) { kml->tag = TAG_PLACEMARK|TAG_POINT|TAG_COORDINATES; const char* accuracy = dc_attr_find(attr, "accuracy"); if (accuracy) { kml->curr.accuracy = dc_atof(accuracy); } } } static void kml_text_cb(void* userdata, const char* text, int len) { dc_kml_t* kml = (dc_kml_t*)userdata; if (kml->tag&(TAG_WHEN|TAG_COORDINATES)) { char* val = dc_strdup(text); dc_str_replace(&val, "\n", ""); dc_str_replace(&val, "\r", ""); dc_str_replace(&val, "\t", ""); dc_str_replace(&val, " ", ""); if (kml->tag&TAG_WHEN && strlen(val)>=19) { struct tm tmval; memset(&tmval, 0, sizeof(struct tm)); // YYYY-MM-DDTHH:MM:SS // 0 4 7 10 13 16 19 val[4] = 0; tmval.tm_year = atoi(val) - 1900; val[7] = 0; tmval.tm_mon = atoi(val+5) - 1; val[10] = 0; tmval.tm_mday = atoi(val+8); val[13] = 0; tmval.tm_hour = atoi(val+11); val[16] = 0; tmval.tm_min = atoi(val+14); val[19] = 0; tmval.tm_sec = atoi(val+17); kml->curr.timestamp = mkgmtime(&tmval); if (kml->curr.timestamp>time(NULL)) { kml->curr.timestamp = time(NULL); } } else if (kml->tag&TAG_COORDINATES) { char* comma = strchr(val, ','); if (comma) { char* longitude = val; // reverse order! char* latitude = comma+1; *comma = 0; comma = strchr(latitude, ','); if (comma) { *comma = 0; } kml->curr.latitude = dc_atof(latitude); kml->curr.longitude = dc_atof(longitude); } } free(val); } } static void kml_endtag_cb(void* userdata, const char* tag) { dc_kml_t* kml = (dc_kml_t*)userdata; if (strcmp(tag, "placemark")==0) { if (kml->tag&TAG_PLACEMARK && kml->curr.timestamp && kml->curr.latitude && kml->curr.longitude) { dc_location_t* location = calloc(1, sizeof(dc_location_t)); *location = kml->curr; dc_array_add_ptr(kml->locations, location); } kml->tag = 0; } } dc_kml_t* dc_kml_parse(dc_context_t* context, const char* content, size_t content_bytes) { dc_kml_t* kml = calloc(1, sizeof(dc_kml_t)); char* content_nullterminated = NULL; dc_saxparser_t saxparser; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (content_bytes > 1*1024*1024) { dc_log_warning(context, 0, "A kml-files with %i bytes is larger than reasonably expected.", content_bytes); goto cleanup; } content_nullterminated = dc_null_terminate(content, content_bytes); if (content_nullterminated==NULL) { goto cleanup; } kml->locations = dc_array_new_typed(context, DC_ARRAY_LOCATIONS, 100); dc_saxparser_init (&saxparser, kml); dc_saxparser_set_tag_handler (&saxparser, kml_starttag_cb, kml_endtag_cb); dc_saxparser_set_text_handler(&saxparser, kml_text_cb); dc_saxparser_parse (&saxparser, content_nullterminated); cleanup: free(content_nullterminated); return kml; } void dc_kml_unref(dc_kml_t* kml) { if (kml==NULL) { return; } dc_array_unref(kml->locations); free(kml->addr); free(kml); } uint32_t dc_save_locations(dc_context_t* context, uint32_t chat_id, uint32_t contact_id, const dc_array_t* locations, int independent) { sqlite3_stmt* stmt_test = NULL; sqlite3_stmt* stmt_insert = NULL; time_t newest_timestamp = 0; uint32_t newest_location_id = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || chat_id<=DC_CHAT_ID_LAST_SPECIAL || locations==NULL) { goto cleanup; } stmt_test = dc_sqlite3_prepare(context->sql, "SELECT id FROM locations WHERE timestamp=? AND from_id=?"); stmt_insert = dc_sqlite3_prepare(context->sql, "INSERT INTO locations " " (timestamp,from_id,chat_id, latitude,longitude,accuracy, independent)" " VALUES (?,?,?, ?,?,?, ?);"); for (int i=0; itimestamp); sqlite3_bind_int (stmt_test, 2, contact_id); if (independent || sqlite3_step(stmt_test)!=SQLITE_ROW) { sqlite3_reset (stmt_insert); sqlite3_bind_int64 (stmt_insert, 1, location->timestamp); sqlite3_bind_int (stmt_insert, 2, contact_id); sqlite3_bind_int (stmt_insert, 3, chat_id); sqlite3_bind_double(stmt_insert, 4, location->latitude); sqlite3_bind_double(stmt_insert, 5, location->longitude); sqlite3_bind_double(stmt_insert, 6, location->accuracy); sqlite3_bind_double(stmt_insert, 7, independent); sqlite3_step(stmt_insert); } if (location->timestamp > newest_timestamp) { newest_timestamp = location->timestamp; newest_location_id = dc_sqlite3_get_rowid2(context->sql, "locations", "timestamp", location->timestamp, "from_id", contact_id); } } cleanup: sqlite3_finalize(stmt_test); sqlite3_finalize(stmt_insert); return newest_location_id; } /******************************************************************************* * job to send locations out to all chats that want them ******************************************************************************/ #define MAYBE_SEND_LOCATIONS_WAIT_SECONDS 60 static void schedule_MAYBE_SEND_LOCATIONS(dc_context_t* context, int flags) { #define FORCE_SCHEDULE 0x01 if ((flags&FORCE_SCHEDULE) || !dc_job_action_exists(context, DC_JOB_MAYBE_SEND_LOCATIONS)) { dc_job_add(context, DC_JOB_MAYBE_SEND_LOCATIONS, 0, NULL, MAYBE_SEND_LOCATIONS_WAIT_SECONDS); } } void dc_job_do_DC_JOB_MAYBE_SEND_LOCATIONS(dc_context_t* context, dc_job_t* job) { sqlite3_stmt* stmt_chats = NULL; sqlite3_stmt* stmt_locations = NULL; time_t now = time(NULL); int continue_streaming = 1; dc_log_info(context, 0, " ----------------- MAYBE_SEND_LOCATIONS -------------- "); stmt_chats = dc_sqlite3_prepare(context->sql, "SELECT id, locations_send_begin, locations_last_sent " " FROM chats " " WHERE locations_send_until>?;"); // this should be the same condition as for the return value dc_set_location() sqlite3_bind_int64(stmt_chats, 1, now); while (sqlite3_step(stmt_chats)==SQLITE_ROW) { uint32_t chat_id = sqlite3_column_int (stmt_chats, 0); time_t locations_send_begin = sqlite3_column_int64(stmt_chats, 1); time_t locations_last_sent = sqlite3_column_int64(stmt_chats, 2); continue_streaming = 1; // be a bit tolerant as the timer may not align exactly with time(NULL) if (now-locations_last_sent < (MAYBE_SEND_LOCATIONS_WAIT_SECONDS-3)) { continue; } if (stmt_locations==NULL) { stmt_locations = dc_sqlite3_prepare(context->sql, "SELECT id " " FROM locations " " WHERE from_id=? " " AND timestamp>=? " " AND timestamp>? " " AND independent=0 " " ORDER BY timestamp;"); } else { sqlite3_reset(stmt_locations); } sqlite3_bind_int (stmt_locations, 1, DC_CONTACT_ID_SELF); sqlite3_bind_int64 (stmt_locations, 2, locations_send_begin); sqlite3_bind_int64 (stmt_locations, 3, locations_last_sent); // if there is no new location, there's nothing to send. // however, maybe we want to bypass this test eg. 15 minutes if (sqlite3_step(stmt_locations)!=SQLITE_ROW) { continue; } // pending locations are attached automatically to every message, // so also to this empty text message. // DC_CMD_LOCATION is only needed to create a nicer subject. // // for optimisation and to avoid flooding the sending queue, // we could sending these messages only if we're really online. // the easiest way to determine this, is to check for an empty message queue. // (might not be 100%, however, as positions are sent combined later // and dc_set_location() is typically called periodically, this is ok) dc_msg_t* msg = dc_msg_new(context, DC_MSG_TEXT); msg->hidden = 1; dc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_LOCATION_ONLY); dc_send_msg(context, chat_id, msg); dc_msg_unref(msg); } if (continue_streaming) { // force scheduing as there is at least one job - the current one schedule_MAYBE_SEND_LOCATIONS(context, FORCE_SCHEDULE); } //cleanup: sqlite3_finalize(stmt_chats); sqlite3_finalize(stmt_locations); } void dc_job_do_DC_JOB_MAYBE_SEND_LOC_ENDED(dc_context_t* context, dc_job_t* job) { // this function is called when location-streaming _might_ have ended for a chat. // the function checks, if location-streaming is really ended; // if so, a device-message is added if not yet done. uint32_t chat_id = job->foreign_id; time_t locations_send_begin = 0; time_t locations_send_until = 0; sqlite3_stmt* stmt = NULL; char* stock_str = NULL; stmt = dc_sqlite3_prepare(context->sql, "SELECT locations_send_begin, locations_send_until " " FROM chats " " WHERE id=?"); sqlite3_bind_int (stmt, 1, chat_id); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } locations_send_begin = sqlite3_column_int64(stmt, 0); locations_send_until = sqlite3_column_int64(stmt, 1); sqlite3_finalize(stmt); stmt = NULL; if (locations_send_begin!=0 && time(NULL)<=locations_send_until) { // still streaming - // may happen as several calls to dc_send_locations_to_chat() // do not un-schedule pending DC_MAYBE_SEND_LOC_ENDED jobs goto cleanup; } if (locations_send_begin==0 && locations_send_until==0) { // not streaming, device-message already sent goto cleanup; } // inform the ui that location-streaming has ended stmt = dc_sqlite3_prepare(context->sql, "UPDATE chats " " SET locations_send_begin=0, locations_send_until=0 " " WHERE id=?"); sqlite3_bind_int (stmt, 1, chat_id); sqlite3_step(stmt); stock_str = dc_stock_system_msg(context, DC_STR_MSGLOCATIONDISABLED, NULL, NULL, 0); dc_add_device_msg(context, chat_id, stock_str); context->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0); cleanup: sqlite3_finalize(stmt); free(stock_str); } /******************************************************************************* * high-level ui-functions ******************************************************************************/ /** * Enable or disable location streaming for a chat. * Locations are sent to all members of the chat for the given number of seconds; * after that, location streaming is automatically disabled for the chat. * The current location streaming state of a chat * can be checked using dc_is_sending_locations_to_chat(). * * The locations that should be sent to the chat can be set using * dc_set_location(). * * @memberof dc_context_t * @param context The context object. * @param chat_id Chat id to enable location streaming for. * @param seconds >0: enable location streaming for the given number of seconds; * 0: disable location streaming. * @return None. */ void dc_send_locations_to_chat(dc_context_t* context, uint32_t chat_id, int seconds) { sqlite3_stmt* stmt = NULL; time_t now = time(NULL); dc_msg_t* msg = NULL; char* stock_str = NULL; int is_sending_locations_before = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || seconds<0 || chat_id<=DC_CHAT_ID_LAST_SPECIAL) { goto cleanup; } is_sending_locations_before = dc_is_sending_locations_to_chat(context, chat_id); stmt = dc_sqlite3_prepare(context->sql, "UPDATE chats " " SET locations_send_begin=?, " " locations_send_until=? " " WHERE id=?"); sqlite3_bind_int64(stmt, 1, seconds? now : 0); sqlite3_bind_int64(stmt, 2, seconds? now+seconds : 0); sqlite3_bind_int (stmt, 3, chat_id); sqlite3_step(stmt); // add/sent status message. // as disable also happens after a timeout, this is not sent explicitly. if (seconds && !is_sending_locations_before) { msg = dc_msg_new(context, DC_MSG_TEXT); msg->text = dc_stock_system_msg(context, DC_STR_MSGLOCATIONENABLED, NULL, NULL, 0); dc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_LOCATION_STREAMING_ENABLED); dc_send_msg(context, chat_id, msg); } else if(!seconds && is_sending_locations_before) { stock_str = dc_stock_system_msg(context, DC_STR_MSGLOCATIONDISABLED, NULL, NULL, 0); dc_add_device_msg(context, chat_id, stock_str); } // update eg. the "location-sending"-icon context->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0); if (seconds) { schedule_MAYBE_SEND_LOCATIONS(context, 0); dc_job_add(context, DC_JOB_MAYBE_SEND_LOC_ENDED, chat_id, NULL, seconds+1); } cleanup: free(stock_str); dc_msg_unref(msg); sqlite3_finalize(stmt); } /** * Check if location streaming is enabled. * Location stream can be enabled or disabled using dc_send_locations_to_chat(). * If you have already a dc_chat_t object, * dc_chat_is_sending_locations() may be more handy. * * @memberof dc_context_t * @param context The context object. * @param chat_id >0: Check if location streaming is enabled for the given chat. * 0: Check of location streaming is enabled for any chat. * @return 1: location streaming is enabled for the given chat(s); * 0: location streaming is disabled for the given chat(s). */ int dc_is_sending_locations_to_chat(dc_context_t* context, uint32_t chat_id) { int is_sending_locations = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT id " " FROM chats " " WHERE (? OR id=?)" " AND locations_send_until>?;"); sqlite3_bind_int (stmt, 1, chat_id==0? 1 : 0); sqlite3_bind_int (stmt, 2, chat_id); sqlite3_bind_int64(stmt, 3, time(NULL)); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } is_sending_locations = 1; cleanup: sqlite3_finalize(stmt); return is_sending_locations; } /** * Set current location. * The location is sent to all chats where location streaming is enabled * using dc_send_locations_to_chat(). * * Typically results in the event #DC_EVENT_LOCATION_CHANGED with * contact_id set to DC_CONTACT_ID_SELF. * * The UI should call this function on all location changes. * The locations set by this function are not sent immediately, * instead a message with the last locations is sent out every some minutes * or when the user sends out a normal message, * the last locations are attached. * * @memberof dc_context_t * @param context The context object. * @param latitude North-south position of the location. * Set to 0.0 if the latitude is not known. * @param longitude East-west position of the location. * Set to 0.0 if the longitude is not known. * @param accuracy Estimated accuracy of the location, radial, in meters. * Set to 0.0 if the accuracy is not known. * @return 1: location streaming is still enabled for at least one chat, * this dc_set_location() should be called as soon as the location changes; * 0: location streaming is no longer needed, * dc_is_sending_locations_to_chat() is false for all chats. */ int dc_set_location(dc_context_t* context, double latitude, double longitude, double accuracy) { sqlite3_stmt* stmt_chats = NULL; sqlite3_stmt* stmt_insert = NULL; int continue_streaming = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || (latitude==0.0 && longitude==0.0)) { continue_streaming = 1; goto cleanup; } stmt_chats = dc_sqlite3_prepare(context->sql, "SELECT id FROM chats WHERE locations_send_until>?;"); sqlite3_bind_int64(stmt_chats, 1, time(NULL)); while (sqlite3_step(stmt_chats)==SQLITE_ROW) { uint32_t chat_id = sqlite3_column_int(stmt_chats, 0); stmt_insert = dc_sqlite3_prepare(context->sql, "INSERT INTO locations " " (latitude, longitude, accuracy, timestamp, chat_id, from_id)" " VALUES (?,?,?,?,?,?);"); sqlite3_bind_double(stmt_insert, 1, latitude); sqlite3_bind_double(stmt_insert, 2, longitude); sqlite3_bind_double(stmt_insert, 3, accuracy); sqlite3_bind_int64 (stmt_insert, 4, time(NULL)); sqlite3_bind_int (stmt_insert, 5, chat_id); sqlite3_bind_int (stmt_insert, 6, DC_CONTACT_ID_SELF); sqlite3_step(stmt_insert); continue_streaming = 1; } if (continue_streaming) { context->cb(context, DC_EVENT_LOCATION_CHANGED, DC_CONTACT_ID_SELF, 0); schedule_MAYBE_SEND_LOCATIONS(context, 0); } cleanup: sqlite3_finalize(stmt_chats); sqlite3_finalize(stmt_insert); return continue_streaming; } static int is_marker(const char* txt) { if (txt) { int len = dc_utf8_strlen(txt); if (len==1 && txt[0]!=' ') { return 1; } } return 0; } /** * Get shared locations from the database. * The locations can be filtered by the chat-id, the contact-id * and by a timespan. * * The number of returned locations can be retrieved using dc_array_get_cnt(). * To get information for each location, * use dc_array_get_latitude(), dc_array_get_longitude(), * dc_array_get_accuracy(), dc_array_get_timestamp(), dc_array_get_contact_id() * and dc_array_get_msg_id(). * The latter returns 0 if there is no message bound to the location. * * Note that only if dc_array_is_independent() returns 0, * the location is the current or a past position of the user. * If dc_array_is_independent() returns 1, * the location is any location on earth that is marked by the user. * * @memberof dc_context_t * @param context The context object. * @param chat_id Chat-id to get location information for. * 0 to get locations independently of the chat. * @param contact_id Contact-id to get location information for. * If also a chat-id is given, this should be a member of the given chat. * 0 to get locations independently of the contact. * @param timestamp_from Start of timespan to return. * Must be given in number of seconds since 00:00 hours, Jan 1, 1970 UTC. * 0 for "start from the beginning". * @param timestamp_to End of timespan to return. * Must be given in number of seconds since 00:00 hours, Jan 1, 1970 UTC. * 0 for "all up to now". * @return Array of locations, NULL is never returned. * The array is sorted decending; * the first entry in the array is the location with the newest timestamp. * Note that this is only realated to the recent postion of the user * if dc_array_is_independent() returns 0. * The returned array must be freed using dc_array_unref(). * * Examples: * ~~~ * // get locations from the last hour for a global map * dc_array_t* loc = dc_get_locations(context, 0, 0, time(NULL)-60*60, 0); * for (int i=0; imagic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (timestamp_to==0) { timestamp_to = time(NULL) + 10/*messages may be inserted by another thread just now*/; } stmt = dc_sqlite3_prepare(context->sql, "SELECT l.id, l.latitude, l.longitude, l.accuracy, l.timestamp, l.independent, " " m.id, l.from_id, l.chat_id, m.txt " " FROM locations l " " LEFT JOIN msgs m ON l.id=m.location_id " " WHERE (? OR l.chat_id=?) " " AND (? OR l.from_id=?) " " AND (l.independent=1 OR (l.timestamp>=? AND l.timestamp<=?)) " " ORDER BY l.timestamp DESC, l.id DESC, m.id DESC;"); sqlite3_bind_int(stmt, 1, chat_id==0? 1 : 0); sqlite3_bind_int(stmt, 2, chat_id); sqlite3_bind_int(stmt, 3, contact_id==0? 1 : 0); sqlite3_bind_int(stmt, 4, contact_id); sqlite3_bind_int(stmt, 5, timestamp_from); sqlite3_bind_int(stmt, 6, timestamp_to); while (sqlite3_step(stmt)==SQLITE_ROW) { struct _dc_location* loc = calloc(1, sizeof(struct _dc_location)); if (loc==NULL) { goto cleanup; } loc->location_id = sqlite3_column_double(stmt, 0); loc->latitude = sqlite3_column_double(stmt, 1); loc->longitude = sqlite3_column_double(stmt, 2); loc->accuracy = sqlite3_column_double(stmt, 3); loc->timestamp = sqlite3_column_int64 (stmt, 4); loc->independent = sqlite3_column_int (stmt, 5); loc->msg_id = sqlite3_column_int (stmt, 6); loc->contact_id = sqlite3_column_int (stmt, 7); loc->chat_id = sqlite3_column_int (stmt, 8); if (loc->msg_id) { const char* txt = (const char*)sqlite3_column_text(stmt, 9); if (is_marker(txt)) { loc->marker = strdup(txt); } } dc_array_add_ptr(ret, loc); } cleanup: sqlite3_finalize(stmt); return ret; } /** * Delete all locations on the current device. * Locations already sent cannot be deleted. * * Typically results in the event #DC_EVENT_LOCATION_CHANGED * with contact_id set to 0. * * @memberof dc_context_t * @param context The context object. * @return None. */ void dc_delete_all_locations(dc_context_t* context) { sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "DELETE FROM locations;"); sqlite3_step(stmt); context->cb(context, DC_EVENT_LOCATION_CHANGED, 0, 0); cleanup: sqlite3_finalize(stmt); } ``` Filename: dc_log.c ```c /* Asynchronous "Thread-errors" are reported by the dc_log_error() function. These errors must be shown to the user by a bubble or so. "Normal" errors are usually returned by a special value (null or so) and are usually not reported using dc_log_error() - its up to the caller to decide, what should be reported or done. However, these "Normal" errors are usually logged by dc_log_warning(). */ #include #include #include "dc_context.h" static void log_vprintf(dc_context_t* context, int event, int data1, const char* msg_format, va_list va) { char* msg = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } if (msg_format) { #define BUFSIZE 1024 char tempbuf[BUFSIZE+1]; vsnprintf(tempbuf, BUFSIZE, msg_format, va); msg = dc_strdup(tempbuf); } else { msg = dc_mprintf("event #%i", (int)event); } context->cb(context, event, (uintptr_t)data1, (uintptr_t)msg); free(msg); } void dc_log_info(dc_context_t* context, int data1, const char* msg, ...) { va_list va; va_start(va, msg); /* va_start() expects the last non-variable argument as the second parameter */ log_vprintf(context, DC_EVENT_INFO, data1, msg, va); va_end(va); } void dc_log_event(dc_context_t* context, int event_code, int data1, const char* msg, ...) { va_list va; va_start(va, msg); /* va_start() expects the last non-variable argument as the second parameter */ log_vprintf(context, event_code, data1, msg, va); va_end(va); } void dc_log_event_seq(dc_context_t* context, int event_code, int* sequence_start, const char* msg, ...) { // logs an event and add a sequence-start-indicator to data1; // once logged, the sequence-start-indicator is set to 0 so that subseqent events are marked as such. // the indicator is useful for the ui eg. to not raise every connection-retry arror to the user. if (context==NULL || sequence_start==NULL || context->magic!=DC_CONTEXT_MAGIC) { return; } va_list va; va_start(va, msg); log_vprintf(context, event_code, *sequence_start, msg, va); *sequence_start = 0; va_end(va); } void dc_log_warning(dc_context_t* context, int data1, const char* msg, ...) { va_list va; va_start(va, msg); /* va_start() expects the last non-variable argument as the second parameter */ log_vprintf(context, DC_EVENT_WARNING, data1, msg, va); va_end(va); } void dc_log_error(dc_context_t* context, int data1, const char* msg, ...) { va_list va; va_start(va, msg); log_vprintf(context, DC_EVENT_ERROR, data1, msg, va); va_end(va); } ``` Filename: dc_loginparam.c ```c #include "dc_context.h" #include "dc_loginparam.h" dc_loginparam_t* dc_loginparam_new() { dc_loginparam_t* loginparam = NULL; if ((loginparam=calloc(1, sizeof(dc_loginparam_t)))==NULL) { exit(22); /* cannot allocate little memory, unrecoverable error */ } return loginparam; } void dc_loginparam_unref(dc_loginparam_t* loginparam) { if (loginparam==NULL) { return; } dc_loginparam_empty(loginparam); free(loginparam); } void dc_loginparam_empty(dc_loginparam_t* loginparam) { if (loginparam == NULL) { return; /* ok, but nothing to do */ } free(loginparam->addr); loginparam->addr = NULL; free(loginparam->mail_server); loginparam->mail_server = NULL; loginparam->mail_port = 0; free(loginparam->mail_user); loginparam->mail_user = NULL; free(loginparam->mail_pw); loginparam->mail_pw = NULL; free(loginparam->send_server); loginparam->send_server = NULL; loginparam->send_port = 0; free(loginparam->send_user); loginparam->send_user = NULL; free(loginparam->send_pw); loginparam->send_pw = NULL; loginparam->server_flags= 0; } void dc_loginparam_read(dc_loginparam_t* loginparam, dc_sqlite3_t* sql, const char* prefix) { char* key = NULL; #define LP_PREFIX(a) sqlite3_free(key); key=sqlite3_mprintf("%s%s", prefix, (a)); dc_loginparam_empty(loginparam); LP_PREFIX("addr"); loginparam->addr = dc_sqlite3_get_config (sql, key, NULL); LP_PREFIX("mail_server"); loginparam->mail_server = dc_sqlite3_get_config (sql, key, NULL); LP_PREFIX("mail_port"); loginparam->mail_port = dc_sqlite3_get_config_int (sql, key, 0); LP_PREFIX("mail_user"); loginparam->mail_user = dc_sqlite3_get_config (sql, key, NULL); LP_PREFIX("mail_pw"); loginparam->mail_pw = dc_sqlite3_get_config (sql, key, NULL); LP_PREFIX("send_server"); loginparam->send_server = dc_sqlite3_get_config (sql, key, NULL); LP_PREFIX("send_port"); loginparam->send_port = dc_sqlite3_get_config_int (sql, key, 0); LP_PREFIX("send_user"); loginparam->send_user = dc_sqlite3_get_config (sql, key, NULL); LP_PREFIX("send_pw"); loginparam->send_pw = dc_sqlite3_get_config (sql, key, NULL); LP_PREFIX("server_flags");loginparam->server_flags= dc_sqlite3_get_config_int (sql, key, 0); sqlite3_free(key); } void dc_loginparam_write(const dc_loginparam_t* loginparam, dc_sqlite3_t* sql, const char* prefix) { char* key = NULL; LP_PREFIX("addr"); dc_sqlite3_set_config (sql, key, loginparam->addr); LP_PREFIX("mail_server"); dc_sqlite3_set_config (sql, key, loginparam->mail_server); LP_PREFIX("mail_port"); dc_sqlite3_set_config_int (sql, key, loginparam->mail_port); LP_PREFIX("mail_user"); dc_sqlite3_set_config (sql, key, loginparam->mail_user); LP_PREFIX("mail_pw"); dc_sqlite3_set_config (sql, key, loginparam->mail_pw); LP_PREFIX("send_server"); dc_sqlite3_set_config (sql, key, loginparam->send_server); LP_PREFIX("send_port"); dc_sqlite3_set_config_int (sql, key, loginparam->send_port); LP_PREFIX("send_user"); dc_sqlite3_set_config (sql, key, loginparam->send_user); LP_PREFIX("send_pw"); dc_sqlite3_set_config (sql, key, loginparam->send_pw); LP_PREFIX("server_flags"); dc_sqlite3_set_config_int (sql, key, loginparam->server_flags); sqlite3_free(key); } static char* get_readable_flags(int flags) { dc_strbuilder_t strbuilder; dc_strbuilder_init(&strbuilder, 0); #define CAT_FLAG(f, s) if ((1<server_flags); char* ret = dc_mprintf("%s %s:%s:%s:%i %s:%s:%s:%i %s", loginparam->addr? loginparam->addr : unset, loginparam->mail_user? loginparam->mail_user : unset, loginparam->mail_pw? pw : unset, loginparam->mail_server? loginparam->mail_server : unset, loginparam->mail_port, loginparam->send_user? loginparam->send_user : unset, loginparam->send_pw? pw : unset, loginparam->send_server? loginparam->send_server : unset, loginparam->send_port, flags_readable); free(flags_readable); return ret; } ``` Filename: dc_lot.c ```c #include "dc_context.h" #define DC_LOT_MAGIC 0x00107107 dc_lot_t* dc_lot_new() { dc_lot_t* lot = NULL; if ((lot=calloc(1, sizeof(dc_lot_t)))==NULL) { exit(27); /* cannot allocate little memory, unrecoverable error */ } lot->magic = DC_LOT_MAGIC; lot->text1_meaning = 0; return lot; } /** * Frees an object containing a set of parameters. * If the set object contains strings, the strings are also freed with this function. * Set objects are created eg. by dc_chatlist_get_summary() or dc_msg_get_summary(). * * @memberof dc_lot_t * @param set The object to free. * If NULL is given, nothing is done. * @return None. */ void dc_lot_unref(dc_lot_t* set) { if (set==NULL || set->magic!=DC_LOT_MAGIC) { return; } dc_lot_empty(set); set->magic = 0; free(set); } void dc_lot_empty(dc_lot_t* lot) { if (lot==NULL || lot->magic!=DC_LOT_MAGIC) { return; } free(lot->text1); lot->text1 = NULL; lot->text1_meaning = 0; free(lot->text2); lot->text2 = NULL; free(lot->fingerprint); lot->fingerprint = NULL; free(lot->invitenumber); lot->invitenumber = NULL; free(lot->auth); lot->auth = NULL; lot->timestamp = 0; lot->state = 0; lot->id = 0; } /** * Get first string. The meaning of the string is defined by the creator of the object and may be roughly described by dc_lot_get_text1_meaning(). * * @memberof dc_lot_t * @param lot The lot object. * @return A string, the string may be empty and the returned value must be free()'d. NULL if there is no such string. */ char* dc_lot_get_text1(const dc_lot_t* lot) { if (lot==NULL || lot->magic!=DC_LOT_MAGIC) { return NULL; } return dc_strdup_keep_null(lot->text1); } /** * Get second string. The meaning of the string is defined by the creator of the object. * * @memberof dc_lot_t * * @param lot The lot object. * * @return A string, the string may be empty and the returned value must be free()'d . NULL if there is no such string. */ char* dc_lot_get_text2(const dc_lot_t* lot) { if (lot==NULL || lot->magic!=DC_LOT_MAGIC) { return NULL; } return dc_strdup_keep_null(lot->text2); } /** * Get the meaning of the first string. Posssible meanings of the string are defined by the creator of the object and may be returned eg. * as DC_TEXT1_DRAFT, DC_TEXT1_USERNAME or DC_TEXT1_SELF. * * @memberof dc_lot_t * @param lot The lot object. * @return Returns the meaning of the first string, possible meanings are defined by the creator of the object. * 0 if there is no concrete meaning or on errors. */ int dc_lot_get_text1_meaning(const dc_lot_t* lot) { if (lot==NULL || lot->magic!=DC_LOT_MAGIC) { return 0; } return lot->text1_meaning; } /** * Get the associated state. The meaning of the state is defined by the creator of the object. * * @memberof dc_lot_t * * @param lot The lot object. * * @return The state as defined by the creator of the object. 0 if there is not state or on errors. */ int dc_lot_get_state(const dc_lot_t* lot) { if (lot==NULL || lot->magic!=DC_LOT_MAGIC) { return 0; } return lot->state; } /** * Get the associated ID. The meaning of the ID is defined by the creator of the object. * * @memberof dc_lot_t * @param lot The lot object. * @return The state as defined by the creator of the object. 0 if there is not state or on errors. */ uint32_t dc_lot_get_id(const dc_lot_t* lot) { if (lot==NULL || lot->magic!=DC_LOT_MAGIC) { return 0; } return lot->id; } /** * Get the associated timestamp. * The timestamp is returned as a unix timestamp in seconds. * The meaning of the timestamp is defined by the creator of the object. * * @memberof dc_lot_t * * @param lot The lot object. * * @return The timestamp as defined by the creator of the object. 0 if there is not timestamp or on errors. */ time_t dc_lot_get_timestamp(const dc_lot_t* lot) { if (lot==NULL || lot->magic!=DC_LOT_MAGIC) { return 0; } return lot->timestamp; } void dc_lot_fill(dc_lot_t* lot, const dc_msg_t* msg, const dc_chat_t* chat, const dc_contact_t* contact, dc_context_t* context) { if (lot==NULL || lot->magic!=DC_LOT_MAGIC || msg==NULL) { return; } if (msg->state==DC_STATE_OUT_DRAFT) { lot->text1 = dc_stock_str(context, DC_STR_DRAFT); lot->text1_meaning = DC_TEXT1_DRAFT; } else if (msg->from_id==DC_CONTACT_ID_SELF) { if (dc_msg_is_info(msg) || dc_chat_is_self_talk(chat)) { lot->text1 = NULL; lot->text1_meaning = 0; } else { lot->text1 = dc_stock_str(context, DC_STR_SELF); lot->text1_meaning = DC_TEXT1_SELF; } } else if (chat==NULL) { lot->text1 = NULL; lot->text1_meaning = 0; } else if (DC_CHAT_TYPE_IS_MULTI(chat->type)) { if (dc_msg_is_info(msg) || contact==NULL) { lot->text1 = NULL; lot->text1_meaning = 0; } else { // show full name for contact request, later on only the first name if (chat!=NULL && chat->id==DC_CHAT_ID_DEADDROP) { lot->text1 = dc_contact_get_display_name(contact); } else { lot->text1 = dc_contact_get_first_name(contact); } lot->text1_meaning = DC_TEXT1_USERNAME; } } lot->text2 = dc_msg_get_summarytext_by_raw(msg->type, msg->text, msg->param, DC_SUMMARY_CHARACTERS, context); lot->timestamp = dc_msg_get_timestamp(msg); lot->state = msg->state; } ``` Filename: dc_mimefactory.c ```c #include "dc_context.h" #include "dc_mimefactory.h" #include "dc_apeerstate.h" #define LINEEND "\r\n" /* lineend used in IMF */ /******************************************************************************* * Load data ******************************************************************************/ void dc_mimefactory_init(dc_mimefactory_t* factory, dc_context_t* context) { if (factory==NULL || context==NULL) { return; } memset(factory, 0, sizeof(dc_mimefactory_t)); factory->context = context; } void dc_mimefactory_empty(dc_mimefactory_t* factory) { if (factory==NULL) { return; } free(factory->from_addr); factory->from_addr = NULL; free(factory->from_displayname); factory->from_displayname = NULL; free(factory->selfstatus); factory->selfstatus = NULL; free(factory->rfc724_mid); factory->rfc724_mid = NULL; if (factory->recipients_names) { clist_free_content(factory->recipients_names); clist_free(factory->recipients_names); factory->recipients_names = NULL; } if (factory->recipients_addr) { clist_free_content(factory->recipients_addr); clist_free(factory->recipients_addr); factory->recipients_addr = NULL; } dc_msg_unref(factory->msg); factory->msg = NULL; dc_chat_unref(factory->chat); factory->chat = NULL; free(factory->in_reply_to); factory->in_reply_to = NULL; free(factory->references); factory->references = NULL; if (factory->out) { mmap_string_free(factory->out); factory->out = NULL; } factory->out_encrypted = 0; factory->loaded = DC_MF_NOTHING_LOADED; free(factory->error); factory->error = NULL; factory->timestamp = 0; } static void set_error(dc_mimefactory_t* factory, const char* text) { if (factory==NULL) { return; } free(factory->error); factory->error = dc_strdup_keep_null(text); } static void load_from(dc_mimefactory_t* factory) { factory->from_addr = dc_sqlite3_get_config(factory->context->sql, "configured_addr", NULL); factory->from_displayname = dc_sqlite3_get_config(factory->context->sql, "displayname", NULL); factory->selfstatus = dc_sqlite3_get_config(factory->context->sql, "selfstatus", NULL); if (factory->selfstatus==NULL) { factory->selfstatus = dc_stock_str(factory->context, DC_STR_STATUSLINE); } } int dc_mimefactory_load_msg(dc_mimefactory_t* factory, uint32_t msg_id) { int success = 0; sqlite3_stmt* stmt = NULL; if (factory==NULL || msg_id <= DC_MSG_ID_LAST_SPECIAL || factory->context==NULL || factory->msg /*call empty() before */) { goto cleanup; } dc_context_t* context = factory->context; factory->recipients_names = clist_new(); factory->recipients_addr = clist_new(); factory->msg = dc_msg_new_untyped(context); factory->chat = dc_chat_new(context); if (dc_msg_load_from_db(factory->msg, context, msg_id) && dc_chat_load_from_db(factory->chat, factory->msg->chat_id)) { load_from(factory); factory->req_mdn = 0; if (dc_chat_is_self_talk(factory->chat)) { clist_append(factory->recipients_names, (void*)dc_strdup_keep_null(factory->from_displayname)); clist_append(factory->recipients_addr, (void*)dc_strdup(factory->from_addr)); } else { stmt = dc_sqlite3_prepare(context->sql, "SELECT c.authname, c.addr " " FROM chats_contacts cc " " LEFT JOIN contacts c ON cc.contact_id=c.id " " WHERE cc.chat_id=? AND cc.contact_id>" DC_STRINGIFY(DC_CONTACT_ID_LAST_SPECIAL) ";"); sqlite3_bind_int(stmt, 1, factory->msg->chat_id); while (sqlite3_step(stmt)==SQLITE_ROW) { const char* authname = (const char*)sqlite3_column_text(stmt, 0); const char* addr = (const char*)sqlite3_column_text(stmt, 1); if (clist_search_string_nocase(factory->recipients_addr, addr)==0) { clist_append(factory->recipients_names, (void*)((authname&&authname[0])? dc_strdup(authname) : NULL)); clist_append(factory->recipients_addr, (void*)dc_strdup(addr)); } } sqlite3_finalize(stmt); stmt = NULL; int command = dc_param_get_int(factory->msg->param, DC_PARAM_CMD, 0); if (command==DC_CMD_MEMBER_REMOVED_FROM_GROUP /* for added members, the list is just fine */) { char* email_to_remove = dc_param_get(factory->msg->param, DC_PARAM_CMD_ARG, NULL); char* self_addr = dc_sqlite3_get_config(context->sql, "configured_addr", ""); if (email_to_remove && strcasecmp(email_to_remove, self_addr)!=0) { if (clist_search_string_nocase(factory->recipients_addr, email_to_remove)==0) { clist_append(factory->recipients_names, NULL); clist_append(factory->recipients_addr, (void*)email_to_remove); } } free(self_addr); } if (command!=DC_CMD_AUTOCRYPT_SETUP_MESSAGE && command!=DC_CMD_SECUREJOIN_MESSAGE && dc_sqlite3_get_config_int(context->sql, "mdns_enabled", DC_MDNS_DEFAULT_ENABLED)) { factory->req_mdn = 1; } } stmt = dc_sqlite3_prepare(context->sql, "SELECT mime_in_reply_to, mime_references FROM msgs WHERE id=?"); sqlite3_bind_int (stmt, 1, factory->msg->id); if (sqlite3_step(stmt)==SQLITE_ROW) { factory->in_reply_to = dc_strdup((const char*)sqlite3_column_text(stmt, 0)); factory->references = dc_strdup((const char*)sqlite3_column_text(stmt, 1)); } sqlite3_finalize(stmt); stmt = NULL; success = 1; factory->loaded = DC_MF_MSG_LOADED; factory->timestamp = factory->msg->timestamp_sort; factory->rfc724_mid = dc_strdup(factory->msg->rfc724_mid); } if (success) { factory->increation = dc_msg_is_increation(factory->msg); } cleanup: sqlite3_finalize(stmt); return success; } int dc_mimefactory_load_mdn(dc_mimefactory_t* factory, uint32_t msg_id) { int success = 0; dc_contact_t* contact = NULL; if (factory==NULL) { goto cleanup; } factory->recipients_names = clist_new(); factory->recipients_addr = clist_new(); factory->msg = dc_msg_new_untyped(factory->context); if (!dc_sqlite3_get_config_int(factory->context->sql, "mdns_enabled", DC_MDNS_DEFAULT_ENABLED)) { goto cleanup; /* MDNs not enabled - check this is late, in the job. the use may have changed its choice while offline ... */ } contact = dc_contact_new(factory->context); if (!dc_msg_load_from_db(factory->msg, factory->context, msg_id) || !dc_contact_load_from_db(contact, factory->context->sql, factory->msg->from_id)) { goto cleanup; } if (contact->blocked || factory->msg->chat_id<=DC_CHAT_ID_LAST_SPECIAL/* Do not send MDNs trash etc.; chats.blocked is already checked by the caller in dc_markseen_msgs() */) { goto cleanup; } if (factory->msg->from_id <= DC_CONTACT_ID_LAST_SPECIAL) { goto cleanup; } clist_append(factory->recipients_names, (void*)((contact->authname&&contact->authname[0])? dc_strdup(contact->authname) : NULL)); clist_append(factory->recipients_addr, (void*)dc_strdup(contact->addr)); load_from(factory); factory->timestamp = dc_create_smeared_timestamp(factory->context); factory->rfc724_mid = dc_create_outgoing_rfc724_mid(NULL, factory->from_addr); success = 1; factory->loaded = DC_MF_MDN_LOADED; cleanup: dc_contact_unref(contact); return success; } /******************************************************************************* * Render ******************************************************************************/ static int is_file_size_okay(const dc_msg_t* msg) { int file_size_okay = 1; char* pathNfilename = dc_param_get(msg->param, DC_PARAM_FILE, NULL); uint64_t bytes = dc_get_filebytes(msg->context, pathNfilename); if (bytes>DC_MSGSIZE_UPPER_LIMIT) { file_size_okay = 0; } free(pathNfilename); return file_size_okay; } static struct mailmime* build_body_text(char* text) { struct mailmime_fields* mime_fields = NULL; struct mailmime* message_part = NULL; struct mailmime_content* content = NULL; content = mailmime_content_new_with_str("text/plain"); clist_append(content->ct_parameters, mailmime_param_new_with_data("charset", "utf-8")); /* format=flowed currently does not really affect us, see https://www.ietf.org/rfc/rfc3676.txt */ mime_fields = mailmime_fields_new_encoding(MAILMIME_MECHANISM_8BIT); message_part = mailmime_new_empty(content, mime_fields); mailmime_set_body_text(message_part, text, strlen(text)); return message_part; } static struct mailmime* build_body_file(const dc_msg_t* msg, const char* base_name, char** ret_file_name_as_sent) { struct mailmime_fields* mime_fields = NULL; struct mailmime* mime_sub = NULL; struct mailmime_content* content = NULL; char* pathNfilename = dc_param_get(msg->param, DC_PARAM_FILE, NULL); char* mimetype = dc_param_get(msg->param, DC_PARAM_MIMETYPE, NULL); char* suffix = dc_get_filesuffix_lc(pathNfilename); char* filename_to_send = NULL; char* filename_encoded = NULL; if (pathNfilename==NULL) { goto cleanup; } /* get file name to use for sending (for privacy purposes, we do not transfer the original filenames eg. for images; these names are normally not needed and contain timesamps, running numbers etc.) */ if (msg->type==DC_MSG_VOICE) { struct tm wanted_struct; memcpy(&wanted_struct, localtime(&msg->timestamp_sort), sizeof(struct tm)); filename_to_send = dc_mprintf("voice-message_%04i-%02i-%02i_%02i-%02i-%02i.%s", (int)wanted_struct.tm_year+1900, (int)wanted_struct.tm_mon+1, (int)wanted_struct.tm_mday, (int)wanted_struct.tm_hour, (int)wanted_struct.tm_min, (int)wanted_struct.tm_sec, suffix? suffix : "dat"); } else if (msg->type==DC_MSG_AUDIO) { filename_to_send = dc_get_filename(pathNfilename); } else if (msg->type==DC_MSG_IMAGE || msg->type==DC_MSG_GIF) { if (base_name==NULL) { base_name = "image"; } filename_to_send = dc_mprintf("%s.%s", base_name, suffix? suffix : "dat"); } else if (msg->type==DC_MSG_VIDEO) { filename_to_send = dc_mprintf("video.%s", suffix? suffix : "dat"); } else { filename_to_send = dc_get_filename(pathNfilename); } /* check mimetype */ if (mimetype==NULL) { if (suffix==NULL) { mimetype = dc_strdup("application/octet-stream"); } else if (strcmp(suffix, "png")==0) { mimetype = dc_strdup("image/png"); } else if (strcmp(suffix, "jpg")==0 || strcmp(suffix, "jpeg")==0 || strcmp(suffix, "jpe")==0) { mimetype = dc_strdup("image/jpeg"); } else if (strcmp(suffix, "gif")==0) { mimetype = dc_strdup("image/gif"); } else { mimetype = dc_strdup("application/octet-stream"); } } if (mimetype==NULL) { goto cleanup; } /* create mime part, for Content-Disposition, see RFC 2183. `Content-Disposition: attachment` seems not to make a difference to `Content-Disposition: inline` at least on tested Thunderbird and Gma'l in 2017. But I've heard about problems with inline and outl'k, so we just use the attachment-type until we run into other problems ... */ int needs_ext = dc_needs_ext_header(filename_to_send); mime_fields = mailmime_fields_new_filename(MAILMIME_DISPOSITION_TYPE_ATTACHMENT, needs_ext? NULL : dc_strdup(filename_to_send), MAILMIME_MECHANISM_BASE64); if (needs_ext) { for (clistiter* cur1 = clist_begin(mime_fields->fld_list); cur1!=NULL; cur1 = clist_next(cur1)) { struct mailmime_field* field = (struct mailmime_field*)clist_content(cur1); if (field && field->fld_type==MAILMIME_FIELD_DISPOSITION && field->fld_data.fld_disposition) { struct mailmime_disposition* file_disposition = field->fld_data.fld_disposition; if (file_disposition) { struct mailmime_disposition_parm* parm = mailmime_disposition_parm_new( MAILMIME_DISPOSITION_PARM_PARAMETER, NULL, NULL, NULL, NULL, 0, mailmime_parameter_new(strdup("filename*"), dc_encode_ext_header(filename_to_send))); if (parm) { clist_append(file_disposition->dsp_parms, parm); } } break; } } } content = mailmime_content_new_with_str(mimetype); clist_append(content->ct_parameters, mailmime_param_new_with_data("name", (filename_encoded=dc_encode_header_words(filename_to_send)))); mime_sub = mailmime_new_empty(content, mime_fields); mailmime_set_body_file(mime_sub, dc_get_abs_path(msg->context, pathNfilename)); if (ret_file_name_as_sent) { *ret_file_name_as_sent = dc_strdup(filename_to_send); } cleanup: free(pathNfilename); free(mimetype); free(filename_to_send); free(filename_encoded); free(suffix); return mime_sub; } static char* get_subject(const dc_chat_t* chat, const dc_msg_t* msg, int afwd_email) { dc_context_t* context = chat? chat->context : NULL; char* ret = NULL; char* raw_subject = dc_msg_get_summarytext_by_raw(msg->type, msg->text, msg->param, DC_APPROX_SUBJECT_CHARS, context); const char* fwd = afwd_email? "Fwd: " : ""; if (dc_param_get_int(msg->param, DC_PARAM_CMD, 0)==DC_CMD_AUTOCRYPT_SETUP_MESSAGE) { ret = dc_stock_str(context, DC_STR_AC_SETUP_MSG_SUBJECT); /* do not add the "Chat:" prefix for setup messages */ } else if (DC_CHAT_TYPE_IS_MULTI(chat->type)) { ret = dc_mprintf(DC_CHAT_PREFIX " %s: %s%s", chat->name, fwd, raw_subject); } else { ret = dc_mprintf(DC_CHAT_PREFIX " %s%s", fwd, raw_subject); } free(raw_subject); return ret; } int dc_mimefactory_render(dc_mimefactory_t* factory) { struct mailimf_fields* imf_fields = NULL; struct mailmime* message = NULL; char* message_text = NULL; char* message_text2 = NULL; char* subject_str = NULL; int afwd_email = 0; int col = 0; int success = 0; int parts = 0; int e2ee_guaranteed = 0; int min_verified = DC_NOT_VERIFIED; int force_plaintext = 0; // 1=add Autocrypt-header (needed eg. for handshaking), 2=no Autocrypte-header (used for MDN) int do_gossip = 0; char* grpimage = NULL; dc_e2ee_helper_t e2ee_helper; memset(&e2ee_helper, 0, sizeof(dc_e2ee_helper_t)); if (factory==NULL || factory->loaded==DC_MF_NOTHING_LOADED || factory->out/*call empty() before*/) { set_error(factory, "Invalid use of mimefactory-object."); goto cleanup; } /* create basic mail *************************************************************************/ { struct mailimf_mailbox_list* from = mailimf_mailbox_list_new_empty(); mailimf_mailbox_list_add(from, mailimf_mailbox_new(factory->from_displayname? dc_encode_header_words(factory->from_displayname) : NULL, dc_strdup(factory->from_addr))); struct mailimf_address_list* to = NULL; if (factory->recipients_names && factory->recipients_addr && clist_count(factory->recipients_addr)>0) { clistiter *iter1, *iter2; to = mailimf_address_list_new_empty(); for (iter1=clist_begin(factory->recipients_names),iter2=clist_begin(factory->recipients_addr); iter1!=NULL&&iter2!=NULL; iter1=clist_next(iter1),iter2=clist_next(iter2)) { const char* name = clist_content(iter1); const char* addr = clist_content(iter2); mailimf_address_list_add(to, mailimf_address_new(MAILIMF_ADDRESS_MAILBOX, mailimf_mailbox_new(name? dc_encode_header_words(name) : NULL, dc_strdup(addr)), NULL)); } } clist* references_list = NULL; if (factory->references && factory->references[0]) { references_list = dc_str_to_clist(factory->references, " "); } clist* in_reply_to_list = NULL; if (factory->in_reply_to && factory->in_reply_to[0]) { in_reply_to_list = dc_str_to_clist(factory->in_reply_to, " "); } imf_fields = mailimf_fields_new_with_data_all(mailimf_get_date(factory->timestamp), from, NULL /* sender */, NULL /* reply-to */, to, NULL /* cc */, NULL /* bcc */, dc_strdup(factory->rfc724_mid), in_reply_to_list, references_list /* references */, NULL /* subject set later */); /* Add a X-Mailer header. This is only informational for debugging and may be removed in the release. We do not rely on this header as it may be removed by MTAs. */ mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("X-Mailer"), dc_mprintf("Delta Chat Core %s%s%s", DC_VERSION_STR, factory->context->os_name? "/" : "", factory->context->os_name? factory->context->os_name : ""))); mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Chat-Version"), strdup("1.0"))); /* mark message as being sent by a messenger */ if (factory->req_mdn) { /* we use "Chat-Disposition-Notification-To" as replies to "Disposition-Notification-To" are weird in many cases, are just freetext and/or do not follow any standard. */ mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Chat-Disposition-Notification-To"), strdup(factory->from_addr))); } message = mailmime_new_message_data(NULL); mailmime_set_imf_fields(message, imf_fields); } if (factory->loaded==DC_MF_MSG_LOADED) { /* Render a normal message *********************************************************************/ dc_chat_t* chat = factory->chat; dc_msg_t* msg = factory->msg; struct mailmime* meta_part = NULL; char* placeholdertext = NULL; if (chat->type==DC_CHAT_TYPE_VERIFIED_GROUP) { mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Chat-Verified"), strdup("1"))); force_plaintext = 0; e2ee_guaranteed = 1; min_verified = DC_BIDIRECT_VERIFIED; } else { if ((force_plaintext = dc_param_get_int(factory->msg->param, DC_PARAM_FORCE_PLAINTEXT, 0))==0) { e2ee_guaranteed = dc_param_get_int(factory->msg->param, DC_PARAM_GUARANTEE_E2EE, 0); } } // beside key- and member-changes, force re-gossip every 48 hours #define AUTO_REGOSSIP (2*24*60*60) if (chat->gossiped_timestamp==0 || chat->gossiped_timestamp+AUTO_REGOSSIP < time(NULL) ) { do_gossip = 1; } /* build header etc. */ int command = dc_param_get_int(msg->param, DC_PARAM_CMD, 0); if (DC_CHAT_TYPE_IS_MULTI(chat->type)) { mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Chat-Group-ID"), dc_strdup(chat->grpid))); mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Chat-Group-Name"), dc_encode_header_words(chat->name))); if (command==DC_CMD_MEMBER_REMOVED_FROM_GROUP) { char* email_to_remove = dc_param_get(msg->param, DC_PARAM_CMD_ARG, NULL); if (email_to_remove) { mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Chat-Group-Member-Removed"), email_to_remove)); } } else if (command==DC_CMD_MEMBER_ADDED_TO_GROUP) { do_gossip = 1; char* email_to_add = dc_param_get(msg->param, DC_PARAM_CMD_ARG, NULL); if (email_to_add) { mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Chat-Group-Member-Added"), email_to_add)); grpimage = dc_param_get(chat->param, DC_PARAM_PROFILE_IMAGE, NULL); } if (dc_param_get_int(msg->param, DC_PARAM_CMD_ARG2, 0)&DC_FROM_HANDSHAKE) { dc_log_info(msg->context, 0, "sending secure-join message '%s' >>>>>>>>>>>>>>>>>>>>>>>>>", "vg-member-added"); mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Secure-Join"), strdup("vg-member-added"))); } } else if (command==DC_CMD_GROUPNAME_CHANGED) { mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Chat-Group-Name-Changed"), dc_param_get(msg->param, DC_PARAM_CMD_ARG, ""))); } else if (command==DC_CMD_GROUPIMAGE_CHANGED) { grpimage = dc_param_get(msg->param, DC_PARAM_CMD_ARG, NULL); if (grpimage==NULL) { mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Chat-Group-Image"), dc_strdup("0"))); } } } if (command==DC_CMD_LOCATION_STREAMING_ENABLED) { mailimf_fields_add(imf_fields, mailimf_field_new_custom( strdup("Chat-Content"), strdup("location-streaming-enabled"))); } if (command==DC_CMD_AUTOCRYPT_SETUP_MESSAGE) { mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Autocrypt-Setup-Message"), strdup("v1"))); placeholdertext = dc_stock_str(factory->context, DC_STR_AC_SETUP_MSG_BODY); } if (command==DC_CMD_SECUREJOIN_MESSAGE) { char* step = dc_param_get(msg->param, DC_PARAM_CMD_ARG, NULL); if (step) { dc_log_info(msg->context, 0, "sending secure-join message '%s' >>>>>>>>>>>>>>>>>>>>>>>>>", step); mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Secure-Join"), step/*mailimf takes ownership of string*/)); char* param2 = dc_param_get(msg->param, DC_PARAM_CMD_ARG2, NULL); if (param2) { mailimf_fields_add(imf_fields, mailimf_field_new_custom( (strcmp(step, "vg-request-with-auth")==0 || strcmp(step, "vc-request-with-auth")==0)? strdup("Secure-Join-Auth") : strdup("Secure-Join-Invitenumber"), param2/*mailimf takes ownership of string*/)); } char* fingerprint = dc_param_get(msg->param, DC_PARAM_CMD_ARG3, NULL); if (fingerprint) { mailimf_fields_add(imf_fields, mailimf_field_new_custom( strdup("Secure-Join-Fingerprint"), fingerprint/*mailimf takes ownership of string*/)); } char* grpid = dc_param_get(msg->param, DC_PARAM_CMD_ARG4, NULL); if (grpid) { mailimf_fields_add(imf_fields, mailimf_field_new_custom( strdup("Secure-Join-Group"), grpid/*mailimf takes ownership of string*/)); } } } if (grpimage) { dc_msg_t* meta = dc_msg_new_untyped(factory->context); meta->type = DC_MSG_IMAGE; dc_param_set(meta->param, DC_PARAM_FILE, grpimage); char* filename_as_sent = NULL; if ((meta_part=build_body_file(meta, "group-image", &filename_as_sent))!=NULL) { mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Chat-Group-Image"), filename_as_sent/*takes ownership*/)); } dc_msg_unref(meta); } if (msg->type==DC_MSG_VOICE || msg->type==DC_MSG_AUDIO || msg->type==DC_MSG_VIDEO) { if (msg->type==DC_MSG_VOICE) { mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Chat-Voice-Message"), strdup("1"))); } int duration_ms = dc_param_get_int(msg->param, DC_PARAM_DURATION, 0); if (duration_ms > 0) { mailimf_fields_add(imf_fields, mailimf_field_new_custom(strdup("Chat-Duration"), dc_mprintf("%i", (int)duration_ms))); } } /* add text part - we even add empty text and force a MIME-multipart-message as: - some Apps have problems with Non-text in the main part (eg. "Mail" from stock Android) - we can add "forward hints" this way - it looks better */ afwd_email = dc_param_exists(msg->param, DC_PARAM_FORWARDED); char* fwdhint = NULL; if (afwd_email) { fwdhint = dc_strdup("---------- Forwarded message ----------" LINEEND "From: Delta Chat" LINEEND LINEEND); /* do not chage this! expected this way in the simplifier to detect forwarding! */ } const char* final_text = NULL; if (placeholdertext) { final_text = placeholdertext; } else if (msg->text && msg->text[0]) { final_text = msg->text; } char* footer = factory->selfstatus; message_text = dc_mprintf("%s%s%s%s%s", fwdhint? fwdhint : "", final_text? final_text : "", (final_text&&footer&&footer[0])? (LINEEND LINEEND) : "", (footer&&footer[0])? ("-- " LINEEND) : "", (footer&&footer[0])? footer : ""); struct mailmime* text_part = build_body_text(message_text); mailmime_smart_add_part(message, text_part); parts++; free(fwdhint); free(placeholdertext); /* add attachment part */ if (DC_MSG_NEEDS_ATTACHMENT(msg->type)) { if (!is_file_size_okay(msg)) { char* error = dc_mprintf("Message exceeds the recommended %i MB.", DC_MSGSIZE_MAX_RECOMMENDED/1000/1000); set_error(factory, error); free(error); goto cleanup; } struct mailmime* file_part = build_body_file(msg, NULL, NULL); if (file_part) { mailmime_smart_add_part(message, file_part); parts++; } } if (parts==0) { set_error(factory, "Empty message."); goto cleanup; } if (meta_part) { mailmime_smart_add_part(message, meta_part); /* meta parts are only added if there are other parts */ parts++; } if (dc_param_exists(msg->param, DC_PARAM_SET_LATITUDE)) { double latitude = dc_param_get_float(msg->param, DC_PARAM_SET_LATITUDE, 0.0); double longitude = dc_param_get_float(msg->param, DC_PARAM_SET_LONGITUDE, 0.0); char* kml_file = dc_get_message_kml(msg->context, msg->timestamp_sort, latitude, longitude); if (kml_file) { struct mailmime_content* content_type = mailmime_content_new_with_str("application/vnd.google-earth.kml+xml"); struct mailmime_fields* mime_fields = mailmime_fields_new_filename(MAILMIME_DISPOSITION_TYPE_ATTACHMENT, dc_strdup("message.kml"), MAILMIME_MECHANISM_8BIT); struct mailmime* kml_mime_part = mailmime_new_empty(content_type, mime_fields); mailmime_set_body_text(kml_mime_part, kml_file, strlen(kml_file)); mailmime_smart_add_part(message, kml_mime_part); parts++; } } if (dc_is_sending_locations_to_chat(msg->context, msg->chat_id)) { uint32_t last_added_location_id = 0; char* kml_file = dc_get_location_kml(msg->context, msg->chat_id, &last_added_location_id); if (kml_file) { struct mailmime_content* content_type = mailmime_content_new_with_str("application/vnd.google-earth.kml+xml"); struct mailmime_fields* mime_fields = mailmime_fields_new_filename(MAILMIME_DISPOSITION_TYPE_ATTACHMENT, dc_strdup("location.kml"), MAILMIME_MECHANISM_8BIT); struct mailmime* kml_mime_part = mailmime_new_empty(content_type, mime_fields); mailmime_set_body_text(kml_mime_part, kml_file, strlen(kml_file)); mailmime_smart_add_part(message, kml_mime_part); parts++; if (!dc_param_exists(msg->param, DC_PARAM_SET_LATITUDE)) { // otherwise, the independent location is already filed factory->out_last_added_location_id = last_added_location_id; } } } } else if (factory->loaded==DC_MF_MDN_LOADED) { /* Render a MDN *********************************************************************/ struct mailmime* multipart = mailmime_multiple_new("multipart/report"); /* RFC 6522, this also requires the `report-type` parameter which is equal to the MIME subtype of the second body part of the multipart/report */ struct mailmime_content* content = multipart->mm_content_type; clist_append(content->ct_parameters, mailmime_param_new_with_data("report-type", "disposition-notification")); /* RFC */ mailmime_add_part(message, multipart); /* first body part: always human-readable, always REQUIRED by RFC 6522 */ char *p1 = NULL, *p2 = NULL; if (dc_param_get_int(factory->msg->param, DC_PARAM_GUARANTEE_E2EE, 0)) { p1 = dc_stock_str(factory->context, DC_STR_ENCRYPTEDMSG); /* we SHOULD NOT spread encrypted subjects, date etc. in potentially unencrypted MDNs */ } else { p1 = dc_msg_get_summarytext(factory->msg, DC_APPROX_SUBJECT_CHARS); } p2 = dc_stock_str_repl_string(factory->context, DC_STR_READRCPT_MAILBODY, p1); message_text = dc_mprintf("%s" LINEEND, p2); free(p2); free(p1); struct mailmime* human_mime_part = build_body_text(message_text); mailmime_add_part(multipart, human_mime_part); /* second body part: machine-readable, always REQUIRED by RFC 6522 */ message_text2 = dc_mprintf( "Reporting-UA: Delta Chat %s" LINEEND "Original-Recipient: rfc822;%s" LINEEND "Final-Recipient: rfc822;%s" LINEEND "Original-Message-ID: <%s>" LINEEND "Disposition: manual-action/MDN-sent-automatically; displayed" LINEEND, /* manual-action: the user has configured the MUA to send MDNs (automatic-action implies the receipts cannot be disabled) */ DC_VERSION_STR, factory->from_addr, factory->from_addr, factory->msg->rfc724_mid); struct mailmime_content* content_type = mailmime_content_new_with_str("message/disposition-notification"); struct mailmime_fields* mime_fields = mailmime_fields_new_encoding(MAILMIME_MECHANISM_8BIT); struct mailmime* mach_mime_part = mailmime_new_empty(content_type, mime_fields); mailmime_set_body_text(mach_mime_part, message_text2, strlen(message_text2)); mailmime_add_part(multipart, mach_mime_part); /* currently, we do not send MDNs encrypted: - in a multi-device-setup that is not set up properly, MDNs would disturb the communication as they are send automatically which may lead to spreading outdated Autocrypt headers. - they do not carry any information but the Message-ID - this save some KB - in older versions, we did not encrypt messages to ourself when they to to SMTP - however, if these messages are forwarded for any reasons (eg. gmail always forwards to IMAP), we have no chance to decrypt them; this issue is fixed with 0.9.4 */ force_plaintext = DC_FP_NO_AUTOCRYPT_HEADER; } else { set_error(factory, "No message loaded."); goto cleanup; } /* Encrypt the message *************************************************************************/ if (factory->loaded==DC_MF_MDN_LOADED) { char* e = dc_stock_str(factory->context, DC_STR_READRCPT); subject_str = dc_mprintf(DC_CHAT_PREFIX " %s", e); free(e); } else { subject_str = get_subject(factory->chat, factory->msg, afwd_email); } struct mailimf_subject* subject = mailimf_subject_new(dc_encode_header_words(subject_str)); mailimf_fields_add(imf_fields, mailimf_field_new(MAILIMF_FIELD_SUBJECT, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, subject, NULL, NULL, NULL)); if (force_plaintext!=DC_FP_NO_AUTOCRYPT_HEADER) { dc_e2ee_encrypt(factory->context, factory->recipients_addr, force_plaintext, e2ee_guaranteed, min_verified, do_gossip, message, &e2ee_helper); } if (e2ee_helper.encryption_successfull) { factory->out_encrypted = 1; if (do_gossip) { factory->out_gossiped = 1; } } /* create the full mail and return */ factory->out = mmap_string_new(""); mailmime_write_mem(factory->out, &col, message); //{char* t4=dc_null_terminate(ret->str,ret->len); printf("MESSAGE:\n%s\n",t4);free(t4);} success = 1; cleanup: if (message) { mailmime_free(message); } dc_e2ee_thanks(&e2ee_helper); // frees data referenced by "mailmime" but not freed by mailmime_free() free(message_text); // mailmime_set_body_text() does not take ownership of "text" free(message_text2); // - " -- free(subject_str); free(grpimage); return success; } ``` Filename: dc_mimeparser.c ```c #include "dc_context.h" #include "dc_mimeparser.h" #include "dc_mimefactory.h" #include "dc_pgp.h" #include "dc_simplify.h" static void hash_header(dc_hash_t* out, const struct mailimf_fields* in, dc_context_t* context); // deprecated: flag to switch generation of compound messages on and off. static int s_generate_compound_msgs = 1; // deprecated: call dc_no_compound_msgs() // to switch generation of compound messages off for the whole library. void dc_no_compound_msgs(void) { s_generate_compound_msgs = 0; } /******************************************************************************* * debug output ******************************************************************************/ #ifdef DC_USE_MIME_DEBUG /* if you need this functionality, define DC_USE_MIME_DEBUG in the project, eg. in Codeblocks at "Project / Build options / / Compiler settings / #defines" */ static void display_mime_content(struct mailmime_content * content_type); static void display_mime_data(struct mailmime_data * data) { switch (data->dt_type) { case MAILMIME_DATA_TEXT: printf("data : %i bytes\n", (int) data->dt_data.dt_text.dt_length); break; case MAILMIME_DATA_FILE: printf("data (file) : %s\n", data->dt_data.dt_filename); break; } } static void display_mime_dsp_parm(struct mailmime_disposition_parm * param) { switch (param->pa_type) { case MAILMIME_DISPOSITION_PARM_FILENAME: printf("filename: %s\n", param->pa_data.pa_filename); break; } } static void display_mime_disposition(struct mailmime_disposition * disposition) { clistiter * cur; for(cur = clist_begin(disposition->dsp_parms) ; cur!=NULL ; cur = clist_next(cur)) { struct mailmime_disposition_parm * param; param = (struct mailmime_disposition_parm*)clist_content(cur); display_mime_dsp_parm(param); } } static void display_mime_field(struct mailmime_field * field) { switch (field->fld_type) { case MAILMIME_FIELD_VERSION: printf("MIME-Version: ...\n"); break; case MAILMIME_FIELD_TYPE: printf("content-type: "); display_mime_content(field->fld_data.fld_content); printf("\n"); break; case MAILMIME_FIELD_DISPOSITION: display_mime_disposition(field->fld_data.fld_disposition); break; } } static void display_mime_fields(struct mailmime_fields * fields) { clistiter * cur; for(cur = clist_begin(fields->fld_list) ; cur!=NULL ; cur = clist_next(cur)) { struct mailmime_field * field; field = (struct mailmime_field*)clist_content(cur); display_mime_field(field); } } static void display_date_time(struct mailimf_date_time * d) { printf("%02i/%02i/%i %02i:%02i:%02i %+04i", d->dt_day, d->dt_month, d->dt_year, d->dt_hour, d->dt_min, d->dt_sec, d->dt_zone); } static void display_orig_date(struct mailimf_orig_date * orig_date) { display_date_time(orig_date->dt_date_time); } static void display_mailbox(struct mailimf_mailbox * mb) { if (mb->mb_display_name!=NULL) printf("%s ", mb->mb_display_name); printf("<%s>", mb->mb_addr_spec); } static void display_mailbox_list(struct mailimf_mailbox_list * mb_list) { clistiter * cur; for(cur = clist_begin(mb_list->mb_list) ; cur!=NULL ; cur = clist_next(cur)) { struct mailimf_mailbox * mb; mb = (struct mailimf_mailbox*)clist_content(cur); display_mailbox(mb); if (clist_next(cur)!=NULL) { printf(", "); } } } static void display_group(struct mailimf_group * group) { clistiter * cur; printf("%s: ", group->grp_display_name); for(cur = clist_begin(group->grp_mb_list->mb_list) ; cur!=NULL ; cur = clist_next(cur)) { struct mailimf_mailbox * mb; mb = (struct mailimf_mailbox*)clist_content(cur); display_mailbox(mb); } printf("; "); } static void display_address(struct mailimf_address * a) { switch (a->ad_type) { case MAILIMF_ADDRESS_GROUP: display_group(a->ad_data.ad_group); break; case MAILIMF_ADDRESS_MAILBOX: display_mailbox(a->ad_data.ad_mailbox); break; } } static void display_address_list(struct mailimf_address_list * addr_list) { clistiter * cur; for(cur = clist_begin(addr_list->ad_list) ; cur!=NULL ; cur = clist_next(cur)) { struct mailimf_address * addr; addr = (struct mailimf_address*)clist_content(cur); display_address(addr); if (clist_next(cur)!=NULL) { printf(", "); } } } static void display_from(struct mailimf_from * from) { display_mailbox_list(from->frm_mb_list); } static void display_to(struct mailimf_to * to) { display_address_list(to->to_addr_list); } static void display_cc(struct mailimf_cc * cc) { display_address_list(cc->cc_addr_list); } static void display_subject(struct mailimf_subject * subject) { printf("%s", subject->sbj_value); } static void display_field(struct mailimf_field * field) { switch (field->fld_type) { case MAILIMF_FIELD_ORIG_DATE: printf("Date: "); display_orig_date(field->fld_data.fld_orig_date); printf("\n"); break; case MAILIMF_FIELD_FROM: printf("From: "); display_from(field->fld_data.fld_from); printf("\n"); break; case MAILIMF_FIELD_TO: printf("To: "); display_to(field->fld_data.fld_to); printf("\n"); break; case MAILIMF_FIELD_CC: printf("Cc: "); display_cc(field->fld_data.fld_cc); printf("\n"); break; case MAILIMF_FIELD_SUBJECT: printf("Subject: "); display_subject(field->fld_data.fld_subject); printf("\n"); break; case MAILIMF_FIELD_MESSAGE_ID: printf("Message-ID: %s\n", field->fld_data.fld_message_id->mid_value); break; case MAILIMF_FIELD_OPTIONAL_FIELD: { struct mailimf_optional_field* of = field->fld_data.fld_optional_field; if (of) { printf("%s: %s\n", of->fld_name? of->fld_name : "?", of->fld_value? of->fld_value : "?"); } } break; default: printf("MAILIMF_FIELD_%i\n", (int)field->fld_type); break; } } static void display_fields(struct mailimf_fields * fields) { clistiter * cur; for(cur = clist_begin(fields->fld_list) ; cur!=NULL ; cur = clist_next(cur)) { struct mailimf_field * f; f = (struct mailimf_field*)clist_content(cur); display_field(f); } } static void display_mime_discrete_type(struct mailmime_discrete_type * discrete_type) { switch (discrete_type->dt_type) { case MAILMIME_DISCRETE_TYPE_TEXT: printf("text"); break; case MAILMIME_DISCRETE_TYPE_IMAGE: printf("image"); break; case MAILMIME_DISCRETE_TYPE_AUDIO: printf("audio"); break; case MAILMIME_DISCRETE_TYPE_VIDEO: printf("video"); break; case MAILMIME_DISCRETE_TYPE_APPLICATION: printf("application"); break; case MAILMIME_DISCRETE_TYPE_EXTENSION: printf("%s", discrete_type->dt_extension); break; } } static void display_mime_composite_type(struct mailmime_composite_type * ct) { switch (ct->ct_type) { case MAILMIME_COMPOSITE_TYPE_MESSAGE: printf("message"); break; case MAILMIME_COMPOSITE_TYPE_MULTIPART: printf("multipart"); break; case MAILMIME_COMPOSITE_TYPE_EXTENSION: printf("%s", ct->ct_token); break; } } static void display_mime_type(struct mailmime_type * type) { switch (type->tp_type) { case MAILMIME_TYPE_DISCRETE_TYPE: display_mime_discrete_type(type->tp_data.tp_discrete_type); break; case MAILMIME_TYPE_COMPOSITE_TYPE: display_mime_composite_type(type->tp_data.tp_composite_type); break; } } static void display_mime_content(struct mailmime_content * content_type) { printf("type: "); display_mime_type(content_type->ct_type); printf("/%s\n", content_type->ct_subtype); } static void print_mime(struct mailmime * mime) { clistiter * cur; if (mime==NULL) { printf("ERROR: NULL given to print_mime()\n"); return; } switch (mime->mm_type) { case MAILMIME_SINGLE: printf("single part\n"); break; case MAILMIME_MULTIPLE: printf("multipart\n"); break; case MAILMIME_MESSAGE: printf("message\n"); break; } if (mime->mm_mime_fields!=NULL) { if (clist_begin(mime->mm_mime_fields->fld_list)!=NULL) { printf("----------------------------------------------------------------\n"); display_mime_fields(mime->mm_mime_fields); printf("---------------------------------------------------------------\n"); } } display_mime_content(mime->mm_content_type); switch (mime->mm_type) { case MAILMIME_SINGLE: display_mime_data(mime->mm_data.mm_single); break; case MAILMIME_MULTIPLE: for(cur = clist_begin(mime->mm_data.mm_multipart.mm_mp_list) ; cur!=NULL ; cur = clist_next(cur)) { printf("-------------------------------------------------------\n"); print_mime((struct mailmime*)clist_content(cur)); printf("------------------------------------------------------\n"); } break; case MAILMIME_MESSAGE: if (mime->mm_data.mm_message.mm_fields) { if (clist_begin(mime->mm_data.mm_message.mm_fields->fld_list)!=NULL) { printf("---------------------------------------------------------------\n"); display_fields(mime->mm_data.mm_message.mm_fields); printf("--------------------------------------------------------------\n"); } if (mime->mm_data.mm_message.mm_msg_mime!=NULL) { printf("--------------------------------------------------------\n"); print_mime(mime->mm_data.mm_message.mm_msg_mime); printf("-------------------------------------------------------\n"); } } break; } } void mailmime_print(struct mailmime* mime) { printf("========================================================================\n"); print_mime(mime); printf("=======================================================================\n\n"); } #endif /* DEBUG_MIME_OUTPUT */ /******************************************************************************* * low-level-tools for getting a list of all recipients ******************************************************************************/ static void mailimf_get_recipients__add_addr(dc_hash_t* recipients, struct mailimf_mailbox* mb) { /* only used internally by mailimf_get_recipients() */ if (mb) { char* addr_norm = dc_addr_normalize(mb->mb_addr_spec); dc_hash_insert(recipients, addr_norm, strlen(addr_norm), (void*)1); free(addr_norm); } } dc_hash_t* mailimf_get_recipients(struct mailimf_fields* imffields) { /* the returned value must be dc_hash_clear()'d and free()'d. returned addresses are normalized. */ dc_hash_t* recipients = malloc(sizeof(dc_hash_t)); dc_hash_init(recipients, DC_HASH_STRING, 1/*copy key*/); clistiter* cur1; for (cur1 = clist_begin(imffields->fld_list); cur1!=NULL ; cur1=clist_next(cur1)) { struct mailimf_field* fld = (struct mailimf_field*)clist_content(cur1); struct mailimf_to* fld_to = NULL; struct mailimf_cc* fld_cc = NULL; struct mailimf_address_list* addr_list = NULL; switch (fld->fld_type) { case MAILIMF_FIELD_TO: fld_to = fld->fld_data.fld_to; if (fld_to) { addr_list = fld_to->to_addr_list; } break; case MAILIMF_FIELD_CC: fld_cc = fld->fld_data.fld_cc; if (fld_cc) { addr_list = fld_cc->cc_addr_list; } break; } if (addr_list) { clistiter* cur2; for (cur2 = clist_begin(addr_list->ad_list); cur2!=NULL ; cur2=clist_next(cur2)) { struct mailimf_address* adr = (struct mailimf_address*)clist_content(cur2); if (adr) { if (adr->ad_type==MAILIMF_ADDRESS_MAILBOX) { mailimf_get_recipients__add_addr(recipients, adr->ad_data.ad_mailbox); } else if (adr->ad_type==MAILIMF_ADDRESS_GROUP) { struct mailimf_group* group = adr->ad_data.ad_group; if (group && group->grp_mb_list) { clistiter* cur3; for (cur3 = clist_begin(group->grp_mb_list->mb_list); cur3!=NULL ; cur3=clist_next(cur3)) { mailimf_get_recipients__add_addr(recipients, (struct mailimf_mailbox*)clist_content(cur3)); } } } } } } } return recipients; } /******************************************************************************* * low-level-tools for working with mailmime structures directly ******************************************************************************/ struct mailmime_parameter* mailmime_find_ct_parameter(struct mailmime* mime, const char* name) { /* find a parameter in `Content-Type: foo/bar; name=value;` */ if (mime==NULL || name==NULL || mime->mm_content_type==NULL || mime->mm_content_type->ct_parameters==NULL) { return NULL; } clistiter* cur; for (cur = clist_begin(mime->mm_content_type->ct_parameters); cur!=NULL; cur = clist_next(cur)) { struct mailmime_parameter* param = (struct mailmime_parameter*)clist_content(cur); if (param && param->pa_name) { if (strcmp(param->pa_name, name)==0) { return param; } } } return NULL; } int mailmime_transfer_decode(struct mailmime* mime, const char** ret_decoded_data, size_t* ret_decoded_data_bytes, char** ret_to_mmap_string_unref) { int mime_transfer_encoding = MAILMIME_MECHANISM_BINARY; struct mailmime_data* mime_data = NULL; const char* decoded_data = NULL; /* must not be free()'d */ size_t decoded_data_bytes = 0; char* transfer_decoding_buffer = NULL; /* mmap_string_unref()'d if set */ if (mime==NULL || ret_decoded_data==NULL || ret_decoded_data_bytes==NULL || ret_to_mmap_string_unref==NULL || *ret_decoded_data!=NULL || *ret_decoded_data_bytes!=0 || *ret_to_mmap_string_unref!=NULL) { return 0; } mime_data = mime->mm_data.mm_single; if (mime->mm_mime_fields!=NULL) { clistiter* cur; for (cur = clist_begin(mime->mm_mime_fields->fld_list); cur!=NULL; cur = clist_next(cur)) { struct mailmime_field* field = (struct mailmime_field*)clist_content(cur); if (field && field->fld_type==MAILMIME_FIELD_TRANSFER_ENCODING && field->fld_data.fld_encoding) { mime_transfer_encoding = field->fld_data.fld_encoding->enc_type; break; } } } /* regard `Content-Transfer-Encoding:` */ if (mime_transfer_encoding==MAILMIME_MECHANISM_7BIT || mime_transfer_encoding==MAILMIME_MECHANISM_8BIT || mime_transfer_encoding==MAILMIME_MECHANISM_BINARY) { decoded_data = mime_data->dt_data.dt_text.dt_data; decoded_data_bytes = mime_data->dt_data.dt_text.dt_length; if (decoded_data==NULL || decoded_data_bytes <= 0) { return 0; /* no error - but no data */ } } else { int r; size_t current_index = 0; r = mailmime_part_parse(mime_data->dt_data.dt_text.dt_data, mime_data->dt_data.dt_text.dt_length, ¤t_index, mime_transfer_encoding, &transfer_decoding_buffer, &decoded_data_bytes); if (r!=MAILIMF_NO_ERROR || transfer_decoding_buffer==NULL || decoded_data_bytes <= 0) { return 0; } decoded_data = transfer_decoding_buffer; } *ret_decoded_data = decoded_data; *ret_decoded_data_bytes = decoded_data_bytes; *ret_to_mmap_string_unref = transfer_decoding_buffer; return 1; } struct mailimf_fields* mailmime_find_mailimf_fields(struct mailmime* mime) { if (mime==NULL) { return NULL; } switch (mime->mm_type) { case MAILMIME_MULTIPLE: for (clistiter* cur=clist_begin(mime->mm_data.mm_multipart.mm_mp_list); cur!=NULL ; cur=clist_next(cur)) { struct mailimf_fields* header = mailmime_find_mailimf_fields(clist_content(cur)); if (header) { return header; } } break; case MAILMIME_MESSAGE: return mime->mm_data.mm_message.mm_fields; } return NULL; } char* mailimf_find_first_addr(const struct mailimf_mailbox_list* mb_list) { if (mb_list==NULL) { return NULL; } for (clistiter* cur = clist_begin(mb_list->mb_list); cur!=NULL ; cur=clist_next(cur)) { struct mailimf_mailbox* mb = (struct mailimf_mailbox*)clist_content(cur); if (mb && mb->mb_addr_spec) { return dc_addr_normalize(mb->mb_addr_spec); } } return NULL; } struct mailimf_field* mailimf_find_field(struct mailimf_fields* header, int wanted_fld_type) { if (header==NULL || header->fld_list==NULL) { return NULL; } for (clistiter* cur1 = clist_begin(header->fld_list); cur1!=NULL ; cur1=clist_next(cur1)) { struct mailimf_field* field = (struct mailimf_field*)clist_content(cur1); if (field) { if (field->fld_type==wanted_fld_type) { return field; } } } return NULL; } struct mailimf_optional_field* mailimf_find_optional_field(struct mailimf_fields* header, const char* wanted_fld_name) { /* Note: the function does not return fields with no value set! */ if (header==NULL || header->fld_list==NULL) { return NULL; } for (clistiter* cur1 = clist_begin(header->fld_list); cur1!=NULL ; cur1=clist_next(cur1)) { struct mailimf_field* field = (struct mailimf_field*)clist_content(cur1); if (field && field->fld_type==MAILIMF_FIELD_OPTIONAL_FIELD) { struct mailimf_optional_field* optional_field = field->fld_data.fld_optional_field; if (optional_field && optional_field->fld_name && optional_field->fld_value && strcasecmp(optional_field->fld_name, wanted_fld_name)==0) { return optional_field; } } } return NULL; } static int mailmime_is_attachment_disposition(struct mailmime* mime) { if (mime->mm_mime_fields!=NULL) { for (clistiter* cur = clist_begin(mime->mm_mime_fields->fld_list); cur!=NULL; cur = clist_next(cur)) { struct mailmime_field* field = (struct mailmime_field*)clist_content(cur); if (field && field->fld_type==MAILMIME_FIELD_DISPOSITION && field->fld_data.fld_disposition) { if (field->fld_data.fld_disposition->dsp_type && field->fld_data.fld_disposition->dsp_type->dsp_type==MAILMIME_DISPOSITION_TYPE_ATTACHMENT) { return 1; } } } } return 0; } static void reconcat_mime(char** raw_mime, const char* type, const char* subtype) { if (raw_mime) { *raw_mime = dc_mprintf("%s/%s", type? type : "application", subtype? subtype : "octet-stream"); } } static int mailmime_get_mime_type(struct mailmime* mime, int* msg_type, char** raw_mime /*set only for discrete types with attachments*/) { #define DC_MIMETYPE_MP_ALTERNATIVE 10 #define DC_MIMETYPE_MP_RELATED 20 #define DC_MIMETYPE_MP_MIXED 30 #define DC_MIMETYPE_MP_NOT_DECRYPTABLE 40 #define DC_MIMETYPE_MP_REPORT 45 #define DC_MIMETYPE_MP_SIGNED 46 #define DC_MIMETYPE_MP_OTHER 50 #define DC_MIMETYPE_TEXT_PLAIN 60 #define DC_MIMETYPE_TEXT_HTML 70 #define DC_MIMETYPE_IMAGE 80 #define DC_MIMETYPE_AUDIO 90 #define DC_MIMETYPE_VIDEO 100 #define DC_MIMETYPE_FILE 110 #define DC_MIMETYPE_AC_SETUP_FILE 111 struct mailmime_content* c = mime->mm_content_type; int dummy = 0; if (msg_type==NULL) { msg_type = &dummy; } *msg_type = 0; if (c==NULL || c->ct_type==NULL) { return 0; } switch (c->ct_type->tp_type) { case MAILMIME_TYPE_DISCRETE_TYPE: switch (c->ct_type->tp_data.tp_discrete_type->dt_type) { case MAILMIME_DISCRETE_TYPE_TEXT: if (mailmime_is_attachment_disposition(mime)) { ; /* DC_MIMETYPE_FILE is returned below - we leave text attachments as attachments as they may be too large to display as a normal message, eg. complete books. */ } else if (strcmp(c->ct_subtype, "plain")==0) { *msg_type = DC_MSG_TEXT; return DC_MIMETYPE_TEXT_PLAIN; } else if (strcmp(c->ct_subtype, "html")==0) { *msg_type = DC_MSG_TEXT; return DC_MIMETYPE_TEXT_HTML; } *msg_type = DC_MSG_FILE; reconcat_mime(raw_mime, "text", c->ct_subtype); return DC_MIMETYPE_FILE; case MAILMIME_DISCRETE_TYPE_IMAGE: if (strcmp(c->ct_subtype, "gif")==0) { *msg_type = DC_MSG_GIF; } else if (strcmp(c->ct_subtype, "svg+xml")==0) { *msg_type = DC_MSG_FILE; reconcat_mime(raw_mime, "image", c->ct_subtype); return DC_MIMETYPE_FILE; } else { *msg_type = DC_MSG_IMAGE; } reconcat_mime(raw_mime, "image", c->ct_subtype); return DC_MIMETYPE_IMAGE; case MAILMIME_DISCRETE_TYPE_AUDIO: *msg_type = DC_MSG_AUDIO; /* we correct this later to DC_MSG_VOICE, currently, this is not possible as we do not know the main header */ reconcat_mime(raw_mime, "audio", c->ct_subtype); return DC_MIMETYPE_AUDIO; case MAILMIME_DISCRETE_TYPE_VIDEO: *msg_type = DC_MSG_VIDEO; reconcat_mime(raw_mime, "video", c->ct_subtype); return DC_MIMETYPE_VIDEO; default: *msg_type = DC_MSG_FILE; if (c->ct_type->tp_data.tp_discrete_type->dt_type==MAILMIME_DISCRETE_TYPE_APPLICATION && strcmp(c->ct_subtype, "autocrypt-setup")==0) { reconcat_mime(raw_mime, "application", c->ct_subtype); return DC_MIMETYPE_AC_SETUP_FILE; /* application/autocrypt-setup */ } reconcat_mime(raw_mime, c->ct_type->tp_data.tp_discrete_type->dt_extension, c->ct_subtype); return DC_MIMETYPE_FILE; } break; case MAILMIME_TYPE_COMPOSITE_TYPE: if (c->ct_type->tp_data.tp_composite_type->ct_type==MAILMIME_COMPOSITE_TYPE_MULTIPART) { if (strcmp(c->ct_subtype, "alternative")==0) { return DC_MIMETYPE_MP_ALTERNATIVE; } else if (strcmp(c->ct_subtype, "related")==0) { return DC_MIMETYPE_MP_RELATED; } else if (strcmp(c->ct_subtype, "encrypted")==0) { return DC_MIMETYPE_MP_NOT_DECRYPTABLE; /* decryptable parts are already converted to other mime parts in dc_e2ee_decrypt() */ } else if (strcmp(c->ct_subtype, "signed")==0) { return DC_MIMETYPE_MP_SIGNED; } else if (strcmp(c->ct_subtype, "mixed")==0) { return DC_MIMETYPE_MP_MIXED; } else if (strcmp(c->ct_subtype, "report")==0) { return DC_MIMETYPE_MP_REPORT; } else { return DC_MIMETYPE_MP_OTHER; } } else if (c->ct_type->tp_data.tp_composite_type->ct_type==MAILMIME_COMPOSITE_TYPE_MESSAGE) { /* Enacapsulated messages, see https://www.w3.org/Protocols/rfc1341/7_3_Message.html Also used as part "message/disposition-notification" of "multipart/report", which, however, will be handled separatedly. I've not seen any messages using this, so we do not attach these parts (maybe they're used to attach replies, which are unwanted at all). For now, we skip these parts at all; if desired, we could return DC_MIMETYPE_FILE/DC_MSG_FILE for selected and known subparts. */ return 0; } break; default: break; } return 0; /* unknown */ } /******************************************************************************* * a MIME part ******************************************************************************/ static dc_mimepart_t* dc_mimepart_new(void) { dc_mimepart_t* mimepart = NULL; if ((mimepart=calloc(1, sizeof(dc_mimepart_t)))==NULL) { exit(33); } mimepart->type = 0; mimepart->param = dc_param_new(); return mimepart; } static void dc_mimepart_unref(dc_mimepart_t* mimepart) { if (mimepart==NULL) { return; } free(mimepart->msg); mimepart->msg = NULL; free(mimepart->msg_raw); mimepart->msg_raw = NULL; dc_param_unref(mimepart->param); free(mimepart); } /******************************************************************************* * Main interface ******************************************************************************/ /** * Create a new mime parser object. * * @private @memberof dc_mimeparser_t * @param blobdir Directrory to write attachments to. * @param context Mailbox object, used for logging only. * @return The MIME-parser object. */ dc_mimeparser_t* dc_mimeparser_new(const char* blobdir, dc_context_t* context) { dc_mimeparser_t* mimeparser = NULL; if ((mimeparser=calloc(1, sizeof(dc_mimeparser_t)))==NULL) { exit(30); } mimeparser->context = context; mimeparser->parts = carray_new(16); mimeparser->blobdir = blobdir; /* no need to copy the string at the moment */ mimeparser->reports = carray_new(16); mimeparser->e2ee_helper = calloc(1, sizeof(dc_e2ee_helper_t)); dc_hash_init(&mimeparser->header, DC_HASH_STRING, 0/* do not copy key */); return mimeparser; } /** * Free a MIME-parser object. * * Esp. all data allocated by dc_mimeparser_parse() will be free()'d. * * @private @memberof dc_mimeparser_t * @param mimeparser The MIME-parser object. * @return None. */ void dc_mimeparser_unref(dc_mimeparser_t* mimeparser) { if (mimeparser==NULL) { return; } dc_mimeparser_empty(mimeparser); if (mimeparser->parts) { carray_free(mimeparser->parts); } if (mimeparser->reports) { carray_free(mimeparser->reports); } free(mimeparser->e2ee_helper); free(mimeparser); } /** * Empty all data in a MIME-parser object. * * This function is called implicitly by dc_mimeparser_parse() to free * previously allocated data. * * @private @memberof dc_mimeparser_t * @param mimeparser The MIME-parser object. * @return None. */ void dc_mimeparser_empty(dc_mimeparser_t* mimeparser) { if (mimeparser==NULL) { return; } if (mimeparser->parts) { int i, cnt = carray_count(mimeparser->parts); for (i = 0; i < cnt; i++) { dc_mimepart_t* part = (dc_mimepart_t*)carray_get(mimeparser->parts, i); if (part) { dc_mimepart_unref(part); } } carray_set_size(mimeparser->parts, 0); } mimeparser->header_root = NULL; /* a pointer somewhere to the MIME data, must NOT be freed */ dc_hash_clear(&mimeparser->header); if (mimeparser->header_protected) { mailimf_fields_free(mimeparser->header_protected); /* allocated as needed, MUST be freed */ mimeparser->header_protected = NULL; } mimeparser->is_send_by_messenger = 0; mimeparser->is_system_message = 0; free(mimeparser->subject); mimeparser->subject = NULL; if (mimeparser->mimeroot) { mailmime_free(mimeparser->mimeroot); mimeparser->mimeroot = NULL; } mimeparser->is_forwarded = 0; if (mimeparser->reports) { carray_set_size(mimeparser->reports, 0); } mimeparser->decrypting_failed = 0; dc_e2ee_thanks(mimeparser->e2ee_helper); dc_kml_unref(mimeparser->location_kml); mimeparser->location_kml = NULL; dc_kml_unref(mimeparser->message_kml); mimeparser->message_kml = NULL; } void dc_mimeparser_repl_msg_by_error(dc_mimeparser_t* mimeparser, const char* error_msg) { dc_mimepart_t* part = NULL; int i = 0; if (mimeparser==NULL || mimeparser->parts==NULL || carray_count(mimeparser->parts)<=0) { return; } // part->raw_msg is unchanged // so that the original message can be retrieved using dc_get_msg_info() part = (dc_mimepart_t*)carray_get(mimeparser->parts, 0); part->type = DC_MSG_TEXT; free(part->msg); part->msg = dc_mprintf(DC_EDITORIAL_OPEN "%s" DC_EDITORIAL_CLOSE, error_msg); for (i = 1; i < carray_count(mimeparser->parts); i++) { part = (dc_mimepart_t*)carray_get(mimeparser->parts, i); if (part) { dc_mimepart_unref(part); } } carray_set_size(mimeparser->parts, 1); } static void do_add_single_part(dc_mimeparser_t* parser, dc_mimepart_t* part) { /* add a single part to the list of parts, the parser takes the ownership of the part, so you MUST NOT unref it after calling this function. */ if (parser->e2ee_helper->encrypted && dc_hash_cnt(parser->e2ee_helper->signatures)>0) { dc_param_set_int(part->param, DC_PARAM_GUARANTEE_E2EE, 1); } else if (parser->e2ee_helper->encrypted) { dc_param_set_int(part->param, DC_PARAM_ERRONEOUS_E2EE, DC_E2EE_NO_VALID_SIGNATURE); } carray_add(parser->parts, (void*)part, NULL); } static void do_add_single_file_part(dc_mimeparser_t* parser, int msg_type, int mime_type, const char* raw_mime, const char* decoded_data, size_t decoded_data_bytes, const char* desired_filename) { dc_mimepart_t* part = NULL; char* pathNfilename = NULL; /* create a free file name to use */ if ((pathNfilename=dc_get_fine_pathNfilename(parser->context, "$BLOBDIR", desired_filename))==NULL) { goto cleanup; } /* copy data to file */ if (dc_write_file(parser->context, pathNfilename, decoded_data, decoded_data_bytes)==0) { goto cleanup; } part = dc_mimepart_new(); part->type = msg_type; part->int_mimetype = mime_type; part->bytes = decoded_data_bytes; dc_param_set(part->param, DC_PARAM_FILE, pathNfilename); dc_param_set(part->param, DC_PARAM_MIMETYPE, raw_mime); if (mime_type==DC_MIMETYPE_IMAGE) { uint32_t w = 0, h = 0; if (dc_get_filemeta(decoded_data, decoded_data_bytes, &w, &h)) { dc_param_set_int(part->param, DC_PARAM_WIDTH, w); dc_param_set_int(part->param, DC_PARAM_HEIGHT, h); } } do_add_single_part(parser, part); part = NULL; cleanup: free(pathNfilename); dc_mimepart_unref(part); } static int dc_mimeparser_add_single_part_if_known(dc_mimeparser_t* mimeparser, struct mailmime* mime) { dc_mimepart_t* part = NULL; int old_part_count = carray_count(mimeparser->parts); int mime_type; struct mailmime_data* mime_data; char* file_suffix = NULL; char* desired_filename = NULL; int msg_type = 0; char* raw_mime = NULL; char* transfer_decoding_buffer = NULL; /* mmap_string_unref()'d if set */ char* charset_buffer = NULL; /* charconv_buffer_free()'d if set (just calls mmap_string_unref()) */ const char* decoded_data = NULL; /* must not be free()'d */ size_t decoded_data_bytes = 0; dc_simplify_t* simplifier = NULL; if (mime==NULL || mime->mm_data.mm_single==NULL) { goto cleanup; } /* get mime type from `mime` */ mime_type = mailmime_get_mime_type(mime, &msg_type, &raw_mime); /* get data pointer from `mime` */ mime_data = mime->mm_data.mm_single; if (mime_data->dt_type!=MAILMIME_DATA_TEXT /* MAILMIME_DATA_FILE indicates, the data is in a file; AFAIK this is not used on parsing */ || mime_data->dt_data.dt_text.dt_data==NULL || mime_data->dt_data.dt_text.dt_length <= 0) { goto cleanup; } /* regard `Content-Transfer-Encoding:` */ if (!mailmime_transfer_decode(mime, &decoded_data, &decoded_data_bytes, &transfer_decoding_buffer)) { goto cleanup; /* no always error - but no data */ } switch (mime_type) { case DC_MIMETYPE_TEXT_PLAIN: case DC_MIMETYPE_TEXT_HTML: { if (simplifier==NULL) { simplifier = dc_simplify_new(); if (simplifier==NULL) { goto cleanup; } } const char* charset = mailmime_content_charset_get(mime->mm_content_type); /* get from `Content-Type: text/...; charset=utf-8`; must not be free()'d */ if (charset!=NULL && strcmp(charset, "utf-8")!=0 && strcmp(charset, "UTF-8")!=0) { size_t ret_bytes = 0; int r = charconv_buffer("utf-8", charset, decoded_data, decoded_data_bytes, &charset_buffer, &ret_bytes); if (r!=MAIL_CHARCONV_NO_ERROR) { dc_log_warning(mimeparser->context, 0, "Cannot convert %i bytes from \"%s\" to \"utf-8\"; errorcode is %i.", /* if this warning comes up for usual character sets, maybe libetpan is compiled without iconv? */ (int)decoded_data_bytes, charset, (int)r); /* continue, however */ } else if (charset_buffer==NULL || ret_bytes <= 0) { goto cleanup; /* no error - but nothing to add */ } else { decoded_data = charset_buffer; decoded_data_bytes = ret_bytes; } } /* check header directly as is_send_by_messenger is not yet set up */ int is_msgrmsg = dc_mimeparser_lookup_optional_field(mimeparser, "Chat-Version")!=NULL; char* simplified_txt = dc_simplify_simplify(simplifier, decoded_data, decoded_data_bytes, mime_type==DC_MIMETYPE_TEXT_HTML? 1 : 0, is_msgrmsg); if (simplified_txt && simplified_txt[0]) { part = dc_mimepart_new(); part->type = DC_MSG_TEXT; part->int_mimetype = mime_type; part->msg = simplified_txt; part->msg_raw = strndup(decoded_data, decoded_data_bytes); do_add_single_part(mimeparser, part); part = NULL; } else { free(simplified_txt); } if (simplifier->is_forwarded) { mimeparser->is_forwarded = 1; } } break; case DC_MIMETYPE_IMAGE: case DC_MIMETYPE_AUDIO: case DC_MIMETYPE_VIDEO: case DC_MIMETYPE_FILE: case DC_MIMETYPE_AC_SETUP_FILE: { /* try to get file name from `Content-Disposition: ... filename*=...` or `Content-Disposition: ... filename*0*=... filename*1*=... filename*2*=...` or `Content-Disposition: ... filename=...` */ dc_strbuilder_t filename_parts; dc_strbuilder_init(&filename_parts, 0); for (clistiter* cur1 = clist_begin(mime->mm_mime_fields->fld_list); cur1!=NULL; cur1 = clist_next(cur1)) { struct mailmime_field* field = (struct mailmime_field*)clist_content(cur1); if (field && field->fld_type==MAILMIME_FIELD_DISPOSITION && field->fld_data.fld_disposition) { struct mailmime_disposition* file_disposition = field->fld_data.fld_disposition; if (file_disposition) { for (clistiter* cur2 = clist_begin(file_disposition->dsp_parms); cur2!=NULL; cur2 = clist_next(cur2)) { struct mailmime_disposition_parm* dsp_param = (struct mailmime_disposition_parm*)clist_content(cur2); if (dsp_param) { if (dsp_param->pa_type==MAILMIME_DISPOSITION_PARM_PARAMETER && dsp_param->pa_data.pa_parameter && dsp_param->pa_data.pa_parameter->pa_name && strncmp(dsp_param->pa_data.pa_parameter->pa_name, "filename*", 9)==0) { dc_strbuilder_cat(&filename_parts, dsp_param->pa_data.pa_parameter->pa_value); // we assume the filename*?* parts are in order, not seen anything else yet } else if (dsp_param->pa_type==MAILMIME_DISPOSITION_PARM_FILENAME) { desired_filename = dc_decode_header_words(dsp_param->pa_data.pa_filename); // this is used only if the parts buffer stays empty } } } } break; } } if (strlen(filename_parts.buf)) { free(desired_filename); desired_filename = dc_decode_ext_header(filename_parts.buf); } free(filename_parts.buf); /* try to get file name from `Content-Type: ... name=...` */ if (desired_filename==NULL) { struct mailmime_parameter* param = mailmime_find_ct_parameter(mime, "name"); if (param && param->pa_value && param->pa_value[0]) { desired_filename = dc_strdup(param->pa_value);// is already decoded, see #162 } } /* if there is still no filename, guess one */ if (desired_filename==NULL) { if (mime->mm_content_type && mime->mm_content_type->ct_subtype) { desired_filename = dc_mprintf("file.%s", mime->mm_content_type->ct_subtype); } else { goto cleanup; } } if (strncmp(desired_filename, "location", 8)==0 && strncmp(desired_filename+strlen(desired_filename)-4, ".kml", 4)==0) { mimeparser->location_kml = dc_kml_parse(mimeparser->context, decoded_data, decoded_data_bytes); goto cleanup; } if (strncmp(desired_filename, "message", 7)==0 && strncmp(desired_filename+strlen(desired_filename)-4, ".kml", 4)==0) { mimeparser->message_kml = dc_kml_parse(mimeparser->context, decoded_data, decoded_data_bytes); goto cleanup; } dc_replace_bad_utf8_chars(desired_filename); do_add_single_file_part(mimeparser, msg_type, mime_type, raw_mime, decoded_data, decoded_data_bytes, desired_filename); } break; default: break; } /* add object? (we do not add all objetcs, eg. signatures etc. are ignored) */ cleanup: dc_simplify_unref(simplifier); if (charset_buffer) { charconv_buffer_free(charset_buffer); } if (transfer_decoding_buffer) { mmap_string_unref(transfer_decoding_buffer); } free(file_suffix); free(desired_filename); dc_mimepart_unref(part); free(raw_mime); return carray_count(mimeparser->parts)>old_part_count? 1 : 0; /* any part added? */ } static int dc_mimeparser_parse_mime_recursive(dc_mimeparser_t* mimeparser, struct mailmime* mime) { int any_part_added = 0; clistiter* cur = NULL; if (mimeparser==NULL || mime==NULL) { return 0; } if (mailmime_find_ct_parameter(mime, "protected-headers")) { if (mime->mm_type==MAILMIME_SINGLE && mime->mm_content_type->ct_type->tp_type==MAILMIME_TYPE_DISCRETE_TYPE && mime->mm_content_type->ct_type->tp_data.tp_discrete_type->dt_type==MAILMIME_DISCRETE_TYPE_TEXT && mime->mm_content_type->ct_subtype && strcmp(mime->mm_content_type->ct_subtype, "rfc822-headers")==0) { dc_log_info(mimeparser->context, 0, "Protected headers found in text/rfc822-headers attachment: Will be ignored."); /* we want the protected headers in the normal header of the payload */ return 0; } if (mimeparser->header_protected==NULL) { /* use the most outer protected header - this is typically created in sync with the normal, unprotected header */ size_t dummy = 0; if (mailimf_envelope_and_optional_fields_parse(mime->mm_mime_start, mime->mm_length, &dummy, &mimeparser->header_protected)!=MAILIMF_NO_ERROR || mimeparser->header_protected==NULL) { dc_log_warning(mimeparser->context, 0, "Protected headers parsing error."); } else { hash_header(&mimeparser->header, mimeparser->header_protected, mimeparser->context); } } else { dc_log_info(mimeparser->context, 0, "Protected headers found in MIME header: Will be ignored as we already found an outer one."); } } switch (mime->mm_type) { case MAILMIME_SINGLE: any_part_added = dc_mimeparser_add_single_part_if_known(mimeparser, mime); break; case MAILMIME_MULTIPLE: switch (mailmime_get_mime_type(mime, NULL, NULL)) { case DC_MIMETYPE_MP_ALTERNATIVE: /* add "best" part */ /* Most times, mutlipart/alternative contains true alternatives as text/plain and text/html. If we find a multipart/mixed inside mutlipart/alternative, we use this (happens eg in apple mail: "plaintext" as an alternative to "html+PDF attachment") */ for (cur=clist_begin(mime->mm_data.mm_multipart.mm_mp_list); cur!=NULL; cur=clist_next(cur)) { struct mailmime* childmime = (struct mailmime*)clist_content(cur); if (mailmime_get_mime_type(childmime, NULL, NULL)==DC_MIMETYPE_MP_MIXED) { any_part_added = dc_mimeparser_parse_mime_recursive(mimeparser, childmime); break; } } if (!any_part_added) { /* search for text/plain and add this */ for (cur=clist_begin(mime->mm_data.mm_multipart.mm_mp_list); cur!=NULL; cur=clist_next(cur)) { struct mailmime* childmime = (struct mailmime*)clist_content(cur); if (mailmime_get_mime_type(childmime, NULL, NULL)==DC_MIMETYPE_TEXT_PLAIN) { any_part_added = dc_mimeparser_parse_mime_recursive(mimeparser, childmime); break; } } } if (!any_part_added) { /* `text/plain` not found - use the first part */ for (cur=clist_begin(mime->mm_data.mm_multipart.mm_mp_list); cur!=NULL; cur=clist_next(cur)) { if (dc_mimeparser_parse_mime_recursive(mimeparser, (struct mailmime*)clist_content(cur))) { any_part_added = 1; break; /* out of for() */ } } } break; case DC_MIMETYPE_MP_RELATED: /* add the "root part" - the other parts may be referenced which is not interesting for us (eg. embedded images) */ /* we assume he "root part" being the first one, which may not be always true ... however, most times it seems okay. */ cur=clist_begin(mime->mm_data.mm_multipart.mm_mp_list); if (cur) { any_part_added = dc_mimeparser_parse_mime_recursive(mimeparser, (struct mailmime*)clist_content(cur)); } break; case DC_MIMETYPE_MP_NOT_DECRYPTABLE: { dc_mimepart_t* part = dc_mimepart_new(); part->type = DC_MSG_TEXT; char* msg_body = dc_stock_str(mimeparser->context, DC_STR_CANTDECRYPT_MSG_BODY); part->msg = dc_mprintf(DC_EDITORIAL_OPEN "%s" DC_EDITORIAL_CLOSE, msg_body); part->msg_raw = dc_strdup(part->msg); free(msg_body); carray_add(mimeparser->parts, (void*)part, NULL); any_part_added = 1; mimeparser->decrypting_failed = 1; } break; case DC_MIMETYPE_MP_SIGNED: /* RFC 1847: "The multipart/signed content type contains exactly two body parts. The first body part is the body part over which the digital signature was created [...] The second body part contains the control information necessary to verify the digital signature." We simpliy take the first body part and skip the rest. (see https://k9mail.github.io/2016/11/24/OpenPGP-Considerations-Part-I.html for background information why we use encrypted+signed) */ if ((cur=clist_begin(mime->mm_data.mm_multipart.mm_mp_list))!=NULL) { any_part_added = dc_mimeparser_parse_mime_recursive(mimeparser, (struct mailmime*)clist_content(cur)); } break; case DC_MIMETYPE_MP_REPORT: if (clist_count(mime->mm_data.mm_multipart.mm_mp_list) >= 2) /* RFC 6522: the first part is for humans, the second for machines */ { struct mailmime_parameter* report_type = mailmime_find_ct_parameter(mime, "report-type"); if (report_type && report_type->pa_value && strcmp(report_type->pa_value, "disposition-notification")==0) { carray_add(mimeparser->reports, (void*)mime, NULL); } else { /* eg. `report-type=delivery-status`; maybe we should show them as a little error icon */ any_part_added = dc_mimeparser_parse_mime_recursive(mimeparser, (struct mailmime*)clist_content(clist_begin(mime->mm_data.mm_multipart.mm_mp_list))); } } break; default: /* eg. DC_MIMETYPE_MP_MIXED - add all parts (in fact, AddSinglePartIfKnown() later check if the parts are really supported) */ { /* HACK: the following lines are a hack for clients who use multipart/mixed instead of multipart/alternative for combined text/html messages (eg. Stock Android "Mail" does so). So, if I detect such a message below, I skip the HTML part. However, I'm not sure, if there are useful situations to use plain+html in multipart/mixed - if so, we should disable the hack. */ struct mailmime* skip_part = NULL; { struct mailmime* html_part = NULL; int plain_cnt = 0, html_cnt = 0; for (cur=clist_begin(mime->mm_data.mm_multipart.mm_mp_list); cur!=NULL; cur=clist_next(cur)) { struct mailmime* childmime = (struct mailmime*)clist_content(cur); if (mailmime_get_mime_type(childmime, NULL, NULL)==DC_MIMETYPE_TEXT_PLAIN) { plain_cnt++; } else if (mailmime_get_mime_type(childmime, NULL, NULL)==DC_MIMETYPE_TEXT_HTML) { html_part = childmime; html_cnt++; } } if (plain_cnt==1 && html_cnt==1) { dc_log_warning(mimeparser->context, 0, "HACK: multipart/mixed message found with PLAIN and HTML, we'll skip the HTML part as this seems to be unwanted."); skip_part = html_part; } } /* /HACK */ for (cur=clist_begin(mime->mm_data.mm_multipart.mm_mp_list); cur!=NULL; cur=clist_next(cur)) { struct mailmime* childmime = (struct mailmime*)clist_content(cur); if (childmime!=skip_part) { if (dc_mimeparser_parse_mime_recursive(mimeparser, childmime)) { any_part_added = 1; } } } } break; } break; case MAILMIME_MESSAGE: if (mimeparser->header_root==NULL) { mimeparser->header_root = mime->mm_data.mm_message.mm_fields; hash_header(&mimeparser->header, mimeparser->header_root, mimeparser->context); } if (mime->mm_data.mm_message.mm_msg_mime) { any_part_added = dc_mimeparser_parse_mime_recursive(mimeparser, mime->mm_data.mm_message.mm_msg_mime); } break; } return any_part_added; } static void hash_header(dc_hash_t* out, const struct mailimf_fields* in, dc_context_t* context) { if (NULL==in) { return; } for (clistiter* cur1=clist_begin(in->fld_list); cur1!=NULL ; cur1=clist_next(cur1)) { struct mailimf_field* field = (struct mailimf_field*)clist_content(cur1); const char *key = NULL; switch (field->fld_type) { case MAILIMF_FIELD_RETURN_PATH: key = "Return-Path"; break; case MAILIMF_FIELD_ORIG_DATE: key = "Date"; break; case MAILIMF_FIELD_FROM: key = "From"; break; case MAILIMF_FIELD_SENDER: key = "Sender"; break; case MAILIMF_FIELD_REPLY_TO: key = "Reply-To"; break; case MAILIMF_FIELD_TO: key = "To"; break; case MAILIMF_FIELD_CC: key = "Cc"; break; case MAILIMF_FIELD_BCC: key = "Bcc"; break; case MAILIMF_FIELD_MESSAGE_ID: key = "Message-ID"; break; case MAILIMF_FIELD_IN_REPLY_TO: key = "In-Reply-To"; break; case MAILIMF_FIELD_REFERENCES: key = "References"; break; case MAILIMF_FIELD_SUBJECT: key = "Subject"; break; case MAILIMF_FIELD_OPTIONAL_FIELD: { const struct mailimf_optional_field* optional_field = field->fld_data.fld_optional_field; if (optional_field) { key = optional_field->fld_name; } } break; } if (key) { int key_len = strlen(key); if (dc_hash_find(out, key, key_len)) { /* key already in hash, do only overwrite known types */ if (field->fld_type!=MAILIMF_FIELD_OPTIONAL_FIELD || (key_len>5 && strncasecmp(key, "Chat-", 5)==0)) { //dc_log_info(context, 0, "Protected headers: Overwriting \"%s\".", key); dc_hash_insert(out, key, key_len, field); } } else { /* key not hashed before */ dc_hash_insert(out, key, key_len, field); } } } } /** * Parse raw MIME-data into a MIME-object. * * You may call this function several times on the same object; old data are cleared using * dc_mimeparser_empty() before parsing is started. * * After dc_mimeparser_parse() is called successfully, all the functions to get information about the * MIME-structure will work. * * @private @memberof dc_mimeparser_t * @param mimeparser The MIME-parser object. * @param body_not_terminated Plain text, no need to be null-terminated. * @param body_bytes The number of bytes to read from body_not_terminated. * body_not_terminated is null-terminated, use strlen(body_not_terminated) here. * @return None. */ void dc_mimeparser_parse(dc_mimeparser_t* mimeparser, const char* body_not_terminated, size_t body_bytes) { int r = 0; size_t index = 0; struct mailimf_optional_field* optional_field = NULL; dc_mimeparser_empty(mimeparser); /* parse body */ r = mailmime_parse(body_not_terminated, body_bytes, &index, &mimeparser->mimeroot); if(r!=MAILIMF_NO_ERROR || mimeparser->mimeroot==NULL) { goto cleanup; } //printf("before decryption:\n"); mailmime_print(mimeparser->mimeroot); /* decrypt, if possible; handle Autocrypt:-header (decryption may modifiy the given object) */ dc_e2ee_decrypt(mimeparser->context, mimeparser->mimeroot, mimeparser->e2ee_helper); //printf("after decryption:\n"); mailmime_print(mimeparser->mimeroot); /* recursively check, whats parsed, this also sets up header_old */ dc_mimeparser_parse_mime_recursive(mimeparser, mimeparser->mimeroot); /* set some basic data */ { struct mailimf_field* field = dc_mimeparser_lookup_field(mimeparser, "Subject"); if (field && field->fld_type==MAILIMF_FIELD_SUBJECT) { mimeparser->subject = dc_decode_header_words(field->fld_data.fld_subject->sbj_value); } } if (dc_mimeparser_lookup_optional_field(mimeparser, "Chat-Version")) { mimeparser->is_send_by_messenger = 1; } if (dc_mimeparser_lookup_field(mimeparser, "Autocrypt-Setup-Message")) { /* Autocrypt-Setup-Message header found - check if there is an application/autocrypt-setup part */ int i, has_setup_file = 0; for (i = 0; i < carray_count(mimeparser->parts); i++) { dc_mimepart_t* part = (dc_mimepart_t*)carray_get(mimeparser->parts, i); if (part->int_mimetype==DC_MIMETYPE_AC_SETUP_FILE) { has_setup_file = 1; } } if (has_setup_file) { /* delete all parts but the application/autocrypt-setup part */ mimeparser->is_system_message = DC_CMD_AUTOCRYPT_SETUP_MESSAGE; for (i = 0; i < carray_count(mimeparser->parts); i++) { dc_mimepart_t* part = (dc_mimepart_t*)carray_get(mimeparser->parts, i); if (part->int_mimetype!=DC_MIMETYPE_AC_SETUP_FILE) { dc_mimepart_unref(part); carray_delete_slow(mimeparser->parts, i); i--; /* start over with the same index */ } } } } else if ((optional_field=dc_mimeparser_lookup_optional_field(mimeparser, "Chat-Content"))!=NULL && optional_field->fld_value!=NULL) { if (strcmp(optional_field->fld_value, "location-streaming-enabled")==0) { mimeparser->is_system_message = DC_CMD_LOCATION_STREAMING_ENABLED; } } /* some special system message? */ if (dc_mimeparser_lookup_field(mimeparser, "Chat-Group-Image") && carray_count(mimeparser->parts)>=1) { dc_mimepart_t* textpart = (dc_mimepart_t*)carray_get(mimeparser->parts, 0); if (textpart->type==DC_MSG_TEXT) { if (carray_count(mimeparser->parts)>=2) { dc_mimepart_t* imgpart = (dc_mimepart_t*)carray_get(mimeparser->parts, 1); if (imgpart->type==DC_MSG_IMAGE) { imgpart->is_meta = 1; } } } } // create compound messages if (mimeparser->is_send_by_messenger && s_generate_compound_msgs && carray_count(mimeparser->parts)==2) { dc_mimepart_t* textpart = (dc_mimepart_t*)carray_get(mimeparser->parts, 0); dc_mimepart_t* filepart = (dc_mimepart_t*)carray_get(mimeparser->parts, 1); if (textpart->type==DC_MSG_TEXT && DC_MSG_NEEDS_ATTACHMENT(filepart->type) && !filepart->is_meta) { free(filepart->msg); filepart->msg = textpart->msg; textpart->msg = NULL; dc_mimepart_unref(textpart); carray_delete_slow(mimeparser->parts, 0); } } /* prepend subject to message? */ if (mimeparser->subject) { int prepend_subject = 1; if (!mimeparser->decrypting_failed /* if decryption has failed, we always prepend the subject as this may contain cleartext hints from non-Delta MUAs. */) { char* p = strchr(mimeparser->subject, ':'); if ((p-mimeparser->subject)==2 /*Re: etc.*/ || (p-mimeparser->subject)==3 /*Fwd: etc.*/ || mimeparser->is_send_by_messenger || strstr(mimeparser->subject, DC_CHAT_PREFIX)!=NULL) { prepend_subject = 0; } } if (prepend_subject) { char* subj = dc_strdup(mimeparser->subject); char* p = strchr(subj, '['); /* do not add any tags as "[checked by XYZ]" */ if (p) { *p = 0; } dc_trim(subj); if (subj[0]) { int i, icnt = carray_count(mimeparser->parts); /* should be at least one - maybe empty - part */ for (i = 0; i < icnt; i++) { dc_mimepart_t* part = (dc_mimepart_t*)carray_get(mimeparser->parts, i); if (part->type==DC_MSG_TEXT) { char* new_txt = dc_mprintf("%s " DC_NDASH " %s", subj, part->msg); free(part->msg); part->msg = new_txt; break; } } } free(subj); } } /* add forward information to every part */ if (mimeparser->is_forwarded) { int i, icnt = carray_count(mimeparser->parts); /* should be at least one - maybe empty - part */ for (i = 0; i < icnt; i++) { dc_mimepart_t* part = (dc_mimepart_t*)carray_get(mimeparser->parts, i); dc_param_set_int(part->param, DC_PARAM_FORWARDED, 1); } } if (carray_count(mimeparser->parts)==1) { /* mark audio as voice message, if appropriate (we have to do this on global level as we do not know the global header in the recursice parse). and read some additional parameters */ dc_mimepart_t* part = (dc_mimepart_t*)carray_get(mimeparser->parts, 0); if (part->type==DC_MSG_AUDIO) { if (dc_mimeparser_lookup_optional_field(mimeparser, "Chat-Voice-Message")) { part->type = DC_MSG_VOICE; } } if (part->type==DC_MSG_AUDIO || part->type==DC_MSG_VOICE || part->type==DC_MSG_VIDEO) { const struct mailimf_optional_field* field = dc_mimeparser_lookup_optional_field(mimeparser, "Chat-Duration"); if (field) { int duration_ms = atoi(field->fld_value); if (duration_ms > 0 && duration_ms < 24*60*60*1000) { dc_param_set_int(part->param, DC_PARAM_DURATION, duration_ms); } } } } /* check, if the message asks for a MDN */ if (!mimeparser->decrypting_failed) { const struct mailimf_optional_field* dn_field = dc_mimeparser_lookup_optional_field(mimeparser, "Chat-Disposition-Notification-To"); /* we use "Chat-Disposition-Notification-To" as replies to "Disposition-Notification-To" are weird in many cases, are just freetext and/or do not follow any standard. */ if (dn_field && dc_mimeparser_get_last_nonmeta(mimeparser)/*just check if the mail is not empty*/) { struct mailimf_mailbox_list* mb_list = NULL; size_t index = 0; if (mailimf_mailbox_list_parse(dn_field->fld_value, strlen(dn_field->fld_value), &index, &mb_list)==MAILIMF_NO_ERROR && mb_list) { char* dn_to_addr = mailimf_find_first_addr(mb_list); if (dn_to_addr) { struct mailimf_field* from_field = dc_mimeparser_lookup_field(mimeparser, "From"); /* we need From: as this MUST match Disposition-Notification-To: */ if (from_field && from_field->fld_type==MAILIMF_FIELD_FROM && from_field->fld_data.fld_from) { char* from_addr = mailimf_find_first_addr(from_field->fld_data.fld_from->frm_mb_list); if (from_addr) { if (strcmp(from_addr, dn_to_addr)==0) { /* we mark _only_ the _last_ part to send a MDN (this avoids trouble with multi-part-messages who should send only one MDN. Moreover the last one is handy as it is the one typically displayed if the message is larger) */ dc_mimepart_t* part = dc_mimeparser_get_last_nonmeta(mimeparser); if (part) { dc_param_set_int(part->param, DC_PARAM_WANTS_MDN, 1); } } free(from_addr); } } free(dn_to_addr); } mailimf_mailbox_list_free(mb_list); } } } /* Cleanup - and try to create at least an empty part if there are no parts yet */ cleanup: if (!dc_mimeparser_has_nonmeta(mimeparser) && carray_count(mimeparser->reports)==0) { dc_mimepart_t* part = dc_mimepart_new(); part->type = DC_MSG_TEXT; if (mimeparser->subject && !mimeparser->is_send_by_messenger) { part->msg = dc_strdup(mimeparser->subject); } else { part->msg = dc_strdup(""); } carray_add(mimeparser->parts, (void*)part, NULL); } } /** * Lookup the given field name. * * Typical names are `From`, `To`, `Subject` and so on. * * @private @memberof dc_mimeparser_t * @param mimparser The MIME-parser object. * @param field_name The name of the field to look for. * @return A pointer to a mailimf_field structure. Must not be freed! * Before accessing the mailimf_field::fld_data, please always have a look at mailimf_field::fld_type! * If field_name could not be found, NULL is returned. */ struct mailimf_field* dc_mimeparser_lookup_field(dc_mimeparser_t* mimeparser, const char* field_name) { return (struct mailimf_field*)dc_hash_find_str(&mimeparser->header, field_name); } /** * Lookup the given field name. * * In addition to dc_mimeparser_lookup_field, this function also checks the mailimf_field::fld_type * for being MAILIMF_FIELD_OPTIONAL_FIELD. * * @private @memberof dc_mimeparser_t * @param mimparser The MIME-parser object. * @param field_name The name of the field to look for. * @return A pointer to a mailimf_optional_field structure. Must not be freed! * If field_name could not be found or has another type, NULL is returned. */ struct mailimf_optional_field* dc_mimeparser_lookup_optional_field(dc_mimeparser_t* mimeparser, const char* field_name) { struct mailimf_field* field = dc_hash_find_str(&mimeparser->header, field_name); if (field && field->fld_type==MAILIMF_FIELD_OPTIONAL_FIELD) { return field->fld_data.fld_optional_field; } return NULL; } /** * Gets the _last_ part _not_ flagged with is_meta. * * If you just want to check if there is a non-meta part preset, you can also * use the macro dc_mimeparser_has_nonmeta(). * * @private @memberof dc_mimeparser_t * @param mimeparser The MIME-parser object. * @return The last part that is not flagged with is_meta. The returned value * must not be freed. If there is no such part, NULL is returned. */ dc_mimepart_t* dc_mimeparser_get_last_nonmeta(dc_mimeparser_t* mimeparser) { if (mimeparser && mimeparser->parts) { int i, icnt = carray_count(mimeparser->parts); for (i = icnt-1; i >= 0; i--) { dc_mimepart_t* part = (dc_mimepart_t*)carray_get(mimeparser->parts, i); if (part && !part->is_meta) { return part; } } } return NULL; } /** * Checks, if the header of the mail looks as if it is a message from a mailing list. * * @private @memberof dc_mimeparser_t * @param mimeparser The MIME-parser object. * @return 1=the message is probably from a mailing list, * 0=the message is a normal messsage * * Some statistics: * * **Sorted out** by `List-ID`-header: * - Mailman mailing list messages - OK, mass messages * - Xing forum/event notifications - OK, mass messages * - Xing welcome-back, contact-request - Hm, but it _has_ the List-ID header * * **Sorted out** by `Precedence`-header: * - Majordomo mailing list messages - OK, mass messages * * **Not** sorted out: * - Pingdom notifications - OK, individual message * - Paypal notifications - OK, individual message * - Linked in visits, do-you-know - OK, individual message * - Share-It notifications - OK, individual message * - Transifex, Github notifications - OK, individual message * * Current state of mailing list handling: * * As we currently do not have an extra handling for mailing list messages, the * best is to ignore them completely. * * - if we know the sender, we should show them in the normal chat of the sender as this will lose the * context of the mail * * - for unknown senders, mailing list messages are often replies to known messages (see is_reply_to_known_message()) - * which gives the sender some trust. this should not happen for mailing list messages. * this may result in unwanted messages and contacts added to the address book that are not known. * * - of course, all this can be fixed, however, this may be a lot of work. * moreover, if we allow answering to mailing lists, it might not be easy to follow the conventions used in typical mailing list, * eg threads. * * "Mailing lists messages" in this sense are messages marked by List-Id or Precedence headers. * For the future, we might want to show mailing lists as groups. * (NB: typical mailing list header: `From: sender@gmx.net To: list@address.net) * */ int dc_mimeparser_is_mailinglist_message(dc_mimeparser_t* mimeparser) { if (mimeparser==NULL) { return 0; } if (dc_mimeparser_lookup_field(mimeparser, "List-Id")!=NULL) { return 1; /* mailing list identified by the presence of `List-ID` from RFC 2919 */ } struct mailimf_optional_field* precedence = dc_mimeparser_lookup_optional_field(mimeparser, "Precedence"); if (precedence!=NULL) { if (strcasecmp(precedence->fld_value, "list")==0 || strcasecmp(precedence->fld_value, "bulk")==0) { return 1; /* mailing list identified by the presence of `Precedence: bulk` or `Precedence: list` from RFC 3834 */ } } return 0; } /** * Checks, if there is only one recipient address and if the recipient address * matches the sender address. The function does _not_ check, if this address * matches the address configured for a special account. * * The function searches in the outer MIME header, not in possibly protected * memoryhole headers (if needed, we can change this; the reason for this is * only that mailimf_get_recipients() was already there - and does not respect * memoryhole as used on a lower level before memoryhole is calculated) * * @private @memberof dc_mimeparser_t * @param mimeparser The MIME-parser object. * @return 1=Sender matches recipient * 0=Sender does not match recipient or there are more than one recipients */ int dc_mimeparser_sender_equals_recipient(dc_mimeparser_t* mimeparser) { int sender_equals_recipient = 0; const struct mailimf_field* fld = NULL; const struct mailimf_from* fld_from = NULL; struct mailimf_mailbox* mb = NULL; char* from_addr_norm = NULL; dc_hash_t* recipients = NULL; if (mimeparser==NULL || mimeparser->header_root==NULL) { goto cleanup; } /* get From: and check there is exactly one sender */ if ((fld=mailimf_find_field(mimeparser->header_root, MAILIMF_FIELD_FROM))==NULL || (fld_from=fld->fld_data.fld_from)==NULL || fld_from->frm_mb_list==NULL || fld_from->frm_mb_list->mb_list==NULL || clist_count(fld_from->frm_mb_list->mb_list)!=1) { goto cleanup; } mb = (struct mailimf_mailbox*)clist_content(clist_begin(fld_from->frm_mb_list->mb_list)); if (mb==NULL) { goto cleanup; } from_addr_norm = dc_addr_normalize(mb->mb_addr_spec); /* get To:/Cc: and check there is exactly one recipent */ recipients = mailimf_get_recipients(mimeparser->header_root); if (dc_hash_cnt(recipients)!=1) { goto cleanup; } /* check if From:==To:/Cc: */ if (dc_hash_find_str(recipients, from_addr_norm)) { sender_equals_recipient = 1; } cleanup: dc_hash_clear(recipients); free(recipients); free(from_addr_norm); return sender_equals_recipient; } ``` Filename: dc_move.c ```c #include "dc_context.h" #include "dc_mimeparser.h" #include "dc_job.h" void dc_do_heuristics_moves(dc_context_t* context, const char* folder, uint32_t msg_id) { // for already seen messages, folder may be different from msg->folder dc_msg_t* msg = NULL; sqlite3_stmt* stmt = NULL; if (dc_sqlite3_get_config_int(context->sql, "mvbox_move", DC_MVBOX_MOVE_DEFAULT)==0) { goto cleanup; } if (!dc_is_inbox(context, folder) && !dc_is_sentbox(context, folder)) { goto cleanup; } msg = dc_msg_new_load(context, msg_id); if (dc_msg_is_setupmessage(msg)) { // do not move setup messages; // there may be a non-delta device that wants to handle it goto cleanup; } if (dc_is_mvbox(context, folder)) { dc_update_msg_move_state(context, msg->rfc724_mid, DC_MOVE_STATE_STAY); goto cleanup; } if (msg->is_dc_message /*1=dc message, 2=reply to dc message*/) { dc_job_add(context, DC_JOB_MOVE_MSG, msg->id, NULL, 0); dc_update_msg_move_state(context, msg->rfc724_mid, DC_MOVE_STATE_MOVING); } cleanup: sqlite3_finalize(stmt); dc_msg_unref(msg); } ``` Filename: dc_msg.c ```c #include "dc_context.h" #include "dc_imap.h" #include "dc_smtp.h" #include "dc_job.h" #include "dc_pgp.h" #include "dc_mimefactory.h" #define DC_MSG_MAGIC 0x11561156 /** * Create new message object. Message objects are needed eg. for sending messages using * dc_send_msg(). Moreover, they are returned eg. from dc_get_msg(), * set up with the current state of a message. The message object is not updated; * to achieve this, you have to recreate it. * * @memberof dc_msg_t * @param context The context that should be stored in the message object. * @param viewtype The type to the message object to create, * one of the @ref DC_MSG constants. * @return The created message object. */ dc_msg_t* dc_msg_new(dc_context_t* context, int viewtype) { dc_msg_t* msg = NULL; if ((msg=calloc(1, sizeof(dc_msg_t)))==NULL) { exit(15); /* cannot allocate little memory, unrecoverable error */ } msg->context = context; msg->magic = DC_MSG_MAGIC; msg->type = viewtype; msg->state = DC_STATE_UNDEFINED; msg->param = dc_param_new(); return msg; } dc_msg_t* dc_msg_new_untyped(dc_context_t* context) { return dc_msg_new(context, 0); } dc_msg_t* dc_msg_new_load(dc_context_t* context, uint32_t msg_id) { dc_msg_t* msg = dc_msg_new_untyped(context); dc_msg_load_from_db(msg, context, msg_id); return msg; } /** * Free a message object. Message objects are created eg. by dc_get_msg(). * * @memberof dc_msg_t * @param msg The message object to free. * If NULL is given, nothing is done. * @return None. */ void dc_msg_unref(dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return; } dc_msg_empty(msg); dc_param_unref(msg->param); msg->magic = 0; free(msg); } /** * Empty a message object. * * @private @memberof dc_msg_t * @param msg The message object to empty. * @return None. */ void dc_msg_empty(dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return; } free(msg->text); msg->text = NULL; free(msg->rfc724_mid); msg->rfc724_mid = NULL; free(msg->in_reply_to); msg->in_reply_to = NULL; free(msg->server_folder); msg->server_folder = NULL; dc_param_set_packed(msg->param, NULL); msg->hidden = 0; } /** * Get the ID of the message. * * @memberof dc_msg_t * @param msg The message object. * @return The ID of the message. * 0 if the given message object is invalid. */ uint32_t dc_msg_get_id(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return msg->id; } /** * Get the ID of contact who wrote the message. * * If the ID is equal to DC_CONTACT_ID_SELF (1), the message is an outgoing * message that is typically shown on the right side of the chat view. * * Otherwise, the message is an incoming message; to get details about the sender, * pass the returned ID to dc_get_contact(). * * @memberof dc_msg_t * @param msg The message object. * @return The ID of the contact who wrote the message, DC_CONTACT_ID_SELF (1) * if this is an outgoing message, 0 on errors. */ uint32_t dc_msg_get_from_id(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return msg->from_id; } /** * Get the ID of chat the message belongs to. * To get details about the chat, pass the returned ID to dc_get_chat(). * If a message is still in the deaddrop, the ID DC_CHAT_ID_DEADDROP is returned * although internally another ID is used. * * @memberof dc_msg_t * @param msg The message object. * @return The ID of the chat the message belongs to, 0 on errors. */ uint32_t dc_msg_get_chat_id(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return msg->chat_blocked? DC_CHAT_ID_DEADDROP : msg->chat_id; } /** * Get the type of the message. * * @memberof dc_msg_t * @param msg The message object. * @return One of the @ref DC_MSG constants. * 0 if the given message object is invalid. */ int dc_msg_get_viewtype(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return msg->type; } /** * Get the state of a message. * * Incoming message states: * - DC_STATE_IN_FRESH (10) - Incoming _fresh_ message. Fresh messages are not noticed nor seen and are typically shown in notifications. Use dc_get_fresh_msgs() to get all fresh messages. * - DC_STATE_IN_NOTICED (13) - Incoming _noticed_ message. Eg. chat opened but message not yet read - noticed messages are not counted as unread but did not marked as read nor resulted in MDNs. Use dc_marknoticed_chat() or dc_marknoticed_contact() to mark messages as being noticed. * - DC_STATE_IN_SEEN (16) - Incoming message, really _seen_ by the user. Marked as read on IMAP and MDN may be send. Use dc_markseen_msgs() to mark messages as being seen. * * Outgoing message states: * - DC_STATE_OUT_PREPARING (18) - For files which need time to be prepared before they can be sent, * the message enters this state before DC_STATE_OUT_PENDING. * - DC_STATE_OUT_DRAFT (19) - Message saved as draft using dc_set_draft() * - DC_STATE_OUT_PENDING (20) - The user has send the "send" button but the * message is not yet sent and is pending in some way. Maybe we're offline (no checkmark). * - DC_STATE_OUT_FAILED (24) - _Unrecoverable_ error (_recoverable_ errors result in pending messages), you'll receive the event #DC_EVENT_MSG_FAILED. * - DC_STATE_OUT_DELIVERED (26) - Outgoing message successfully delivered to server (one checkmark). Note, that already delivered messages may get into the state DC_STATE_OUT_FAILED if we get such a hint from the server. * If a sent message changes to this state, you'll receive the event #DC_EVENT_MSG_DELIVERED. * - DC_STATE_OUT_MDN_RCVD (28) - Outgoing message read by the recipient (two checkmarks; this requires goodwill on the receiver's side) * If a sent message changes to this state, you'll receive the event #DC_EVENT_MSG_READ. * * If you just want to check if a message is sent or not, please use dc_msg_is_sent() which regards all states accordingly. * * The state of just created message objects is DC_STATE_UNDEFINED (0). * The state is always set by the core-library, users of the library cannot set the state directly, but it is changed implicitly eg. * when calling dc_marknoticed_chat() or dc_markseen_msgs(). * * @memberof dc_msg_t * @param msg The message object. * @return The state of the message. */ int dc_msg_get_state(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return DC_STATE_UNDEFINED; } return msg->state; } /** * Get message sending time. * The sending time is returned as a unix timestamp in seconds. * * Note that the message lists returned eg. by dc_get_chat_msgs() * are not sorted by the _sending_ time but by the _receiving_ time. * This ensures newly received messages always pop up at the end of the list, * however, for delayed messages, the correct sending time will be displayed. * * To display detailed information about the times to the user, * the UI can use dc_get_msg_info(). * * @memberof dc_msg_t * @param msg The message object. * @return The time of the message. */ time_t dc_msg_get_timestamp(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return msg->timestamp_sent? msg->timestamp_sent : msg->timestamp_sort; } /** * Get message receive time. * The receive time is returned as a unix timestamp in seconds. * * To get the sending time, use dc_msg_get_timestamp(). * * @memberof dc_msg_t * @param msg The message object. * @return Receiving time of the message. * For outgoing messages, 0 is returned. */ time_t dc_msg_get_received_timestamp(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return msg->timestamp_rcvd; } /** * Get message time used for sorting. * This function returns the timestamp that is used for sorting the message * into lists as returned eg. by dc_get_chat_msgs(). * This may be the reveived time, the sending time or another time. * * To get the receiving time, use dc_msg_get_received_timestamp(). * To get the sending time, use dc_msg_get_timestamp(). * * @memberof dc_msg_t * @param msg The message object. * @return Time used for ordering. */ time_t dc_msg_get_sort_timestamp(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return msg->timestamp_sort; } /** * Check if a message has a deviating timestamp. * A message has a deviating timestamp * when it is sent on another day as received/sorted by. * * When the UI displays normally only the time beside the message and the full day as headlines, * the UI should display the full date directly beside the message if the timestamp is deviating. * * @memberof dc_msg_t * @param msg The message object. * @return 1=Timestamp is deviating, the UI should display the full date beside the message. * 0=Timestamp is not deviating and belongs to the same date as the date headers, * displaying the time only is sufficient in this case. */ int dc_msg_has_deviating_timestamp(const dc_msg_t* msg) { long cnv_to_local = dc_gm2local_offset(); time_t sort_timestamp = dc_msg_get_sort_timestamp(msg) + cnv_to_local; time_t send_timestamp = dc_msg_get_timestamp(msg) + cnv_to_local; return (sort_timestamp/DC_SECONDS_PER_DAY != send_timestamp/DC_SECONDS_PER_DAY); } /** * Check if a message has a location bound to it. * These messages are also returned by dc_get_locations() * and the UI may decide to display a special icon beside such messages, * * @memberof dc_msg_t * @param msg The message object. * @return 1=Message has location bound to it, 0=No location bound to message. */ int dc_msg_has_location(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return (msg->location_id!=0); } /** * Get the text of the message. * If there is no text associated with the message, an empty string is returned. * NULL is never returned. * * The returned text is plain text, HTML is stripped. * The returned text is truncated to a max. length of currently about 30000 characters, * it does not make sense to show more text in the message list and typical controls * will have problems with showing much more text. * This max. length is to avoid passing _lots_ of data to the frontend which may * result eg. from decoding errors (assume some bytes missing in a mime structure, forcing * an attachment to be plain text). * * To get information about the message and more/raw text, use dc_get_msg_info(). * * @memberof dc_msg_t * @param msg The message object. * @return Message text. The result must be free()'d. Never returns NULL. */ char* dc_msg_get_text(const dc_msg_t* msg) { char* ret = NULL; if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return dc_strdup(NULL); } ret = dc_strdup(msg->text); dc_truncate_str(ret, DC_MAX_GET_TEXT_LEN); /* we do not do this on load: (1) for speed reasons (2) we may decide to process the full text on other places */ return ret; } /** * Find out full path, file name and extension of the file associated with a * message. * * Typically files are associated with images, videos, audios, documents. * Plain text messages do not have a file. * * @memberof dc_msg_t * @param msg The message object. * @return Full path, file name and extension of the file associated with the * message. If there is no file associated with the message, an emtpy * string is returned. NULL is never returned and the returned value must be free()'d. */ char* dc_msg_get_file(const dc_msg_t* msg) { char* file_rel = NULL; char* file_abs = NULL; if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { goto cleanup; } if ((file_rel = dc_param_get(msg->param, DC_PARAM_FILE, NULL))!=NULL) { file_abs = dc_get_abs_path(msg->context, file_rel); } cleanup: free(file_rel); return file_abs? file_abs : dc_strdup(NULL); } /** * Get base file name without path. The base file name includes the extension; the path * is not returned. To get the full path, use dc_msg_get_file(). * * @memberof dc_msg_t * @param msg The message object. * @return Base file name plus extension without part. If there is no file * associated with the message, an empty string is returned. The returned * value must be free()'d. */ char* dc_msg_get_filename(const dc_msg_t* msg) { char* ret = NULL; char* pathNfilename = NULL; if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { goto cleanup; } pathNfilename = dc_param_get(msg->param, DC_PARAM_FILE, NULL); if (pathNfilename==NULL) { goto cleanup; } ret = dc_get_filename(pathNfilename); cleanup: free(pathNfilename); return ret? ret : dc_strdup(NULL); } /** * Get mime type of the file. If there is not file, an empty string is returned. * If there is no associated mime type with the file, the function guesses on; if * in doubt, `application/octet-stream` is returned. NULL is never returned. * * @memberof dc_msg_t * @param msg The message object. * @return String containing the mime type. Must be free()'d after usage. NULL is never returned. */ char* dc_msg_get_filemime(const dc_msg_t* msg) { char* ret = NULL; char* file = NULL; if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { goto cleanup; } ret = dc_param_get(msg->param, DC_PARAM_MIMETYPE, NULL); if (ret==NULL) { file = dc_param_get(msg->param, DC_PARAM_FILE, NULL); if (file==NULL) { goto cleanup; } dc_msg_guess_msgtype_from_suffix(file, NULL, &ret); if (ret==NULL) { ret = dc_strdup("application/octet-stream"); } } cleanup: free(file); return ret? ret : dc_strdup(NULL); } /** * Get the size of the file. Returns the size of the file associated with a * message, if applicable. * * Typically, this is used to show the size of document messages, eg. a PDF. * * @memberof dc_msg_t * @param msg The message object. * @return File size in bytes, 0 if not applicable or on errors. */ uint64_t dc_msg_get_filebytes(const dc_msg_t* msg) { uint64_t ret = 0; char* file = NULL; if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { goto cleanup; } file = dc_param_get(msg->param, DC_PARAM_FILE, NULL); if (file==NULL) { goto cleanup; } ret = dc_get_filebytes(msg->context, file); cleanup: free(file); return ret; } /** * Get width of image or video. The width is returned in pixels. * If the width is unknown or if the associated file is no image or video file, * 0 is returned. * * Often the aspect ratio is the more interesting thing. You can calculate * this using dc_msg_get_width() / dc_msg_get_height(). * * See also dc_msg_get_duration(). * * @memberof dc_msg_t * @param msg The message object. * @return Width in pixels, if applicable. 0 otherwise or if unknown. */ int dc_msg_get_width(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return dc_param_get_int(msg->param, DC_PARAM_WIDTH, 0); } /** * Get height of image or video. The height is returned in pixels. * If the height is unknown or if the associated file is no image or video file, * 0 is returned. * * Often the ascpect ratio is the more interesting thing. You can calculate * this using dc_msg_get_width() / dc_msg_get_height(). * * See also dc_msg_get_duration(). * * @memberof dc_msg_t * @param msg The message object. * @return Height in pixels, if applicable. 0 otherwise or if unknown. */ int dc_msg_get_height(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return dc_param_get_int(msg->param, DC_PARAM_HEIGHT, 0); } /** * Get the duration of audio or video. The duration is returned in milliseconds (ms). * If the duration is unknown or if the associated file is no audio or video file, * 0 is returned. * * See also dc_msg_get_width() and dc_msg_get_height(). * * @memberof dc_msg_t * @param msg The message object. * @return Duration in milliseconds, if applicable. 0 otherwise or if unknown. */ int dc_msg_get_duration(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return dc_param_get_int(msg->param, DC_PARAM_DURATION, 0); } /** * Check if a padlock should be shown beside the message. * * @memberof dc_msg_t * @param msg The message object. * @return 1=padlock should be shown beside message, 0=do not show a padlock beside the message. */ int dc_msg_get_showpadlock(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC || msg->context==NULL) { return 0; } if (dc_param_get_int(msg->param, DC_PARAM_GUARANTEE_E2EE, 0)!=0) { return 1; } return 0; } /** * Get a summary for a message. * * The summary is returned by a dc_lot_t object with the following fields: * * - dc_lot_t::text1: contains the username or the string "Me". * The string may be colored by having a look at text1_meaning. * If the name should not be displayed, the element is NULL. * - dc_lot_t::text1_meaning: one of DC_TEXT1_USERNAME or DC_TEXT1_SELF. * Typically used to show dc_lot_t::text1 with different colors. 0 if not applicable. * - dc_lot_t::text2: contains an excerpt of the message text. * - dc_lot_t::timestamp: the timestamp of the message. * - dc_lot_t::state: The state of the message as one of the DC_STATE_* constants (see #dc_msg_get_state()). * * Typically used to display a search result. See also dc_chatlist_get_summary() to display a list of chats. * * @memberof dc_msg_t * @param msg The message object. * @param chat To speed up things, pass an already available chat object here. * If the chat object is not yet available, it is faster to pass NULL. * @return The summary as an dc_lot_t object. Must be freed using dc_lot_unref(). NULL is never returned. */ dc_lot_t* dc_msg_get_summary(const dc_msg_t* msg, const dc_chat_t* chat) { dc_lot_t* ret = dc_lot_new(); dc_contact_t* contact = NULL; dc_chat_t* chat_to_delete = NULL; if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { goto cleanup; } if (chat==NULL) { if ((chat_to_delete=dc_get_chat(msg->context, msg->chat_id))==NULL) { goto cleanup; } chat = chat_to_delete; } if (msg->from_id!=DC_CONTACT_ID_SELF && DC_CHAT_TYPE_IS_MULTI(chat->type)) { contact = dc_get_contact(chat->context, msg->from_id); } dc_lot_fill(ret, msg, chat, contact, msg->context); cleanup: dc_contact_unref(contact); dc_chat_unref(chat_to_delete); return ret; } /** * Get a message summary as a single line of text. Typically used for * notifications. * * @memberof dc_msg_t * @param msg The message object. * @param approx_characters Rough length of the expected string. * @return A summary for the given messages. The returned string must be free()'d. * Returns an empty string on errors, never returns NULL. */ char* dc_msg_get_summarytext(const dc_msg_t* msg, int approx_characters) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return dc_strdup(NULL); } return dc_msg_get_summarytext_by_raw(msg->type, msg->text, msg->param, approx_characters, msg->context); } /** * Check if a message was sent successfully. * * Currently, "sent" messages are messages that are in the state "delivered" or "mdn received", * see dc_msg_get_state(). * * @memberof dc_msg_t * @param msg The message object. * @return 1=message sent successfully, 0=message not yet sent or message is an incoming message. */ int dc_msg_is_sent(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return (msg->state >= DC_STATE_OUT_DELIVERED)? 1 : 0; } /** * Check if a message is starred. Starred messages are "favorites" marked by the user * with a "star" or something like that. Starred messages can typically be shown * easily and are not deleted automatically. * * To star one or more messages, use dc_star_msgs(), to get a list of starred messages, * use dc_get_chat_msgs() using DC_CHAT_ID_STARRED as the chat_id. * * @memberof dc_msg_t * @param msg The message object. * @return 1=message is starred, 0=message not starred. */ int dc_msg_is_starred(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return msg->starred? 1 : 0; } /** * Check if the message is a forwarded message. * * Forwarded messages may not be created by the contact given as "from". * * Typically, the UI shows a little text for a symbol above forwarded messages. * * For privacy reasons, we do not provide the name or the email address of the * original author (in a typical GUI, you select the messages text and click on * "forwared"; you won't expect other data to be send to the new recipient, * esp. as the new recipient may not be in any relationship to the original author) * * @memberof dc_msg_t * @param msg The message object. * @return 1=message is a forwarded message, 0=message not forwarded. */ int dc_msg_is_forwarded(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } return dc_param_get_int(msg->param, DC_PARAM_FORWARDED, 0)? 1 : 0; } /** * Check if the message is an informational message, created by the * device or by another users. Such messages are not "typed" by the user but * created due to other actions, eg. dc_set_chat_name(), dc_set_chat_profile_image() * or dc_add_contact_to_chat(). * * These messages are typically shown in the center of the chat view, * dc_msg_get_text() returns a descriptive text about what is going on. * * There is no need to perform any action when seeing such a message - this is already done by the core. * Typically, these messages are displayed in the center of the chat. * * @memberof dc_msg_t * @param msg The message object. * @return 1=message is a system command, 0=normal message */ int dc_msg_is_info(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return 0; } int cmd = dc_param_get_int(msg->param, DC_PARAM_CMD, 0); if (msg->from_id==DC_CONTACT_ID_DEVICE || msg->to_id==DC_CONTACT_ID_DEVICE || (cmd && cmd!=DC_CMD_AUTOCRYPT_SETUP_MESSAGE)) { return 1; } return 0; } /** * Check if the message is an Autocrypt Setup Message. * * Setup messages should be shown in an unique way eg. using a different text color. * On a click or another action, the user should be prompted for the setup code * which is forwarded to dc_continue_key_transfer() then. * * Setup message are typically generated by dc_initiate_key_transfer() on another device. * * @memberof dc_msg_t * @param msg The message object. * @return 1=message is a setup message, 0=no setup message. * For setup messages, dc_msg_get_viewtype() returns DC_MSG_FILE. */ int dc_msg_is_setupmessage(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC || msg->type!=DC_MSG_FILE) { return 0; } return dc_param_get_int(msg->param, DC_PARAM_CMD, 0)==DC_CMD_AUTOCRYPT_SETUP_MESSAGE? 1 : 0; } /** * Get the first characters of the setup code. * * Typically, this is used to pre-fill the first entry field of the setup code. * If the user has several setup messages, he can be sure typing in the correct digits. * * To check, if a message is a setup message, use dc_msg_is_setupmessage(). * To decrypt a secret key from a setup message, use dc_continue_key_transfer(). * * @memberof dc_msg_t * @param msg The message object. * @return Typically, the first two digits of the setup code or an empty string if unknown. * NULL is never returned. Must be free()'d when done. */ char* dc_msg_get_setupcodebegin(const dc_msg_t* msg) { char* filename = NULL; char* buf = NULL; size_t buf_bytes = 0; const char* buf_headerline = NULL; // just a pointer inside buf, MUST NOT be free()'d const char* buf_setupcodebegin = NULL; // just a pointer inside buf, MUST NOT be free()'d char* ret = NULL; if (!dc_msg_is_setupmessage(msg)) { goto cleanup; } if ((filename=dc_msg_get_file(msg))==NULL || filename[0]==0) { goto cleanup; } if (!dc_read_file(msg->context, filename, (void**)&buf, &buf_bytes) || buf==NULL || buf_bytes <= 0) { goto cleanup; } if (!dc_split_armored_data(buf, &buf_headerline, &buf_setupcodebegin, NULL, NULL) || strcmp(buf_headerline, "-----BEGIN PGP MESSAGE-----")!=0 || buf_setupcodebegin==NULL) { goto cleanup; } ret = dc_strdup(buf_setupcodebegin); /* we need to make a copy as buf_setupcodebegin just points inside buf (which will be free()'d on cleanup) */ cleanup: free(filename); free(buf); return ret? ret : dc_strdup(NULL); } #define DC_MSG_FIELDS " m.id,rfc724_mid,m.mime_in_reply_to,m.server_folder,m.server_uid,m.move_state,m.chat_id, " \ " m.from_id,m.to_id,m.timestamp,m.timestamp_sent,m.timestamp_rcvd, m.type,m.state,m.msgrmsg,m.txt, " \ " m.param,m.starred,m.hidden,m.location_id, c.blocked " static int dc_msg_set_from_stmt(dc_msg_t* msg, sqlite3_stmt* row, int row_offset) /* field order must be DC_MSG_FIELDS */ { dc_msg_empty(msg); msg->id = (uint32_t)sqlite3_column_int (row, row_offset++); msg->rfc724_mid = dc_strdup((char*)sqlite3_column_text (row, row_offset++)); msg->in_reply_to = dc_strdup((char*)sqlite3_column_text (row, row_offset++)); msg->server_folder= dc_strdup((char*)sqlite3_column_text (row, row_offset++)); msg->server_uid = (uint32_t)sqlite3_column_int (row, row_offset++); msg->move_state = (dc_move_state_t)sqlite3_column_int (row, row_offset++); msg->chat_id = (uint32_t)sqlite3_column_int (row, row_offset++); msg->from_id = (uint32_t)sqlite3_column_int (row, row_offset++); msg->to_id = (uint32_t)sqlite3_column_int (row, row_offset++); msg->timestamp_sort = (time_t)sqlite3_column_int64(row, row_offset++); msg->timestamp_sent = (time_t)sqlite3_column_int64(row, row_offset++); msg->timestamp_rcvd = (time_t)sqlite3_column_int64(row, row_offset++); msg->type = sqlite3_column_int (row, row_offset++); msg->state = sqlite3_column_int (row, row_offset++); msg->is_dc_message= sqlite3_column_int (row, row_offset++); msg->text = dc_strdup((char*)sqlite3_column_text (row, row_offset++)); dc_param_set_packed( msg->param, (char*)sqlite3_column_text (row, row_offset++)); msg->starred = sqlite3_column_int (row, row_offset++); msg->hidden = sqlite3_column_int (row, row_offset++); msg->location_id = sqlite3_column_int (row, row_offset++); msg->chat_blocked = sqlite3_column_int (row, row_offset++); if (msg->chat_blocked==2) { dc_truncate_n_unwrap_str(msg->text, 256 /* 256 characters is about a half screen on a 5" smartphone display */, 0/*unwrap*/); } return 1; } /** * Load a message from the database to the message object. * * @private @memberof dc_msg_t */ int dc_msg_load_from_db(dc_msg_t* msg, dc_context_t* context, uint32_t id) { int success = 0; sqlite3_stmt* stmt = NULL; if (msg==NULL || msg->magic!=DC_MSG_MAGIC || context==NULL || context->sql==NULL) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT " DC_MSG_FIELDS " FROM msgs m LEFT JOIN chats c ON c.id=m.chat_id" " WHERE m.id=?;"); sqlite3_bind_int(stmt, 1, id); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } if (!dc_msg_set_from_stmt(msg, stmt, 0)) { /* also calls dc_msg_empty() */ goto cleanup; } msg->context = context; success = 1; cleanup: sqlite3_finalize(stmt); return success; } /** * Guess message type from suffix. * * @private @memberof dc_msg_t * @param pathNfilename Path and filename of the file to guess the type for. * @param[out] ret_msgtype Guessed message type is copied here as one of the DC_MSG_* constants. * May be NULL if you're not interested in this value. * @param[out] ret_mime The pointer to a string buffer is set to the guessed MIME-type. May be NULL. Must be free()'d by the caller. * @return None. But there are output parameters. */ void dc_msg_guess_msgtype_from_suffix(const char* pathNfilename, int* ret_msgtype, char** ret_mime) { char* suffix = NULL; int dummy_msgtype = 0; char* dummy_buf = NULL; if (pathNfilename==NULL) { goto cleanup; } if (ret_msgtype==NULL) { ret_msgtype = &dummy_msgtype; } if (ret_mime==NULL) { ret_mime = &dummy_buf; } *ret_msgtype = 0; *ret_mime = NULL; suffix = dc_get_filesuffix_lc(pathNfilename); if (suffix==NULL) { goto cleanup; } if (strcmp(suffix, "mp3")==0) { *ret_msgtype = DC_MSG_AUDIO; *ret_mime = dc_strdup("audio/mpeg"); } else if (strcmp(suffix, "aac")==0) { *ret_msgtype = DC_MSG_AUDIO; *ret_mime = dc_strdup("audio/aac"); } else if (strcmp(suffix, "mp4")==0) { *ret_msgtype = DC_MSG_VIDEO; *ret_mime = dc_strdup("video/mp4"); } else if (strcmp(suffix, "jpg")==0 || strcmp(suffix, "jpeg")==0) { *ret_msgtype = DC_MSG_IMAGE; *ret_mime = dc_strdup("image/jpeg"); } else if (strcmp(suffix, "png")==0) { *ret_msgtype = DC_MSG_IMAGE; *ret_mime = dc_strdup("image/png"); } else if (strcmp(suffix, "webp")==0) { *ret_msgtype = DC_MSG_IMAGE; *ret_mime = dc_strdup("image/webp"); } else if (strcmp(suffix, "gif")==0) { *ret_msgtype = DC_MSG_GIF; *ret_mime = dc_strdup("image/gif"); } else if (strcmp(suffix, "vcf")==0 || strcmp(suffix, "vcard")==0) { *ret_msgtype = DC_MSG_FILE; *ret_mime = dc_strdup("text/vcard"); } cleanup: free(suffix); free(dummy_buf); } char* dc_msg_get_summarytext_by_raw(int type, const char* text, dc_param_t* param, int approx_characters, dc_context_t* context) { /* get a summary text, result must be free()'d, never returns NULL. */ char* ret = NULL; char* prefix = NULL; char* pathNfilename = NULL; char* label = NULL; char* value = NULL; int append_text = 1; switch (type) { case DC_MSG_IMAGE: prefix = dc_stock_str(context, DC_STR_IMAGE); break; case DC_MSG_GIF: prefix = dc_stock_str(context, DC_STR_GIF); break; case DC_MSG_VIDEO: prefix = dc_stock_str(context, DC_STR_VIDEO); break; case DC_MSG_VOICE: prefix = dc_stock_str(context, DC_STR_VOICEMESSAGE); break; case DC_MSG_AUDIO: case DC_MSG_FILE: if (dc_param_get_int(param, DC_PARAM_CMD, 0)==DC_CMD_AUTOCRYPT_SETUP_MESSAGE) { prefix = dc_stock_str(context, DC_STR_AC_SETUP_MSG_SUBJECT); append_text = 0; } else { pathNfilename = dc_param_get(param, DC_PARAM_FILE, "ErrFilename"); value = dc_get_filename(pathNfilename); label = dc_stock_str(context, type==DC_MSG_AUDIO? DC_STR_AUDIO : DC_STR_FILE); prefix = dc_mprintf("%s " DC_NDASH " %s", label, value); } break; default: if (dc_param_get_int(param, DC_PARAM_CMD, 0)==DC_CMD_LOCATION_ONLY) { prefix = dc_stock_str(context, DC_STR_LOCATION); append_text = 0; } break; } if (append_text && prefix && text && text[0]) { ret = dc_mprintf("%s " DC_NDASH " %s", prefix, text); dc_truncate_n_unwrap_str(ret, approx_characters, 1/*unwrap*/); } else if (append_text && text && text[0]) { ret = dc_strdup(text); dc_truncate_n_unwrap_str(ret, approx_characters, 1/*unwrap*/); } else { ret = prefix; prefix = NULL; } /* cleanup */ free(prefix); free(pathNfilename); free(label); free(value); if (ret==NULL) { ret = dc_strdup(NULL); } return ret; } /** * Check if a message is still in creation. A message is in creation between * the calls to dc_prepare_msg() and dc_send_msg(). * * Typically, this is used for videos that are recoded by the UI before * they can be sent. * * @memberof dc_msg_t * @param msg The message object * @return 1=message is still in creation (dc_send_msg() was not called yet), * 0=message no longer in creation */ int dc_msg_is_increation(const dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC || msg->context==NULL) { return 0; } return DC_MSG_NEEDS_ATTACHMENT(msg->type) && msg->state==DC_STATE_OUT_PREPARING; } void dc_msg_save_param_to_disk(dc_msg_t* msg) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC || msg->context==NULL || msg->context->sql==NULL) { return; } sqlite3_stmt* stmt = dc_sqlite3_prepare(msg->context->sql, "UPDATE msgs SET param=? WHERE id=?;"); sqlite3_bind_text(stmt, 1, msg->param->packed, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 2, msg->id); sqlite3_step(stmt); sqlite3_finalize(stmt); } /** * Set the text of a message object. * This does not alter any information in the database; this may be done by dc_send_msg() later. * * @memberof dc_msg_t * @param msg The message object. * @param text Message text. * @return None. */ void dc_msg_set_text(dc_msg_t* msg, const char* text) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return; } free(msg->text); msg->text = dc_strdup(text); } /** * Set the file associated with a message object. * This does not alter any information in the database * nor copy or move the file or checks if the file exist. * All this can be done with dc_send_msg() later. * * @memberof dc_msg_t * @param msg The message object. * @param file If the message object is used in dc_send_msg() later, * this must be the full path of the image file to send. * @param filemime Mime type of the file. NULL if you don't know or don't care. * @return None. */ void dc_msg_set_file(dc_msg_t* msg, const char* file, const char* filemime) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return; } dc_param_set(msg->param, DC_PARAM_FILE, file); dc_param_set(msg->param, DC_PARAM_MIMETYPE, filemime); } /** * Set the dimensions associated with message object. * Typically this is the width and the height of an image or video associated using dc_msg_set_file(). * This does not alter any information in the database; this may be done by dc_send_msg() later. * * @memberof dc_msg_t * @param msg The message object. * @param width Width in pixels, if known. 0 if you don't know or don't care. * @param height Height in pixels, if known. 0 if you don't know or don't care. * @return None. */ void dc_msg_set_dimension(dc_msg_t* msg, int width, int height) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return; } dc_param_set_int(msg->param, DC_PARAM_WIDTH, width); dc_param_set_int(msg->param, DC_PARAM_HEIGHT, height); } /** * Set the duration associated with message object. * Typically this is the duration of an audio or video associated using dc_msg_set_file(). * This does not alter any information in the database; this may be done by dc_send_msg() later. * * @memberof dc_msg_t * @param msg The message object. * @param duration Length in milliseconds. 0 if you don't know or don't care. * @return None. */ void dc_msg_set_duration(dc_msg_t* msg, int duration) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { return; } dc_param_set_int(msg->param, DC_PARAM_DURATION, duration); } /** * Set any location that should be bound to the message object. * The function is useful to add a marker to the map * at a position different from the self-location. * You should not call this function * if you want to bind the current self-location to a message; * this is done by dc_set_location() and dc_send_locations_to_chat(). * * Typically results in the event #DC_EVENT_LOCATION_CHANGED with * contact_id set to DC_CONTACT_ID_SELF. * * @memberof dc_msg_t * @param msg The message object. * @param latitude North-south position of the location. * @param longitude East-west position of the location. * @return None. */ void dc_msg_set_location(dc_msg_t* msg, double latitude, double longitude) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC || (latitude==0.0 && longitude==0.0)) { return; } dc_param_set_float(msg->param, DC_PARAM_SET_LATITUDE, latitude); dc_param_set_float(msg->param, DC_PARAM_SET_LONGITUDE, longitude); } /** * Late filing information to a message. * In contrast to the dc_msg_set_*() functions, this function really stores the information in the database. * * Sometimes, the core cannot find out the width, the height or the duration * of an image, an audio or a video. * * If, in these cases, the frontend can provide the information, it can save * them together with the message object for later usage. * * This function should only be used if dc_msg_get_width(), dc_msg_get_height() or dc_msg_get_duration() * do not provide the expected values. * * To get the stored values later, use dc_msg_get_width(), dc_msg_get_height() or dc_msg_get_duration(). * * @memberof dc_msg_t * @param msg The message object. * @param width The new width to store in the message object. 0 if you do not want to change width and height. * @param height The new height to store in the message object. 0 if you do not want to change width and height. * @param duration The new duration to store in the message object. 0 if you do not want to change it. * @return None. */ void dc_msg_latefiling_mediasize(dc_msg_t* msg, int width, int height, int duration) { if (msg==NULL || msg->magic!=DC_MSG_MAGIC) { goto cleanup; } if (width>0 && height>0) { dc_param_set_int(msg->param, DC_PARAM_WIDTH, width); dc_param_set_int(msg->param, DC_PARAM_HEIGHT, height); } if (duration>0) { dc_param_set_int(msg->param, DC_PARAM_DURATION, duration); } dc_msg_save_param_to_disk(msg); cleanup: ; } /******************************************************************************* * Context functions to work with messages ******************************************************************************/ /* * Check if there is a record for the given msg_id * and that the record is not about to be deleted. */ int dc_msg_exists(dc_context_t* context, uint32_t msg_id) { int msg_exists = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg_id<=DC_MSG_ID_LAST_SPECIAL) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT chat_id FROM msgs WHERE id=?;"); sqlite3_bind_int(stmt, 1, msg_id); if (sqlite3_step(stmt)==SQLITE_ROW) { uint32_t chat_id = sqlite3_column_int(stmt, 0); if (chat_id!=DC_CHAT_ID_TRASH) { msg_exists = 1; } } cleanup: sqlite3_finalize(stmt); return msg_exists; } void dc_update_msg_chat_id(dc_context_t* context, uint32_t msg_id, uint32_t chat_id) { sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "UPDATE msgs SET chat_id=? WHERE id=?;"); sqlite3_bind_int(stmt, 1, chat_id); sqlite3_bind_int(stmt, 2, msg_id); sqlite3_step(stmt); sqlite3_finalize(stmt); } void dc_update_msg_state(dc_context_t* context, uint32_t msg_id, int state) { sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "UPDATE msgs SET state=? WHERE id=?;"); sqlite3_bind_int(stmt, 1, state); sqlite3_bind_int(stmt, 2, msg_id); sqlite3_step(stmt); sqlite3_finalize(stmt); } void dc_update_msg_move_state(dc_context_t* context, const char* rfc724_mid, dc_move_state_t state) { // we update the move_state for all messages belonging to a given Message-ID // so that the state stay intact when parts are deleted sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "UPDATE msgs SET move_state=? WHERE rfc724_mid=?;"); sqlite3_bind_int (stmt, 1, state); sqlite3_bind_text(stmt, 2, rfc724_mid, -1, SQLITE_STATIC); sqlite3_step(stmt); sqlite3_finalize(stmt); } /** * Changes the state of PREPARING, PENDING or DELIVERED messages to DC_STATE_OUT_FAILED. * Moreover, the message error text can be updated. * Finally, the given error text is also logged using dc_log_error(). * * @private @memberof dc_context_t */ void dc_set_msg_failed(dc_context_t* context, uint32_t msg_id, const char* error) { dc_msg_t* msg = dc_msg_new_untyped(context); sqlite3_stmt* stmt = NULL; if (!dc_msg_load_from_db(msg, context, msg_id)) { goto cleanup; } if (DC_STATE_OUT_PREPARING==msg->state || DC_STATE_OUT_PENDING ==msg->state || DC_STATE_OUT_DELIVERED==msg->state) { msg->state = DC_STATE_OUT_FAILED; } if (error) { dc_param_set(msg->param, DC_PARAM_ERROR, error); dc_log_error(context, 0, "%s", error); } stmt = dc_sqlite3_prepare(context->sql, "UPDATE msgs SET state=?, param=? WHERE id=?;"); sqlite3_bind_int (stmt, 1, msg->state); sqlite3_bind_text(stmt, 2, msg->param->packed, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 3, msg_id); sqlite3_step(stmt); context->cb(context, DC_EVENT_MSG_FAILED, msg->chat_id, msg_id); cleanup: sqlite3_finalize(stmt); dc_msg_unref(msg); } size_t dc_get_real_msg_cnt(dc_context_t* context) { sqlite3_stmt* stmt = NULL; size_t ret = 0; if (context->sql->cobj==NULL) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) " " FROM msgs m " " LEFT JOIN chats c ON c.id=m.chat_id " " WHERE m.id>" DC_STRINGIFY(DC_MSG_ID_LAST_SPECIAL) " AND m.chat_id>" DC_STRINGIFY(DC_CHAT_ID_LAST_SPECIAL) " AND c.blocked=0;"); if (sqlite3_step(stmt)!=SQLITE_ROW) { dc_sqlite3_log_error(context->sql, "dc_get_real_msg_cnt() failed."); goto cleanup; } ret = sqlite3_column_int(stmt, 0); cleanup: sqlite3_finalize(stmt); return ret; } size_t dc_get_deaddrop_msg_cnt(dc_context_t* context) { sqlite3_stmt* stmt = NULL; size_t ret = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || context->sql->cobj==NULL) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM msgs m LEFT JOIN chats c ON c.id=m.chat_id WHERE c.blocked=2;"); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } ret = sqlite3_column_int(stmt, 0); cleanup: sqlite3_finalize(stmt); return ret; } int dc_rfc724_mid_cnt(dc_context_t* context, const char* rfc724_mid) { /* check the number of messages with the same rfc724_mid */ int ret = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || context->sql->cobj==NULL) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM msgs WHERE rfc724_mid=?;"); sqlite3_bind_text(stmt, 1, rfc724_mid, -1, SQLITE_STATIC); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } ret = sqlite3_column_int(stmt, 0); cleanup: sqlite3_finalize(stmt); return ret; } /** * Check, if the given Message-ID exists in the database. * If not, the caller loads the message typically completely from the server and parses it. * To avoid unnecessary dowonloads and parsing, we should even keep unuseful messages * in the database (we can leave the other fields empty to save space). * * @private @memberof dc_context_t */ uint32_t dc_rfc724_mid_exists(dc_context_t* context, const char* rfc724_mid, char** ret_server_folder, uint32_t* ret_server_uid) { uint32_t ret = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || rfc724_mid==NULL || rfc724_mid[0]==0) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT server_folder, server_uid, id FROM msgs WHERE rfc724_mid=?;"); sqlite3_bind_text(stmt, 1, rfc724_mid, -1, SQLITE_STATIC); if (sqlite3_step(stmt)!=SQLITE_ROW) { if (ret_server_folder) { *ret_server_folder = NULL; } if (ret_server_uid) { *ret_server_uid = 0; } goto cleanup; } if (ret_server_folder) { *ret_server_folder = dc_strdup((char*)sqlite3_column_text(stmt, 0)); } if (ret_server_uid) { *ret_server_uid = sqlite3_column_int(stmt, 1); /* may be 0 */ } ret = sqlite3_column_int(stmt, 2); cleanup: sqlite3_finalize(stmt); return ret; } void dc_update_server_uid(dc_context_t* context, const char* rfc724_mid, const char* server_folder, uint32_t server_uid) { sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "UPDATE msgs SET server_folder=?, server_uid=? WHERE rfc724_mid=?;"); /* we update by "rfc724_mid" instead of "id" as there may be several db-entries refering to the same "rfc724_mid" */ sqlite3_bind_text(stmt, 1, server_folder, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 2, server_uid); sqlite3_bind_text(stmt, 3, rfc724_mid, -1, SQLITE_STATIC); sqlite3_step(stmt); sqlite3_finalize(stmt); } /** * Get a single message object of the type dc_msg_t. * For a list of messages in a chat, see dc_get_chat_msgs() * For a list or chats, see dc_get_chatlist() * * @memberof dc_context_t * @param context The context as created by dc_context_new(). * @param msg_id The message ID for which the message object should be created. * @return A dc_msg_t message object. * On errors, NULL is returned. * When done, the object must be freed using dc_msg_unref(). */ dc_msg_t* dc_get_msg(dc_context_t* context, uint32_t msg_id) { int success = 0; dc_msg_t* obj = dc_msg_new_untyped(context); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (!dc_msg_load_from_db(obj, context, msg_id)) { goto cleanup; } success = 1; cleanup: if (success) { return obj; } else { dc_msg_unref(obj); return NULL; } } /** * Get an informational text for a single message. The text is multiline and may * contain eg. the raw text of the message. * * The max. text returned is typically longer (about 100000 characters) than the * max. text returned by dc_msg_get_text() (about 30000 characters). * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). * @param msg_id The message id for which information should be generated * @return Text string, must be free()'d after usage */ char* dc_get_msg_info(dc_context_t* context, uint32_t msg_id) { sqlite3_stmt* stmt = NULL; dc_msg_t* msg = dc_msg_new_untyped(context); dc_contact_t* contact_from = dc_contact_new(context); char* rawtxt = NULL; char* p = NULL; dc_strbuilder_t ret; dc_strbuilder_init(&ret, 0); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } dc_msg_load_from_db(msg, context, msg_id); dc_contact_load_from_db(contact_from, context->sql, msg->from_id); stmt = dc_sqlite3_prepare(context->sql, "SELECT txt_raw FROM msgs WHERE id=?;"); sqlite3_bind_int(stmt, 1, msg_id); if (sqlite3_step(stmt)!=SQLITE_ROW) { p = dc_mprintf("Cannot load message #%i.", (int)msg_id); dc_strbuilder_cat(&ret, p); free(p); goto cleanup; } rawtxt = dc_strdup((char*)sqlite3_column_text(stmt, 0)); sqlite3_finalize(stmt); stmt = NULL; dc_trim(rawtxt); dc_truncate_str(rawtxt, DC_MAX_GET_INFO_LEN); /* add time */ dc_strbuilder_cat(&ret, "Sent: "); p = dc_timestamp_to_str(dc_msg_get_timestamp(msg)); dc_strbuilder_cat(&ret, p); free(p); p = dc_contact_get_name_n_addr(contact_from); dc_strbuilder_catf(&ret, " by %s", p); free(p); dc_strbuilder_cat(&ret, "\n"); if (msg->from_id!=DC_CONTACT_ID_SELF) { dc_strbuilder_cat(&ret, "Received: "); p = dc_timestamp_to_str(msg->timestamp_rcvd? msg->timestamp_rcvd : msg->timestamp_sort); dc_strbuilder_cat(&ret, p); free(p); dc_strbuilder_cat(&ret, "\n"); } if (msg->from_id==DC_CONTACT_ID_DEVICE || msg->to_id==DC_CONTACT_ID_DEVICE) { goto cleanup; // device-internal message, no further details needed } /* add mdn's time and readers */ stmt = dc_sqlite3_prepare(context->sql, "SELECT contact_id, timestamp_sent FROM msgs_mdns WHERE msg_id=?;"); sqlite3_bind_int (stmt, 1, msg_id); while (sqlite3_step(stmt)==SQLITE_ROW) { dc_strbuilder_cat(&ret, "Read: "); p = dc_timestamp_to_str(sqlite3_column_int64(stmt, 1)); dc_strbuilder_cat(&ret, p); free(p); dc_strbuilder_cat(&ret, " by "); dc_contact_t* contact = dc_contact_new(context); dc_contact_load_from_db(contact, context->sql, sqlite3_column_int64(stmt, 0)); p = dc_contact_get_name_n_addr(contact); dc_strbuilder_cat(&ret, p); free(p); dc_contact_unref(contact); dc_strbuilder_cat(&ret, "\n"); } sqlite3_finalize(stmt); stmt = NULL; /* add state */ p = NULL; switch (msg->state) { case DC_STATE_IN_FRESH: p = dc_strdup("Fresh"); break; case DC_STATE_IN_NOTICED: p = dc_strdup("Noticed"); break; case DC_STATE_IN_SEEN: p = dc_strdup("Seen"); break; case DC_STATE_OUT_DELIVERED: p = dc_strdup("Delivered"); break; case DC_STATE_OUT_FAILED: p = dc_strdup("Failed"); break; case DC_STATE_OUT_MDN_RCVD: p = dc_strdup("Read"); break; case DC_STATE_OUT_PENDING: p = dc_strdup("Pending"); break; case DC_STATE_OUT_PREPARING: p = dc_strdup("Preparing"); break; default: p = dc_mprintf("%i", msg->state); break; } dc_strbuilder_catf(&ret, "State: %s", p); free(p); if (dc_msg_has_location(msg)) { dc_strbuilder_cat(&ret, ", Location sent"); } p = NULL; int e2ee_errors; if ((e2ee_errors=dc_param_get_int(msg->param, DC_PARAM_ERRONEOUS_E2EE, 0))) { if (e2ee_errors&DC_E2EE_NO_VALID_SIGNATURE) { p = dc_strdup("Encrypted, no valid signature"); } } else if (dc_param_get_int(msg->param, DC_PARAM_GUARANTEE_E2EE, 0)) { p = dc_strdup("Encrypted"); } if (p) { dc_strbuilder_catf(&ret, ", %s", p); free(p); } dc_strbuilder_cat(&ret, "\n"); if ((p=dc_param_get(msg->param, DC_PARAM_ERROR, NULL))!=NULL) { dc_strbuilder_catf(&ret, "Error: %s\n", p); free(p); } /* add file info */ if ((p=dc_msg_get_file(msg))!=NULL && p[0]) { dc_strbuilder_catf(&ret, "\nFile: %s, %i bytes\n", p, (int)dc_get_filebytes(context, p)); } free(p); if (msg->type!=DC_MSG_TEXT) { p = NULL; switch (msg->type) { case DC_MSG_AUDIO: p = dc_strdup("Audio"); break; case DC_MSG_FILE: p = dc_strdup("File"); break; case DC_MSG_GIF: p = dc_strdup("GIF"); break; case DC_MSG_IMAGE: p = dc_strdup("Image"); break; case DC_MSG_VIDEO: p = dc_strdup("Video"); break; case DC_MSG_VOICE: p = dc_strdup("Voice"); break; default: p = dc_mprintf("%i", msg->type); break; } dc_strbuilder_catf(&ret, "Type: %s\n", p); free(p); p = dc_msg_get_filemime(msg); dc_strbuilder_catf(&ret, "Mimetype: %s\n", p); free(p); } int w = dc_param_get_int(msg->param, DC_PARAM_WIDTH, 0); int h = dc_param_get_int(msg->param, DC_PARAM_HEIGHT, 0); if (w!=0 || h!=0) { p = dc_mprintf("Dimension: %i x %i\n", w, h); dc_strbuilder_cat(&ret, p); free(p); } int duration = dc_param_get_int(msg->param, DC_PARAM_DURATION, 0); if (duration!=0) { p = dc_mprintf("Duration: %i ms\n", duration); dc_strbuilder_cat(&ret, p); free(p); } /* add rawtext */ if (rawtxt && rawtxt[0]) { dc_strbuilder_cat(&ret, "\n"); dc_strbuilder_cat(&ret, rawtxt); dc_strbuilder_cat(&ret, "\n"); } /* add Message-ID, Server-Folder and Server-UID; the database ID is normally only of interest if you have access to sqlite; if so you can easily get it from the "msgs" table. */ if (msg->rfc724_mid && msg->rfc724_mid[0]) { dc_strbuilder_catf(&ret, "\nMessage-ID: %s", msg->rfc724_mid); } if (msg->server_folder && msg->server_folder[0]) { dc_strbuilder_catf(&ret, "\nLast seen as: %s/%i", msg->server_folder, (int)msg->server_uid); } cleanup: sqlite3_finalize(stmt); dc_msg_unref(msg); dc_contact_unref(contact_from); free(rawtxt); return ret.buf; } /** * Get the raw mime-headers of the given message. * Raw headers are saved for incoming messages * only if `dc_set_config(context, "save_mime_headers", "1")` * was called before. * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). * @param msg_id The message id, must be the id of an incoming message. * @return Raw headers as a multi-line string, must be free()'d after usage. * Returns NULL if there are no headers saved for the given message, * eg. because of save_mime_headers is not set * or the message is not incoming. */ char* dc_get_mime_headers(dc_context_t* context, uint32_t msg_id) { char* eml = NULL; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT mime_headers FROM msgs WHERE id=?;"); sqlite3_bind_int(stmt, 1, msg_id); if (sqlite3_step(stmt)==SQLITE_ROW) { eml = dc_strdup_keep_null((const char*)sqlite3_column_text(stmt, 0)); } cleanup: sqlite3_finalize(stmt); return eml; } /** * Star/unstar messages by setting the last parameter to 0 (unstar) or 1 (star). * Starred messages are collected in a virtual chat that can be shown using * dc_get_chat_msgs() using the chat_id DC_CHAT_ID_STARRED. * * @memberof dc_context_t * @param context The context object as created by dc_context_new() * @param msg_ids An array of uint32_t message IDs defining the messages to star or unstar * @param msg_cnt The number of IDs in msg_ids * @param star 0=unstar the messages in msg_ids, 1=star them * @return None. */ void dc_star_msgs(dc_context_t* context, const uint32_t* msg_ids, int msg_cnt, int star) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg_ids==NULL || msg_cnt<=0 || (star!=0 && star!=1)) { return; } dc_sqlite3_begin_transaction(context->sql); sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "UPDATE msgs SET starred=? WHERE id=?;"); for (int i = 0; i < msg_cnt; i++) { sqlite3_reset(stmt); sqlite3_bind_int(stmt, 1, star); sqlite3_bind_int(stmt, 2, msg_ids[i]); sqlite3_step(stmt); } sqlite3_finalize(stmt); dc_sqlite3_commit(context->sql); } /******************************************************************************* * Delete messages ******************************************************************************/ /** * Low-level function to delete a message from the database. * This does not delete the messages from the server. * * @private @memberof dc_context_t */ void dc_delete_msg_from_db(dc_context_t* context, uint32_t msg_id) { dc_msg_t* msg = dc_msg_new_untyped(context); sqlite3_stmt* stmt = NULL; if (!dc_msg_load_from_db(msg, context, msg_id)) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "DELETE FROM msgs WHERE id=?;"); sqlite3_bind_int(stmt, 1, msg->id); sqlite3_step(stmt); sqlite3_finalize(stmt); stmt = NULL; stmt = dc_sqlite3_prepare(context->sql, "DELETE FROM msgs_mdns WHERE msg_id=?;"); sqlite3_bind_int(stmt, 1, msg->id); sqlite3_step(stmt); sqlite3_finalize(stmt); stmt = NULL; cleanup: sqlite3_finalize(stmt); dc_msg_unref(msg); } /** * Delete messages. The messages are deleted on the current device and * on the IMAP server. * * @memberof dc_context_t * @param context The context object as created by dc_context_new() * @param msg_ids an array of uint32_t containing all message IDs that should be deleted * @param msg_cnt The number of messages IDs in the msg_ids array * @return None. */ void dc_delete_msgs(dc_context_t* context, const uint32_t* msg_ids, int msg_cnt) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg_ids==NULL || msg_cnt<=0) { return; } dc_sqlite3_begin_transaction(context->sql); for (int i = 0; i < msg_cnt; i++) { dc_update_msg_chat_id(context, msg_ids[i], DC_CHAT_ID_TRASH); dc_job_add(context, DC_JOB_DELETE_MSG_ON_IMAP, msg_ids[i], NULL, 0); } dc_sqlite3_commit(context->sql); if (msg_cnt) { context->cb(context, DC_EVENT_MSGS_CHANGED, 0, 0); dc_job_kill_action(context, DC_JOB_HOUSEKEEPING); dc_job_add(context, DC_JOB_HOUSEKEEPING, 0, NULL, DC_HOUSEKEEPING_DELAY_SEC); } } /******************************************************************************* * mark message as seen ******************************************************************************/ /** * Mark a message as _seen_, updates the IMAP state and * sends MDNs. If the message is not in a real chat (eg. a contact request), the * message is only marked as NOTICED and no IMAP/MDNs is done. See also * dc_marknoticed_chat() and dc_marknoticed_contact() * * @memberof dc_context_t * @param context The context object. * @param msg_ids An array of uint32_t containing all the messages IDs that should be marked as seen. * @param msg_cnt The number of message IDs in msg_ids. * @return None. */ void dc_markseen_msgs(dc_context_t* context, const uint32_t* msg_ids, int msg_cnt) { int transaction_pending = 0; int i = 0; int send_event = 0; int curr_state = 0; int curr_blocked = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || msg_ids==NULL || msg_cnt<=0) { goto cleanup; } dc_sqlite3_begin_transaction(context->sql); transaction_pending = 1; stmt = dc_sqlite3_prepare(context->sql, "SELECT m.state, c.blocked " " FROM msgs m " " LEFT JOIN chats c ON c.id=m.chat_id " " WHERE m.id=? AND m.chat_id>" DC_STRINGIFY(DC_CHAT_ID_LAST_SPECIAL)); for (i = 0; i < msg_cnt; i++) { sqlite3_reset(stmt); sqlite3_bind_int(stmt, 1, msg_ids[i]); if (sqlite3_step(stmt)!=SQLITE_ROW) { continue; } curr_state = sqlite3_column_int(stmt, 0); curr_blocked = sqlite3_column_int(stmt, 1); if (curr_blocked==0) { if (curr_state==DC_STATE_IN_FRESH || curr_state==DC_STATE_IN_NOTICED) { dc_update_msg_state(context, msg_ids[i], DC_STATE_IN_SEEN); dc_log_info(context, 0, "Seen message #%i.", msg_ids[i]); dc_job_add(context, DC_JOB_MARKSEEN_MSG_ON_IMAP, msg_ids[i], NULL, 0); send_event = 1; } } else { /* message may be in contact requests, mark as NOTICED, this does not force IMAP updated nor send MDNs */ if (curr_state==DC_STATE_IN_FRESH) { dc_update_msg_state(context, msg_ids[i], DC_STATE_IN_NOTICED); send_event = 1; } } } dc_sqlite3_commit(context->sql); transaction_pending = 0; /* the event is needed eg. to remove the deaddrop from the chatlist */ if (send_event) { context->cb(context, DC_EVENT_MSGS_CHANGED, 0, 0); } cleanup: if (transaction_pending) { dc_sqlite3_rollback(context->sql); } sqlite3_finalize(stmt); } int dc_mdn_from_ext(dc_context_t* context, uint32_t from_id, const char* rfc724_mid, time_t timestamp_sent, uint32_t* ret_chat_id, uint32_t* ret_msg_id) { int read_by_all = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || from_id<=DC_CONTACT_ID_LAST_SPECIAL || rfc724_mid==NULL || ret_chat_id==NULL || ret_msg_id==NULL || *ret_chat_id!=0 || *ret_msg_id!=0) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT m.id, c.id, c.type, m.state FROM msgs m " " LEFT JOIN chats c ON m.chat_id=c.id " " WHERE rfc724_mid=? AND from_id=1 " " ORDER BY m.id;"); /* the ORDER BY makes sure, if one rfc724_mid is splitted into its parts, we always catch the same one. However, we do not send multiparts, we do not request MDNs for multiparts, and should not receive read requests for multiparts. So this is currently more theoretical. */ sqlite3_bind_text(stmt, 1, rfc724_mid, -1, SQLITE_STATIC); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; } *ret_msg_id = sqlite3_column_int(stmt, 0); *ret_chat_id = sqlite3_column_int(stmt, 1); int chat_type = sqlite3_column_int(stmt, 2); int msg_state = sqlite3_column_int(stmt, 3); sqlite3_finalize(stmt); stmt = NULL; if (msg_state!=DC_STATE_OUT_PREPARING && msg_state!=DC_STATE_OUT_PENDING && msg_state!=DC_STATE_OUT_DELIVERED) { goto cleanup; /* eg. already marked as MDNS_RCVD. however, it is importent, that the message ID is set above as this will allow the caller eg. to move the message away */ } // collect receipt senders, we do this also for normal chats as we may want to show the timestamp stmt = dc_sqlite3_prepare(context->sql, "SELECT contact_id FROM msgs_mdns WHERE msg_id=? AND contact_id=?;"); sqlite3_bind_int(stmt, 1, *ret_msg_id); sqlite3_bind_int(stmt, 2, from_id); int mdn_already_in_table = (sqlite3_step(stmt)==SQLITE_ROW)? 1 : 0; sqlite3_finalize(stmt); stmt = NULL; if (!mdn_already_in_table) { stmt = dc_sqlite3_prepare(context->sql, "INSERT INTO msgs_mdns (msg_id, contact_id, timestamp_sent) VALUES (?, ?, ?);"); sqlite3_bind_int (stmt, 1, *ret_msg_id); sqlite3_bind_int (stmt, 2, from_id); sqlite3_bind_int64(stmt, 3, timestamp_sent); sqlite3_step(stmt); sqlite3_finalize(stmt); stmt = NULL; } // Normal chat? that's quite easy. if (chat_type==DC_CHAT_TYPE_SINGLE) { dc_update_msg_state(context, *ret_msg_id, DC_STATE_OUT_MDN_RCVD); read_by_all = 1; goto cleanup; /* send event about new state */ } // Group chat: get the number of receipt senders stmt = dc_sqlite3_prepare(context->sql, "SELECT COUNT(*) FROM msgs_mdns WHERE msg_id=?;"); sqlite3_bind_int(stmt, 1, *ret_msg_id); if (sqlite3_step(stmt)!=SQLITE_ROW) { goto cleanup; /* error */ } int ist_cnt = sqlite3_column_int(stmt, 0); sqlite3_finalize(stmt); stmt = NULL; /* Groupsize: Min. MDNs 1 S n/a 2 SR 1 3 SRR 2 4 SRRR 2 5 SRRRR 3 6 SRRRRR 3 (S=Sender, R=Recipient) */ int soll_cnt = (dc_get_chat_contact_cnt(context, *ret_chat_id)+1/*for rounding, SELF is already included!*/) / 2; if (ist_cnt < soll_cnt) { goto cleanup; /* wait for more receipts */ } /* got enough receipts :-) */ dc_update_msg_state(context, *ret_msg_id, DC_STATE_OUT_MDN_RCVD); read_by_all = 1; cleanup: sqlite3_finalize(stmt); return read_by_all; } ``` Filename: dc_oauth2.c ```c #include "dc_context.h" #include "dc_oauth2.h" #include "dc_jsmn.h" typedef struct oauth2_t { char* client_id; char* get_code; char* init_token; char* refresh_token; char* get_userinfo; } oauth2_t; static oauth2_t* get_info(const char* addr) { oauth2_t* oauth2 = NULL; char* addr_normalized = NULL; const char* domain = NULL; addr_normalized = dc_addr_normalize(addr); domain = strchr(addr_normalized, '@'); if (domain==NULL || domain[0]==0) { goto cleanup; } domain++; if (strcasecmp(domain, "gmail.com")==0 || strcasecmp(domain, "googlemail.com")==0) { // see https://developers.google.com/identity/protocols/OAuth2InstalledApp oauth2 = calloc(1, sizeof(oauth2_t)); oauth2->client_id = "959970109878-4mvtgf6feshskf7695nfln6002mom908.apps.googleusercontent.com"; oauth2->get_code = "https://accounts.google.com/o/oauth2/auth" "?client_id=$CLIENT_ID" "&redirect_uri=$REDIRECT_URI" "&response_type=code" "&scope=https%3A%2F%2Fmail.google.com%2F%20email" "&access_type=offline"; oauth2->init_token = "https://accounts.google.com/o/oauth2/token" "?client_id=$CLIENT_ID" "&redirect_uri=$REDIRECT_URI" "&code=$CODE" "&grant_type=authorization_code"; oauth2->refresh_token = "https://accounts.google.com/o/oauth2/token" "?client_id=$CLIENT_ID" "&redirect_uri=$REDIRECT_URI" "&refresh_token=$REFRESH_TOKEN" "&grant_type=refresh_token"; oauth2->get_userinfo = "https://www.googleapis.com/oauth2/v1/userinfo" "?alt=json" "&access_token=$ACCESS_TOKEN"; } else if (strcasecmp(domain, "yandex.com")==0 || strcasecmp(domain, "yandex.ru")==0 || strcasecmp(domain, "yandex.ua")==0) { // see https://tech.yandex.com/oauth/doc/dg/reference/auto-code-client-docpage/ oauth2 = calloc(1, sizeof(oauth2_t)); oauth2->client_id = "c4d0b6735fc8420a816d7e1303469341"; oauth2->get_code = "https://oauth.yandex.com/authorize" "?client_id=$CLIENT_ID" "&response_type=code" "&scope=mail%3Aimap_full%20mail%3Asmtp" "&force_confirm=true"; oauth2->init_token = "https://oauth.yandex.com/token" "?grant_type=authorization_code" "&code=$CODE" "&client_id=$CLIENT_ID" "&client_secret=58b8c6e94cf44fbe952da8511955dacf"; oauth2->refresh_token = "https://oauth.yandex.com/token" "?grant_type=refresh_token" "&refresh_token=$REFRESH_TOKEN" "&client_id=$CLIENT_ID" "&client_secret=58b8c6e94cf44fbe952da8511955dacf"; } cleanup: free(addr_normalized); return oauth2; } static void replace_in_uri(char** uri, const char* key, const char* value) { if (uri && key && value) { char* value_urlencoded = dc_urlencode(value); dc_str_replace(uri, key, value_urlencoded); free(value_urlencoded); } } static int jsoneq(const char *json, jsmntok_t *tok, const char *s) { // from the jsmn parser example if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start && strncmp(json + tok->start, s, tok->end - tok->start) == 0) { return 0; } return -1; } static char* jsondup(const char *json, jsmntok_t *tok) { if (tok->type == JSMN_STRING || tok->type == JSMN_PRIMITIVE) { return strndup(json+tok->start, tok->end - tok->start); } return strdup(""); } static int is_expired(dc_context_t* context) { time_t expire_timestamp = dc_sqlite3_get_config_int64(context->sql, "oauth2_timestamp_expires", 0); if (expire_timestamp<=0) { return 0; // timestamp does never expire } if (expire_timestamp>time(NULL)) { return 0; // expire timestamp is in the future and not yet expired } return 1; // expired } /** * Get url that can be used to initiate an OAuth2 authorisation. * * If an OAuth2 authorization is possible for a given e-mail-address, * this function returns the URL that should be opened in a browser. * * If the user authorizes access, * the given redirect_uri is called by the provider. * It's up to the UI to handle this call. * * The provider will attach some parameters to the url, * most important the parameter `code` that should be set as the `mail_pw`. * With `server_flags` set to #DC_LP_AUTH_OAUTH2, * dc_configure() can be called as usual afterwards. * * Note: OAuth2 depends on #DC_EVENT_HTTP_POST; * if you have not implemented #DC_EVENT_HTTP_POST in the ui, * OAuth2 **won't work**. * * @memberof dc_context_t * @param context The context object as created by dc_context_new(). * @param addr E-mail address the user has entered. * In case the user selects a different e-mail-address during * authorization, this is corrected in dc_configure() * @param redirect_uri URL that will get `code` that is used as `mail_pw` then. * Not all URLs are allowed here, however, the following should work: * `chat.delta:/PATH`, `http://localhost:PORT/PATH`, * `https://localhost:PORT/PATH`, `urn:ietf:wg:oauth:2.0:oob` * (the latter just displays the code the user can copy+paste then) * @return URL that can be opened in the browser to start OAuth2. * If OAuth2 is not possible for the given e-mail-address, NULL is returned. */ char* dc_get_oauth2_url(dc_context_t* context, const char* addr, const char* redirect_uri) { #define CLIENT_ID "959970109878-4mvtgf6feshskf7695nfln6002mom908.apps.googleusercontent.com" oauth2_t* oauth2 = NULL; char* oauth2_url = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || redirect_uri==NULL || redirect_uri[0]==0) { goto cleanup; } oauth2 = get_info(addr); if (oauth2==NULL) { goto cleanup; } dc_sqlite3_set_config(context->sql, "oauth2_pending_redirect_uri", redirect_uri); oauth2_url = dc_strdup(oauth2->get_code); replace_in_uri(&oauth2_url, "$CLIENT_ID", oauth2->client_id); replace_in_uri(&oauth2_url, "$REDIRECT_URI", redirect_uri); cleanup: free(oauth2); return oauth2_url; } char* dc_get_oauth2_access_token(dc_context_t* context, const char* addr, const char* code, int flags) { oauth2_t* oauth2 = NULL; char* access_token = NULL; char* refresh_token = NULL; char* refresh_token_for = NULL; char* redirect_uri = NULL; int update_redirect_uri_on_success = 0; char* token_url = NULL; time_t expires_in = 0; char* error = NULL; char* error_description = NULL; char* json = NULL; jsmn_parser parser; jsmntok_t tok[128]; // we do not expect nor read more tokens int tok_cnt = 0; int locked = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || code==NULL || code[0]==0) { dc_log_warning(context, 0, "Internal OAuth2 error"); goto cleanup; } if ((oauth2=get_info(addr))==NULL) { dc_log_warning(context, 0, "Internal OAuth2 error: 2"); goto cleanup; } pthread_mutex_lock(&context->oauth2_critical); locked = 1; // read generated token if ( !(flags&DC_REGENERATE) && !is_expired(context) ) { access_token = dc_sqlite3_get_config(context->sql, "oauth2_access_token", NULL); if (access_token!=NULL) { goto cleanup; // success } } // generate new token: build & call auth url refresh_token = dc_sqlite3_get_config(context->sql, "oauth2_refresh_token", NULL); refresh_token_for = dc_sqlite3_get_config(context->sql, "oauth2_refresh_token_for", "unset"); if (refresh_token==NULL || strcmp(refresh_token_for, code)!=0) { dc_log_info(context, 0, "Generate OAuth2 refresh_token and access_token..."); redirect_uri = dc_sqlite3_get_config(context->sql, "oauth2_pending_redirect_uri", "unset"); update_redirect_uri_on_success = 1; token_url = dc_strdup(oauth2->init_token); } else { dc_log_info(context, 0, "Regenerate OAuth2 access_token by refresh_token..."); redirect_uri = dc_sqlite3_get_config(context->sql, "oauth2_redirect_uri", "unset"); token_url = dc_strdup(oauth2->refresh_token); } replace_in_uri(&token_url, "$CLIENT_ID", oauth2->client_id); replace_in_uri(&token_url, "$REDIRECT_URI", redirect_uri); replace_in_uri(&token_url, "$CODE", code); replace_in_uri(&token_url, "$REFRESH_TOKEN", refresh_token); json = (char*)context->cb(context, DC_EVENT_HTTP_POST, (uintptr_t)token_url, 0); if (json==NULL) { dc_log_warning(context, 0, "Error calling OAuth2 at %s", token_url); goto cleanup; } // generate new token: parse returned json jsmn_init(&parser); tok_cnt = jsmn_parse(&parser, json, strlen(json), tok, sizeof(tok)/sizeof(tok[0])); if (tok_cnt<2 || tok[0].type!=JSMN_OBJECT) { dc_log_warning(context, 0, "Failed to parse OAuth2 json from %s", token_url); goto cleanup; } for (int i = 1; i < tok_cnt; i++) { if (access_token==NULL && jsoneq(json, &tok[i], "access_token")==0) { access_token = jsondup(json, &tok[i+1]); } else if (refresh_token==NULL && jsoneq(json, &tok[i], "refresh_token")==0) { refresh_token = jsondup(json, &tok[i+1]); } else if (jsoneq(json, &tok[i], "expires_in")==0) { char* expires_in_str = jsondup(json, &tok[i+1]); if (expires_in_str) { time_t val = atol(expires_in_str); // val should be reasonable, maybe between 20 seconds and 5 years. // if out of range, we re-create when the token gets invalid, // which may create some additional load and requests wrt threads. if (val>20 && val<(60*60*24*365*5)) { expires_in = val; } free(expires_in_str); } } else if (error==NULL && jsoneq(json, &tok[i], "error")==0) { error = jsondup(json, &tok[i+1]); } else if (error_description==NULL && jsoneq(json, &tok[i], "error_description")==0) { error_description = jsondup(json, &tok[i+1]); } } if (error || error_description) { dc_log_warning(context, 0, "OAuth error: %s: %s", error? error : "unknown", error_description? error_description : "no details"); // continue, errors do not imply everything went wrong } // update refresh_token if given, typically on the first round, but we update it later as well. if (refresh_token && refresh_token[0]) { dc_sqlite3_set_config(context->sql, "oauth2_refresh_token", refresh_token); dc_sqlite3_set_config(context->sql, "oauth2_refresh_token_for", code); } // after that, save the access token. // if it's unset, we may get it in the next round as we have the refresh_token now. if (access_token==NULL || access_token[0]==0) { dc_log_warning(context, 0, "Failed to find OAuth2 access token"); goto cleanup; } dc_sqlite3_set_config(context->sql, "oauth2_access_token", access_token); dc_sqlite3_set_config_int64(context->sql, "oauth2_timestamp_expires", expires_in? time(NULL)+expires_in-5/*refresh a bet before*/ : 0); if (update_redirect_uri_on_success) { dc_sqlite3_set_config(context->sql, "oauth2_redirect_uri", redirect_uri); } cleanup: if (locked) { pthread_mutex_unlock(&context->oauth2_critical); } free(refresh_token); free(refresh_token_for); free(redirect_uri); free(token_url); free(json); free(error); free(error_description); free(oauth2); return access_token? access_token : dc_strdup(NULL); } static char* get_oauth2_addr(dc_context_t* context, const oauth2_t* oauth2, const char* access_token) { char* addr_out = NULL; char* userinfo_url = NULL; char* json = NULL; jsmn_parser parser; jsmntok_t tok[128]; // we do not expect nor read more tokens int tok_cnt = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || access_token==NULL || access_token[0]==0 || oauth2==NULL) { goto cleanup; } userinfo_url = dc_strdup(oauth2->get_userinfo); replace_in_uri(&userinfo_url, "$ACCESS_TOKEN", access_token); // should returns sth. as // { // "id": "100000000831024152393", // "email": "NAME@gmail.com", // "verified_email": true, // "picture": "https://lh4.googleusercontent.com/-Gj5jh_9R0BY/AAAAAAAAAAI/AAAAAAAAAAA/IAjtjfjtjNA/photo.jpg" // } json = (char*)context->cb(context, DC_EVENT_HTTP_GET, (uintptr_t)userinfo_url, 0); if (json==NULL) { dc_log_warning(context, 0, "Error getting userinfo."); goto cleanup; } jsmn_init(&parser); tok_cnt = jsmn_parse(&parser, json, strlen(json), tok, sizeof(tok)/sizeof(tok[0])); if (tok_cnt<2 || tok[0].type!=JSMN_OBJECT) { dc_log_warning(context, 0, "Failed to parse userinfo."); goto cleanup; } for (int i = 1; i < tok_cnt; i++) { if (addr_out==NULL && jsoneq(json, &tok[i], "email")==0) { addr_out = jsondup(json, &tok[i+1]); } } if (addr_out==NULL) { dc_log_warning(context, 0, "E-mail missing in userinfo."); } cleanup: free(userinfo_url); free(json); return addr_out; } char* dc_get_oauth2_addr(dc_context_t* context, const char* addr, const char* code) { char* access_token = NULL; char* addr_out = NULL; oauth2_t* oauth2 = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || (oauth2=get_info(addr))==NULL || oauth2->get_userinfo==NULL) { goto cleanup; } access_token = dc_get_oauth2_access_token(context, addr, code, 0); addr_out = get_oauth2_addr(context, oauth2, access_token); if (addr_out==NULL) { free(access_token); access_token = dc_get_oauth2_access_token(context, addr, code, DC_REGENERATE); addr_out = get_oauth2_addr(context, oauth2, access_token); } cleanup: free(access_token); free(oauth2); return addr_out; } ``` Filename: dc_openssl.c ```c #include #include #include #include #include "dc_context.h" static pthread_mutex_t s_init_lock = PTHREAD_MUTEX_INITIALIZER; static int s_init_not_required = 0; static int s_init_counter = 0; static pthread_mutex_t* s_mutex_buf = NULL; /** * Skip OpenSSL initialisation. * By default, the OpenSSL library is initialized thread-safe when calling * dc_context_new() the first time. When the last context-object is deleted * using dc_context_unref(), the OpenSSL library will be released as well. * * If your app needs OpenSSL on its own _outside_ these calls, you have to initialize the * OpenSSL-library yourself and skip the initialisation in deltachat-core by calling * dc_openssl_init_not_required() _before_ calling dc_context_new() the first time. * * Multiple calls to dc_openssl_init_not_required() are not needed, however, * they do not harm. * * @memberof dc_context_t * @return None. */ void dc_openssl_init_not_required(void) { pthread_mutex_lock(&s_init_lock); s_init_not_required = 1; pthread_mutex_unlock(&s_init_lock); } static unsigned long id_function(void) { return ((unsigned long)pthread_self()); } static void locking_function(int mode, int n, const char* file, int line) { if (mode & CRYPTO_LOCK) { pthread_mutex_lock(&s_mutex_buf[n]); } else { pthread_mutex_unlock(&s_mutex_buf[n]); } } struct CRYPTO_dynlock_value { pthread_mutex_t mutex; }; static struct CRYPTO_dynlock_value* dyn_create_function(const char* file, int line) { struct CRYPTO_dynlock_value* value = (struct CRYPTO_dynlock_value*)malloc(sizeof(struct CRYPTO_dynlock_value)); if (NULL==value) { return NULL; } pthread_mutex_init(&value->mutex, NULL); return value; } static void dyn_lock_function(int mode, struct CRYPTO_dynlock_value* l, const char* file, int line) { if (mode & CRYPTO_LOCK) { pthread_mutex_lock(&l->mutex); } else { pthread_mutex_unlock(&l->mutex); } } static void dyn_destroy_function(struct CRYPTO_dynlock_value* l, const char* file, int line) { pthread_mutex_destroy(&l->mutex); free(l); } void dc_openssl_init(void) { pthread_mutex_lock(&s_init_lock); s_init_counter++; if (s_init_counter==1) { if (!s_init_not_required) { s_mutex_buf = (pthread_mutex_t*)malloc(CRYPTO_num_locks() * sizeof(*s_mutex_buf)); if (s_mutex_buf==NULL) { exit(53); } for (int i=0 ; i0) { s_init_counter--; if (s_init_counter==0 && !s_init_not_required) { CRYPTO_set_id_callback(NULL); CRYPTO_set_locking_callback(NULL); CRYPTO_set_dynlock_create_callback(NULL); CRYPTO_set_dynlock_lock_callback(NULL); CRYPTO_set_dynlock_destroy_callback(NULL); for (int i=0 ; i #include #include "dc_context.h" #include "dc_tools.h" static char* find_param(char* haystack, int key, char** ret_p2) { char* p1 = NULL; char* p2 = NULL; /* let p1 point to the start of the */ p1 = haystack; while (1) { if (p1==NULL || *p1==0) { return NULL; } else if (*p1==key && p1[1]=='=') { break; } else { p1 = strchr(p1, '\n'); /* if `\r\n` is used, this `\r` is also skipped by this*/ if (p1) { p1++; } } } /* let p2 point to the character _after_ the value - eiter `\n` or `\0` */ p2 = strchr(p1, '\n'); if (p2==NULL) { p2 = &p1[strlen(p1)]; } *ret_p2 = p2; return p1; } /** * Create new parameter list object. * * @private @memberof dc_param_t * @return The created parameter list object. */ dc_param_t* dc_param_new() { dc_param_t* param = NULL; if ((param=calloc(1, sizeof(dc_param_t)))==NULL) { exit(28); /* cannot allocate little memory, unrecoverable error */ } param->packed = calloc(1, 1); return param; } /** * Free an parameter list object created eg. by dc_param_new(). * * @private @memberof dc_param_t * @param param The parameter list object to free. */ void dc_param_unref(dc_param_t* param) { if (param==NULL) { return; } dc_param_empty(param); free(param->packed); free(param); } /** * Delete all parameters in the object. * * @memberof dc_param_t * @param param Parameter object to modify. * @return None. */ void dc_param_empty(dc_param_t* param) { if (param==NULL) { return; } param->packed[0] = 0; } /** * Store a parameter set. The parameter set must be given in a packed form as * `a=value1\nb=value2`. The format should be very strict, additional spaces are not allowed. * * Before the new packed parameters are stored, _all_ existant parameters are deleted. * * @private @memberof dc_param_t * @param param Parameter object to modify. * @param packed Parameters to set, see comment above. * @return None. */ void dc_param_set_packed(dc_param_t* param, const char* packed) { if (param==NULL) { return; } dc_param_empty(param); if (packed) { free(param->packed); param->packed = dc_strdup(packed); } } /** * Same as dc_param_set_packed() but uses '&' as a separator (instead '\n'). * Urldecoding itself is not done by this function, this is up to the caller. */ void dc_param_set_urlencoded(dc_param_t* param, const char* urlencoded) { if (param==NULL) { return; } dc_param_empty(param); if (urlencoded) { free(param->packed); param->packed = dc_strdup(urlencoded); dc_str_replace(¶m->packed, "&", "\n"); } } /** * Check if a parameter exists. * * @memberof dc_param_t * @param param Parameter object to query. * @param key Key of the parameter to check the existance, one of the DC_PARAM_* constants. * @return 1=parameter exists in object, 0=parameter does not exist in parameter object. */ int dc_param_exists(dc_param_t* param, int key) { char *p2 = NULL; if (param==NULL || key==0) { return 0; } return find_param(param->packed, key, &p2)? 1 : 0; } /** * Get value of a parameter. * * @memberof dc_param_t * @param param Parameter object to query. * @param key Key of the parameter to get, one of the DC_PARAM_* constants. * @param def Value to return if the parameter is not set. * @return The stored value or the default value. In both cases, the returned value must be free()'d. */ char* dc_param_get(const dc_param_t* param, int key, const char* def) { char* p1 = NULL; char* p2 = NULL; char bak = 0; char* ret = NULL; if (param==NULL || key==0) { return def? dc_strdup(def) : NULL; } p1 = find_param(param->packed, key, &p2); if (p1==NULL) { return def? dc_strdup(def) : NULL; } p1 += 2; /* skip key and "=" (safe as find_param checks for its existance) */ bak = *p2; *p2 = 0; ret = dc_strdup(p1); dc_rtrim(ret); /* to be safe with '\r' characters ... */ *p2 = bak; return ret; } /** * Get value of a parameter. * * @memberof dc_param_t * @param param Parameter object to query. * @param key Key of the parameter to get, one of the DC_PARAM_* constants. * @param def Value to return if the parameter is not set. * @return The stored value or the default value. */ int32_t dc_param_get_int(const dc_param_t* param, int key, int32_t def) { if (param==NULL || key==0) { return def; } char* str = dc_param_get(param, key, NULL); if (str==NULL) { return def; } int32_t ret = atol(str); free(str); return ret; } /** * Get value of a parameter. * * @memberof dc_param_t * @param param Parameter object to query. * @param key Key of the parameter to get, one of the DC_PARAM_* constants. * @param def Value to return if the parameter is not set. * @return The stored value or the default value. */ double dc_param_get_float(const dc_param_t* param, int key, double def) { if (param==NULL || key==0) { return def; } char* str = dc_param_get(param, key, NULL); if (str==NULL) { return def; } double ret = dc_atof(str); free(str); return ret; } /** * Set parameter to a string. * * @memberof dc_param_t * @param param Parameter object to modify. * @param key Key of the parameter to modify, one of the DC_PARAM_* constants. * @param value Value to store for key. NULL to clear the value. * @return None. */ void dc_param_set(dc_param_t* param, int key, const char* value) { char* old1 = NULL; char* old2 = NULL; char* new1 = NULL; if (param==NULL || key==0) { return; } old1 = param->packed; old2 = NULL; /* remove existing parameter from packed string, if any */ if (old1) { char *p1, *p2; p1 = find_param(old1, key, &p2); if (p1 != NULL) { *p1 = 0; old2 = p2; } else if (value==NULL) { return; /* parameter does not exist and should be cleared -> done. */ } } dc_rtrim(old1); /* trim functions are null-pointer-safe */ dc_ltrim(old2); if (old1 && old1[0]==0) { old1 = NULL; } if (old2 && old2[0]==0) { old2 = NULL; } /* create new string */ if (value) { new1 = dc_mprintf("%s%s%c=%s%s%s", old1? old1 : "", old1? "\n" : "", key, value, old2? "\n" : "", old2? old2 : ""); } else { new1 = dc_mprintf("%s%s%s", old1? old1 : "", (old1&&old2)? "\n" : "", old2? old2 : ""); } free(param->packed); param->packed = new1; } /** * Set parameter to an integer. * * @memberof dc_param_t * @param param Parameter object to modify. * @param key Key of the parameter to modify, one of the DC_PARAM_* constants. * @param value Value to store for key. * @return None. */ void dc_param_set_int(dc_param_t* param, int key, int32_t value) { if (param==NULL || key==0) { return; } char* value_str = dc_mprintf("%i", (int)value); if (value_str==NULL) { return; } dc_param_set(param, key, value_str); free(value_str); } /** * Set parameter to a float. * * @memberof dc_param_t * @param param Parameter object to modify. * @param key Key of the parameter to modify, one of the DC_PARAM_* constants. * @param value Value to store for key. * @return None. */ void dc_param_set_float(dc_param_t* param, int key, double value) { if (param==NULL || key==0) { return; } char* value_str = dc_ftoa(value); if (value_str==NULL) { return; } dc_param_set(param, key, value_str); free(value_str); } ``` Filename: dc_pgp.c ```c /* End-to-end-encryption and other cryptographic functions based upon OpenSSL and BSD's netpgp. If we want to switch to other encryption engines, here are the functions to be replaced. However, eg. GpgME cannot (easily) be used standalone and GnuPG's licence would not allow the original creator of Delta Chat to release a proprietary version, which, however, is required for the Apple store. (NB: the original creator is the only person who could do this, a normal licensee is not allowed to do so at all) So, we do not see a simple alternative - but everyone is welcome to implement one :-) */ #include "dc_context.h" #ifdef DC_USE_RPGP #include #else #include #include #endif #include "dc_key.h" #include "dc_keyring.h" #include "dc_pgp.h" #include "dc_hash.h" #ifdef DC_USE_RPGP void dc_pgp_init(void) { } #else // !DC_USE_RPGP static int s_io_initialized = 0; static pgp_io_t s_io; void dc_pgp_init(void) { if (s_io_initialized) { return; } memset(&s_io, 0, sizeof(pgp_io_t)); s_io.outs = stdout; s_io.errs = stderr; s_io.res = stderr; s_io_initialized = 1; } #endif // !DC_USE_RPGP void dc_pgp_exit(void) { } #ifdef DC_USE_RPGP void dc_pgp_rand_seed(dc_context_t* context, const void* buf, size_t bytes) {} #else // !DC_USE_RPGP void dc_pgp_rand_seed(dc_context_t* context, const void* buf, size_t bytes) { if (buf==NULL || bytes<=0) { return; } RAND_seed(buf, bytes); } #endif // !DC_USE_RPGP /* Split data from PGP Armored Data as defined in https://tools.ietf.org/html/rfc4880#section-6.2. The given buffer is modified and the returned pointers just point inside the modified buffer, no additional data to free therefore. (NB: netpgp allows only parsing of Version, Comment, MessageID, Hash and Charset) */ int dc_split_armored_data(char* buf, const char** ret_headerline, const char** ret_setupcodebegin, const char** ret_preferencrypt, const char** ret_base64) { int success = 0; size_t line_chars = 0; char* line = buf; char* p1 = buf; char* p2 = NULL; char* headerline = NULL; char* base64 = NULL; #define PGP_WS "\t\r\n " if (ret_headerline) { *ret_headerline = NULL; } if (ret_setupcodebegin) { *ret_setupcodebegin = NULL; } if (ret_preferencrypt) { *ret_preferencrypt = NULL; } if (ret_base64) { *ret_base64 = NULL; } if (buf==NULL || ret_headerline==NULL) { goto cleanup; } dc_remove_cr_chars(buf); while (*p1) { if (*p1=='\n') { /* line found ... */ line[line_chars] = 0; if (headerline==NULL) { /* ... headerline */ dc_trim(line); if (strncmp(line, "-----BEGIN ", 11)==0 && strncmp(&line[strlen(line)-5], "-----", 5)==0) { headerline = line; if (ret_headerline) { *ret_headerline = headerline; } } } else if (strspn(line, PGP_WS)==strlen(line)) { /* ... empty line: base64 starts on next line */ base64 = p1+1; break; } else if ((p2=strchr(line, ':'))==NULL) { /* ... non-standard-header without empty line: base64 starts with this line */ line[line_chars] = '\n'; base64 = line; break; } else { /* header line */ *p2 = 0; dc_trim(line); if (strcasecmp(line, "Passphrase-Begin")==0) { p2++; dc_trim(p2); if (ret_setupcodebegin) { *ret_setupcodebegin = p2; } } else if (strcasecmp(line, "Autocrypt-Prefer-Encrypt")==0) { p2++; dc_trim(p2); if (ret_preferencrypt) { *ret_preferencrypt = p2; } } } /* prepare for next line */ p1++; line = p1; line_chars = 0; } else { p1++; line_chars++; } } if (headerline==NULL || base64==NULL) { goto cleanup; } /* now, line points to beginning of base64 data, search end */ if ((p1=strstr(base64, "-----END "/*the trailing space makes sure, this is not a normal base64 sequence*/))==NULL || strncmp(p1+9, headerline+11, strlen(headerline+11))!=0) { goto cleanup; } *p1 = 0; dc_trim(base64); if (ret_base64) { *ret_base64 = base64; } success = 1; cleanup: return success; } #ifdef DC_USE_RPGP /* returns 0 if there is no error, otherwise logs the error if a context is provided and returns 1*/ int dc_pgp_handle_rpgp_error(dc_context_t* context) { int success = 0; int len = 0; char* msg = NULL; len = rpgp_last_error_length(); if (len==0) { goto cleanup; } msg = rpgp_last_error_message(); if (context != NULL) { dc_log_info(context, 0, "[rpgp][error] %s", msg); } success = 1; cleanup: if (msg) { rpgp_string_drop(msg); } return success; } #endif /* DC_USE_RPGP */ /******************************************************************************* * Key generatation ******************************************************************************/ #ifdef DC_USE_RPGP int dc_pgp_create_keypair(dc_context_t* context, const char* addr, dc_key_t* ret_public_key, dc_key_t* ret_private_key) { int success = 0; rpgp_signed_secret_key* skey = NULL; rpgp_signed_public_key* pkey = NULL; rpgp_cvec* skey_bytes = NULL; rpgp_cvec* pkey_bytes = NULL; char* user_id = NULL; /* Create the user id */ user_id = dc_mprintf("<%s>", addr); /* Create the actual key */ skey = rpgp_create_rsa_skey(DC_KEYGEN_BITS, user_id); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } /* Serialize secret key into bytes */ skey_bytes = rpgp_skey_to_bytes(skey); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } /* Get the public key */ pkey = rpgp_skey_public_key(skey); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } /* Serialize public key into bytes */ pkey_bytes = rpgp_pkey_to_bytes(pkey); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } /* copy into the return secret key */ dc_key_set_from_binary(ret_private_key, rpgp_cvec_data(skey_bytes), rpgp_cvec_len(skey_bytes), DC_KEY_PRIVATE); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } /* copy into the return public key */ dc_key_set_from_binary(ret_public_key, rpgp_cvec_data(pkey_bytes), rpgp_cvec_len(pkey_bytes), DC_KEY_PUBLIC); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } success = 1; /* cleanup */ cleanup: if (skey) { rpgp_skey_drop(skey); } if (skey_bytes) { rpgp_cvec_drop(skey_bytes); } if (pkey) { rpgp_pkey_drop(pkey); } if (pkey_bytes) { rpgp_cvec_drop(pkey_bytes); } if (user_id) { free(user_id); } return success; } #else // !DC_USE_RPGP static unsigned add_key_prefs(pgp_create_sig_t *sig) { /* similar to pgp_add_key_prefs(), Mimic of GPG default settings, limited to supported algos */ return /* Symmetric algo prefs */ pgp_write_ss_header(sig->output, 6, PGP_PTAG_SS_PREFERRED_SKA) && pgp_write_scalar(sig->output, PGP_SA_AES_256, 1) && pgp_write_scalar(sig->output, PGP_SA_AES_128, 1) && pgp_write_scalar(sig->output, PGP_SA_CAST5, 1) && pgp_write_scalar(sig->output, PGP_SA_TRIPLEDES, 1) && pgp_write_scalar(sig->output, PGP_SA_IDEA, 1) && /* Hash algo prefs, the first algo is the preferred algo */ pgp_write_ss_header(sig->output, 6, PGP_PTAG_SS_PREFERRED_HASH) && pgp_write_scalar(sig->output, PGP_HASH_SHA256, 1) && pgp_write_scalar(sig->output, PGP_HASH_SHA384, 1) && pgp_write_scalar(sig->output, PGP_HASH_SHA512, 1) && pgp_write_scalar(sig->output, PGP_HASH_SHA224, 1) && pgp_write_scalar(sig->output, PGP_HASH_SHA1, 1) && /* Edit for Autocrypt/Delta Chat: due to the weak SHA1, it should not be preferred */ /* Compression algo prefs */ pgp_write_ss_header(sig->output, 2/*1+number of following items*/, PGP_PTAG_SS_PREF_COMPRESS) && pgp_write_scalar(sig->output, PGP_C_ZLIB, 1) /*&& -- not sure if Delta Chat will support bzip2 on all platforms, however, this is not that important as typical files are compressed themselves and text is not that big pgp_write_scalar(sig->output, PGP_C_BZIP2, 1) -- if you re-enable this, do not forget to modifiy the header count*/; } static void add_selfsigned_userid(pgp_key_t *skey, pgp_key_t *pkey, const uint8_t *userid, time_t key_expiry) { /* similar to pgp_add_selfsigned_userid() which, however, uses different key flags */ pgp_create_sig_t* sig = NULL; pgp_subpacket_t sigpacket; pgp_memory_t* mem_sig = NULL; pgp_output_t* sigoutput = NULL; /* create sig for this pkt */ sig = pgp_create_sig_new(); pgp_sig_start_key_sig(sig, &skey->key.seckey.pubkey, NULL, userid, PGP_CERT_POSITIVE); pgp_add_creation_time(sig, time(NULL)); pgp_add_key_expiration_time(sig, key_expiry); pgp_add_primary_userid(sig, 1); pgp_add_key_flags(sig, PGP_KEYFLAG_SIGN_DATA|PGP_KEYFLAG_CERT_KEYS); add_key_prefs(sig); pgp_add_key_features(sig); /* will add 0x01 - modification detection */ pgp_end_hashed_subpkts(sig); pgp_add_issuer_keyid(sig, skey->pubkeyid); /* the issuer keyid is not hashed by definition */ pgp_setup_memory_write(&sigoutput, &mem_sig, 128); pgp_write_sig(sigoutput, sig, &skey->key.seckey.pubkey, &skey->key.seckey); /* add this packet to key */ sigpacket.length = pgp_mem_len(mem_sig); sigpacket.raw = pgp_mem_data(mem_sig); /* add user id and signature to key */ pgp_update_userid(skey, userid, &sigpacket, &sig->sig.info); if(pkey) { pgp_update_userid(pkey, userid, &sigpacket, &sig->sig.info); } /* cleanup */ pgp_create_sig_delete(sig); pgp_output_delete(sigoutput); pgp_memory_free(mem_sig); } static void add_subkey_binding_signature(pgp_subkeysig_t* p, pgp_key_t* primarykey, pgp_key_t* subkey, pgp_key_t* seckey) { /*add "0x18: Subkey Binding Signature" packet, PGP_SIG_SUBKEY */ pgp_create_sig_t* sig = NULL; pgp_output_t* sigoutput = NULL; pgp_memory_t* mem_sig = NULL; sig = pgp_create_sig_new(); pgp_sig_start_key_sig(sig, &primarykey->key.pubkey, &subkey->key.pubkey, NULL, PGP_SIG_SUBKEY); pgp_add_creation_time(sig, time(NULL)); pgp_add_key_expiration_time(sig, 0); pgp_add_key_flags(sig, PGP_KEYFLAG_ENC_STORAGE|PGP_KEYFLAG_ENC_COMM); /* NB: algo/hash/compression preferences are not added to subkeys */ pgp_end_hashed_subpkts(sig); pgp_add_issuer_keyid(sig, seckey->pubkeyid); /* the issuer keyid is not hashed by definition */ pgp_setup_memory_write(&sigoutput, &mem_sig, 128); pgp_write_sig(sigoutput, sig, &seckey->key.seckey.pubkey, &seckey->key.seckey); p->subkey = primarykey->subkeyc-1; /* index of subkey in array */ p->packet.length = mem_sig->length; p->packet.raw = mem_sig->buf; mem_sig->buf = NULL; /* move ownership to packet */ copy_sig_info(&p->siginfo, &sig->sig.info); /* not sure, if this is okay, however, siginfo should be set up, otherwise we get "bad info-type" errors */ pgp_create_sig_delete(sig); pgp_output_delete(sigoutput); free(mem_sig); /* do not use pgp_memory_free() as this would also free mem_sig->buf which is owned by the packet */ } int dc_pgp_create_keypair(dc_context_t* context, const char* addr, dc_key_t* ret_public_key, dc_key_t* ret_private_key) { int success = 0; pgp_key_t seckey; pgp_key_t pubkey; pgp_key_t subkey; uint8_t subkeyid[PGP_KEY_ID_SIZE]; uint8_t* user_id = NULL; pgp_memory_t* pubmem = pgp_memory_new(); pgp_memory_t* secmem = pgp_memory_new(); pgp_output_t* pubout = pgp_output_new(); pgp_output_t* secout = pgp_output_new(); memset(&seckey, 0, sizeof(pgp_key_t)); memset(&pubkey, 0, sizeof(pgp_key_t)); memset(&subkey, 0, sizeof(pgp_key_t)); if (context==NULL || addr==NULL || ret_public_key==NULL || ret_private_key==NULL || pubmem==NULL || secmem==NULL || pubout==NULL || secout==NULL) { goto cleanup; } /* Generate User ID. By convention, this is the e-mail-address in angle brackets. As the user-id is only decorative in Autocrypt and not needed for Delta Chat, so we _could_ just use sth. that looks like an e-mail-address. This would protect the user's privacy if someone else uploads the keys to keyservers. However, as eg. Enigmail displayes the user-id in "Good signature from , for now, we decided to leave the address in the user-id */ #if 0 user_id = (uint8_t*)dc_mprintf("<%08X@%08X.org>", (int)random(), (int)random()); #else user_id = (uint8_t*)dc_mprintf("<%s>", addr); #endif /* generate two keypairs */ if (!pgp_rsa_generate_keypair(&seckey, DC_KEYGEN_BITS, DC_KEYGEN_E, NULL, NULL, NULL, 0) || !pgp_rsa_generate_keypair(&subkey, DC_KEYGEN_BITS, DC_KEYGEN_E, NULL, NULL, NULL, 0)) { goto cleanup; } /* Create public key, bind public subkey to public key ------------------------------------------------------------------------ */ pubkey.type = PGP_PTAG_CT_PUBLIC_KEY; pgp_pubkey_dup(&pubkey.key.pubkey, &seckey.key.pubkey); memcpy(pubkey.pubkeyid, seckey.pubkeyid, PGP_KEY_ID_SIZE); pgp_fingerprint(&pubkey.pubkeyfpr, &seckey.key.pubkey, 0); add_selfsigned_userid(&seckey, &pubkey, (const uint8_t*)user_id, 0/*never expire*/); EXPAND_ARRAY((&pubkey), subkey); { pgp_subkey_t* p = &pubkey.subkeys[pubkey.subkeyc++]; pgp_pubkey_dup(&p->key.pubkey, &subkey.key.pubkey); pgp_keyid(subkeyid, PGP_KEY_ID_SIZE, &pubkey.key.pubkey, PGP_HASH_SHA1); memcpy(p->id, subkeyid, PGP_KEY_ID_SIZE); } EXPAND_ARRAY((&pubkey), subkeysig); add_subkey_binding_signature(&pubkey.subkeysigs[pubkey.subkeysigc++], &pubkey, &subkey, &seckey); /* Create secret key, bind secret subkey to secret key ------------------------------------------------------------------------ */ EXPAND_ARRAY((&seckey), subkey); { pgp_subkey_t* p = &seckey.subkeys[seckey.subkeyc++]; pgp_seckey_dup(&p->key.seckey, &subkey.key.seckey); pgp_keyid(subkeyid, PGP_KEY_ID_SIZE, &seckey.key.pubkey, PGP_HASH_SHA1); memcpy(p->id, subkeyid, PGP_KEY_ID_SIZE); } EXPAND_ARRAY((&seckey), subkeysig); add_subkey_binding_signature(&seckey.subkeysigs[seckey.subkeysigc++], &seckey, &subkey, &seckey); /* Done with key generation, write binary keys to memory ------------------------------------------------------------------------ */ pgp_writer_set_memory(pubout, pubmem); if (!pgp_write_xfer_key(pubout, &pubkey, 0/*armored*/) || pubmem->buf==NULL || pubmem->length <= 0) { goto cleanup; } pgp_writer_set_memory(secout, secmem); if (!pgp_write_xfer_key(secout, &seckey, 0/*armored*/) || secmem->buf==NULL || secmem->length <= 0) { goto cleanup; } dc_key_set_from_binary(ret_public_key, pubmem->buf, pubmem->length, DC_KEY_PUBLIC); dc_key_set_from_binary(ret_private_key, secmem->buf, secmem->length, DC_KEY_PRIVATE); success = 1; cleanup: if (pubout) { pgp_output_delete(pubout); } if (secout) { pgp_output_delete(secout); } if (pubmem) { pgp_memory_free(pubmem); } if (secmem) { pgp_memory_free(secmem); } pgp_key_free(&seckey); /* not: pgp_keydata_free() which will also free the pointer itself (we created it on the stack) */ pgp_key_free(&pubkey); pgp_key_free(&subkey); free(user_id); return success; } #endif // !DC_USE_RPGP /******************************************************************************* * Check keys ******************************************************************************/ #ifdef DC_USE_RPGP int dc_pgp_is_valid_key(dc_context_t* context, const dc_key_t* raw_key) { int key_is_valid = 0; rpgp_public_or_secret_key* key = NULL; if (context==NULL || raw_key==NULL || raw_key->binary==NULL || raw_key->bytes <= 0) { goto cleanup; } key = rpgp_key_from_bytes(raw_key->binary, raw_key->bytes); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } if (raw_key->type==DC_KEY_PUBLIC && rpgp_key_is_public(key)) { key_is_valid = 1; } else if (raw_key->type==DC_KEY_PRIVATE && rpgp_key_is_secret(key)) { key_is_valid = 1; } cleanup: if (key) { rpgp_key_drop(key); } return key_is_valid; } #else // !DC_USE_RPGP int dc_pgp_is_valid_key(dc_context_t* context, const dc_key_t* raw_key) { int key_is_valid = 0; pgp_keyring_t* public_keys = calloc(1, sizeof(pgp_keyring_t)); pgp_keyring_t* private_keys = calloc(1, sizeof(pgp_keyring_t)); pgp_memory_t* keysmem = pgp_memory_new(); if (context==NULL || raw_key==NULL || raw_key->binary==NULL || raw_key->bytes <= 0 || public_keys==NULL || private_keys==NULL || keysmem==NULL) { goto cleanup; } pgp_memory_add(keysmem, raw_key->binary, raw_key->bytes); pgp_filter_keys_from_mem(&s_io, public_keys, private_keys, NULL, 0, keysmem); /* function returns 0 on any error in any packet - this does not mean, we cannot use the key. We check the details below therefore. */ if (raw_key->type==DC_KEY_PUBLIC && public_keys->keyc >= 1) { key_is_valid = 1; } else if (raw_key->type==DC_KEY_PRIVATE && private_keys->keyc >= 1) { key_is_valid = 1; } cleanup: if (keysmem) { pgp_memory_free(keysmem); } if (public_keys) { pgp_keyring_purge(public_keys); free(public_keys); } /*pgp_keyring_free() frees the content, not the pointer itself*/ if (private_keys) { pgp_keyring_purge(private_keys); free(private_keys); } return key_is_valid; } #endif // !DC_USE_RPGP #ifdef DC_USE_RPGP int dc_pgp_calc_fingerprint(const dc_key_t* raw_key, uint8_t** ret_fingerprint, size_t* ret_fingerprint_bytes) { int success = 0; rpgp_public_or_secret_key* key = NULL; rpgp_cvec* fingerprint = NULL; if (raw_key==NULL || ret_fingerprint==NULL || *ret_fingerprint!=NULL || ret_fingerprint_bytes==NULL || *ret_fingerprint_bytes!=0 || raw_key->binary==NULL || raw_key->bytes <= 0) { goto cleanup; } /* get the key into the right format */ key = rpgp_key_from_bytes(raw_key->binary, raw_key->bytes); if (dc_pgp_handle_rpgp_error(NULL)) { goto cleanup; } /* calc the fingerprint */ fingerprint = rpgp_key_fingerprint(key); if (dc_pgp_handle_rpgp_error(NULL)) { goto cleanup; } /* copy into the result */ *ret_fingerprint_bytes = rpgp_cvec_len(fingerprint); *ret_fingerprint = malloc(*ret_fingerprint_bytes); memcpy(*ret_fingerprint, rpgp_cvec_data(fingerprint), *ret_fingerprint_bytes); success = 1; cleanup: if (key) { rpgp_key_drop(key); } if (fingerprint) { rpgp_cvec_drop(fingerprint); } return success; } #else // !DC_USE_RPGP int dc_pgp_calc_fingerprint(const dc_key_t* raw_key, uint8_t** ret_fingerprint, size_t* ret_fingerprint_bytes) { int success = 0; pgp_keyring_t* public_keys = calloc(1, sizeof(pgp_keyring_t)); pgp_keyring_t* private_keys = calloc(1, sizeof(pgp_keyring_t)); pgp_memory_t* keysmem = pgp_memory_new(); if (raw_key==NULL || ret_fingerprint==NULL || *ret_fingerprint!=NULL || ret_fingerprint_bytes==NULL || *ret_fingerprint_bytes!=0 || raw_key->binary==NULL || raw_key->bytes <= 0 || public_keys==NULL || private_keys==NULL || keysmem==NULL) { goto cleanup; } pgp_memory_add(keysmem, raw_key->binary, raw_key->bytes); pgp_filter_keys_from_mem(&s_io, public_keys, private_keys, NULL, 0, keysmem); if (raw_key->type != DC_KEY_PUBLIC || public_keys->keyc <= 0) { goto cleanup; } pgp_key_t* key0 = &public_keys->keys[0]; pgp_pubkey_t* pubkey0 = &key0->key.pubkey; if (!pgp_fingerprint(&key0->pubkeyfpr, pubkey0, 0)) { goto cleanup; } *ret_fingerprint_bytes = key0->pubkeyfpr.length; *ret_fingerprint = malloc(*ret_fingerprint_bytes); memcpy(*ret_fingerprint, key0->pubkeyfpr.fingerprint, *ret_fingerprint_bytes); success = 1; cleanup: if (keysmem) { pgp_memory_free(keysmem); } if (public_keys) { pgp_keyring_purge(public_keys); free(public_keys); } /*pgp_keyring_free() frees the content, not the pointer itself*/ if (private_keys) { pgp_keyring_purge(private_keys); free(private_keys); } return success; } #endif // !DC_USE_RPGP #ifdef DC_USE_RPGP int dc_pgp_split_key(dc_context_t* context, const dc_key_t* private_in, dc_key_t* ret_public_key) { int success = 0; rpgp_signed_secret_key* key = NULL; rpgp_signed_public_key* pub_key = NULL; rpgp_cvec* buf = NULL; if (context==NULL || private_in==NULL || ret_public_key==NULL) { goto cleanup; } if (private_in->type!=DC_KEY_PRIVATE) { dc_log_warning(context, 0, "Split key: Given key is no private key."); goto cleanup; } /* deserialize secret key */ key = rpgp_skey_from_bytes(private_in->binary, private_in->bytes); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } /* convert to public key */ pub_key = rpgp_skey_public_key(key); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } /* serialize public key */ buf = rpgp_pkey_to_bytes(pub_key); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } /* create return value */ dc_key_set_from_binary(ret_public_key, rpgp_cvec_data(buf), rpgp_cvec_len(buf), DC_KEY_PUBLIC); success = 1; cleanup: if (key) { rpgp_skey_drop(key); } if (pub_key) { rpgp_pkey_drop(pub_key); } if (buf) { rpgp_cvec_drop(buf); } return success; } #else // !DC_USE_RPGP int dc_pgp_split_key(dc_context_t* context, const dc_key_t* private_in, dc_key_t* ret_public_key) { int success = 0; pgp_keyring_t* public_keys = calloc(1, sizeof(pgp_keyring_t)); pgp_keyring_t* private_keys = calloc(1, sizeof(pgp_keyring_t)); pgp_memory_t* keysmem = pgp_memory_new(); pgp_memory_t* pubmem = pgp_memory_new(); pgp_output_t* pubout = pgp_output_new(); if (context==NULL || private_in==NULL || ret_public_key==NULL || public_keys==NULL || private_keys==NULL || keysmem==NULL || pubmem==NULL || pubout==NULL) { goto cleanup; } pgp_memory_add(keysmem, private_in->binary, private_in->bytes); pgp_filter_keys_from_mem(&s_io, public_keys, private_keys, NULL, 0, keysmem); if (private_in->type!=DC_KEY_PRIVATE || private_keys->keyc <= 0) { dc_log_warning(context, 0, "Split key: Given key is no private key."); goto cleanup; } if (public_keys->keyc <= 0) { dc_log_warning(context, 0, "Split key: Given key does not contain a public key."); goto cleanup; } pgp_writer_set_memory(pubout, pubmem); if (!pgp_write_xfer_key(pubout, &public_keys->keys[0], 0/*armored*/) || pubmem->buf==NULL || pubmem->length <= 0) { goto cleanup; } dc_key_set_from_binary(ret_public_key, pubmem->buf, pubmem->length, DC_KEY_PUBLIC); success = 1; cleanup: if (pubout) { pgp_output_delete(pubout); } if (pubmem) { pgp_memory_free(pubmem); } if (keysmem) { pgp_memory_free(keysmem); } if (public_keys) { pgp_keyring_purge(public_keys); free(public_keys); } /*pgp_keyring_free() frees the content, not the pointer itself*/ if (private_keys) { pgp_keyring_purge(private_keys); free(private_keys); } return success; } #endif // !DC_USE_RPGP /******************************************************************************* * Public key encrypt/decrypt ******************************************************************************/ #ifdef DC_USE_RPGP int dc_pgp_pk_encrypt( dc_context_t* context, const void* plain_text, size_t plain_bytes, const dc_keyring_t* raw_public_keys_for_encryption, const dc_key_t* raw_private_key_for_signing, int use_armor, void** ret_ctext, size_t* ret_ctext_bytes) { int i = 0; int success = 0; int public_keys_len = 0; rpgp_signed_public_key* *public_keys = NULL; rpgp_signed_secret_key* private_key = NULL; rpgp_message* encrypted = NULL; if (context==NULL || plain_text==NULL || plain_bytes==0 || ret_ctext==NULL || ret_ctext_bytes==NULL || raw_public_keys_for_encryption==NULL || raw_public_keys_for_encryption->count<=0 || use_armor==0 /* only support use_armor=1 */) { goto cleanup; } *ret_ctext = NULL; *ret_ctext_bytes = 0; public_keys_len = raw_public_keys_for_encryption->count; public_keys = malloc(sizeof(rpgp_signed_public_key*) * public_keys_len); /* setup secret key for signing */ if (raw_private_key_for_signing) { private_key = rpgp_skey_from_bytes(raw_private_key_for_signing->binary, raw_private_key_for_signing->bytes); if (private_key == NULL || dc_pgp_handle_rpgp_error(context)) { dc_log_warning(context, 0, "No key for signing found."); goto cleanup; } } /* setup public keys for encryption */ for (i = 0; i < public_keys_len; i++) { public_keys[i] = rpgp_pkey_from_bytes(raw_public_keys_for_encryption->keys[i]->binary, raw_public_keys_for_encryption->keys[i]->bytes); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } } /* sign & encrypt */ { clock_t op_clocks = 0; clock_t start = clock(); if (private_key==NULL) { encrypted = rpgp_encrypt_bytes_to_keys(plain_text, plain_bytes, (const rpgp_signed_public_key* const*)public_keys, public_keys_len); if (dc_pgp_handle_rpgp_error(context)) { dc_log_warning(context, 0, "Encryption failed."); goto cleanup; } op_clocks = clock()-start; dc_log_info(context, 0, "Message encrypted in %.3f ms.", (double)(op_clocks)*1000.0/CLOCKS_PER_SEC); } else { encrypted = rpgp_sign_encrypt_bytes_to_keys(plain_text, plain_bytes, (const rpgp_signed_public_key* const*)public_keys, public_keys_len, private_key); if (dc_pgp_handle_rpgp_error(context)) { dc_log_warning(context, 0, "Signing and encrypting failed."); goto cleanup; } op_clocks = clock()-start; dc_log_info(context, 0, "Message signed and encrypted in %.3f ms.", (double)(op_clocks)*1000.0/CLOCKS_PER_SEC); } /* convert message to armored bytes and return values */ rpgp_cvec* armored = rpgp_msg_to_armored(encrypted); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } *ret_ctext = (void*)rpgp_cvec_data(armored); *ret_ctext_bytes = rpgp_cvec_len(armored); // No drop as we only remove the struct free(armored); } success = 1; cleanup: if (private_key) { rpgp_skey_drop(private_key); } for (i = 0; i < public_keys_len; i++) { rpgp_pkey_drop(public_keys[i]); } if (encrypted) { rpgp_msg_drop(encrypted); } return success; } #else // !DC_USE_RPGP int dc_pgp_pk_encrypt( dc_context_t* context, const void* plain_text, size_t plain_bytes, const dc_keyring_t* raw_public_keys_for_encryption, const dc_key_t* raw_private_key_for_signing, int use_armor, void** ret_ctext, size_t* ret_ctext_bytes) { pgp_keyring_t* public_keys = calloc(1, sizeof(pgp_keyring_t)); pgp_keyring_t* private_keys = calloc(1, sizeof(pgp_keyring_t)); pgp_keyring_t* dummy_keys = calloc(1, sizeof(pgp_keyring_t)); pgp_memory_t* keysmem = pgp_memory_new(); pgp_memory_t* signedmem = NULL; int i = 0; int success = 0; if (context==NULL || plain_text==NULL || plain_bytes==0 || ret_ctext==NULL || ret_ctext_bytes==NULL || raw_public_keys_for_encryption==NULL || raw_public_keys_for_encryption->count<=0 || keysmem==NULL || public_keys==NULL || private_keys==NULL || dummy_keys==NULL) { goto cleanup; } *ret_ctext = NULL; *ret_ctext_bytes = 0; /* setup keys (the keys may come from pgp_filter_keys_fileread(), see also pgp_keyring_add(rcpts, key)) */ for (i = 0; i < raw_public_keys_for_encryption->count; i++) { pgp_memory_clear(keysmem); pgp_memory_add(keysmem, raw_public_keys_for_encryption->keys[i]->binary, raw_public_keys_for_encryption->keys[i]->bytes); pgp_filter_keys_from_mem(&s_io, public_keys, private_keys/*should stay empty*/, NULL, 0, keysmem); } if (public_keys->keyc <=0 || private_keys->keyc!=0) { dc_log_warning(context, 0, "Encryption-keyring contains unexpected data (%i/%i)", public_keys->keyc, private_keys->keyc); goto cleanup; } /* encrypt */ { const void* signed_text = NULL; size_t signed_bytes = 0; int encrypt_raw_packet = 0; clock_t sign_clocks = 0; clock_t encrypt_clocks = 0; if (raw_private_key_for_signing) { pgp_memory_clear(keysmem); pgp_memory_add(keysmem, raw_private_key_for_signing->binary, raw_private_key_for_signing->bytes); pgp_filter_keys_from_mem(&s_io, dummy_keys, private_keys, NULL, 0, keysmem); if (private_keys->keyc <= 0) { dc_log_warning(context, 0, "No key for signing found."); goto cleanup; } clock_t start = clock(); pgp_key_t* sk0 = &private_keys->keys[0]; signedmem = pgp_sign_buf(&s_io, plain_text, plain_bytes, &sk0->key.seckey, time(NULL)/*birthtime*/, 0/*duration*/, NULL/*hash, defaults to sha256*/, 0/*armored*/, 0/*cleartext*/); sign_clocks = clock()-start; if (signedmem==NULL) { dc_log_warning(context, 0, "Signing failed."); goto cleanup; } signed_text = signedmem->buf; signed_bytes = signedmem->length; encrypt_raw_packet = 1; } else { signed_text = plain_text; signed_bytes = plain_bytes; encrypt_raw_packet = 0; } clock_t start = clock(); pgp_memory_t* outmem = pgp_encrypt_buf(&s_io, signed_text, signed_bytes, public_keys, use_armor, NULL/*cipher*/, encrypt_raw_packet); encrypt_clocks = clock()-start; dc_log_info(context, 0, "Message signed in %.3f ms and encrypted in %.3f ms.", (double)(sign_clocks)*1000.0/CLOCKS_PER_SEC, (double)(encrypt_clocks)*1000.0/CLOCKS_PER_SEC); if (outmem==NULL) { dc_log_warning(context, 0, "Encryption failed."); goto cleanup; } *ret_ctext = outmem->buf; *ret_ctext_bytes = outmem->length; free(outmem); /* do not use pgp_memory_free() as we took ownership of the buffer */ } success = 1; cleanup: if (keysmem) { pgp_memory_free(keysmem); } if (signedmem) { pgp_memory_free(signedmem); } if (public_keys) { pgp_keyring_purge(public_keys); free(public_keys); } /*pgp_keyring_free() frees the content, not the pointer itself*/ if (private_keys) { pgp_keyring_purge(private_keys); free(private_keys); } if (dummy_keys) { pgp_keyring_purge(dummy_keys); free(dummy_keys); } return success; } #endif // !DC_USE_RPGP #ifdef DC_USE_RPGP int dc_pgp_pk_decrypt( dc_context_t* context, const void* ctext, size_t ctext_bytes, const dc_keyring_t* raw_private_keys_for_decryption, const dc_keyring_t* raw_public_keys_for_validation, int use_armor, void** ret_plain, size_t* ret_plain_bytes, dc_hash_t* ret_signature_fingerprints) { int i = 0; int success = 0; rpgp_message* encrypted = NULL; rpgp_message_decrypt_result* decrypted = NULL; int private_keys_len = 0; int public_keys_len = 0; rpgp_signed_secret_key* *private_keys = NULL; rpgp_signed_public_key* *public_keys = NULL; if (context==NULL || ctext==NULL || ctext_bytes==0 || ret_plain==NULL || ret_plain_bytes==NULL || raw_private_keys_for_decryption==NULL || raw_private_keys_for_decryption->count<=0 || use_armor==0 /* only support use_armor=1 */) { goto cleanup; } *ret_plain = NULL; *ret_plain_bytes = 0; private_keys_len = raw_private_keys_for_decryption->count; private_keys = malloc(sizeof(rpgp_signed_secret_key*) * private_keys_len); if (raw_public_keys_for_validation) { public_keys_len = raw_public_keys_for_validation->count; public_keys = malloc(sizeof(rpgp_signed_public_key*) * public_keys_len); } /* setup secret keys for decryption */ for (i = 0; i < raw_private_keys_for_decryption->count; i++) { private_keys[i] = rpgp_skey_from_bytes(raw_private_keys_for_decryption->keys[i]->binary, raw_private_keys_for_decryption->keys[i]->bytes); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } } /* setup public keys for validation */ if (raw_public_keys_for_validation) { for (i = 0; i < raw_public_keys_for_validation->count; i++) { public_keys[i] = rpgp_pkey_from_bytes(raw_public_keys_for_validation->keys[i]->binary, raw_public_keys_for_validation->keys[i]->bytes); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } } } /* decrypt */ { encrypted = rpgp_msg_from_armor(ctext, ctext_bytes); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } decrypted = rpgp_msg_decrypt_no_pw(encrypted, (const rpgp_signed_secret_key* const*)private_keys, private_keys_len, (const rpgp_signed_public_key* const*)public_keys, public_keys_len); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } rpgp_cvec* decrypted_bytes = rpgp_msg_to_bytes(decrypted->message_ptr); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } *ret_plain_bytes = rpgp_cvec_len(decrypted_bytes); *ret_plain = (void*)rpgp_cvec_data(decrypted_bytes); // No drop as we only remove the struct free(decrypted_bytes); /* collect the keys of the valid signatures */ if (ret_signature_fingerprints) { uint32_t j = 0; uint32_t len = (uint32_t)decrypted->valid_ids_len; for (; j < len; j++) { char* fingerprint_hex = decrypted->valid_ids_ptr[j]; if (fingerprint_hex) { dc_hash_insert(ret_signature_fingerprints, fingerprint_hex, strlen(fingerprint_hex), (void*)1); free(fingerprint_hex); } } } } success = 1; cleanup: for (i = 0; i < private_keys_len; i++) { rpgp_skey_drop(private_keys[i]); } for (i = 0; i < public_keys_len; i++) { rpgp_pkey_drop(public_keys[i]); } if (encrypted) { rpgp_msg_drop(encrypted); } if (decrypted) { rpgp_message_decrypt_result_drop(decrypted); } return success; } #else // !DC_USE_RPGP int dc_pgp_pk_decrypt( dc_context_t* context, const void* ctext, size_t ctext_bytes, const dc_keyring_t* raw_private_keys_for_decryption, const dc_keyring_t* raw_public_keys_for_validation, int use_armor, void** ret_plain, size_t* ret_plain_bytes, dc_hash_t* ret_signature_fingerprints) { pgp_keyring_t* public_keys = calloc(1, sizeof(pgp_keyring_t)); /*should be 0 after parsing*/ pgp_keyring_t* private_keys = calloc(1, sizeof(pgp_keyring_t)); pgp_keyring_t* dummy_keys = calloc(1, sizeof(pgp_keyring_t)); pgp_validation_t* vresult = calloc(1, sizeof(pgp_validation_t)); key_id_t* recipients_key_ids = NULL; unsigned recipients_cnt = 0; pgp_memory_t* keysmem = pgp_memory_new(); int i = 0; int success = 0; if (context==NULL || ctext==NULL || ctext_bytes==0 || ret_plain==NULL || ret_plain_bytes==NULL || raw_private_keys_for_decryption==NULL || raw_private_keys_for_decryption->count<=0 || vresult==NULL || keysmem==NULL || public_keys==NULL || private_keys==NULL) { goto cleanup; } *ret_plain = NULL; *ret_plain_bytes = 0; /* setup keys (the keys may come from pgp_filter_keys_fileread(), see also pgp_keyring_add(rcpts, key)) */ for (i = 0; i < raw_private_keys_for_decryption->count; i++) { pgp_memory_clear(keysmem); /* a simple concatenate of private binary keys fails (works for public keys, however, we don't do it there either) */ pgp_memory_add(keysmem, raw_private_keys_for_decryption->keys[i]->binary, raw_private_keys_for_decryption->keys[i]->bytes); pgp_filter_keys_from_mem(&s_io, dummy_keys/*should stay empty*/, private_keys, NULL, 0, keysmem); } if (private_keys->keyc<=0) { dc_log_warning(context, 0, "Decryption-keyring contains unexpected data (%i/%i)", public_keys->keyc, private_keys->keyc); goto cleanup; } if (raw_public_keys_for_validation) { for (i = 0; i < raw_public_keys_for_validation->count; i++) { pgp_memory_clear(keysmem); pgp_memory_add(keysmem, raw_public_keys_for_validation->keys[i]->binary, raw_public_keys_for_validation->keys[i]->bytes); pgp_filter_keys_from_mem(&s_io, public_keys, dummy_keys/*should stay empty*/, NULL, 0, keysmem); } } /* decrypt */ { pgp_memory_t* outmem = pgp_decrypt_and_validate_buf(&s_io, vresult, ctext, ctext_bytes, private_keys, public_keys, use_armor, &recipients_key_ids, &recipients_cnt); if (outmem==NULL) { dc_log_warning(context, 0, "Decryption failed."); goto cleanup; } *ret_plain = outmem->buf; *ret_plain_bytes = outmem->length; free(outmem); /* do not use pgp_memory_free() as we took ownership of the buffer */ // collect the keys of the valid signatures if (ret_signature_fingerprints) { for (i = 0; i < vresult->validc; i++) { unsigned from = 0; pgp_key_t* key0 = pgp_getkeybyid(&s_io, public_keys, vresult->valid_sigs[i].signer_id, &from, NULL, NULL, 0, 0); if (key0) { pgp_pubkey_t* pubkey0 = &key0->key.pubkey; if (!pgp_fingerprint(&key0->pubkeyfpr, pubkey0, 0)) { goto cleanup; } char* fingerprint_hex = dc_binary_to_uc_hex(key0->pubkeyfpr.fingerprint, key0->pubkeyfpr.length); if (fingerprint_hex) { dc_hash_insert(ret_signature_fingerprints, fingerprint_hex, strlen(fingerprint_hex), (void*)1); } free(fingerprint_hex); } } } } success = 1; cleanup: if (keysmem) { pgp_memory_free(keysmem); } if (public_keys) { pgp_keyring_purge(public_keys); free(public_keys); } /*pgp_keyring_free() frees the content, not the pointer itself*/ if (private_keys) { pgp_keyring_purge(private_keys); free(private_keys); } if (dummy_keys) { pgp_keyring_purge(dummy_keys); free(dummy_keys); } if (vresult) { pgp_validate_result_free(vresult); } free(recipients_key_ids); return success; } #endif // !DC_USE_RPGP /******************************************************************************* * Symmetric encrypt/decrypt, needed for the autocrypt setup messages ******************************************************************************/ #ifdef DC_USE_RPGP int dc_pgp_symm_encrypt(dc_context_t* context, const char* passphrase, const void* plain, size_t plain_bytes, char** ret_ctext_armored) { int success = 0; rpgp_message* decrypted = NULL; if (context==NULL || passphrase==NULL || plain==NULL || plain_bytes==0 || ret_ctext_armored==NULL ) { goto cleanup; } decrypted = rpgp_encrypt_bytes_with_password(plain, plain_bytes, passphrase); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } *ret_ctext_armored = rpgp_msg_to_armored_str(decrypted); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } success = 1; cleanup: if (decrypted) { rpgp_msg_drop(decrypted); } return success; } #else // !DC_USE_RPGP int dc_pgp_symm_encrypt(dc_context_t* context, const char* passphrase, const void* plain, size_t plain_bytes, char** ret_ctext_armored) { int success = 0; uint8_t salt[PGP_SALT_SIZE]; pgp_crypt_t crypt_info; uint8_t* key = NULL; pgp_output_t* payload_output = NULL; pgp_memory_t* payload_mem = NULL; pgp_output_t* encr_output = NULL; pgp_memory_t* encr_mem = NULL; if (context==NULL || passphrase==NULL || plain==NULL || plain_bytes==0 || ret_ctext_armored==NULL ) { goto cleanup; } //printf("\n~~~~~~~~~~~~~~~~~~~~SETUP-PAYLOAD~~~~~~~~~~~~~~~~~~~~\n%s~~~~~~~~~~~~~~~~~~~~/SETUP-PAYLOAD~~~~~~~~~~~~~~~~~~~~\n",key_asc); // DEBUG OUTPUT /* put the payload into a literal data packet which will be encrypted then, see RFC 4880, 5.7 : "When it has been decrypted, it contains other packets (usually a literal data packet or compressed data packet, but in theory other Symmetrically Encrypted Data packets or sequences of packets that form whole OpenPGP messages)" */ pgp_setup_memory_write(&payload_output, &payload_mem, 128); pgp_write_litdata(payload_output, (const uint8_t*)plain, plain_bytes, PGP_LDT_BINARY); /* create salt for the key */ pgp_random(salt, PGP_SALT_SIZE); /* S2K */ #define SYMM_ALGO PGP_SA_AES_128 if (!pgp_crypt_any(&crypt_info, SYMM_ALGO)) { goto cleanup; } int s2k_spec = PGP_S2KS_ITERATED_AND_SALTED; // 0=simple, 1=salted, 3=salted+iterated int s2k_iter_id = 96; // 0=1024 iterations, 96=65536 iterations #define HASH_ALG PGP_HASH_SHA256 if ((key = pgp_s2k_do(passphrase, crypt_info.keysize, s2k_spec, HASH_ALG, salt, s2k_iter_id))==NULL) { goto cleanup; } /* encrypt the payload using the key using AES-128 and put it into OpenPGP's "Symmetric-Key Encrypted Session Key" (Tag 3, https://tools.ietf.org/html/rfc4880#section-5.3) followed by OpenPGP's "Symmetrically Encrypted Data Packet" (Tag 18, https://tools.ietf.org/html/rfc4880#section-5.13 , better than Tag 9) */ pgp_setup_memory_write(&encr_output, &encr_mem, 128); pgp_writer_push_armor_msg(encr_output); /* Tag 3 - PGP_PTAG_CT_SK_SESSION_KEY */ pgp_write_ptag (encr_output, PGP_PTAG_CT_SK_SESSION_KEY); pgp_write_length (encr_output, 1/*version*/ + 1/*symm. algo*/ + 1/*s2k_spec*/ + 1/*S2 hash algo*/ + ((s2k_spec==PGP_S2KS_SALTED || s2k_spec==PGP_S2KS_ITERATED_AND_SALTED)? PGP_SALT_SIZE : 0)/*the salt*/ + ((s2k_spec==PGP_S2KS_ITERATED_AND_SALTED)? 1 : 0)/*number of iterations*/); pgp_write_scalar (encr_output, 4, 1); // 1 octet: version pgp_write_scalar (encr_output, SYMM_ALGO, 1); // 1 octet: symm. algo pgp_write_scalar (encr_output, s2k_spec, 1); // 1 octet: s2k_spec pgp_write_scalar (encr_output, HASH_ALG, 1); // 1 octet: S2 hash algo if (s2k_spec==PGP_S2KS_SALTED || s2k_spec==PGP_S2KS_ITERATED_AND_SALTED) { pgp_write (encr_output, salt, PGP_SALT_SIZE); // 8 octets: the salt } if (s2k_spec==PGP_S2KS_ITERATED_AND_SALTED) { pgp_write_scalar (encr_output, s2k_iter_id, 1); // 1 octet: number of iterations } // for(int j=0; jbuf, payload_mem->length, PGP_SA_AES_128, key, encr_output); //-- would generate Tag 9 { uint8_t* iv = calloc(1, crypt_info.blocksize); if (iv==NULL) { goto cleanup; } crypt_info.set_iv(&crypt_info, iv); free(iv); crypt_info.set_crypt_key(&crypt_info, &key[0]); pgp_encrypt_init(&crypt_info); pgp_write_se_ip_pktset(encr_output, payload_mem->buf, payload_mem->length, &crypt_info); crypt_info.decrypt_finish(&crypt_info); } /* done with symmetric key block */ pgp_writer_close(encr_output); *ret_ctext_armored = dc_null_terminate((const char*)encr_mem->buf, encr_mem->length); //printf("\n~~~~~~~~~~~~~~~~~~~~SYMMETRICALLY ENCRYPTED~~~~~~~~~~~~~~~~~~~~\n%s~~~~~~~~~~~~~~~~~~~~/SYMMETRICALLY ENCRYPTED~~~~~~~~~~~~~~~~~~~~\n",encr_string); // DEBUG OUTPUT success = 1; cleanup: if (payload_output) { pgp_output_delete(payload_output); } if (payload_mem) { pgp_memory_free(payload_mem); } if (encr_output) { pgp_output_delete(encr_output); } if (encr_mem) { pgp_memory_free(encr_mem); } free(key); return success; } #endif // !DC_USE_RPGP #ifdef DC_USE_RPGP int dc_pgp_symm_decrypt(dc_context_t* context, const char* passphrase, const void* ctext, size_t ctext_bytes, void** ret_plain_text, size_t* ret_plain_bytes) { int success = 0; rpgp_message* encrypted = NULL; rpgp_message* decrypted = NULL; encrypted = rpgp_msg_from_bytes(ctext, ctext_bytes); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } decrypted = rpgp_msg_decrypt_with_password(encrypted, passphrase); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } rpgp_cvec* decrypted_bytes = rpgp_msg_to_bytes(decrypted); if (dc_pgp_handle_rpgp_error(context)) { goto cleanup; } *ret_plain_text = (void*)rpgp_cvec_data(decrypted_bytes); *ret_plain_bytes = rpgp_cvec_len(decrypted_bytes); // No drop as we only remove the struct free(decrypted_bytes); success = 1; cleanup: if (encrypted) { rpgp_msg_drop(encrypted); } if (decrypted) { rpgp_msg_drop(decrypted); } return success; } #else // !DC_USE_RPGP int dc_pgp_symm_decrypt(dc_context_t* context, const char* passphrase, const void* ctext, size_t ctext_bytes, void** ret_plain_text, size_t* ret_plain_bytes) { int success = 0; pgp_io_t io; pgp_memory_t* outmem = NULL; memset(&io, 0, sizeof(pgp_io_t)); io.outs = stdout; io.errs = stderr; io.res = stderr; if ((outmem=pgp_decrypt_buf(&io, ctext, ctext_bytes, NULL, NULL, 0, 0, passphrase))==NULL) { goto cleanup; } *ret_plain_text = outmem->buf; *ret_plain_bytes = outmem->length; free(outmem); /* do not use pgp_memory_free() as we took ownership of the buffer */ outmem = NULL; success = 1; cleanup: if (outmem) { pgp_memory_free(outmem); } return success; } #endif // !DC_USE_RPGP ``` Filename: dc_qr.c ```c #include #include #include "dc_context.h" #include "dc_apeerstate.h" #define MAILTO_SCHEME "mailto:" #define MATMSG_SCHEME "MATMSG:" #define VCARD_BEGIN "BEGIN:VCARD" #define SMTP_SCHEME "SMTP:" /** * Check a scanned QR code. * The function should be called after a QR code is scanned. * The function takes the raw text scanned and checks what can be done with it. * * The QR code state is returned in dc_lot_t::state as: * * - DC_QR_ASK_VERIFYCONTACT with dc_lot_t::id=Contact ID * - DC_QR_ASK_VERIFYGROUP withdc_lot_t::text1=Group name * - DC_QR_FPR_OK with dc_lot_t::id=Contact ID * - DC_QR_FPR_MISMATCH with dc_lot_t::id=Contact ID * - DC_QR_FPR_WITHOUT_ADDR with dc_lot_t::test1=Formatted fingerprint * - DC_QR_ADDR with dc_lot_t::id=Contact ID * - DC_QR_TEXT with dc_lot_t::text1=Text * - DC_QR_URL with dc_lot_t::text1=URL * - DC_QR_ERROR with dc_lot_t::text1=Error string * * * @memberof dc_context_t * @param context The context object. * @param qr The text of the scanned QR code. * @return Parsed QR code as an dc_lot_t object. The returned object must be * freed using dc_lot_unref() after usage. */ dc_lot_t* dc_check_qr(dc_context_t* context, const char* qr) { char* payload = NULL; char* addr = NULL; // must be normalized, if set char* fingerprint = NULL; // must be normalized, if set char* name = NULL; char* invitenumber = NULL; char* auth = NULL; dc_apeerstate_t* peerstate = dc_apeerstate_new(context); dc_lot_t* qr_parsed = dc_lot_new(); uint32_t chat_id = 0; char* device_msg = NULL; char* grpid = NULL; char* grpname = NULL; qr_parsed->state = 0; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || qr==NULL) { goto cleanup; } dc_log_info(context, 0, "Scanned QR code: %s", qr); /* split parameters from the qr code ------------------------------------ */ if (strncasecmp(qr, DC_OPENPGP4FPR_SCHEME, strlen(DC_OPENPGP4FPR_SCHEME))==0) { /* scheme: OPENPGP4FPR:FINGERPRINT#a=ADDR&n=NAME&i=INVITENUMBER&s=AUTH or: OPENPGP4FPR:FINGERPRINT#a=ADDR&g=GROUPNAME&x=GROUPID&i=INVITENUMBER&s=AUTH */ payload = dc_strdup(&qr[strlen(DC_OPENPGP4FPR_SCHEME)]); char* fragment = strchr(payload, '#'); /* must not be freed, only a pointer inside payload */ if (fragment) { *fragment = 0; fragment++; dc_param_t* param = dc_param_new(); dc_param_set_urlencoded(param, fragment); addr = dc_param_get(param, 'a', NULL); if (addr) { char* urlencoded = dc_param_get(param, 'n', NULL); if(urlencoded) { name = dc_urldecode(urlencoded); dc_normalize_name(name); free(urlencoded); } invitenumber = dc_param_get(param, 'i', NULL); auth = dc_param_get(param, 's', NULL); grpid = dc_param_get(param, 'x', NULL); if (grpid) { urlencoded = dc_param_get(param, 'g', NULL); if (urlencoded) { grpname = dc_urldecode(urlencoded); free(urlencoded); } } } dc_param_unref(param); } fingerprint = dc_normalize_fingerprint(payload); } else if (strncasecmp(qr, MAILTO_SCHEME, strlen(MAILTO_SCHEME))==0) { /* scheme: mailto:addr...?subject=...&body=... */ payload = dc_strdup(&qr[strlen(MAILTO_SCHEME)]); char* query = strchr(payload, '?'); /* must not be freed, only a pointer inside payload */ if (query) { *query = 0; } addr = dc_strdup(payload); } else if (strncasecmp(qr, SMTP_SCHEME, strlen(SMTP_SCHEME))==0) { /* scheme: `SMTP:addr...:subject...:body...` */ payload = dc_strdup(&qr[strlen(SMTP_SCHEME)]); char* colon = strchr(payload, ':'); /* must not be freed, only a pointer inside payload */ if (colon) { *colon = 0; } addr = dc_strdup(payload); } else if (strncasecmp(qr, MATMSG_SCHEME, strlen(MATMSG_SCHEME))==0) { /* scheme: `MATMSG:TO:addr...;SUB:subject...;BODY:body...;` - there may or may not be linebreaks after the fields */ char* to = strstr(qr, "TO:"); /* does not work when the text `TO:` is used in subject/body _and_ TO: is not the first field. we ignore this case. */ if (to) { addr = dc_strdup(&to[3]); char* semicolon = strchr(addr, ';'); if (semicolon) { *semicolon = 0; } } else { qr_parsed->state = DC_QR_ERROR; qr_parsed->text1 = dc_strdup("Bad e-mail address."); goto cleanup; } } else if (strncasecmp(qr, VCARD_BEGIN, strlen(VCARD_BEGIN))==0) { /* scheme: `VCARD:BEGIN\nN:last name;first name;...;\nEMAIL:addr...;` */ carray* lines = dc_split_into_lines(qr); for (int i = 0; i < carray_count(lines); i++) { char* key = (char*)carray_get(lines, i); dc_trim(key); char* value = strchr(key, ':'); if (value) { *value = 0; value++; char* semicolon = strchr(key, ';'); if (semicolon) { *semicolon = 0; } /* handle `EMAIL;type=work:` stuff */ if (strcasecmp(key, "EMAIL")==0) { semicolon = strchr(value, ';'); if (semicolon) { *semicolon = 0; } /* use the first EMAIL */ addr = dc_strdup(value); } else if (strcasecmp(key, "N")==0) { semicolon = strchr(value, ';'); if (semicolon) { semicolon = strchr(semicolon+1, ';'); if (semicolon) { *semicolon = 0; } } /* the N format is `lastname;prename;wtf;title` - skip everything after the second semicolon */ name = dc_strdup(value); dc_str_replace(&name, ";", ","); /* the format "lastname,prename" is handled by dc_normalize_name() */ dc_normalize_name(name); } } } dc_free_splitted_lines(lines); } /* check the paramters ---------------------- */ if (addr) { char* temp = dc_urldecode(addr); free(addr); addr = temp; /* urldecoding is needed at least for OPENPGP4FPR but should not hurt in the other cases */ temp = dc_addr_normalize(addr); free(addr); addr = temp; if (!dc_may_be_valid_addr(addr)) { qr_parsed->state = DC_QR_ERROR; qr_parsed->text1 = dc_strdup("Bad e-mail address."); goto cleanup; } } if (fingerprint) { if (strlen(fingerprint) != 40) { qr_parsed->state = DC_QR_ERROR; qr_parsed->text1 = dc_strdup("Bad fingerprint length in QR code."); goto cleanup; } } /* let's see what we can do with the parameters ---------------------------------------------- */ if (fingerprint) { /* fingerprint set ... */ if (addr==NULL || invitenumber==NULL || auth==NULL) { // _only_ fingerprint set ... // (we could also do this before/instead of a secure-join, however, this may require complicated questions in the ui) if (dc_apeerstate_load_by_fingerprint(peerstate, context->sql, fingerprint)) { qr_parsed->state = DC_QR_FPR_OK; qr_parsed->id = dc_add_or_lookup_contact(context, NULL, peerstate->addr, DC_ORIGIN_UNHANDLED_QR_SCAN, NULL); dc_create_or_lookup_nchat_by_contact_id(context, qr_parsed->id, DC_CHAT_DEADDROP_BLOCKED, &chat_id, NULL); device_msg = dc_mprintf("%s verified.", peerstate->addr); } else { qr_parsed->text1 = dc_format_fingerprint(fingerprint); qr_parsed->state = DC_QR_FPR_WITHOUT_ADDR; } } else { // fingerprint + addr set, secure-join requested // do not comapre the fingerprint already - it may have changed - errors are catched later more proberly. // (theroretically, there is also the state "addr=set, fingerprint=set, invitenumber=0", however, currently, we won't get into this state) if (grpid && grpname) { qr_parsed->state = DC_QR_ASK_VERIFYGROUP; qr_parsed->text1 = dc_strdup(grpname); qr_parsed->text2 = dc_strdup(grpid); } else { qr_parsed->state = DC_QR_ASK_VERIFYCONTACT; } qr_parsed->id = dc_add_or_lookup_contact(context, name, addr, DC_ORIGIN_UNHANDLED_QR_SCAN, NULL); qr_parsed->fingerprint = dc_strdup(fingerprint); qr_parsed->invitenumber = dc_strdup(invitenumber); qr_parsed->auth = dc_strdup(auth); } } else if (addr) { qr_parsed->state = DC_QR_ADDR; qr_parsed->id = dc_add_or_lookup_contact(context, name, addr, DC_ORIGIN_UNHANDLED_QR_SCAN, NULL); } else if (strstr(qr, "http://")==qr || strstr(qr, "https://")==qr) { qr_parsed->state = DC_QR_URL; qr_parsed->text1 = dc_strdup(qr); } else { qr_parsed->state = DC_QR_TEXT; qr_parsed->text1 = dc_strdup(qr); } if (device_msg) { dc_add_device_msg(context, chat_id, device_msg); } cleanup: free(addr); free(fingerprint); dc_apeerstate_unref(peerstate); free(payload); free(name); free(invitenumber); free(auth); free(device_msg); free(grpname); free(grpid); return qr_parsed; } ``` Filename: dc_receive_imf.c ```c #include #include "dc_context.h" #ifdef DC_USE_RPGP #include #else #include #endif #include "dc_mimeparser.h" #include "dc_mimefactory.h" #include "dc_imap.h" #include "dc_job.h" #include "dc_array.h" #include "dc_apeerstate.h" /******************************************************************************* * Add contacts to database on receiving messages ******************************************************************************/ static void add_or_lookup_contact_by_addr(dc_context_t* context, const char* display_name_enc, const char* addr_spec, int origin, dc_array_t* ids, int* check_self) { /* is addr_spec equal to SELF? */ int dummy = 0; if (check_self==NULL) { check_self = &dummy; } if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || addr_spec==NULL) { return; } *check_self = 0; char* self_addr = dc_sqlite3_get_config(context->sql, "configured_addr", ""); if (dc_addr_cmp(self_addr, addr_spec)==0) { *check_self = 1; } free(self_addr); if (*check_self) { return; } /* add addr_spec if missing, update otherwise */ char* display_name_dec = NULL; if (display_name_enc) { display_name_dec = dc_decode_header_words(display_name_enc); dc_normalize_name(display_name_dec); } uint32_t row_id = dc_add_or_lookup_contact(context, display_name_dec /*can be NULL*/, addr_spec, origin, NULL); free(display_name_dec); if (row_id) { if (!dc_array_search_id(ids, row_id, NULL)) { dc_array_add_id(ids, row_id); } } } static void dc_add_or_lookup_contacts_by_mailbox_list(dc_context_t* context, const struct mailimf_mailbox_list* mb_list, int origin, dc_array_t* ids, int* check_self) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || mb_list==NULL) { return; } for (clistiter* cur = clist_begin(mb_list->mb_list); cur!=NULL ; cur=clist_next(cur)) { struct mailimf_mailbox* mb = (struct mailimf_mailbox*)clist_content(cur); if (mb) { add_or_lookup_contact_by_addr(context, mb->mb_display_name, mb->mb_addr_spec, origin, ids, check_self); } } } static void dc_add_or_lookup_contacts_by_address_list(dc_context_t* context, const struct mailimf_address_list* adr_list, int origin, dc_array_t* ids, int* check_self) { if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || adr_list==NULL /*may be NULL eg. if bcc is given as `Bcc: \n` in the header */) { return; } for (clistiter* cur = clist_begin(adr_list->ad_list); cur!=NULL ; cur=clist_next(cur)) { struct mailimf_address* adr = (struct mailimf_address*)clist_content(cur); if (adr) { if (adr->ad_type==MAILIMF_ADDRESS_MAILBOX) { struct mailimf_mailbox* mb = adr->ad_data.ad_mailbox; /* can be NULL */ if (mb) { add_or_lookup_contact_by_addr(context, mb->mb_display_name, mb->mb_addr_spec, origin, ids, check_self); } } else if (adr->ad_type==MAILIMF_ADDRESS_GROUP) { struct mailimf_group* group = adr->ad_data.ad_group; /* can be NULL */ if (group && group->grp_mb_list /*can be NULL*/) { dc_add_or_lookup_contacts_by_mailbox_list(context, group->grp_mb_list, origin, ids, check_self); } } } } } /******************************************************************************* * Check if a message is a reply to a known message (messenger or non-messenger) ******************************************************************************/ static int is_known_rfc724_mid(dc_context_t* context, const char* rfc724_mid) { int is_known = 0; if (rfc724_mid) { sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "SELECT m.id FROM msgs m " " LEFT JOIN chats c ON m.chat_id=c.id " " WHERE m.rfc724_mid=? " " AND m.chat_id>" DC_STRINGIFY(DC_CHAT_ID_LAST_SPECIAL) " AND c.blocked=0;"); sqlite3_bind_text(stmt, 1, rfc724_mid, -1, SQLITE_STATIC); if (sqlite3_step(stmt)==SQLITE_ROW) { is_known = 1; } sqlite3_finalize(stmt); } return is_known; } static int is_known_rfc724_mid_in_list(dc_context_t* context, const clist* mid_list) { if (mid_list) { clistiter* cur; for (cur = clist_begin(mid_list); cur!=NULL ; cur=clist_next(cur)) { if (is_known_rfc724_mid(context, clist_content(cur))) { return 1; } } } return 0; } static int dc_is_reply_to_known_message(dc_context_t* context, dc_mimeparser_t* mime_parser) { /* check if the message is a reply to a known message; the replies are identified by the Message-ID from `In-Reply-To`/`References:` (to support non-Delta-Clients) or from `Chat-Predecessor:` (Delta clients, see comment in dc_chat.c) */ struct mailimf_optional_field* optional_field = NULL; if ((optional_field=dc_mimeparser_lookup_optional_field(mime_parser, "Chat-Predecessor"))!=NULL) { if (is_known_rfc724_mid(context, optional_field->fld_value)) { return 1; } } struct mailimf_field* field = NULL; if ((field=dc_mimeparser_lookup_field(mime_parser, "In-Reply-To"))!=NULL && field->fld_type==MAILIMF_FIELD_IN_REPLY_TO) { struct mailimf_in_reply_to* fld_in_reply_to = field->fld_data.fld_in_reply_to; if (fld_in_reply_to) { if (is_known_rfc724_mid_in_list(context, field->fld_data.fld_in_reply_to->mid_list)) { return 1; } } } if ((field=dc_mimeparser_lookup_field(mime_parser, "References"))!=NULL && field->fld_type==MAILIMF_FIELD_REFERENCES) { struct mailimf_references* fld_references = field->fld_data.fld_references; if (fld_references) { if (is_known_rfc724_mid_in_list(context, field->fld_data.fld_references->mid_list)) { return 1; } } } return 0; } /******************************************************************************* * Check if a message is a reply to any messenger message ******************************************************************************/ static int is_msgrmsg_rfc724_mid(dc_context_t* context, const char* rfc724_mid) { int is_msgrmsg = 0; if (rfc724_mid) { sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "SELECT id FROM msgs " " WHERE rfc724_mid=? " " AND msgrmsg!=0 " " AND chat_id>" DC_STRINGIFY(DC_CHAT_ID_LAST_SPECIAL) ";"); sqlite3_bind_text(stmt, 1, rfc724_mid, -1, SQLITE_STATIC); if (sqlite3_step(stmt)==SQLITE_ROW) { is_msgrmsg = 1; } sqlite3_finalize(stmt); } return is_msgrmsg; } static int is_msgrmsg_rfc724_mid_in_list(dc_context_t* context, const clist* mid_list) { if (mid_list) { for (clistiter* cur = clist_begin(mid_list); cur!=NULL ; cur=clist_next(cur)) { if (is_msgrmsg_rfc724_mid(context, clist_content(cur))) { return 1; } } } return 0; } static int dc_is_reply_to_messenger_message(dc_context_t* context, dc_mimeparser_t* mime_parser) { /* function checks, if the message defined by mime_parser references a message send by us from Delta Chat. This is similar to is_reply_to_known_message() but - checks also if any of the referenced IDs are send by a messenger - it is okay, if the referenced messages are moved to trash here - no check for the Chat-* headers (function is only called if it is no messenger message itself) */ struct mailimf_field* field = NULL; if ((field=dc_mimeparser_lookup_field(mime_parser, "In-Reply-To"))!=NULL && field->fld_type==MAILIMF_FIELD_IN_REPLY_TO) { struct mailimf_in_reply_to* fld_in_reply_to = field->fld_data.fld_in_reply_to; if (fld_in_reply_to) { if (is_msgrmsg_rfc724_mid_in_list(context, field->fld_data.fld_in_reply_to->mid_list)) { return 1; } } } if ((field=dc_mimeparser_lookup_field(mime_parser, "References"))!=NULL && field->fld_type==MAILIMF_FIELD_REFERENCES) { struct mailimf_references* fld_references = field->fld_data.fld_references; if (fld_references) { if (is_msgrmsg_rfc724_mid_in_list(context, field->fld_data.fld_references->mid_list)) { return 1; } } } return 0; } /******************************************************************************* * Misc. Tools ******************************************************************************/ static void calc_timestamps(dc_context_t* context, uint32_t chat_id, uint32_t from_id, time_t message_timestamp, int is_fresh_msg, time_t* sort_timestamp, time_t* sent_timestamp, time_t* rcvd_timestamp) { *rcvd_timestamp = time(NULL); *sent_timestamp = message_timestamp; if (*sent_timestamp > *rcvd_timestamp /* no sending times in the future */) { *sent_timestamp = *rcvd_timestamp; } *sort_timestamp = message_timestamp; /* truncatd below to smeared time (not to _now_ to keep the order) */ /* use the last message from another user (including SELF) as the MINIMUM for sort_timestamp; this is to force fresh messages popping up at the end of the list. (we do this check only for fresh messages, other messages may pop up whereever, this may happen eg. when restoring old messages or synchronizing different clients) */ if (is_fresh_msg) { sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, "SELECT MAX(timestamp) FROM msgs WHERE chat_id=? and from_id!=? AND timestamp>=?"); sqlite3_bind_int (stmt, 1, chat_id); sqlite3_bind_int (stmt, 2, from_id); sqlite3_bind_int64(stmt, 3, *sort_timestamp); if (sqlite3_step(stmt)==SQLITE_ROW) { time_t last_msg_time = sqlite3_column_int64(stmt, 0); if (last_msg_time > 0 /* may happen as we do not check against sqlite3_column_type()!=SQLITE_NULL */) { if (*sort_timestamp <= last_msg_time) { *sort_timestamp = last_msg_time+1; /* this may result in several incoming messages having the same one-second-after-the-last-other-message-timestamp. however, this is no big deal as we do not try to recrete the order of bad-date-messages and as we always order by ID as second criterion */ } } } sqlite3_finalize(stmt); } /* use the (smeared) current time as the MAXIMUM */ if (*sort_timestamp >= dc_smeared_time(context)) { *sort_timestamp = dc_create_smeared_timestamp(context); } } static dc_array_t* search_chat_ids_by_contact_ids(dc_context_t* context, const dc_array_t* unsorted_contact_ids) { /* searches chat_id's by the given contact IDs, may return zero, one or more chat_id's */ sqlite3_stmt* stmt = NULL; dc_array_t* contact_ids = dc_array_new(context, 23); char* contact_ids_str = NULL; char* q3 = NULL; dc_array_t* chat_ids = dc_array_new(context, 23); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } /* copy array, remove duplicates and SELF, sort by ID */ { int i, iCnt = dc_array_get_cnt(unsorted_contact_ids); if (iCnt <= 0) { goto cleanup; } for (i = 0; i < iCnt; i++) { uint32_t curr_id = dc_array_get_id(unsorted_contact_ids, i); if (curr_id!=DC_CONTACT_ID_SELF && !dc_array_search_id(contact_ids, curr_id, NULL)) { dc_array_add_id(contact_ids, curr_id); } } if (dc_array_get_cnt(contact_ids)==0) { goto cleanup; } dc_array_sort_ids(contact_ids); /* for easy comparison, we also sort the sql result below */ } /* collect all possible chats with the contact count as the data (as contact_ids have no doubles, this is sufficient) */ contact_ids_str = dc_array_get_string(contact_ids, ","); q3 = sqlite3_mprintf("SELECT DISTINCT cc.chat_id, cc.contact_id " " FROM chats_contacts cc " " LEFT JOIN chats c ON c.id=cc.chat_id " " WHERE cc.chat_id IN(SELECT chat_id FROM chats_contacts WHERE contact_id IN(%s))" " AND c.type=" DC_STRINGIFY(DC_CHAT_TYPE_GROUP) /* no verified groups and no single chats (which are equal to a group with a single member and without SELF) */ " AND cc.contact_id!=" DC_STRINGIFY(DC_CONTACT_ID_SELF) /* ignore SELF, we've also removed it above - if the user has left the group, it is still the same group */ " ORDER BY cc.chat_id, cc.contact_id;", contact_ids_str); stmt = dc_sqlite3_prepare(context->sql, q3); { uint32_t last_chat_id = 0, matches = 0, mismatches = 0; while (sqlite3_step(stmt)==SQLITE_ROW) { uint32_t chat_id = sqlite3_column_int(stmt, 0); uint32_t contact_id = sqlite3_column_int(stmt, 1); if (chat_id!=last_chat_id) { if (matches==dc_array_get_cnt(contact_ids) && mismatches==0) { dc_array_add_id(chat_ids, last_chat_id); } last_chat_id = chat_id; matches = 0; mismatches = 0; } if (contact_id==dc_array_get_id(contact_ids, matches)) { matches++; } else { mismatches++; } } if (matches==dc_array_get_cnt(contact_ids) && mismatches==0) { dc_array_add_id(chat_ids, last_chat_id); } } cleanup: sqlite3_finalize(stmt); free(contact_ids_str); dc_array_unref(contact_ids); sqlite3_free(q3); return chat_ids; } static char* create_adhoc_grp_id(dc_context_t* context, dc_array_t* member_ids /*including SELF*/) { /* algorithm: - sort normalized, lowercased, e-mail addresses alphabetically - put all e-mail addresses into a single string, separate the addresss by a single comma - sha-256 this string (without possibly terminating null-characters) - encode the first 64 bits of the sha-256 output as lowercase hex (results in 16 characters from the set [0-9a-f]) */ dc_array_t* member_addrs = dc_array_new(context, 23); char* member_ids_str = dc_array_get_string(member_ids, ","); sqlite3_stmt* stmt = NULL; char* q3 = NULL; char* addr = NULL; int i = 0; int iCnt = 0; char* ret = NULL; dc_strbuilder_t member_cs; dc_strbuilder_init(&member_cs, 0); /* collect all addresses and sort them */ q3 = sqlite3_mprintf("SELECT addr FROM contacts WHERE id IN(%s) AND id!=" DC_STRINGIFY(DC_CONTACT_ID_SELF), member_ids_str); stmt = dc_sqlite3_prepare(context->sql, q3); addr = dc_sqlite3_get_config(context->sql, "configured_addr", "no-self"); dc_strlower_in_place(addr); dc_array_add_ptr(member_addrs, addr); while (sqlite3_step(stmt)==SQLITE_ROW) { addr = dc_strdup((const char*)sqlite3_column_text(stmt, 0)); dc_strlower_in_place(addr); dc_array_add_ptr(member_addrs, addr); } dc_array_sort_strings(member_addrs); /* build a single, comma-separated (cs) string from all addresses */ iCnt = dc_array_get_cnt(member_addrs); for (i = 0; i < iCnt; i++) { if (i) { dc_strbuilder_cat(&member_cs, ","); } dc_strbuilder_cat(&member_cs, (const char*)dc_array_get_ptr(member_addrs, i)); } /* make sha-256 from the string */ #ifdef DC_USE_RPGP rpgp_cvec* binary_hash = rpgp_hash_sha256((const uint8_t*)member_cs.buf, strlen(member_cs.buf)); if (binary_hash==NULL) { goto cleanup; } ret = calloc(1, 256); if (ret==NULL) { goto cleanup; } for (i = 0; i < 8; i++) { sprintf(&ret[i*2], "%02x", (int)rpgp_cvec_data(binary_hash)[i]); } rpgp_cvec_drop(binary_hash); #else uint8_t* binary_hash = NULL; { pgp_hash_t hasher; pgp_hash_sha256(&hasher); hasher.init(&hasher); hasher.add(&hasher, (const uint8_t*)member_cs.buf, strlen(member_cs.buf)); binary_hash = malloc(hasher.size); hasher.finish(&hasher, binary_hash); } /* output the first 8 bytes as 16 hex-characters - CAVE: if the lenght changes here, also adapt dc_extract_grpid_from_rfc724_mid() */ ret = calloc(1, 256); if (ret==NULL) { goto cleanup; } for (i = 0; i < 8; i++) { sprintf(&ret[i*2], "%02x", (int)binary_hash[i]); } free(binary_hash); #endif cleanup: dc_array_free_ptr(member_addrs); dc_array_unref(member_addrs); free(member_ids_str); sqlite3_finalize(stmt); sqlite3_free(q3); free(member_cs.buf); return ret; } static uint32_t create_group_record(dc_context_t* context, const char* grpid, const char* grpname, int create_blocked, int create_verified) { uint32_t chat_id = 0; sqlite3_stmt* stmt = NULL; stmt = dc_sqlite3_prepare(context->sql, "INSERT INTO chats (type, name, grpid, blocked) VALUES(?, ?, ?, ?);"); sqlite3_bind_int (stmt, 1, create_verified? DC_CHAT_TYPE_VERIFIED_GROUP : DC_CHAT_TYPE_GROUP); sqlite3_bind_text(stmt, 2, grpname, -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 3, grpid, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 4, create_blocked); if (sqlite3_step(stmt)!=SQLITE_DONE) { goto cleanup; } chat_id = dc_sqlite3_get_rowid(context->sql, "chats", "grpid", grpid); cleanup: sqlite3_finalize(stmt); return chat_id; } /******************************************************************************* * Handle groups for received messages ******************************************************************************/ static void create_or_lookup_adhoc_group(dc_context_t* context, dc_mimeparser_t* mime_parser, int allow_creation, int create_blocked, int32_t from_id, const dc_array_t* to_ids,/*does not contain SELF*/ uint32_t* ret_chat_id, int* ret_chat_id_blocked) { /* if we're here, no grpid was found, check there is an existing ad-hoc group matching the to-list or if we can create one */ dc_array_t* member_ids = NULL; uint32_t chat_id = 0; int chat_id_blocked = 0; int i = 0; dc_array_t* chat_ids = NULL; char* chat_ids_str = NULL; char* q3 = NULL; sqlite3_stmt* stmt = NULL; char* grpid = NULL; char* grpname = NULL; /* build member list from the given ids */ if (dc_array_get_cnt(to_ids)==0 || dc_mimeparser_is_mailinglist_message(mime_parser)) { goto cleanup; /* too few contacts or a mailinglist */ } member_ids = dc_array_duplicate(to_ids); if (!dc_array_search_id(member_ids, from_id, NULL)) { dc_array_add_id(member_ids, from_id); } if (!dc_array_search_id(member_ids, DC_CONTACT_ID_SELF, NULL)) { dc_array_add_id(member_ids, DC_CONTACT_ID_SELF); } if (dc_array_get_cnt(member_ids) < 3) { goto cleanup; /* too few contacts given */ } /* check if the member list matches other chats, if so, choose the one with the most recent activity */ chat_ids = search_chat_ids_by_contact_ids(context, member_ids); if (dc_array_get_cnt(chat_ids)>0) { chat_ids_str = dc_array_get_string(chat_ids, ","); q3 = sqlite3_mprintf("SELECT c.id, c.blocked " " FROM chats c " " LEFT JOIN msgs m ON m.chat_id=c.id " " WHERE c.id IN(%s) " " ORDER BY m.timestamp DESC, m.id DESC " " LIMIT 1;", chat_ids_str); stmt = dc_sqlite3_prepare(context->sql, q3); if (sqlite3_step(stmt)==SQLITE_ROW) { chat_id = sqlite3_column_int(stmt, 0); chat_id_blocked = sqlite3_column_int(stmt, 1); goto cleanup; /* success, chat found */ } } if (!allow_creation) { goto cleanup; } /* we do not check if the message is a reply to another group, this may result in chats with unclear member list. instead we create a new group in the following lines ... */ /* create a new ad-hoc group - there is no need to check if this group exists; otherwise we would have catched it above */ if ((grpid = create_adhoc_grp_id(context, member_ids))==NULL) { goto cleanup; } /* use subject as initial chat name */ if (mime_parser->subject && mime_parser->subject[0]) { grpname = dc_strdup(mime_parser->subject); } else { grpname = dc_stock_str_repl_int(context, DC_STR_MEMBER, dc_array_get_cnt(member_ids)); } /* create group record */ chat_id = create_group_record(context, grpid, grpname, create_blocked, 0); chat_id_blocked = create_blocked; for (i = 0; i < dc_array_get_cnt(member_ids); i++) { dc_add_to_chat_contacts_table(context, chat_id, dc_array_get_id(member_ids, i)); } context->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0); cleanup: dc_array_unref(member_ids); dc_array_unref(chat_ids); free(chat_ids_str); free(grpid); free(grpname); sqlite3_finalize(stmt); sqlite3_free(q3); if (ret_chat_id) { *ret_chat_id = chat_id; } if (ret_chat_id_blocked) { *ret_chat_id_blocked = chat_id_blocked; } } static int check_verified_properties(dc_context_t* context, dc_mimeparser_t* mimeparser, uint32_t from_id, const dc_array_t* to_ids, char** failure_reason) { int everythings_okay = 0; dc_contact_t* contact = dc_contact_new(context); dc_apeerstate_t* peerstate = dc_apeerstate_new(context); char* to_ids_str = NULL; char* q3 = NULL; sqlite3_stmt* stmt = NULL; #define VERIFY_FAIL(a) \ *failure_reason = dc_mprintf("%s. See \"Info\" for details.", (a)); \ dc_log_warning(context, 0, *failure_reason); if (!dc_contact_load_from_db(contact, context->sql, from_id)) { VERIFY_FAIL("Internal Error; cannot load contact.") goto cleanup; } // ensure, the message is encrypted if (!mimeparser->e2ee_helper->encrypted) { VERIFY_FAIL("This message is not encrypted.") goto cleanup; } // ensure, the contact is verified // and the message is signed with a verified key of the sender. // this check is skipped for SELF as there is no proper SELF-peerstate // and results in group-splits otherwise. if (from_id!=DC_CONTACT_ID_SELF) { if (!dc_apeerstate_load_by_addr(peerstate, context->sql, contact->addr) || dc_contact_is_verified_ex(contact, peerstate) != DC_BIDIRECT_VERIFIED) { VERIFY_FAIL("The sender of this message is not verified.") goto cleanup; } if (!dc_apeerstate_has_verified_key(peerstate, mimeparser->e2ee_helper->signatures)) { VERIFY_FAIL("The message was sent with non-verified encryption.") goto cleanup; } } // check that all members are verified. // if a verification is missing, check if this was just gossiped - as we've verified the sender, we verify the member then. to_ids_str = dc_array_get_string(to_ids, ","); q3 = sqlite3_mprintf("SELECT c.addr, LENGTH(ps.verified_key_fingerprint) " " FROM contacts c " " LEFT JOIN acpeerstates ps ON c.addr=ps.addr " " WHERE c.id IN(%s) ", to_ids_str); stmt = dc_sqlite3_prepare(context->sql, q3); while (sqlite3_step(stmt)==SQLITE_ROW) { const char* to_addr = (const char*)sqlite3_column_text(stmt, 0); int is_verified = sqlite3_column_int (stmt, 1); if (dc_hash_find_str(mimeparser->e2ee_helper->gossipped_addr, to_addr) && dc_apeerstate_load_by_addr(peerstate, context->sql, to_addr)) { // if we're here, we know the gossip key is verified: // - use the gossip-key as verified-key if there is no verified-key // - OR if the verified-key does not match public-key or gossip-key // (otherwise a verified key can _only_ be updated through QR scan which might be annoying, // see https://github.com/nextleap-project/countermitm/issues/46 for a discussion about this point) if (!is_verified || (strcmp(peerstate->verified_key_fingerprint, peerstate->public_key_fingerprint)!=0 && strcmp(peerstate->verified_key_fingerprint, peerstate->gossip_key_fingerprint)!=0)) { dc_log_info(context, 0, "%s has verfied %s.", contact->addr, to_addr); dc_apeerstate_set_verified(peerstate, DC_PS_GOSSIP_KEY, peerstate->gossip_key_fingerprint, DC_BIDIRECT_VERIFIED); dc_apeerstate_save_to_db(peerstate, context->sql, 0); is_verified = 1; } } if (!is_verified) { char* err = dc_mprintf("%s is not a member of this verified group.", to_addr); VERIFY_FAIL(err) free(err); goto cleanup; } } // it's up to the caller to check if the sender is a member of the group // (we do this for both, verified and unverified group, so we do not check this here) everythings_okay = 1; cleanup: sqlite3_finalize(stmt); dc_contact_unref(contact); dc_apeerstate_unref(peerstate); free(to_ids_str); sqlite3_free(q3); return everythings_okay; } static void set_better_msg(dc_mimeparser_t* mime_parser, char** better_msg) { if (*better_msg && carray_count(mime_parser->parts)>0) { dc_mimepart_t* part = (dc_mimepart_t*)carray_get(mime_parser->parts, 0); if (part->type==DC_MSG_TEXT) { free(part->msg); part->msg = *better_msg; *better_msg = NULL; } } } /* the function tries extracts the group-id from the message and returns the corresponding chat_id. If the chat_id is not existant, it is created. If the message contains groups commands (name, profile image, changed members), they are executed as well. if no group-id could be extracted from the message, create_or_lookup_adhoc_group() is called which tries to create or find out the chat_id by: - is there a group with the same recipients? if so, use this (if there are multiple, use the most recent one) - create an ad-hoc group based on the recipient list So when the function returns, the caller has the group id matching the current state of the group. */ static void create_or_lookup_group(dc_context_t* context, dc_mimeparser_t* mime_parser, int allow_creation, int create_blocked, int32_t from_id, const dc_array_t* to_ids, uint32_t* ret_chat_id, int* ret_chat_id_blocked) { uint32_t chat_id = 0; int chat_id_blocked = 0; int chat_id_verified = 0; char* grpid = NULL; char* grpname = NULL; sqlite3_stmt* stmt; int i = 0; int to_ids_cnt = dc_array_get_cnt(to_ids); char* self_addr = NULL; int recreate_member_list = 0; int send_EVENT_CHAT_MODIFIED = 0; char* X_MrRemoveFromGrp = NULL; /* pointer somewhere into mime_parser, must not be freed */ char* X_MrAddToGrp = NULL; /* pointer somewhere into mime_parser, must not be freed */ int X_MrGrpNameChanged = 0; const char* X_MrGrpImageChanged = NULL; char* better_msg = NULL; char* failure_reason = NULL; /* some preparations not really related to groups */ if (mime_parser->is_system_message==DC_CMD_LOCATION_STREAMING_ENABLED) { better_msg = dc_stock_system_msg(context, DC_STR_MSGLOCATIONENABLED, NULL, NULL, from_id); } set_better_msg(mime_parser, &better_msg); /* search the grpid in the header */ { struct mailimf_field* field = NULL; struct mailimf_optional_field* optional_field = NULL; if ((optional_field=dc_mimeparser_lookup_optional_field(mime_parser, "Chat-Group-ID"))!=NULL) { grpid = dc_strdup(optional_field->fld_value); } if (grpid==NULL) { if ((field=dc_mimeparser_lookup_field(mime_parser, "Message-ID"))!=NULL && field->fld_type==MAILIMF_FIELD_MESSAGE_ID) { struct mailimf_message_id* fld_message_id = field->fld_data.fld_message_id; if (fld_message_id) { grpid = dc_extract_grpid_from_rfc724_mid(fld_message_id->mid_value); } } if (grpid==NULL) { if ((field=dc_mimeparser_lookup_field(mime_parser, "In-Reply-To"))!=NULL && field->fld_type==MAILIMF_FIELD_IN_REPLY_TO) { struct mailimf_in_reply_to* fld_in_reply_to = field->fld_data.fld_in_reply_to; if (fld_in_reply_to) { grpid = dc_extract_grpid_from_rfc724_mid_list(fld_in_reply_to->mid_list); } } if (grpid==NULL) { if ((field=dc_mimeparser_lookup_field(mime_parser, "References"))!=NULL && field->fld_type==MAILIMF_FIELD_REFERENCES) { struct mailimf_references* fld_references = field->fld_data.fld_references; if (fld_references) { grpid = dc_extract_grpid_from_rfc724_mid_list(fld_references->mid_list); } } if (grpid==NULL) { create_or_lookup_adhoc_group(context, mime_parser, allow_creation, create_blocked, from_id, to_ids, &chat_id, &chat_id_blocked); goto cleanup; } } } } if ((optional_field=dc_mimeparser_lookup_optional_field(mime_parser, "Chat-Group-Name"))!=NULL) { grpname = dc_decode_header_words(optional_field->fld_value); /* this is no changed groupname message */ } if ((optional_field=dc_mimeparser_lookup_optional_field(mime_parser, "Chat-Group-Member-Removed"))!=NULL) { X_MrRemoveFromGrp = optional_field->fld_value; mime_parser->is_system_message = DC_CMD_MEMBER_REMOVED_FROM_GROUP; int left_group = (dc_lookup_contact_id_by_addr(context, X_MrRemoveFromGrp)==from_id); better_msg = dc_stock_system_msg(context, left_group? DC_STR_MSGGROUPLEFT : DC_STR_MSGDELMEMBER, X_MrRemoveFromGrp, NULL, from_id); } else if ((optional_field=dc_mimeparser_lookup_optional_field(mime_parser, "Chat-Group-Member-Added"))!=NULL) { X_MrAddToGrp = optional_field->fld_value; mime_parser->is_system_message = DC_CMD_MEMBER_ADDED_TO_GROUP; if ((optional_field=dc_mimeparser_lookup_optional_field(mime_parser, "Chat-Group-Image"))!=NULL) { X_MrGrpImageChanged = optional_field->fld_value; } better_msg = dc_stock_system_msg(context, DC_STR_MSGADDMEMBER, X_MrAddToGrp, NULL, from_id); } else if ((optional_field=dc_mimeparser_lookup_optional_field(mime_parser, "Chat-Group-Name-Changed"))!=NULL) { X_MrGrpNameChanged = 1; mime_parser->is_system_message = DC_CMD_GROUPNAME_CHANGED; better_msg = dc_stock_system_msg(context, DC_STR_MSGGRPNAME, optional_field->fld_value, grpname, from_id); } else if ((optional_field=dc_mimeparser_lookup_optional_field(mime_parser, "Chat-Group-Image"))!=NULL) { X_MrGrpImageChanged = optional_field->fld_value; mime_parser->is_system_message = DC_CMD_GROUPIMAGE_CHANGED; better_msg = dc_stock_system_msg(context, strcmp(X_MrGrpImageChanged, "0")==0? DC_STR_MSGGRPIMGDELETED : DC_STR_MSGGRPIMGCHANGED, NULL, NULL, from_id); } } set_better_msg(mime_parser, &better_msg); /* check, if we have a chat with this group ID */ if ((chat_id=dc_get_chat_id_by_grpid(context, grpid, &chat_id_blocked, &chat_id_verified))!=0) { if (chat_id_verified && !check_verified_properties(context, mime_parser, from_id, to_ids, &failure_reason)) { dc_mimeparser_repl_msg_by_error(mime_parser, failure_reason); } } /* check if the sender is a member of the existing group - if not, we'll recreate the group list */ if (chat_id!=0 && !dc_is_contact_in_chat(context, chat_id, from_id)) { recreate_member_list = 1; } /* check if the group does not exist but should be created */ int group_explicitly_left = dc_is_group_explicitly_left(context, grpid); self_addr = dc_sqlite3_get_config(context->sql, "configured_addr", ""); if (chat_id==0 && !dc_mimeparser_is_mailinglist_message(mime_parser) && grpid && grpname && X_MrRemoveFromGrp==NULL /*otherwise, a pending "quit" message may pop up*/ && (!group_explicitly_left || (X_MrAddToGrp&&dc_addr_cmp(self_addr,X_MrAddToGrp)==0)) /*re-create explicitly left groups only if ourself is re-added*/ ) { int create_verified = 0; if (dc_mimeparser_lookup_field(mime_parser, "Chat-Verified")) { create_verified = 1; if (!check_verified_properties(context, mime_parser, from_id, to_ids, &failure_reason)) { dc_mimeparser_repl_msg_by_error(mime_parser, failure_reason); } } if (!allow_creation) { goto cleanup; } chat_id = create_group_record(context, grpid, grpname, create_blocked, create_verified); chat_id_blocked = create_blocked; chat_id_verified = create_verified; recreate_member_list = 1; } /* again, check chat_id */ if (chat_id <= DC_CHAT_ID_LAST_SPECIAL) { chat_id = 0; if (group_explicitly_left) { chat_id = DC_CHAT_ID_TRASH; /* we got a message for a chat we've deleted - do not show this even as a normal chat */ } else { create_or_lookup_adhoc_group(context, mime_parser, allow_creation, create_blocked, from_id, to_ids, &chat_id, &chat_id_blocked); } goto cleanup; } /* execute group commands */ if (X_MrAddToGrp || X_MrRemoveFromGrp) { recreate_member_list = 1; } else if (X_MrGrpNameChanged && grpname && strlen(grpname) < 200) { stmt = dc_sqlite3_prepare(context->sql, "UPDATE chats SET name=? WHERE id=?;"); sqlite3_bind_text(stmt, 1, grpname, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 2, chat_id); sqlite3_step(stmt); sqlite3_finalize(stmt); context->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0); } if (X_MrGrpImageChanged) { int ok = 0; char* grpimage = NULL; if( strcmp(X_MrGrpImageChanged, "0")==0 ) { ok = 1; // group image deleted } else { for (int i = 0; i < carray_count(mime_parser->parts); i++) { dc_mimepart_t* part = (dc_mimepart_t*)carray_get(mime_parser->parts, i); if (part->type==DC_MSG_IMAGE) { grpimage = dc_param_get(part->param, DC_PARAM_FILE, NULL); ok = 1; // new group image set } } } if (ok) { dc_chat_t* chat = dc_chat_new(context); dc_log_info(context, 0, "New group image set to %s.", grpimage? "DELETED" : grpimage); dc_chat_load_from_db(chat, chat_id); dc_param_set(chat->param, DC_PARAM_PROFILE_IMAGE, grpimage/*may be NULL*/); dc_chat_update_param(chat); dc_chat_unref(chat); free(grpimage); send_EVENT_CHAT_MODIFIED = 1; } } /* add members to group/check members for recreation: we should add a timestamp */ if (recreate_member_list) { // TODO: the member list should only be recreated if the corresponding message is newer // than the one that is responsible for the current member list, see // https://github.com/deltachat/deltachat-core/issues/127 const char* skip = X_MrRemoveFromGrp? X_MrRemoveFromGrp : NULL; stmt = dc_sqlite3_prepare(context->sql, "DELETE FROM chats_contacts WHERE chat_id=?;"); sqlite3_bind_int (stmt, 1, chat_id); sqlite3_step(stmt); sqlite3_finalize(stmt); if (skip==NULL || dc_addr_cmp(self_addr, skip)!=0) { dc_add_to_chat_contacts_table(context, chat_id, DC_CONTACT_ID_SELF); } if (from_id > DC_CONTACT_ID_LAST_SPECIAL) { if (dc_addr_equals_contact(context, self_addr, from_id)==0 && (skip==NULL || dc_addr_equals_contact(context, skip, from_id)==0)) { dc_add_to_chat_contacts_table(context, chat_id, from_id); } } for (i = 0; i < to_ids_cnt; i++) { uint32_t to_id = dc_array_get_id(to_ids, i); /* to_id is only once in to_ids and is non-special */ if (dc_addr_equals_contact(context, self_addr, to_id)==0 && (skip==NULL || dc_addr_equals_contact(context, skip, to_id)==0)) { dc_add_to_chat_contacts_table(context, chat_id, to_id); } } send_EVENT_CHAT_MODIFIED = 1; dc_reset_gossiped_timestamp(context, chat_id); } if (send_EVENT_CHAT_MODIFIED) { context->cb(context, DC_EVENT_CHAT_MODIFIED, chat_id, 0); } /* check the number of receivers - the only critical situation is if the user hits "Reply" instead of "Reply all" in a non-messenger-client */ if (to_ids_cnt==1 && mime_parser->is_send_by_messenger==0) { int is_contact_cnt = dc_get_chat_contact_cnt(context, chat_id); if (is_contact_cnt > 3 /* to_ids_cnt==1 may be "From: A, To: B, SELF" as SELF is not counted in to_ids_cnt. So everything up to 3 is no error. */) { chat_id = 0; create_or_lookup_adhoc_group(context, mime_parser, allow_creation, create_blocked, from_id, to_ids, &chat_id, &chat_id_blocked); goto cleanup; } } cleanup: free(grpid); free(grpname); free(self_addr); free(better_msg); free(failure_reason); if (ret_chat_id) { *ret_chat_id = chat_id; } if (ret_chat_id_blocked) { *ret_chat_id_blocked = chat_id? chat_id_blocked : 0; } } /******************************************************************************* * Receive a message and add it to the database ******************************************************************************/ void dc_receive_imf(dc_context_t* context, const char* imf_raw_not_terminated, size_t imf_raw_bytes, const char* server_folder, uint32_t server_uid, uint32_t flags) { /* the function returns the number of created messages in the database */ int incoming = 1; int incoming_origin = 0; #define outgoing (!incoming) dc_array_t* to_ids = NULL; int to_self = 0; uint32_t from_id = 0; int from_id_blocked = 0; uint32_t to_id = 0; uint32_t chat_id = 0; int chat_id_blocked = 0; int state = DC_STATE_UNDEFINED; int hidden = 0; int msgrmsg = 0; int add_delete_job = 0; uint32_t insert_msg_id = 0; sqlite3_stmt* stmt = NULL; size_t i = 0; size_t icnt = 0; char* rfc724_mid = NULL; /* Message-ID from the header */ time_t sort_timestamp = DC_INVALID_TIMESTAMP; time_t sent_timestamp = DC_INVALID_TIMESTAMP; time_t rcvd_timestamp = DC_INVALID_TIMESTAMP; dc_mimeparser_t* mime_parser = dc_mimeparser_new(context->blobdir, context); int transaction_pending = 0; const struct mailimf_field* field; char* mime_in_reply_to = NULL; char* mime_references = NULL; carray* created_db_entries = carray_new(16); int create_event_to_send = DC_EVENT_MSGS_CHANGED; carray* rr_event_to_send = carray_new(16); char* txt_raw = NULL; dc_log_info(context, 0, "Receiving message %s/%lu...", server_folder? server_folder:"?", server_uid); to_ids = dc_array_new(context, 16); if (to_ids==NULL || created_db_entries==NULL || rr_event_to_send==NULL || mime_parser==NULL) { dc_log_info(context, 0, "Bad param."); goto cleanup; } /* parse the imf to mailimf_message { mailimf_fields* msg_fields { clist* fld_list; // list of mailimf_field } mailimf_body* msg_body { //!=NULL const char * bd_text; //!=NULL size_t bd_size; } }; normally, this is done by mailimf_message_parse(), however, as we also need the MIME data, we use mailmime_parse() through dc_mimeparser (both call mailimf_struct_multiple_parse() somewhen, I did not found out anything that speaks against this approach yet) */ dc_mimeparser_parse(mime_parser, imf_raw_not_terminated, imf_raw_bytes); if (dc_hash_cnt(&mime_parser->header)==0) { dc_log_info(context, 0, "No header."); goto cleanup; /* Error - even adding an empty record won't help as we do not know the message ID */ } /* messages without a Return-Path header typically are outgoing, however, if the Return-Path header is missing for other reasons, see issue #150, foreign messages appear as own messages, this is very confusing. as it may even be confusing when _own_ messages sent from other devices with other e-mail-adresses appear as being sent from SELF we disabled this check for now */ #if 0 if (!dc_mimeparser_lookup_field(mime_parser, "Return-Path")) { incoming = 0; } #endif if ((field=dc_mimeparser_lookup_field(mime_parser, "Date"))!=NULL && field->fld_type==MAILIMF_FIELD_ORIG_DATE) { struct mailimf_orig_date* orig_date = field->fld_data.fld_orig_date; if (orig_date) { sent_timestamp = dc_timestamp_from_date(orig_date->dt_date_time); // is not yet checked against bad times! we do this later if we have the database information. } } dc_sqlite3_begin_transaction(context->sql); transaction_pending = 1; /* get From: and check if it is known (for known From:'s we add the other To:/Cc: in the 3rd pass) or if From: is equal to SELF (in this case, it is any outgoing messages, we do not check Return-Path any more as this is unreliable, see issue #150 */ if ((field=dc_mimeparser_lookup_field(mime_parser, "From"))!=NULL && field->fld_type==MAILIMF_FIELD_FROM) { struct mailimf_from* fld_from = field->fld_data.fld_from; if (fld_from) { int check_self; dc_array_t* from_list = dc_array_new(context, 16); dc_add_or_lookup_contacts_by_mailbox_list(context, fld_from->frm_mb_list, DC_ORIGIN_INCOMING_UNKNOWN_FROM, from_list, &check_self); if (check_self) { incoming = 0; if (dc_mimeparser_sender_equals_recipient(mime_parser)) { from_id = DC_CONTACT_ID_SELF; } } else { if (dc_array_get_cnt(from_list)>=1) /* if there is no from given, from_id stays 0 which is just fine. These messages are very rare, however, we have to add them to the database (they go to the "deaddrop" chat) to avoid a re-download from the server. See also [**] */ { from_id = dc_array_get_id(from_list, 0); incoming_origin = dc_get_contact_origin(context, from_id, &from_id_blocked); } } dc_array_unref(from_list); } } /* Make sure, to_ids starts with the first To:-address (Cc: is added in the loop below pass) */ if ((field=dc_mimeparser_lookup_field(mime_parser, "To"))!=NULL && field->fld_type==MAILIMF_FIELD_TO) { struct mailimf_to* fld_to = field->fld_data.fld_to; /* can be NULL */ if (fld_to) { dc_add_or_lookup_contacts_by_address_list(context, fld_to->to_addr_list /*!= NULL*/, outgoing? DC_ORIGIN_OUTGOING_TO : (incoming_origin>=DC_ORIGIN_MIN_VERIFIED? DC_ORIGIN_INCOMING_TO : DC_ORIGIN_INCOMING_UNKNOWN_TO), to_ids, &to_self); } } if (dc_mimeparser_has_nonmeta(mime_parser)) { /********************************************************************** * Add parts *********************************************************************/ /* collect the rest information, CC: is added to the to-list, BCC: is ignored (we should not add BCC to groups as this would split groups. We could add them as "known contacts", however, the benefit is very small and this may leak data that is expected to be hidden) */ if ((field=dc_mimeparser_lookup_field(mime_parser, "Cc"))!=NULL && field->fld_type==MAILIMF_FIELD_CC) { struct mailimf_cc* fld_cc = field->fld_data.fld_cc; if (fld_cc) { dc_add_or_lookup_contacts_by_address_list(context, fld_cc->cc_addr_list, outgoing? DC_ORIGIN_OUTGOING_CC : (incoming_origin>=DC_ORIGIN_MIN_VERIFIED? DC_ORIGIN_INCOMING_CC : DC_ORIGIN_INCOMING_UNKNOWN_CC), to_ids, NULL); } } /* get Message-ID; if the header is lacking one, generate one based on fields that do never change. (missing Message-IDs may come if the mail was set from this account with another client that relies in the SMTP server to generate one. true eg. for the Webmailer used in all-inkl-KAS) */ if ((field=dc_mimeparser_lookup_field(mime_parser, "Message-ID"))!=NULL && field->fld_type==MAILIMF_FIELD_MESSAGE_ID) { struct mailimf_message_id* fld_message_id = field->fld_data.fld_message_id; if (fld_message_id) { rfc724_mid = dc_strdup(fld_message_id->mid_value); } } if (rfc724_mid==NULL) { rfc724_mid = dc_create_incoming_rfc724_mid(sent_timestamp, from_id, to_ids); if (rfc724_mid==NULL) { dc_log_info(context, 0, "Cannot create Message-ID."); goto cleanup; } } /* check, if the mail is already in our database - if so, just update the folder/uid (if the mail was moved around) and finish. (we may get a mail twice eg. if it is moved between folders. make sure, this check is done eg. before securejoin-processing) */ { char* old_server_folder = NULL; uint32_t old_server_uid = 0; if (dc_rfc724_mid_exists(context, rfc724_mid, &old_server_folder, &old_server_uid)) { if (strcmp(old_server_folder, server_folder)!=0 || old_server_uid!=server_uid) { dc_sqlite3_rollback(context->sql); transaction_pending = 0; dc_update_server_uid(context, rfc724_mid, server_folder, server_uid); } free(old_server_folder); dc_log_info(context, 0, "Message already in DB."); goto cleanup; } } msgrmsg = mime_parser->is_send_by_messenger; /* 1 or 0 for yes/no */ if (msgrmsg==0 && dc_is_reply_to_messenger_message(context, mime_parser)) { msgrmsg = 2; /* 2=no, but is reply to messenger message */ } /* incoming non-chat messages may be discarded; maybe this can be optimized later, by checking the state before the message body is downloaded */ int allow_creation = 1; if (mime_parser->is_system_message==DC_CMD_AUTOCRYPT_SETUP_MESSAGE) { ; } else if (msgrmsg==0) { /* this message is a classic email - not a chat-message nor a reply to one */ int show_emails = dc_sqlite3_get_config_int(context->sql, "show_emails", DC_SHOW_EMAILS_DEFAULT); if (show_emails==DC_SHOW_EMAILS_OFF) { chat_id = DC_CHAT_ID_TRASH; allow_creation = 0; } else if (show_emails==DC_SHOW_EMAILS_ACCEPTED_CONTACTS) { allow_creation = 0; } } /* check if the message introduces a new chat: - outgoing messages introduce a chat with the first to: address if they are sent by a messenger - incoming messages introduce a chat only for known contacts if they are sent by a messenger (of course, the user can add other chats manually later) */ if (incoming) { state = (flags&DC_IMAP_SEEN)? DC_STATE_IN_SEEN : DC_STATE_IN_FRESH; to_id = DC_CONTACT_ID_SELF; // handshake messages must be processed _before_ chats are created // (eg. contacs may be marked as verified) if (dc_mimeparser_lookup_field(mime_parser, "Secure-Join")) { msgrmsg = 1; // avoid discarding by show_emails setting chat_id = 0; allow_creation = 1; dc_sqlite3_commit(context->sql); int handshake = dc_handle_securejoin_handshake(context, mime_parser, from_id); if (handshake & DC_HANDSHAKE_STOP_NORMAL_PROCESSING) { hidden = 1; add_delete_job = (handshake & DC_HANDSHAKE_ADD_DELETE_JOB); state = DC_STATE_IN_SEEN; } dc_sqlite3_begin_transaction(context->sql); } /* test if there is a normal chat with the sender - if so, this allows us to create groups in the next step */ uint32_t test_normal_chat_id = 0; int test_normal_chat_id_blocked = 0; dc_lookup_real_nchat_by_contact_id(context, from_id, &test_normal_chat_id, &test_normal_chat_id_blocked); /* get the chat_id - a chat_id here is no indicator that the chat is displayed in the normal list, it might also be blocked and displayed in the deaddrop as a result */ if (chat_id==0) { /* try to create a group (groups appear automatically only if the _sender_ is known, see core issue #54) */ int create_blocked = ((test_normal_chat_id&&test_normal_chat_id_blocked==DC_CHAT_NOT_BLOCKED) || incoming_origin>=DC_ORIGIN_MIN_START_NEW_NCHAT/*always false, for now*/)? DC_CHAT_NOT_BLOCKED : DC_CHAT_DEADDROP_BLOCKED; create_or_lookup_group(context, mime_parser, allow_creation, create_blocked, from_id, to_ids, &chat_id, &chat_id_blocked); if (chat_id && chat_id_blocked && !create_blocked) { dc_unblock_chat(context, chat_id); chat_id_blocked = 0; } } if (chat_id==0) { /* check if the message belongs to a mailing list */ if (dc_mimeparser_is_mailinglist_message(mime_parser)) { chat_id = DC_CHAT_ID_TRASH; dc_log_info(context, 0, "Message belongs to a mailing list and is ignored."); } } if (chat_id==0) { /* try to create a normal chat */ int create_blocked = (incoming_origin>=DC_ORIGIN_MIN_START_NEW_NCHAT/*always false, for now*/ || from_id==to_id)? DC_CHAT_NOT_BLOCKED : DC_CHAT_DEADDROP_BLOCKED; if (test_normal_chat_id) { chat_id = test_normal_chat_id; chat_id_blocked = test_normal_chat_id_blocked; } else if(allow_creation) { dc_create_or_lookup_nchat_by_contact_id(context, from_id, create_blocked, &chat_id, &chat_id_blocked); } if (chat_id && chat_id_blocked) { if (!create_blocked) { dc_unblock_chat(context, chat_id); chat_id_blocked = 0; } else if (dc_is_reply_to_known_message(context, mime_parser)) { dc_scaleup_contact_origin(context, from_id, DC_ORIGIN_INCOMING_REPLY_TO); /* we do not want any chat to be created implicitly. Because of the origin-scale-up, the contact requests will pop up and this should be just fine. */ dc_log_info(context, 0, "Message is a reply to a known message, mark sender as known."); incoming_origin = DC_MAX(incoming_origin, DC_ORIGIN_INCOMING_REPLY_TO); } } } if (chat_id==0) { /* maybe from_id is null or sth. else is suspicious, move message to trash */ chat_id = DC_CHAT_ID_TRASH; } /* if the chat_id is blocked, for unknown senders and non-delta messages set the state to NOTICED to not result in a contact request (this would require the state FRESH) */ if (chat_id_blocked && state==DC_STATE_IN_FRESH) { if (incoming_origin < DC_ORIGIN_MIN_VERIFIED && msgrmsg==0) { state = DC_STATE_IN_NOTICED; } } } else /* outgoing */ { state = DC_STATE_OUT_DELIVERED; /* the mail is on the IMAP server, probably it is also delivered. We cannot recreate other states (read, error). */ from_id = DC_CONTACT_ID_SELF; if (dc_array_get_cnt(to_ids) >= 1) { to_id = dc_array_get_id(to_ids, 0); if (chat_id==0) { create_or_lookup_group(context, mime_parser, allow_creation, DC_CHAT_NOT_BLOCKED, from_id, to_ids, &chat_id, &chat_id_blocked); if (chat_id && chat_id_blocked) { dc_unblock_chat(context, chat_id); chat_id_blocked = 0; } } if (chat_id==0 && allow_creation) { int create_blocked = (msgrmsg && !dc_is_contact_blocked(context, to_id))? DC_CHAT_NOT_BLOCKED : DC_CHAT_DEADDROP_BLOCKED; dc_create_or_lookup_nchat_by_contact_id(context, to_id, create_blocked, &chat_id, &chat_id_blocked); if (chat_id && chat_id_blocked && !create_blocked) { dc_unblock_chat(context, chat_id); chat_id_blocked = 0; } } } if (chat_id==0) { if (dc_array_get_cnt(to_ids)==0 && to_self) { /* from_id==to_id==DC_CONTACT_ID_SELF - this is a self-sent messages, maybe an Autocrypt Setup Message */ dc_create_or_lookup_nchat_by_contact_id(context, DC_CONTACT_ID_SELF, DC_CHAT_NOT_BLOCKED, &chat_id, &chat_id_blocked); if (chat_id && chat_id_blocked) { dc_unblock_chat(context, chat_id); chat_id_blocked = 0; } } } if (chat_id==0) { chat_id = DC_CHAT_ID_TRASH; } } /* correct message_timestamp, it should not be used before, however, we cannot do this earlier as we need from_id to be set */ calc_timestamps(context, chat_id, from_id, sent_timestamp, (flags&DC_IMAP_SEEN)? 0 : 1 /*fresh message?*/, &sort_timestamp, &sent_timestamp, &rcvd_timestamp); /* unarchive chat */ dc_unarchive_chat(context, chat_id); // if the mime-headers should be saved, find out its size // (the mime-header ends with an empty line) int save_mime_headers = dc_sqlite3_get_config_int(context->sql, "save_mime_headers", 0); int header_bytes = imf_raw_bytes; if (save_mime_headers) { char* p; if ((p=strstr(imf_raw_not_terminated, "\r\n\r\n"))!=NULL) { header_bytes = (p-imf_raw_not_terminated)+4; } else if ((p=strstr(imf_raw_not_terminated, "\n\n"))!=NULL) { header_bytes = (p-imf_raw_not_terminated)+2; } } if ((field=dc_mimeparser_lookup_field(mime_parser, "In-Reply-To"))!=NULL && field->fld_type==MAILIMF_FIELD_IN_REPLY_TO) { struct mailimf_in_reply_to* fld_in_reply_to = field->fld_data.fld_in_reply_to; if (fld_in_reply_to) { mime_in_reply_to = dc_str_from_clist(field->fld_data.fld_in_reply_to->mid_list, " "); } } if ((field=dc_mimeparser_lookup_field(mime_parser, "References"))!=NULL && field->fld_type==MAILIMF_FIELD_REFERENCES) { struct mailimf_references* fld_references = field->fld_data.fld_references; if (fld_references) { mime_references = dc_str_from_clist(field->fld_data.fld_references->mid_list, " "); } } /* fine, so far. now, split the message into simple parts usable as "short messages" and add them to the database (mails sent by other messenger clients should result into only one message; mails sent by other clients may result in several messages (eg. one per attachment)) */ icnt = carray_count(mime_parser->parts); /* should be at least one - maybe empty - part */ stmt = dc_sqlite3_prepare(context->sql, "INSERT INTO msgs (rfc724_mid, server_folder, server_uid, chat_id, from_id, to_id," " timestamp, timestamp_sent, timestamp_rcvd, type, state, msgrmsg, " " txt, txt_raw, param, bytes, hidden, mime_headers, " " mime_in_reply_to, mime_references)" " VALUES (?,?,?,?,?,?, ?,?,?,?,?,?, ?,?,?,?,?,?, ?,?);"); for (i = 0; i < icnt; i++) { dc_mimepart_t* part = (dc_mimepart_t*)carray_get(mime_parser->parts, i); if (part->is_meta) { continue; } if (mime_parser->location_kml && icnt==1 && part->msg && (strcmp(part->msg, "-location-")==0 || part->msg[0]==0)) { hidden = 1; if (state==DC_STATE_IN_FRESH) { state = DC_STATE_IN_NOTICED; } } if (part->type==DC_MSG_TEXT) { txt_raw = dc_mprintf("%s\n\n%s", mime_parser->subject? mime_parser->subject : "", part->msg_raw); } if (mime_parser->is_system_message) { dc_param_set_int(part->param, DC_PARAM_CMD, mime_parser->is_system_message); } sqlite3_reset(stmt); sqlite3_bind_text (stmt, 1, rfc724_mid, -1, SQLITE_STATIC); sqlite3_bind_text (stmt, 2, server_folder, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 3, server_uid); sqlite3_bind_int (stmt, 4, chat_id); sqlite3_bind_int (stmt, 5, from_id); sqlite3_bind_int (stmt, 6, to_id); sqlite3_bind_int64(stmt, 7, sort_timestamp); sqlite3_bind_int64(stmt, 8, sent_timestamp); sqlite3_bind_int64(stmt, 9, rcvd_timestamp); sqlite3_bind_int (stmt, 10, part->type); sqlite3_bind_int (stmt, 11, state); sqlite3_bind_int (stmt, 12, msgrmsg); sqlite3_bind_text (stmt, 13, part->msg? part->msg : "", -1, SQLITE_STATIC); sqlite3_bind_text (stmt, 14, txt_raw? txt_raw : "", -1, SQLITE_STATIC); sqlite3_bind_text (stmt, 15, part->param->packed, -1, SQLITE_STATIC); sqlite3_bind_int (stmt, 16, part->bytes); sqlite3_bind_int (stmt, 17, hidden); sqlite3_bind_text (stmt, 18, save_mime_headers? imf_raw_not_terminated : NULL, header_bytes, SQLITE_STATIC); sqlite3_bind_text (stmt, 19, mime_in_reply_to, -1, SQLITE_STATIC); sqlite3_bind_text (stmt, 20, mime_references, -1, SQLITE_STATIC); if (sqlite3_step(stmt)!=SQLITE_DONE) { dc_log_info(context, 0, "Cannot write DB."); goto cleanup; /* i/o error - there is nothing more we can do - in other cases, we try to write at least an empty record */ } free(txt_raw); txt_raw = NULL; insert_msg_id = dc_sqlite3_get_rowid(context->sql, "msgs", "rfc724_mid", rfc724_mid); carray_add(created_db_entries, (void*)(uintptr_t)chat_id, NULL); carray_add(created_db_entries, (void*)(uintptr_t)insert_msg_id, NULL); } dc_log_info(context, 0, "Message has %i parts and is assigned to chat #%i.", icnt, chat_id); /* check event to send */ if (chat_id==DC_CHAT_ID_TRASH) { create_event_to_send = 0; } else if (incoming && state==DC_STATE_IN_FRESH) { if (from_id_blocked) { create_event_to_send = 0; } else if (chat_id_blocked) { create_event_to_send = DC_EVENT_MSGS_CHANGED; /*if (dc_sqlite3_get_config_int(context->sql, "show_deaddrop", 0)!=0) { create_event_to_send = DC_EVENT_INCOMING_MSG; }*/ } else { create_event_to_send = DC_EVENT_INCOMING_MSG; } } dc_do_heuristics_moves(context, server_folder, insert_msg_id); } else { // there are no non-meta data in message, do some basic calculations so that the varaiables are correct in the further processing if (sent_timestamp > time(NULL)) { sent_timestamp = time(NULL); } } if (carray_count(mime_parser->reports) > 0) { /****************************************************************** * Handle reports (mainly MDNs) *****************************************************************/ int mdns_enabled = dc_sqlite3_get_config_int(context->sql, "mdns_enabled", DC_MDNS_DEFAULT_ENABLED); icnt = carray_count(mime_parser->reports); for (i = 0; i < icnt; i++) { int mdn_consumed = 0; struct mailmime* report_root = carray_get(mime_parser->reports, i); struct mailmime_parameter* report_type = mailmime_find_ct_parameter(report_root, "report-type"); if (report_root==NULL || report_type==NULL || report_type->pa_value==NULL) { continue; } if (strcmp(report_type->pa_value, "disposition-notification")==0 && clist_count(report_root->mm_data.mm_multipart.mm_mp_list) >= 2 /* the first part is for humans, the second for machines */) { if (mdns_enabled /*to get a clear functionality, do not show incoming MDNs if the options is disabled*/) { struct mailmime* report_data = (struct mailmime*)clist_content(clist_next(clist_begin(report_root->mm_data.mm_multipart.mm_mp_list))); if (report_data && report_data->mm_content_type->ct_type->tp_type==MAILMIME_TYPE_COMPOSITE_TYPE && report_data->mm_content_type->ct_type->tp_data.tp_composite_type->ct_type==MAILMIME_COMPOSITE_TYPE_MESSAGE && strcmp(report_data->mm_content_type->ct_subtype, "disposition-notification")==0) { /* we received a MDN (although the MDN is only a header, we parse it as a complete mail) */ const char* report_body = NULL; size_t report_body_bytes = 0; char* to_mmap_string_unref = NULL; if (mailmime_transfer_decode(report_data, &report_body, &report_body_bytes, &to_mmap_string_unref)) { struct mailmime* report_parsed = NULL; size_t dummy = 0; if (mailmime_parse(report_body, report_body_bytes, &dummy, &report_parsed)==MAIL_NO_ERROR && report_parsed!=NULL) { struct mailimf_fields* report_fields = mailmime_find_mailimf_fields(report_parsed); if (report_fields) { struct mailimf_optional_field* of_disposition = mailimf_find_optional_field(report_fields, "Disposition"); /* MUST be preset, _if_ preset, we assume a sort of attribution and do not go into details */ struct mailimf_optional_field* of_org_msgid = mailimf_find_optional_field(report_fields, "Original-Message-ID"); /* can't live without */ if (of_disposition && of_disposition->fld_value && of_org_msgid && of_org_msgid->fld_value) { char* rfc724_mid = NULL; dummy = 0; if (mailimf_msg_id_parse(of_org_msgid->fld_value, strlen(of_org_msgid->fld_value), &dummy, &rfc724_mid)==MAIL_NO_ERROR && rfc724_mid!=NULL) { uint32_t chat_id = 0; uint32_t msg_id = 0; if (dc_mdn_from_ext(context, from_id, rfc724_mid, sent_timestamp, &chat_id, &msg_id)) { carray_add(rr_event_to_send, (void*)(uintptr_t)chat_id, NULL); carray_add(rr_event_to_send, (void*)(uintptr_t)msg_id, NULL); } mdn_consumed = (msg_id!=0); free(rfc724_mid); } } } mailmime_free(report_parsed); } if (to_mmap_string_unref) { mmap_string_unref(to_mmap_string_unref); } } } } /* Move the MDN away to the chats folder. We do this for: - Consumed or not consumed MDNs from other messengers - Consumed MDNs from normal MUAs Unconsumed MDNs from normal MUAs are _not_ moved. NB: we do not delete the MDN as it may be used by other clients */ if (mime_parser->is_send_by_messenger || mdn_consumed) { dc_param_t* param = dc_param_new(); dc_param_set(param, DC_PARAM_SERVER_FOLDER, server_folder); dc_param_set_int(param, DC_PARAM_SERVER_UID, server_uid); if (mime_parser->is_send_by_messenger && dc_sqlite3_get_config_int(context->sql, "mvbox_move", DC_MVBOX_MOVE_DEFAULT)) { dc_param_set_int(param, DC_PARAM_ALSO_MOVE, 1); } dc_job_add(context, DC_JOB_MARKSEEN_MDN_ON_IMAP, 0, param->packed, 0); dc_param_unref(param); } } } /* for() */ } { /****************************************************************** * save locations *****************************************************************/ int location_id_written = 0; int send_event = 0; if (mime_parser->message_kml && chat_id > DC_CHAT_ID_LAST_SPECIAL) { uint32_t newest_location_id = dc_save_locations(context, chat_id, from_id, mime_parser->message_kml->locations, 1); if (newest_location_id && !hidden) { dc_set_msg_location_id(context, insert_msg_id, newest_location_id); location_id_written = 1; send_event = 1; } } if (mime_parser->location_kml && chat_id > DC_CHAT_ID_LAST_SPECIAL) { dc_contact_t* contact = dc_get_contact(context, from_id); if (mime_parser->location_kml->addr && contact && contact->addr && strcasecmp(contact->addr, mime_parser->location_kml->addr)==0) { uint32_t newest_location_id = dc_save_locations(context, chat_id, from_id, mime_parser->location_kml->locations, 0); if (newest_location_id && !hidden && !location_id_written) { dc_set_msg_location_id(context, insert_msg_id, newest_location_id); } send_event = 1; } dc_contact_unref(contact); } if (send_event) { context->cb(context, DC_EVENT_LOCATION_CHANGED, from_id, 0); } } if (add_delete_job && carray_count(created_db_entries)>=2) { dc_job_add(context, DC_JOB_DELETE_MSG_ON_IMAP, (int)(uintptr_t)carray_get(created_db_entries, 1), NULL, 0); } dc_sqlite3_commit(context->sql); transaction_pending = 0; cleanup: if (transaction_pending) { dc_sqlite3_rollback(context->sql); } dc_mimeparser_unref(mime_parser); free(rfc724_mid); free(mime_in_reply_to); free(mime_references); dc_array_unref(to_ids); if (created_db_entries) { if (create_event_to_send) { size_t i, icnt = carray_count(created_db_entries); for (i = 0; i < icnt; i += 2) { context->cb(context, create_event_to_send, (uintptr_t)carray_get(created_db_entries, i), (uintptr_t)carray_get(created_db_entries, i+1)); } } carray_free(created_db_entries); } if (rr_event_to_send) { size_t i, icnt = carray_count(rr_event_to_send); for (i = 0; i < icnt; i += 2) { context->cb(context, DC_EVENT_MSG_READ, (uintptr_t)carray_get(rr_event_to_send, i), (uintptr_t)carray_get(rr_event_to_send, i+1)); } carray_free(rr_event_to_send); } free(txt_raw); sqlite3_finalize(stmt); } ``` Filename: dc_saxparser.c ```c /* dc_saxparser_t parses XML and HTML files that may not be wellformed and spits out all text and tags found. - Attributes are recognized with single, double or no quotes - Whitespace ignored inside tags - Self-closing tags are issued as open-tag plus close-tag - CDATA is supoorted; DTA, comments, processing instruction are skipped properly - The parser does not care about hierarchy, if needed this can be done by the user. - Input and output strings must be UTF-8 encoded. - Tag and attribute names are converted to lower case. - Parsing does not stop on errors; instead errors are recovered. NB: SAX = Simple API for XML */ #include #include #include #include "dc_context.h" #include "dc_tools.h" #include "dc_saxparser.h" /******************************************************************************* * Decoding text ******************************************************************************/ static const char* s_ent[] = { /* Convert entities as ä to UTF-8 characters. - The first strings MUST NOT start with `&` and MUST end with `;`. - take care not to miss a comma between the strings. - It's also possible to specify the destination as a character reference as `"` (they are converted in a second pass without a table). */ /* basic XML/HTML */ "lt;", "<", "gt;", ">", "quot;", "\"", "apos;", "'", "amp;", "&", "nbsp;", " ", /* advanced HTML */ "iexcl;", "¡", "cent;", "¢", "pound;", "£", "curren;", "¤", "yen;", "¥", "brvbar;", "¦", "sect;", "§", "uml;", "¨", "copy;", "©", "ordf;", "ª", "laquo;", "«", "not;", "¬", "shy;", "-", "reg;", "®", "macr;", "¯", "deg;", "°", "plusmn;", "±", "sup2;", "²", "sup3;", "³", "acute;", "´", "micro;", "µ", "para;", "¶", "middot;", "·", "cedil;", "¸", "sup1;", "¹", "ordm;", "º", "raquo;", "»", "frac14;", "¼", "frac12;", "½", "frac34;", "¾", "iquest;", "¿", "Agrave;", "À", "Aacute;", "Á", "Acirc;", "Â", "Atilde;", "Ã", "Auml;", "Ä", "Aring;", "Å", "AElig;", "Æ", "Ccedil;", "Ç", "Egrave;", "È", "Eacute;", "É", "Ecirc;", "Ê", "Euml;", "Ë", "Igrave;", "Ì", "Iacute;", "Í", "Icirc;", "Î", "Iuml;", "Ï", "ETH;", "Ð", "Ntilde;", "Ñ", "Ograve;", "Ò", "Oacute;", "Ó", "Ocirc;", "Ô", "Otilde;", "Õ", "Ouml;", "Ö", "times;", "×", "Oslash;", "Ø", "Ugrave;", "Ù", "Uacute;", "Ú", "Ucirc;", "Û", "Uuml;", "Ü", "Yacute;", "Ý", "THORN;", "Þ", "szlig;", "ß", "agrave;", "à", "aacute;", "á", "acirc;", "â", "atilde;", "ã", "auml;", "ä", "aring;", "å", "aelig;", "æ", "ccedil;", "ç", "egrave;", "è", "eacute;", "é", "ecirc;", "ê", "euml;", "ë", "igrave;", "ì", "iacute;", "í", "icirc;", "î", "iuml;", "ï", "eth;", "ð", "ntilde;", "ñ", "ograve;", "ò", "oacute;", "ó", "ocirc;", "ô", "otilde;", "õ", "ouml;", "ö", "divide;", "÷", "oslash;", "ø", "ugrave;", "ù", "uacute;", "ú", "ucirc;", "û", "uuml;", "ü", "yacute;", "ý", "thorn;", "þ", "yuml;", "ÿ", "OElig;", "Œ", "oelig;", "œ", "Scaron;", "Š", "scaron;", "š", "Yuml;", "Ÿ", "fnof;", "ƒ", "circ;", "ˆ", "tilde;", "˜", "Alpha;", "Α", "Beta;", "Β", "Gamma;", "Γ", "Delta;", "Δ", "Epsilon;", "Ε", "Zeta;", "Ζ", "Eta;", "Η", "Theta;", "Θ", "Iota;", "Ι", "Kappa;", "Κ", "Lambda;", "Λ", "Mu;", "Μ", "Nu;", "Ν", "Xi;", "Ξ", "Omicron;", "Ο", "Pi;", "Π", "Rho;", "Ρ", "Sigma;", "Σ", "Tau;", "Τ", "Upsilon;", "Υ", "Phi;", "Φ", "Chi;", "Χ", "Psi;", "Ψ", "Omega;", "Ω", "alpha;", "α", "beta;", "β", "gamma;", "γ", "delta;", "δ", "epsilon;", "ε", "zeta;", "ζ", "eta;", "η", "theta;", "θ", "iota;", "ι", "kappa;", "κ", "lambda;", "λ", "mu;", "μ", "nu;", "ν", "xi;", "ξ", "omicron;", "ο", "pi;", "π", "rho;", "ρ", "sigmaf;", "ς", "sigma;", "σ", "tau;", "τ", "upsilon;", "υ", "phi;", "φ", "chi;", "χ", "psi;", "ψ", "omega;", "ω", "thetasym;","ϑ", "upsih;", "ϒ", "piv;", "ϖ", "ensp;", " ", "emsp;", " ", "thinsp;", " ", "zwnj;", "" , "zwj;", "" , "lrm;", "" , "rlm;", "" , "ndash;", "–", "mdash;", "—", "lsquo;", "‘", "rsquo;", "’", "sbquo;", "‚", "ldquo;", "“", "rdquo;", "”", "bdquo;", "„", "dagger;", "†", "Dagger;", "‡", "bull;", "•", "hellip;", "…", "permil;", "‰", "prime;", "′", "Prime;", "″", "lsaquo;", "‹", "rsaquo;", "›", "oline;", "‾", "frasl;", "⁄", "euro;", "€", "image;", "ℑ", "weierp;", "℘", "real;", "ℜ", "trade;", "™", "alefsym;", "ℵ", "larr;", "←", "uarr;", "↑", "rarr;", "→", "darr;", "↓", "harr;", "↔", "crarr;", "↵", "lArr;", "⇐", "uArr;", "⇑", "rArr;", "⇒", "dArr;", "⇓", "hArr;", "⇔", "forall;", "∀", "part;", "∂", "exist;", "∃", "empty;", "∅", "nabla;", "∇", "isin;", "∈", "notin;", "∉", "ni;", "∋", "prod;", "∏", "sum;", "∑", "minus;", "−", "lowast;", "∗", "radic;", "√", "prop;", "∝", "infin;", "∞", "ang;", "∠", "and;", "∧", "or;", "∨", "cap;", "∩", "cup;", "∪", "int;", "∫", "there4;", "∴", "sim;", "∼", "cong;", "≅", "asymp;", "≈", "ne;", "≠", "equiv;", "≡", "le;", "≤", "ge;", "≥", "sub;", "⊂", "sup;", "⊃", "nsub;", "⊄", "sube;", "⊆", "supe;", "⊇", "oplus;", "⊕", "otimes;", "⊗", "perp;", "⊥", "sdot;", "⋅", "lceil;", "⌈", "rceil;", "⌉", "lfloor;", "⌊", "rfloor;", "⌋", "lang;", "<", "rang;", ">", "loz;", "◊", "spades;", "♠", "clubs;", "♣", "hearts;", "♥", "diams;", "♦", /* MUST be last */ NULL, NULL, }; /* Recursively decodes entity and character references and normalizes new lines. set "type" to ... '&' for general entity decoding, '%' for parameter entity decoding (currently not needed), 'c' for cdata sections, ' ' for attribute normalization, or '*' for non-cdata attribute normalization (currently not needed). Returns s, or if the decoded string is longer than s, returns a malloced string that must be freed. Function based upon ezxml_decode() from the "ezxml" parser which is Copyright 2004-2006 Aaron Voisine */ static char* xml_decode(char* s, char type) { char* e = NULL; char* r = s; const char* original_buf = s; long b = 0; long c = 0; long d = 0; long l = 0; for (; *s; s++) { /* normalize line endings */ while (*s == '\r') { *(s++) = '\n'; if (*s == '\n') memmove(s, (s + 1), strlen(s)); } } for (s = r; ;) { while (*s && *s != '&' /*&& (*s != '%' || type != '%')*/ && !isspace(*s)) s++; if (! *s) { break; } else if (type != 'c' && ! strncmp(s, "&#", 2)) { /* character reference */ if (s[2] == 'x') c = strtol(s + 3, &e, 16); /* base 16 */ else c = strtol(s + 2, &e, 10); /* base 10 */ if (! c || *e != ';') { s++; continue; } /* not a character ref */ if (c < 0x80) *(s++) = c; /* US-ASCII subset */ else { /* multi-byte UTF-8 sequence */ for (b = 0, d = c; d; d /= 2) b++; /* number of bits in c */ b = (b - 2) / 5; /* number of bytes in payload */ *(s++) = (0xFF << (7 - b)) | (c >> (6 * b)); /* head */ while (b) *(s++) = 0x80 | ((c >> (6 * --b)) & 0x3F); /* payload */ } memmove(s, strchr(s, ';') + 1, strlen(strchr(s, ';'))); } else if ((*s == '&' && (type == '&' || type == ' ' /*|| type == '*'*/)) /*|| (*s == '%' && type == '%')*/) { /* entity reference */ for (b = 0; s_ent[b] && strncmp(s + 1, s_ent[b], strlen(s_ent[b])); b += 2) ; /* find entity in entity list */ if (s_ent[b++]) { /* found a match */ if ((c = strlen(s_ent[b])) - 1 > (e = strchr(s, ';')) - s) { /* the replacement is larger than the entity: enlarge buffer */ l = (d = (s - r)) + c + strlen(e); /* new length */ if (r == original_buf) { char* new_ret = malloc(l); if (new_ret == NULL) { return r; } strcpy(new_ret, r); r = new_ret; } else { char* new_ret = realloc(r, l); if (new_ret == NULL) { return r; } r = new_ret; } e = strchr((s = r + d), ';'); /* fix up pointers */ } memmove(s + c, e + 1, strlen(e)); /* shift rest of string */ strncpy(s, s_ent[b], c); /* copy in replacement text */ } else s++; /* not a known entity */ } else if ((type == ' ' /*|| type == '*'*/) && isspace(*s)) { *(s++) = ' '; } else s++; /* no decoding needed */ } /* normalize spaces for non-cdata attributes if (type == '*') { for (s = r; *s; s++) { if ((l = strspn(s, " "))) memmove(s, s + l, strlen(s + l) + 1); while (*s && *s != ' ') s++; } if (--s >= r && *s == ' ') *s = '\0'; }*/ return r; } /******************************************************************************* * Tools ******************************************************************************/ #define XML_WS "\t\r\n " static void def_starttag_cb (void* userdata, const char* tag, char** attr) { } static void def_endtag_cb (void* userdata, const char* tag) { } static void def_text_cb (void* userdata, const char* text, int len) { } static void call_text_cb(dc_saxparser_t* saxparser, char* text, size_t len, char type) { if (text && len) { char bak = text[len], *text_new; text[len] = '\0'; text_new = xml_decode(text, type); saxparser->text_cb(saxparser->userdata, text_new, len); if (text != text_new) { free(text_new); } text[len] = bak; } } static void do_free_attr(char** attr, int* free_attr) { /* "attr" are key/value pairs; the function frees the data if the corresponding bit in "free_attr" is set. (we need this as we try to use the strings from the "main" document instead of allocating small strings) */ #define FREE_KEY 0x01 #define FREE_VALUE 0x02 int i = 0; while (attr[i]) { if (free_attr[i>>1]&FREE_KEY && attr[i]) { free(attr[i]); } if (free_attr[i>>1]&FREE_VALUE && attr[i+1]) { free(attr[i+1]); } i += 2; } attr[0] = NULL; /* set list to zero-length */ } /******************************************************************************* * Main interface ******************************************************************************/ const char* dc_attr_find(char** attr, const char* key) { if (attr && key) { int i = 0; while (attr[i] && strcmp(key, attr[i])) { i += 2; } if (attr[i]) { return attr[i + 1]; } } return NULL; } void dc_saxparser_init(dc_saxparser_t* saxparser, void* userdata) { saxparser->userdata = userdata; saxparser->starttag_cb = def_starttag_cb; saxparser->endtag_cb = def_endtag_cb; saxparser->text_cb = def_text_cb; } void dc_saxparser_set_tag_handler(dc_saxparser_t* saxparser, dc_saxparser_starttag_cb_t starttag_cb, dc_saxparser_endtag_cb_t endtag_cb) { if (saxparser==NULL) { return; } saxparser->starttag_cb = starttag_cb? starttag_cb : def_starttag_cb; saxparser->endtag_cb = endtag_cb? endtag_cb : def_endtag_cb; } void dc_saxparser_set_text_handler (dc_saxparser_t* saxparser, dc_saxparser_text_cb_t text_cb) { if (saxparser==NULL) { return; } saxparser->text_cb = text_cb? text_cb : def_text_cb; } void dc_saxparser_parse(dc_saxparser_t* saxparser, const char* buf_start__) { char bak = 0; char* buf_start = NULL; char* last_text_start = NULL; char* p = NULL; #define MAX_ATTR 100 /* attributes per tag - a fixed border here is a security feature, not a limit */ char* attr[(MAX_ATTR+1)*2]; /* attributes as key/value pairs, +1 for terminating the list */ int free_attr[MAX_ATTR]; /* free the value at attr[i*2+1]? */ attr[0] = NULL; /* null-terminate list, this also terminates "free_values" */ if (saxparser==NULL) { return; } buf_start = dc_strdup(buf_start__); /* we make a copy as we can easily null-terminate tag names and attributes "in place" */ last_text_start = buf_start; p = buf_start; while (*p) { if (*p=='<') { call_text_cb(saxparser, last_text_start, p - last_text_start, '&'); /* flush pending text */ p++; if (strncmp(p, "!--", 3)==0) { /* skip comment **************************************************************/ p = strstr(p, "-->"); if (p==NULL) { goto cleanup; } p += 3; } else if (strncmp(p, "![CDATA[", 8)==0) { /* process text **************************************************************/ char* text_beg = p + 8; if ((p = strstr(p, "]]>"))!=NULL) /* `]]>` itself is not allowed in CDATA and must be escaped by dividing into two CDATA parts */ { call_text_cb(saxparser, text_beg, p-text_beg, 'c'); p += 3; } else { call_text_cb(saxparser, text_beg, strlen(text_beg), 'c'); /* CDATA not closed, add all remaining text */ goto cleanup; } } else if (strncmp(p, "!DOCTYPE", 8)==0) { /* skip or **************************************************************/ while (*p && *p != '[' && *p != '>' ) p++; /* search for [ or >, whatever comes first */ if (*p==0) { goto cleanup; /* unclosed doctype */ } else if (*p=='[') { p = strstr(p, "]>"); /* search end of inline doctype */ if (p==NULL) { goto cleanup; /* unclosed inline doctype */ } else { p += 2; } } else { p++; } } else if (*p=='?') { /* skip processing instruction **************************************************************/ p = strstr(p, "?>"); if (p==NULL) { goto cleanup; } /* unclosed processing instruction */ p += 2; } else { p += strspn(p, XML_WS); /* skip whitespace between `<` and tagname */ if (*p=='/') { /* process end tag **************************************************************/ p++; p += strspn(p, XML_WS); /* skip whitespace between `/` and tagname */ char* beg_tag_name = p; p += strcspn(p, XML_WS "/>"); /* find character after tagname */ if (p != beg_tag_name) { bak = *p; *p = '\0'; /* null-terminate tag name temporary, eg. a covered `>` may get important downwards */ dc_strlower_in_place(beg_tag_name); saxparser->endtag_cb(saxparser->userdata, beg_tag_name); *p = bak; } } else { /* process **************************************************************/ do_free_attr(attr, free_attr); char* beg_tag_name = p; p += strcspn(p, XML_WS "/>"); /* find character after tagname */ if (p != beg_tag_name) { char* after_tag_name = p; /* scan for attributes */ int attr_index = 0; while (isspace(*p)) { p++; } /* forward to first attribute name beginning */ while (*p && *p!='/' && *p!='>') { char *beg_attr_name = p, *beg_attr_value = NULL, *beg_attr_value_new = NULL; if ('='==*beg_attr_name) { p++; // otherwise eg. `"val"=` causes a deadlock as the second `=` is no exit condition and is not skipped by strcspn() continue; } p += strcspn(p, XML_WS "=/>"); /* get end of attribute name */ if (p != beg_attr_name) { /* attribute found */ char* after_attr_name = p; p += strspn(p, XML_WS); /* skip whitespace between attribute name and possible `=` */ if (*p=='=') { p += strspn(p, XML_WS "="); /* skip spaces and equal signs */ char quote = *p; if (quote=='"' || quote=='\'') { /* quoted attribute value */ p++; beg_attr_value = p; while (*p && *p != quote) { p++; } if (*p) { *p = '\0'; /* null terminate attribute val */ p++; } beg_attr_value_new = xml_decode(beg_attr_value, ' '); } else { /* unquoted attribute value, as the needed null-terminated may overwrite important characters, we'll create a copy */ beg_attr_value = p; p += strcspn(p, XML_WS "/>"); /* get end of attribute value */ bak = *p; *p = '\0'; char* temp = dc_strdup(beg_attr_value); beg_attr_value_new = xml_decode(temp, ' '); if (beg_attr_value_new!=temp) { free(temp); } *p = bak; } } else { beg_attr_value_new = dc_strdup(NULL); } /* add attribute */ if (attr_index < MAX_ATTR) { char* beg_attr_name_new = beg_attr_name; int free_bits = (beg_attr_value_new != beg_attr_value)? FREE_VALUE : 0; if (after_attr_name==p) { /* take care not to overwrite the current pointer (happens eg. for `` */ bak = *after_attr_name; *after_attr_name = '\0'; beg_attr_name_new = dc_strdup(beg_attr_name); *after_attr_name = bak; free_bits |= FREE_KEY; } else { *after_attr_name = '\0'; } dc_strlower_in_place(beg_attr_name_new); attr[attr_index] = beg_attr_name_new; attr[attr_index+1] = beg_attr_value_new; attr[attr_index+2] = NULL; /* null-terminate list */ free_attr[attr_index>>1] = free_bits; attr_index += 2; } } while (isspace(*p)) { p++; } /* forward to attribute name beginning */ } char bak = *after_tag_name; /* backup the character as it may be `/` or `>` which gets important downwards */ *after_tag_name = 0; dc_strlower_in_place(beg_tag_name); saxparser->starttag_cb(saxparser->userdata, beg_tag_name, attr); *after_tag_name = bak; /* self-closing tag */ p += strspn(p, XML_WS); /* skip whitespace before possible `/` */ if (*p=='/') { p++; *after_tag_name = 0; saxparser->endtag_cb(saxparser->userdata, beg_tag_name); /* already lowercase from starttag_cb()-call */ } } } /* end of processing start-tag */ p = strchr(p, '>'); if (p==NULL) { goto cleanup; } /* unclosed start-tag or end-tag */ p++; } /* end of processing start-tag or end-tag */ last_text_start = p; } else { p++; } } call_text_cb(saxparser, last_text_start, p - last_text_start, '&'); /* flush pending text */ cleanup: do_free_attr(attr, free_attr); free(buf_start); } ``` Filename: dc_securejoin.c ```c #include #include #include "dc_context.h" #include "dc_key.h" #include "dc_apeerstate.h" #include "dc_mimeparser.h" #include "dc_mimefactory.h" #include "dc_job.h" #include "dc_token.h" /** * @name Secure Join * @{ */ /******************************************************************************* * Tools: Handle degraded keys and lost verificaton ******************************************************************************/ void dc_handle_degrade_event(dc_context_t* context, dc_apeerstate_t* peerstate) { sqlite3_stmt* stmt = NULL; uint32_t contact_id = 0; uint32_t contact_chat_id = 0; if (context==NULL || peerstate==NULL) { goto cleanup; } // - we do not issue an warning for DC_DE_ENCRYPTION_PAUSED as this is quite normal // - currently, we do not issue an extra warning for DC_DE_VERIFICATION_LOST - this always comes // together with DC_DE_FINGERPRINT_CHANGED which is logged, the idea is not to bother // with things they cannot fix, so the user is just kicked from the verified group // (and he will know this and can fix this) if (peerstate->degrade_event & DC_DE_FINGERPRINT_CHANGED) { stmt = dc_sqlite3_prepare(context->sql, "SELECT id FROM contacts WHERE addr=?;"); sqlite3_bind_text(stmt, 1, peerstate->addr, -1, SQLITE_STATIC); sqlite3_step(stmt); contact_id = sqlite3_column_int(stmt, 0); sqlite3_finalize(stmt); if (contact_id==0) { goto cleanup; } dc_create_or_lookup_nchat_by_contact_id(context, contact_id, DC_CHAT_DEADDROP_BLOCKED, &contact_chat_id, NULL); char* msg = dc_stock_str_repl_string(context, DC_STR_CONTACT_SETUP_CHANGED, peerstate->addr); dc_add_device_msg(context, contact_chat_id, msg); free(msg); context->cb(context, DC_EVENT_CHAT_MODIFIED, contact_chat_id, 0); } cleanup: ; } /******************************************************************************* * Tools: Misc. ******************************************************************************/ static int encrypted_and_signed(dc_mimeparser_t* mimeparser, const char* expected_fingerprint) { if (!mimeparser->e2ee_helper->encrypted) { dc_log_warning(mimeparser->context, 0, "Message not encrypted."); return 0; } if (dc_hash_cnt(mimeparser->e2ee_helper->signatures)<=0) { dc_log_warning(mimeparser->context, 0, "Message not signed."); return 0; } if (expected_fingerprint==NULL) { dc_log_warning(mimeparser->context, 0, "Fingerprint for comparison missing."); return 0; } if (dc_hash_find_str(mimeparser->e2ee_helper->signatures, expected_fingerprint)==NULL) { dc_log_warning(mimeparser->context, 0, "Message does not match expected fingerprint %s.", expected_fingerprint); return 0; } return 1; } static char* get_self_fingerprint(dc_context_t* context) { char* self_addr = NULL; dc_key_t* self_key = dc_key_new(); char* fingerprint = NULL; if ((self_addr = dc_sqlite3_get_config(context->sql, "configured_addr", NULL))==NULL || !dc_key_load_self_public(self_key, self_addr, context->sql)) { goto cleanup; } if ((fingerprint=dc_key_get_fingerprint(self_key))==NULL) { goto cleanup; } cleanup: free(self_addr); dc_key_unref(self_key); return fingerprint; } static uint32_t chat_id_2_contact_id(dc_context_t* context, uint32_t contact_chat_id) { uint32_t contact_id = 0; dc_array_t* contacts = dc_get_chat_contacts(context, contact_chat_id); if (dc_array_get_cnt(contacts)!=1) { goto cleanup; } contact_id = dc_array_get_id(contacts, 0); cleanup: dc_array_unref(contacts); return contact_id; } static int fingerprint_equals_sender(dc_context_t* context, const char* fingerprint, uint32_t contact_chat_id) { int fingerprint_equal = 0; dc_array_t* contacts = dc_get_chat_contacts(context, contact_chat_id); dc_contact_t* contact = dc_contact_new(context); dc_apeerstate_t* peerstate = dc_apeerstate_new(context); char* fingerprint_normalized = NULL; if (dc_array_get_cnt(contacts)!=1) { goto cleanup; } if (!dc_contact_load_from_db(contact, context->sql, dc_array_get_id(contacts, 0)) || !dc_apeerstate_load_by_addr(peerstate, context->sql, contact->addr)) { goto cleanup; } fingerprint_normalized = dc_normalize_fingerprint(fingerprint); if (strcasecmp(fingerprint_normalized, peerstate->public_key_fingerprint)==0) { fingerprint_equal = 1; } cleanup: free(fingerprint_normalized); dc_contact_unref(contact); dc_array_unref(contacts); return fingerprint_equal; } static int mark_peer_as_verified(dc_context_t* context, const char* fingerprint) { int success = 0; dc_apeerstate_t* peerstate = dc_apeerstate_new(context); if (!dc_apeerstate_load_by_fingerprint(peerstate, context->sql, fingerprint)) { goto cleanup; } if (!dc_apeerstate_set_verified(peerstate, DC_PS_PUBLIC_KEY, fingerprint, DC_BIDIRECT_VERIFIED)) { goto cleanup; } // set MUTUAL as an out-of-band-verification is a strong hint that encryption is wanted. // the state may be corrected by the Autocrypt headers as usual later; // maybe it is a good idea to add the prefer-encrypt-state to the QR code. peerstate->prefer_encrypt = DC_PE_MUTUAL; peerstate->to_save |= DC_SAVE_ALL; dc_apeerstate_save_to_db(peerstate, context->sql, 0); success = 1; cleanup: dc_apeerstate_unref(peerstate); return success; } static const char* lookup_field(dc_mimeparser_t* mimeparser, const char* key) { const char* value = NULL; struct mailimf_field* field = dc_mimeparser_lookup_field(mimeparser, key); if (field==NULL || field->fld_type!=MAILIMF_FIELD_OPTIONAL_FIELD || field->fld_data.fld_optional_field==NULL || (value=field->fld_data.fld_optional_field->fld_value)==NULL) { return NULL; } return value; } static void send_handshake_msg(dc_context_t* context, uint32_t contact_chat_id, const char* step, const char* param2, const char* fingerprint, const char* grpid) { dc_msg_t* msg = dc_msg_new_untyped(context); msg->type = DC_MSG_TEXT; msg->text = dc_mprintf("Secure-Join: %s", step); msg->hidden = 1; dc_param_set_int(msg->param, DC_PARAM_CMD, DC_CMD_SECUREJOIN_MESSAGE); dc_param_set (msg->param, DC_PARAM_CMD_ARG, step); if (param2) { dc_param_set(msg->param, DC_PARAM_CMD_ARG2, param2); // depening on step, this goes either to Secure-Join-Invitenumber or Secure-Join-Auth in mrmimefactory.c } if (fingerprint) { dc_param_set(msg->param, DC_PARAM_CMD_ARG3, fingerprint); } if (grpid) { dc_param_set(msg->param, DC_PARAM_CMD_ARG4, grpid); } if (strcmp(step, "vg-request")==0 || strcmp(step, "vc-request")==0) { dc_param_set_int(msg->param, DC_PARAM_FORCE_PLAINTEXT, DC_FP_ADD_AUTOCRYPT_HEADER); // the request message MUST NOT be encrypted - it may be that the key has changed and the message cannot be decrypted otherwise } else { dc_param_set_int(msg->param, DC_PARAM_GUARANTEE_E2EE, 1); /* all but the first message MUST be encrypted */ } dc_send_msg(context, contact_chat_id, msg); dc_msg_unref(msg); } static void could_not_establish_secure_connection(dc_context_t* context, uint32_t contact_chat_id, const char* details) { uint32_t contact_id = chat_id_2_contact_id(context, contact_chat_id); dc_contact_t* contact = dc_get_contact(context, contact_id); char* msg = dc_stock_str_repl_string(context, DC_STR_CONTACT_NOT_VERIFIED, contact? contact->addr : "?"); dc_add_device_msg(context, contact_chat_id, msg); dc_log_error(context, 0, "%s (%s)", msg, details); // additionaly raise an error; this typically results in a toast (inviter side) or a dialog (joiner side) free(msg); dc_contact_unref(contact); } static void secure_connection_established(dc_context_t* context, uint32_t contact_chat_id) { uint32_t contact_id = chat_id_2_contact_id(context, contact_chat_id); dc_contact_t* contact = dc_get_contact(context, contact_id); char* msg = dc_stock_str_repl_string(context, DC_STR_CONTACT_VERIFIED, contact? contact->addr : "?"); dc_add_device_msg(context, contact_chat_id, msg); // in addition to DC_EVENT_MSGS_CHANGED (sent by dc_add_device_msg()), also send DC_EVENT_CHAT_MODIFIED to update all views context->cb(context, DC_EVENT_CHAT_MODIFIED, contact_chat_id, 0); free(msg); dc_contact_unref(contact); } static void end_bobs_joining(dc_context_t* context, int status) { context->bobs_status = status; dc_stop_ongoing_process(context); } /******************************************************************************* * Secure-join main flow ******************************************************************************/ /** * Get QR code text that will offer an secure-join verification. * The QR code is compatible to the OPENPGP4FPR format * so that a basic fingerprint comparison also works eg. with OpenKeychain. * * The scanning device will pass the scanned content to dc_check_qr() then; * if this function returns DC_QR_ASK_VERIFYCONTACT or DC_QR_ASK_VERIFYGROUP * an out-of-band-verification can be joined using dc_join_securejoin() * * @memberof dc_context_t * @param context The context object. * @param group_chat_id If set to a group-chat-id, * the group-join-protocol is offered in the QR code; * works for verified groups as well as for normal groups. * If set to 0, the setup-Verified-contact-protocol is offered in the QR code. * @return Text that should go to the QR code, * On errors, an empty QR code is returned, NULL is never returned. * The returned string must be free()'d after usage. */ char* dc_get_securejoin_qr(dc_context_t* context, uint32_t group_chat_id) { /* ========================================================= ==== Alice - the inviter side ==== ==== Step 1 in "Setup verified contact" protocol ==== ========================================================= */ char* qr = NULL; char* self_addr = NULL; char* self_addr_urlencoded = NULL; char* self_name = NULL; char* self_name_urlencoded = NULL; char* fingerprint = NULL; char* invitenumber = NULL; char* auth = NULL; dc_chat_t* chat = NULL; char* group_name = NULL; char* group_name_urlencoded= NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } dc_ensure_secret_key_exists(context); // invitenumber will be used to allow starting the handshake, auth will be used to verify the fingerprint invitenumber = dc_token_lookup(context, DC_TOKEN_INVITENUMBER, group_chat_id); if (invitenumber==NULL) { invitenumber = dc_create_id(); dc_token_save(context, DC_TOKEN_INVITENUMBER, group_chat_id, invitenumber); } auth = dc_token_lookup(context, DC_TOKEN_AUTH, group_chat_id); if (auth==NULL) { auth = dc_create_id(); dc_token_save(context, DC_TOKEN_AUTH, group_chat_id, auth); } if ((self_addr = dc_sqlite3_get_config(context->sql, "configured_addr", NULL))==NULL) { dc_log_error(context, 0, "Not configured, cannot generate QR code."); goto cleanup; } self_name = dc_sqlite3_get_config(context->sql, "displayname", ""); if ((fingerprint=get_self_fingerprint(context))==NULL) { goto cleanup; } self_addr_urlencoded = dc_urlencode(self_addr); self_name_urlencoded = dc_urlencode(self_name); if (group_chat_id) { // parameters used: a=g=x=i=s= chat = dc_get_chat(context, group_chat_id); if (chat==NULL) { dc_log_error(context, 0, "Cannot get QR-code for chat-id %i", group_chat_id); goto cleanup; } group_name = dc_chat_get_name(chat); group_name_urlencoded = dc_urlencode(group_name); qr = dc_mprintf(DC_OPENPGP4FPR_SCHEME "%s#a=%s&g=%s&x=%s&i=%s&s=%s", fingerprint, self_addr_urlencoded, group_name_urlencoded, chat->grpid, invitenumber, auth); } else { // parameters used: a=n=i=s= qr = dc_mprintf(DC_OPENPGP4FPR_SCHEME "%s#a=%s&n=%s&i=%s&s=%s", fingerprint, self_addr_urlencoded, self_name_urlencoded, invitenumber, auth); } dc_log_info(context, 0, "Generated QR code: %s", qr); cleanup: free(self_addr_urlencoded); free(self_addr); free(self_name); free(self_name_urlencoded); free(fingerprint); free(invitenumber); free(auth); dc_chat_unref(chat); free(group_name); free(group_name_urlencoded); return qr? qr : dc_strdup(NULL); } /** * Join an out-of-band-verification initiated on another device with dc_get_securejoin_qr(). * This function is typically called when dc_check_qr() returns * lot.state=DC_QR_ASK_VERIFYCONTACT or lot.state=DC_QR_ASK_VERIFYGROUP. * * This function takes some time and sends and receives several messages. * You should call it in a separate thread; if you want to abort it, you should * call dc_stop_ongoing_process(). * * @memberof dc_context_t * @param context The context object * @param qr The text of the scanned QR code. Typically, the same string as given * to dc_check_qr(). * @return Chat-id of the joined chat, the UI may redirect to the this chat. * If the out-of-band verification failed or was aborted, 0 is returned. */ uint32_t dc_join_securejoin(dc_context_t* context, const char* qr) { /* ========================================================== ==== Bob - the joiner's side ===== ==== Step 2 in "Setup verified contact" protocol ===== ========================================================== */ int ret_chat_id = 0; int ongoing_allocated = 0; uint32_t contact_chat_id = 0; int join_vg = 0; dc_lot_t* qr_scan = NULL; int qr_locked = 0; #define LOCK_QR { pthread_mutex_lock(&context->bobs_qr_critical); qr_locked = 1; } #define UNLOCK_QR if (qr_locked) { pthread_mutex_unlock(&context->bobs_qr_critical); qr_locked = 0; } #define CHECK_EXIT if (context->shall_stop_ongoing) { goto cleanup; } dc_log_info(context, 0, "Requesting secure-join ..."); dc_ensure_secret_key_exists(context); if ((ongoing_allocated=dc_alloc_ongoing(context))==0) { goto cleanup; } if (((qr_scan=dc_check_qr(context, qr))==NULL) || (qr_scan->state!=DC_QR_ASK_VERIFYCONTACT && qr_scan->state!=DC_QR_ASK_VERIFYGROUP)) { dc_log_error(context, 0, "Unknown QR code."); goto cleanup; } if ((contact_chat_id=dc_create_chat_by_contact_id(context, qr_scan->id))==0) { dc_log_error(context, 0, "Unknown contact."); goto cleanup; } CHECK_EXIT join_vg = (qr_scan->state==DC_QR_ASK_VERIFYGROUP); context->bobs_status = 0; LOCK_QR context->bobs_qr_scan = qr_scan; UNLOCK_QR if (fingerprint_equals_sender(context, qr_scan->fingerprint, contact_chat_id)) { // the scanned fingerprint matches Alice's key, we can proceed to step 4b) directly and save two mails dc_log_info(context, 0, "Taking protocol shortcut."); context->bob_expects = DC_VC_CONTACT_CONFIRM; context->cb(context, DC_EVENT_SECUREJOIN_JOINER_PROGRESS, chat_id_2_contact_id(context, contact_chat_id), 400); char* own_fingerprint = get_self_fingerprint(context); send_handshake_msg(context, contact_chat_id, join_vg? "vg-request-with-auth" : "vc-request-with-auth", qr_scan->auth, own_fingerprint, join_vg? qr_scan->text2 : NULL); // Bob -> Alice free(own_fingerprint); } else { context->bob_expects = DC_VC_AUTH_REQUIRED; send_handshake_msg(context, contact_chat_id, join_vg? "vg-request" : "vc-request", qr_scan->invitenumber, NULL, NULL); // Bob -> Alice } while (1) { CHECK_EXIT usleep(300*1000); // 0.3 seconds } cleanup: context->bob_expects = 0; if (context->bobs_status==DC_BOB_SUCCESS) { if (join_vg) { ret_chat_id = dc_get_chat_id_by_grpid(context, qr_scan->text2, NULL, NULL); } else { ret_chat_id = contact_chat_id; } } LOCK_QR context->bobs_qr_scan = NULL; UNLOCK_QR dc_lot_unref(qr_scan); if (ongoing_allocated) { dc_free_ongoing(context); } return ret_chat_id; } /** * Handle incoming handshake messages. Called from receive_imf(). * Assume, when dc_handle_securejoin_handshake() is called, the message is not yet filed in the database. * * @private @memberof dc_context_t * @param context The context object. * @param mimeparser The mail. * @param contact_id Contact-id of the sender (typically the From: header) * @return bitfield of DC_HANDSHAKE_STOP_NORMAL_PROCESSING, DC_HANDSHAKE_CONTINUE_NORMAL_PROCESSING, DC_HANDSHAKE_ADD_DELETE_JOB; * 0 if the message is no secure join message */ int dc_handle_securejoin_handshake(dc_context_t* context, dc_mimeparser_t* mimeparser, uint32_t contact_id) { int qr_locked = 0; const char* step = NULL; int join_vg = 0; char* scanned_fingerprint_of_alice = NULL; char* auth = NULL; char* own_fingerprint = NULL; uint32_t contact_chat_id = 0; int contact_chat_id_blocked = 0; char* grpid = NULL; int ret = 0; dc_contact_t* contact = NULL; if (context==NULL || mimeparser==NULL || contact_id <= DC_CONTACT_ID_LAST_SPECIAL) { goto cleanup; } if ((step=lookup_field(mimeparser, "Secure-Join"))==NULL) { goto cleanup; } dc_log_info(context, 0, ">>>>>>>>>>>>>>>>>>>>>>>>> secure-join message '%s' received", step); join_vg = (strncmp(step, "vg-", 3)==0); dc_create_or_lookup_nchat_by_contact_id(context, contact_id, DC_CHAT_NOT_BLOCKED, &contact_chat_id, &contact_chat_id_blocked); if (contact_chat_id_blocked) { dc_unblock_chat(context, contact_chat_id); } ret = DC_HANDSHAKE_STOP_NORMAL_PROCESSING; if (strcmp(step, "vg-request")==0 || strcmp(step, "vc-request")==0) { /* ========================================================= ==== Alice - the inviter side ==== ==== Step 3 in "Setup verified contact" protocol ==== ========================================================= */ // this message may be unencrypted (Bob, the joinder and the sender, might not have Alice's key yet) // it just ensures, we have Bobs key now. If we do _not_ have the key because eg. MitM has removed it, // send_message() will fail with the error "End-to-end-encryption unavailable unexpectedly.", so, there is no additional check needed here. // verify that the `Secure-Join-Invitenumber:`-header matches invitenumber written to the QR code const char* invitenumber = NULL; if ((invitenumber=lookup_field(mimeparser, "Secure-Join-Invitenumber"))==NULL) { dc_log_warning(context, 0, "Secure-join denied (invitenumber missing)."); // do not raise an error, this might just be spam or come from an old request goto cleanup; } if (dc_token_exists(context, DC_TOKEN_INVITENUMBER, invitenumber)==0) { dc_log_warning(context, 0, "Secure-join denied (bad invitenumber)."); // do not raise an error, this might just be spam or come from an old request goto cleanup; } dc_log_info(context, 0, "Secure-join requested."); context->cb(context, DC_EVENT_SECUREJOIN_INVITER_PROGRESS, contact_id, 300); send_handshake_msg(context, contact_chat_id, join_vg? "vg-auth-required" : "vc-auth-required", NULL, NULL, NULL); // Alice -> Bob } else if (strcmp(step, "vg-auth-required")==0 || strcmp(step, "vc-auth-required")==0) { /* ========================================================== ==== Bob - the joiner's side ===== ==== Step 4 in "Setup verified contact" protocol ===== ========================================================== */ // verify that Alice's Autocrypt key and fingerprint matches the QR-code LOCK_QR if ( context->bobs_qr_scan==NULL || context->bob_expects!=DC_VC_AUTH_REQUIRED || (join_vg && context->bobs_qr_scan->state!=DC_QR_ASK_VERIFYGROUP)) { dc_log_warning(context, 0, "auth-required message out of sync."); goto cleanup; // no error, just aborted somehow or a mail from another handshake } scanned_fingerprint_of_alice = dc_strdup(context->bobs_qr_scan->fingerprint); auth = dc_strdup(context->bobs_qr_scan->auth); if (join_vg) { grpid = dc_strdup(context->bobs_qr_scan->text2); } UNLOCK_QR if (!encrypted_and_signed(mimeparser, scanned_fingerprint_of_alice)) { could_not_establish_secure_connection(context, contact_chat_id, mimeparser->e2ee_helper->encrypted? "No valid signature." : "Not encrypted."); end_bobs_joining(context, DC_BOB_ERROR); goto cleanup; } if (!fingerprint_equals_sender(context, scanned_fingerprint_of_alice, contact_chat_id)) { // MitM? could_not_establish_secure_connection(context, contact_chat_id, "Fingerprint mismatch on joiner-side."); end_bobs_joining(context, DC_BOB_ERROR); goto cleanup; } dc_log_info(context, 0, "Fingerprint verified."); own_fingerprint = get_self_fingerprint(context); context->cb(context, DC_EVENT_SECUREJOIN_JOINER_PROGRESS, contact_id, 400); context->bob_expects = DC_VC_CONTACT_CONFIRM; send_handshake_msg(context, contact_chat_id, join_vg? "vg-request-with-auth" : "vc-request-with-auth", auth, own_fingerprint, grpid); // Bob -> Alice } else if (strcmp(step, "vg-request-with-auth")==0 || strcmp(step, "vc-request-with-auth")==0) { /* ============================================================ ==== Alice - the inviter side ==== ==== Steps 5+6 in "Setup verified contact" protocol ==== ==== Step 6 in "Out-of-band verified groups" protocol ==== ============================================================ */ // verify that Secure-Join-Fingerprint:-header matches the fingerprint of Bob const char* fingerprint = NULL; if ((fingerprint=lookup_field(mimeparser, "Secure-Join-Fingerprint"))==NULL) { could_not_establish_secure_connection(context, contact_chat_id, "Fingerprint not provided."); goto cleanup; } if (!encrypted_and_signed(mimeparser, fingerprint)) { could_not_establish_secure_connection(context, contact_chat_id, "Auth not encrypted."); goto cleanup; } if (!fingerprint_equals_sender(context, fingerprint, contact_chat_id)) { // MitM? could_not_establish_secure_connection(context, contact_chat_id, "Fingerprint mismatch on inviter-side."); goto cleanup; } dc_log_info(context, 0, "Fingerprint verified."); // verify that the `Secure-Join-Auth:`-header matches the secret written to the QR code const char* auth = NULL; if ((auth=lookup_field(mimeparser, "Secure-Join-Auth"))==NULL) { could_not_establish_secure_connection(context, contact_chat_id, "Auth not provided."); goto cleanup; } if (dc_token_exists(context, DC_TOKEN_AUTH, auth)==0) { could_not_establish_secure_connection(context, contact_chat_id, "Auth invalid."); goto cleanup; } if (!mark_peer_as_verified(context, fingerprint)) { could_not_establish_secure_connection(context, contact_chat_id, "Fingerprint mismatch on inviter-side."); // should not happen, we've compared the fingerprint some lines above goto cleanup; } dc_scaleup_contact_origin(context, contact_id, DC_ORIGIN_SECUREJOIN_INVITED); dc_log_info(context, 0, "Auth verified."); secure_connection_established(context, contact_chat_id); context->cb(context, DC_EVENT_CONTACTS_CHANGED, contact_id/*selected contact*/, 0); context->cb(context, DC_EVENT_SECUREJOIN_INVITER_PROGRESS, contact_id, 600); if (join_vg) { // the vg-member-added message is special: this is a normal Chat-Group-Member-Added message with an additional Secure-Join header grpid = dc_strdup(lookup_field(mimeparser, "Secure-Join-Group")); uint32_t group_chat_id = dc_get_chat_id_by_grpid(context, grpid, NULL, NULL); if (group_chat_id==0) { dc_log_error(context, 0, "Chat %s not found.", grpid); goto cleanup; } dc_add_contact_to_chat_ex(context, group_chat_id, contact_id, DC_FROM_HANDSHAKE); // Alice -> Bob and all members } else { send_handshake_msg(context, contact_chat_id, "vc-contact-confirm", NULL, NULL, NULL); // Alice -> Bob context->cb(context, DC_EVENT_SECUREJOIN_INVITER_PROGRESS, contact_id, 1000); // done contact joining } } else if (strcmp(step, "vg-member-added")==0 || strcmp(step, "vc-contact-confirm")==0) { /* ========================================================== ==== Bob - the joiner's side ===== ==== Step 7 in "Setup verified contact" protocol ===== ========================================================== */ if (join_vg) { // vg-member-added is just part of a Chat-Group-Member-Added which should be kept in any way, eg. for multi-client ret = DC_HANDSHAKE_CONTINUE_NORMAL_PROCESSING; } if (context->bob_expects!=DC_VC_CONTACT_CONFIRM) { dc_log_info(context, 0, "Message belongs to a different handshake."); goto cleanup; } LOCK_QR if (context->bobs_qr_scan==NULL || (join_vg && context->bobs_qr_scan->state!=DC_QR_ASK_VERIFYGROUP)) { dc_log_warning(context, 0, "Message out of sync or belongs to a different handshake."); goto cleanup; } scanned_fingerprint_of_alice = dc_strdup(context->bobs_qr_scan->fingerprint); if (join_vg) { grpid = dc_strdup(context->bobs_qr_scan->text2); } UNLOCK_QR int vg_expect_encrypted = 1; if (join_vg) { int is_verified_group = 0; dc_get_chat_id_by_grpid(context, grpid, NULL, &is_verified_group); if (!is_verified_group) { // when joining a normal group after verification, // the vg-member-added message may be unencrypted // when not all group members have keys or prefer encryption. // this does not affect the contact verification as such. vg_expect_encrypted = 0; } } if (vg_expect_encrypted) { if (!encrypted_and_signed(mimeparser, scanned_fingerprint_of_alice)) { could_not_establish_secure_connection(context, contact_chat_id, "Contact confirm message not encrypted."); end_bobs_joining(context, DC_BOB_ERROR); goto cleanup; } } if (!mark_peer_as_verified(context, scanned_fingerprint_of_alice)) { could_not_establish_secure_connection(context, contact_chat_id, "Fingerprint mismatch on joiner-side."); // MitM? - key has changed since vc-auth-required message goto cleanup; } dc_scaleup_contact_origin(context, contact_id, DC_ORIGIN_SECUREJOIN_JOINED); context->cb(context, DC_EVENT_CONTACTS_CHANGED, 0/*no select event*/, 0); if (join_vg) { if (!dc_addr_equals_self(context, lookup_field(mimeparser, "Chat-Group-Member-Added"))) { dc_log_info(context, 0, "Message belongs to a different handshake (scaled up contact anyway to allow creation of group)."); goto cleanup; } } secure_connection_established(context, contact_chat_id); context->bob_expects = 0; if (join_vg) { send_handshake_msg(context, contact_chat_id, "vg-member-added-received", NULL, NULL, NULL); // Bob -> Alice } end_bobs_joining(context, DC_BOB_SUCCESS); } else if (strcmp(step, "vg-member-added-received")==0) { /* ============================================================ ==== Alice - the inviter side ==== ==== Step 8 in "Out-of-band verified groups" protocol ==== ============================================================ */ if (NULL==(contact=dc_get_contact(context, contact_id)) || !dc_contact_is_verified(contact)) { dc_log_warning(context, 0, "vg-member-added-received invalid."); goto cleanup; } context->cb(context, DC_EVENT_SECUREJOIN_INVITER_PROGRESS, contact_id, 800); context->cb(context, DC_EVENT_SECUREJOIN_INVITER_PROGRESS, contact_id, 1000); // done group joining } // for errors, we do not the corresponding message at all, // it may come eg. from another device or may be useful to find out what was going wrong. if (ret & DC_HANDSHAKE_STOP_NORMAL_PROCESSING) { ret |= DC_HANDSHAKE_ADD_DELETE_JOB; } cleanup: UNLOCK_QR dc_contact_unref(contact); free(scanned_fingerprint_of_alice); free(auth); free(own_fingerprint); free(grpid); return ret; } /** * @} */ ``` Filename: dc_smtp.c ```c #include #include #include "dc_context.h" #include "dc_smtp.h" #include "dc_job.h" #include "dc_oauth2.h" #ifndef DEBUG_SMTP #define DEBUG_SMTP 0 #endif dc_smtp_t* dc_smtp_new(dc_context_t* context) { dc_smtp_t* smtp = NULL; if ((smtp=calloc(1, sizeof(dc_smtp_t)))==NULL) { exit(29); } smtp->log_connect_errors = 1; smtp->context = context; /* should be used for logging only */ return smtp; } void dc_smtp_unref(dc_smtp_t* smtp) { if (smtp==NULL) { return; } dc_smtp_disconnect(smtp); free(smtp->from); free(smtp->error); free(smtp); } static void log_error(dc_smtp_t* smtp, const char* what_failed, int r) { char* error_msg = dc_mprintf("%s: %s: %s", what_failed, mailsmtp_strerror(r), smtp->etpan->response); dc_log_warning(smtp->context, 0, "%s", error_msg); free(smtp->error); smtp->error = error_msg; smtp->error_etpan = r; } int dc_smtp_is_connected(const dc_smtp_t* smtp) { return (smtp && smtp->etpan)? 1 : 0; } static void body_progress(size_t current, size_t maximum, void* user_data) { #if DEBUG_SMTP printf("body_progress called with current=%i, maximum=%i.", (int)current, (int)maximum); #endif } #if DEBUG_SMTP static void logger(mailsmtp* smtp, int log_type, const char* buffer__, size_t size, void* user_data) { char* buffer = malloc(size+1); memcpy(buffer, buffer__, size); buffer[size] = 0; printf("SMTP: %i: %s", log_type, buffer__); } #endif int dc_smtp_connect(dc_smtp_t* smtp, const dc_loginparam_t* lp) { int success = 0; int r = 0; int try_esmtp = 0; if (smtp==NULL || lp==NULL) { return 0; } if (smtp->etpan) { dc_log_warning(smtp->context, 0, "SMTP already connected."); success = 1; /* otherwise, the handle would get deleted */ goto cleanup; } if (lp->addr==NULL || lp->send_server==NULL || lp->send_port==0) { dc_log_event_seq(smtp->context, DC_EVENT_ERROR_NETWORK, &smtp->log_connect_errors, "SMTP bad parameters."); goto cleanup; } free(smtp->from); smtp->from = dc_strdup(lp->addr); smtp->etpan = mailsmtp_new(0, NULL); if (smtp->etpan==NULL) { dc_log_error(smtp->context, 0, "SMTP-object creation failed."); goto cleanup; } mailsmtp_set_timeout(smtp->etpan, DC_SMTP_TIMEOUT_SEC); mailsmtp_set_progress_callback(smtp->etpan, body_progress, smtp); #if DEBUG_SMTP mailsmtp_set_logger(smtp->etpan, logger, smtp); #endif /* connect to SMTP server */ if (lp->server_flags&(DC_LP_SMTP_SOCKET_STARTTLS|DC_LP_SMTP_SOCKET_PLAIN)) { if ((r=mailsmtp_socket_connect(smtp->etpan, lp->send_server, lp->send_port)) != MAILSMTP_NO_ERROR) { dc_log_event_seq(smtp->context, DC_EVENT_ERROR_NETWORK, &smtp->log_connect_errors, "SMTP-Socket connection to %s:%i failed (%s)", lp->send_server, (int)lp->send_port, mailsmtp_strerror(r)); goto cleanup; } } else { if ((r=mailsmtp_ssl_connect(smtp->etpan, lp->send_server, lp->send_port)) != MAILSMTP_NO_ERROR) { dc_log_event_seq(smtp->context, DC_EVENT_ERROR_NETWORK, &smtp->log_connect_errors, "SMTP-SSL connection to %s:%i failed (%s)", lp->send_server, (int)lp->send_port, mailsmtp_strerror(r)); goto cleanup; } } try_esmtp = 1; smtp->esmtp = 0; if (try_esmtp && (r=mailesmtp_ehlo(smtp->etpan))==MAILSMTP_NO_ERROR) { smtp->esmtp = 1; } else if (!try_esmtp || r==MAILSMTP_ERROR_NOT_IMPLEMENTED) { r = mailsmtp_helo(smtp->etpan); } if (r != MAILSMTP_NO_ERROR) { dc_log_event_seq(smtp->context, DC_EVENT_ERROR_NETWORK, &smtp->log_connect_errors, "SMTP-helo failed (%s)", mailsmtp_strerror(r)); goto cleanup; } if (lp->server_flags&DC_LP_SMTP_SOCKET_STARTTLS) { if ((r=mailsmtp_socket_starttls(smtp->etpan)) != MAILSMTP_NO_ERROR) { dc_log_event_seq(smtp->context, DC_EVENT_ERROR_NETWORK, &smtp->log_connect_errors, "SMTP-STARTTLS failed (%s)", mailsmtp_strerror(r)); goto cleanup; } smtp->esmtp = 0; if (try_esmtp && (r=mailesmtp_ehlo(smtp->etpan))==MAILSMTP_NO_ERROR) { smtp->esmtp = 1; } else if (!try_esmtp || r==MAILSMTP_ERROR_NOT_IMPLEMENTED) { r = mailsmtp_helo(smtp->etpan); } if (r != MAILSMTP_NO_ERROR) { dc_log_event_seq(smtp->context, DC_EVENT_ERROR_NETWORK, &smtp->log_connect_errors, "SMTP-helo failed (%s)", mailsmtp_strerror(r)); goto cleanup; } dc_log_info(smtp->context, 0, "SMTP-server %s:%i STARTTLS-connected.", lp->send_server, (int)lp->send_port); } else if (lp->server_flags&DC_LP_SMTP_SOCKET_PLAIN) { dc_log_info(smtp->context, 0, "SMTP-server %s:%i connected.", lp->send_server, (int)lp->send_port); } else { dc_log_info(smtp->context, 0, "SMTP-server %s:%i SSL-connected.", lp->send_server, (int)lp->send_port); } if (lp->send_user) { if (lp->server_flags&DC_LP_AUTH_OAUTH2) { dc_log_info(smtp->context, 0, "SMTP-OAuth2 connect..."); char* access_token = dc_get_oauth2_access_token(smtp->context, lp->addr, lp->send_pw, 0); // if we want to support outlook, there is a mailsmtp_oauth2_outlook_authenticate() ... if ((r = mailsmtp_oauth2_authenticate(smtp->etpan, lp->send_user, access_token)) != MAILSMTP_NO_ERROR) { free(access_token); access_token = dc_get_oauth2_access_token(smtp->context, lp->addr, lp->send_pw, DC_REGENERATE); r = mailsmtp_oauth2_authenticate(smtp->etpan, lp->send_user, access_token); } free(access_token); } else if((r=mailsmtp_auth(smtp->etpan, lp->send_user, lp->send_pw))!=MAILSMTP_NO_ERROR) { /* * There are some Mailservers which do not correclty implement PLAIN auth (hMail) * So here we try a workaround. See https://github.com/deltachat/deltachat-android/issues/67 */ if (smtp->etpan->auth & MAILSMTP_AUTH_PLAIN) { dc_log_info(smtp->context, 0, "Trying SMTP-Login workaround \"%s\"...", lp->send_user); int err; char hostname[513]; err = gethostname(hostname, sizeof(hostname)); if (err < 0) { dc_log_error(smtp->context, 0, "SMTP-Login: Cannot get hostname."); goto cleanup; } r = mailesmtp_auth_sasl(smtp->etpan, "PLAIN", hostname, NULL, NULL, NULL, lp->send_user, lp->send_pw, NULL); } } if (r != MAILSMTP_NO_ERROR) { dc_log_event_seq(smtp->context, DC_EVENT_ERROR_NETWORK, &smtp->log_connect_errors, "SMTP-login failed for user %s (%s)", lp->send_user, mailsmtp_strerror(r)); goto cleanup; } dc_log_event(smtp->context, DC_EVENT_SMTP_CONNECTED, 0, "SMTP-login as %s ok.", lp->send_user); } success = 1; cleanup: if (!success) { if (smtp->etpan) { mailsmtp_free(smtp->etpan); smtp->etpan = NULL; } } return success; } void dc_smtp_disconnect(dc_smtp_t* smtp) { if (smtp==NULL) { return; } if (smtp->etpan) { //mailsmtp_quit(smtp->etpan); -- ? mailsmtp_free(smtp->etpan); smtp->etpan = NULL; } } /******************************************************************************* * Send a message ******************************************************************************/ int dc_smtp_send_msg(dc_smtp_t* smtp, const clist* recipients, const char* data_not_terminated, size_t data_bytes) { int success = 0; int r = 0; clistiter* iter = NULL; if (smtp==NULL) { goto cleanup; } if (recipients==NULL || clist_count(recipients)==0 || data_not_terminated==NULL || data_bytes==0) { success = 1; goto cleanup; // "null message" send } if (smtp->etpan==NULL) { goto cleanup; } // set source // the `etPanSMTPTest` is the ENVID from RFC 3461 (SMTP DSNs), we should probably replace it by a random value if ((r=(smtp->esmtp? mailesmtp_mail(smtp->etpan, smtp->from, 1, "etPanSMTPTest") : mailsmtp_mail(smtp->etpan, smtp->from))) != MAILSMTP_NO_ERROR) { // this error is very usual - we've simply lost the server connection and reconnect as soon as possible. // log_error() does log the error as a warning in the first place, the caller will log the error later if it is not recovered. log_error(smtp, "SMTP failed to start message", r); goto cleanup; } // set recipients // if the recipient is on the same server, this may fail at once. // TODO: question is what to do if one recipient in a group fails for (iter=clist_begin(recipients); iter!=NULL; iter=clist_next(iter)) { const char* rcpt = clist_content(iter); if ((r = (smtp->esmtp? mailesmtp_rcpt(smtp->etpan, rcpt, MAILSMTP_DSN_NOTIFY_FAILURE|MAILSMTP_DSN_NOTIFY_DELAY, NULL) : mailsmtp_rcpt(smtp->etpan, rcpt))) != MAILSMTP_NO_ERROR) { log_error(smtp, "SMTP failed to add recipient", r); goto cleanup; } } // message if ((r = mailsmtp_data(smtp->etpan)) != MAILSMTP_NO_ERROR) { log_error(smtp, "SMTP failed to set data", r); goto cleanup; } if ((r = mailsmtp_data_message(smtp->etpan, data_not_terminated, data_bytes)) != MAILSMTP_NO_ERROR) { log_error(smtp, "SMTP failed to send message", r); goto cleanup; } dc_log_event(smtp->context, DC_EVENT_SMTP_MESSAGE_SENT, 0, "Message was sent to SMTP server"); success = 1; cleanup: return success; } ``` Filename: dc_sqlite3.c ```c #include #include #include #include "dc_context.h" #include "dc_apeerstate.h" /* This class wraps around SQLite. We use a single handle for the database connections, mainly because we do not know from which threads the UI calls the dc_*() functions. As the open the Database in serialized mode explicitly, in general, this is safe. However, there are some points to keep in mind: 1. Reading can be done at the same time from several threads, however, only one thread can write. If a seconds thread tries to write, this thread is halted until the first has finished writing, at most the timespan set by sqlite3_busy_timeout(). 2. Transactions are possible using `BEGIN IMMEDIATE` (this causes the first thread trying to write to block the others as described in 1. Transaction cannot be nested, we recommend to use them only in the top-level functions or not to use them. 3. Using sqlite3_last_insert_rowid() and sqlite3_changes() cause race conditions (between the query and the call another thread may insert or update a row. These functions MUST NOT be used; dc_sqlite3_get_rowid() provides an alternative. */ void dc_sqlite3_log_error(dc_sqlite3_t* sql, const char* msg_format, ...) { char* msg = NULL; va_list va; if (sql==NULL || msg_format==NULL) { return; } va_start(va, msg_format); msg = sqlite3_vmprintf(msg_format, va); dc_log_error(sql->context, 0, "%s SQLite says: %s", msg? msg : "", sql->cobj? sqlite3_errmsg(sql->cobj) : "SQLite object not set up."); sqlite3_free(msg); va_end(va); } sqlite3_stmt* dc_sqlite3_prepare(dc_sqlite3_t* sql, const char* querystr) { sqlite3_stmt* stmt = NULL; if (sql==NULL || querystr==NULL || sql->cobj==NULL) { return NULL; } if (sqlite3_prepare_v2(sql->cobj, querystr, -1 /*read `querystr` up to the first null-byte*/, &stmt, NULL /*tail not interesting, we use only single statements*/) != SQLITE_OK) { dc_sqlite3_log_error(sql, "Query failed: %s", querystr); return NULL; } /* success - the result must be freed using sqlite3_finalize() */ return stmt; } int dc_sqlite3_try_execute(dc_sqlite3_t* sql, const char* querystr) { // same as dc_sqlite3_execute() but does not pass error to ui int success = 0; sqlite3_stmt* stmt = NULL; int sql_state = 0; stmt = dc_sqlite3_prepare(sql, querystr); if (stmt==NULL) { goto cleanup; } sql_state = sqlite3_step(stmt); if (sql_state != SQLITE_DONE && sql_state != SQLITE_ROW) { dc_log_warning(sql->context, 0, "Try-execute for \"%s\" failed: %s", querystr, sqlite3_errmsg(sql->cobj)); goto cleanup; } success = 1; cleanup: sqlite3_finalize(stmt); return success; } int dc_sqlite3_execute(dc_sqlite3_t* sql, const char* querystr) { int success = 0; sqlite3_stmt* stmt = NULL; int sqlState = 0; stmt = dc_sqlite3_prepare(sql, querystr); if (stmt==NULL) { goto cleanup; } sqlState = sqlite3_step(stmt); if (sqlState != SQLITE_DONE && sqlState != SQLITE_ROW) { dc_sqlite3_log_error(sql, "Cannot execute \"%s\".", querystr); goto cleanup; } success = 1; cleanup: sqlite3_finalize(stmt); return success; } uint32_t dc_sqlite3_get_rowid(dc_sqlite3_t* sql, const char* table, const char* field, const char* value) { // alternative to sqlite3_last_insert_rowid() which MUST NOT be used due to race conditions, see comment above. // the ORDER BY ensures, this function always returns the most recent id, // eg. if a Message-ID is splitted into different messages. uint32_t id = 0; char* q3 = sqlite3_mprintf("SELECT id FROM %s WHERE %s=%Q ORDER BY id DESC;", table, field, value); sqlite3_stmt* stmt = dc_sqlite3_prepare(sql, q3); if (SQLITE_ROW==sqlite3_step(stmt)) { id = sqlite3_column_int(stmt, 0); } sqlite3_finalize(stmt); sqlite3_free(q3); return id; } uint32_t dc_sqlite3_get_rowid2(dc_sqlite3_t* sql, const char* table, const char* field, uint64_t value, const char* field2, uint32_t value2) { // same as dc_sqlite3_get_rowid() with a key over two columns uint32_t id = 0; // see https://www.sqlite.org/printf.html for sqlite-printf modifiers char* q3 = sqlite3_mprintf( "SELECT id FROM %s WHERE %s=%lli AND %s=%i ORDER BY id DESC;", table, field, value, field2, value2); sqlite3_stmt* stmt = dc_sqlite3_prepare(sql, q3); if (SQLITE_ROW==sqlite3_step(stmt)) { id = sqlite3_column_int(stmt, 0); } sqlite3_finalize(stmt); sqlite3_free(q3); return id; } dc_sqlite3_t* dc_sqlite3_new(dc_context_t* context) { dc_sqlite3_t* sql = NULL; if ((sql=calloc(1, sizeof(dc_sqlite3_t)))==NULL) { exit(24); /* cannot allocate little memory, unrecoverable error */ } sql->context = context; return sql; } void dc_sqlite3_unref(dc_sqlite3_t* sql) { if (sql==NULL) { return; } if (sql->cobj) { dc_sqlite3_close(sql); } free(sql); } int dc_sqlite3_open(dc_sqlite3_t* sql, const char* dbfile, int flags) { if (dc_sqlite3_is_open(sql)) { return 0; // a cleanup would close the database } if (sql==NULL || dbfile==NULL) { goto cleanup; } if (sqlite3_threadsafe()==0) { dc_log_error(sql->context, 0, "Sqlite3 compiled thread-unsafe; this is not supported."); goto cleanup; } if (sql->cobj) { dc_log_error(sql->context, 0, "Cannot open, database \"%s\" already opened.", dbfile); goto cleanup; } // Force serialized mode (SQLITE_OPEN_FULLMUTEX) explicitly. // So, most of the explicit lock/unlocks on dc_sqlite3_t object are no longer needed. // However, locking is _also_ used for dc_context_t which _is_ still needed, so, we // should remove locks only if we're really sure. // // `PRAGMA cache_size` and `PRAGMA page_size`: As we save BLOBs in external // files, caching is not that important; we rely on the system defaults here // (normally 2 MB cache, 1 KB page size on sqlite < 3.12.0, 4 KB for newer // versions) if (sqlite3_open_v2(dbfile, &sql->cobj, SQLITE_OPEN_FULLMUTEX | ((flags&DC_OPEN_READONLY)? SQLITE_OPEN_READONLY : (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE)), NULL) != SQLITE_OK) { dc_sqlite3_log_error(sql, "Cannot open database \"%s\".", dbfile); /* ususally, even for errors, the pointer is set up (if not, this is also checked by dc_sqlite3_log_error()) */ goto cleanup; } // let SQLite overwrite deleted content with zeros dc_sqlite3_execute(sql, "PRAGMA secure_delete=on;"); // Only one process can make changes to the database at one time. // busy_timeout defines, that if a seconds process wants write access, this second process will wait some milliseconds // and try over until it gets write access or the given timeout is elapsed. // If the second process does not get write access within the given timeout, sqlite3_step() will return the error SQLITE_BUSY. // (without a busy_timeout, sqlite3_step() would return SQLITE_BUSY at once) sqlite3_busy_timeout(sql->cobj, 10*1000); if (!(flags&DC_OPEN_READONLY)) { int exists_before_update = 0; int dbversion_before_update = 0; /* Init tables to dbversion=0 */ if (!dc_sqlite3_table_exists(sql, "config")) { dc_log_info(sql->context, 0, "First time init: creating tables in \"%s\".", dbfile); // the row with the type `INTEGER PRIMARY KEY` is an alias to the 64-bit-ROWID present in every table // we re-use this ID for our own purposes. // (the last inserted ROWID can be accessed using sqlite3_last_insert_rowid(), which, however, is // not recommended as not thread-safe, see above) dc_sqlite3_execute(sql, "CREATE TABLE config (id INTEGER PRIMARY KEY, keyname TEXT, value TEXT);"); dc_sqlite3_execute(sql, "CREATE INDEX config_index1 ON config (keyname);"); dc_sqlite3_execute(sql, "CREATE TABLE contacts (id INTEGER PRIMARY KEY AUTOINCREMENT," " name TEXT DEFAULT ''," " addr TEXT DEFAULT '' COLLATE NOCASE," " origin INTEGER DEFAULT 0," " blocked INTEGER DEFAULT 0," " last_seen INTEGER DEFAULT 0," /* last_seen is for future use */ " param TEXT DEFAULT '');"); /* param is for future use, eg. for the status */ dc_sqlite3_execute(sql, "CREATE INDEX contacts_index1 ON contacts (name COLLATE NOCASE);"); /* needed for query contacts */ dc_sqlite3_execute(sql, "CREATE INDEX contacts_index2 ON contacts (addr COLLATE NOCASE);"); /* needed for query and on receiving mails */ dc_sqlite3_execute(sql, "INSERT INTO contacts (id,name,origin) VALUES (1,'self',262144), (2,'device',262144), (3,'rsvd',262144), (4,'rsvd',262144), (5,'rsvd',262144), (6,'rsvd',262144), (7,'rsvd',262144), (8,'rsvd',262144), (9,'rsvd',262144);"); #if !defined(DC_ORIGIN_INTERNAL) || DC_ORIGIN_INTERNAL!=262144 #error #endif dc_sqlite3_execute(sql, "CREATE TABLE chats (id INTEGER PRIMARY KEY AUTOINCREMENT, " " type INTEGER DEFAULT 0," " name TEXT DEFAULT ''," " draft_timestamp INTEGER DEFAULT 0," " draft_txt TEXT DEFAULT ''," " blocked INTEGER DEFAULT 0," " grpid TEXT DEFAULT ''," /* contacts-global unique group-ID, see dc_chat.c for details */ " param TEXT DEFAULT '');"); dc_sqlite3_execute(sql, "CREATE INDEX chats_index1 ON chats (grpid);"); dc_sqlite3_execute(sql, "CREATE TABLE chats_contacts (chat_id INTEGER, contact_id INTEGER);"); dc_sqlite3_execute(sql, "CREATE INDEX chats_contacts_index1 ON chats_contacts (chat_id);"); dc_sqlite3_execute(sql, "INSERT INTO chats (id,type,name) VALUES (1,120,'deaddrop'), (2,120,'rsvd'), (3,120,'trash'), (4,120,'msgs_in_creation'), (5,120,'starred'), (6,120,'archivedlink'), (7,100,'rsvd'), (8,100,'rsvd'), (9,100,'rsvd');"); #if !defined(DC_CHAT_TYPE_SINGLE) || DC_CHAT_TYPE_SINGLE!=100 || DC_CHAT_TYPE_GROUP!=120 || \ DC_CHAT_ID_DEADDROP!=1 || DC_CHAT_ID_TRASH!=3 || \ DC_CHAT_ID_MSGS_IN_CREATION!=4 || DC_CHAT_ID_STARRED!=5 || DC_CHAT_ID_ARCHIVED_LINK!=6 || \ DC_CHAT_NOT_BLOCKED!=0 || DC_CHAT_MANUALLY_BLOCKED!=1 || DC_CHAT_DEADDROP_BLOCKED!=2 #error #endif dc_sqlite3_execute(sql, "CREATE TABLE msgs (id INTEGER PRIMARY KEY AUTOINCREMENT," " rfc724_mid TEXT DEFAULT ''," /* forever-global-unique Message-ID-string, unfortunately, this cannot be easily used to communicate via IMAP */ " server_folder TEXT DEFAULT ''," /* folder as used on the server, the folder will change when messages are moved around. */ " server_uid INTEGER DEFAULT 0," /* UID as used on the server, the UID will change when messages are moved around, unique together with validity, see RFC 3501; the validity may differ from folder to folder. We use the server_uid for "markseen" and to delete messages as we check against the message-id, we ignore the validity for these commands. */ " chat_id INTEGER DEFAULT 0," " from_id INTEGER DEFAULT 0," " to_id INTEGER DEFAULT 0," /* to_id is needed to allow moving messages eg. from "deaddrop" to a normal chat, may be unset */ " timestamp INTEGER DEFAULT 0," " type INTEGER DEFAULT 0," " state INTEGER DEFAULT 0," " msgrmsg INTEGER DEFAULT 1," /* does the message come from a messenger? (0=no, 1=yes, 2=no, but the message is a reply to a messenger message) */ " bytes INTEGER DEFAULT 0," /* not used, added in ~ v0.1.12 */ " txt TEXT DEFAULT ''," " txt_raw TEXT DEFAULT ''," " param TEXT DEFAULT '');"); dc_sqlite3_execute(sql, "CREATE INDEX msgs_index1 ON msgs (rfc724_mid);"); /* in our database, one email may be split up to several messages (eg. one per image), so the email-Message-ID may be used for several records; id is always unique */ dc_sqlite3_execute(sql, "CREATE INDEX msgs_index2 ON msgs (chat_id);"); dc_sqlite3_execute(sql, "CREATE INDEX msgs_index3 ON msgs (timestamp);"); /* for sorting */ dc_sqlite3_execute(sql, "CREATE INDEX msgs_index4 ON msgs (state);"); /* for selecting the count of fresh messages (as there are normally only few unread messages, an index over the chat_id is not required for _this_ purpose */ dc_sqlite3_execute(sql, "INSERT INTO msgs (id,msgrmsg,txt) VALUES (1,0,'marker1'), (2,0,'rsvd'), (3,0,'rsvd'), (4,0,'rsvd'), (5,0,'rsvd'), (6,0,'rsvd'), (7,0,'rsvd'), (8,0,'rsvd'), (9,0,'daymarker');"); /* make sure, the reserved IDs are not used */ dc_sqlite3_execute(sql, "CREATE TABLE jobs (id INTEGER PRIMARY KEY AUTOINCREMENT," " added_timestamp INTEGER," " desired_timestamp INTEGER DEFAULT 0," " action INTEGER," " foreign_id INTEGER," " param TEXT DEFAULT '');"); dc_sqlite3_execute(sql, "CREATE INDEX jobs_index1 ON jobs (desired_timestamp);"); if (!dc_sqlite3_table_exists(sql, "config") || !dc_sqlite3_table_exists(sql, "contacts") || !dc_sqlite3_table_exists(sql, "chats") || !dc_sqlite3_table_exists(sql, "chats_contacts") || !dc_sqlite3_table_exists(sql, "msgs") || !dc_sqlite3_table_exists(sql, "jobs")) { dc_sqlite3_log_error(sql, "Cannot create tables in new database \"%s\".", dbfile); goto cleanup; /* cannot create the tables - maybe we cannot write? */ } dc_sqlite3_set_config_int(sql, "dbversion", 0); } else { exists_before_update = 1; dbversion_before_update = dc_sqlite3_get_config_int(sql, "dbversion", 0); } // (1) update low-level database structure. // this should be done before updates that use high-level objects that // rely themselves on the low-level structure. // -------------------------------------------------------------------- int dbversion = dbversion_before_update; int recalc_fingerprints = 0; int update_file_paths = 0; #define NEW_DB_VERSION 1 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "CREATE TABLE leftgrps (" " id INTEGER PRIMARY KEY," " grpid TEXT DEFAULT '');"); dc_sqlite3_execute(sql, "CREATE INDEX leftgrps_index1 ON leftgrps (grpid);"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 2 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "ALTER TABLE contacts ADD COLUMN authname TEXT DEFAULT '';"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 7 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "CREATE TABLE keypairs (" " id INTEGER PRIMARY KEY," " addr TEXT DEFAULT '' COLLATE NOCASE," " is_default INTEGER DEFAULT 0," " private_key," " public_key," " created INTEGER DEFAULT 0);"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 10 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "CREATE TABLE acpeerstates (" " id INTEGER PRIMARY KEY," " addr TEXT DEFAULT '' COLLATE NOCASE," /* no UNIQUE here, Autocrypt: requires the index above mail+type (type however, is not used at the moment, but to be future-proof, we do not use an index. instead we just check ourself if there is a record or not)*/ " last_seen INTEGER DEFAULT 0," " last_seen_autocrypt INTEGER DEFAULT 0," " public_key," " prefer_encrypted INTEGER DEFAULT 0);"); dc_sqlite3_execute(sql, "CREATE INDEX acpeerstates_index1 ON acpeerstates (addr);"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 12 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "CREATE TABLE msgs_mdns (" " msg_id INTEGER, " " contact_id INTEGER);"); dc_sqlite3_execute(sql, "CREATE INDEX msgs_mdns_index1 ON msgs_mdns (msg_id);"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 17 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "ALTER TABLE chats ADD COLUMN archived INTEGER DEFAULT 0;"); dc_sqlite3_execute(sql, "CREATE INDEX chats_index2 ON chats (archived);"); dc_sqlite3_execute(sql, "ALTER TABLE msgs ADD COLUMN starred INTEGER DEFAULT 0;"); dc_sqlite3_execute(sql, "CREATE INDEX msgs_index5 ON msgs (starred);"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 18 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "ALTER TABLE acpeerstates ADD COLUMN gossip_timestamp INTEGER DEFAULT 0;"); dc_sqlite3_execute(sql, "ALTER TABLE acpeerstates ADD COLUMN gossip_key;"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 27 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "DELETE FROM msgs WHERE chat_id=1 OR chat_id=2;"); /* chat.id=1 and chat.id=2 are the old deaddrops, the current ones are defined by chats.blocked=2 */ dc_sqlite3_execute(sql, "CREATE INDEX chats_contacts_index2 ON chats_contacts (contact_id);"); /* needed to find chat by contact list */ dc_sqlite3_execute(sql, "ALTER TABLE msgs ADD COLUMN timestamp_sent INTEGER DEFAULT 0;"); dc_sqlite3_execute(sql, "ALTER TABLE msgs ADD COLUMN timestamp_rcvd INTEGER DEFAULT 0;"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 34 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "ALTER TABLE msgs ADD COLUMN hidden INTEGER DEFAULT 0;"); dc_sqlite3_execute(sql, "ALTER TABLE msgs_mdns ADD COLUMN timestamp_sent INTEGER DEFAULT 0;"); dc_sqlite3_execute(sql, "ALTER TABLE acpeerstates ADD COLUMN public_key_fingerprint TEXT DEFAULT '';"); /* do not add `COLLATE NOCASE` case-insensivity is not needed as we force uppercase on store - otoh case-sensivity may be neeed for other/upcoming fingerprint formats */ dc_sqlite3_execute(sql, "ALTER TABLE acpeerstates ADD COLUMN gossip_key_fingerprint TEXT DEFAULT '';"); /* do not add `COLLATE NOCASE` case-insensivity is not needed as we force uppercase on store - otoh case-sensivity may be neeed for other/upcoming fingerprint formats */ dc_sqlite3_execute(sql, "CREATE INDEX acpeerstates_index3 ON acpeerstates (public_key_fingerprint);"); dc_sqlite3_execute(sql, "CREATE INDEX acpeerstates_index4 ON acpeerstates (gossip_key_fingerprint);"); recalc_fingerprints = 1; dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 39 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "CREATE TABLE tokens (" " id INTEGER PRIMARY KEY," " namespc INTEGER DEFAULT 0," " foreign_id INTEGER DEFAULT 0," " token TEXT DEFAULT ''," " timestamp INTEGER DEFAULT 0);"); dc_sqlite3_execute(sql, "ALTER TABLE acpeerstates ADD COLUMN verified_key;"); dc_sqlite3_execute(sql, "ALTER TABLE acpeerstates ADD COLUMN verified_key_fingerprint TEXT DEFAULT '';"); /* do not add `COLLATE NOCASE` case-insensivity is not needed as we force uppercase on store - otoh case-sensivity may be neeed for other/upcoming fingerprint formats */ dc_sqlite3_execute(sql, "CREATE INDEX acpeerstates_index5 ON acpeerstates (verified_key_fingerprint);"); if (dbversion_before_update==34) { // migrate database from the use of verified-flags to verified_key, // _only_ version 34 (0.17.0) has the fields public_key_verified and gossip_key_verified // this block can be deleted in half a year or so (created 5/2018) dc_sqlite3_execute(sql, "UPDATE acpeerstates SET verified_key=gossip_key, verified_key_fingerprint=gossip_key_fingerprint WHERE gossip_key_verified=2;"); dc_sqlite3_execute(sql, "UPDATE acpeerstates SET verified_key=public_key, verified_key_fingerprint=public_key_fingerprint WHERE public_key_verified=2;"); } dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 40 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "ALTER TABLE jobs ADD COLUMN thread INTEGER DEFAULT 0;"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 41 if (dbversion < NEW_DB_VERSION) { update_file_paths = 1; dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 42 if (dbversion < NEW_DB_VERSION) { // older versions set the txt-field to the filenames, for debugging and fulltext search. // to allow text+attachment compound messages, we need to reset these fields. dc_sqlite3_execute(sql, "UPDATE msgs SET txt='' WHERE type!=" DC_STRINGIFY(DC_MSG_TEXT)); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 44 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "ALTER TABLE msgs ADD COLUMN mime_headers TEXT;"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 46 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "ALTER TABLE msgs ADD COLUMN mime_in_reply_to TEXT;"); dc_sqlite3_execute(sql, "ALTER TABLE msgs ADD COLUMN mime_references TEXT;"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 47 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "ALTER TABLE jobs ADD COLUMN tries INTEGER DEFAULT 0;"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 48 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "ALTER TABLE msgs ADD COLUMN move_state INTEGER DEFAULT 1;"); assert( DC_MOVE_STATE_UNDEFINED == 0 ); assert( DC_MOVE_STATE_PENDING == 1 ); assert( DC_MOVE_STATE_STAY == 2 ); assert( DC_MOVE_STATE_MOVING == 3 ); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 49 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "ALTER TABLE chats ADD COLUMN gossiped_timestamp INTEGER DEFAULT 0;"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 50 if (dbversion < NEW_DB_VERSION) { /* installations <= 0.100.1 used DC_SHOW_EMAILS_ALL implicitly; keep this default and use DC_SHOW_EMAILS_NO only for new installations */ if (exists_before_update) { dc_sqlite3_set_config_int(sql, "show_emails", DC_SHOW_EMAILS_ALL); } dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 53 if (dbversion < NEW_DB_VERSION) { // the messages containing _only_ locations // are also added to the database as _hidden_. dc_sqlite3_execute(sql, "CREATE TABLE locations (" " id INTEGER PRIMARY KEY AUTOINCREMENT," " latitude REAL DEFAULT 0.0," " longitude REAL DEFAULT 0.0," " accuracy REAL DEFAULT 0.0," " timestamp INTEGER DEFAULT 0," " chat_id INTEGER DEFAULT 0," " from_id INTEGER DEFAULT 0);"); dc_sqlite3_execute(sql, "CREATE INDEX locations_index1 ON locations (from_id);"); dc_sqlite3_execute(sql, "CREATE INDEX locations_index2 ON locations (timestamp);"); dc_sqlite3_execute(sql, "ALTER TABLE chats ADD COLUMN locations_send_begin INTEGER DEFAULT 0;"); dc_sqlite3_execute(sql, "ALTER TABLE chats ADD COLUMN locations_send_until INTEGER DEFAULT 0;"); dc_sqlite3_execute(sql, "ALTER TABLE chats ADD COLUMN locations_last_sent INTEGER DEFAULT 0;"); dc_sqlite3_execute(sql, "CREATE INDEX chats_index3 ON chats (locations_send_until);"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 54 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "ALTER TABLE msgs ADD COLUMN location_id INTEGER DEFAULT 0;"); dc_sqlite3_execute(sql, "CREATE INDEX msgs_index6 ON msgs (location_id);"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION #define NEW_DB_VERSION 55 if (dbversion < NEW_DB_VERSION) { dc_sqlite3_execute(sql, "ALTER TABLE locations ADD COLUMN independent INTEGER DEFAULT 0;"); dbversion = NEW_DB_VERSION; dc_sqlite3_set_config_int(sql, "dbversion", NEW_DB_VERSION); } #undef NEW_DB_VERSION // (2) updates that require high-level objects // (the structure is complete now and all objects are usable) // -------------------------------------------------------------------- if (recalc_fingerprints) { sqlite3_stmt* stmt = dc_sqlite3_prepare(sql, "SELECT addr FROM acpeerstates;"); while (sqlite3_step(stmt)==SQLITE_ROW) { dc_apeerstate_t* peerstate = dc_apeerstate_new(sql->context); if (dc_apeerstate_load_by_addr(peerstate, sql, (const char*)sqlite3_column_text(stmt, 0)) && dc_apeerstate_recalc_fingerprint(peerstate)) { dc_apeerstate_save_to_db(peerstate, sql, 0/*don't create*/); } dc_apeerstate_unref(peerstate); } sqlite3_finalize(stmt); } if (update_file_paths) { // versions before 2018-08 save the absolute paths in the database files at "param.f="; // for newer versions, we copy files always to the blob directory and store relative paths. // this snippet converts older databases and can be removed after some time. char* repl_from = dc_sqlite3_get_config(sql, "backup_for", sql->context->blobdir); dc_ensure_no_slash(repl_from); assert('f'==DC_PARAM_FILE); char* q3 = sqlite3_mprintf("UPDATE msgs SET param=replace(param, 'f=%q/', 'f=$BLOBDIR/');", repl_from); dc_sqlite3_execute(sql, q3); sqlite3_free(q3); assert('i'==DC_PARAM_PROFILE_IMAGE); q3 = sqlite3_mprintf("UPDATE chats SET param=replace(param, 'i=%q/', 'i=$BLOBDIR/');", repl_from); dc_sqlite3_execute(sql, q3); sqlite3_free(q3); free(repl_from); dc_sqlite3_set_config(sql, "backup_for", NULL); } } dc_log_info(sql->context, 0, "Opened \"%s\".", dbfile); return 1; cleanup: dc_sqlite3_close(sql); return 0; } void dc_sqlite3_close(dc_sqlite3_t* sql) { if (sql==NULL) { return; } if (sql->cobj) { sqlite3_close(sql->cobj); sql->cobj = NULL; } dc_log_info(sql->context, 0, "Database closed."); /* We log the information even if not real closing took place; this is to detect logic errors. */ } int dc_sqlite3_is_open(const dc_sqlite3_t* sql) { if (sql==NULL || sql->cobj==NULL) { return 0; } return 1; } int dc_sqlite3_table_exists(dc_sqlite3_t* sql, const char* name) { int ret = 0; char* querystr = NULL; sqlite3_stmt* stmt = NULL; int sqlState = 0; if ((querystr=sqlite3_mprintf("PRAGMA table_info(%s)", name))==NULL) { /* this statement cannot be used with binded variables */ dc_log_error(sql->context, 0, "dc_sqlite3_table_exists_(): Out of memory."); goto cleanup; } if ((stmt=dc_sqlite3_prepare(sql, querystr))==NULL) { goto cleanup; } sqlState = sqlite3_step(stmt); if (sqlState==SQLITE_ROW) { ret = 1; /* the table exists. Other states are SQLITE_DONE or SQLITE_ERROR in both cases we return 0. */ } /* success - fall through to free allocated objects */ ; /* error/cleanup */ cleanup: if (stmt) { sqlite3_finalize(stmt); } if (querystr) { sqlite3_free(querystr); } return ret; } /******************************************************************************* * Handle configuration ******************************************************************************/ int dc_sqlite3_set_config(dc_sqlite3_t* sql, const char* key, const char* value) { int state = 0; sqlite3_stmt* stmt = NULL; if (key==NULL) { dc_log_error(sql->context, 0, "dc_sqlite3_set_config(): Bad parameter."); return 0; } if (!dc_sqlite3_is_open(sql)) { dc_log_error(sql->context, 0, "dc_sqlite3_set_config(): Database not ready."); return 0; } if (value) { /* insert/update key=value */ #define SELECT_v_FROM_config_k_STATEMENT "SELECT value FROM config WHERE keyname=?;" stmt = dc_sqlite3_prepare(sql, SELECT_v_FROM_config_k_STATEMENT); sqlite3_bind_text (stmt, 1, key, -1, SQLITE_STATIC); state = sqlite3_step(stmt); sqlite3_finalize(stmt); if (state==SQLITE_DONE) { stmt = dc_sqlite3_prepare(sql, "INSERT INTO config (keyname, value) VALUES (?, ?);"); sqlite3_bind_text (stmt, 1, key, -1, SQLITE_STATIC); sqlite3_bind_text (stmt, 2, value, -1, SQLITE_STATIC); state = sqlite3_step(stmt); sqlite3_finalize(stmt); } else if (state==SQLITE_ROW) { stmt = dc_sqlite3_prepare(sql, "UPDATE config SET value=? WHERE keyname=?;"); sqlite3_bind_text (stmt, 1, value, -1, SQLITE_STATIC); sqlite3_bind_text (stmt, 2, key, -1, SQLITE_STATIC); state = sqlite3_step(stmt); sqlite3_finalize(stmt); } else { dc_log_error(sql->context, 0, "dc_sqlite3_set_config(): Cannot read value."); return 0; } } else { /* delete key */ stmt = dc_sqlite3_prepare(sql, "DELETE FROM config WHERE keyname=?;"); sqlite3_bind_text (stmt, 1, key, -1, SQLITE_STATIC); state = sqlite3_step(stmt); sqlite3_finalize(stmt); } if (state != SQLITE_DONE) { dc_log_error(sql->context, 0, "dc_sqlite3_set_config(): Cannot change value."); return 0; } return 1; } char* dc_sqlite3_get_config(dc_sqlite3_t* sql, const char* key, const char* def) /* the returned string must be free()'d, NULL is only returned if def is NULL */ { sqlite3_stmt* stmt = NULL; if (!dc_sqlite3_is_open(sql) || key==NULL) { return dc_strdup_keep_null(def); } stmt = dc_sqlite3_prepare(sql, SELECT_v_FROM_config_k_STATEMENT); sqlite3_bind_text(stmt, 1, key, -1, SQLITE_STATIC); if (sqlite3_step(stmt)==SQLITE_ROW) { const unsigned char* ptr = sqlite3_column_text(stmt, 0); /* Do not pass the pointers returned from sqlite3_column_text(), etc. into sqlite3_free(). */ if (ptr) { /* success, fall through below to free objects */ char* ret = dc_strdup((const char*)ptr); sqlite3_finalize(stmt); return ret; } } /* return the default value */ sqlite3_finalize(stmt); return dc_strdup_keep_null(def); } int32_t dc_sqlite3_get_config_int(dc_sqlite3_t* sql, const char* key, int32_t def) { char* str = dc_sqlite3_get_config(sql, key, NULL); if (str==NULL) { return def; } int32_t ret = atol(str); free(str); return ret; } int64_t dc_sqlite3_get_config_int64(dc_sqlite3_t* sql, const char* key, int64_t def) { char* str = dc_sqlite3_get_config(sql, key, NULL); if (str==NULL) { return def; } int64_t ret = 0; sscanf(str, "%"SCNd64, &ret); free(str); return ret; } int dc_sqlite3_set_config_int(dc_sqlite3_t* sql, const char* key, int32_t value) { char* value_str = dc_mprintf("%i", (int)value); if (value_str==NULL) { return 0; } int ret = dc_sqlite3_set_config(sql, key, value_str); free(value_str); return ret; } int dc_sqlite3_set_config_int64(dc_sqlite3_t* sql, const char* key, int64_t value) { char* value_str = dc_mprintf("%"PRId64, (long)value); if (value_str==NULL) { return 0; } int ret = dc_sqlite3_set_config(sql, key, value_str); free(value_str); return ret; } /******************************************************************************* * Transactions ******************************************************************************/ #undef USE_TRANSACTIONS void dc_sqlite3_begin_transaction(dc_sqlite3_t* sql) { #ifdef USE_TRANSACTIONS // `BEGIN IMMEDIATE` ensures, only one thread may write. // all other calls to `BEGIN IMMEDIATE` will try over until sqlite3_busy_timeout() is reached. // CAVE: This also implies that transactions MUST NOT be nested. sqlite3_stmt* stmt = dc_sqlite3_prepare(sql, "BEGIN IMMEDIATE;"); if (sqlite3_step(stmt) != SQLITE_DONE) { dc_sqlite3_log_error(sql, "Cannot begin transaction."); } sqlite3_finalize(stmt); #endif } void dc_sqlite3_rollback(dc_sqlite3_t* sql) { #ifdef USE_TRANSACTIONS sqlite3_stmt* stmt = dc_sqlite3_prepare(sql, "ROLLBACK;"); if (sqlite3_step(stmt) != SQLITE_DONE) { dc_sqlite3_log_error(sql, "Cannot rollback transaction."); } sqlite3_finalize(stmt); #endif } void dc_sqlite3_commit(dc_sqlite3_t* sql) { #ifdef USE_TRANSACTIONS sqlite3_stmt* stmt = dc_sqlite3_prepare(sql, "COMMIT;"); if (sqlite3_step(stmt) != SQLITE_DONE) { dc_sqlite3_log_error(sql, "Cannot commit transaction."); } sqlite3_finalize(stmt); #endif } /******************************************************************************* * Housekeeping ******************************************************************************/ static void maybe_add_file(dc_hash_t* files_in_use, const char* file) { #define PREFIX "$BLOBDIR/" #define PREFIX_LEN 9 if (strncmp(file, PREFIX, PREFIX_LEN)!=0) { return; } const char* raw_name = &file[PREFIX_LEN]; dc_hash_insert_str(files_in_use, raw_name, (void*)1); } static void maybe_add_from_param(dc_context_t* context, dc_hash_t* files_in_use, const char* query, int param_id) { dc_param_t* param = dc_param_new(); sqlite3_stmt* stmt = dc_sqlite3_prepare(context->sql, query); while (sqlite3_step(stmt)==SQLITE_ROW) { dc_param_set_packed(param, (const char*)sqlite3_column_text(stmt, 0)); char* file = dc_param_get(param, param_id, NULL); if (file!=NULL) { maybe_add_file(files_in_use, file); free(file); } } sqlite3_finalize(stmt); dc_param_unref(param); } static int is_file_in_use(dc_hash_t* files_in_use, const char* namespc, const char* name) { char* name_to_check = dc_strdup(name); if (namespc) { int name_len = strlen(name); int namespc_len = strlen(namespc); if (name_len<=namespc_len || strcmp(&name[name_len-namespc_len], namespc)!=0) { return 0; } name_to_check[name_len-namespc_len] = 0; } int ret = (dc_hash_find_str(files_in_use, name_to_check)!=NULL); free(name_to_check); return ret; } void dc_housekeeping(dc_context_t* context) { sqlite3_stmt* stmt = NULL; DIR* dir_handle = NULL; struct dirent* dir_entry = NULL; dc_hash_t files_in_use; char* path = NULL; int unreferenced_count = 0; dc_hash_init(&files_in_use, DC_HASH_STRING, DC_HASH_COPY_KEY); dc_log_info(context, 0, "Start housekeeping..."); /* collect all files in use */ maybe_add_from_param(context, &files_in_use, "SELECT param FROM msgs " " WHERE chat_id!=" DC_STRINGIFY(DC_CHAT_ID_TRASH) " AND type!=" DC_STRINGIFY(DC_MSG_TEXT) ";", DC_PARAM_FILE); maybe_add_from_param(context, &files_in_use, "SELECT param FROM jobs;", DC_PARAM_FILE); maybe_add_from_param(context, &files_in_use, "SELECT param FROM chats;", DC_PARAM_PROFILE_IMAGE); maybe_add_from_param(context, &files_in_use, "SELECT param FROM contacts;", DC_PARAM_PROFILE_IMAGE); stmt = dc_sqlite3_prepare(context->sql, "SELECT value FROM config;"); while (sqlite3_step(stmt)==SQLITE_ROW) { maybe_add_file(&files_in_use, (const char*)sqlite3_column_text(stmt, 0)); } dc_log_info(context, 0, "%i files in use.", (int)dc_hash_cnt(&files_in_use)); /* go through directory and delete unused files */ if ((dir_handle=opendir(context->blobdir))==NULL) { dc_log_warning(context, 0, "Housekeeping: Cannot open %s.", context->blobdir); goto cleanup; } /* avoid deletion of files that are just created to build a message object */ time_t keep_files_newer_than = time(NULL) - 60*60; while ((dir_entry=readdir(dir_handle))!=NULL) { const char* name = dir_entry->d_name; /* name without path or `.` or `..` */ int name_len = strlen(name); if ((name_len==1 && name[0]=='.') || (name_len==2 && name[0]=='.' && name[1]=='.')) { continue; } if (is_file_in_use(&files_in_use, NULL, name) || is_file_in_use(&files_in_use, ".increation", name) || is_file_in_use(&files_in_use, ".waveform", name) || is_file_in_use(&files_in_use, "-preview.jpg", name)) { continue; } unreferenced_count++; free(path); path = dc_mprintf("%s/%s", context->blobdir, name); struct stat st; if (stat(path, &st)==0) { if (st.st_mtime > keep_files_newer_than || st.st_atime > keep_files_newer_than || st.st_ctime > keep_files_newer_than) { dc_log_info(context, 0, "Housekeeping: Keeping new unreferenced file #%i: %s", unreferenced_count, name); continue; } } dc_log_info(context, 0, "Housekeeping: Deleting unreferenced file #%i: %s", unreferenced_count, name); dc_delete_file(context, path); } cleanup: if (dir_handle) { closedir(dir_handle); } sqlite3_finalize(stmt); dc_hash_clear(&files_in_use); free(path); dc_log_info(context, 0, "Housekeeping done."); } ``` Filename: dc_stock.c ```c /* Add translated strings that are used by the messager backend. As the logging functions may use these strings, do not log any errors from here. */ #include "dc_context.h" static char* default_string(int id) { switch (id) { case DC_STR_NOMESSAGES: return dc_strdup("No messages."); case DC_STR_SELF: return dc_strdup("Me"); case DC_STR_DRAFT: return dc_strdup("Draft"); case DC_STR_MEMBER: return dc_strdup("%1$s member(s)"); case DC_STR_CONTACT: return dc_strdup("%1$s contact(s)"); case DC_STR_VOICEMESSAGE: return dc_strdup("Voice message"); case DC_STR_DEADDROP: return dc_strdup("Contact requests"); case DC_STR_IMAGE: return dc_strdup("Image"); case DC_STR_GIF: return dc_strdup("GIF"); case DC_STR_VIDEO: return dc_strdup("Video"); case DC_STR_AUDIO: return dc_strdup("Audio"); case DC_STR_FILE: return dc_strdup("File"); case DC_STR_LOCATION: return dc_strdup("Location"); case DC_STR_ENCRYPTEDMSG: return dc_strdup("Encrypted message"); case DC_STR_STATUSLINE: return dc_strdup("Sent with my Delta Chat Messenger: https://delta.chat"); case DC_STR_NEWGROUPDRAFT: return dc_strdup("Hello, I've just created the group \"%1$s\" for us."); case DC_STR_MSGGRPNAME: return dc_strdup("Group name changed from \"%1$s\" to \"%2$s\"."); case DC_STR_MSGGRPIMGCHANGED: return dc_strdup("Group image changed."); case DC_STR_MSGADDMEMBER: return dc_strdup("Member %1$s added."); case DC_STR_MSGDELMEMBER: return dc_strdup("Member %1$s removed."); case DC_STR_MSGGROUPLEFT: return dc_strdup("Group left."); case DC_STR_MSGLOCATIONENABLED: return dc_strdup("Location streaming enabled."); case DC_STR_MSGLOCATIONDISABLED: return dc_strdup("Location streaming disabled."); case DC_STR_MSGACTIONBYUSER: return dc_strdup("%1$s by %2$s."); case DC_STR_MSGACTIONBYME: return dc_strdup("%1$s by me."); case DC_STR_E2E_AVAILABLE: return dc_strdup("End-to-end encryption available."); case DC_STR_ENCR_TRANSP: return dc_strdup("Transport-encryption."); case DC_STR_ENCR_NONE: return dc_strdup("No encryption."); case DC_STR_FINGERPRINTS: return dc_strdup("Fingerprints"); case DC_STR_READRCPT: return dc_strdup("Return receipt"); case DC_STR_READRCPT_MAILBODY: return dc_strdup("This is a return receipt for the message \"%1$s\"."); case DC_STR_MSGGRPIMGDELETED: return dc_strdup("Group image deleted."); case DC_STR_E2E_PREFERRED: return dc_strdup("End-to-end encryption preferred."); case DC_STR_CONTACT_VERIFIED: return dc_strdup("%1$s verified."); case DC_STR_CONTACT_NOT_VERIFIED: return dc_strdup("Cannot verifiy %1$s"); case DC_STR_CONTACT_SETUP_CHANGED: return dc_strdup("Changed setup for %1$s"); case DC_STR_ARCHIVEDCHATS: return dc_strdup("Archived chats"); case DC_STR_STARREDMSGS: return dc_strdup("Starred messages"); case DC_STR_AC_SETUP_MSG_SUBJECT: return dc_strdup("Autocrypt Setup Message"); case DC_STR_AC_SETUP_MSG_BODY: return dc_strdup("This is the Autocrypt Setup Message used to transfer your key between clients.\n\nTo decrypt and use your key, open the message in an Autocrypt-compliant client and enter the setup code presented on the generating device."); case DC_STR_SELFTALK_SUBTITLE: return dc_strdup("Messages I sent to myself"); case DC_STR_CANTDECRYPT_MSG_BODY: return dc_strdup("This message was encrypted for another setup."); case DC_STR_CANNOT_LOGIN: return dc_strdup("Cannot login as %1$s."); case DC_STR_SERVER_RESPONSE: return dc_strdup("Response from %1$s: %2$s"); } return dc_strdup("ErrStr"); } static char* get_string(dc_context_t* context, int id, int qty) { char* ret = NULL; if (context) { ret = (char*)context->cb(context, DC_EVENT_GET_STRING, id, qty); } if (ret == NULL) { ret = default_string(id); } return ret; } char* dc_stock_str(dc_context_t* context, int id) { return get_string(context, id, 0); } char* dc_stock_str_repl_string(dc_context_t* context, int id, const char* to_insert) { char* ret = get_string(context, id, 0); dc_str_replace(&ret, "%1$s", to_insert); dc_str_replace(&ret, "%1$d", to_insert); return ret; } char* dc_stock_str_repl_int(dc_context_t* context, int id, int to_insert_int) { char* ret = get_string(context, id, to_insert_int); char* to_insert_str = dc_mprintf("%i", (int)to_insert_int); dc_str_replace(&ret, "%1$s", to_insert_str); dc_str_replace(&ret, "%1$d", to_insert_str); free(to_insert_str); return ret; } char* dc_stock_str_repl_string2(dc_context_t* context, int id, const char* to_insert, const char* to_insert2) { char* ret = get_string(context, id, 0); dc_str_replace(&ret, "%1$s", to_insert); dc_str_replace(&ret, "%1$d", to_insert); dc_str_replace(&ret, "%2$s", to_insert2); dc_str_replace(&ret, "%2$d", to_insert2); return ret; } char* dc_stock_system_msg(dc_context_t* context, int str_id, const char* param1, const char* param2, uint32_t from_id) { char* ret = NULL; dc_contact_t* mod_contact = NULL; char* mod_displayname = NULL; dc_contact_t* from_contact = NULL; char* from_displayname = NULL; /* if the first parameter is an email-address, expand it to name+address */ if (str_id==DC_STR_MSGADDMEMBER || str_id==DC_STR_MSGDELMEMBER) { uint32_t mod_contact_id = dc_lookup_contact_id_by_addr(context, param1); if (mod_contact_id!=0) { mod_contact = dc_get_contact(context, mod_contact_id); mod_displayname = dc_contact_get_name_n_addr(mod_contact); param1 = mod_displayname; } } char* action = dc_stock_str_repl_string2(context, str_id, param1, param2); if (from_id) { // to simplify building of sentencens in some languages, // remove the full-stop from the action string if (strlen(action) && action[strlen(action)-1]=='.') { action[strlen(action)-1] = 0; } from_contact = dc_get_contact(context, from_id); from_displayname = dc_contact_get_display_name(from_contact); ret = dc_stock_str_repl_string2(context, from_id==DC_CONTACT_ID_SELF? DC_STR_MSGACTIONBYME : DC_STR_MSGACTIONBYUSER, action, from_displayname); } else { ret = dc_strdup(action); } free(action); free(from_displayname); free(mod_displayname); dc_contact_unref(from_contact); dc_contact_unref(mod_contact); return ret; } ``` Filename: dc_strbuilder.c ```c #include "dc_context.h" /** * Init a string-builder-object. * A string-builder-object is placed typically on the stack and contains a string-buffer * which is initially empty. * * You can add data to the string-buffer using eg. dc_strbuilder_cat() or * dc_strbuilder_catf() - the buffer is reallocated as needed. * * When you're done with string building, the ready-to-use, null-terminates * string can be found at dc_strbuilder_t::buf, you can do whatever you like * with this buffer, however, never forget to call free() when done. * * @param strbuilder The object to initialze. * @param init_bytes The number of bytes to reserve for the string. If you have an * idea about how long the resulting string will be, you can give this as a hint here; * this avoids some reallocations; if the string gets longer, reallocation is done. * If you do not know how larget the string will be, give 0 here. * @return None. */ void dc_strbuilder_init(dc_strbuilder_t* strbuilder, int init_bytes) { if (strbuilder==NULL) { return; } strbuilder->allocated = DC_MAX(init_bytes, 128); /* use a small default minimum, we may use _many_ of these objects at the same time */ strbuilder->buf = malloc(strbuilder->allocated); if (strbuilder->buf==NULL) { exit(38); } strbuilder->buf[0] = 0; strbuilder->free = strbuilder->allocated - 1 /*the nullbyte! */; strbuilder->eos = strbuilder->buf; } /** * Add a string to the end of the current string in a string-builder-object. * The internal buffer is reallocated as needed. * If reallocation fails, the program halts. * * @param strbuilder The object to initialze. Must be initialized with * dc_strbuilder_init(). * @param text Null-terminated string to add to the end of the string-builder-string. * @return Returns a pointer to the copy of the given text. * The returned pointer is a pointer inside dc_strbuilder_t::buf and MUST NOT * be freed. If the string-builder was empty before, the returned * pointer is equal to dc_strbuilder_t::buf. * If the given text is NULL, NULL is returned and the string-builder-object is not modified. */ char* dc_strbuilder_cat(dc_strbuilder_t* strbuilder, const char* text) { // this function MUST NOT call logging functions as it is used to output the log if (strbuilder==NULL || text==NULL) { return NULL; } int len = strlen(text); if (len > strbuilder->free) { int add_bytes = DC_MAX(len, strbuilder->allocated); int old_offset = (int)(strbuilder->eos - strbuilder->buf); strbuilder->allocated = strbuilder->allocated + add_bytes; strbuilder->buf = realloc(strbuilder->buf, strbuilder->allocated+add_bytes); if (strbuilder->buf==NULL) { exit(39); } strbuilder->free = strbuilder->free + add_bytes; strbuilder->eos = strbuilder->buf + old_offset; } char* ret = strbuilder->eos; strcpy(strbuilder->eos, text); strbuilder->eos += len; strbuilder->free -= len; return ret; } /** * Add a formatted string to a string-builder-object. * This function is similar to dc_strbuilder_cat() but allows the same * formatting options as eg. printf() * * @param strbuilder The object to initialze. Must be initialized with * dc_strbuilder_init(). * @param format The formatting string to add to the string-builder-object. * This parameter may be followed by data to be inserted into the * formatting string, see eg. printf() * @return None. */ void dc_strbuilder_catf(dc_strbuilder_t* strbuilder, const char* format, ...) { char testbuf[1]; char* buf = NULL; int char_cnt_without_zero = 0; va_list argp; va_list argp_copy; va_start(argp, format); va_copy(argp_copy, argp); char_cnt_without_zero = vsnprintf(testbuf, 0, format, argp); va_end(argp); if (char_cnt_without_zero < 0) { va_end(argp_copy); dc_strbuilder_cat(strbuilder, "ErrFmt"); return; } buf = malloc(char_cnt_without_zero+2 /* +1 would be enough, however, protect against off-by-one-errors */); if (buf==NULL) { va_end(argp_copy); dc_strbuilder_cat(strbuilder, "ErrMem"); return; } vsnprintf(buf, char_cnt_without_zero+1, format, argp_copy); va_end(argp_copy); dc_strbuilder_cat(strbuilder, buf); free(buf); } /** * Set the string to a lenght of 0. This does not free the buffer; * if you want to free the buffer, you have to call free() on dc_strbuilder_t::buf. * * @param strbuilder The object to initialze. Must be initialized with * dc_strbuilder_init(). * @return None. */ void dc_strbuilder_empty(dc_strbuilder_t* strbuilder) { strbuilder->buf[0] = 0; strbuilder->free = strbuilder->allocated - 1 /*the nullbyte! */; strbuilder->eos = strbuilder->buf; } ``` Filename: dc_strencode.c ```c #include #include #include "dc_context.h" #include "dc_strencode.h" /******************************************************************************* * URL encoding and decoding, RFC 3986 ******************************************************************************/ static char int_2_uppercase_hex(char code) { static const char hex[] = "0123456789ABCDEF"; return hex[code & 15]; } static char hex_2_int(char ch) { return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10; } /** * Url-encodes a string. * All characters but A-Z, a-z, 0-9 and -_. are encoded by a percent sign followed by two hexadecimal digits. * * The space in encoded as `+` - this is correct for parts in the url _after_ the `?` and saves some bytes when used in QR codes. * (in the URL _before_ the `?` or elsewhere, the space should be encoded as `%20`) * * Belongs to RFC 3986: https://tools.ietf.org/html/rfc3986#section-2 * * Example: The string `Bj√∂rn Petersen` will be encoded as `"Bj%C3%B6rn+Petersen`. * * @param to_encode Null-terminated UTF-8 string to encode. * @return Returns a null-terminated url-encoded strings. The result must be free()'d when no longer needed. * On memory allocation errors the program halts. * On other errors, an empty string is returned. */ char* dc_urlencode(const char *to_encode) { const char *pstr = to_encode; if (to_encode==NULL) { return dc_strdup(""); } char *buf = malloc(strlen(to_encode) * 3 + 1), *pbuf = buf; if (buf==NULL) { exit(46); } while (*pstr) { if (isalnum(*pstr) || *pstr=='-' || *pstr=='_' || *pstr=='.' || *pstr=='~') { *pbuf++ = *pstr; } else if (*pstr==' ') { *pbuf++ = '+'; } else { *pbuf++ = '%', *pbuf++ = int_2_uppercase_hex(*pstr >> 4), *pbuf++ = int_2_uppercase_hex(*pstr & 15); } pstr++; } *pbuf = '\0'; return buf; } /** * Returns a url-decoded version of the given string. * The string may be encoded eg. by dc_urlencode(). * Belongs to RFC 3986: https://tools.ietf.org/html/rfc3986#section-2 * * @param to_decode Null-terminated string to decode. * @return The function returns a null-terminated UTF-8 string. * The return value must be free() when no longer used. * On memory allocation errors the program halts. * On other errors, an empty string is returned. */ char* dc_urldecode(const char* to_decode) { const char *pstr = to_decode; if (to_decode==NULL) { return dc_strdup(""); } char *buf = malloc(strlen(to_decode) + 1), *pbuf = buf; if (buf==NULL) { exit(50); } while (*pstr) { if (*pstr=='%') { if (pstr[1] && pstr[2]) { *pbuf++ = hex_2_int(pstr[1]) << 4 | hex_2_int(pstr[2]); pstr += 2; } } else if (*pstr=='+') { *pbuf++ = ' '; } else { *pbuf++ = *pstr; } pstr++; } *pbuf = '\0'; return buf; } /******************************************************************************* * Encode/decode header words, RFC 2047 ******************************************************************************/ #define DEF_INCOMING_CHARSET "iso-8859-1" #define DEF_DISPLAY_CHARSET "utf-8" #define MAX_IMF_LINE 666 /* see comment below */ static int to_be_quoted(const char * word, size_t size) { const char* cur = word; size_t i = 0; for (i = 0; i < size; i++) { switch (*cur) { case ',': case ':': case '!': case '"': case '#': case '$': case '@': case '[': case '\\': case ']': case '^': case '`': case '{': case '|': case '}': case '~': case '=': case '?': case '_': return 1; default: if (((unsigned char)*cur) >= 128) { return 1; } break; } cur++; } return 0; } static int quote_word(const char* display_charset, MMAPString* mmapstr, const char* word, size_t size) { const char* cur = NULL; size_t i = 0; char hex[4]; int col = 0; if (mmap_string_append(mmapstr, "=?")==NULL) { return 0; } if (mmap_string_append(mmapstr, display_charset)==NULL) { return 0; } if (mmap_string_append(mmapstr, "?Q?")==NULL) { return 0; } col = mmapstr->len; cur = word; for(i = 0 ; i < size ; i ++) { int do_quote_char; #if MAX_IMF_LINE != 666 if (col + 2 /* size of "?=" */ + 3 /* max size of newly added character */ + 1 /* minimum column of string in a folded header */ >= MAX_IMF_LINE) { /* adds a concatened encoded word */ int old_pos; if (mmap_string_append(mmapstr, "?=")==NULL) { return 0; } if (mmap_string_append(mmapstr, " ")==NULL) { return 0; } old_pos = mmapstr->len; if (mmap_string_append(mmapstr, "=?")==NULL) { return 0; } if (mmap_string_append(mmapstr, display_charset)==NULL) { return 0; } if (mmap_string_append(mmapstr, "?Q?")==NULL) { return 0; } col = mmapstr->len - old_pos; } #endif do_quote_char = 0; switch (*cur) { case ',': case ':': case '!': case '"': case '#': case '$': case '@': case '[': case '\\': case ']': case '^': case '`': case '{': case '|': case '}': case '~': case '=': case '?': case '_': do_quote_char = 1; break; default: if (((unsigned char) * cur) >= 128) { do_quote_char = 1; } break; } if (do_quote_char) { snprintf(hex, 4, "=%2.2X", (unsigned char) * cur); if (mmap_string_append(mmapstr, hex)==NULL) { return 0; } col += 3; } else { if (* cur==' ') { if (mmap_string_append_c(mmapstr, '_')==NULL) { return 0; } } else { if (mmap_string_append_c(mmapstr, * cur)==NULL) { return 0; } } col += 3; } cur++; } if (mmap_string_append(mmapstr, "?=")==NULL) { return 0; } return 1; } static void get_word(const char* begin, const char** pend, int* pto_be_quoted) { const char* cur = begin; while ((* cur != ' ') && (* cur != '\t') && (* cur != '\0')) { cur ++; } #if MAX_IMF_LINE != 666 if (cur - begin + 1 /* minimum column of string in a folded header */ > MAX_IMF_LINE) *pto_be_quoted = 1; else #endif *pto_be_quoted = to_be_quoted(begin, cur - begin); *pend = cur; } /** * Encode non-ascii-strings as `=?UTF-8?Q?Bj=c3=b6rn_Petersen?=`. * Belongs to RFC 2047: https://tools.ietf.org/html/rfc2047 * * We do not fold at position 72; this would result in empty words as `=?utf-8?Q??=` which are correct, * but cannot be displayed by some mail programs (eg. Android Stock Mail). * however, this is not needed, as long as _one_ word is not longer than 72 characters. * _if_ it is, the display may get weird. This affects the subject only. * the best solution wor all this would be if libetpan encodes the line as only libetpan knowns when a header line is full. * * @param to_encode Null-terminated UTF-8-string to encode. * @return Returns the encoded string which must be free()'d when no longed needed. * On errors, NULL is returned. */ char* dc_encode_header_words(const char* to_encode) { char* ret_str = NULL; const char* cur = to_encode; MMAPString* mmapstr = mmap_string_new(""); if (to_encode==NULL || mmapstr==NULL) { goto cleanup; } while (* cur != '\0') { const char * begin; const char * end; int do_quote; int quote_words; begin = cur; end = begin; quote_words = 0; do_quote = 1; while (* cur != '\0') { get_word(cur, &cur, &do_quote); if (do_quote) { quote_words = 1; end = cur; } else { break; } if (* cur != '\0') { cur ++; } } if (quote_words) { if ( !quote_word(DEF_DISPLAY_CHARSET, mmapstr, begin, end - begin)) { goto cleanup; } if ((* end==' ') || (* end=='\t')) { if (mmap_string_append_c(mmapstr, * end)==0) { goto cleanup; } end ++; } if (* end != '\0') { if (mmap_string_append_len(mmapstr, end, cur - end)==NULL) { goto cleanup; } } } else { if (mmap_string_append_len(mmapstr, begin, cur - begin)==NULL) { goto cleanup; } } if ((* cur==' ') || (* cur=='\t')) { if (mmap_string_append_c(mmapstr, * cur)==0) { goto cleanup; } cur ++; } } ret_str = strdup(mmapstr->str); cleanup: if (mmapstr) { mmap_string_free(mmapstr); } return ret_str; } /** * Decode non-ascii-strings as `=?UTF-8?Q?Bj=c3=b6rn_Petersen?=`. * Belongs to RFC 2047: https://tools.ietf.org/html/rfc2047 * * @param in String to decode. * @return Returns the null-terminated decoded string as UTF-8. Must be free()'d when no longed needed. * On errors, NULL is returned. */ char* dc_decode_header_words(const char* in) { /* decode strings as. `=?UTF-8?Q?Bj=c3=b6rn_Petersen?=`) if `in` is NULL, `out` is NULL as well; also returns NULL on errors */ if (in==NULL) { return NULL; /* no string given */ } char* out = NULL; size_t cur_token = 0; int r = mailmime_encoded_phrase_parse(DEF_INCOMING_CHARSET, in, strlen(in), &cur_token, DEF_DISPLAY_CHARSET, &out); if (r != MAILIMF_NO_ERROR || out==NULL) { out = dc_strdup(in); /* error, make a copy of the original string (as we free it later) */ } return out; /* must be free()'d by the caller */ } /******************************************************************************* * Encode/decode modified UTF-7 as needed for IMAP, see RFC 2192 ******************************************************************************/ // UTF7 modified base64 alphabet static const char base64chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,"; /** * Convert an UTF-8 string to a modified UTF-7 string * that is needed eg. for IMAP mailbox names. * * Example: `Bj√∂rn Petersen` gets encoded to `Bj&APY-rn_Petersen` * * @param to_encode Null-terminated UTF-8 string to encode * @param change_spaces If set, spaces are encoded using the underscore character. * @return Null-terminated encoded string. Must be free()'d after usage. * Halts the program on memory allocation errors, * for all other errors, an empty string is returned. * NULL is never returned. */ char* dc_encode_modified_utf7(const char* to_encode, int change_spaces) { #define UTF16MASK 0x03FFUL #define UTF16SHIFT 10 #define UTF16BASE 0x10000UL #define UTF16HIGHSTART 0xD800UL #define UTF16HIGHEND 0xDBFFUL #define UTF16LOSTART 0xDC00UL #define UTF16LOEND 0xDFFFUL #define UNDEFINED 64 unsigned int utf8pos = 0; unsigned int utf8total = 0; unsigned int c = 0; unsigned int utf7mode = 0; unsigned int bitstogo = 0; unsigned int utf16flag = 0; unsigned long ucs4 = 0; unsigned long bitbuf = 0; char* dst = NULL; char* res = NULL; if (!to_encode) { return dc_strdup(""); } res = (char*)malloc(2*strlen(to_encode)+1); dst = res; if(!dst) { exit(51); } utf7mode = 0; utf8total = 0; bitstogo = 0; utf8pos = 0; while ((c = (unsigned char)*to_encode) != '\0') { ++to_encode; // normal character? if (c >= ' ' && c <= '~' && (c != '_' || !change_spaces)) { // switch out of UTF-7 mode if (utf7mode) { if (bitstogo) { *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F]; } *dst++ = '-'; utf7mode = 0; utf8pos = 0; bitstogo = 0; utf8total= 0; } if (change_spaces && c==' ') { *dst++ = '_'; } else { *dst++ = c; } // encode '&' as '&-' if (c=='&') { *dst++ = '-'; } continue; } // switch to UTF-7 mode if (!utf7mode) { *dst++ = '&'; utf7mode = 1; } // encode ascii characters as themselves if (c < 0x80) { ucs4 = c; } else if (utf8total) { // save UTF8 bits into UCS4 ucs4 = (ucs4 << 6) | (c & 0x3FUL); if (++utf8pos < utf8total) { continue; } } else { utf8pos = 1; if (c < 0xE0) { utf8total = 2; ucs4 = c & 0x1F; } else if (c < 0xF0) { utf8total = 3; ucs4 = c & 0x0F; } else { // NOTE: cannot convert UTF8 sequences longer than 4 utf8total = 4; ucs4 = c & 0x03; } continue; } // loop to split ucs4 into two utf16 chars if necessary utf8total = 0; do { if (ucs4 >= UTF16BASE) { ucs4 -= UTF16BASE; bitbuf = (bitbuf << 16) | ((ucs4 >> UTF16SHIFT) + UTF16HIGHSTART); ucs4 = (ucs4 & UTF16MASK) + UTF16LOSTART; utf16flag = 1; } else { bitbuf = (bitbuf << 16) | ucs4; utf16flag = 0; } bitstogo += 16; /* spew out base64 */ while (bitstogo >= 6) { bitstogo -= 6; *dst++ = base64chars[(bitstogo ? (bitbuf >> bitstogo) : bitbuf) & 0x3F]; } } while (utf16flag); } // if in UTF-7 mode, finish in ASCII if (utf7mode) { if (bitstogo) { *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F]; } *dst++ = '-'; } *dst = '\0'; return res; } /** * Convert an modified UTF-7 encoded string to an UTF-8 string. * Modified UTF-7 strings are used eg. in IMAP mailbox names. * * @param to_decode Null-terminated, modified UTF-7 string to decode. * @param change_spaces If set, the underscore character `_` is converted to * a space. * @return Null-terminated UTF-8 string. Must be free()'d after usage. * Halts the program on memory allocation errors, * for all other errors, an empty string is returned. * NULL is never returned. */ char* dc_decode_modified_utf7(const char *to_decode, int change_spaces) { unsigned c = 0; unsigned i = 0; unsigned bitcount = 0; unsigned long ucs4 = 0; unsigned long utf16 = 0; unsigned long bitbuf = 0; unsigned char base64[256]; const char* src = NULL; char* dst = NULL; char* res = NULL; if (to_decode==NULL) { return dc_strdup(""); } res = (char*)malloc(4*strlen(to_decode)+1); dst = res; src = to_decode; if(!dst) { exit(52); } memset(base64, UNDEFINED, sizeof (base64)); for (i = 0; i < sizeof (base64chars); ++i) { base64[(unsigned)base64chars[i]] = i; } while (*src != '\0') { c = *src++; // deal with literal characters and &- if (c != '&' || *src=='-') { // encode literally if (change_spaces && c=='_') { *dst++ = ' '; } else { *dst++ = c; } // skip over the '-' if this is an &- sequence if (c=='&') ++src; } else { // convert modified UTF-7 -> UTF-16 -> UCS-4 -> UTF-8 -> HEX bitbuf = 0; bitcount = 0; ucs4 = 0; while ((c = base64[(unsigned char) *src]) != UNDEFINED) { ++src; bitbuf = (bitbuf << 6) | c; bitcount += 6; // enough bits for a UTF-16 character? if (bitcount >= 16) { bitcount -= 16; utf16 = (bitcount ? bitbuf >> bitcount : bitbuf) & 0xffff; // convert UTF16 to UCS4 if (utf16 >= UTF16HIGHSTART && utf16 <= UTF16HIGHEND) { ucs4 = (utf16 - UTF16HIGHSTART) << UTF16SHIFT; continue; } else if (utf16 >= UTF16LOSTART && utf16 <= UTF16LOEND) { ucs4 += utf16 - UTF16LOSTART + UTF16BASE; } else { ucs4 = utf16; } // convert UTF-16 range of UCS4 to UTF-8 if (ucs4 <= 0x7fUL) { dst[0] = ucs4; dst += 1; } else if (ucs4 <= 0x7ffUL) { dst[0] = 0xc0 | (ucs4 >> 6); dst[1] = 0x80 | (ucs4 & 0x3f); dst += 2; } else if (ucs4 <= 0xffffUL) { dst[0] = 0xe0 | (ucs4 >> 12); dst[1] = 0x80 | ((ucs4 >> 6) & 0x3f); dst[2] = 0x80 | (ucs4 & 0x3f); dst += 3; } else { dst[0] = 0xf0 | (ucs4 >> 18); dst[1] = 0x80 | ((ucs4 >> 12) & 0x3f); dst[2] = 0x80 | ((ucs4 >> 6) & 0x3f); dst[3] = 0x80 | (ucs4 & 0x3f); dst += 4; } } } // skip over trailing '-' in modified UTF-7 encoding if (*src=='-') { ++src; } } } *dst = '\0'; return res; } /******************************************************************************* * Encode/decode extended header, RFC 2231, RFC 5987 ******************************************************************************/ /** * Check if extended header format is needed for a given string. * * @param to_check Null-terminated UTF-8 string to check. * @return 0=extended header encoding is not needed, * 1=extended header encoding is needed, * use dc_encode_ext_header() for this purpose. */ int dc_needs_ext_header(const char* to_check) { if (to_check) { while (*to_check) { if (!isalnum(*to_check) && *to_check!='-' && *to_check!='_' && *to_check!='.' && *to_check!='~') { return 1; } to_check++; } } return 0; } /** * Encode an UTF-8 string to the extended header format. * * Example: `Bj√∂rn Petersen` gets encoded to `utf-8''Bj%C3%B6rn%20Petersen` * * @param to_encode Null-terminated UTF-8 string to encode. * @return Null-terminated encoded string. Must be free()'d after usage. * Halts the program on memory allocation errors, * for all other errors, an empty string is returned or just the given string is returned. * NULL is never returned. */ char* dc_encode_ext_header(const char* to_encode) { #define PREFIX "utf-8''" const char *pstr = to_encode; if (to_encode==NULL) { return dc_strdup(PREFIX); } char *buf = malloc(strlen(PREFIX) + strlen(to_encode) * 3 + 1); if (buf==NULL) { exit(46); } char* pbuf = buf; strcpy(pbuf, PREFIX); pbuf += strlen(pbuf); while (*pstr) { if (isalnum(*pstr) || *pstr=='-' || *pstr=='_' || *pstr=='.' || *pstr=='~') { *pbuf++ = *pstr; } else { *pbuf++ = '%', *pbuf++ = int_2_uppercase_hex(*pstr >> 4), *pbuf++ = int_2_uppercase_hex(*pstr & 15); } pstr++; } *pbuf = '\0'; return buf; } /** * Decode an extended-header-format strings to UTF-8. * * @param to_decode Null-terminated string to decode * @return Null-terminated decoded UTF-8 string. Must be free()'d after usage. * Halts the program on memory allocation errors, * for all other errors, an empty string is returned or just the given string is returned. * NULL is never returned. */ char* dc_decode_ext_header(const char* to_decode) { char* decoded = NULL; char* charset = NULL; const char* p2 = NULL; if (to_decode==NULL) { goto cleanup; } // get char set if ((p2=strchr(to_decode, '\''))==NULL || (p2==to_decode) /*no empty charset allowed*/) { goto cleanup; } charset = dc_null_terminate(to_decode, p2-to_decode); p2++; // skip language if ((p2=strchr(p2, '\''))==NULL) { goto cleanup; } p2++; // decode text decoded = dc_urldecode(p2); if (charset!=NULL && strcmp(charset, "utf-8")!=0 && strcmp(charset, "UTF-8")!=0) { char* converted = NULL; int r = charconv("utf-8", charset, decoded, strlen(decoded), &converted); if (r==MAIL_CHARCONV_NO_ERROR && converted != NULL) { free(decoded); decoded = converted; } else { free(converted); } } cleanup: free(charset); return decoded? decoded : dc_strdup(to_decode); } ``` Filename: dc_token.c ```c #include "dc_context.h" #include "dc_token.h" void dc_token_save(dc_context_t* context, dc_tokennamespc_t namespc, uint32_t foreign_id, const char* token) { sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || token==NULL) { // foreign_id may be 0 goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "INSERT INTO tokens (namespc, foreign_id, token, timestamp) VALUES (?, ?, ?, ?);"); sqlite3_bind_int (stmt, 1, (int)namespc); sqlite3_bind_int (stmt, 2, (int)foreign_id); sqlite3_bind_text (stmt, 3, token, -1, SQLITE_STATIC); sqlite3_bind_int64(stmt, 4, time(NULL)); sqlite3_step(stmt); cleanup: sqlite3_finalize(stmt); } char* dc_token_lookup(dc_context_t* context, dc_tokennamespc_t namespc, uint32_t foreign_id) { char* token = NULL; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT token FROM tokens WHERE namespc=? AND foreign_id=?;"); sqlite3_bind_int (stmt, 1, (int)namespc); sqlite3_bind_int (stmt, 2, (int)foreign_id); sqlite3_step(stmt); token = dc_strdup_keep_null((char*)sqlite3_column_text(stmt, 0)); cleanup: sqlite3_finalize(stmt); return token; } int dc_token_exists(dc_context_t* context, dc_tokennamespc_t namespc, const char* token) { int exists = 0; sqlite3_stmt* stmt = NULL; if (context==NULL || context->magic!=DC_CONTEXT_MAGIC || token==NULL) { goto cleanup; } stmt = dc_sqlite3_prepare(context->sql, "SELECT id FROM tokens WHERE namespc=? AND token=?;"); sqlite3_bind_int (stmt, 1, (int)namespc); sqlite3_bind_text(stmt, 2, token, -1, SQLITE_STATIC); exists = (sqlite3_step(stmt)!=0); cleanup: sqlite3_finalize(stmt); return exists; } ``` Filename: dc_tools.c ```c #include #include #include #include #include #include /* for getpid() */ #include /* for getpid() */ #include #include #include #include "dc_context.h" /******************************************************************************* * Math tools ******************************************************************************/ int dc_exactly_one_bit_set(int v) { return (v && !(v & (v - 1))); /* via http://www.graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2 */ } /******************************************************************************* * String tools ******************************************************************************/ char* dc_strdup(const char* s) /* strdup(NULL) is undefined, save_strdup(NULL) returns an empty string in this case */ { char* ret = NULL; if (s) { if ((ret=strdup(s))==NULL) { exit(16); /* cannot allocate (little) memory, unrecoverable error */ } } else { if ((ret=(char*)calloc(1, 1))==NULL) { exit(17); /* cannot allocate little memory, unrecoverable error */ } } return ret; } char* dc_strdup_keep_null(const char* s) /* strdup(NULL) is undefined, safe_strdup_keep_null(NULL) returns NULL in this case */ { return s? dc_strdup(s) : NULL; } int dc_atoi_null_is_0(const char* s) { return s? atoi(s) : 0; } double dc_atof(const char* str) { // hack around atof() that may accept only `,` as decimal point on mac char* test = dc_mprintf("%f", 1.2); test[2] = 0; char* str_locale = dc_strdup(str); dc_str_replace(&str_locale, ".", test+1); double f = atof(str_locale); free(test); free(str_locale); return f; } char* dc_ftoa(double f) { // hack around printf(%f) that may return `,` as decimal point on mac char* test = dc_mprintf("%f", 1.2); test[2] = 0; char* str = dc_mprintf("%f", f); dc_str_replace(&str, test+1, "."); free(test); return str; } void dc_ltrim(char* buf) { size_t len = 0; const unsigned char* cur = NULL; if (buf && *buf) { len = strlen(buf); cur = (const unsigned char*)buf; while (*cur && isspace(*cur)) { cur++; len--; } if ((const unsigned char*)buf!=cur) { memmove(buf, cur, len + 1); } } } void dc_rtrim(char* buf) { size_t len = 0; unsigned char* cur = NULL; if (buf && *buf) { len = strlen(buf); cur = (unsigned char*)buf + len - 1; while (cur!=(unsigned char*)buf && isspace(*cur)) { --cur, --len; } cur[isspace(*cur) ? 0 : 1] = '\0'; } } void dc_trim(char* buf) { dc_ltrim(buf); dc_rtrim(buf); } void dc_strlower_in_place(char* in) { char* p = in; for ( ; *p; p++) { *p = tolower(*p); } } char* dc_strlower(const char* in) /* the result must be free()'d */ { char* out = dc_strdup(in); char* p = out; for ( ; *p; p++) { *p = tolower(*p); } return out; } /* * haystack may be realloc()'d, returns the number of replacements. */ int dc_str_replace(char** haystack, const char* needle, const char* replacement) { int replacements = 0; int start_search_pos = 0; int needle_len = 0; int replacement_len = 0; if (haystack==NULL || *haystack==NULL || needle==NULL || needle[0]==0) { return 0; } needle_len = strlen(needle); replacement_len = replacement? strlen(replacement) : 0; while (1) { char* p2 = strstr((*haystack)+start_search_pos, needle); if (p2==NULL) { break; } start_search_pos = (p2-(*haystack))+replacement_len; /* avoid recursion and skip the replaced part */ *p2 = 0; p2 += needle_len; char* new_string = dc_mprintf("%s%s%s", *haystack, replacement? replacement : "", p2); free(*haystack); *haystack = new_string; replacements++; } return replacements; } int dc_str_contains(const char* haystack, const char* needle) { /* case-insensitive search of needle in haystack, return 1 if found, 0 if not */ if (haystack==NULL || needle==NULL) { return 0; } if (strstr(haystack, needle)!=NULL) { return 1; } char* haystack_lower = dc_strlower(haystack); char* needle_lower = dc_strlower(needle); int ret = strstr(haystack_lower, needle_lower)? 1 : 0; free(haystack_lower); free(needle_lower); return ret; } /** * Creates a null-terminated string from a buffer. * Similar to strndup() but allows bad parameters and just halts the program * on memory allocation errors. * * @param in The start of the string. * @param bytes The number of bytes to take from the string. * @return The null-terminates string, must be free()'d by the caller. * On memory-allocation errors, the program halts. * On other errors, an empty string is returned. */ char* dc_null_terminate(const char* in, int bytes) /* the result must be free()'d */ { char* out = malloc(bytes+1); if (out==NULL) { exit(45); } if (in && bytes > 0) { strncpy(out, in, bytes); } out[bytes] = 0; return out; } /** * Converts a byte-buffer to a string with hexadecimal, * upper-case digits. * * This function is used eg. to create readable fingerprints, however, it may * be used for other purposes as well. * * @param buf The buffer to convert to an hexadecimal string. If this is NULL, * the functions returns NULL. * @param bytes The number of bytes in buf. buf may or may not be null-terminated * If this is <=0, the function returns NULL. * @return Returns a null-terminated string, must be free()'d when no longer * needed. For errors, NULL is returned. */ char* dc_binary_to_uc_hex(const uint8_t* buf, size_t bytes) { char* hex = NULL; int i = 0; if (buf==NULL || bytes<=0) { goto cleanup; } if ((hex=calloc(sizeof(char), bytes*2+1))==NULL) { goto cleanup; } for (i = 0; i < bytes; i++) { snprintf(&hex[i*2], 3, "%02X", (int)buf[i]); } cleanup: return hex; } char* dc_mprintf(const char* format, ...) { char testbuf[1]; char* buf = NULL; int char_cnt_without_zero = 0; va_list argp; va_list argp_copy; va_start(argp, format); va_copy(argp_copy, argp); char_cnt_without_zero = vsnprintf(testbuf, 0, format, argp); va_end(argp); if (char_cnt_without_zero < 0) { va_end(argp_copy); return dc_strdup("ErrFmt"); } buf = malloc(char_cnt_without_zero+2 /* +1 would be enough, however, protect against off-by-one-errors */); if (buf==NULL) { va_end(argp_copy); return dc_strdup("ErrMem"); } vsnprintf(buf, char_cnt_without_zero+1, format, argp_copy); va_end(argp_copy); return buf; #if 0 /* old implementation based upon sqlite3 */ char *sqlite_str, *c_string; va_list argp; va_start(argp, format); /* expects the last non-variable argument as the second parameter */ sqlite_str = sqlite3_vmprintf(format, argp); va_end(argp); if (sqlite_str==NULL) { return dc_strdup("ErrFmt"); /* error - the result must be free()'d */ } /* as sqlite-strings must be freed using sqlite3_free() instead of a simple free(), convert it to a normal c-string */ c_string = dc_strdup(sqlite_str); /* exists on errors */ sqlite3_free(sqlite_str); return c_string; /* success - the result must be free()'d */ #endif /* /old implementation based upon sqlite3 */ } /** * Remove all `\r` characters from the given buffer. * This function will not convert anything else in the future, so it can be used * safely for marking thinks to remove by `\r` and call this function afterwards. * * @param buf The buffer to convert. * @return None. */ void dc_remove_cr_chars(char* buf) { const char* p1 = buf; /* search for first `\r` */ while (*p1) { if (*p1=='\r') { break; } p1++; } char* p2 = (char*)p1; /* p1 is `\r` or null-byte; start removing `\r` */ while (*p1) { if (*p1!='\r') { *p2 = *p1; p2++; } p1++; } /* add trailing null-byte */ *p2 = 0; } /** * Unify the lineends in the given null-terminated buffer to a simple `\n` (LF, ^J). * Carriage return characters (`\r`, CR, ^M) are removed. * * This function does _not_ convert only-CR linefeeds; AFAIK, they only came from * Mac OS 9 and before and should not be in use for nearly 20 year, so maybe this * is no issue. However, this could be easily added to the function as needed * by converting all `\r` to `\n` if there is no single `\n` in the original buffer. * * @param buf The buffer to convert. * @return None. */ void dc_unify_lineends(char* buf) { // this function may be extended to do more linefeed unification, do not mess up // with dc_remove_cr_chars() which does only exactly removing CR. dc_remove_cr_chars(buf); } void dc_replace_bad_utf8_chars(char* buf) { if (buf==NULL) { return; } unsigned char* p1 = (unsigned char*)buf; /* force unsigned - otherwise the `> ' '` comparison will fail */ int p1len = strlen(buf); int c = 0; int i = 0; int ix = 0; int n = 0; int j = 0; for (i=0, ix=p1len; i < ix; i++) { c = p1[i]; if (c > 0 && c <= 0x7f) { n=0; } /* 0bbbbbbb */ else if ((c & 0xE0) == 0xC0) { n=1; } /* 110bbbbb */ else if (c==0xed && i<(ix-1) && (p1[i+1] & 0xa0)==0xa0) { goto error; } /* U+d800 to U+dfff */ else if ((c & 0xF0) == 0xE0) { n=2; } /* 1110bbbb */ else if ((c & 0xF8) == 0xF0) { n=3; } /* 11110bbb */ //else if ((c & 0xFC) == 0xF8) { n=4; } /* 111110bb - not valid in https://tools.ietf.org/html/rfc3629 */ //else if ((c & 0xFE) == 0xFC) { n=5; } /* 1111110b - not valid in https://tools.ietf.org/html/rfc3629 */ else { goto error; } for (j = 0; j < n && i < ix; j++) { /* n bytes matching 10bbbbbb follow ? */ if ((++i == ix) || (( p1[i] & 0xC0) != 0x80)) { goto error; } } } /* everything is fine */ return; error: /* there are errors in the string -> replace potential errors by the character `_` (to avoid problems in filenames, we do not use eg. `?`) */ while (*p1) { if (*p1 > 0x7f) { *p1 = '_'; } p1++; } } size_t dc_utf8_strlen(const char* s) { if (s==NULL) { return 0; } size_t i = 0; size_t j = 0; while (s[i]) { if ((s[i]&0xC0) != 0x80) j++; i++; } return j; } static size_t dc_utf8_strnlen(const char* s, size_t n) { if (s==NULL) { return 0; } size_t i = 0; size_t j = 0; while (i < n) { if ((s[i]&0xC0) != 0x80) j++; i++; } return j; } void dc_truncate_n_unwrap_str(char* buf, int approx_characters, int do_unwrap) { /* Function unwraps the given string and removes unnecessary whitespace. Function stops processing after approx_characters are processed. (as we're using UTF-8, for simplicity, we cut the string only at whitespaces). */ const char* ellipse_utf8 = do_unwrap? " ..." : " " DC_EDITORIAL_ELLIPSE; /* a single line is truncated `...` instead of `[...]` (the former is typically also used by the UI to fit strings in a rectangle) */ int lastIsCharacter = 0; unsigned char* p1 = (unsigned char*)buf; /* force unsigned - otherwise the `> ' '` comparison will fail */ while (*p1) { if (*p1 > ' ') { lastIsCharacter = 1; } else { if (lastIsCharacter) { size_t used_bytes = (size_t)((uintptr_t)p1 - (uintptr_t)buf); if (dc_utf8_strnlen(buf, used_bytes) >= approx_characters) { size_t buf_bytes = strlen(buf); if (buf_bytes-used_bytes >= strlen(ellipse_utf8) /* check if we have room for the ellipse */) { strcpy((char*)p1, ellipse_utf8); } break; } lastIsCharacter = 0; if (do_unwrap) { *p1 = ' '; } } else { if (do_unwrap) { *p1 = '\r'; /* removed below */ } } } p1++; } if (do_unwrap) { dc_remove_cr_chars(buf); } } void dc_truncate_str(char* buf, int approx_chars) { if (approx_chars > 0 && strlen(buf) > approx_chars+strlen(DC_EDITORIAL_ELLIPSE)) { char* p = &buf[approx_chars]; /* null-terminate string at the desired length */ *p = 0; if (strchr(buf, ' ')!=NULL) { while (p[-1]!=' ' && p[-1]!='\n') { /* rewind to the previous space, avoid half utf-8 characters */ p--; *p = 0; } } strcat(p, DC_EDITORIAL_ELLIPSE); } } carray* dc_split_into_lines(const char* buf_terminated) { carray* lines = carray_new(1024); size_t line_chars = 0; const char* p1 = buf_terminated; const char* line_start = p1; unsigned int l_indx = 0; while (*p1) { if (*p1=='\n') { carray_add(lines, (void*)strndup(line_start, line_chars), &l_indx); p1++; line_start = p1; line_chars = 0; } else { p1++; line_chars++; } } carray_add(lines, (void*)strndup(line_start, line_chars), &l_indx); return lines; /* should be freed using dc_free_splitted_lines() */ } void dc_free_splitted_lines(carray* lines) { if (lines) { int i, cnt = carray_count(lines); for (i = 0; i < cnt; i++) { free(carray_get(lines, i)); } carray_free(lines); } } char* dc_insert_breaks(const char* in, int break_every, const char* break_chars) { /* insert a space every n characters, the return must be free()'d. this is useful to allow lines being wrapped according to RFC 5322 (adds linebreaks before spaces) */ if (in==NULL || break_every<=0 || break_chars==NULL) { return dc_strdup(in); } int out_len = strlen(in); int chars_added = 0; int break_chars_len = strlen(break_chars); out_len += (out_len/break_every+1)*break_chars_len + 1/*nullbyte*/; char* out = malloc(out_len); if (out==NULL) { return NULL; } const char* i = in; char* o = out; while (*i) { *o++ = *i++; chars_added++; if (chars_added==break_every && *i) { strcpy(o, break_chars); o+=break_chars_len; chars_added = 0; } } *o = 0; return out; } // Join clist element to a string. char* dc_str_from_clist(const clist* list, const char* delimiter) { dc_strbuilder_t str; dc_strbuilder_init(&str, 256); if (list) { for (clistiter* cur = clist_begin(list); cur!=NULL ; cur=clist_next(cur)) { const char* rfc724_mid = clist_content(cur); if (rfc724_mid) { if (str.buf[0] && delimiter) { dc_strbuilder_cat(&str, delimiter); } dc_strbuilder_cat(&str, rfc724_mid); } } } return str.buf; } // Split a string by a character. // If the string is empty or NULL, an empty list is returned. // The returned clist must be freed using clist_free_content()+clist_free() // or given eg. to libetpan objects. clist* dc_str_to_clist(const char* str, const char* delimiter) { clist* list = clist_new(); if (list==NULL) { exit(54); } if (str && delimiter && strlen(delimiter)>=1) { const char* p1 = str; while (1) { const char* p2 = strstr(p1, delimiter); if (p2==NULL) { clist_append(list, (void*)strdup(p1)); break; } else { clist_append(list, (void*)strndup(p1, p2-p1)); p1 = p2+strlen(delimiter); } } } return list; } int dc_str_to_color(const char* str) { char* str_lower = dc_strlower(str); /* the colors must fulfill some criterions as: - contrast to black and to white - work as a text-color - being noticable on a typical map - harmonize together while being different enough (therefore, we cannot just use random rgb colors :) */ static uint32_t colors[] = { 0xe56555, 0xf28c48, 0x8e85ee, 0x76c84d, 0x5bb6cc, 0x549cdd, 0xd25c99, 0xb37800, 0xf23030, 0x39B249, 0xBB243B, 0x964078, 0x66874F, 0x308AB9, 0x127ed0, 0xBE450C }; int checksum = 0; int str_len = strlen(str_lower); for (int i = 0; i < str_len; i++) { checksum += (i+1)*str_lower[i]; checksum %= 0x00FFFFFF; } int color_index = checksum % (sizeof(colors)/sizeof(uint32_t)); free(str_lower); return colors[color_index]; } /******************************************************************************* * clist tools ******************************************************************************/ void clist_free_content(const clist* haystack) { for (clistiter* iter=clist_begin(haystack); iter!=NULL; iter=clist_next(iter)) { free(iter->data); iter->data = NULL; } } int clist_search_string_nocase(const clist* haystack, const char* needle) { for (clistiter* iter=clist_begin(haystack); iter!=NULL; iter=clist_next(iter)) { if (strcasecmp((const char*)iter->data, needle)==0) { return 1; } } return 0; } /******************************************************************************* * date/time tools ******************************************************************************/ static int tmcomp(struct tm * atmp, struct tm * btmp) /* from mailcore2 */ { int result = 0; if ((result = (atmp->tm_year - btmp->tm_year))==0 && (result = (atmp->tm_mon - btmp->tm_mon))==0 && (result = (atmp->tm_mday - btmp->tm_mday))==0 && (result = (atmp->tm_hour - btmp->tm_hour))==0 && (result = (atmp->tm_min - btmp->tm_min))==0) result = atmp->tm_sec - btmp->tm_sec; return result; } time_t mkgmtime(struct tm * tmp) /* from mailcore2 */ { int dir = 0; int bits = 0; int saved_seconds = 0; time_t t = 0; struct tm yourtm; struct tm mytm; yourtm = *tmp; saved_seconds = yourtm.tm_sec; yourtm.tm_sec = 0; /* ** Calculate the number of magnitude bits in a time_t ** (this works regardless of whether time_t is ** signed or unsigned, though lint complains if unsigned). */ for (bits = 0, t = 1; t > 0; ++bits, t <<= 1) ; /* ** If time_t is signed, then 0 is the median value, ** if time_t is unsigned, then 1 << bits is median. */ if(bits > 40) bits = 40; t = (t < 0) ? 0 : ((time_t) 1 << bits); for ( ; ;) { gmtime_r(&t, &mytm); dir = tmcomp(&mytm, &yourtm); if (dir!=0) { if (bits-- < 0) { return DC_INVALID_TIMESTAMP; } if (bits < 0) --t; else if (dir > 0) t -= (time_t) 1 << bits; else t += (time_t) 1 << bits; continue; } break; } t += saved_seconds; return t; } time_t dc_timestamp_from_date(struct mailimf_date_time * date_time) /* from mailcore2 */ { struct tm tmval; time_t timeval = 0; int zone_min = 0; int zone_hour = 0; memset(&tmval, 0, sizeof(struct tm)); tmval.tm_sec = date_time->dt_sec; tmval.tm_min = date_time->dt_min; tmval.tm_hour = date_time->dt_hour; tmval.tm_mday = date_time->dt_day; tmval.tm_mon = date_time->dt_month - 1; if (date_time->dt_year < 1000) { /* workaround when century is not given in year */ tmval.tm_year = date_time->dt_year + 2000 - 1900; } else { tmval.tm_year = date_time->dt_year - 1900; } timeval = mkgmtime(&tmval); if (date_time->dt_zone >= 0) { zone_hour = date_time->dt_zone / 100; zone_min = date_time->dt_zone % 100; } else { zone_hour = -((- date_time->dt_zone) / 100); zone_min = -((- date_time->dt_zone) % 100); } timeval -= zone_hour * 3600 + zone_min * 60; return timeval; } long dc_gm2local_offset(void) { /* returns the offset that must be _added_ to an UTC/GMT-time to create the localtime. the function may return nagative values. */ time_t gmtime = time(NULL); struct tm timeinfo = {0}; localtime_r(&gmtime, &timeinfo); return timeinfo.tm_gmtoff; } char* dc_timestamp_to_str(time_t wanted) { struct tm wanted_struct; memcpy(&wanted_struct, localtime(&wanted), sizeof(struct tm)); /* if you need the current time for relative dates, use the following lines: time_t curr; struct tm curr_struct; time(&curr); memcpy(&curr_struct, localtime(&curr), sizeof(struct tm)); */ return dc_mprintf("%02i.%02i.%04i %02i:%02i:%02i", (int)wanted_struct.tm_mday, (int)wanted_struct.tm_mon+1, (int)wanted_struct.tm_year+1900, (int)wanted_struct.tm_hour, (int)wanted_struct.tm_min, (int)wanted_struct.tm_sec); } struct mailimap_date_time* dc_timestamp_to_mailimap_date_time(time_t timeval) { struct tm gmt; struct tm lt; int off = 0; struct mailimap_date_time* date_time; int sign = 0; int hour = 0; int min = 0; gmtime_r(&timeval, &gmt); localtime_r(&timeval, <); off = (int) ((mkgmtime(<) - mkgmtime(&gmt)) / 60); if (off < 0) { sign = -1; } else { sign = 1; } off = off * sign; min = off % 60; hour = off / 60; off = hour * 100 + min; off = off * sign; date_time = mailimap_date_time_new(lt.tm_mday, lt.tm_mon + 1, lt.tm_year + 1900, lt.tm_hour, lt.tm_min, lt.tm_sec, off); return date_time; } /******************************************************************************* * Time smearing ******************************************************************************/ #define DC_MAX_SECONDS_TO_LEND_FROM_FUTURE 5 #define SMEAR_LOCK { pthread_mutex_lock(&context->smear_critical); } #define SMEAR_UNLOCK { pthread_mutex_unlock(&context->smear_critical); } time_t dc_create_smeared_timestamp(dc_context_t* context) { time_t now = time(NULL); time_t ret = now; SMEAR_LOCK if (ret <= context->last_smeared_timestamp) { ret = context->last_smeared_timestamp+1; if ((ret-now) > DC_MAX_SECONDS_TO_LEND_FROM_FUTURE) { ret = now + DC_MAX_SECONDS_TO_LEND_FROM_FUTURE; } } context->last_smeared_timestamp = ret; SMEAR_UNLOCK return ret; } time_t dc_create_smeared_timestamps(dc_context_t* context, int count) { /* get a range to timestamps that can be used uniquely */ time_t now = time(NULL); time_t start = now + DC_MIN(count, DC_MAX_SECONDS_TO_LEND_FROM_FUTURE) - count; SMEAR_LOCK start = DC_MAX(context->last_smeared_timestamp+1, start); context->last_smeared_timestamp = start+(count-1); SMEAR_UNLOCK return start; } time_t dc_smeared_time(dc_context_t* context) { /* function returns a corrected time(NULL) */ time_t now = time(NULL); SMEAR_LOCK if (context->last_smeared_timestamp >= now) { now = context->last_smeared_timestamp+1; } SMEAR_UNLOCK return now; } /******************************************************************************* * generate Message-IDs ******************************************************************************/ static char* encode_66bits_as_base64(uint32_t v1, uint32_t v2, uint32_t fill /*only the lower 2 bits are used*/) { /* encode 66 bits as a base64 string. This is useful for ID generating with short strings as we save 5 character in each id compared to 64 bit hex encoding, for a typical group ID, these are 10 characters (grpid+msgid): hex: 64 bit, 4 bits/character, length = 64/4 = 16 characters base64: 64 bit, 6 bits/character, length = 64/6 = 11 characters (plus 2 additional bits) */ char* ret = malloc(12); if (ret==NULL) { exit(34); } static const char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; ret[ 0] = chars[ (v1>>26) & 0x3F ]; ret[ 1] = chars[ (v1>>20) & 0x3F ]; ret[ 2] = chars[ (v1>>14) & 0x3F ]; ret[ 3] = chars[ (v1>> 8) & 0x3F ]; ret[ 4] = chars[ (v1>> 2) & 0x3F ]; ret[ 5] = chars[ ( (v1<< 4) & 0x30) | ( (v2>>28) & 0x0F) ]; ret[ 6] = chars[ (v2>>22) & 0x3F ]; ret[ 7] = chars[ (v2>>16) & 0x3F ]; ret[ 8] = chars[ (v2>>10) & 0x3F ]; ret[ 9] = chars[ (v2>> 4) & 0x3F ]; ret[10] = chars[ ( (v2<< 2) & 0x3C) | (fill & 0x03) ]; ret[11] = 0; return ret; } char* dc_create_id(void) { /* generate an id. the generated ID should be as short and as unique as possible: - short, because it may also used as part of Message-ID headers or in QR codes - unique as two IDs generated on two devices should not be the same. However, collisions are not world-wide but only by the few contacts. IDs generated by this function are 66 bit wide and are returned as 11 base64 characters. If possible, RNG of OpenSSL is used. Additional information when used as a message-id or group-id: - for OUTGOING messages this ID is written to the header as `Chat-Group-ID:` and is added to the message ID as Gr..@ - for INCOMING messages, the ID is taken from the Chat-Group-ID-header or from the Message-ID in the In-Reply-To: or References:-Header - the group-id should be a string with the characters [a-zA-Z0-9\-_] */ uint32_t buf[3]; if (!RAND_bytes((unsigned char*)&buf, sizeof(uint32_t)*3)) { RAND_pseudo_bytes((unsigned char*)&buf, sizeof(uint32_t)*3); } return encode_66bits_as_base64(buf[0], buf[1], buf[2]/*only the lower 2 bits are taken from this value*/); } char* dc_create_outgoing_rfc724_mid(const char* grpid, const char* from_addr) { /* Function generates a Message-ID that can be used for a new outgoing message. - this function is called for all outgoing messages. - the message ID should be globally unique - do not add a counter or any private data as as this may give unneeded information to the receiver */ char* rand1 = NULL; char* rand2 = dc_create_id(); char* ret = NULL; const char* at_hostname = strchr(from_addr, '@'); if (at_hostname==NULL) { at_hostname = "@nohost"; } if (grpid) { ret = dc_mprintf("Gr.%s.%s%s", grpid, rand2, at_hostname); /* ^^^ `Gr.` must never change as this is used to identify group messages in normal-clients-replies. The dot is choosen as this is normally not used for random ID creation. */ } else { rand1 = dc_create_id(); ret = dc_mprintf("Mr.%s.%s%s", rand1, rand2, at_hostname); /* ^^^ `Mr.` is currently not used, however, this may change in future */ } free(rand1); free(rand2); return ret; } char* dc_create_incoming_rfc724_mid(time_t message_timestamp, uint32_t contact_id_from, dc_array_t* contact_ids_to) { /* Function generates a Message-ID for incoming messages that lacks one. - normally, this function is not needed as incoming messages already have an ID - the generated ID is only for internal use; it should be database-unique - when fetching the same message again, this function should generate the same Message-ID */ if (contact_ids_to==NULL || dc_array_get_cnt(contact_ids_to)==0) { return NULL; } /* find out the largest receiver ID (we could also take the smallest, but it should be unique) */ size_t i = 0; size_t icnt = dc_array_get_cnt(contact_ids_to); uint32_t largest_id_to = 0; for (i = 0; i < icnt; i++) { uint32_t cur_id = dc_array_get_id(contact_ids_to, i); if (cur_id > largest_id_to) { largest_id_to = cur_id; } } /* build a more or less unique string based on the timestamp and one receiver - for our purposes, this seems "good enough" for the moment, esp. as clients normally set Message-ID on sent. */ return dc_mprintf("%lu-%lu-%lu@stub", (unsigned long)message_timestamp, (unsigned long)contact_id_from, (unsigned long)largest_id_to); } char* dc_extract_grpid_from_rfc724_mid(const char* mid) { /* extract our group ID from Message-IDs as `Gr.12345678901.morerandom@domain.de`; "12345678901" is the wanted ID in this example. */ int success = 0; char* grpid = NULL; char* p1 = NULL; int grpid_len = 0; if (mid==NULL || strlen(mid)<8 || mid[0]!='G' || mid[1]!='r' || mid[2]!='.') { goto cleanup; } grpid = dc_strdup(&mid[3]); p1 = strchr(grpid, '.'); if (p1==NULL) { goto cleanup; } *p1 = 0; #define DC_ALSO_VALID_ID_LEN 16 /* length returned by create_adhoc_grp_id() */ grpid_len = strlen(grpid); if (grpid_len!=DC_CREATE_ID_LEN && grpid_len!=DC_ALSO_VALID_ID_LEN) { /* strict length comparison, the 'Gr.' magic is weak enough */ goto cleanup; } success = 1; cleanup: if (success==0) { free(grpid); grpid = NULL; } return success? grpid : NULL; } char* dc_extract_grpid_from_rfc724_mid_list(const clist* list) { if (list) { for (clistiter* cur = clist_begin(list); cur!=NULL ; cur=clist_next(cur)) { const char* mid = clist_content(cur); char* grpid = dc_extract_grpid_from_rfc724_mid(mid); if (grpid) { return grpid; } } } return NULL; } /******************************************************************************* * file tools ******************************************************************************/ /* * removes trailing slash from given path. */ void dc_ensure_no_slash(char* pathNfilename) { int path_len = strlen(pathNfilename); if (path_len > 0) { if (pathNfilename[path_len-1]=='/' || pathNfilename[path_len-1]=='\\') { pathNfilename[path_len-1] = 0; } } } void dc_validate_filename(char* filename) { /* function modifies the given buffer and replaces all characters not valid in filenames by a "-" */ char* p1 = filename; while (*p1) { if (*p1=='/' || *p1=='\\' || *p1==':') { *p1 = '-'; } p1++; } } char* dc_get_filename(const char* pathNfilename) { const char* p = strrchr(pathNfilename, '/'); if (p==NULL) { p = strrchr(pathNfilename, '\\'); } if (p) { p++; return dc_strdup(p); } else { return dc_strdup(pathNfilename); } } void dc_split_filename(const char* pathNfilename, char** ret_basename, char** ret_all_suffixes_incl_dot) { /* splits a filename into basename and all suffixes, eg. "/path/foo.tar.gz" is split into "foo.tar" and ".gz", (we use the _last_ dot which allows the usage inside the filename which are very usual; maybe the detection could be more intelligent, however, for the moment, it is just file) - if there is no suffix, the returned suffix string is empty, eg. "/path/foobar" is split into "foobar" and "" - the case of the returned suffix is preserved; this is to allow reconstruction of (similar) names */ char* basename = dc_get_filename(pathNfilename); char* suffix = NULL; char* p1 = strrchr(basename, '.'); if (p1) { suffix = dc_strdup(p1); *p1 = 0; } else { suffix = dc_strdup(NULL); } /* return the given values */ if (ret_basename ) { *ret_basename = basename; } else { free(basename); } if (ret_all_suffixes_incl_dot) { *ret_all_suffixes_incl_dot = suffix; } else { free(suffix); } } char* dc_get_filesuffix_lc(const char* pathNfilename) { if (pathNfilename) { const char* p = strrchr(pathNfilename, '.'); /* use the last point, we're interesting the "main" type */ if (p) { p++; return dc_strlower(p); /* in contrast to dc_split_filename() we return the lowercase suffix */ } } return NULL; } int dc_get_filemeta(const void* buf_start, size_t buf_bytes, uint32_t* ret_width, uint32_t *ret_height) { /* Strategy: reading GIF dimensions requires the first 10 bytes of the file reading PNG dimensions requires the first 24 bytes of the file reading JPEG dimensions requires scanning through jpeg chunks In all formats, the file is at least 24 bytes big, so we'll read that always inspired by http://www.cplusplus.com/forum/beginner/45217/ */ const unsigned char* buf = buf_start; if (buf_bytes<24) { return 0; } /* For JPEGs, we need to check the first bytes of each DCT chunk. */ if (buf[0]==0xFF && buf[1]==0xD8 && buf[2]==0xFF) { long pos = 2; while (buf[pos]==0xFF) { if (buf[pos+1]==0xC0 || buf[pos+1]==0xC1 || buf[pos+1]==0xC2 || buf[pos+1]==0xC3 || buf[pos+1]==0xC9 || buf[pos+1]==0xCA || buf[pos+1]==0xCB) { *ret_height = (buf[pos+5]<<8) + buf[pos+6]; /* sic! height is first */ *ret_width = (buf[pos+7]<<8) + buf[pos+8]; return 1; } pos += 2+(buf[pos+2]<<8)+buf[pos+3]; if (pos+12>buf_bytes) { break; } } } /* GIF: first three bytes say "GIF", next three give version number. Then dimensions */ if (buf[0]=='G' && buf[1]=='I' && buf[2]=='F') { *ret_width = buf[6] + (buf[7]<<8); *ret_height = buf[8] + (buf[9]<<8); return 1; } /* PNG: the first frame is by definition an IHDR frame, which gives dimensions */ if (buf[0]==0x89 && buf[1]=='P' && buf[2]=='N' && buf[3]=='G' && buf[4]==0x0D && buf[5]==0x0A && buf[6]==0x1A && buf[7]==0x0A && buf[12]=='I' && buf[13]=='H' && buf[14]=='D' && buf[15]=='R') { *ret_width = (buf[16]<<24) + (buf[17]<<16) + (buf[18]<<8) + (buf[19]<<0); *ret_height = (buf[20]<<24) + (buf[21]<<16) + (buf[22]<<8) + (buf[23]<<0); return 1; } return 0; } char* dc_get_abs_path(dc_context_t* context, const char* pathNfilename) { int success = 0; char* pathNfilename_abs = NULL; if (context==NULL || pathNfilename==NULL) { goto cleanup; } pathNfilename_abs = dc_strdup(pathNfilename); if (strncmp(pathNfilename_abs, "$BLOBDIR", 8)==0) { if (context->blobdir==NULL) { goto cleanup; } dc_str_replace(&pathNfilename_abs, "$BLOBDIR", context->blobdir); } success = 1; cleanup: if (!success) { free(pathNfilename_abs); pathNfilename_abs = NULL; } return pathNfilename_abs; } int dc_file_exist(dc_context_t* context, const char* pathNfilename) { int exist = 0; char* pathNfilename_abs = NULL; if ((pathNfilename_abs=dc_get_abs_path(context, pathNfilename))==NULL) { goto cleanup; } struct stat st; if (stat(pathNfilename_abs, &st)==0) { exist = 1; // the size, however, may be 0 } cleanup: free(pathNfilename_abs); return exist; } uint64_t dc_get_filebytes(dc_context_t* context, const char* pathNfilename) { uint64_t filebytes = 0; char* pathNfilename_abs = NULL; if ((pathNfilename_abs=dc_get_abs_path(context, pathNfilename))==NULL) { goto cleanup; } struct stat st; if (stat(pathNfilename_abs, &st)==0) { filebytes = (uint64_t)st.st_size; } cleanup: free(pathNfilename_abs); return filebytes; } int dc_delete_file(dc_context_t* context, const char* pathNfilename) { int success = 0; char* pathNfilename_abs = NULL; if ((pathNfilename_abs=dc_get_abs_path(context, pathNfilename))==NULL) { goto cleanup; } if (remove(pathNfilename_abs)!=0) { dc_log_warning(context, 0, "Cannot delete \"%s\".", pathNfilename); goto cleanup; } success = 1; cleanup: free(pathNfilename_abs); return success; } int dc_copy_file(dc_context_t* context, const char* src, const char* dest) { int success = 0; char* src_abs = NULL; char* dest_abs = NULL; int fd_src = -1; int fd_dest = -1; #define DC_COPY_BUF_SIZE 4096 char buf[DC_COPY_BUF_SIZE]; size_t bytes_read = 0; int anything_copied = 0; if ((src_abs=dc_get_abs_path(context, src))==NULL || (dest_abs=dc_get_abs_path(context, dest))==NULL) { goto cleanup; } if ((fd_src=open(src_abs, O_RDONLY)) < 0) { dc_log_error(context, 0, "Cannot open source file \"%s\".", src); goto cleanup; } if ((fd_dest=open(dest_abs, O_WRONLY|O_CREAT|O_EXCL, 0666)) < 0) { dc_log_error(context, 0, "Cannot open destination file \"%s\".", dest); goto cleanup; } while ((bytes_read=read(fd_src, buf, DC_COPY_BUF_SIZE)) > 0) { if (write(fd_dest, buf, bytes_read)!=bytes_read) { dc_log_error(context, 0, "Cannot write %i bytes to \"%s\".", bytes_read, dest); } anything_copied = 1; } if (!anything_copied) { /* not a single byte copied -> check if the source is empty, too */ close(fd_src); fd_src = -1; if (dc_get_filebytes(context, src)!=0) { dc_log_error(context, 0, "Different size information for \"%s\".", bytes_read, dest); goto cleanup; } } success = 1; cleanup: if (fd_src >= 0) { close(fd_src); } if (fd_dest >= 0) { close(fd_dest); } free(src_abs); free(dest_abs); return success; } int dc_create_folder(dc_context_t* context, const char* pathNfilename) { int success = 0; char* pathNfilename_abs = NULL; if ((pathNfilename_abs=dc_get_abs_path(context, pathNfilename))==NULL) { goto cleanup; } struct stat st; if (stat(pathNfilename_abs, &st)==-1) { if (mkdir(pathNfilename_abs, 0755)!=0) { dc_log_warning(context, 0, "Cannot create directory \"%s\".", pathNfilename); goto cleanup; } } success = 1; cleanup: free(pathNfilename_abs); return success; } int dc_write_file(dc_context_t* context, const char* pathNfilename, const void* buf, size_t buf_bytes) { int success = 0; char* pathNfilename_abs = NULL; if ((pathNfilename_abs=dc_get_abs_path(context, pathNfilename))==NULL) { goto cleanup; } FILE* f = fopen(pathNfilename_abs, "wb"); if (f) { if (fwrite(buf, 1, buf_bytes, f)==buf_bytes) { success = 1; } else { dc_log_warning(context, 0, "Cannot write %lu bytes to \"%s\".", (unsigned long)buf_bytes, pathNfilename); } fclose(f); } else { dc_log_warning(context, 0, "Cannot open \"%s\" for writing.", pathNfilename); } cleanup: free(pathNfilename_abs); return success; } int dc_read_file(dc_context_t* context, const char* pathNfilename, void** buf, size_t* buf_bytes) { int success = 0; char* pathNfilename_abs = NULL; FILE* f = NULL; if (pathNfilename==NULL || buf==NULL || buf_bytes==NULL) { return 0; /* do not go to cleanup as this would dereference "buf" and "buf_bytes" */ } *buf = NULL; *buf_bytes = 0; if ((pathNfilename_abs=dc_get_abs_path(context, pathNfilename))==NULL) { goto cleanup; } f = fopen(pathNfilename_abs, "rb"); if (f==NULL) { goto cleanup; } fseek(f, 0, SEEK_END); *buf_bytes = ftell(f); fseek(f, 0, SEEK_SET); if (*buf_bytes<=0) { goto cleanup; } *buf = malloc( (*buf_bytes) + 1 /*be pragmatic and terminate all files by a null - fine for texts and does not hurt for the rest */); if (*buf==NULL) { goto cleanup; } ((char*)*buf)[*buf_bytes /*we allocated one extra byte above*/] = 0; if (fread(*buf, 1, *buf_bytes, f)!=*buf_bytes) { goto cleanup; } success = 1; cleanup: if (f) { fclose(f); } if (success==0) { free(*buf); *buf = NULL; *buf_bytes = 0; dc_log_warning(context, 0, "Cannot read \"%s\" or file is empty.", pathNfilename); } free(pathNfilename_abs); return success; /* buf must be free()'d by the caller */ } char* dc_get_fine_pathNfilename(dc_context_t* context, const char* pathNfolder, const char* desired_filenameNsuffix__) { char* ret = NULL; char* pathNfolder_wo_slash = NULL; char* filenameNsuffix = NULL; char* basename = NULL; char* dotNSuffix = NULL; time_t now = time(NULL); int i = 0; pathNfolder_wo_slash = dc_strdup(pathNfolder); dc_ensure_no_slash(pathNfolder_wo_slash); filenameNsuffix = dc_strdup(desired_filenameNsuffix__); dc_validate_filename(filenameNsuffix); dc_split_filename(filenameNsuffix, &basename, &dotNSuffix); for (i = 0; i < 1000 /*no deadlocks, please*/; i++) { if (i) { time_t idx = i<100? i : now+i; ret = dc_mprintf("%s/%s-%lu%s", pathNfolder_wo_slash, basename, (unsigned long)idx, dotNSuffix); } else { ret = dc_mprintf("%s/%s%s", pathNfolder_wo_slash, basename, dotNSuffix); } if (!dc_file_exist(context, ret)) { goto cleanup; /* fine filename found */ } free(ret); /* try over with the next index */ ret = NULL; } cleanup: free(filenameNsuffix); free(basename); free(dotNSuffix); free(pathNfolder_wo_slash); return ret; } void dc_make_rel_path(dc_context_t* context, char** path) { if (context==NULL || path==NULL || *path==NULL) { return; } if (strncmp(*path, context->blobdir, strlen(context->blobdir))==0) { dc_str_replace(path, context->blobdir, "$BLOBDIR"); } } /** * Check if a path describes a file in the blob directory. * The path can be absolute or relative (starting with `$BLOBDIR`). * The function does not check if the file really exists. */ int dc_is_blobdir_path(dc_context_t* context, const char* path) { if ((strncmp(path, context->blobdir, strlen(context->blobdir))==0) || (strncmp(path, "$BLOBDIR", 8)==0)) { return 1; } return 0; } /** * Copy a file to the blob directory, if needed. * * @param context The context object as returned from dc_context_new(). * @param[in,out] path The path, may be modified to a relative path * starting with `$BLOBDIR`. * @return 1=success file may or may not be copied, 0=error */ int dc_make_rel_and_copy(dc_context_t* context, char** path) { int success = 0; char* filename = NULL; char* blobdir_path = NULL; if (context==NULL || path==NULL || *path==NULL) { goto cleanup; } if (dc_is_blobdir_path(context, *path)) { dc_make_rel_path(context, path); success = 1; // file is already in blobdir goto cleanup; } if ((filename=dc_get_filename(*path))==NULL || (blobdir_path=dc_get_fine_pathNfilename(context, "$BLOBDIR", filename))==NULL || !dc_copy_file(context, *path, blobdir_path)) { goto cleanup; } free(*path); *path = blobdir_path; blobdir_path = NULL; dc_make_rel_path(context, path); success = 1; cleanup: free(blobdir_path); free(filename); return success; } ```