c_path stringclasses 26 values | c_func stringlengths 79 17.1k | rust_path stringlengths 34 53 | rust_func stringlengths 53 16.4k | rust_context stringlengths 0 36.3k | rust_imports stringlengths 0 2.09k | rustrepotrans_file stringlengths 56 77 |
|---|---|---|---|---|---|---|
projects/deltachat-core/c/dc_chat.c | * 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);
} | projects/deltachat-core/rust/chat.rs | pub async fn delete(self, context: &Context) -> Result<()> {
ensure!(
!self.is_special(),
"bad chat_id, can not be a special chat: {}",
self
);
let chat = Chat::load_from_db(context, self).await?;
context
.sql
.execute(
"DELETE FROM msgs_mdns WHERE msg_id IN (SELECT id FROM msgs WHERE chat_id=?);",
(self,),
)
.await?;
context
.sql
.execute("DELETE FROM msgs WHERE chat_id=?;", (self,))
.await?;
context
.sql
.execute("DELETE FROM chats_contacts WHERE chat_id=?;", (self,))
.await?;
context
.sql
.execute("DELETE FROM chats WHERE id=?;", (self,))
.await?;
context.emit_msgs_changed_without_ids();
chatlist_events::emit_chatlist_changed(context);
context
.set_config_internal(Config::LastHousekeeping, None)
.await?;
context.scheduler.interrupt_inbox().await;
if chat.is_self_talk() {
let mut msg = Message::new(Viewtype::Text);
msg.text = stock_str::self_deleted_msg_body(context).await;
add_device_msg(context, None, Some(&mut msg)).await?;
}
chatlist_events::emit_chatlist_changed(context);
Ok(())
} | pub(crate) async fn set_config_internal(&self, key: Config, value: Option<&str>) -> Result<()> {
self.set_config_ex(Sync, key, value).await
}
pub fn new(viewtype: Viewtype) -> Self {
Message {
viewtype,
..Default::default()
}
}
pub(crate) fn emit_chatlist_changed(context: &Context) {
context.emit_event(EventType::ChatlistChanged);
}
pub(crate) async fn self_deleted_msg_body(context: &Context) -> String {
translated(context, StockMessage::SelfDeletedMsgBody).await
}
pub async fn add_device_msg(
context: &Context,
label: Option<&str>,
msg: Option<&mut Message>,
) -> Result<MsgId> {
add_device_msg_with_importance(context, label, msg, false).await
}
pub fn is_self_talk(&self) -> bool {
self.param.exists(Param::Selftalk)
}
pub fn emit_msgs_changed_without_ids(&self) {
self.emit_event(EventType::MsgsChanged {
chat_id: ChatId::new(0),
msg_id: MsgId::new(0),
});
}
pub fn is_special(self) -> bool {
(0..=DC_CHAT_ID_LAST_SPECIAL.0).contains(&self.0)
}
pub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result<Self> {
let mut chat = context
.sql
.query_row(
"SELECT c.type, c.name, c.grpid, c.param, c.archived,
c.blocked, c.locations_send_until, c.muted_until, c.protected
FROM chats c
WHERE c.id=?;",
(chat_id,),
|row| {
let c = Chat {
id: chat_id,
typ: row.get(0)?,
name: row.get::<_, String>(1)?,
grpid: row.get::<_, String>(2)?,
param: row.get::<_, String>(3)?.parse().unwrap_or_default(),
visibility: row.get(4)?,
blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),
is_sending_locations: row.get(6)?,
mute_duration: row.get(7)?,
protected: row.get(8)?,
};
Ok(c)
},
)
.await
.context(format!("Failed loading chat {chat_id} from database"))?;
if chat.id.is_archived_link() {
chat.name = stock_str::archived_chats(context).await;
} else {
if chat.typ == Chattype::Single && chat.name.is_empty() {
// chat.name is set to contact.display_name on changes,
// however, if things went wrong somehow, we do this here explicitly.
let mut chat_name = "Err [Name not found]".to_owned();
match get_chat_contacts(context, chat.id).await {
Ok(contacts) => {
if let Some(contact_id) = contacts.first() {
if let Ok(contact) = Contact::get_by_id(context, *contact_id).await {
contact.get_display_name().clone_into(&mut chat_name);
}
}
}
Err(err) => {
error!(
context,
"Failed to load contacts for {}: {:#}.", chat.id, err
);
}
}
chat.name = chat_name;
}
if chat.param.exists(Param::Selftalk) {
chat.name = stock_str::saved_messages(context).await;
} else if chat.param.exists(Param::Devicetalk) {
chat.name = stock_str::device_messages(context).await;
}
}
Ok(chat)
}
pub enum Config {
/// Email address, used in the `From:` field.
Addr,
/// IMAP server hostname.
MailServer,
/// IMAP server username.
MailUser,
/// IMAP server password.
MailPw,
/// IMAP server port.
MailPort,
/// IMAP server security (e.g. TLS, STARTTLS).
MailSecurity,
/// How to check IMAP server TLS certificates.
ImapCertificateChecks,
/// SMTP server hostname.
SendServer,
/// SMTP server username.
SendUser,
/// SMTP server password.
SendPw,
/// SMTP server port.
SendPort,
/// SMTP server security (e.g. TLS, STARTTLS).
SendSecurity,
/// How to check SMTP server TLS certificates.
SmtpCertificateChecks,
/// Whether to use OAuth 2.
///
/// Historically contained other bitflags, which are now deprecated.
/// Should not be extended in the future, create new config keys instead.
ServerFlags,
/// True if SOCKS5 is enabled.
///
/// Can be used to disable SOCKS5 without erasing SOCKS5 configuration.
Socks5Enabled,
/// SOCKS5 proxy server hostname or address.
Socks5Host,
/// SOCKS5 proxy server port.
Socks5Port,
/// SOCKS5 proxy server username.
Socks5User,
/// SOCKS5 proxy server password.
Socks5Password,
/// Own name to use in the `From:` field when sending messages.
Displayname,
/// Own status to display, sent in message footer.
Selfstatus,
/// Own avatar filename.
Selfavatar,
/// Send BCC copy to self.
///
/// Should be enabled for multidevice setups.
#[strum(props(default = "1"))]
BccSelf,
/// True if encryption is preferred according to Autocrypt standard.
#[strum(props(default = "1"))]
E2eeEnabled,
/// True if Message Delivery Notifications (read receipts) should
/// be sent and requested.
#[strum(props(default = "1"))]
MdnsEnabled,
/// True if "Sent" folder should be watched for changes.
#[strum(props(default = "0"))]
SentboxWatch,
/// True if chat messages should be moved to a separate folder.
#[strum(props(default = "1"))]
MvboxMove,
/// Watch for new messages in the "Mvbox" (aka DeltaChat folder) only.
///
/// This will not entirely disable other folders, e.g. the spam folder will also still
/// be watched for new messages.
#[strum(props(default = "0"))]
OnlyFetchMvbox,
/// Whether to show classic emails or only chat messages.
#[strum(props(default = "2"))] // also change ShowEmails.default() on changes
ShowEmails,
/// Quality of the media files to send.
#[strum(props(default = "0"))] // also change MediaQuality.default() on changes
MediaQuality,
/// If set to "1", on the first time `start_io()` is called after configuring,
/// the newest existing messages are fetched.
/// Existing recipients are added to the contact database regardless of this setting.
#[strum(props(default = "0"))]
FetchExistingMsgs,
/// If set to "1", then existing messages are considered to be already fetched.
/// This flag is reset after successful configuration.
#[strum(props(default = "1"))]
FetchedExistingMsgs,
/// Type of the OpenPGP key to generate.
#[strum(props(default = "0"))]
KeyGenType,
/// Timer in seconds after which the message is deleted from the
/// server.
///
/// Equals to 0 by default, which means the message is never
/// deleted.
///
/// Value 1 is treated as "delete at once": messages are deleted
/// immediately, without moving to DeltaChat folder.
#[strum(props(default = "0"))]
DeleteServerAfter,
/// Timer in seconds after which the message is deleted from the
/// device.
///
/// Equals to 0 by default, which means the message is never
/// deleted.
#[strum(props(default = "0"))]
DeleteDeviceAfter,
/// Move messages to the Trash folder instead of marking them "\Deleted". Overrides
/// `ProviderOptions::delete_to_trash`.
DeleteToTrash,
/// Save raw MIME messages with headers in the database if true.
SaveMimeHeaders,
/// The primary email address. Also see `SecondaryAddrs`.
ConfiguredAddr,
/// Configured IMAP server hostname.
ConfiguredMailServer,
/// Configured IMAP server username.
ConfiguredMailUser,
/// Configured IMAP server password.
ConfiguredMailPw,
/// Configured IMAP server port.
ConfiguredMailPort,
/// Configured IMAP server security (e.g. TLS, STARTTLS).
ConfiguredMailSecurity,
/// How to check IMAP server TLS certificates.
ConfiguredImapCertificateChecks,
/// Configured SMTP server hostname.
ConfiguredSendServer,
/// Configured SMTP server username.
ConfiguredSendUser,
/// Configured SMTP server password.
ConfiguredSendPw,
/// Configured SMTP server port.
ConfiguredSendPort,
/// How to check SMTP server TLS certificates.
ConfiguredSmtpCertificateChecks,
/// Whether OAuth 2 is used with configured provider.
ConfiguredServerFlags,
/// Configured SMTP server security (e.g. TLS, STARTTLS).
ConfiguredSendSecurity,
/// Configured folder for incoming messages.
ConfiguredInboxFolder,
/// Configured folder for chat messages.
ConfiguredMvboxFolder,
/// Configured "Sent" folder.
ConfiguredSentboxFolder,
/// Configured "Trash" folder.
ConfiguredTrashFolder,
/// Unix timestamp of the last successful configuration.
ConfiguredTimestamp,
/// ID of the configured provider from the provider database.
ConfiguredProvider,
/// True if account is configured.
Configured,
/// True if account is a chatmail account.
IsChatmail,
/// All secondary self addresses separated by spaces
/// (`addr1@example.org addr2@example.org addr3@example.org`)
SecondaryAddrs,
/// Read-only core version string.
#[strum(serialize = "sys.version")]
SysVersion,
/// Maximal recommended attachment size in bytes.
#[strum(serialize = "sys.msgsize_max_recommended")]
SysMsgsizeMaxRecommended,
/// Space separated list of all config keys available.
#[strum(serialize = "sys.config_keys")]
SysConfigKeys,
/// True if it is a bot account.
Bot,
/// True when to skip initial start messages in groups.
#[strum(props(default = "0"))]
SkipStartMessages,
/// Whether we send a warning if the password is wrong (set to false when we send a warning
/// because we do not want to send a second warning)
#[strum(props(default = "0"))]
NotifyAboutWrongPw,
/// If a warning about exceeding quota was shown recently,
/// this is the percentage of quota at the time the warning was given.
/// Unset, when quota falls below minimal warning threshold again.
QuotaExceeding,
/// address to webrtc instance to use for videochats
WebrtcInstance,
/// Timestamp of the last time housekeeping was run
LastHousekeeping,
/// Timestamp of the last `CantDecryptOutgoingMsgs` notification.
LastCantDecryptOutgoingMsgs,
/// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.
#[strum(props(default = "60"))]
ScanAllFoldersDebounceSecs,
/// Whether to avoid using IMAP IDLE even if the server supports it.
///
/// This is a developer option for testing "fake idle".
#[strum(props(default = "0"))]
DisableIdle,
/// Defines the max. size (in bytes) of messages downloaded automatically.
/// 0 = no limit.
#[strum(props(default = "0"))]
DownloadLimit,
/// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set.
#[strum(props(default = "1"))]
SyncMsgs,
/// Space-separated list of all the authserv-ids which we believe
/// may be the one of our email server.
///
/// See `crate::authres::update_authservid_candidates`.
AuthservIdCandidates,
/// Make all outgoing messages with Autocrypt header "multipart/signed".
SignUnencrypted,
/// Let the core save all events to the database.
/// This value is used internally to remember the MsgId of the logging xdc
#[strum(props(default = "0"))]
DebugLogging,
/// Last message processed by the bot.
LastMsgId,
/// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by
/// default.
///
/// This is not supposed to be changed by UIs and only used for testing.
#[strum(props(default = "172800"))]
GossipPeriod,
/// Feature flag for verified 1:1 chats; the UI should set it
/// to 1 if it supports verified 1:1 chats.
/// Regardless of this setting, `chat.is_protected()` returns true while the key is verified,
/// and when the key changes, an info message is posted into the chat.
/// 0=Nothing else happens when the key changes.
/// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true
/// until `chat_id.accept()` is called.
#[strum(props(default = "0"))]
VerifiedOneOnOneChats,
/// Row ID of the key in the `keypairs` table
/// used for signatures, encryption to self and included in `Autocrypt` header.
KeyId,
/// This key is sent to the self_reporting bot so that the bot can recognize the user
/// without storing the email address
SelfReportingId,
/// MsgId of webxdc map integration.
WebxdcIntegration,
/// Iroh secret key.
IrohSecretKey,
}
pub struct Context {
pub(crate) inner: Arc<InnerContext>,
}
pub struct ChatId(u32); | use std::cmp;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;
use anyhow::{anyhow, bail, ensure, Context as _, Result};
use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};
use deltachat_derive::{FromSql, ToSql};
use serde::{Deserialize, Serialize};
use strum_macros::EnumIter;
use tokio::task;
use crate::aheader::EncryptPreference;
use crate::blob::BlobObject;
use crate::chatlist::Chatlist;
use crate::chatlist_events;
use crate::color::str_to_color;
use crate::config::Config;
use crate::constants::{
self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,
DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,
};
use crate::contact::{self, Contact, ContactId, Origin};
use crate::context::Context;
use crate::debug_logging::maybe_set_logging_xdc;
use crate::download::DownloadState;
use crate::ephemeral::Timer as EphemeralTimer;
use crate::events::EventType;
use crate::html::new_html_mimepart;
use crate::location;
use crate::log::LogExt;
use crate::message::{self, Message, MessageState, MsgId, Viewtype};
use crate::mimefactory::MimeFactory;
use crate::mimeparser::SystemMessage;
use crate::param::{Param, Params};
use crate::peerstate::Peerstate;
use crate::receive_imf::ReceivedMsg;
use crate::securejoin::BobState;
use crate::smtp::send_msg_to_smtp;
use crate::sql;
use crate::stock_str;
use crate::sync::{self, Sync::*, SyncData};
use crate::tools::{
buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,
create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,
smeared_time, time, IsNoneOrEmpty, SystemTime,
};
use crate::webxdc::WEBXDC_SUFFIX;
use CantSendReason::*;
use super::*;
use crate::chatlist::get_archived_cnt;
use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};
use crate::message::delete_msgs;
use crate::receive_imf::receive_imf;
use crate::test_utils::{sync, TestContext, TestContextManager};
use strum::IntoEnumIterator;
use tokio::fs; | projects__deltachat-core__rust__chat__.rs__function__30.txt |
projects/deltachat-core/c/dc_sqlite3.c | void dc_sqlite3_close(dc_sqlite3_t* sql)
{
if (sql==NULL) {
return;
}
if (sql->cobj)
{
sqlite3_close(sql->cobj);
sql->cobj = NULL;
}
} | projects/deltachat-core/rust/sql.rs | async fn close(&self) {
let _ = self.pool.write().await.take();
// drop closes the connection
} | pub struct Sql {
/// Database file path
pub(crate) dbfile: PathBuf,
/// Write transactions mutex.
///
/// See [`Self::write_lock`].
write_mtx: Mutex<()>,
/// SQL connection pool.
pool: RwLock<Option<Pool>>,
/// None if the database is not open, true if it is open with passphrase and false if it is
/// open without a passphrase.
is_encrypted: RwLock<Option<bool>>,
/// Cache of `config` table.
pub(crate) config_cache: RwLock<HashMap<String, Option<String>>>,
} | use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use anyhow::{bail, Context as _, Result};
use rusqlite::{config::DbConfig, types::ValueRef, Connection, OpenFlags, Row};
use tokio::sync::{Mutex, MutexGuard, RwLock};
use crate::blob::BlobObject;
use crate::chat::{self, add_device_msg, update_device_icon, update_saved_messages_icon};
use crate::config::Config;
use crate::constants::DC_CHAT_ID_TRASH;
use crate::context::Context;
use crate::debug_logging::set_debug_logging_xdc;
use crate::ephemeral::start_ephemeral_timers;
use crate::imex::BLOBS_BACKUP_NAME;
use crate::location::delete_orphaned_poi_locations;
use crate::log::LogExt;
use crate::message::{Message, MsgId, Viewtype};
use crate::param::{Param, Params};
use crate::peerstate::Peerstate;
use crate::stock_str;
use crate::tools::{delete_file, time, SystemTime};
use pool::Pool;
use super::*;
use crate::{test_utils::TestContext, EventType};
use tempfile::tempdir;
use tempfile::tempdir;
use tempfile::tempdir; | projects__deltachat-core__rust__sql__.rs__function__6.txt |
projects/deltachat-core/c/dc_msg.c | 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);
} | projects/deltachat-core/rust/message.rs | pub fn get_filemime(&self) -> Option<String> {
if let Some(m) = self.param.get(Param::MimeType) {
return Some(m.to_string());
} else if let Some(file) = self.param.get(Param::File) {
if let Some((_, mime)) = guess_msgtype_from_suffix(Path::new(file)) {
return Some(mime.to_string());
}
// we have a file but no mimetype, let's use a generic one
return Some("application/octet-stream".to_string());
}
// no mimetype and no file
None
} | pub fn get(&self, contact_id: ContactId) -> Reaction {
self.reactions.get(&contact_id).cloned().unwrap_or_default()
}
pub(crate) fn guess_msgtype_from_suffix(path: &Path) -> Option<(Viewtype, &str)> {
let extension: &str = &path.extension()?.to_str()?.to_lowercase();
let info = match extension {
// before using viewtype other than Viewtype::File,
// make sure, all target UIs support that type in the context of the used viewer/player.
// if in doubt, it is better to default to Viewtype::File that passes handing to an external app.
// (cmp. <https://developer.android.com/guide/topics/media/media-formats>)
"3gp" => (Viewtype::Video, "video/3gpp"),
"aac" => (Viewtype::Audio, "audio/aac"),
"avi" => (Viewtype::Video, "video/x-msvideo"),
"avif" => (Viewtype::File, "image/avif"), // supported since Android 12 / iOS 16
"doc" => (Viewtype::File, "application/msword"),
"docx" => (
Viewtype::File,
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
),
"epub" => (Viewtype::File, "application/epub+zip"),
"flac" => (Viewtype::Audio, "audio/flac"),
"gif" => (Viewtype::Gif, "image/gif"),
"heic" => (Viewtype::File, "image/heic"), // supported since Android 10 / iOS 11
"heif" => (Viewtype::File, "image/heif"), // supported since Android 10 / iOS 11
"html" => (Viewtype::File, "text/html"),
"htm" => (Viewtype::File, "text/html"),
"ico" => (Viewtype::File, "image/vnd.microsoft.icon"),
"jar" => (Viewtype::File, "application/java-archive"),
"jpeg" => (Viewtype::Image, "image/jpeg"),
"jpe" => (Viewtype::Image, "image/jpeg"),
"jpg" => (Viewtype::Image, "image/jpeg"),
"json" => (Viewtype::File, "application/json"),
"mov" => (Viewtype::Video, "video/quicktime"),
"m4a" => (Viewtype::Audio, "audio/m4a"),
"mp3" => (Viewtype::Audio, "audio/mpeg"),
"mp4" => (Viewtype::Video, "video/mp4"),
"odp" => (
Viewtype::File,
"application/vnd.oasis.opendocument.presentation",
),
"ods" => (
Viewtype::File,
"application/vnd.oasis.opendocument.spreadsheet",
),
"odt" => (Viewtype::File, "application/vnd.oasis.opendocument.text"),
"oga" => (Viewtype::Audio, "audio/ogg"),
"ogg" => (Viewtype::Audio, "audio/ogg"),
"ogv" => (Viewtype::File, "video/ogg"),
"opus" => (Viewtype::File, "audio/ogg"), // supported since Android 10
"otf" => (Viewtype::File, "font/otf"),
"pdf" => (Viewtype::File, "application/pdf"),
"png" => (Viewtype::Image, "image/png"),
"ppt" => (Viewtype::File, "application/vnd.ms-powerpoint"),
"pptx" => (
Viewtype::File,
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
),
"rar" => (Viewtype::File, "application/vnd.rar"),
"rtf" => (Viewtype::File, "application/rtf"),
"spx" => (Viewtype::File, "audio/ogg"), // Ogg Speex Profile
"svg" => (Viewtype::File, "image/svg+xml"),
"tgs" => (Viewtype::Sticker, "application/x-tgsticker"),
"tiff" => (Viewtype::File, "image/tiff"),
"tif" => (Viewtype::File, "image/tiff"),
"ttf" => (Viewtype::File, "font/ttf"),
"txt" => (Viewtype::File, "text/plain"),
"vcard" => (Viewtype::Vcard, "text/vcard"),
"vcf" => (Viewtype::Vcard, "text/vcard"),
"wav" => (Viewtype::Audio, "audio/wav"),
"weba" => (Viewtype::File, "audio/webm"),
"webm" => (Viewtype::Video, "video/webm"),
"webp" => (Viewtype::Image, "image/webp"), // iOS via SDWebImage, Android since 4.0
"wmv" => (Viewtype::Video, "video/x-ms-wmv"),
"xdc" => (Viewtype::Webxdc, "application/webxdc+zip"),
"xhtml" => (Viewtype::File, "application/xhtml+xml"),
"xls" => (Viewtype::File, "application/vnd.ms-excel"),
"xlsx" => (
Viewtype::File,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
),
"xml" => (Viewtype::File, "application/xml"),
"zip" => (Viewtype::File, "application/zip"),
_ => {
return None;
}
};
Some(info)
}
pub struct Message {
/// Message ID.
pub(crate) id: MsgId,
/// `From:` contact ID.
pub(crate) from_id: ContactId,
/// ID of the first contact in the `To:` header.
pub(crate) to_id: ContactId,
/// ID of the chat message belongs to.
pub(crate) chat_id: ChatId,
/// Type of the message.
pub(crate) viewtype: Viewtype,
/// State of the message.
pub(crate) state: MessageState,
pub(crate) download_state: DownloadState,
/// Whether the message is hidden.
pub(crate) hidden: bool,
pub(crate) timestamp_sort: i64,
pub(crate) timestamp_sent: i64,
pub(crate) timestamp_rcvd: i64,
pub(crate) ephemeral_timer: EphemeralTimer,
pub(crate) ephemeral_timestamp: i64,
pub(crate) text: String,
/// Message subject.
///
/// If empty, a default subject will be generated when sending.
pub(crate) subject: String,
/// `Message-ID` header value.
pub(crate) rfc724_mid: String,
/// `In-Reply-To` header value.
pub(crate) in_reply_to: Option<String>,
pub(crate) is_dc_message: MessengerMessage,
pub(crate) mime_modified: bool,
pub(crate) chat_blocked: Blocked,
pub(crate) location_id: u32,
pub(crate) error: Option<String>,
pub(crate) param: Params,
}
pub enum Param {
/// For messages
File = b'f',
/// For messages: original filename (as shown in chat)
Filename = b'v',
/// For messages: This name should be shown instead of contact.get_display_name()
/// (used if this is a mailinglist
/// or explicitly set using set_override_sender_name(), eg. by bots)
OverrideSenderDisplayname = b'O',
/// For Messages
Width = b'w',
/// For Messages
Height = b'h',
/// For Messages
Duration = b'd',
/// For Messages
MimeType = b'm',
/// For Messages: HTML to be written to the database and to be send.
/// `SendHtml` param is not used for received messages.
/// Use `MsgId::get_html()` to get HTML of received messages.
SendHtml = b'T',
/// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send
GuaranteeE2ee = b'c',
/// For Messages: quoted message is encrypted.
///
/// If this message is sent unencrypted, quote text should be replaced.
ProtectQuote = b'0',
/// For Messages: decrypted with validation errors or without mutual set, if neither
/// 'c' nor 'e' are preset, the messages is only transport encrypted.
ErroneousE2ee = b'e',
/// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.
ForcePlaintext = b'u',
/// For Messages: do not include Autocrypt header.
SkipAutocrypt = b'o',
/// For Messages
WantsMdn = b'r',
/// For Messages: the message is a reaction.
Reaction = b'x',
/// For Chats: the timestamp of the last reaction.
LastReactionTimestamp = b'y',
/// For Chats: Message ID of the last reaction.
LastReactionMsgId = b'Y',
/// For Chats: Contact ID of the last reaction.
LastReactionContactId = b'1',
/// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot").
Bot = b'b',
/// For Messages: unset or 0=not forwarded,
/// 1=forwarded from unknown msg_id, >9 forwarded from msg_id
Forwarded = b'a',
/// For Messages: quoted text.
Quote = b'q',
/// For Messages
Cmd = b'S',
/// For Messages
Arg = b'E',
/// For Messages
Arg2 = b'F',
/// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.
Arg3 = b'G',
/// Deprecated `Secure-Join-Group` header for messages.
Arg4 = b'H',
/// For Messages
AttachGroupImage = b'A',
/// For Messages
WebrtcRoom = b'V',
/// For Messages: space-separated list of messaged IDs of forwarded copies.
///
/// This is used when a [crate::message::Message] is in the
/// [crate::message::MessageState::OutPending] state but is already forwarded.
/// In this case the forwarded messages are written to the
/// database and their message IDs are added to this parameter of
/// the original message, which is also saved in the database.
/// When the original message is then finally sent this parameter
/// is used to also send all the forwarded messages.
PrepForwards = b'P',
/// For Messages
SetLatitude = b'l',
/// For Messages
SetLongitude = b'n',
/// For Groups
///
/// An unpromoted group has not had any messages sent to it and thus only exists on the
/// creator's device. Any changes made to an unpromoted group do not need to send
/// system messages to the group members to update them of the changes. Once a message
/// has been sent to a group it is promoted and group changes require sending system
/// messages to all members.
Unpromoted = b'U',
/// For Groups and Contacts
ProfileImage = b'i',
/// For Chats
/// Signals whether the chat is the `saved messages` chat
Selftalk = b'K',
/// For Chats: On sending a new message we set the subject to `Re: <last subject>`.
/// Usually we just use the subject of the parent message, but if the parent message
/// is deleted, we use the LastSubject of the chat.
LastSubject = b't',
/// For Chats
Devicetalk = b'D',
/// For Chats: If this is a mailing list chat, contains the List-Post address.
/// None if there simply is no `List-Post` header in the mailing list.
/// Some("") if the mailing list is using multiple different List-Post headers.
///
/// The List-Post address is the email address where the user can write to in order to
/// post something to the mailing list.
ListPost = b'p',
/// For Contacts: If this is the List-Post address of a mailing list, contains
/// the List-Id of the mailing list (which is also used as the group id of the chat).
ListId = b's',
/// For Contacts: timestamp of status (aka signature or footer) update.
StatusTimestamp = b'j',
/// For Contacts and Chats: timestamp of avatar update.
AvatarTimestamp = b'J',
/// For Chats: timestamp of status/signature/footer update.
EphemeralSettingsTimestamp = b'B',
/// For Chats: timestamp of subject update.
SubjectTimestamp = b'C',
/// For Chats: timestamp of group name update.
GroupNameTimestamp = b'g',
/// For Chats: timestamp of member list update.
MemberListTimestamp = b'k',
/// For Webxdc Message Instances: Current document name
WebxdcDocument = b'R',
/// For Webxdc Message Instances: timestamp of document name update.
WebxdcDocumentTimestamp = b'W',
/// For Webxdc Message Instances: Current summary
WebxdcSummary = b'N',
/// For Webxdc Message Instances: timestamp of summary update.
WebxdcSummaryTimestamp = b'Q',
/// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()
WebxdcIntegration = b'3',
/// For Webxdc Message Instances: Chat to integrate the Webxdc for.
WebxdcIntegrateFor = b'2',
/// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.
ForceSticker = b'X',
// 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.
} | use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use anyhow::{ensure, format_err, Context as _, Result};
use deltachat_contact_tools::{parse_vcard, VcardContact};
use deltachat_derive::{FromSql, ToSql};
use serde::{Deserialize, Serialize};
use tokio::{fs, io};
use crate::blob::BlobObject;
use crate::chat::{Chat, ChatId, ChatIdBlocked};
use crate::chatlist_events;
use crate::config::Config;
use crate::constants::{
Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,
};
use crate::contact::{Contact, ContactId};
use crate::context::Context;
use crate::debug_logging::set_debug_logging_xdc;
use crate::download::DownloadState;
use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};
use crate::events::EventType;
use crate::imap::markseen_on_imap_table;
use crate::location::delete_poi_location;
use crate::mimeparser::{parse_message_id, SystemMessage};
use crate::param::{Param, Params};
use crate::pgp::split_armored_data;
use crate::reaction::get_msg_reactions;
use crate::sql;
use crate::summary::Summary;
use crate::tools::{
buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,
timestamp_to_str, truncate,
};
use MessageState::*;
use MessageState::*;
use num_traits::FromPrimitive;
use super::*;
use crate::chat::{
self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,
};
use crate::chatlist::Chatlist;
use crate::config::Config;
use crate::reaction::send_reaction;
use crate::receive_imf::receive_imf;
use crate::test_utils as test;
use crate::test_utils::{TestContext, TestContextManager}; | projects__deltachat-core__rust__message__.rs__function__22.txt |
projects/deltachat-core/c/dc_chat.c | 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);
} | projects/deltachat-core/rust/chat.rs | pub async fn lookup_by_contact(
context: &Context,
contact_id: ContactId,
) -> Result<Option<Self>> {
ensure!(context.sql.is_open().await, "Database not available");
ensure!(
contact_id != ContactId::UNDEFINED,
"Invalid contact id requested"
);
context
.sql
.query_row_optional(
"SELECT c.id, c.blocked
FROM chats c
INNER JOIN chats_contacts j
ON c.id=j.chat_id
WHERE c.type=100 -- 100 = Chattype::Single
AND c.id>9 -- 9 = DC_CHAT_ID_LAST_SPECIAL
AND j.contact_id=?;",
(contact_id,),
|row| {
let id: ChatId = row.get(0)?;
let blocked: Blocked = row.get(1)?;
Ok(ChatIdBlocked { id, blocked })
},
)
.await
.map_err(Into::into)
} | pub async fn is_open(&self) -> bool {
self.pool.read().await.is_some()
}
pub async fn query_row_optional<T, F>(
&self,
sql: &str,
params: impl rusqlite::Params + Send,
f: F,
) -> Result<Option<T>>
where
F: Send + FnOnce(&rusqlite::Row) -> rusqlite::Result<T>,
T: Send + 'static,
{
self.call(move |conn| match conn.query_row(sql.as_ref(), params, f) {
Ok(res) => Ok(Some(res)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(rusqlite::Error::InvalidColumnType(_, _, rusqlite::types::Type::Null)) => Ok(None),
Err(err) => Err(err.into()),
})
.await
}
pub struct Context {
pub(crate) inner: Arc<InnerContext>,
}
pub struct InnerContext {
/// Blob directory path
pub(crate) blobdir: PathBuf,
pub(crate) sql: Sql,
pub(crate) smeared_timestamp: SmearedTimestamp,
/// The global "ongoing" process state.
///
/// This is a global mutex-like state for operations which should be modal in the
/// clients.
running_state: RwLock<RunningState>,
/// Mutex to avoid generating the key for the user more than once.
pub(crate) generating_key_mutex: Mutex<()>,
/// Mutex to enforce only a single running oauth2 is running.
pub(crate) oauth2_mutex: Mutex<()>,
/// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent.
pub(crate) wrong_pw_warning_mutex: Mutex<()>,
pub(crate) translated_stockstrings: StockStrings,
pub(crate) events: Events,
pub(crate) scheduler: SchedulerState,
pub(crate) ratelimit: RwLock<Ratelimit>,
/// Recently loaded quota information, if any.
/// Set to `None` if quota was never tried to load.
pub(crate) quota: RwLock<Option<QuotaInfo>>,
/// IMAP UID resync request.
pub(crate) resync_request: AtomicBool,
/// Notify about new messages.
///
/// This causes [`Context::wait_next_msgs`] to wake up.
pub(crate) new_msgs_notify: Notify,
/// Server ID response if ID capability is supported
/// and the server returned non-NIL on the inbox connection.
/// <https://datatracker.ietf.org/doc/html/rfc2971>
pub(crate) server_id: RwLock<Option<HashMap<String, String>>>,
/// IMAP METADATA.
pub(crate) metadata: RwLock<Option<ServerMetadata>>,
pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>,
/// ID for this `Context` in the current process.
///
/// This allows for multiple `Context`s open in a single process where each context can
/// be identified by this ID.
pub(crate) id: u32,
creation_time: tools::Time,
/// The text of the last error logged and emitted as an event.
/// If the ui wants to display an error after a failure,
/// `last_error` should be used to avoid races with the event thread.
pub(crate) last_error: std::sync::RwLock<String>,
/// If debug logging is enabled, this contains all necessary information
///
/// Standard RwLock instead of [`tokio::sync::RwLock`] is used
/// because the lock is used from synchronous [`Context::emit_event`].
pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>,
/// Push subscriber to store device token
/// and register for heartbeat notifications.
pub(crate) push_subscriber: PushSubscriber,
/// True if account has subscribed to push notifications via IMAP.
pub(crate) push_subscribed: AtomicBool,
/// Iroh for realtime peer channels.
pub(crate) iroh: OnceCell<Iroh>,
}
pub struct ChatId(u32);
pub(crate) struct ChatIdBlocked {
/// Chat ID.
pub id: ChatId,
/// Whether the chat is blocked, unblocked or a contact request.
pub blocked: Blocked,
}
pub struct ContactId(u32);
impl ContactId {
/// Undefined contact. Used as a placeholder for trashed messages.
pub const UNDEFINED: ContactId = ContactId::new(0);
} | use std::cmp;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;
use anyhow::{anyhow, bail, ensure, Context as _, Result};
use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};
use deltachat_derive::{FromSql, ToSql};
use serde::{Deserialize, Serialize};
use strum_macros::EnumIter;
use tokio::task;
use crate::aheader::EncryptPreference;
use crate::blob::BlobObject;
use crate::chatlist::Chatlist;
use crate::chatlist_events;
use crate::color::str_to_color;
use crate::config::Config;
use crate::constants::{
self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,
DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,
};
use crate::contact::{self, Contact, ContactId, Origin};
use crate::context::Context;
use crate::debug_logging::maybe_set_logging_xdc;
use crate::download::DownloadState;
use crate::ephemeral::Timer as EphemeralTimer;
use crate::events::EventType;
use crate::html::new_html_mimepart;
use crate::location;
use crate::log::LogExt;
use crate::message::{self, Message, MessageState, MsgId, Viewtype};
use crate::mimefactory::MimeFactory;
use crate::mimeparser::SystemMessage;
use crate::param::{Param, Params};
use crate::peerstate::Peerstate;
use crate::receive_imf::ReceivedMsg;
use crate::securejoin::BobState;
use crate::smtp::send_msg_to_smtp;
use crate::sql;
use crate::stock_str;
use crate::sync::{self, Sync::*, SyncData};
use crate::tools::{
buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,
create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,
smeared_time, time, IsNoneOrEmpty, SystemTime,
};
use crate::webxdc::WEBXDC_SUFFIX;
use CantSendReason::*;
use super::*;
use crate::chatlist::get_archived_cnt;
use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};
use crate::message::delete_msgs;
use crate::receive_imf::receive_imf;
use crate::test_utils::{sync, TestContext, TestContextManager};
use strum::IntoEnumIterator;
use tokio::fs; | projects__deltachat-core__rust__chat__.rs__function__98.txt |
projects/deltachat-core/c/dc_context.c | * 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 AS id"
"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 ?"
"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 AS 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.chat_id>9"
"AND m.hidden=0"
"AND c.blocked!=1"
"AND ct.blocked=0"
"AND m.txt LIKE ?"
"ORDER BY m.id DESC LIMIT 1000"); /* 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;
}
} | projects/deltachat-core/rust/context.rs | pub async fn search_msgs(&self, chat_id: Option<ChatId>, query: &str) -> Result<Vec<MsgId>> {
let real_query = query.trim();
if real_query.is_empty() {
return Ok(Vec::new());
}
let str_like_in_text = format!("%{real_query}%");
let list = if let Some(chat_id) = chat_id {
self.sql
.query_map(
"SELECT m.id AS id
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 ?
ORDER BY m.timestamp,m.id;",
(chat_id, str_like_in_text),
|row| row.get::<_, MsgId>("id"),
|rows| {
let mut ret = Vec::new();
for id in rows {
ret.push(id?);
}
Ok(ret)
},
)
.await?
} else {
// For performance reasons results are sorted only by `id`, that is in the order of
// message reception.
//
// Unlike chat view, sorting by `timestamp` is not necessary but slows down the query by
// ~25% according to benchmarks.
//
// To speed up incremental search, where queries for few characters usually return lots
// of unwanted results that are discarded moments later, we added `LIMIT 1000`.
// According to some tests, this limit speeds up eg. 2 character searches by factor 10.
// The limit is documented and UI may add a hint when getting 1000 results.
self.sql
.query_map(
"SELECT m.id AS 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.chat_id>9
AND m.hidden=0
AND c.blocked!=1
AND ct.blocked=0
AND m.txt LIKE ?
ORDER BY m.id DESC LIMIT 1000",
(str_like_in_text,),
|row| row.get::<_, MsgId>("id"),
|rows| {
let mut ret = Vec::new();
for id in rows {
ret.push(id?);
}
Ok(ret)
},
)
.await?
};
Ok(list)
} | pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub async fn query_map<T, F, G, H>(
&self,
sql: &str,
params: impl rusqlite::Params + Send,
f: F,
mut g: G,
) -> Result<H>
where
F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result<T>,
G: Send + FnMut(rusqlite::MappedRows<F>) -> Result<H>,
H: Send + 'static,
{
self.call(move |conn| {
let mut stmt = conn.prepare(sql)?;
let res = stmt.query_map(params, f)?;
g(res)
})
.await
}
pub struct Context {
pub(crate) inner: Arc<InnerContext>,
}
pub struct InnerContext {
/// Blob directory path
pub(crate) blobdir: PathBuf,
pub(crate) sql: Sql,
pub(crate) smeared_timestamp: SmearedTimestamp,
/// The global "ongoing" process state.
///
/// This is a global mutex-like state for operations which should be modal in the
/// clients.
running_state: RwLock<RunningState>,
/// Mutex to avoid generating the key for the user more than once.
pub(crate) generating_key_mutex: Mutex<()>,
/// Mutex to enforce only a single running oauth2 is running.
pub(crate) oauth2_mutex: Mutex<()>,
/// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent.
pub(crate) wrong_pw_warning_mutex: Mutex<()>,
pub(crate) translated_stockstrings: StockStrings,
pub(crate) events: Events,
pub(crate) scheduler: SchedulerState,
pub(crate) ratelimit: RwLock<Ratelimit>,
/// Recently loaded quota information, if any.
/// Set to `None` if quota was never tried to load.
pub(crate) quota: RwLock<Option<QuotaInfo>>,
/// IMAP UID resync request.
pub(crate) resync_request: AtomicBool,
/// Notify about new messages.
///
/// This causes [`Context::wait_next_msgs`] to wake up.
pub(crate) new_msgs_notify: Notify,
/// Server ID response if ID capability is supported
/// and the server returned non-NIL on the inbox connection.
/// <https://datatracker.ietf.org/doc/html/rfc2971>
pub(crate) server_id: RwLock<Option<HashMap<String, String>>>,
/// IMAP METADATA.
pub(crate) metadata: RwLock<Option<ServerMetadata>>,
pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>,
/// ID for this `Context` in the current process.
///
/// This allows for multiple `Context`s open in a single process where each context can
/// be identified by this ID.
pub(crate) id: u32,
creation_time: tools::Time,
/// The text of the last error logged and emitted as an event.
/// If the ui wants to display an error after a failure,
/// `last_error` should be used to avoid races with the event thread.
pub(crate) last_error: std::sync::RwLock<String>,
/// If debug logging is enabled, this contains all necessary information
///
/// Standard RwLock instead of [`tokio::sync::RwLock`] is used
/// because the lock is used from synchronous [`Context::emit_event`].
pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>,
/// Push subscriber to store device token
/// and register for heartbeat notifications.
pub(crate) push_subscriber: PushSubscriber,
/// True if account has subscribed to push notifications via IMAP.
pub(crate) push_subscribed: AtomicBool,
/// Iroh for realtime peer channels.
pub(crate) iroh: OnceCell<Iroh>,
}
pub struct MsgId(u32); | use std::collections::{BTreeMap, HashMap};
use std::ffi::OsString;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use anyhow::{bail, ensure, Context as _, Result};
use async_channel::{self as channel, Receiver, Sender};
use pgp::SignedPublicKey;
use ratelimit::Ratelimit;
use tokio::sync::{Mutex, Notify, OnceCell, RwLock};
use crate::aheader::EncryptPreference;
use crate::chat::{get_chat_cnt, ChatId, ProtectionStatus};
use crate::chatlist_events;
use crate::config::Config;
use crate::constants::{
self, DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT, DC_CHAT_ID_TRASH, DC_VERSION_STR,
};
use crate::contact::{Contact, ContactId};
use crate::debug_logging::DebugLogging;
use crate::download::DownloadState;
use crate::events::{Event, EventEmitter, EventType, Events};
use crate::imap::{FolderMeaning, Imap, ServerMetadata};
use crate::key::{load_self_public_key, load_self_secret_key, DcKey as _};
use crate::login_param::LoginParam;
use crate::message::{self, Message, MessageState, MsgId, Viewtype};
use crate::param::{Param, Params};
use crate::peer_channels::Iroh;
use crate::peerstate::Peerstate;
use crate::push::PushSubscriber;
use crate::quota::QuotaInfo;
use crate::scheduler::{convert_folder_meaning, SchedulerState};
use crate::sql::Sql;
use crate::stock_str::StockStrings;
use crate::timesmearing::SmearedTimestamp;
use crate::tools::{self, create_id, duration_to_str, time, time_elapsed};
use anyhow::Context as _;
use strum::IntoEnumIterator;
use tempfile::tempdir;
use super::*;
use crate::chat::{get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, MuteDuration};
use crate::chatlist::Chatlist;
use crate::constants::Chattype;
use crate::mimeparser::SystemMessage;
use crate::receive_imf::receive_imf;
use crate::test_utils::{get_chat_msg, TestContext};
use crate::tools::{create_outgoing_rfc724_mid, SystemTime}; | projects__deltachat-core__rust__context__.rs__function__47.txt |
projects/deltachat-core/c/dc_param.c | 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;
} | projects/deltachat-core/rust/param.rs | pub fn get_i64(&self, key: Param) -> Option<i64> {
self.get(key).and_then(|s| s.parse().ok())
} | pub fn get(&self, key: Param) -> Option<&str> {
self.inner.get(&key).map(|s| s.as_str())
}
pub struct Params {
inner: BTreeMap<Param, String>,
} | use std::collections::BTreeMap;
use std::fmt;
use std::path::PathBuf;
use std::str;
use anyhow::{bail, Error, Result};
use num_traits::FromPrimitive;
use serde::{Deserialize, Serialize};
use crate::blob::BlobObject;
use crate::context::Context;
use crate::mimeparser::SystemMessage;
use std::path::Path;
use std::str::FromStr;
use tokio::fs;
use super::*;
use crate::test_utils::TestContext; | projects__deltachat-core__rust__param__.rs__function__12.txt |
projects/deltachat-core/c/dc_apeerstate.c | * 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;
} | projects/deltachat-core/rust/peerstate.rs | pub fn peek_key(&self, verified: bool) -> Option<&SignedPublicKey> {
if verified {
self.verified_key.as_ref()
} else {
self.public_key.as_ref().or(self.gossip_key.as_ref())
}
} | pub struct Peerstate {
/// E-mail address of the contact.
pub addr: String,
/// Timestamp of the latest peerstate update.
///
/// Updated when a message is received from a contact,
/// either with or without `Autocrypt` header.
pub last_seen: i64,
/// Timestamp of the latest `Autocrypt` header reception.
pub last_seen_autocrypt: i64,
/// Encryption preference of the contact.
pub prefer_encrypt: EncryptPreference,
/// Public key of the contact received in `Autocrypt` header.
pub public_key: Option<SignedPublicKey>,
/// Fingerprint of the contact public key.
pub public_key_fingerprint: Option<Fingerprint>,
/// Public key of the contact received in `Autocrypt-Gossip` header.
pub gossip_key: Option<SignedPublicKey>,
/// Timestamp of the latest `Autocrypt-Gossip` header reception.
///
/// It is stored to avoid applying outdated gossiped key
/// from delayed or reordered messages.
pub gossip_timestamp: i64,
/// Fingerprint of the contact gossip key.
pub gossip_key_fingerprint: Option<Fingerprint>,
/// Public key of the contact at the time it was verified,
/// either directly or via gossip from the verified contact.
pub verified_key: Option<SignedPublicKey>,
/// Fingerprint of the verified public key.
pub verified_key_fingerprint: Option<Fingerprint>,
/// The address that introduced this verified key.
pub verifier: Option<String>,
/// Secondary public verified key of the contact.
/// It could be a contact gossiped by another verified contact in a shared group
/// or a key that was previously used as a verified key.
pub secondary_verified_key: Option<SignedPublicKey>,
/// Fingerprint of the secondary verified public key.
pub secondary_verified_key_fingerprint: Option<Fingerprint>,
/// The address that introduced secondary verified key.
pub secondary_verifier: Option<String>,
/// Row ID of the key in the `keypairs` table
/// that we think the peer knows as verified.
pub backward_verified_key_id: Option<i64>,
/// True if it was detected
/// that the fingerprint of the key used in chats with
/// opportunistic encryption was changed after Peerstate creation.
pub fingerprint_changed: bool,
} | use std::mem;
use anyhow::{Context as _, Error, Result};
use deltachat_contact_tools::{addr_cmp, ContactAddress};
use num_traits::FromPrimitive;
use crate::aheader::{Aheader, EncryptPreference};
use crate::chat::{self, Chat};
use crate::chatlist::Chatlist;
use crate::config::Config;
use crate::constants::Chattype;
use crate::contact::{Contact, Origin};
use crate::context::Context;
use crate::events::EventType;
use crate::key::{DcKey, Fingerprint, SignedPublicKey};
use crate::message::Message;
use crate::mimeparser::SystemMessage;
use crate::sql::Sql;
use crate::{chatlist_events, stock_str};
use super::*;
use crate::test_utils::alice_keypair; | projects__deltachat-core__rust__peerstate__.rs__function__14.txt |
projects/deltachat-core/c/dc_configure.c | 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;
} | projects/deltachat-core/rust/context.rs | pub(crate) async fn alloc_ongoing(&self) -> Result<Receiver<()>> {
let mut s = self.running_state.write().await;
ensure!(
matches!(*s, RunningState::Stopped),
"There is already another ongoing process running."
);
let (sender, receiver) = channel::bounded(1);
*s = RunningState::Running {
cancel_sender: sender,
};
Ok(receiver)
} | pub struct Context {
pub(crate) inner: Arc<InnerContext>,
}
pub struct InnerContext {
/// Blob directory path
pub(crate) blobdir: PathBuf,
pub(crate) sql: Sql,
pub(crate) smeared_timestamp: SmearedTimestamp,
/// The global "ongoing" process state.
///
/// This is a global mutex-like state for operations which should be modal in the
/// clients.
running_state: RwLock<RunningState>,
/// Mutex to avoid generating the key for the user more than once.
pub(crate) generating_key_mutex: Mutex<()>,
/// Mutex to enforce only a single running oauth2 is running.
pub(crate) oauth2_mutex: Mutex<()>,
/// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent.
pub(crate) wrong_pw_warning_mutex: Mutex<()>,
pub(crate) translated_stockstrings: StockStrings,
pub(crate) events: Events,
pub(crate) scheduler: SchedulerState,
pub(crate) ratelimit: RwLock<Ratelimit>,
/// Recently loaded quota information, if any.
/// Set to `None` if quota was never tried to load.
pub(crate) quota: RwLock<Option<QuotaInfo>>,
/// IMAP UID resync request.
pub(crate) resync_request: AtomicBool,
/// Notify about new messages.
///
/// This causes [`Context::wait_next_msgs`] to wake up.
pub(crate) new_msgs_notify: Notify,
/// Server ID response if ID capability is supported
/// and the server returned non-NIL on the inbox connection.
/// <https://datatracker.ietf.org/doc/html/rfc2971>
pub(crate) server_id: RwLock<Option<HashMap<String, String>>>,
/// IMAP METADATA.
pub(crate) metadata: RwLock<Option<ServerMetadata>>,
pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>,
/// ID for this `Context` in the current process.
///
/// This allows for multiple `Context`s open in a single process where each context can
/// be identified by this ID.
pub(crate) id: u32,
creation_time: tools::Time,
/// The text of the last error logged and emitted as an event.
/// If the ui wants to display an error after a failure,
/// `last_error` should be used to avoid races with the event thread.
pub(crate) last_error: std::sync::RwLock<String>,
/// If debug logging is enabled, this contains all necessary information
///
/// Standard RwLock instead of [`tokio::sync::RwLock`] is used
/// because the lock is used from synchronous [`Context::emit_event`].
pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>,
/// Push subscriber to store device token
/// and register for heartbeat notifications.
pub(crate) push_subscriber: PushSubscriber,
/// True if account has subscribed to push notifications via IMAP.
pub(crate) push_subscribed: AtomicBool,
/// Iroh for realtime peer channels.
pub(crate) iroh: OnceCell<Iroh>,
}
enum RunningState {
/// Ongoing process is allocated.
Running { cancel_sender: Sender<()> },
/// Cancel signal has been sent, waiting for ongoing process to be freed.
ShallStop { request: tools::Time },
/// There is no ongoing process, a new one can be allocated.
Stopped,
} | use std::collections::{BTreeMap, HashMap};
use std::ffi::OsString;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use anyhow::{bail, ensure, Context as _, Result};
use async_channel::{self as channel, Receiver, Sender};
use pgp::SignedPublicKey;
use ratelimit::Ratelimit;
use tokio::sync::{Mutex, Notify, OnceCell, RwLock};
use crate::aheader::EncryptPreference;
use crate::chat::{get_chat_cnt, ChatId, ProtectionStatus};
use crate::chatlist_events;
use crate::config::Config;
use crate::constants::{
self, DC_BACKGROUND_FETCH_QUOTA_CHECK_RATELIMIT, DC_CHAT_ID_TRASH, DC_VERSION_STR,
};
use crate::contact::{Contact, ContactId};
use crate::debug_logging::DebugLogging;
use crate::download::DownloadState;
use crate::events::{Event, EventEmitter, EventType, Events};
use crate::imap::{FolderMeaning, Imap, ServerMetadata};
use crate::key::{load_self_public_key, load_self_secret_key, DcKey as _};
use crate::login_param::LoginParam;
use crate::message::{self, Message, MessageState, MsgId, Viewtype};
use crate::param::{Param, Params};
use crate::peer_channels::Iroh;
use crate::peerstate::Peerstate;
use crate::push::PushSubscriber;
use crate::quota::QuotaInfo;
use crate::scheduler::{convert_folder_meaning, SchedulerState};
use crate::sql::Sql;
use crate::stock_str::StockStrings;
use crate::timesmearing::SmearedTimestamp;
use crate::tools::{self, create_id, duration_to_str, time, time_elapsed};
use anyhow::Context as _;
use strum::IntoEnumIterator;
use tempfile::tempdir;
use super::*;
use crate::chat::{get_chat_contacts, get_chat_msgs, send_msg, set_muted, Chat, MuteDuration};
use crate::chatlist::Chatlist;
use crate::constants::Chattype;
use crate::mimeparser::SystemMessage;
use crate::receive_imf::receive_imf;
use crate::test_utils::{get_chat_msg, TestContext};
use crate::tools::{create_outgoing_rfc724_mid, SystemTime}; | projects__deltachat-core__rust__context__.rs__function__37.txt |
projects/deltachat-core/c/dc_tools.c | 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;
} | projects/deltachat-core/rust/blob.rs | pub fn to_abs_path(&self) -> PathBuf {
let fname = Path::new(&self.name).strip_prefix("$BLOBDIR/").unwrap();
self.blobdir.join(fname)
} | pub struct BlobObject<'a> {
blobdir: &'a Path,
name: String,
} | use core::cmp::max;
use std::ffi::OsStr;
use std::fmt;
use std::io::Cursor;
use dIterator;
use std::mem;
use std::path::{Path, PathBuf};
use anyhow::{format_err, Context as _, Result};
use base64::Engine as _;
use futures::StreamExt;
use image::codecs::jpeg::JpegEncoder;
use image::{DynamicImage, GenericImage, GenericImageView, ImageFormat, Pixel, Rgba};
use num_traits::FromPrimitive;
use tokio::io::AsyncWriteExt;
use tokio::{fs, io};
use tokio_stream::wrappers::ReadDirStream;
use crate::config::Config;
use crate::constants::{self, MediaQuality};
use crate::context::Context;
use crate::events::EventType;
use crate::log::LogExt;
use fs::File;
use super::*;
use crate::chat::{self, create_group_chat, ProtectionStatus};
use crate::message::{Message, Viewtype};
use crate::test_utils::{self, TestContext}; | projects__deltachat-core__rust__blob__.rs__function__7.txt |
projects/deltachat-core/c/dc_tools.c | 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 + 1]; /* 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);
}
} | projects/deltachat-core/rust/tools.rs | pub(crate) fn truncate(buf: &str, approx_chars: usize) -> Cow<str> {
let count = buf.chars().count();
if count > approx_chars + DC_ELLIPSIS.len() {
let end_pos = buf
.char_indices()
.nth(approx_chars)
.map(|(n, _)| n)
.unwrap_or_default();
if let Some(index) = buf[..end_pos].rfind(|c| c == ' ' || c == '\n') {
Cow::Owned(format!("{}{}", &buf[..=index], DC_ELLIPSIS))
} else {
Cow::Owned(format!("{}{}", &buf[..end_pos], DC_ELLIPSIS))
}
} else {
Cow::Borrowed(buf)
}
} | pub(crate) const DC_ELLIPSIS: &str = "[...]"; | use std::borrow::Cow;
use std::io::{Cursor, Write};
use std::mem;
use std::path::{Path, PathBuf};
use std::str::from_utf8;
use std::time::Duration;
use std::time::SystemTime as Time;
use std::time::SystemTime;
use anyhow::{bail, Context as _, Result};
use base64::Engine as _;
use chrono::{Local, NaiveDateTime, NaiveTime, TimeZone};
use deltachat_contact_tools::{strip_rtlo_characters, EmailAddress};
use deltachat_time::SystemTimeTools as SystemTime;
use futures::{StreamExt, TryStreamExt};
use mailparse::dateparse;
use mailparse::headers::Headers;
use mailparse::MailHeaderMap;
use rand::{thread_rng, Rng};
use tokio::{fs, io};
use url::Url;
use crate::chat::{add_device_msg, add_device_msg_with_importance};
use crate::constants::{DC_ELLIPSIS, DC_OUTDATED_WARNING_DAYS};
use crate::context::Context;
use crate::events::EventType;
use crate::message::{Message, Viewtype};
use crate::stock_str;
use chrono::NaiveDate;
use proptest::prelude::*;
use super::*;
use crate::chatlist::Chatlist;
use crate::{chat, test_utils};
use crate::{receive_imf::receive_imf, test_utils::TestContext};
use super::*; | projects__deltachat-core__rust__tools__.rs__function__1.txt |
projects/deltachat-core/c/dc_msg.c | int dc_msg_is_starred(const dc_msg_t* msg)
{
return msg->id <= DC_MSG_ID_LAST_SPECIAL? 1 : 0;
} | projects/deltachat-core/rust/message.rs | pub fn is_special(self) -> bool {
self.0 <= DC_MSG_ID_LAST_SPECIAL
} | pub struct MsgId(u32); | use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use anyhow::{ensure, format_err, Context as _, Result};
use deltachat_contact_tools::{parse_vcard, VcardContact};
use deltachat_derive::{FromSql, ToSql};
use serde::{Deserialize, Serialize};
use tokio::{fs, io};
use crate::blob::BlobObject;
use crate::chat::{Chat, ChatId, ChatIdBlocked};
use crate::chatlist_events;
use crate::config::Config;
use crate::constants::{
Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,
};
use crate::contact::{Contact, ContactId};
use crate::context::Context;
use crate::debug_logging::set_debug_logging_xdc;
use crate::download::DownloadState;
use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};
use crate::events::EventType;
use crate::imap::markseen_on_imap_table;
use crate::location::delete_poi_location;
use crate::mimeparser::{parse_message_id, SystemMessage};
use crate::param::{Param, Params};
use crate::pgp::split_armored_data;
use crate::reaction::get_msg_reactions;
use crate::sql;
use crate::summary::Summary;
use crate::tools::{
buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,
timestamp_to_str, truncate,
};
use MessageState::*;
use MessageState::*;
use num_traits::FromPrimitive;
use super::*;
use crate::chat::{
self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,
};
use crate::chatlist::Chatlist;
use crate::config::Config;
use crate::reaction::send_reaction;
use crate::receive_imf::receive_imf;
use crate::test_utils as test;
use crate::test_utils::{TestContext, TestContextManager}; | projects__deltachat-core__rust__message__.rs__function__3.txt |
projects/deltachat-core/c/dc_msg.c | * 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);
} | projects/deltachat-core/rust/message.rs | pub fn get_width(&self) -> i32 {
self.param.get_int(Param::Width).unwrap_or_default()
} | pub fn get_int(&self, key: Param) -> Option<i32> {
self.get(key).and_then(|s| s.parse().ok())
}
pub struct Message {
/// Message ID.
pub(crate) id: MsgId,
/// `From:` contact ID.
pub(crate) from_id: ContactId,
/// ID of the first contact in the `To:` header.
pub(crate) to_id: ContactId,
/// ID of the chat message belongs to.
pub(crate) chat_id: ChatId,
/// Type of the message.
pub(crate) viewtype: Viewtype,
/// State of the message.
pub(crate) state: MessageState,
pub(crate) download_state: DownloadState,
/// Whether the message is hidden.
pub(crate) hidden: bool,
pub(crate) timestamp_sort: i64,
pub(crate) timestamp_sent: i64,
pub(crate) timestamp_rcvd: i64,
pub(crate) ephemeral_timer: EphemeralTimer,
pub(crate) ephemeral_timestamp: i64,
pub(crate) text: String,
/// Message subject.
///
/// If empty, a default subject will be generated when sending.
pub(crate) subject: String,
/// `Message-ID` header value.
pub(crate) rfc724_mid: String,
/// `In-Reply-To` header value.
pub(crate) in_reply_to: Option<String>,
pub(crate) is_dc_message: MessengerMessage,
pub(crate) mime_modified: bool,
pub(crate) chat_blocked: Blocked,
pub(crate) location_id: u32,
pub(crate) error: Option<String>,
pub(crate) param: Params,
}
pub enum Param {
/// For messages
File = b'f',
/// For messages: original filename (as shown in chat)
Filename = b'v',
/// For messages: This name should be shown instead of contact.get_display_name()
/// (used if this is a mailinglist
/// or explicitly set using set_override_sender_name(), eg. by bots)
OverrideSenderDisplayname = b'O',
/// For Messages
Width = b'w',
/// For Messages
Height = b'h',
/// For Messages
Duration = b'd',
/// For Messages
MimeType = b'm',
/// For Messages: HTML to be written to the database and to be send.
/// `SendHtml` param is not used for received messages.
/// Use `MsgId::get_html()` to get HTML of received messages.
SendHtml = b'T',
/// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send
GuaranteeE2ee = b'c',
/// For Messages: quoted message is encrypted.
///
/// If this message is sent unencrypted, quote text should be replaced.
ProtectQuote = b'0',
/// For Messages: decrypted with validation errors or without mutual set, if neither
/// 'c' nor 'e' are preset, the messages is only transport encrypted.
ErroneousE2ee = b'e',
/// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.
ForcePlaintext = b'u',
/// For Messages: do not include Autocrypt header.
SkipAutocrypt = b'o',
/// For Messages
WantsMdn = b'r',
/// For Messages: the message is a reaction.
Reaction = b'x',
/// For Chats: the timestamp of the last reaction.
LastReactionTimestamp = b'y',
/// For Chats: Message ID of the last reaction.
LastReactionMsgId = b'Y',
/// For Chats: Contact ID of the last reaction.
LastReactionContactId = b'1',
/// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot").
Bot = b'b',
/// For Messages: unset or 0=not forwarded,
/// 1=forwarded from unknown msg_id, >9 forwarded from msg_id
Forwarded = b'a',
/// For Messages: quoted text.
Quote = b'q',
/// For Messages
Cmd = b'S',
/// For Messages
Arg = b'E',
/// For Messages
Arg2 = b'F',
/// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.
Arg3 = b'G',
/// Deprecated `Secure-Join-Group` header for messages.
Arg4 = b'H',
/// For Messages
AttachGroupImage = b'A',
/// For Messages
WebrtcRoom = b'V',
/// For Messages: space-separated list of messaged IDs of forwarded copies.
///
/// This is used when a [crate::message::Message] is in the
/// [crate::message::MessageState::OutPending] state but is already forwarded.
/// In this case the forwarded messages are written to the
/// database and their message IDs are added to this parameter of
/// the original message, which is also saved in the database.
/// When the original message is then finally sent this parameter
/// is used to also send all the forwarded messages.
PrepForwards = b'P',
/// For Messages
SetLatitude = b'l',
/// For Messages
SetLongitude = b'n',
/// For Groups
///
/// An unpromoted group has not had any messages sent to it and thus only exists on the
/// creator's device. Any changes made to an unpromoted group do not need to send
/// system messages to the group members to update them of the changes. Once a message
/// has been sent to a group it is promoted and group changes require sending system
/// messages to all members.
Unpromoted = b'U',
/// For Groups and Contacts
ProfileImage = b'i',
/// For Chats
/// Signals whether the chat is the `saved messages` chat
Selftalk = b'K',
/// For Chats: On sending a new message we set the subject to `Re: <last subject>`.
/// Usually we just use the subject of the parent message, but if the parent message
/// is deleted, we use the LastSubject of the chat.
LastSubject = b't',
/// For Chats
Devicetalk = b'D',
/// For Chats: If this is a mailing list chat, contains the List-Post address.
/// None if there simply is no `List-Post` header in the mailing list.
/// Some("") if the mailing list is using multiple different List-Post headers.
///
/// The List-Post address is the email address where the user can write to in order to
/// post something to the mailing list.
ListPost = b'p',
/// For Contacts: If this is the List-Post address of a mailing list, contains
/// the List-Id of the mailing list (which is also used as the group id of the chat).
ListId = b's',
/// For Contacts: timestamp of status (aka signature or footer) update.
StatusTimestamp = b'j',
/// For Contacts and Chats: timestamp of avatar update.
AvatarTimestamp = b'J',
/// For Chats: timestamp of status/signature/footer update.
EphemeralSettingsTimestamp = b'B',
/// For Chats: timestamp of subject update.
SubjectTimestamp = b'C',
/// For Chats: timestamp of group name update.
GroupNameTimestamp = b'g',
/// For Chats: timestamp of member list update.
MemberListTimestamp = b'k',
/// For Webxdc Message Instances: Current document name
WebxdcDocument = b'R',
/// For Webxdc Message Instances: timestamp of document name update.
WebxdcDocumentTimestamp = b'W',
/// For Webxdc Message Instances: Current summary
WebxdcSummary = b'N',
/// For Webxdc Message Instances: timestamp of summary update.
WebxdcSummaryTimestamp = b'Q',
/// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()
WebxdcIntegration = b'3',
/// For Webxdc Message Instances: Chat to integrate the Webxdc for.
WebxdcIntegrateFor = b'2',
/// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.
ForceSticker = b'X',
// 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.
} | use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use anyhow::{ensure, format_err, Context as _, Result};
use deltachat_contact_tools::{parse_vcard, VcardContact};
use deltachat_derive::{FromSql, ToSql};
use serde::{Deserialize, Serialize};
use tokio::{fs, io};
use crate::blob::BlobObject;
use crate::chat::{Chat, ChatId, ChatIdBlocked};
use crate::chatlist_events;
use crate::config::Config;
use crate::constants::{
Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,
};
use crate::contact::{Contact, ContactId};
use crate::context::Context;
use crate::debug_logging::set_debug_logging_xdc;
use crate::download::DownloadState;
use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};
use crate::events::EventType;
use crate::imap::markseen_on_imap_table;
use crate::location::delete_poi_location;
use crate::mimeparser::{parse_message_id, SystemMessage};
use crate::param::{Param, Params};
use crate::pgp::split_armored_data;
use crate::reaction::get_msg_reactions;
use crate::sql;
use crate::summary::Summary;
use crate::tools::{
buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,
timestamp_to_str, truncate,
};
use MessageState::*;
use MessageState::*;
use num_traits::FromPrimitive;
use super::*;
use crate::chat::{
self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,
};
use crate::chatlist::Chatlist;
use crate::config::Config;
use crate::reaction::send_reaction;
use crate::receive_imf::receive_imf;
use crate::test_utils as test;
use crate::test_utils::{TestContext, TestContextManager}; | projects__deltachat-core__rust__message__.rs__function__43.txt |
projects/deltachat-core/c/dc_contact.c | * Same as dc_contact_is_verified() but allows speeding up things
* by adding the peerstate belonging to the contact.
* If you do not have the peerstate available, it is loaded automatically.
*
* @private @memberof dc_context_t
*/
int dc_contact_is_verified_ex(dc_contact_t* contact, const dc_apeerstate_t* peerstate)
{
int contact_verified = DC_NOT_VERIFIED;
dc_apeerstate_t* peerstate_to_delete = NULL;
if (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) {
goto cleanup;
}
if (contact->id==DC_CONTACT_ID_SELF) {
contact_verified = DC_BIDIRECT_VERIFIED;
goto cleanup; // we're always sort of secured-verified as we could verify the key on this device any time with the key on this device
}
if (peerstate==NULL) {
peerstate_to_delete = dc_apeerstate_new(contact->context);
if (!dc_apeerstate_load_by_addr(peerstate_to_delete, contact->context->sql, contact->addr)) {
goto cleanup;
}
peerstate = peerstate_to_delete;
}
contact_verified = peerstate->verified_key? DC_BIDIRECT_VERIFIED : 0;
cleanup:
dc_apeerstate_unref(peerstate_to_delete);
return contact_verified;
} | projects/deltachat-core/rust/contact.rs | pub async fn is_verified(&self, context: &Context) -> Result<bool> {
// We're always sort of secured-verified as we could verify the key on this device any time with the key
// on this device
if self.id == ContactId::SELF {
return Ok(true);
}
let Some(peerstate) = Peerstate::from_addr(context, &self.addr).await? else {
return Ok(false);
};
let forward_verified = peerstate.is_using_verified_key();
let backward_verified = peerstate.is_backward_verified(context).await?;
Ok(forward_verified && backward_verified)
} | pub(crate) async fn is_backward_verified(&self, context: &Context) -> Result<bool> {
let Some(backward_verified_key_id) = self.backward_verified_key_id else {
return Ok(false);
};
let self_key_id = context.get_config_i64(Config::KeyId).await?;
let backward_verified = backward_verified_key_id == self_key_id;
Ok(backward_verified)
}
pub(crate) fn is_using_verified_key(&self) -> bool {
let verified = self.peek_key_fingerprint(true);
verified.is_some() && verified == self.peek_key_fingerprint(false)
}
pub struct Context {
pub(crate) inner: Arc<InnerContext>,
}
pub async fn from_addr(context: &Context, addr: &str) -> Result<Option<Peerstate>> {
if context.is_self_addr(addr).await? {
return Ok(None);
}
let query = "SELECT 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, \
verifier, \
secondary_verified_key, secondary_verified_key_fingerprint, \
secondary_verifier, \
backward_verified_key_id \
FROM acpeerstates \
WHERE addr=? COLLATE NOCASE LIMIT 1;";
Self::from_stmt(context, query, (addr,)).await
}
pub struct Contact {
/// The contact ID.
pub id: ContactId,
/// Contact name. It is recommended to use `Contact::get_name`,
/// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.
/// May be empty, initially set to `authname`.
name: String,
/// Name authorized by the contact himself. Only this name may be spread to others,
/// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,
/// to access this field.
authname: String,
/// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.
addr: String,
/// Blocked state. Use contact_is_blocked to access this field.
pub blocked: bool,
/// Time when the contact was seen last time, Unix time in seconds.
last_seen: i64,
/// The origin/source of the contact.
pub origin: Origin,
/// Parameters as Param::ProfileImage
pub param: Params,
/// Last seen message signature for this contact, to be displayed in the profile.
status: String,
/// If the contact is a bot.
is_bot: bool,
}
pub struct ContactId(u32);
impl ContactId {
/// Undefined contact. Used as a placeholder for trashed messages.
pub const UNDEFINED: ContactId = ContactId::new(0);
/// The owner of the account.
///
/// The email-address is set by `set_config` using "addr".
pub const SELF: ContactId = ContactId::new(1);
/// ID of the contact for info messages.
pub const INFO: ContactId = ContactId::new(2);
/// ID of the contact for device messages.
pub const DEVICE: ContactId = ContactId::new(5);
pub(crate) const LAST_SPECIAL: ContactId = ContactId::new(9);
/// Address to go with [`ContactId::DEVICE`].
///
/// This is used by APIs which need to return an email address for this contact.
pub const DEVICE_ADDR: &'static str = "device@localhost";
} | use std::cmp::{min, Reverse};
use std::collections::BinaryHeap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;
use anyhow::{bail, ensure, Context as _, Result};
use async_channel::{self as channel, Receiver, Sender};
use base64::Engine as _;
use deltachat_contact_tools::may_be_valid_addr;
use deltachat_contact_tools::{
self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,
ContactAddress, VcardContact,
};
use deltachat_derive::{FromSql, ToSql};
use rusqlite::OptionalExtension;
use serde::{Deserialize, Serialize};
use tokio::task;
use tokio::time::{timeout, Duration};
use crate::aheader::{Aheader, EncryptPreference};
use crate::blob::BlobObject;
use crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};
use crate::color::str_to_color;
use crate::config::Config;
use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};
use crate::context::Context;
use crate::events::EventType;
use crate::key::{load_self_public_key, DcKey, SignedPublicKey};
use crate::log::LogExt;
use crate::login_param::LoginParam;
use crate::message::MessageState;
use crate::mimeparser::AvatarAction;
use crate::param::{Param, Params};
use crate::peerstate::Peerstate;
use crate::sql::{self, params_iter};
use crate::sync::{self, Sync::*};
use crate::tools::{
duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,
};
use crate::{chat, chatlist_events, stock_str};
use deltachat_contact_tools::{may_be_valid_addr, normalize_name};
use super::*;
use crate::chat::{get_chat_contacts, send_text_msg, Chat};
use crate::chatlist::Chatlist;
use crate::receive_imf::receive_imf;
use crate::test_utils::{self, TestContext, TestContextManager}; | projects__deltachat-core__rust__contact__.rs__function__46.txt |
projects/deltachat-core/c/dc_apeerstate.c | void dc_apeerstate_degrade_encryption(dc_apeerstate_t* peerstate, time_t message_time)
{
if (peerstate==NULL) {
return 0;
}
peerstate->prefer_encrypt = DC_PE_RESET;
peerstate->last_seen = message_time; /*last_seen_autocrypt is not updated as there was not Autocrypt:-header seen*/
} | projects/deltachat-core/rust/peerstate.rs | pub fn degrade_encryption(&mut self, message_time: i64) {
self.prefer_encrypt = EncryptPreference::Reset;
self.last_seen = message_time;
} | pub struct Peerstate {
/// E-mail address of the contact.
pub addr: String,
/// Timestamp of the latest peerstate update.
///
/// Updated when a message is received from a contact,
/// either with or without `Autocrypt` header.
pub last_seen: i64,
/// Timestamp of the latest `Autocrypt` header reception.
pub last_seen_autocrypt: i64,
/// Encryption preference of the contact.
pub prefer_encrypt: EncryptPreference,
/// Public key of the contact received in `Autocrypt` header.
pub public_key: Option<SignedPublicKey>,
/// Fingerprint of the contact public key.
pub public_key_fingerprint: Option<Fingerprint>,
/// Public key of the contact received in `Autocrypt-Gossip` header.
pub gossip_key: Option<SignedPublicKey>,
/// Timestamp of the latest `Autocrypt-Gossip` header reception.
///
/// It is stored to avoid applying outdated gossiped key
/// from delayed or reordered messages.
pub gossip_timestamp: i64,
/// Fingerprint of the contact gossip key.
pub gossip_key_fingerprint: Option<Fingerprint>,
/// Public key of the contact at the time it was verified,
/// either directly or via gossip from the verified contact.
pub verified_key: Option<SignedPublicKey>,
/// Fingerprint of the verified public key.
pub verified_key_fingerprint: Option<Fingerprint>,
/// The address that introduced this verified key.
pub verifier: Option<String>,
/// Secondary public verified key of the contact.
/// It could be a contact gossiped by another verified contact in a shared group
/// or a key that was previously used as a verified key.
pub secondary_verified_key: Option<SignedPublicKey>,
/// Fingerprint of the secondary verified public key.
pub secondary_verified_key_fingerprint: Option<Fingerprint>,
/// The address that introduced secondary verified key.
pub secondary_verifier: Option<String>,
/// Row ID of the key in the `keypairs` table
/// that we think the peer knows as verified.
pub backward_verified_key_id: Option<i64>,
/// True if it was detected
/// that the fingerprint of the key used in chats with
/// opportunistic encryption was changed after Peerstate creation.
pub fingerprint_changed: bool,
}
pub enum EncryptPreference {
#[default]
NoPreference = 0,
Mutual = 1,
Reset = 20,
} | use std::mem;
use anyhow::{Context as _, Error, Result};
use deltachat_contact_tools::{addr_cmp, ContactAddress};
use num_traits::FromPrimitive;
use crate::aheader::{Aheader, EncryptPreference};
use crate::chat::{self, Chat};
use crate::chatlist::Chatlist;
use crate::config::Config;
use crate::constants::Chattype;
use crate::contact::{Contact, Origin};
use crate::context::Context;
use crate::events::EventType;
use crate::key::{DcKey, Fingerprint, SignedPublicKey};
use crate::message::Message;
use crate::mimeparser::SystemMessage;
use crate::sql::Sql;
use crate::{chatlist_events, stock_str};
use super::*;
use crate::test_utils::alice_keypair; | projects__deltachat-core__rust__peerstate__.rs__function__9.txt |
projects/deltachat-core/c/dc_imex.c | 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);
} | projects/deltachat-core/rust/imex.rs | pub async fn imex(
context: &Context,
what: ImexMode,
path: &Path,
passphrase: Option<String>,
) -> Result<()> {
let cancel = context.alloc_ongoing().await?;
let res = {
let _guard = context.scheduler.pause(context.clone()).await?;
imex_inner(context, what, path, passphrase)
.race(async {
cancel.recv().await.ok();
Err(format_err!("canceled"))
})
.await
};
context.free_ongoing().await;
if let Err(err) = res.as_ref() {
// We are using Anyhow's .context() and to show the inner error, too, we need the {:#}:
error!(context, "IMEX failed to complete: {:#}", err);
context.emit_event(EventType::ImexProgress(0));
} else {
info!(context, "IMEX successfully completed");
context.emit_event(EventType::ImexProgress(1000));
}
res
} | pub(crate) async fn free_ongoing(&self) {
let mut s = self.running_state.write().await;
if let RunningState::ShallStop { request } = *s {
info!(self, "Ongoing stopped in {:?}", time_elapsed(&request));
}
*s = RunningState::Stopped;
}
async fn imex_inner(
context: &Context,
what: ImexMode,
path: &Path,
passphrase: Option<String>,
) -> Result<()> {
info!(
context,
"{} path: {}",
match what {
ImexMode::ExportSelfKeys | ImexMode::ExportBackup => "Export",
ImexMode::ImportSelfKeys | ImexMode::ImportBackup => "Import",
},
path.display()
);
ensure!(context.sql.is_open().await, "Database not opened.");
context.emit_event(EventType::ImexProgress(10));
if what == ImexMode::ExportBackup || what == ImexMode::ExportSelfKeys {
// before we export anything, make sure the private key exists
e2ee::ensure_secret_key_exists(context)
.await
.context("Cannot create private key or private key not available")?;
create_folder(context, &path).await?;
}
match what {
ImexMode::ExportSelfKeys => export_self_keys(context, path).await,
ImexMode::ImportSelfKeys => import_self_keys(context, path).await,
ImexMode::ExportBackup => {
export_backup(context, path, passphrase.unwrap_or_default()).await
}
ImexMode::ImportBackup => {
import_backup(context, path, passphrase.unwrap_or_default()).await
}
}
}
pub(crate) async fn alloc_ongoing(&self) -> Result<Receiver<()>> {
let mut s = self.running_state.write().await;
ensure!(
matches!(*s, RunningState::Stopped),
"There is already another ongoing process running."
);
let (sender, receiver) = channel::bounded(1);
*s = RunningState::Running {
cancel_sender: sender,
};
Ok(receiver)
}
pub async fn recv(&self) -> Option<Event> {
let mut lock = self.0.lock().await;
match lock.recv().await {
Err(async_broadcast::RecvError::Overflowed(n)) => Some(Event {
id: 0,
typ: EventType::EventChannelOverflow { n },
}),
Err(async_broadcast::RecvError::Closed) => None,
Ok(event) => Some(event),
}
}
macro_rules! error {
($ctx:expr, $msg:expr) => {
error!($ctx, $msg,)
};
($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{
let formatted = format!($msg, $($args),*);
$ctx.set_last_error(&formatted);
$ctx.emit_event($crate::EventType::Error(formatted));
}};
}
macro_rules! anyhow {
($msg:literal $(,)?) => {
$crate::__private::must_use({
let error = $crate::__private::format_err($crate::__private::format_args!($msg));
error
})
};
($err:expr $(,)?) => {
$crate::__private::must_use({
use $crate::__private::kind::*;
let error = match $err {
error => (&error).anyhow_kind().new(error),
};
error
})
};
($fmt:expr, $($arg:tt)*) => {
$crate::Error::msg($crate::__private::format!($fmt, $($arg)*))
};
}
macro_rules! info {
($ctx:expr, $msg:expr) => {
info!($ctx, $msg,)
};
($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{
let formatted = format!($msg, $($args),*);
let full = format!("{file}:{line}: {msg}",
file = file!(),
line = line!(),
msg = &formatted);
$ctx.emit_event($crate::EventType::Info(full));
}};
}
pub fn emit_event(&self, event: EventType) {
{
let lock = self.debug_logging.read().expect("RwLock is poisoned");
if let Some(debug_logging) = &*lock {
debug_logging.log_event(event.clone());
}
}
self.events.emit(Event {
id: self.id,
typ: event,
});
}
pub struct Context {
pub(crate) inner: Arc<InnerContext>,
}
pub enum EventType {
/// The library-user may write an informational string to the log.
///
/// This event should *not* be reported to the end-user using a popup or something like
/// that.
Info(String),
/// Emitted when SMTP connection is established and login was successful.
SmtpConnected(String),
/// Emitted when IMAP connection is established and login was successful.
ImapConnected(String),
/// Emitted when a message was successfully sent to the SMTP server.
SmtpMessageSent(String),
/// Emitted when an IMAP message has been marked as deleted
ImapMessageDeleted(String),
/// Emitted when an IMAP message has been moved
ImapMessageMoved(String),
/// Emitted before going into IDLE on the Inbox folder.
ImapInboxIdle,
/// Emitted when an new file in the $BLOBDIR was created
NewBlobFile(String),
/// Emitted when an file in the $BLOBDIR was deleted
DeletedBlobFile(String),
/// The library-user should write a warning string to the log.
///
/// This event should *not* be reported to the end-user using a popup or something like
/// that.
Warning(String),
/// The library-user should report an error to the end-user.
///
/// As most things are asynchronous, things may go wrong at any time and the user
/// should not be disturbed by a dialog or so. Instead, use a bubble or so.
///
/// However, for ongoing processes (eg. configure())
/// or for functions that are expected to fail (eg. dc_continue_key_transfer())
/// it might be better to delay showing these events until the function has really
/// failed (returned false). It should be sufficient to report only the *last* error
/// in a messasge box then.
Error(String),
/// An action cannot be performed because the user is not in the group.
/// Reported eg. after a call to
/// dc_set_chat_name(), dc_set_chat_profile_image(),
/// dc_add_contact_to_chat(), dc_remove_contact_from_chat(),
/// dc_send_text_msg() or another sending function.
ErrorSelfNotInGroup(String),
/// Messages or chats changed. One or more messages or chats changed for various
/// reasons in the database:
/// - Messages sent, received or removed
/// - Chats created, deleted or archived
/// - A draft has been set
///
MsgsChanged {
/// Set if only a single chat is affected by the changes, otherwise 0.
chat_id: ChatId,
/// Set if only a single message is affected by the changes, otherwise 0.
msg_id: MsgId,
},
/// Reactions for the message changed.
ReactionsChanged {
/// ID of the chat which the message belongs to.
chat_id: ChatId,
/// ID of the message for which reactions were changed.
msg_id: MsgId,
/// ID of the contact whose reaction set is changed.
contact_id: ContactId,
},
/// There is a fresh message. Typically, the user will show an notification
/// when receiving this message.
///
/// There is no extra #DC_EVENT_MSGS_CHANGED event send together with this event.
IncomingMsg {
/// ID of the chat where the message is assigned.
chat_id: ChatId,
/// ID of the message.
msg_id: MsgId,
},
/// Downloading a bunch of messages just finished.
IncomingMsgBunch,
/// Messages were seen or noticed.
/// chat id is always set.
MsgsNoticed(ChatId),
/// A single message is sent successfully. State changed from DC_STATE_OUT_PENDING to
/// DC_STATE_OUT_DELIVERED, see dc_msg_get_state().
MsgDelivered {
/// ID of the chat which the message belongs to.
chat_id: ChatId,
/// ID of the message that was successfully sent.
msg_id: MsgId,
},
/// A single message could not be sent. State changed from DC_STATE_OUT_PENDING or DC_STATE_OUT_DELIVERED to
/// DC_STATE_OUT_FAILED, see dc_msg_get_state().
MsgFailed {
/// ID of the chat which the message belongs to.
chat_id: ChatId,
/// ID of the message that could not be sent.
msg_id: MsgId,
},
/// A single message is read by the receiver. State changed from DC_STATE_OUT_DELIVERED to
/// DC_STATE_OUT_MDN_RCVD, see dc_msg_get_state().
MsgRead {
/// ID of the chat which the message belongs to.
chat_id: ChatId,
/// ID of the message that was read.
msg_id: MsgId,
},
/// A single message was deleted.
///
/// This event means that the message will no longer appear in the messagelist.
/// UI should remove the message from the messagelist
/// in response to this event if the message is currently displayed.
///
/// The message may have been explicitly deleted by the user or expired.
/// Internally the message may have been removed from the database,
/// moved to the trash chat or hidden.
///
/// This event does not indicate the message
/// deletion from the server.
MsgDeleted {
/// ID of the chat where the message was prior to deletion.
/// Never 0 or trash chat.
chat_id: ChatId,
/// ID of the deleted message. Never 0.
msg_id: MsgId,
},
/// Chat changed. The name or the image of a chat group was changed or members were added or removed.
/// Or the verify state of a chat has changed.
/// See dc_set_chat_name(), dc_set_chat_profile_image(), dc_add_contact_to_chat()
/// and dc_remove_contact_from_chat().
///
/// This event does not include ephemeral timer modification, which
/// is a separate event.
ChatModified(ChatId),
/// Chat ephemeral timer changed.
ChatEphemeralTimerModified {
/// Chat ID.
chat_id: ChatId,
/// New ephemeral timer value.
timer: EphemeralTimer,
},
/// Contact(s) created, renamed, blocked, deleted or changed their "recently seen" status.
///
/// @param data1 (int) If set, this is the contact_id of an added contact that should be selected.
ContactsChanged(Option<ContactId>),
/// Location of one or more contact has changed.
///
/// @param data1 (u32) contact_id of the contact for which the location has changed.
/// If the locations of several contacts have been changed,
/// eg. after calling dc_delete_all_locations(), this parameter is set to `None`.
LocationChanged(Option<ContactId>),
/// Inform about the configuration progress started by configure().
ConfigureProgress {
/// Progress.
///
/// 0=error, 1-999=progress in permille, 1000=success and done
progress: usize,
/// Progress comment or error, something to display to the user.
comment: Option<String>,
},
/// Inform about the import/export progress started by imex().
///
/// @param data1 (usize) 0=error, 1-999=progress in permille, 1000=success and done
/// @param data2 0
ImexProgress(usize),
/// A file has been exported. A file has been written by imex().
/// This event may be sent multiple times by a single call to imex().
///
/// A typical purpose for a handler of this event may be to make the file public to some system
/// services.
///
/// @param data2 0
ImexFileWritten(PathBuf),
/// Progress information of a secure-join handshake from the view of the inviter
/// (Alice, the person who shows the QR code).
///
/// These events are typically sent after a joiner has scanned the QR code
/// generated by dc_get_securejoin_qr().
SecurejoinInviterProgress {
/// ID of the contact that wants to join.
contact_id: ContactId,
/// Progress as:
/// 300=vg-/vc-request received, typically shown as "bob@addr joins".
/// 600=vg-/vc-request-with-auth received, vg-member-added/vc-contact-confirm sent, typically shown as "bob@addr verified".
/// 800=contact added to chat, shown as "bob@addr securely joined GROUP". Only for the verified-group-protocol.
/// 1000=Protocol finished for this contact.
progress: usize,
},
/// Progress information of a secure-join handshake from the view of the joiner
/// (Bob, the person who scans the QR code).
/// The events are typically sent while dc_join_securejoin(), which
/// may take some time, is executed.
SecurejoinJoinerProgress {
/// ID of the inviting contact.
contact_id: ContactId,
/// Progress as:
/// 400=vg-/vc-request-with-auth sent, typically shown as "alice@addr verified, introducing myself."
/// (Bob has verified alice and waits until Alice does the same for him)
/// 1000=vg-member-added/vc-contact-confirm received
progress: usize,
},
/// The connectivity to the server changed.
/// This means that you should refresh the connectivity view
/// and possibly the connectivtiy HTML; see dc_get_connectivity() and
/// dc_get_connectivity_html() for details.
ConnectivityChanged,
/// The user's avatar changed.
/// Deprecated by `ConfigSynced`.
SelfavatarChanged,
/// A multi-device synced config value changed. Maybe the app needs to refresh smth. For
/// uniformity this is emitted on the source device too. The value isn't here, otherwise it
/// would be logged which might not be good for privacy.
ConfigSynced {
/// Configuration key.
key: Config,
},
/// Webxdc status update received.
WebxdcStatusUpdate {
/// Message ID.
msg_id: MsgId,
/// Status update ID.
status_update_serial: StatusUpdateSerial,
},
/// Data received over an ephemeral peer channel.
WebxdcRealtimeData {
/// Message ID.
msg_id: MsgId,
/// Realtime data.
data: Vec<u8>,
},
/// Inform that a message containing a webxdc instance has been deleted.
WebxdcInstanceDeleted {
/// ID of the deleted message.
msg_id: MsgId,
},
/// Tells that the Background fetch was completed (or timed out).
/// This event acts as a marker, when you reach this event you can be sure
/// that all events emitted during the background fetch were processed.
///
/// This event is only emitted by the account manager
AccountsBackgroundFetchDone,
/// Inform that set of chats or the order of the chats in the chatlist has changed.
///
/// Sometimes this is emitted together with `UIChatlistItemChanged`.
ChatlistChanged,
/// Inform that a single chat list item changed and needs to be rerendered.
/// If `chat_id` is set to None, then all currently visible chats need to be rerendered, and all not-visible items need to be cleared from cache if the UI has a cache.
ChatlistItemChanged {
/// ID of the changed chat
chat_id: Option<ChatId>,
},
/// Event for using in tests, e.g. as a fence between normally generated events.
#[cfg(test)]
Test,
/// Inform than some events have been skipped due to event channel overflow.
EventChannelOverflow {
/// Number of events skipped.
n: u64,
},
} | use std::any::Any;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use ::pgp::types::KeyTrait;
use anyhow::{bail, ensure, format_err, Context as _, Result};
use deltachat_contact_tools::EmailAddress;
use futures::StreamExt;
use futures_lite::FutureExt;
use rand::{thread_rng, Rng};
use tokio::fs::{self, File};
use tokio_tar::Archive;
use crate::blob::{BlobDirContents, BlobObject};
use crate::chat::{self, delete_and_reset_all_device_msgs, ChatId};
use crate::config::Config;
use crate::contact::ContactId;
use crate::context::Context;
use crate::e2ee;
use crate::events::EventType;
use crate::key::{
self, load_self_secret_key, DcKey, DcSecretKey, SignedPublicKey, SignedSecretKey,
};
use crate::log::LogExt;
use crate::message::{Message, MsgId, Viewtype};
use crate::mimeparser::SystemMessage;
use crate::param::Param;
use crate::pgp;
use crate::sql;
use crate::stock_str;
use crate::tools::{
create_folder, delete_file, get_filesuffix_lc, open_file_std, read_file, time, write_file,
};
use transfer::{get_backup, BackupProvider};
use std::time::Duration;
use ::pgp::armor::BlockType;
use tokio::task;
use super::*;
use crate::pgp::{split_armored_data, HEADER_AUTOCRYPT, HEADER_SETUPCODE};
use crate::receive_imf::receive_imf;
use crate::stock_str::StockMessage;
use crate::test_utils::{alice_keypair, TestContext, TestContextManager}; | projects__deltachat-core__rust__imex__.rs__function__1.txt |
projects/deltachat-core/c/dc_securejoin.c | 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);
} | projects/deltachat-core/rust/securejoin.rs | pub async fn get_securejoin_qr(context: &Context, group: Option<ChatId>) -> Result<String> {
/*=======================================================
==== Alice - the inviter side ====
==== Step 1 in "Setup verified contact" protocol ====
=======================================================*/
ensure_secret_key_exists(context).await.ok();
// invitenumber will be used to allow starting the handshake,
// auth will be used to verify the fingerprint
let sync_token = token::lookup(context, Namespace::InviteNumber, group)
.await?
.is_none();
let invitenumber = token::lookup_or_new(context, Namespace::InviteNumber, group).await?;
let auth = token::lookup_or_new(context, Namespace::Auth, group).await?;
let self_addr = context.get_primary_self_addr().await?;
let self_name = context
.get_config(Config::Displayname)
.await?
.unwrap_or_default();
let fingerprint: Fingerprint = match get_self_fingerprint(context).await {
Some(fp) => fp,
None => {
bail!("No fingerprint, cannot generate QR code.");
}
};
let self_addr_urlencoded =
utf8_percent_encode(&self_addr, NON_ALPHANUMERIC_WITHOUT_DOT).to_string();
let self_name_urlencoded =
utf8_percent_encode(&self_name, NON_ALPHANUMERIC_WITHOUT_DOT).to_string();
let qr = if let Some(group) = group {
// parameters used: a=g=x=i=s=
let chat = Chat::load_from_db(context, group).await?;
if chat.grpid.is_empty() {
bail!(
"can't generate securejoin QR code for ad-hoc group {}",
group
);
}
let group_name = chat.get_name();
let group_name_urlencoded = utf8_percent_encode(group_name, NON_ALPHANUMERIC).to_string();
if sync_token {
context.sync_qr_code_tokens(Some(chat.id)).await?;
}
format!(
"OPENPGP4FPR:{}#a={}&g={}&x={}&i={}&s={}",
fingerprint.hex(),
self_addr_urlencoded,
&group_name_urlencoded,
&chat.grpid,
&invitenumber,
&auth,
)
} else {
// parameters used: a=n=i=s=
if sync_token {
context.sync_qr_code_tokens(None).await?;
}
format!(
"OPENPGP4FPR:{}#a={}&n={}&i={}&s={}",
fingerprint.hex(),
self_addr_urlencoded,
self_name_urlencoded,
&invitenumber,
&auth,
)
};
info!(context, "Generated QR code.");
Ok(qr)
} | pub async fn ensure_secret_key_exists(context: &Context) -> Result<()> {
load_self_public_key(context).await?;
Ok(())
}
pub async fn lookup(
context: &Context,
namespace: Namespace,
chat: Option<ChatId>,
) -> Result<Option<String>> {
let token = match chat {
Some(chat_id) => {
context
.sql
.query_get_value(
"SELECT token FROM tokens WHERE namespc=? AND foreign_id=? ORDER BY timestamp DESC LIMIT 1;",
(namespace, chat_id),
)
.await?
}
// foreign_id is declared as `INTEGER DEFAULT 0` in the schema.
None => {
context
.sql
.query_get_value(
"SELECT token FROM tokens WHERE namespc=? AND foreign_id=0 ORDER BY timestamp DESC LIMIT 1;",
(namespace,),
)
.await?
}
};
Ok(token)
}
pub async fn lookup_or_new(
context: &Context,
namespace: Namespace,
foreign_id: Option<ChatId>,
) -> Result<String> {
if let Some(token) = lookup(context, namespace, foreign_id).await? {
return Ok(token);
}
let token = create_id();
save(context, namespace, foreign_id, &token).await?;
Ok(token)
}
pub async fn get_config(&self, key: Config) -> Result<Option<String>> {
let env_key = format!("DELTACHAT_{}", key.as_ref().to_uppercase());
if let Ok(value) = env::var(env_key) {
return Ok(Some(value));
}
let value = match key {
Config::Selfavatar => {
let rel_path = self.sql.get_raw_config(key.as_ref()).await?;
rel_path.map(|p| {
get_abs_path(self, Path::new(&p))
.to_string_lossy()
.into_owned()
})
}
Config::SysVersion => Some((*DC_VERSION_STR).clone()),
Config::SysMsgsizeMaxRecommended => Some(format!("{RECOMMENDED_FILE_SIZE}")),
Config::SysConfigKeys => Some(get_config_keys_string()),
_ => self.sql.get_raw_config(key.as_ref()).await?,
};
if value.is_some() {
return Ok(value);
}
// Default values
match key {
Config::ConfiguredInboxFolder => Ok(Some("INBOX".to_owned())),
_ => Ok(key.get_str("default").map(|s| s.to_string())),
}
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub(crate) async fn sync_qr_code_tokens(&self, chat_id: Option<ChatId>) -> Result<()> {
if !self.get_config_bool(Config::SyncMsgs).await? {
return Ok(());
}
if let (Some(invitenumber), Some(auth)) = (
token::lookup(self, Namespace::InviteNumber, chat_id).await?,
token::lookup(self, Namespace::Auth, chat_id).await?,
) {
let grpid = if let Some(chat_id) = chat_id {
let chat = Chat::load_from_db(self, chat_id).await?;
if !chat.is_promoted() {
info!(
self,
"group '{}' not yet promoted, do not sync tokens yet.", chat.grpid
);
return Ok(());
}
Some(chat.grpid)
} else {
None
};
self.add_sync_item(SyncData::AddQrToken(QrTokenData {
invitenumber,
auth,
grpid,
}))
.await?;
}
Ok(())
}
pub async fn load_from_db(context: &Context, chat_id: ChatId) -> Result<Self> {
let mut chat = context
.sql
.query_row(
"SELECT c.type, c.name, c.grpid, c.param, c.archived,
c.blocked, c.locations_send_until, c.muted_until, c.protected
FROM chats c
WHERE c.id=?;",
(chat_id,),
|row| {
let c = Chat {
id: chat_id,
typ: row.get(0)?,
name: row.get::<_, String>(1)?,
grpid: row.get::<_, String>(2)?,
param: row.get::<_, String>(3)?.parse().unwrap_or_default(),
visibility: row.get(4)?,
blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),
is_sending_locations: row.get(6)?,
mute_duration: row.get(7)?,
protected: row.get(8)?,
};
Ok(c)
},
)
.await
.context(format!("Failed loading chat {chat_id} from database"))?;
if chat.id.is_archived_link() {
chat.name = stock_str::archived_chats(context).await;
} else {
if chat.typ == Chattype::Single && chat.name.is_empty() {
// chat.name is set to contact.display_name on changes,
// however, if things went wrong somehow, we do this here explicitly.
let mut chat_name = "Err [Name not found]".to_owned();
match get_chat_contacts(context, chat.id).await {
Ok(contacts) => {
if let Some(contact_id) = contacts.first() {
if let Ok(contact) = Contact::get_by_id(context, *contact_id).await {
contact.get_display_name().clone_into(&mut chat_name);
}
}
}
Err(err) => {
error!(
context,
"Failed to load contacts for {}: {:#}.", chat.id, err
);
}
}
chat.name = chat_name;
}
if chat.param.exists(Param::Selftalk) {
chat.name = stock_str::saved_messages(context).await;
} else if chat.param.exists(Param::Devicetalk) {
chat.name = stock_str::device_messages(context).await;
}
}
Ok(chat)
}
pub async fn get_primary_self_addr(&self) -> Result<String> {
self.get_config(Config::ConfiguredAddr)
.await?
.context("No self addr configured")
}
pub fn get_name(&self) -> &str {
&self.name
}
async fn get_self_fingerprint(context: &Context) -> Option<Fingerprint> {
match load_self_public_key(context).await {
Ok(key) => Some(key.fingerprint()),
Err(_) => {
warn!(context, "get_self_fingerprint(): failed to load key");
None
}
}
}
pub enum Namespace {
#[default]
Unknown = 0,
Auth = 110,
InviteNumber = 100,
}
pub struct Context {
pub(crate) inner: Arc<InnerContext>,
}
pub struct Fingerprint(Vec<u8>);
pub enum Config {
/// Email address, used in the `From:` field.
Addr,
/// IMAP server hostname.
MailServer,
/// IMAP server username.
MailUser,
/// IMAP server password.
MailPw,
/// IMAP server port.
MailPort,
/// IMAP server security (e.g. TLS, STARTTLS).
MailSecurity,
/// How to check IMAP server TLS certificates.
ImapCertificateChecks,
/// SMTP server hostname.
SendServer,
/// SMTP server username.
SendUser,
/// SMTP server password.
SendPw,
/// SMTP server port.
SendPort,
/// SMTP server security (e.g. TLS, STARTTLS).
SendSecurity,
/// How to check SMTP server TLS certificates.
SmtpCertificateChecks,
/// Whether to use OAuth 2.
///
/// Historically contained other bitflags, which are now deprecated.
/// Should not be extended in the future, create new config keys instead.
ServerFlags,
/// True if SOCKS5 is enabled.
///
/// Can be used to disable SOCKS5 without erasing SOCKS5 configuration.
Socks5Enabled,
/// SOCKS5 proxy server hostname or address.
Socks5Host,
/// SOCKS5 proxy server port.
Socks5Port,
/// SOCKS5 proxy server username.
Socks5User,
/// SOCKS5 proxy server password.
Socks5Password,
/// Own name to use in the `From:` field when sending messages.
Displayname,
/// Own status to display, sent in message footer.
Selfstatus,
/// Own avatar filename.
Selfavatar,
/// Send BCC copy to self.
///
/// Should be enabled for multidevice setups.
#[strum(props(default = "1"))]
BccSelf,
/// True if encryption is preferred according to Autocrypt standard.
#[strum(props(default = "1"))]
E2eeEnabled,
/// True if Message Delivery Notifications (read receipts) should
/// be sent and requested.
#[strum(props(default = "1"))]
MdnsEnabled,
/// True if "Sent" folder should be watched for changes.
#[strum(props(default = "0"))]
SentboxWatch,
/// True if chat messages should be moved to a separate folder.
#[strum(props(default = "1"))]
MvboxMove,
/// Watch for new messages in the "Mvbox" (aka DeltaChat folder) only.
///
/// This will not entirely disable other folders, e.g. the spam folder will also still
/// be watched for new messages.
#[strum(props(default = "0"))]
OnlyFetchMvbox,
/// Whether to show classic emails or only chat messages.
#[strum(props(default = "2"))] // also change ShowEmails.default() on changes
ShowEmails,
/// Quality of the media files to send.
#[strum(props(default = "0"))] // also change MediaQuality.default() on changes
MediaQuality,
/// If set to "1", on the first time `start_io()` is called after configuring,
/// the newest existing messages are fetched.
/// Existing recipients are added to the contact database regardless of this setting.
#[strum(props(default = "0"))]
FetchExistingMsgs,
/// If set to "1", then existing messages are considered to be already fetched.
/// This flag is reset after successful configuration.
#[strum(props(default = "1"))]
FetchedExistingMsgs,
/// Type of the OpenPGP key to generate.
#[strum(props(default = "0"))]
KeyGenType,
/// Timer in seconds after which the message is deleted from the
/// server.
///
/// Equals to 0 by default, which means the message is never
/// deleted.
///
/// Value 1 is treated as "delete at once": messages are deleted
/// immediately, without moving to DeltaChat folder.
#[strum(props(default = "0"))]
DeleteServerAfter,
/// Timer in seconds after which the message is deleted from the
/// device.
///
/// Equals to 0 by default, which means the message is never
/// deleted.
#[strum(props(default = "0"))]
DeleteDeviceAfter,
/// Move messages to the Trash folder instead of marking them "\Deleted". Overrides
/// `ProviderOptions::delete_to_trash`.
DeleteToTrash,
/// Save raw MIME messages with headers in the database if true.
SaveMimeHeaders,
/// The primary email address. Also see `SecondaryAddrs`.
ConfiguredAddr,
/// Configured IMAP server hostname.
ConfiguredMailServer,
/// Configured IMAP server username.
ConfiguredMailUser,
/// Configured IMAP server password.
ConfiguredMailPw,
/// Configured IMAP server port.
ConfiguredMailPort,
/// Configured IMAP server security (e.g. TLS, STARTTLS).
ConfiguredMailSecurity,
/// How to check IMAP server TLS certificates.
ConfiguredImapCertificateChecks,
/// Configured SMTP server hostname.
ConfiguredSendServer,
/// Configured SMTP server username.
ConfiguredSendUser,
/// Configured SMTP server password.
ConfiguredSendPw,
/// Configured SMTP server port.
ConfiguredSendPort,
/// How to check SMTP server TLS certificates.
ConfiguredSmtpCertificateChecks,
/// Whether OAuth 2 is used with configured provider.
ConfiguredServerFlags,
/// Configured SMTP server security (e.g. TLS, STARTTLS).
ConfiguredSendSecurity,
/// Configured folder for incoming messages.
ConfiguredInboxFolder,
/// Configured folder for chat messages.
ConfiguredMvboxFolder,
/// Configured "Sent" folder.
ConfiguredSentboxFolder,
/// Configured "Trash" folder.
ConfiguredTrashFolder,
/// Unix timestamp of the last successful configuration.
ConfiguredTimestamp,
/// ID of the configured provider from the provider database.
ConfiguredProvider,
/// True if account is configured.
Configured,
/// True if account is a chatmail account.
IsChatmail,
/// All secondary self addresses separated by spaces
/// (`addr1@example.org addr2@example.org addr3@example.org`)
SecondaryAddrs,
/// Read-only core version string.
#[strum(serialize = "sys.version")]
SysVersion,
/// Maximal recommended attachment size in bytes.
#[strum(serialize = "sys.msgsize_max_recommended")]
SysMsgsizeMaxRecommended,
/// Space separated list of all config keys available.
#[strum(serialize = "sys.config_keys")]
SysConfigKeys,
/// True if it is a bot account.
Bot,
/// True when to skip initial start messages in groups.
#[strum(props(default = "0"))]
SkipStartMessages,
/// Whether we send a warning if the password is wrong (set to false when we send a warning
/// because we do not want to send a second warning)
#[strum(props(default = "0"))]
NotifyAboutWrongPw,
/// If a warning about exceeding quota was shown recently,
/// this is the percentage of quota at the time the warning was given.
/// Unset, when quota falls below minimal warning threshold again.
QuotaExceeding,
/// address to webrtc instance to use for videochats
WebrtcInstance,
/// Timestamp of the last time housekeeping was run
LastHousekeeping,
/// Timestamp of the last `CantDecryptOutgoingMsgs` notification.
LastCantDecryptOutgoingMsgs,
/// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.
#[strum(props(default = "60"))]
ScanAllFoldersDebounceSecs,
/// Whether to avoid using IMAP IDLE even if the server supports it.
///
/// This is a developer option for testing "fake idle".
#[strum(props(default = "0"))]
DisableIdle,
/// Defines the max. size (in bytes) of messages downloaded automatically.
/// 0 = no limit.
#[strum(props(default = "0"))]
DownloadLimit,
/// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set.
#[strum(props(default = "1"))]
SyncMsgs,
/// Space-separated list of all the authserv-ids which we believe
/// may be the one of our email server.
///
/// See `crate::authres::update_authservid_candidates`.
AuthservIdCandidates,
/// Make all outgoing messages with Autocrypt header "multipart/signed".
SignUnencrypted,
/// Let the core save all events to the database.
/// This value is used internally to remember the MsgId of the logging xdc
#[strum(props(default = "0"))]
DebugLogging,
/// Last message processed by the bot.
LastMsgId,
/// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by
/// default.
///
/// This is not supposed to be changed by UIs and only used for testing.
#[strum(props(default = "172800"))]
GossipPeriod,
/// Feature flag for verified 1:1 chats; the UI should set it
/// to 1 if it supports verified 1:1 chats.
/// Regardless of this setting, `chat.is_protected()` returns true while the key is verified,
/// and when the key changes, an info message is posted into the chat.
/// 0=Nothing else happens when the key changes.
/// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true
/// until `chat_id.accept()` is called.
#[strum(props(default = "0"))]
VerifiedOneOnOneChats,
/// Row ID of the key in the `keypairs` table
/// used for signatures, encryption to self and included in `Autocrypt` header.
KeyId,
/// This key is sent to the self_reporting bot so that the bot can recognize the user
/// without storing the email address
SelfReportingId,
/// MsgId of webxdc map integration.
WebxdcIntegration,
/// Iroh secret key.
IrohSecretKey,
} | use anyhow::{bail, Context as _, Error, Result};
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
use crate::aheader::EncryptPreference;
use crate::chat::{self, Chat, ChatId, ChatIdBlocked, ProtectionStatus};
use crate::chatlist_events;
use crate::config::Config;
use crate::constants::Blocked;
use crate::contact::{Contact, ContactId, Origin};
use crate::context::Context;
use crate::e2ee::ensure_secret_key_exists;
use crate::events::EventType;
use crate::headerdef::HeaderDef;
use crate::key::{load_self_public_key, DcKey, Fingerprint};
use crate::message::{Message, Viewtype};
use crate::mimeparser::{MimeMessage, SystemMessage};
use crate::param::Param;
use crate::peerstate::Peerstate;
use crate::qr::check_qr;
use crate::securejoin::bob::JoinerProgress;
use crate::stock_str;
use crate::sync::Sync::*;
use crate::token;
use crate::tools::time;
use bobstate::BobState;
use qrinvite::QrInvite;
use crate::token::Namespace;
use deltachat_contact_tools::{ContactAddress, EmailAddress};
use super::*;
use crate::chat::{remove_contact_from_chat, CantSendReason};
use crate::chatlist::Chatlist;
use crate::constants::{self, Chattype};
use crate::imex::{imex, ImexMode};
use crate::receive_imf::receive_imf;
use crate::stock_str::{self, chat_protection_enabled};
use crate::test_utils::get_chat_msg;
use crate::test_utils::{TestContext, TestContextManager};
use crate::tools::SystemTime;
use std::collections::HashSet;
use std::time::Duration; | projects__deltachat-core__rust__securejoin__.rs__function__2.txt |
projects/deltachat-core/c/dc_contact.c | char* dc_addr_normalize(const char* addr)
{
char* addr_normalized = dc_strdup(addr);
dc_trim(addr_normalized);
if (strncmp(addr_normalized, "mailto:", 7)==0) {
char* old = addr_normalized;
addr_normalized = dc_strdup(&old[7]);
free(old);
dc_trim(addr_normalized);
}
return addr_normalized;
} | projects/deltachat-core/rust/oauth2.rs | fn normalize_addr(addr: &str) -> &str {
let normalized = addr.trim();
normalized.trim_start_matches("mailto:")
} | use std::collections::HashMap;
use anyhow::Result;
use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
use serde::Deserialize;
use crate::config::Config;
use crate::context::Context;
use crate::provider;
use crate::provider::Oauth2Authorizer;
use crate::socks::Socks5Config;
use crate::tools::time;
use super::*;
use crate::test_utils::TestContext; | projects__deltachat-core__rust__oauth2__.rs__function__8.txt | |
projects/deltachat-core/c/dc_contact.c | int dc_addr_equals_self(dc_context_t* context, const char* addr)
{
int ret = 0;
char* normalized_addr = NULL;
char* self_addr = NULL;
if (context==NULL || addr==NULL) {
goto cleanup;
}
normalized_addr = dc_addr_normalize(addr);
if (NULL==(self_addr=dc_sqlite3_get_config(context->sql, "configured_addr", NULL))) {
goto cleanup;
}
ret = strcasecmp(normalized_addr, self_addr)==0? 1 : 0;
cleanup:
free(self_addr);
free(normalized_addr);
return ret;
} | projects/deltachat-core/rust/config.rs | pub(crate) async fn is_self_addr(&self, addr: &str) -> Result<bool> {
Ok(self
.get_config(Config::ConfiguredAddr)
.await?
.iter()
.any(|a| addr_cmp(addr, a))
|| self
.get_secondary_self_addrs()
.await?
.iter()
.any(|a| addr_cmp(addr, a)))
} | pub(crate) async fn get_secondary_self_addrs(&self) -> Result<Vec<String>> {
let secondary_addrs = self
.get_config(Config::SecondaryAddrs)
.await?
.unwrap_or_default();
Ok(secondary_addrs
.split_ascii_whitespace()
.map(|s| s.to_string())
.collect())
}
pub(crate) fn iter(&self) -> BlobDirIter<'_> {
BlobDirIter::new(self.context, self.inner.iter())
}
pub async fn get_config(&self, key: Config) -> Result<Option<String>> {
let env_key = format!("DELTACHAT_{}", key.as_ref().to_uppercase());
if let Ok(value) = env::var(env_key) {
return Ok(Some(value));
}
let value = match key {
Config::Selfavatar => {
let rel_path = self.sql.get_raw_config(key.as_ref()).await?;
rel_path.map(|p| {
get_abs_path(self, Path::new(&p))
.to_string_lossy()
.into_owned()
})
}
Config::SysVersion => Some((*DC_VERSION_STR).clone()),
Config::SysMsgsizeMaxRecommended => Some(format!("{RECOMMENDED_FILE_SIZE}")),
Config::SysConfigKeys => Some(get_config_keys_string()),
_ => self.sql.get_raw_config(key.as_ref()).await?,
};
if value.is_some() {
return Ok(value);
}
// Default values
match key {
Config::ConfiguredInboxFolder => Ok(Some("INBOX".to_owned())),
_ => Ok(key.get_str("default").map(|s| s.to_string())),
}
}
pub struct Context {
pub(crate) inner: Arc<InnerContext>,
}
pub enum Config {
/// Email address, used in the `From:` field.
Addr,
/// IMAP server hostname.
MailServer,
/// IMAP server username.
MailUser,
/// IMAP server password.
MailPw,
/// IMAP server port.
MailPort,
/// IMAP server security (e.g. TLS, STARTTLS).
MailSecurity,
/// How to check IMAP server TLS certificates.
ImapCertificateChecks,
/// SMTP server hostname.
SendServer,
/// SMTP server username.
SendUser,
/// SMTP server password.
SendPw,
/// SMTP server port.
SendPort,
/// SMTP server security (e.g. TLS, STARTTLS).
SendSecurity,
/// How to check SMTP server TLS certificates.
SmtpCertificateChecks,
/// Whether to use OAuth 2.
///
/// Historically contained other bitflags, which are now deprecated.
/// Should not be extended in the future, create new config keys instead.
ServerFlags,
/// True if SOCKS5 is enabled.
///
/// Can be used to disable SOCKS5 without erasing SOCKS5 configuration.
Socks5Enabled,
/// SOCKS5 proxy server hostname or address.
Socks5Host,
/// SOCKS5 proxy server port.
Socks5Port,
/// SOCKS5 proxy server username.
Socks5User,
/// SOCKS5 proxy server password.
Socks5Password,
/// Own name to use in the `From:` field when sending messages.
Displayname,
/// Own status to display, sent in message footer.
Selfstatus,
/// Own avatar filename.
Selfavatar,
/// Send BCC copy to self.
///
/// Should be enabled for multidevice setups.
#[strum(props(default = "1"))]
BccSelf,
/// True if encryption is preferred according to Autocrypt standard.
#[strum(props(default = "1"))]
E2eeEnabled,
/// True if Message Delivery Notifications (read receipts) should
/// be sent and requested.
#[strum(props(default = "1"))]
MdnsEnabled,
/// True if "Sent" folder should be watched for changes.
#[strum(props(default = "0"))]
SentboxWatch,
/// True if chat messages should be moved to a separate folder.
#[strum(props(default = "1"))]
MvboxMove,
/// Watch for new messages in the "Mvbox" (aka DeltaChat folder) only.
///
/// This will not entirely disable other folders, e.g. the spam folder will also still
/// be watched for new messages.
#[strum(props(default = "0"))]
OnlyFetchMvbox,
/// Whether to show classic emails or only chat messages.
#[strum(props(default = "2"))] // also change ShowEmails.default() on changes
ShowEmails,
/// Quality of the media files to send.
#[strum(props(default = "0"))] // also change MediaQuality.default() on changes
MediaQuality,
/// If set to "1", on the first time `start_io()` is called after configuring,
/// the newest existing messages are fetched.
/// Existing recipients are added to the contact database regardless of this setting.
#[strum(props(default = "0"))]
FetchExistingMsgs,
/// If set to "1", then existing messages are considered to be already fetched.
/// This flag is reset after successful configuration.
#[strum(props(default = "1"))]
FetchedExistingMsgs,
/// Type of the OpenPGP key to generate.
#[strum(props(default = "0"))]
KeyGenType,
/// Timer in seconds after which the message is deleted from the
/// server.
///
/// Equals to 0 by default, which means the message is never
/// deleted.
///
/// Value 1 is treated as "delete at once": messages are deleted
/// immediately, without moving to DeltaChat folder.
#[strum(props(default = "0"))]
DeleteServerAfter,
/// Timer in seconds after which the message is deleted from the
/// device.
///
/// Equals to 0 by default, which means the message is never
/// deleted.
#[strum(props(default = "0"))]
DeleteDeviceAfter,
/// Move messages to the Trash folder instead of marking them "\Deleted". Overrides
/// `ProviderOptions::delete_to_trash`.
DeleteToTrash,
/// Save raw MIME messages with headers in the database if true.
SaveMimeHeaders,
/// The primary email address. Also see `SecondaryAddrs`.
ConfiguredAddr,
/// Configured IMAP server hostname.
ConfiguredMailServer,
/// Configured IMAP server username.
ConfiguredMailUser,
/// Configured IMAP server password.
ConfiguredMailPw,
/// Configured IMAP server port.
ConfiguredMailPort,
/// Configured IMAP server security (e.g. TLS, STARTTLS).
ConfiguredMailSecurity,
/// How to check IMAP server TLS certificates.
ConfiguredImapCertificateChecks,
/// Configured SMTP server hostname.
ConfiguredSendServer,
/// Configured SMTP server username.
ConfiguredSendUser,
/// Configured SMTP server password.
ConfiguredSendPw,
/// Configured SMTP server port.
ConfiguredSendPort,
/// How to check SMTP server TLS certificates.
ConfiguredSmtpCertificateChecks,
/// Whether OAuth 2 is used with configured provider.
ConfiguredServerFlags,
/// Configured SMTP server security (e.g. TLS, STARTTLS).
ConfiguredSendSecurity,
/// Configured folder for incoming messages.
ConfiguredInboxFolder,
/// Configured folder for chat messages.
ConfiguredMvboxFolder,
/// Configured "Sent" folder.
ConfiguredSentboxFolder,
/// Configured "Trash" folder.
ConfiguredTrashFolder,
/// Unix timestamp of the last successful configuration.
ConfiguredTimestamp,
/// ID of the configured provider from the provider database.
ConfiguredProvider,
/// True if account is configured.
Configured,
/// True if account is a chatmail account.
IsChatmail,
/// All secondary self addresses separated by spaces
/// (`addr1@example.org addr2@example.org addr3@example.org`)
SecondaryAddrs,
/// Read-only core version string.
#[strum(serialize = "sys.version")]
SysVersion,
/// Maximal recommended attachment size in bytes.
#[strum(serialize = "sys.msgsize_max_recommended")]
SysMsgsizeMaxRecommended,
/// Space separated list of all config keys available.
#[strum(serialize = "sys.config_keys")]
SysConfigKeys,
/// True if it is a bot account.
Bot,
/// True when to skip initial start messages in groups.
#[strum(props(default = "0"))]
SkipStartMessages,
/// Whether we send a warning if the password is wrong (set to false when we send a warning
/// because we do not want to send a second warning)
#[strum(props(default = "0"))]
NotifyAboutWrongPw,
/// If a warning about exceeding quota was shown recently,
/// this is the percentage of quota at the time the warning was given.
/// Unset, when quota falls below minimal warning threshold again.
QuotaExceeding,
/// address to webrtc instance to use for videochats
WebrtcInstance,
/// Timestamp of the last time housekeeping was run
LastHousekeeping,
/// Timestamp of the last `CantDecryptOutgoingMsgs` notification.
LastCantDecryptOutgoingMsgs,
/// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.
#[strum(props(default = "60"))]
ScanAllFoldersDebounceSecs,
/// Whether to avoid using IMAP IDLE even if the server supports it.
///
/// This is a developer option for testing "fake idle".
#[strum(props(default = "0"))]
DisableIdle,
/// Defines the max. size (in bytes) of messages downloaded automatically.
/// 0 = no limit.
#[strum(props(default = "0"))]
DownloadLimit,
/// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set.
#[strum(props(default = "1"))]
SyncMsgs,
/// Space-separated list of all the authserv-ids which we believe
/// may be the one of our email server.
///
/// See `crate::authres::update_authservid_candidates`.
AuthservIdCandidates,
/// Make all outgoing messages with Autocrypt header "multipart/signed".
SignUnencrypted,
/// Let the core save all events to the database.
/// This value is used internally to remember the MsgId of the logging xdc
#[strum(props(default = "0"))]
DebugLogging,
/// Last message processed by the bot.
LastMsgId,
/// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by
/// default.
///
/// This is not supposed to be changed by UIs and only used for testing.
#[strum(props(default = "172800"))]
GossipPeriod,
/// Feature flag for verified 1:1 chats; the UI should set it
/// to 1 if it supports verified 1:1 chats.
/// Regardless of this setting, `chat.is_protected()` returns true while the key is verified,
/// and when the key changes, an info message is posted into the chat.
/// 0=Nothing else happens when the key changes.
/// 1=After the key changed, `can_send()` returns false and `is_protection_broken()` returns true
/// until `chat_id.accept()` is called.
#[strum(props(default = "0"))]
VerifiedOneOnOneChats,
/// Row ID of the key in the `keypairs` table
/// used for signatures, encryption to self and included in `Autocrypt` header.
KeyId,
/// This key is sent to the self_reporting bot so that the bot can recognize the user
/// without storing the email address
SelfReportingId,
/// MsgId of webxdc map integration.
WebxdcIntegration,
/// Iroh secret key.
IrohSecretKey,
} | use std::env;
use std::path::Path;
use std::str::FromStr;
use anyhow::{ensure, Context as _, Result};
use base64::Engine as _;
use deltachat_contact_tools::addr_cmp;
use serde::{Deserialize, Serialize};
use strum::{EnumProperty, IntoEnumIterator};
use strum_macros::{AsRefStr, Display, EnumIter, EnumString};
use tokio::fs;
use crate::blob::BlobObject;
use crate::constants::{self, DC_VERSION_STR};
use crate::context::Context;
use crate::events::EventType;
use crate::log::LogExt;
use crate::mimefactory::RECOMMENDED_FILE_SIZE;
use crate::provider::{get_provider_by_id, Provider};
use crate::sync::{self, Sync::*, SyncData};
use crate::tools::{get_abs_path, improve_single_line_input};
use num_traits::FromPrimitive;
use super::*;
use crate::test_utils::{sync, TestContext, TestContextManager}; | projects__deltachat-core__rust__config__.rs__function__27.txt |
projects/deltachat-core/c/dc_pgp.c | 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 <user-id>,
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;
} | projects/deltachat-core/rust/pgp.rs | pub(crate) fn create_keypair(addr: EmailAddress, keygen_type: KeyGenType) -> Result<KeyPair> {
let (signing_key_type, encryption_key_type) = match keygen_type {
KeyGenType::Rsa2048 => (PgpKeyType::Rsa(2048), PgpKeyType::Rsa(2048)),
KeyGenType::Rsa4096 => (PgpKeyType::Rsa(4096), PgpKeyType::Rsa(4096)),
KeyGenType::Ed25519 | KeyGenType::Default => (PgpKeyType::EdDSA, PgpKeyType::ECDH),
};
let user_id = format!("<{addr}>");
let key_params = SecretKeyParamsBuilder::default()
.key_type(signing_key_type)
.can_certify(true)
.can_sign(true)
.primary_user_id(user_id)
.passphrase(None)
.preferred_symmetric_algorithms(smallvec![
SymmetricKeyAlgorithm::AES256,
SymmetricKeyAlgorithm::AES192,
SymmetricKeyAlgorithm::AES128,
])
.preferred_hash_algorithms(smallvec![
HashAlgorithm::SHA2_256,
HashAlgorithm::SHA2_384,
HashAlgorithm::SHA2_512,
HashAlgorithm::SHA2_224,
HashAlgorithm::SHA1,
])
.preferred_compression_algorithms(smallvec![
CompressionAlgorithm::ZLIB,
CompressionAlgorithm::ZIP,
])
.subkey(
SubkeyParamsBuilder::default()
.key_type(encryption_key_type)
.can_encrypt(true)
.passphrase(None)
.build()
.context("failed to build subkey parameters")?,
)
.build()
.context("failed to build key parameters")?;
let secret_key = key_params
.generate()
.context("failed to generate the key")?
.sign(|| "".into())
.context("failed to sign secret key")?;
secret_key
.verify()
.context("invalid secret key generated")?;
let public_key = secret_key
.public_key()
.sign(&secret_key, || "".into())
.context("failed to sign public key")?;
public_key
.verify()
.context("invalid public key generated")?;
Ok(KeyPair {
addr,
public: public_key,
secret: secret_key,
})
} | pub struct KeyPair {
/// Email address.
pub addr: EmailAddress,
/// Public key.
pub public: SignedPublicKey,
/// Secret key.
pub secret: SignedSecretKey,
}
pub enum KeyGenType {
#[default]
Default = 0,
/// 2048-bit RSA.
Rsa2048 = 1,
/// [Ed25519](https://ed25519.cr.yp.to/) signature and X25519 encryption.
Ed25519 = 2,
/// 4096-bit RSA.
Rsa4096 = 3,
} | use std::collections::{BTreeMap, HashSet};
use std::io;
use std::io::Cursor;
use anyhow::{bail, Context as _, Result};
use deltachat_contact_tools::EmailAddress;
use pgp::armor::BlockType;
use pgp::composed::{
Deserializable, KeyType as PgpKeyType, Message, SecretKeyParamsBuilder, SignedPublicKey,
SignedPublicSubKey, SignedSecretKey, StandaloneSignature, SubkeyParamsBuilder,
};
use pgp::crypto::hash::HashAlgorithm;
use pgp::crypto::sym::SymmetricKeyAlgorithm;
use pgp::types::{
CompressionAlgorithm, KeyTrait, Mpi, PublicKeyTrait, SecretKeyTrait, StringToKey,
};
use rand::{thread_rng, CryptoRng, Rng};
use tokio::runtime::Handle;
use crate::constants::KeyGenType;
use crate::key::{DcKey, Fingerprint};
use std::io::Read;
use once_cell::sync::Lazy;
use tokio::sync::OnceCell;
use super::*;
use crate::test_utils::{alice_keypair, bob_keypair}; | projects__deltachat-core__rust__pgp__.rs__function__8.txt |
projects/deltachat-core/c/dc_chat.c | * 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 chat_id != ? AND (type=? OR type=? OR type=?) ORDER BY timestamp, id;");
sqlite3_bind_int(stmt, 1, chat_id);
sqlite3_bind_int(stmt, 2, DC_CHAT_ID_TRASH);
sqlite3_bind_int(stmt, 3, msg_type);
sqlite3_bind_int(stmt, 4, msg_type2>0? msg_type2 : msg_type);
sqlite3_bind_int(stmt, 5, 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;
} | projects/deltachat-core/rust/chat.rs | pub async fn get_chat_media(
context: &Context,
chat_id: Option<ChatId>,
msg_type: Viewtype,
msg_type2: Viewtype,
msg_type3: Viewtype,
) -> Result<Vec<MsgId>> {
// TODO This query could/should be converted to `AND type IN (?, ?, ?)`.
let list = context
.sql
.query_map(
"SELECT id
FROM msgs
WHERE (1=? OR chat_id=?)
AND chat_id != ?
AND (type=? OR type=? OR type=?)
AND hidden=0
ORDER BY timestamp, id;",
(
chat_id.is_none(),
chat_id.unwrap_or_else(|| ChatId::new(0)),
DC_CHAT_ID_TRASH,
msg_type,
if msg_type2 != Viewtype::Unknown {
msg_type2
} else {
msg_type
},
if msg_type3 != Viewtype::Unknown {
msg_type3
} else {
msg_type
},
),
|row| row.get::<_, MsgId>(0),
|ids| Ok(ids.flatten().collect()),
)
.await?;
Ok(list)
} | pub struct Context {
pub(crate) inner: Arc<InnerContext>,
}
pub struct InnerContext {
/// Blob directory path
pub(crate) blobdir: PathBuf,
pub(crate) sql: Sql,
pub(crate) smeared_timestamp: SmearedTimestamp,
/// The global "ongoing" process state.
///
/// This is a global mutex-like state for operations which should be modal in the
/// clients.
running_state: RwLock<RunningState>,
/// Mutex to avoid generating the key for the user more than once.
pub(crate) generating_key_mutex: Mutex<()>,
/// Mutex to enforce only a single running oauth2 is running.
pub(crate) oauth2_mutex: Mutex<()>,
/// Mutex to prevent a race condition when a "your pw is wrong" warning is sent, resulting in multiple messages being sent.
pub(crate) wrong_pw_warning_mutex: Mutex<()>,
pub(crate) translated_stockstrings: StockStrings,
pub(crate) events: Events,
pub(crate) scheduler: SchedulerState,
pub(crate) ratelimit: RwLock<Ratelimit>,
/// Recently loaded quota information, if any.
/// Set to `None` if quota was never tried to load.
pub(crate) quota: RwLock<Option<QuotaInfo>>,
/// IMAP UID resync request.
pub(crate) resync_request: AtomicBool,
/// Notify about new messages.
///
/// This causes [`Context::wait_next_msgs`] to wake up.
pub(crate) new_msgs_notify: Notify,
/// Server ID response if ID capability is supported
/// and the server returned non-NIL on the inbox connection.
/// <https://datatracker.ietf.org/doc/html/rfc2971>
pub(crate) server_id: RwLock<Option<HashMap<String, String>>>,
/// IMAP METADATA.
pub(crate) metadata: RwLock<Option<ServerMetadata>>,
pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>,
/// ID for this `Context` in the current process.
///
/// This allows for multiple `Context`s open in a single process where each context can
/// be identified by this ID.
pub(crate) id: u32,
creation_time: tools::Time,
/// The text of the last error logged and emitted as an event.
/// If the ui wants to display an error after a failure,
/// `last_error` should be used to avoid races with the event thread.
pub(crate) last_error: std::sync::RwLock<String>,
/// If debug logging is enabled, this contains all necessary information
///
/// Standard RwLock instead of [`tokio::sync::RwLock`] is used
/// because the lock is used from synchronous [`Context::emit_event`].
pub(crate) debug_logging: std::sync::RwLock<Option<DebugLogging>>,
/// Push subscriber to store device token
/// and register for heartbeat notifications.
pub(crate) push_subscriber: PushSubscriber,
/// True if account has subscribed to push notifications via IMAP.
pub(crate) push_subscribed: AtomicBool,
/// Iroh for realtime peer channels.
pub(crate) iroh: OnceCell<Iroh>,
}
pub async fn query_map<T, F, G, H>(
&self,
sql: &str,
params: impl rusqlite::Params + Send,
f: F,
mut g: G,
) -> Result<H>
where
F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result<T>,
G: Send + FnMut(rusqlite::MappedRows<F>) -> Result<H>,
H: Send + 'static,
{
self.call(move |conn| {
let mut stmt = conn.prepare(sql)?;
let res = stmt.query_map(params, f)?;
g(res)
})
.await
}
pub enum Viewtype {
/// Unknown message type.
#[default]
Unknown = 0,
/// Text message.
/// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text().
Text = 10,
/// Image message.
/// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to
/// `Gif` when sending the message.
/// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension
/// and retrieved via dc_msg_set_file(), dc_msg_set_dimension().
Image = 20,
/// Animated GIF message.
/// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension()
/// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height().
Gif = 21,
/// Message containing a sticker, similar to image.
/// If possible, the ui should display the image without borders in a transparent way.
/// A click on a sticker will offer to install the sticker set in some future.
Sticker = 23,
/// Message containing an Audio file.
/// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()
/// and retrieved via dc_msg_get_file(), dc_msg_get_duration().
Audio = 40,
/// A voice message that was directly recorded by the user.
/// For all other audio messages, the type #DC_MSG_AUDIO should be used.
/// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()
/// and retrieved via dc_msg_get_file(), dc_msg_get_duration()
Voice = 41,
/// Video messages.
/// File, width, height and durarion
/// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration()
/// and retrieved via
/// dc_msg_get_file(), dc_msg_get_width(),
/// dc_msg_get_height(), dc_msg_get_duration().
Video = 50,
/// Message containing any file, eg. a PDF.
/// The file is set via dc_msg_set_file()
/// and retrieved via dc_msg_get_file().
File = 60,
/// Message is an invitation to a videochat.
VideochatInvitation = 70,
/// Message is an webxdc instance.
Webxdc = 80,
/// Message containing shared contacts represented as a vCard (virtual contact file)
/// with email addresses and possibly other fields.
/// Use `parse_vcard()` to retrieve them.
Vcard = 90,
}
pub struct MsgId(u32);
pub struct ChatId(u32);
impl ChatId {
/// Create a new [ChatId].
pub const fn new(id: u32) -> ChatId {
ChatId(id)
}
} | use std::cmp;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;
use anyhow::{anyhow, bail, ensure, Context as _, Result};
use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};
use deltachat_derive::{FromSql, ToSql};
use serde::{Deserialize, Serialize};
use strum_macros::EnumIter;
use tokio::task;
use crate::aheader::EncryptPreference;
use crate::blob::BlobObject;
use crate::chatlist::Chatlist;
use crate::chatlist_events;
use crate::color::str_to_color;
use crate::config::Config;
use crate::constants::{
self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,
DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,
};
use crate::contact::{self, Contact, ContactId, Origin};
use crate::context::Context;
use crate::debug_logging::maybe_set_logging_xdc;
use crate::download::DownloadState;
use crate::ephemeral::Timer as EphemeralTimer;
use crate::events::EventType;
use crate::html::new_html_mimepart;
use crate::location;
use crate::log::LogExt;
use crate::message::{self, Message, MessageState, MsgId, Viewtype};
use crate::mimefactory::MimeFactory;
use crate::mimeparser::SystemMessage;
use crate::param::{Param, Params};
use crate::peerstate::Peerstate;
use crate::receive_imf::ReceivedMsg;
use crate::securejoin::BobState;
use crate::smtp::send_msg_to_smtp;
use crate::sql;
use crate::stock_str;
use crate::sync::{self, Sync::*, SyncData};
use crate::tools::{
buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,
create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,
smeared_time, time, IsNoneOrEmpty, SystemTime,
};
use crate::webxdc::WEBXDC_SUFFIX;
use CantSendReason::*;
use super::*;
use crate::chatlist::get_archived_cnt;
use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};
use crate::message::delete_msgs;
use crate::receive_imf::receive_imf;
use crate::test_utils::{sync, TestContext, TestContextManager};
use strum::IntoEnumIterator;
use tokio::fs; | projects__deltachat-core__rust__chat__.rs__function__116.txt |
projects/deltachat-core/c/dc_msg.c | 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;
} | projects/deltachat-core/rust/message.rs | pub fn get_from_id(&self) -> ContactId {
self.from_id
} | pub struct ContactId(u32);
pub struct Message {
/// Message ID.
pub(crate) id: MsgId,
/// `From:` contact ID.
pub(crate) from_id: ContactId,
/// ID of the first contact in the `To:` header.
pub(crate) to_id: ContactId,
/// ID of the chat message belongs to.
pub(crate) chat_id: ChatId,
/// Type of the message.
pub(crate) viewtype: Viewtype,
/// State of the message.
pub(crate) state: MessageState,
pub(crate) download_state: DownloadState,
/// Whether the message is hidden.
pub(crate) hidden: bool,
pub(crate) timestamp_sort: i64,
pub(crate) timestamp_sent: i64,
pub(crate) timestamp_rcvd: i64,
pub(crate) ephemeral_timer: EphemeralTimer,
pub(crate) ephemeral_timestamp: i64,
pub(crate) text: String,
/// Message subject.
///
/// If empty, a default subject will be generated when sending.
pub(crate) subject: String,
/// `Message-ID` header value.
pub(crate) rfc724_mid: String,
/// `In-Reply-To` header value.
pub(crate) in_reply_to: Option<String>,
pub(crate) is_dc_message: MessengerMessage,
pub(crate) mime_modified: bool,
pub(crate) chat_blocked: Blocked,
pub(crate) location_id: u32,
pub(crate) error: Option<String>,
pub(crate) param: Params,
} | use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use anyhow::{ensure, format_err, Context as _, Result};
use deltachat_contact_tools::{parse_vcard, VcardContact};
use deltachat_derive::{FromSql, ToSql};
use serde::{Deserialize, Serialize};
use tokio::{fs, io};
use crate::blob::BlobObject;
use crate::chat::{Chat, ChatId, ChatIdBlocked};
use crate::chatlist_events;
use crate::config::Config;
use crate::constants::{
Blocked, Chattype, VideochatType, DC_CHAT_ID_TRASH, DC_DESIRED_TEXT_LEN, DC_MSG_ID_LAST_SPECIAL,
};
use crate::contact::{Contact, ContactId};
use crate::context::Context;
use crate::debug_logging::set_debug_logging_xdc;
use crate::download::DownloadState;
use crate::ephemeral::{start_ephemeral_timers_msgids, Timer as EphemeralTimer};
use crate::events::EventType;
use crate::imap::markseen_on_imap_table;
use crate::location::delete_poi_location;
use crate::mimeparser::{parse_message_id, SystemMessage};
use crate::param::{Param, Params};
use crate::pgp::split_armored_data;
use crate::reaction::get_msg_reactions;
use crate::sql;
use crate::summary::Summary;
use crate::tools::{
buf_compress, buf_decompress, get_filebytes, get_filemeta, gm2local_offset, read_file, time,
timestamp_to_str, truncate,
};
use MessageState::*;
use MessageState::*;
use num_traits::FromPrimitive;
use super::*;
use crate::chat::{
self, add_contact_to_chat, marknoticed_chat, send_text_msg, ChatItem, ProtectionStatus,
};
use crate::chatlist::Chatlist;
use crate::config::Config;
use crate::reaction::send_reaction;
use crate::receive_imf::receive_imf;
use crate::test_utils as test;
use crate::test_utils::{TestContext, TestContextManager}; | projects__deltachat-core__rust__message__.rs__function__32.txt |
projects/deltachat-core/c/dc_contact.c | uint32_t dc_contact_get_id(const dc_contact_t* contact)
{
if (contact==NULL || contact->magic!=DC_CONTACT_MAGIC) {
return 0;
}
return contact->id;
} | projects/deltachat-core/rust/contact.rs | pub fn get_id(&self) -> ContactId {
self.id
} | pub struct ContactId(u32);
pub struct Contact {
/// The contact ID.
pub id: ContactId,
/// Contact name. It is recommended to use `Contact::get_name`,
/// `Contact::get_display_name` or `Contact::get_name_n_addr` to access this field.
/// May be empty, initially set to `authname`.
name: String,
/// Name authorized by the contact himself. Only this name may be spread to others,
/// e.g. in To:-lists. May be empty. It is recommended to use `Contact::get_authname`,
/// to access this field.
authname: String,
/// E-Mail-Address of the contact. It is recommended to use `Contact::get_addr` to access this field.
addr: String,
/// Blocked state. Use contact_is_blocked to access this field.
pub blocked: bool,
/// Time when the contact was seen last time, Unix time in seconds.
last_seen: i64,
/// The origin/source of the contact.
pub origin: Origin,
/// Parameters as Param::ProfileImage
pub param: Params,
/// Last seen message signature for this contact, to be displayed in the profile.
status: String,
/// If the contact is a bot.
is_bot: bool,
} | use std::cmp::{min, Reverse};
use std::collections::BinaryHeap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;
use anyhow::{bail, ensure, Context as _, Result};
use async_channel::{self as channel, Receiver, Sender};
use base64::Engine as _;
use deltachat_contact_tools::may_be_valid_addr;
use deltachat_contact_tools::{
self as contact_tools, addr_cmp, addr_normalize, sanitize_name_and_addr, strip_rtlo_characters,
ContactAddress, VcardContact,
};
use deltachat_derive::{FromSql, ToSql};
use rusqlite::OptionalExtension;
use serde::{Deserialize, Serialize};
use tokio::task;
use tokio::time::{timeout, Duration};
use crate::aheader::{Aheader, EncryptPreference};
use crate::blob::BlobObject;
use crate::chat::{ChatId, ChatIdBlocked, ProtectionStatus};
use crate::color::str_to_color;
use crate::config::Config;
use crate::constants::{Blocked, Chattype, DC_GCL_ADD_SELF, DC_GCL_VERIFIED_ONLY};
use crate::context::Context;
use crate::events::EventType;
use crate::key::{load_self_public_key, DcKey, SignedPublicKey};
use crate::log::LogExt;
use crate::login_param::LoginParam;
use crate::message::MessageState;
use crate::mimeparser::AvatarAction;
use crate::param::{Param, Params};
use crate::peerstate::Peerstate;
use crate::sql::{self, params_iter};
use crate::sync::{self, Sync::*};
use crate::tools::{
duration_to_str, get_abs_path, improve_single_line_input, smeared_time, time, SystemTime,
};
use crate::{chat, chatlist_events, stock_str};
use deltachat_contact_tools::{may_be_valid_addr, normalize_name};
use super::*;
use crate::chat::{get_chat_contacts, send_text_msg, Chat};
use crate::chatlist::Chatlist;
use crate::receive_imf::receive_imf;
use crate::test_utils::{self, TestContext, TestContextManager}; | projects__deltachat-core__rust__contact__.rs__function__36.txt |
projects/deltachat-core/c/dc_chat.c | 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 */
} | projects/deltachat-core/rust/chat.rs | pub async fn lookup_by_contact(
context: &Context,
contact_id: ContactId,
) -> Result<Option<Self>> {
let Some(chat_id_blocked) = ChatIdBlocked::lookup_by_contact(context, contact_id).await?
else {
return Ok(None);
};
let chat_id = match chat_id_blocked.blocked {
Blocked::Not | Blocked::Request => Some(chat_id_blocked.id),
Blocked::Yes => None,
};
Ok(chat_id)
} | pub struct Context {
pub(crate) inner: Arc<InnerContext>,
}
pub struct ChatId(u32);
pub(crate) struct ChatIdBlocked {
/// Chat ID.
pub id: ChatId,
/// Whether the chat is blocked, unblocked or a contact request.
pub blocked: Blocked,
}
impl ChatIdBlocked {
pub async fn lookup_by_contact(
context: &Context,
contact_id: ContactId,
) -> Result<Option<Self>> {
ensure!(context.sql.is_open().await, "Database not available");
ensure!(
contact_id != ContactId::UNDEFINED,
"Invalid contact id requested"
);
context
.sql
.query_row_optional(
"SELECT c.id, c.blocked
FROM chats c
INNER JOIN chats_contacts j
ON c.id=j.chat_id
WHERE c.type=100 -- 100 = Chattype::Single
AND c.id>9 -- 9 = DC_CHAT_ID_LAST_SPECIAL
AND j.contact_id=?;",
(contact_id,),
|row| {
let id: ChatId = row.get(0)?;
let blocked: Blocked = row.get(1)?;
Ok(ChatIdBlocked { id, blocked })
},
)
.await
.map_err(Into::into)
}
}
pub struct ContactId(u32);
pub enum Blocked {
#[default]
Not = 0,
Yes = 1,
Request = 2,
} | use std::cmp;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;
use anyhow::{anyhow, bail, ensure, Context as _, Result};
use deltachat_contact_tools::{strip_rtlo_characters, ContactAddress};
use deltachat_derive::{FromSql, ToSql};
use serde::{Deserialize, Serialize};
use strum_macros::EnumIter;
use tokio::task;
use crate::aheader::EncryptPreference;
use crate::blob::BlobObject;
use crate::chatlist::Chatlist;
use crate::chatlist_events;
use crate::color::str_to_color;
use crate::config::Config;
use crate::constants::{
self, Blocked, Chattype, DC_CHAT_ID_ALLDONE_HINT, DC_CHAT_ID_ARCHIVED_LINK,
DC_CHAT_ID_LAST_SPECIAL, DC_CHAT_ID_TRASH, DC_RESEND_USER_AVATAR_DAYS,
};
use crate::contact::{self, Contact, ContactId, Origin};
use crate::context::Context;
use crate::debug_logging::maybe_set_logging_xdc;
use crate::download::DownloadState;
use crate::ephemeral::Timer as EphemeralTimer;
use crate::events::EventType;
use crate::html::new_html_mimepart;
use crate::location;
use crate::log::LogExt;
use crate::message::{self, Message, MessageState, MsgId, Viewtype};
use crate::mimefactory::MimeFactory;
use crate::mimeparser::SystemMessage;
use crate::param::{Param, Params};
use crate::peerstate::Peerstate;
use crate::receive_imf::ReceivedMsg;
use crate::securejoin::BobState;
use crate::smtp::send_msg_to_smtp;
use crate::sql;
use crate::stock_str;
use crate::sync::{self, Sync::*, SyncData};
use crate::tools::{
buf_compress, create_id, create_outgoing_rfc724_mid, create_smeared_timestamp,
create_smeared_timestamps, get_abs_path, gm2local_offset, improve_single_line_input,
smeared_time, time, IsNoneOrEmpty, SystemTime,
};
use crate::webxdc::WEBXDC_SUFFIX;
use CantSendReason::*;
use super::*;
use crate::chatlist::get_archived_cnt;
use crate::constants::{DC_GCL_ARCHIVED_ONLY, DC_GCL_NO_SPECIALS};
use crate::message::delete_msgs;
use crate::receive_imf::receive_imf;
use crate::test_utils::{sync, TestContext, TestContextManager};
use strum::IntoEnumIterator;
use tokio::fs; | projects__deltachat-core__rust__chat__.rs__function__8.txt |
projects/deltachat-core/c/dc_mimefactory.c | 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;
} | projects/deltachat-core/rust/mimefactory.rs | pub async fn render(mut self, context: &Context) -> Result<RenderedEmail> {
let mut headers: MessageHeaders = Default::default();
let from = Address::new_mailbox_with_name(
self.from_displayname.to_string(),
self.from_addr.clone(),
);
let undisclosed_recipients = match &self.loaded {
Loaded::Message { chat } => chat.typ == Chattype::Broadcast,
Loaded::Mdn { .. } => false,
};
let mut to = Vec::new();
if undisclosed_recipients {
to.push(Address::new_group(
"hidden-recipients".to_string(),
Vec::new(),
));
} else {
let email_to_remove =
if self.msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup {
self.msg.param.get(Param::Arg)
} else {
None
};
for (name, addr) in &self.recipients {
if let Some(email_to_remove) = email_to_remove {
if email_to_remove == addr {
continue;
}
}
if name.is_empty() {
to.push(Address::new_mailbox(addr.clone()));
} else {
to.push(Address::new_mailbox_with_name(
name.to_string(),
addr.clone(),
));
}
}
if to.is_empty() {
to.push(from.clone());
}
}
// Start with Internet Message Format headers in the order of the standard example
// <https://datatracker.ietf.org/doc/html/rfc5322#appendix-A.1.1>.
let from_header = Header::new_with_value("From".into(), vec![from]).unwrap();
headers.unprotected.push(from_header.clone());
headers.protected.push(from_header);
if let Some(sender_displayname) = &self.sender_displayname {
let sender =
Address::new_mailbox_with_name(sender_displayname.clone(), self.from_addr.clone());
headers
.unprotected
.push(Header::new_with_value("Sender".into(), vec![sender]).unwrap());
}
headers
.unprotected
.push(Header::new_with_value("To".into(), to).unwrap());
let subject_str = self.subject_str(context).await?;
let encoded_subject = if subject_str
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == ' ')
// We do not use needs_encoding() here because needs_encoding() returns true if the string contains a space
// but we do not want to encode all subjects just because they contain a space.
{
subject_str.clone()
} else {
encode_words(&subject_str)
};
headers
.protected
.push(Header::new("Subject".into(), encoded_subject));
let date = chrono::DateTime::<chrono::Utc>::from_timestamp(self.timestamp, 0)
.unwrap()
.to_rfc2822();
headers.unprotected.push(Header::new("Date".into(), date));
let rfc724_mid = match self.loaded {
Loaded::Message { .. } => self.msg.rfc724_mid.clone(),
Loaded::Mdn { .. } => create_outgoing_rfc724_mid(),
};
let rfc724_mid_headervalue = render_rfc724_mid(&rfc724_mid);
let rfc724_mid_header = Header::new("Message-ID".into(), rfc724_mid_headervalue);
headers.unprotected.push(rfc724_mid_header.clone());
headers.hidden.push(rfc724_mid_header);
// Reply headers as in <https://datatracker.ietf.org/doc/html/rfc5322#appendix-A.2>.
if !self.in_reply_to.is_empty() {
headers
.unprotected
.push(Header::new("In-Reply-To".into(), self.in_reply_to.clone()));
}
if !self.references.is_empty() {
headers
.unprotected
.push(Header::new("References".into(), self.references.clone()));
}
// Automatic Response headers <https://www.rfc-editor.org/rfc/rfc3834>
if let Loaded::Mdn { .. } = self.loaded {
headers.unprotected.push(Header::new(
"Auto-Submitted".to_string(),
"auto-replied".to_string(),
));
} else if context.get_config_bool(Config::Bot).await? {
headers.unprotected.push(Header::new(
"Auto-Submitted".to_string(),
"auto-generated".to_string(),
));
}
if let Loaded::Message { chat } = &self.loaded {
if chat.typ == Chattype::Broadcast {
let encoded_chat_name = encode_words(&chat.name);
headers.protected.push(Header::new(
"List-ID".into(),
format!("{encoded_chat_name} <{}>", chat.grpid),
));
}
}
// Non-standard headers.
headers
.unprotected
.push(Header::new("Chat-Version".to_string(), "1.0".to_string()));
if self.req_mdn {
// we use "Chat-Disposition-Notification-To"
// because replies to "Disposition-Notification-To" are weird in many cases
// eg. are just freetext and/or do not follow any standard.
headers.protected.push(Header::new(
"Chat-Disposition-Notification-To".into(),
self.from_addr.clone(),
));
}
let verified = self.verified();
let grpimage = self.grpimage();
let force_plaintext = self.should_force_plaintext();
let skip_autocrypt = self.should_skip_autocrypt();
let e2ee_guaranteed = self.is_e2ee_guaranteed();
let encrypt_helper = EncryptHelper::new(context).await?;
if !skip_autocrypt {
// unless determined otherwise we add the Autocrypt header
let aheader = encrypt_helper.get_aheader().to_string();
headers
.unprotected
.push(Header::new("Autocrypt".into(), aheader));
}
let ephemeral_timer = self.msg.chat_id.get_ephemeral_timer(context).await?;
if let EphemeralTimer::Enabled { duration } = ephemeral_timer {
headers.protected.push(Header::new(
"Ephemeral-Timer".to_string(),
duration.to_string(),
));
}
// MIME header <https://datatracker.ietf.org/doc/html/rfc2045>.
// Content-Type
headers
.unprotected
.push(Header::new("MIME-Version".into(), "1.0".into()));
let mut is_gossiped = false;
let peerstates = self.peerstates_for_recipients(context).await?;
let should_encrypt =
encrypt_helper.should_encrypt(context, e2ee_guaranteed, &peerstates)?;
let is_encrypted = should_encrypt && !force_plaintext;
let (main_part, parts) = match self.loaded {
Loaded::Message { .. } => {
self.render_message(context, &mut headers, &grpimage, is_encrypted)
.await?
}
Loaded::Mdn { .. } => (self.render_mdn(context).await?, Vec::new()),
};
let message = if parts.is_empty() {
// Single part, render as regular message.
main_part
} else {
// Multiple parts, render as multipart.
let part_holder = if self.msg.param.get_cmd() == SystemMessage::MultiDeviceSync {
PartBuilder::new().header((
"Content-Type".to_string(),
"multipart/report; report-type=multi-device-sync".to_string(),
))
} else if self.msg.param.get_cmd() == SystemMessage::WebxdcStatusUpdate {
PartBuilder::new().header((
"Content-Type".to_string(),
"multipart/report; report-type=status-update".to_string(),
))
} else {
PartBuilder::new().message_type(MimeMultipartType::Mixed)
};
parts
.into_iter()
.fold(part_holder.child(main_part.build()), |message, part| {
message.child(part.build())
})
};
let get_content_type_directives_header = || {
(
"Content-Type-Deltachat-Directives".to_string(),
"protected-headers=\"v1\"".to_string(),
)
};
let outer_message = if is_encrypted {
// Store protected headers in the inner message.
let message = headers
.protected
.into_iter()
.fold(message, |message, header| message.header(header));
// Add hidden headers to encrypted payload.
let mut message = headers
.hidden
.into_iter()
.fold(message, |message, header| message.header(header));
// Add gossip headers in chats with multiple recipients
let multiple_recipients =
peerstates.len() > 1 || context.get_config_bool(Config::BccSelf).await?;
if self.should_do_gossip(context, multiple_recipients).await? {
for peerstate in peerstates.iter().filter_map(|(state, _)| state.as_ref()) {
if let Some(header) = peerstate.render_gossip_header(verified) {
message = message.header(Header::new("Autocrypt-Gossip".into(), header));
is_gossiped = true;
}
}
}
// Set the appropriate Content-Type for the inner message.
let mut existing_ct = message
.get_header("Content-Type".to_string())
.and_then(|h| h.get_value::<String>().ok())
.unwrap_or_else(|| "text/plain; charset=utf-8;".to_string());
if !existing_ct.ends_with(';') {
existing_ct += ";";
}
let message = message.header(get_content_type_directives_header());
// Set the appropriate Content-Type for the outer message
let outer_message = PartBuilder::new().header((
"Content-Type".to_string(),
"multipart/encrypted; protocol=\"application/pgp-encrypted\"".to_string(),
));
if std::env::var(crate::DCC_MIME_DEBUG).is_ok() {
info!(
context,
"mimefactory: unencrypted message mime-body:\n{}",
message.clone().build().as_string(),
);
}
// Disable compression for SecureJoin to ensure
// there are no compression side channels
// leaking information about the tokens.
let compress = self.msg.param.get_cmd() != SystemMessage::SecurejoinMessage;
let encrypted = encrypt_helper
.encrypt(context, verified, message, peerstates, compress)
.await?;
outer_message
.child(
// Autocrypt part 1
PartBuilder::new()
.content_type(&"application/pgp-encrypted".parse::<mime::Mime>().unwrap())
.header(("Content-Description", "PGP/MIME version identification"))
.body("Version: 1\r\n")
.build(),
)
.child(
// Autocrypt part 2
PartBuilder::new()
.content_type(
&"application/octet-stream; name=\"encrypted.asc\""
.parse::<mime::Mime>()
.unwrap(),
)
.header(("Content-Description", "OpenPGP encrypted message"))
.header(("Content-Disposition", "inline; filename=\"encrypted.asc\";"))
.body(encrypted)
.build(),
)
.header(("Subject".to_string(), "...".to_string()))
} else if matches!(self.loaded, Loaded::Mdn { .. }) {
// Never add outer multipart/mixed wrapper to MDN
// as multipart/report Content-Type is used to recognize MDNs
// by Delta Chat receiver and Chatmail servers
// allowing them to be unencrypted and not contain Autocrypt header
// without resetting Autocrypt encryption or triggering Chatmail filter
// that normally only allows encrypted mails.
// Hidden headers are dropped.
// Store protected headers in the outer message.
let message = headers
.protected
.iter()
.fold(message, |message, header| message.header(header.clone()));
let protected: HashSet<Header> = HashSet::from_iter(headers.protected.into_iter());
for h in headers.unprotected.split_off(0) {
if !protected.contains(&h) {
headers.unprotected.push(h);
}
}
message
} else {
// Store hidden headers in the inner unencrypted message.
let message = headers
.hidden
.into_iter()
.fold(message, |message, header| message.header(header));
let message = PartBuilder::new()
.message_type(MimeMultipartType::Mixed)
.child(message.build());
// Store protected headers in the outer message.
let message = headers
.protected
.iter()
.fold(message, |message, header| message.header(header.clone()));
if skip_autocrypt || !context.get_config_bool(Config::SignUnencrypted).await? {
let protected: HashSet<Header> = HashSet::from_iter(headers.protected.into_iter());
for h in headers.unprotected.split_off(0) {
if !protected.contains(&h) {
headers.unprotected.push(h);
}
}
message
} else {
let message = message.header(get_content_type_directives_header());
let (payload, signature) = encrypt_helper.sign(context, message).await?;
PartBuilder::new()
.header((
"Content-Type",
"multipart/signed; protocol=\"application/pgp-signature\"",
))
.child(payload)
.child(
PartBuilder::new()
.content_type(
&"application/pgp-signature; name=\"signature.asc\""
.parse::<mime::Mime>()
.unwrap(),
)
.header(("Content-Description", "OpenPGP digital signature"))
.header(("Content-Disposition", "attachment; filename=\"signature\";"))
.body(signature)
.build(),
)
}
};
// Store the unprotected headers on the outer message.
let outer_message = headers
.unprotected
.into_iter()
.fold(outer_message, |message, header| message.header(header));
if std::env::var(crate::DCC_MIME_DEBUG).is_ok() {
info!(
context,
"mimefactory: outgoing message mime-body:\n{}",
outer_message.clone().build().as_string(),
);
}
let MimeFactory {
last_added_location_id,
..
} = self;
Ok(RenderedEmail {
message: outer_message.build().as_string(),
// envelope: Envelope::new,
is_encrypted,
is_gossiped,
last_added_location_id,
sync_ids_to_delete: self.sync_ids_to_delete,
rfc724_mid,
subject: subject_str,
})
} | pub fn is_empty(&self) -> bool {
self.ids.is_empty()
}
async fn render_mdn(&mut self, context: &Context) -> Result<PartBuilder> {
// 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
//
// 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
let additional_msg_ids = match &self.loaded {
Loaded::Message { .. } => bail!("Attempt to render a message as MDN"),
Loaded::Mdn {
additional_msg_ids, ..
} => additional_msg_ids,
};
let mut message = PartBuilder::new().header((
"Content-Type".to_string(),
"multipart/report; report-type=disposition-notification".to_string(),
));
// first body part: always human-readable, always REQUIRED by RFC 6522
let p1 = if 0
!= self
.msg
.param
.get_int(Param::GuaranteeE2ee)
.unwrap_or_default()
{
stock_str::encrypted_msg(context).await
} else {
self.msg
.get_summary(context, None)
.await?
.truncated_text(32)
.to_string()
};
let p2 = stock_str::read_rcpt_mail_body(context, &p1).await;
let message_text = format!("{}\r\n", format_flowed(&p2));
let text_part = PartBuilder::new().header((
"Content-Type".to_string(),
"text/plain; charset=utf-8; format=flowed; delsp=no".to_string(),
));
let text_part = self.add_message_text(text_part, message_text);
message = message.child(text_part.build());
// second body part: machine-readable, always REQUIRED by RFC 6522
let message_text2 = format!(
"Original-Recipient: rfc822;{}\r\n\
Final-Recipient: rfc822;{}\r\n\
Original-Message-ID: <{}>\r\n\
Disposition: manual-action/MDN-sent-automatically; displayed\r\n",
self.from_addr, self.from_addr, self.msg.rfc724_mid
);
let extension_fields = if additional_msg_ids.is_empty() {
"".to_string()
} else {
"Additional-Message-IDs: ".to_string()
+ &additional_msg_ids
.iter()
.map(|mid| render_rfc724_mid(mid))
.collect::<Vec<String>>()
.join(" ")
+ "\r\n"
};
message = message.child(
PartBuilder::new()
.content_type(&"message/disposition-notification".parse().unwrap())
.body(message_text2 + &extension_fields)
.build(),
);
Ok(message)
}
pub(crate) fn create_outgoing_rfc724_mid() -> String {
format!("Mr.{}.{}@localhost", create_id(), create_id())
}
fn encode_words(word: &str) -> String {
encoded_words::encode(word, None, encoded_words::EncodingFlag::Shortest, None)
}
fn render_rfc724_mid(rfc724_mid: &str) -> String {
let rfc724_mid = rfc724_mid.trim().to_string();
if rfc724_mid.chars().next().unwrap_or_default() == '<' {
rfc724_mid
} else {
format!("<{rfc724_mid}>")
}
}
pub enum Chattype {
/// 1:1 chat.
Single = 100,
/// Group chat.
Group = 120,
/// Mailing list.
Mailinglist = 140,
/// Broadcast list.
Broadcast = 160,
}
pub enum Loaded {
Message { chat: Chat },
Mdn { additional_msg_ids: Vec<String> },
}
pub enum SystemMessage {
/// Unknown type of system message.
#[default]
Unknown = 0,
/// Group name changed.
GroupNameChanged = 2,
/// Group avatar changed.
GroupImageChanged = 3,
/// Member was added to the group.
MemberAddedToGroup = 4,
/// Member was removed from the group.
MemberRemovedFromGroup = 5,
/// Autocrypt Setup Message.
AutocryptSetupMessage = 6,
/// Secure-join message.
SecurejoinMessage = 7,
/// Location streaming is enabled.
LocationStreamingEnabled = 8,
/// Location-only message.
LocationOnly = 9,
/// Chat ephemeral message timer is changed.
EphemeralTimerChanged = 10,
/// "Messages are guaranteed to be end-to-end encrypted from now on."
ChatProtectionEnabled = 11,
/// "%1$s sent a message from another device."
ChatProtectionDisabled = 12,
/// Message can't be sent because of `Invalid unencrypted mail to <>`
/// which is sent by chatmail servers.
InvalidUnencryptedMail = 13,
/// 1:1 chats info message telling that SecureJoin has started and the user should wait for it
/// to complete.
SecurejoinWait = 14,
/// 1:1 chats info message telling that SecureJoin is still running, but the user may already
/// send messages.
SecurejoinWaitTimeout = 15,
/// Self-sent-message that contains only json used for multi-device-sync;
/// if possible, we attach that to other messages as for locations.
MultiDeviceSync = 20,
/// Sync message that contains a json payload
/// sent to the other webxdc instances
/// These messages are not shown in the chat.
WebxdcStatusUpdate = 30,
/// Webxdc info added with `info` set in `send_webxdc_status_update()`.
WebxdcInfoMessage = 32,
/// This message contains a users iroh node address.
IrohNodeAddr = 40,
}
pub enum Param {
/// For messages
File = b'f',
/// For messages: original filename (as shown in chat)
Filename = b'v',
/// For messages: This name should be shown instead of contact.get_display_name()
/// (used if this is a mailinglist
/// or explicitly set using set_override_sender_name(), eg. by bots)
OverrideSenderDisplayname = b'O',
/// For Messages
Width = b'w',
/// For Messages
Height = b'h',
/// For Messages
Duration = b'd',
/// For Messages
MimeType = b'm',
/// For Messages: HTML to be written to the database and to be send.
/// `SendHtml` param is not used for received messages.
/// Use `MsgId::get_html()` to get HTML of received messages.
SendHtml = b'T',
/// For Messages: message is encrypted, outgoing: guarantee E2EE or the message is not send
GuaranteeE2ee = b'c',
/// For Messages: quoted message is encrypted.
///
/// If this message is sent unencrypted, quote text should be replaced.
ProtectQuote = b'0',
/// For Messages: decrypted with validation errors or without mutual set, if neither
/// 'c' nor 'e' are preset, the messages is only transport encrypted.
ErroneousE2ee = b'e',
/// For Messages: force unencrypted message, a value from `ForcePlaintext` enum.
ForcePlaintext = b'u',
/// For Messages: do not include Autocrypt header.
SkipAutocrypt = b'o',
/// For Messages
WantsMdn = b'r',
/// For Messages: the message is a reaction.
Reaction = b'x',
/// For Chats: the timestamp of the last reaction.
LastReactionTimestamp = b'y',
/// For Chats: Message ID of the last reaction.
LastReactionMsgId = b'Y',
/// For Chats: Contact ID of the last reaction.
LastReactionContactId = b'1',
/// For Messages: a message with "Auto-Submitted: auto-generated" header ("bot").
Bot = b'b',
/// For Messages: unset or 0=not forwarded,
/// 1=forwarded from unknown msg_id, >9 forwarded from msg_id
Forwarded = b'a',
/// For Messages: quoted text.
Quote = b'q',
/// For Messages
Cmd = b'S',
/// For Messages
Arg = b'E',
/// For Messages
Arg2 = b'F',
/// `Secure-Join-Fingerprint` header for `{vc,vg}-request-with-auth` messages.
Arg3 = b'G',
/// Deprecated `Secure-Join-Group` header for messages.
Arg4 = b'H',
/// For Messages
AttachGroupImage = b'A',
/// For Messages
WebrtcRoom = b'V',
/// For Messages: space-separated list of messaged IDs of forwarded copies.
///
/// This is used when a [crate::message::Message] is in the
/// [crate::message::MessageState::OutPending] state but is already forwarded.
/// In this case the forwarded messages are written to the
/// database and their message IDs are added to this parameter of
/// the original message, which is also saved in the database.
/// When the original message is then finally sent this parameter
/// is used to also send all the forwarded messages.
PrepForwards = b'P',
/// For Messages
SetLatitude = b'l',
/// For Messages
SetLongitude = b'n',
/// For Groups
///
/// An unpromoted group has not had any messages sent to it and thus only exists on the
/// creator's device. Any changes made to an unpromoted group do not need to send
/// system messages to the group members to update them of the changes. Once a message
/// has been sent to a group it is promoted and group changes require sending system
/// messages to all members.
Unpromoted = b'U',
/// For Groups and Contacts
ProfileImage = b'i',
/// For Chats
/// Signals whether the chat is the `saved messages` chat
Selftalk = b'K',
/// For Chats: On sending a new message we set the subject to `Re: <last subject>`.
/// Usually we just use the subject of the parent message, but if the parent message
/// is deleted, we use the LastSubject of the chat.
LastSubject = b't',
/// For Chats
Devicetalk = b'D',
/// For Chats: If this is a mailing list chat, contains the List-Post address.
/// None if there simply is no `List-Post` header in the mailing list.
/// Some("") if the mailing list is using multiple different List-Post headers.
///
/// The List-Post address is the email address where the user can write to in order to
/// post something to the mailing list.
ListPost = b'p',
/// For Contacts: If this is the List-Post address of a mailing list, contains
/// the List-Id of the mailing list (which is also used as the group id of the chat).
ListId = b's',
/// For Contacts: timestamp of status (aka signature or footer) update.
StatusTimestamp = b'j',
/// For Contacts and Chats: timestamp of avatar update.
AvatarTimestamp = b'J',
/// For Chats: timestamp of status/signature/footer update.
EphemeralSettingsTimestamp = b'B',
/// For Chats: timestamp of subject update.
SubjectTimestamp = b'C',
/// For Chats: timestamp of group name update.
GroupNameTimestamp = b'g',
/// For Chats: timestamp of member list update.
MemberListTimestamp = b'k',
/// For Webxdc Message Instances: Current document name
WebxdcDocument = b'R',
/// For Webxdc Message Instances: timestamp of document name update.
WebxdcDocumentTimestamp = b'W',
/// For Webxdc Message Instances: Current summary
WebxdcSummary = b'N',
/// For Webxdc Message Instances: timestamp of summary update.
WebxdcSummaryTimestamp = b'Q',
/// For Webxdc Message Instances: Webxdc is an integration, see init_webxdc_integration()
WebxdcIntegration = b'3',
/// For Webxdc Message Instances: Chat to integrate the Webxdc for.
WebxdcIntegrateFor = b'2',
/// For messages: Whether [crate::message::Viewtype::Sticker] should be forced.
ForceSticker = b'X',
// 'L' was defined as ProtectionSettingsTimestamp for Chats, however, never used in production.
} | use deltachat_contact_tools::ContactAddress;
use mailparse::{addrparse_header, MailHeaderMap};
use std::str;
use super::*;
use crate::chat::{
add_contact_to_chat, create_group_chat, remove_contact_from_chat, send_text_msg, ChatId,
ProtectionStatus,
};
use crate::chatlist::Chatlist;
use crate::constants;
use crate::contact::Origin;
use crate::mimeparser::MimeMessage;
use crate::receive_imf::receive_imf;
use crate::test_utils::{get_chat_msg, TestContext, TestContextManager}; | projects__deltachat-core__rust__mimefactory__.rs__function__13.txt |
projects/deltachat-core/c/dc_msg.c | 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;
} | projects/deltachat-core/rust/summary.rs | async fn get_summary_text_without_prefix(&self, context: &Context) -> String {
let (emoji, type_name, type_file, append_text);
match self.viewtype {
Viewtype::Image => {
emoji = Some("📷");
type_name = Some(stock_str::image(context).await);
type_file = None;
append_text = true;
}
Viewtype::Gif => {
emoji = None;
type_name = Some(stock_str::gif(context).await);
type_file = None;
append_text = true;
}
Viewtype::Sticker => {
emoji = None;
type_name = Some(stock_str::sticker(context).await);
type_file = None;
append_text = true;
}
Viewtype::Video => {
emoji = Some("🎥");
type_name = Some(stock_str::video(context).await);
type_file = None;
append_text = true;
}
Viewtype::Voice => {
emoji = Some("🎤");
type_name = Some(stock_str::voice_message(context).await);
type_file = None;
append_text = true;
}
Viewtype::Audio => {
emoji = Some("🎵");
type_name = Some(stock_str::audio(context).await);
type_file = self.get_filename();
append_text = true
}
Viewtype::File => {
if self.param.get_cmd() == SystemMessage::AutocryptSetupMessage {
emoji = None;
type_name = Some(stock_str::ac_setup_msg_subject(context).await);
type_file = None;
append_text = false;
} else {
emoji = Some("📎");
type_name = Some(stock_str::file(context).await);
type_file = self.get_filename();
append_text = true
}
}
Viewtype::VideochatInvitation => {
emoji = None;
type_name = Some(stock_str::videochat_invitation(context).await);
type_file = None;
append_text = false;
}
Viewtype::Webxdc => {
emoji = None;
type_name = None;
type_file = Some(
self.get_webxdc_info(context)
.await
.map(|info| info.name)
.unwrap_or_else(|_| "ErrWebxdcName".to_string()),
);
append_text = true;
}
Viewtype::Vcard => {
emoji = Some("👤");
type_name = Some(stock_str::contact(context).await);
type_file = None;
append_text = true;
}
Viewtype::Text | Viewtype::Unknown => {
emoji = None;
if self.param.get_cmd() == SystemMessage::LocationOnly {
type_name = Some(stock_str::location(context).await);
type_file = None;
append_text = false;
} else {
type_name = None;
type_file = None;
append_text = true;
}
}
};
let text = self.text.clone();
let summary = if let Some(type_file) = type_file {
if append_text && !text.is_empty() {
format!("{type_file} – {text}")
} else {
type_file
}
} else if append_text && !text.is_empty() {
if emoji.is_some() {
text
} else if let Some(type_name) = type_name {
format!("{type_name} – {text}")
} else {
text
}
} else if let Some(type_name) = type_name {
type_name
} else {
"".to_string()
};
let summary = if let Some(emoji) = emoji {
format!("{emoji} {summary}")
} else {
summary
};
summary.split_whitespace().collect::<Vec<&str>>().join(" ")
} | pub(crate) async fn voice_message(context: &Context) -> String {
translated(context, StockMessage::VoiceMessage).await
}
pub(crate) async fn image(context: &Context) -> String {
translated(context, StockMessage::Image).await
}
pub(crate) async fn video(context: &Context) -> String {
translated(context, StockMessage::Video).await
}
pub(crate) async fn audio(context: &Context) -> String {
translated(context, StockMessage::Audio).await
}
pub(crate) async fn file(context: &Context) -> String {
translated(context, StockMessage::File).await
}
pub(crate) async fn gif(context: &Context) -> String {
translated(context, StockMessage::Gif).await
}
pub(crate) async fn sticker(context: &Context) -> String {
translated(context, StockMessage::Sticker).await
}
pub(crate) async fn location(context: &Context) -> String {
translated(context, StockMessage::Location).await
}
pub(crate) async fn ac_setup_msg_subject(context: &Context) -> String {
translated(context, StockMessage::AcSetupMsgSubject).await
}
pub(crate) async fn videochat_invitation(context: &Context) -> String {
translated(context, StockMessage::VideochatInvitation).await
}
pub(crate) async fn contact(context: &Context) -> String {
translated(context, StockMessage::Contact).await
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub fn get_cmd(&self) -> SystemMessage {
self.get_int(Param::Cmd)
.and_then(SystemMessage::from_i32)
.unwrap_or_default()
}
pub fn get_filename(&self) -> Option<String> {
if let Some(name) = self.param.get(Param::Filename) {
return Some(name.to_string());
}
self.param
.get(Param::File)
.and_then(|file| Path::new(file).file_name())
.map(|name| name.to_string_lossy().to_string())
}
pub struct Context {
pub(crate) inner: Arc<InnerContext>,
}
pub struct Message {
/// Message ID.
pub(crate) id: MsgId,
/// `From:` contact ID.
pub(crate) from_id: ContactId,
/// ID of the first contact in the `To:` header.
pub(crate) to_id: ContactId,
/// ID of the chat message belongs to.
pub(crate) chat_id: ChatId,
/// Type of the message.
pub(crate) viewtype: Viewtype,
/// State of the message.
pub(crate) state: MessageState,
pub(crate) download_state: DownloadState,
/// Whether the message is hidden.
pub(crate) hidden: bool,
pub(crate) timestamp_sort: i64,
pub(crate) timestamp_sent: i64,
pub(crate) timestamp_rcvd: i64,
pub(crate) ephemeral_timer: EphemeralTimer,
pub(crate) ephemeral_timestamp: i64,
pub(crate) text: String,
/// Message subject.
///
/// If empty, a default subject will be generated when sending.
pub(crate) subject: String,
/// `Message-ID` header value.
pub(crate) rfc724_mid: String,
/// `In-Reply-To` header value.
pub(crate) in_reply_to: Option<String>,
pub(crate) is_dc_message: MessengerMessage,
pub(crate) mime_modified: bool,
pub(crate) chat_blocked: Blocked,
pub(crate) location_id: u32,
pub(crate) error: Option<String>,
pub(crate) param: Params,
}
pub enum Viewtype {
/// Unknown message type.
#[default]
Unknown = 0,
/// Text message.
/// The text of the message is set using dc_msg_set_text() and retrieved with dc_msg_get_text().
Text = 10,
/// Image message.
/// If the image is a GIF and has the appropriate extension, the viewtype is auto-changed to
/// `Gif` when sending the message.
/// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension
/// and retrieved via dc_msg_set_file(), dc_msg_set_dimension().
Image = 20,
/// Animated GIF message.
/// File, width and height are set via dc_msg_set_file(), dc_msg_set_dimension()
/// and retrieved via dc_msg_get_file(), dc_msg_get_width(), dc_msg_get_height().
Gif = 21,
/// Message containing a sticker, similar to image.
/// If possible, the ui should display the image without borders in a transparent way.
/// A click on a sticker will offer to install the sticker set in some future.
Sticker = 23,
/// Message containing an Audio file.
/// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()
/// and retrieved via dc_msg_get_file(), dc_msg_get_duration().
Audio = 40,
/// A voice message that was directly recorded by the user.
/// For all other audio messages, the type #DC_MSG_AUDIO should be used.
/// File and duration are set via dc_msg_set_file(), dc_msg_set_duration()
/// and retrieved via dc_msg_get_file(), dc_msg_get_duration()
Voice = 41,
/// Video messages.
/// File, width, height and durarion
/// are set via dc_msg_set_file(), dc_msg_set_dimension(), dc_msg_set_duration()
/// and retrieved via
/// dc_msg_get_file(), dc_msg_get_width(),
/// dc_msg_get_height(), dc_msg_get_duration().
Video = 50,
/// Message containing any file, eg. a PDF.
/// The file is set via dc_msg_set_file()
/// and retrieved via dc_msg_get_file().
File = 60,
/// Message is an invitation to a videochat.
VideochatInvitation = 70,
/// Message is an webxdc instance.
Webxdc = 80,
/// Message containing shared contacts represented as a vCard (virtual contact file)
/// with email addresses and possibly other fields.
/// Use `parse_vcard()` to retrieve them.
Vcard = 90,
} | use std::borrow::Cow;
use std::fmt;
use std::str;
use crate::chat::Chat;
use crate::constants::Chattype;
use crate::contact::{Contact, ContactId};
use crate::context::Context;
use crate::message::{Message, MessageState, Viewtype};
use crate::mimeparser::SystemMessage;
use crate::stock_str;
use crate::stock_str::msg_reacted;
use crate::tools::truncate;
use anyhow::Result;
use super::*;
use crate::param::Param;
use crate::test_utils as test; | projects__deltachat-core__rust__summary__.rs__function__6.txt |
projects/incubator-milagro-crypto/c/src/ecdh_support.c | void KDF2(int sha,const octet *z,const octet *p,int olen,octet *key)
{
/* NOTE: the parameter olen is the length of the output k in bytes */
char h[64];
octet H= {0,sizeof(h),h};
int cthreshold;
int hlen=sha;
OCT_empty(key);
cthreshold=ROUNDUP(olen,hlen);
for (int counter=1; counter<=cthreshold; counter++)
{
ehashit(sha,z,counter,p,&H,0);
if (key->len+hlen>olen) OCT_jbytes(key,H.val,olen%hlen);
else OCT_joctet(key,&H);
}
} | projects/incubator-milagro-crypto/rust/src/ecdh.rs | pub fn kdf2(sha: usize, z: &[u8], p: Option<&[u8]>, olen: usize, k: &mut [u8]) {
// NOTE: the parameter olen is the length of the output K in bytes
let hlen = sha;
let mut lk = 0;
let mut cthreshold = olen / hlen;
if olen % hlen != 0 {
cthreshold += 1
}
for counter in 1..=cthreshold {
let mut b: [u8; 64] = [0; 64];
hashit(sha, z, counter, p, 0, &mut b);
if lk + hlen > olen {
for i in 0..(olen % hlen) {
k[lk] = b[i];
lk += 1
}
} else {
for i in 0..hlen {
k[lk] = b[i];
lk += 1
}
}
}
} | fn hashit(sha: usize, a: &[u8], n: usize, b: Option<&[u8]>, pad: usize, w: &mut [u8]) {
let mut r: [u8; 64] = [0; 64];
if sha == SHA256 {
let mut h = HASH256::new();
h.process_array(a);
if n > 0 {
h.process_num(n as i32)
}
if let Some(x) = b {
h.process_array(x);
}
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
}
if sha == SHA384 {
let mut h = HASH384::new();
h.process_array(a);
if n > 0 {
h.process_num(n as i32)
}
if let Some(x) = b {
h.process_array(x);
}
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
}
if sha == SHA512 {
let mut h = HASH512::new();
h.process_array(a);
if n > 0 {
h.process_num(n as i32)
}
if let Some(x) = b {
h.process_array(x);
}
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
}
if pad == 0 {
for i in 0..sha {
w[i] = r[i]
}
} else {
if pad <= sha {
for i in 0..pad {
w[i] = r[i]
}
} else {
for i in 0..sha {
w[i + pad - sha] = r[i]
}
for i in 0..(pad - sha) {
w[i] = 0
}
}
}
} | use super::big;
use super::big::Big;
use super::ecp;
use super::ecp::ECP;
use super::rom;
use crate::aes;
use crate::aes::AES;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*;
use crate::types::CurveType; | projects__incubator-milagro-crypto__rust__src__ecdh__.rs__function__4.txt |
projects/incubator-milagro-crypto/c/src/pbc_support.c | unsign32 today(void)
{
/* return time in slots since epoch */
unsign32 ti=(unsign32)time(NULL);
return ti/(60*TIME_SLOT_MINUTES);
} | projects/incubator-milagro-crypto/rust/src/mpin256.rs | pub fn today() -> usize {
return (SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
/ (60 * 1440)) as usize;
} | use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use super::big;
use super::big::Big;
use super::ecp;
use super::ecp::ECP;
use super::ecp8::ECP8;
use super::fp16::FP16;
use super::fp48::FP48;
use super::pair256;
use super::rom;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*; | projects__incubator-milagro-crypto__rust__src__mpin256__.rs__function__3.txt | |
projects/incubator-milagro-crypto/c/src/pbc_support.c | void HASH_ALL(int sha,const octet *HID,const octet *xID,const octet *xCID,const octet *SEC,const octet *Y,const octet *R,const octet *W,octet *H)
{
char t[1284]; // assumes max modulus of 1024-bits
octet T= {0,sizeof(t),t};
OCT_joctet(&T,HID);
if (xCID!=NULL) OCT_joctet(&T,xCID);
else OCT_joctet(&T,xID);
OCT_joctet(&T,SEC);
OCT_joctet(&T,Y);
OCT_joctet(&T,R);
OCT_joctet(&T,W);
mhashit(sha,0,&T,H);
} | projects/incubator-milagro-crypto/rust/src/mpin192.rs | pub fn hash_all(
sha: usize,
hid: &[u8],
xid: &[u8],
xcid: Option<&[u8]>,
sec: &[u8],
y: &[u8],
r: &[u8],
w: &[u8],
h: &mut [u8],
) -> bool {
let mut tlen: usize = 0;
const RM: usize = big::MODBYTES as usize;
let mut t: [u8; 10 * RM + 4] = [0; 10 * RM + 4];
for i in 0..hid.len() {
t[i] = hid[i]
}
tlen += hid.len();
if let Some(rxcid) = xcid {
for i in 0..rxcid.len() {
t[i + tlen] = rxcid[i]
}
tlen += rxcid.len();
} else {
for i in 0..xid.len() {
t[i + tlen] = xid[i]
}
tlen += xid.len();
}
for i in 0..sec.len() {
t[i + tlen] = sec[i]
}
tlen += sec.len();
for i in 0..y.len() {
t[i + tlen] = y[i]
}
tlen += y.len();
for i in 0..r.len() {
t[i + tlen] = r[i]
}
tlen += r.len();
for i in 0..w.len() {
t[i + tlen] = w[i]
}
tlen += w.len();
if tlen != 10 * RM + 4 {
return false;
}
return hashit(sha, 0, &t, h);
} | fn hashit(sha: usize, n: usize, id: &[u8], w: &mut [u8]) -> bool {
let mut r: [u8; 64] = [0; 64];
let mut didit = false;
if sha == SHA256 {
let mut h = HASH256::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if sha == SHA384 {
let mut h = HASH384::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if sha == SHA512 {
let mut h = HASH512::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if !didit {
return false;
}
let rm = big::MODBYTES as usize;
if sha > rm {
for i in 0..rm {
w[i] = r[i]
}
} else {
for i in 0..sha {
w[i + rm - sha] = r[i]
}
for i in 0..(rm - sha) {
w[i] = 0
}
}
return true;
} | use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use super::big;
use super::big::Big;
use super::ecp;
use super::ecp::ECP;
use super::ecp4::ECP4;
use super::fp24::FP24;
use super::fp8::FP8;
use super::pair192;
use super::rom;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*; | projects__incubator-milagro-crypto__rust__src__mpin192__.rs__function__27.txt |
projects/incubator-milagro-crypto/c/src/rsa_support.c | int OAEP_ENCODE(int sha,const octet *m,csprng *RNG,const octet *p,octet *f)
{
int slen;
int olen=f->max-1;
int mlen=m->len;
int hlen;
int seedlen;
char dbmask[MAX_RSA_BYTES];
char seed[64];
octet DBMASK= {0,sizeof(dbmask),dbmask};
octet SEED= {0,sizeof(seed),seed};
hlen=seedlen=sha;
if (mlen>olen-hlen-seedlen-1) return 1;
if (m==f) return 1; /* must be distinct octets */
hashit(sha,p,-1,f);
slen=olen-mlen-hlen-seedlen-1;
OCT_jbyte(f,0,slen);
OCT_jbyte(f,0x1,1);
OCT_joctet(f,m);
OCT_rand(&SEED,RNG,seedlen);
MGF1(sha,&SEED,olen-seedlen,&DBMASK);
OCT_xor(&DBMASK,f);
MGF1(sha,&DBMASK,seedlen,f);
OCT_xor(f,&SEED);
OCT_joctet(f,&DBMASK);
OCT_pad(f,f->max);
OCT_clear(&SEED);
OCT_clear(&DBMASK);
return 0;
} | projects/incubator-milagro-crypto/rust/src/rsa.rs | pub fn oaep_encode(sha: usize, m: &[u8], rng: &mut RAND, p: Option<&[u8]>, f: &mut [u8]) -> bool {
let olen = RFS - 1;
let mlen = m.len();
let hlen = sha;
let mut seed: [u8; 64] = [0; 64];
let seedlen = hlen;
if mlen > olen - hlen - seedlen - 1 {
return false;
}
let mut dbmask: [u8; RFS] = [0; RFS];
hashit(sha, p, -1, f);
let slen = olen - mlen - hlen - seedlen - 1;
for i in 0..slen {
f[hlen + i] = 0
}
f[hlen + slen] = 1;
for i in 0..mlen {
f[hlen + slen + 1 + i] = m[i]
}
for i in 0..seedlen {
seed[i] = rng.getbyte()
}
mgf1(sha, &seed, olen - seedlen, &mut dbmask);
for i in 0..olen - seedlen {
dbmask[i] ^= f[i]
}
mgf1(sha, &dbmask[0..olen - seedlen], seedlen, f);
for i in 0..seedlen {
f[i] ^= seed[i]
}
for i in 0..olen - seedlen {
f[i + seedlen] = dbmask[i]
}
/* pad to length RFS */
let d = 1;
for i in (d..RFS).rev() {
f[i] = f[i - d];
}
for i in (0..d).rev() {
f[i] = 0;
}
return true;
} | fn hashit(sha: usize, a: Option<&[u8]>, n: isize, w: &mut [u8]) {
if sha == SHA256 {
let mut h = HASH256::new();
if let Some(x) = a {
h.process_array(x);
}
if n >= 0 {
h.process_num(n as i32)
}
let hs = h.hash();
for i in 0..sha {
w[i] = hs[i]
}
}
if sha == SHA384 {
let mut h = HASH384::new();
if let Some(x) = a {
h.process_array(x);
}
if n >= 0 {
h.process_num(n as i32)
}
let hs = h.hash();
for i in 0..sha {
w[i] = hs[i]
}
}
if sha == SHA512 {
let mut h = HASH512::new();
if let Some(x) = a {
h.process_array(x);
}
if n >= 0 {
h.process_num(n as i32)
}
let hs = h.hash();
for i in 0..sha {
w[i] = hs[i]
}
}
}
pub fn mgf1(sha: usize, z: &[u8], olen: usize, k: &mut [u8]) {
let hlen = sha;
let mut j = 0;
for i in 0..k.len() {
k[i] = 0
}
let mut cthreshold = olen / hlen;
if olen % hlen != 0 {
cthreshold += 1
}
for counter in 0..cthreshold {
let mut b: [u8; 64] = [0; 64];
hashit(sha, Some(z), counter as isize, &mut b);
if j + hlen > olen {
for i in 0..(olen % hlen) {
k[j] = b[i];
j += 1
}
} else {
for i in 0..hlen {
k[j] = b[i];
j += 1
}
}
}
}
pub fn getbyte(&mut self) -> u8 {
let r = self.pool[self.pool_ptr];
self.pool_ptr += 1;
if self.pool_ptr >= 32 {
self.fill_pool()
}
return u8::from(r);
}
pub struct RAND {
ira: [u32; RAND_NK], /* random number... */
rndptr: usize,
borrow: u32,
pool_ptr: usize,
pool: [u8; 32],
}
pub const RFS: usize = (big::MODBYTES as usize) * ff::FFLEN; | use super::big;
use super::ff;
use super::ff::FF;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*; | projects__incubator-milagro-crypto__rust__src__rsa__.rs__function__7.txt |
projects/incubator-milagro-crypto/c/src/pbc_support.c | void HASH_ALL(int sha,const octet *HID,const octet *xID,const octet *xCID,const octet *SEC,const octet *Y,const octet *R,const octet *W,octet *H)
{
char t[1284]; // assumes max modulus of 1024-bits
octet T= {0,sizeof(t),t};
OCT_joctet(&T,HID);
if (xCID!=NULL) OCT_joctet(&T,xCID);
else OCT_joctet(&T,xID);
OCT_joctet(&T,SEC);
OCT_joctet(&T,Y);
OCT_joctet(&T,R);
OCT_joctet(&T,W);
mhashit(sha,0,&T,H);
} | projects/incubator-milagro-crypto/rust/src/mpin.rs | pub fn hash_all(
sha: usize,
hid: &[u8],
xid: &[u8],
xcid: Option<&[u8]>,
sec: &[u8],
y: &[u8],
r: &[u8],
w: &[u8],
h: &mut [u8],
) -> bool {
let mut tlen: usize = 0;
const RM: usize = big::MODBYTES as usize;
let mut t: [u8; 10 * RM + 4] = [0; 10 * RM + 4];
for i in 0..hid.len() {
t[i] = hid[i]
}
tlen += hid.len();
if let Some(rxcid) = xcid {
for i in 0..rxcid.len() {
t[i + tlen] = rxcid[i]
}
tlen += rxcid.len();
} else {
for i in 0..xid.len() {
t[i + tlen] = xid[i]
}
tlen += xid.len();
}
for i in 0..sec.len() {
t[i + tlen] = sec[i]
}
tlen += sec.len();
for i in 0..y.len() {
t[i + tlen] = y[i]
}
tlen += y.len();
for i in 0..r.len() {
t[i + tlen] = r[i]
}
tlen += r.len();
for i in 0..w.len() {
t[i + tlen] = w[i]
}
tlen += w.len();
if tlen != 10 * RM + 4 {
return false;
}
return hashit(sha, 0, &t, h);
} | fn hashit(sha: usize, n: usize, id: &[u8], w: &mut [u8]) -> bool {
let mut r: [u8; 64] = [0; 64];
let mut didit = false;
if sha == SHA256 {
let mut h = HASH256::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if sha == SHA384 {
let mut h = HASH384::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if sha == SHA512 {
let mut h = HASH512::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if !didit {
return false;
}
let rm = big::MODBYTES as usize;
if sha > rm {
for i in 0..rm {
w[i] = r[i]
}
} else {
for i in 0..sha {
w[i + rm - sha] = r[i]
}
for i in 0..(rm - sha) {
w[i] = 0
}
}
return true;
} | use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use super::big;
use super::big::Big;
use super::ecp;
use super::ecp::ECP;
use super::ecp2::ECP2;
use super::fp12::FP12;
use super::fp4::FP4;
use super::pair;
use super::rom;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*; | projects__incubator-milagro-crypto__rust__src__mpin__.rs__function__27.txt |
projects/incubator-milagro-crypto/c/src/pbc_support.c | unsign32 today(void)
{
/* return time in slots since epoch */
unsign32 ti=(unsign32)time(NULL);
return ti/(60*TIME_SLOT_MINUTES);
} | projects/incubator-milagro-crypto/rust/src/mpin192.rs | pub fn today() -> usize {
return (SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
/ (60 * 1440)) as usize;
} | use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use super::big;
use super::big::Big;
use super::ecp;
use super::ecp::ECP;
use super::ecp4::ECP4;
use super::fp24::FP24;
use super::fp8::FP8;
use super::pair192;
use super::rom;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*; | projects__incubator-milagro-crypto__rust__src__mpin192__.rs__function__3.txt | |
projects/incubator-milagro-crypto/c/src/pbc_support.c | unsign32 today(void)
{
/* return time in slots since epoch */
unsign32 ti=(unsign32)time(NULL);
return ti/(60*TIME_SLOT_MINUTES);
} | projects/incubator-milagro-crypto/rust/src/mpin.rs | pub fn today() -> usize {
return (SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
/ (60 * 1440)) as usize;
} | use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use super::big;
use super::big::Big;
use super::ecp;
use super::ecp::ECP;
use super::ecp2::ECP2;
use super::fp12::FP12;
use super::fp4::FP4;
use super::pair;
use super::rom;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*; | projects__incubator-milagro-crypto__rust__src__mpin__.rs__function__3.txt | |
projects/incubator-milagro-crypto/c/src/ecdh_support.c | void PBKDF2(int sha,const octet *p,octet *s,int rep,int olen,octet *key)
{
int len;
int d=ROUNDUP(olen,sha);
char f[64];
char u[64];
octet F= {0,sizeof(f),f};
octet U= {0,sizeof(u),u};
OCT_empty(key);
for (int i=1; i<=d; i++)
{
len=s->len;
OCT_jint(s,i,4);
HMAC(sha,s,p,sha,&F);
s->len=len;
OCT_copy(&U,&F);
for (int j=2; j<=rep; j++)
{
HMAC(sha,&U,p,sha,&U);
OCT_xor(&F,&U);
}
OCT_joctet(key,&F);
}
OCT_chop(key,NULL,olen);
} | projects/incubator-milagro-crypto/rust/src/ecdh.rs | pub fn pbkdf2(sha: usize, pass: &[u8], salt: &[u8], rep: usize, olen: usize, k: &mut [u8]) {
let mut d = olen / sha;
if olen % sha != 0 {
d += 1
}
let mut f: [u8; 64] = [0; 64];
let mut u: [u8; 64] = [0; 64];
let mut ku: [u8; 64] = [0; 64];
let mut s: [u8; 36] = [0; 36]; // Maximum salt of 32 bytes + 4
let mut n: [u8; 4] = [0; 4];
let sl = salt.len();
let mut kp = 0;
for i in 0..d {
for j in 0..sl {
s[j] = salt[j]
}
intto_bytes(i + 1, &mut n);
for j in 0..4 {
s[sl + j] = n[j]
}
hmac(sha, &s[0..sl + 4], pass, sha, &mut f);
for j in 0..sha {
u[j] = f[j]
}
for _ in 1..rep {
hmac(sha, &u, pass, sha, &mut ku);
for k in 0..sha {
u[k] = ku[k];
f[k] ^= u[k]
}
}
for j in 0..EFS {
if kp < olen && kp < f.len() {
k[kp] = f[j]
}
kp += 1
}
}
} | pub fn hmac(sha: usize, m: &[u8], k: &[u8], olen: usize, tag: &mut [u8]) -> bool {
// Input is from an octet m
// olen is requested output length in bytes. k is the key
// The output is the calculated tag
let mut b: [u8; 64] = [0; 64]; // Not good
let mut k0: [u8; 128] = [0; 128];
if olen < 4 {
return false;
}
let mut lb = 64;
if sha > 32 {
lb = 128
}
for i in 0..lb {
k0[i] = 0
}
if k.len() > lb {
hashit(sha, k, 0, None, 0, &mut b);
for i in 0..sha {
k0[i] = b[i]
}
} else {
for i in 0..k.len() {
k0[i] = k[i]
}
}
for i in 0..lb {
k0[i] ^= 0x36
}
hashit(sha, &k0[0..lb], 0, Some(m), 0, &mut b);
for i in 0..lb {
k0[i] ^= 0x6a
}
hashit(sha, &k0[0..lb], 0, Some(&b[0..sha]), olen, tag);
return true;
}
fn intto_bytes(n: usize, b: &mut [u8]) {
let mut i = b.len();
let mut m = n;
while m > 0 && i > 0 {
i -= 1;
b[i] = (m & 0xff) as u8;
m /= 256;
}
} | use super::big;
use super::big::Big;
use super::ecp;
use super::ecp::ECP;
use super::rom;
use crate::aes;
use crate::aes::AES;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*;
use crate::types::CurveType; | projects__incubator-milagro-crypto__rust__src__ecdh__.rs__function__5.txt |
projects/incubator-milagro-crypto/c/src/pbc_support.c | void HASH_ALL(int sha,const octet *HID,const octet *xID,const octet *xCID,const octet *SEC,const octet *Y,const octet *R,const octet *W,octet *H)
{
char t[1284]; // assumes max modulus of 1024-bits
octet T= {0,sizeof(t),t};
OCT_joctet(&T,HID);
if (xCID!=NULL) OCT_joctet(&T,xCID);
else OCT_joctet(&T,xID);
OCT_joctet(&T,SEC);
OCT_joctet(&T,Y);
OCT_joctet(&T,R);
OCT_joctet(&T,W);
mhashit(sha,0,&T,H);
} | projects/incubator-milagro-crypto/rust/src/mpin256.rs | pub fn hash_all(
sha: usize,
hid: &[u8],
xid: &[u8],
xcid: Option<&[u8]>,
sec: &[u8],
y: &[u8],
r: &[u8],
w: &[u8],
h: &mut [u8],
) -> bool {
let mut tlen: usize = 0;
const RM: usize = big::MODBYTES as usize;
let mut t: [u8; 10 * RM + 4] = [0; 10 * RM + 4];
for i in 0..hid.len() {
t[i] = hid[i]
}
tlen += hid.len();
if let Some(rxcid) = xcid {
for i in 0..rxcid.len() {
t[i + tlen] = rxcid[i]
}
tlen += rxcid.len();
} else {
for i in 0..xid.len() {
t[i + tlen] = xid[i]
}
tlen += xid.len();
}
for i in 0..sec.len() {
t[i + tlen] = sec[i]
}
tlen += sec.len();
for i in 0..y.len() {
t[i + tlen] = y[i]
}
tlen += y.len();
for i in 0..r.len() {
t[i + tlen] = r[i]
}
tlen += r.len();
for i in 0..w.len() {
t[i + tlen] = w[i]
}
tlen += w.len();
if tlen != 10 * RM + 4 {
return false;
}
return hashit(sha, 0, &t, h);
} | fn hashit(sha: usize, n: usize, id: &[u8], w: &mut [u8]) -> bool {
let mut r: [u8; 64] = [0; 64];
let mut didit = false;
if sha == SHA256 {
let mut h = HASH256::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if sha == SHA384 {
let mut h = HASH384::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if sha == SHA512 {
let mut h = HASH512::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if !didit {
return false;
}
let rm = big::MODBYTES as usize;
if sha > rm {
for i in 0..rm {
w[i] = r[i]
}
} else {
for i in 0..sha {
w[i + rm - sha] = r[i]
}
for i in 0..(rm - sha) {
w[i] = 0
}
}
return true;
} | use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use super::big;
use super::big::Big;
use super::ecp;
use super::ecp::ECP;
use super::ecp8::ECP8;
use super::fp16::FP16;
use super::fp48::FP48;
use super::pair256;
use super::rom;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*; | projects__incubator-milagro-crypto__rust__src__mpin256__.rs__function__27.txt |
projects/incubator-milagro-crypto/c/src/hash.c | void HASH512_hash(hash512 *sh,char *hash)
{
/* pad message and finish - supply digest */
unsign64 len0;
unsign64 len1;
len0=sh->length[0];
len1=sh->length[1];
HASH512_process(sh,PAD);
while ((sh->length[0]%1024)!=896) HASH512_process(sh,ZERO);
sh->w[14]=len1;
sh->w[15]=len0;
HASH512_transform(sh);
for (int i=0; i<sh->hlen; i++)
{
/* convert to bytes */
hash[i]=(char)((sh->h[i/8]>>(8*(7-i%8))) & 0xffL);
}
HASH512_init(sh);
} | projects/incubator-milagro-crypto/rust/src/hash512.rs | pub fn hash(&mut self) -> [u8; 64] {
/* pad message and finish - supply digest */
let mut digest: [u8; 64] = [0; 64];
let len0 = self.length[0];
let len1 = self.length[1];
self.process(0x80);
while (self.length[0] % 1024) != 896 {
self.process(0)
}
self.w[14] = len1;
self.w[15] = len0;
self.transform();
for i in 0..64 {
/* convert to bytes */
digest[i] = ((self.h[i / 8] >> (8 * (7 - i % 8))) & 0xff) as u8;
}
self.init();
return digest;
} | fn transform(&mut self) {
/* basic transformation step */
for j in 16..80 {
self.w[j] = Self::theta1(self.w[j - 2])
.wrapping_add(self.w[j - 7])
.wrapping_add(Self::theta0(self.w[j - 15]))
.wrapping_add(self.w[j - 16]);
}
let mut a = self.h[0];
let mut b = self.h[1];
let mut c = self.h[2];
let mut d = self.h[3];
let mut e = self.h[4];
let mut f = self.h[5];
let mut g = self.h[6];
let mut hh = self.h[7];
for j in 0..80 {
/* 64 times - mush it up */
let t1 = hh
.wrapping_add(Self::sig1(e))
.wrapping_add(Self::ch(e, f, g))
.wrapping_add(HASH512_K[j])
.wrapping_add(self.w[j]);
let t2 = Self::sig0(a).wrapping_add(Self::maj(a, b, c));
hh = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
self.h[0] = self.h[0].wrapping_add(a);
self.h[1] = self.h[1].wrapping_add(b);
self.h[2] = self.h[2].wrapping_add(c);
self.h[3] = self.h[3].wrapping_add(d);
self.h[4] = self.h[4].wrapping_add(e);
self.h[5] = self.h[5].wrapping_add(f);
self.h[6] = self.h[6].wrapping_add(g);
self.h[7] = self.h[7].wrapping_add(hh);
}
pub fn init(&mut self) {
/* initialise */
for i in 0..64 {
self.w[i] = 0
}
self.length[0] = 0;
self.length[1] = 0;
self.h[0] = HASH512_H0;
self.h[1] = HASH512_H1;
self.h[2] = HASH512_H2;
self.h[3] = HASH512_H3;
self.h[4] = HASH512_H4;
self.h[5] = HASH512_H5;
self.h[6] = HASH512_H6;
self.h[7] = HASH512_H7;
}
pub fn process(&mut self, byt: u8) {
/* process the next message byte */
let cnt = ((self.length[0] / 64) % 16) as usize;
self.w[cnt] <<= 8;
self.w[cnt] |= (byt & 0xFF) as u64;
self.length[0] += 8;
if self.length[0] == 0 {
self.length[1] += 1;
self.length[0] = 0
}
if (self.length[0] % 1024) == 0 {
self.transform()
}
}
pub struct HASH512 {
length: [u64; 2],
h: [u64; 8],
w: [u64; 80],
} | use super::*; | projects__incubator-milagro-crypto__rust__src__hash512__.rs__function__15.txt |
projects/incubator-milagro-crypto/c/src/rand.c | void RAND_seed(csprng *rng,int rawlen,const char *raw)
{
/* initialise from at least 128 byte string of raw *
* random (keyboard?) input, and 32-bit time-of-day */
int i;
char digest[32];
uchar b[4];
hash256 sh;
rng->pool_ptr=0;
for (i=0; i<NK; i++) rng->ira[i]=0;
if (rawlen>0)
{
HASH256_init(&sh);
for (i=0; i<rawlen; i++)
HASH256_process(&sh,raw[i]);
HASH256_hash(&sh,digest);
/* initialise PRNG from distilled randomness */
for (i=0; i<8; i++)
{
b[0]=digest[4*i];
b[1]=digest[4*i+1];
b[2]=digest[4*i+2];
b[3]=digest[4*i+3];
sirand(rng,pack(b));
}
}
fill_pool(rng);
} | projects/incubator-milagro-crypto/rust/src/rand.rs | pub fn seed(&mut self, rawlen: usize, raw: &[u8]) {
/* initialise from at least 128 byte string of raw random entropy */
let mut b: [u8; 4] = [0; 4];
let mut sh = HASH256::new();
self.pool_ptr = 0;
for i in 0..RAND_NK {
self.ira[i] = 0
}
if rawlen > 0 {
for i in 0..rawlen {
sh.process(raw[i]);
}
let digest = sh.hash();
/* initialise PRNG from distilled randomness */
for i in 0..8 {
b[0] = digest[4 * i];
b[1] = digest[4 * i + 1];
b[2] = digest[4 * i + 2];
b[3] = digest[4 * i + 3];
self.sirand(RAND::pack(b));
}
}
self.fill_pool();
} | fn sirand(&mut self, seed: u32) {
let mut m: u32 = 1;
let mut sd = seed;
self.borrow = 0;
self.rndptr = 0;
self.ira[0] ^= sd;
for i in 1..RAND_NK {
/* fill initialisation vector */
let inn = (RAND_NV * i) % RAND_NK;
self.ira[inn] ^= m; /* note XOR */
let t = m;
m = sd.wrapping_sub(m);
sd = t;
}
for _ in 0..10000 {
self.sbrand();
} /* "warm-up" & stir the generator */
}
pub fn process(&mut self, byt: u8) {
/* process the next message byte */
let cnt = ((self.length[0] / 32) % 16) as usize;
self.w[cnt] <<= 8;
self.w[cnt] |= (byt & 0xFF) as u32;
self.length[0] += 8;
if self.length[0] == 0 {
self.length[1] += 1;
self.length[0] = 0
}
if (self.length[0] % 512) == 0 {
self.transform()
}
}
fn fill_pool(&mut self) {
let mut sh = HASH256::new();
for _ in 0..128 {
sh.process((self.sbrand() & 0xff) as u8)
}
let w = sh.hash();
for i in 0..32 {
self.pool[i] = w[i]
}
self.pool_ptr = 0;
}
fn pack(b: [u8; 4]) -> u32 {
/* pack 4 bytes into a 32-bit Word */
return (((b[3] as u32) & 0xff) << 24)
| (((b[2] as u32) & 0xff) << 16)
| (((b[1] as u32) & 0xff) << 8)
| ((b[0] as u32) & 0xff);
}
pub fn hash(&mut self) -> [u8; HASH_BYTES] {
// pad message and finish - supply digest
let mut digest: [u8; 32] = [0; 32];
let len0 = self.length[0];
let len1 = self.length[1];
self.process(0x80);
while (self.length[0] % 512) != 448 {
self.process(0)
}
self.w[14] = len1;
self.w[15] = len0;
self.transform();
for i in 0..32 {
// convert to bytes
digest[i] = ((self.h[i / 4] >> (8 * (3 - i % 4))) & 0xff) as u8;
}
self.init();
return digest;
}
pub fn new() -> HASH256 {
let mut nh = HASH256 {
length: [0; 2],
h: [0; 8],
w: [0; 64],
};
nh.init();
return nh;
}
pub struct RAND {
ira: [u32; RAND_NK], /* random number... */
rndptr: usize,
borrow: u32,
pool_ptr: usize,
pool: [u8; 32],
} | use crate::hash256::HASH256; | projects__incubator-milagro-crypto__rust__src__rand__.rs__function__7.txt |
projects/incubator-milagro-crypto/c/src/rsa_support.c | int OAEP_DECODE(int sha,const octet *p,octet *f)
{
int comp;
int x;
int t;
int i;
int k;
int olen=f->max-1;
int hlen;
int seedlen;
char dbmask[MAX_RSA_BYTES];
char seed[64];
char chash[64];
octet DBMASK= {0,sizeof(dbmask),dbmask};
octet SEED= {0,sizeof(seed),seed};
octet CHASH= {0,sizeof(chash),chash};
seedlen=hlen=sha;
if (olen<seedlen+hlen+1) return 1;
if (!OCT_pad(f,olen+1)) return 1;
hashit(sha,p,-1,&CHASH);
x=f->val[0];
for (i=seedlen; i<olen; i++)
DBMASK.val[i-seedlen]=f->val[i+1];
DBMASK.len=olen-seedlen;
MGF1(sha,&DBMASK,seedlen,&SEED);
for (i=0; i<seedlen; i++) SEED.val[i]^=f->val[i+1];
MGF1(sha,&SEED,olen-seedlen,f);
OCT_xor(&DBMASK,f);
comp=OCT_ncomp(&CHASH,&DBMASK,hlen);
OCT_shl(&DBMASK,hlen);
OCT_clear(&SEED);
OCT_clear(&CHASH);
for (k=0;; k++)
{
if (k>=DBMASK.len)
{
OCT_clear(&DBMASK);
return 1;
}
if (DBMASK.val[k]!=0) break;
}
t=DBMASK.val[k];
if (!comp || x!=0 || t!=0x01)
{
OCT_clear(&DBMASK);
return 1;
}
OCT_shl(&DBMASK,k+1);
OCT_copy(f,&DBMASK);
OCT_clear(&DBMASK);
return 0;
} | projects/incubator-milagro-crypto/rust/src/rsa.rs | pub fn oaep_decode(sha: usize, p: Option<&[u8]>, f: &mut [u8]) -> usize {
let olen = RFS - 1;
let hlen = sha;
let mut seed: [u8; 64] = [0; 64];
let seedlen = hlen;
let mut chash: [u8; 64] = [0; 64];
if olen < seedlen + hlen + 1 {
return 0;
}
let mut dbmask: [u8; RFS] = [0; RFS];
//for i in 0..olen-seedlen {dbmask[i]=0}
if f.len() < RFS {
let d = RFS - f.len();
for i in (d..RFS).rev() {
f[i] = f[i - d];
}
for i in (0..d).rev() {
f[i] = 0;
}
}
hashit(sha, p, -1, &mut chash);
let x = f[0];
for i in seedlen..olen {
dbmask[i - seedlen] = f[i + 1];
}
mgf1(sha, &dbmask[0..olen - seedlen], seedlen, &mut seed);
for i in 0..seedlen {
seed[i] ^= f[i + 1]
}
mgf1(sha, &seed, olen - seedlen, f);
for i in 0..olen - seedlen {
dbmask[i] ^= f[i]
}
let mut comp = true;
for i in 0..hlen {
if chash[i] != dbmask[i] {
comp = false
}
}
for i in 0..olen - seedlen - hlen {
dbmask[i] = dbmask[i + hlen]
}
for i in 0..hlen {
seed[i] = 0;
chash[i] = 0
}
let mut k = 0;
loop {
if k >= olen - seedlen - hlen {
return 0;
}
if dbmask[k] != 0 {
break;
}
k += 1;
}
let t = dbmask[k];
if !comp || x != 0 || t != 0x01 {
for i in 0..olen - seedlen {
dbmask[i] = 0
}
return 0;
}
for i in 0..olen - seedlen - hlen - k - 1 {
f[i] = dbmask[i + k + 1];
}
for i in 0..olen - seedlen {
dbmask[i] = 0
}
return olen - seedlen - hlen - k - 1;
} | fn hashit(sha: usize, a: Option<&[u8]>, n: isize, w: &mut [u8]) {
if sha == SHA256 {
let mut h = HASH256::new();
if let Some(x) = a {
h.process_array(x);
}
if n >= 0 {
h.process_num(n as i32)
}
let hs = h.hash();
for i in 0..sha {
w[i] = hs[i]
}
}
if sha == SHA384 {
let mut h = HASH384::new();
if let Some(x) = a {
h.process_array(x);
}
if n >= 0 {
h.process_num(n as i32)
}
let hs = h.hash();
for i in 0..sha {
w[i] = hs[i]
}
}
if sha == SHA512 {
let mut h = HASH512::new();
if let Some(x) = a {
h.process_array(x);
}
if n >= 0 {
h.process_num(n as i32)
}
let hs = h.hash();
for i in 0..sha {
w[i] = hs[i]
}
}
}
pub fn mgf1(sha: usize, z: &[u8], olen: usize, k: &mut [u8]) {
let hlen = sha;
let mut j = 0;
for i in 0..k.len() {
k[i] = 0
}
let mut cthreshold = olen / hlen;
if olen % hlen != 0 {
cthreshold += 1
}
for counter in 0..cthreshold {
let mut b: [u8; 64] = [0; 64];
hashit(sha, Some(z), counter as isize, &mut b);
if j + hlen > olen {
for i in 0..(olen % hlen) {
k[j] = b[i];
j += 1
}
} else {
for i in 0..hlen {
k[j] = b[i];
j += 1
}
}
}
}
pub const RFS: usize = (big::MODBYTES as usize) * ff::FFLEN; | use super::big;
use super::ff;
use super::ff::FF;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*; | projects__incubator-milagro-crypto__rust__src__rsa__.rs__function__8.txt |
projects/incubator-milagro-crypto/c/src/pbc_support.c | void HASH_ID(int sha,const octet *ID,octet *HID)
{
mhashit(sha,0,ID,HID);
} | projects/incubator-milagro-crypto/rust/src/mpin.rs | pub fn hash_id(sha: usize, id: &[u8], w: &mut [u8]) -> bool {
return hashit(sha, 0, id, w);
} | fn hashit(sha: usize, n: usize, id: &[u8], w: &mut [u8]) -> bool {
let mut r: [u8; 64] = [0; 64];
let mut didit = false;
if sha == SHA256 {
let mut h = HASH256::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if sha == SHA384 {
let mut h = HASH384::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if sha == SHA512 {
let mut h = HASH512::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if !didit {
return false;
}
let rm = big::MODBYTES as usize;
if sha > rm {
for i in 0..rm {
w[i] = r[i]
}
} else {
for i in 0..sha {
w[i + rm - sha] = r[i]
}
for i in 0..(rm - sha) {
w[i] = 0
}
}
return true;
} | use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use super::big;
use super::big::Big;
use super::ecp;
use super::ecp::ECP;
use super::ecp2::ECP2;
use super::fp12::FP12;
use super::fp4::FP4;
use super::pair;
use super::rom;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*; | projects__incubator-milagro-crypto__rust__src__mpin__.rs__function__6.txt |
projects/incubator-milagro-crypto/c/src/pbc_support.c | void HASH_ID(int sha,const octet *ID,octet *HID)
{
mhashit(sha,0,ID,HID);
} | projects/incubator-milagro-crypto/rust/src/mpin256.rs | pub fn hash_id(sha: usize, id: &[u8], w: &mut [u8]) -> bool {
return hashit(sha, 0, id, w);
} | fn hashit(sha: usize, n: usize, id: &[u8], w: &mut [u8]) -> bool {
let mut r: [u8; 64] = [0; 64];
let mut didit = false;
if sha == SHA256 {
let mut h = HASH256::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if sha == SHA384 {
let mut h = HASH384::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if sha == SHA512 {
let mut h = HASH512::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if !didit {
return false;
}
let rm = big::MODBYTES as usize;
if sha > rm {
for i in 0..rm {
w[i] = r[i]
}
} else {
for i in 0..sha {
w[i + rm - sha] = r[i]
}
for i in 0..(rm - sha) {
w[i] = 0
}
}
return true;
} | use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use super::big;
use super::big::Big;
use super::ecp;
use super::ecp::ECP;
use super::ecp8::ECP8;
use super::fp16::FP16;
use super::fp48::FP48;
use super::pair256;
use super::rom;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*; | projects__incubator-milagro-crypto__rust__src__mpin256__.rs__function__6.txt |
projects/incubator-milagro-crypto/c/src/rsa_support.c | int PKCS15(int sha,const octet *m,octet *w)
{
int olen=w->max;
int hlen=sha;
int idlen=19;
char h[64];
octet H= {0,sizeof(h),h};
if (olen<idlen+hlen+10) return 1;
hashit(sha,m,-1,&H);
OCT_empty(w);
OCT_jbyte(w,0x00,1);
OCT_jbyte(w,0x01,1);
OCT_jbyte(w,0xff,olen-idlen-hlen-3);
OCT_jbyte(w,0x00,1);
if (hlen==32) OCT_jbytes(w,(char *)SHA256ID,idlen);
if (hlen==48) OCT_jbytes(w,(char *)SHA384ID,idlen);
if (hlen==64) OCT_jbytes(w,(char *)SHA512ID,idlen);
OCT_joctet(w,&H);
return 0;
} | projects/incubator-milagro-crypto/rust/src/rsa.rs | pub fn pkcs15(sha: usize, m: &[u8], w: &mut [u8]) -> bool {
let olen = ff::FF_BITS / 8;
let hlen = sha;
let idlen = 19;
let mut b: [u8; 64] = [0; 64]; /* Not good */
if olen < idlen + hlen + 10 {
return false;
}
hashit(sha, Some(m), -1, &mut b);
for i in 0..w.len() {
w[i] = 0
}
let mut i = 0;
w[i] = 0;
i += 1;
w[i] = 1;
i += 1;
for _ in 0..olen - idlen - hlen - 3 {
w[i] = 0xff;
i += 1
}
w[i] = 0;
i += 1;
if hlen == SHA256 {
for j in 0..idlen {
w[i] = SHA256ID[j];
i += 1
}
}
if hlen == SHA384 {
for j in 0..idlen {
w[i] = SHA384ID[j];
i += 1
}
}
if hlen == SHA512 {
for j in 0..idlen {
w[i] = SHA512ID[j];
i += 1
}
}
for j in 0..hlen {
w[i] = b[j];
i += 1
}
return true;
} | fn hashit(sha: usize, a: Option<&[u8]>, n: isize, w: &mut [u8]) {
if sha == SHA256 {
let mut h = HASH256::new();
if let Some(x) = a {
h.process_array(x);
}
if n >= 0 {
h.process_num(n as i32)
}
let hs = h.hash();
for i in 0..sha {
w[i] = hs[i]
}
}
if sha == SHA384 {
let mut h = HASH384::new();
if let Some(x) = a {
h.process_array(x);
}
if n >= 0 {
h.process_num(n as i32)
}
let hs = h.hash();
for i in 0..sha {
w[i] = hs[i]
}
}
if sha == SHA512 {
let mut h = HASH512::new();
if let Some(x) = a {
h.process_array(x);
}
if n >= 0 {
h.process_num(n as i32)
}
let hs = h.hash();
for i in 0..sha {
w[i] = hs[i]
}
}
}
const SHA256ID: [u8; 19] = [
0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
0x00, 0x04, 0x20,
];
const SHA384ID: [u8; 19] = [
0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
0x00, 0x04, 0x30,
];
const SHA512ID: [u8; 19] = [
0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
0x00, 0x04, 0x40,
]; | use super::big;
use super::ff;
use super::ff::FF;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*; | projects__incubator-milagro-crypto__rust__src__rsa__.rs__function__6.txt |
projects/incubator-milagro-crypto/c/src/hash.c | void HASH384_hash(hash384 *sh,char *hash)
{
/* pad message and finish - supply digest */
unsign64 len0;
unsign64 len1;
len0=sh->length[0];
len1=sh->length[1];
HASH384_process(sh,PAD);
while ((sh->length[0]%1024)!=896) HASH384_process(sh,ZERO);
sh->w[14]=len1;
sh->w[15]=len0;
HASH384_transform(sh);
for (int i=0; i<sh->hlen; i++)
{
/* convert to bytes */
hash[i]=(char)((sh->h[i/8]>>(8*(7-i%8))) & 0xffL);
}
HASH384_init(sh);
} | projects/incubator-milagro-crypto/rust/src/hash384.rs | pub fn hash(&mut self) -> [u8; HASH_BYTES] {
/* pad message and finish - supply digest */
let mut digest: [u8; 48] = [0; HASH_BYTES];
let len0 = self.length[0];
let len1 = self.length[1];
self.process(0x80);
while (self.length[0] % 1024) != 896 {
self.process(0)
}
self.w[14] = len1;
self.w[15] = len0;
self.transform();
for i in 0..HASH_BYTES {
// convert to bytes
digest[i] = ((self.h[i / 8] >> (8 * (7 - i % 8))) & 0xff) as u8;
}
self.init();
return digest;
} | fn transform(&mut self) {
// basic transformation step
for j in 16..80 {
self.w[j] = Self::theta1(self.w[j - 2])
.wrapping_add(self.w[j - 7])
.wrapping_add(Self::theta0(self.w[j - 15]))
.wrapping_add(self.w[j - 16]);
}
let mut a = self.h[0];
let mut b = self.h[1];
let mut c = self.h[2];
let mut d = self.h[3];
let mut e = self.h[4];
let mut f = self.h[5];
let mut g = self.h[6];
let mut hh = self.h[7];
for j in 0..80 {
/* 64 times - mush it up */
let t1 = hh
.wrapping_add(Self::sig1(e))
.wrapping_add(Self::ch(e, f, g))
.wrapping_add(HASH384_K[j])
.wrapping_add(self.w[j]);
let t2 = Self::sig0(a).wrapping_add(Self::maj(a, b, c));
hh = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
self.h[0] = self.h[0].wrapping_add(a);
self.h[1] = self.h[1].wrapping_add(b);
self.h[2] = self.h[2].wrapping_add(c);
self.h[3] = self.h[3].wrapping_add(d);
self.h[4] = self.h[4].wrapping_add(e);
self.h[5] = self.h[5].wrapping_add(f);
self.h[6] = self.h[6].wrapping_add(g);
self.h[7] = self.h[7].wrapping_add(hh);
}
pub fn init(&mut self) {
// initialise
for i in 0..64 {
self.w[i] = 0
}
self.length[0] = 0;
self.length[1] = 0;
self.h[0] = HASH384_H0;
self.h[1] = HASH384_H1;
self.h[2] = HASH384_H2;
self.h[3] = HASH384_H3;
self.h[4] = HASH384_H4;
self.h[5] = HASH384_H5;
self.h[6] = HASH384_H6;
self.h[7] = HASH384_H7;
}
pub fn process(&mut self, byt: u8) {
/* process the next message byte */
let cnt = ((self.length[0] / 64) % 16) as usize;
self.w[cnt] <<= 8;
self.w[cnt] |= (byt & 0xFF) as u64;
self.length[0] += 8;
if self.length[0] == 0 {
self.length[1] += 1;
self.length[0] = 0
}
if (self.length[0] % 1024) == 0 {
self.transform()
}
}
pub struct HASH384 {
length: [u64; 2],
h: [u64; 8],
w: [u64; 80],
}
pub const HASH_BYTES: usize = 48; | use super::*; | projects__incubator-milagro-crypto__rust__src__hash384__.rs__function__15.txt |
projects/incubator-milagro-crypto/c/src/hash.c | void HASH512_init(hash512 *sh)
{
/* re-initialise */
for (int i=0; i<80; i++) sh->w[i]=0;
sh->length[0]=sh->length[1]=0;
sh->h[0]=H0_512;
sh->h[1]=H1_512;
sh->h[2]=H2_512;
sh->h[3]=H3_512;
sh->h[4]=H4_512;
sh->h[5]=H5_512;
sh->h[6]=H6_512;
sh->h[7]=H7_512;
} | projects/incubator-milagro-crypto/rust/src/hash512.rs | pub fn init(&mut self) {
/* initialise */
for i in 0..64 {
self.w[i] = 0
}
self.length[0] = 0;
self.length[1] = 0;
self.h[0] = HASH512_H0;
self.h[1] = HASH512_H1;
self.h[2] = HASH512_H2;
self.h[3] = HASH512_H3;
self.h[4] = HASH512_H4;
self.h[5] = HASH512_H5;
self.h[6] = HASH512_H6;
self.h[7] = HASH512_H7;
} | pub struct HASH512 {
length: [u64; 2],
h: [u64; 8],
w: [u64; 80],
}
const HASH512_H0: u64 = 0x6a09e667f3bcc908;
const HASH512_H1: u64 = 0xbb67ae8584caa73b;
const HASH512_H2: u64 = 0x3c6ef372fe94f82b;
const HASH512_H3: u64 = 0xa54ff53a5f1d36f1;
const HASH512_H4: u64 = 0x510e527fade682d1;
const HASH512_H5: u64 = 0x9b05688c2b3e6c1f;
const HASH512_H6: u64 = 0x1f83d9abfb41bd6b;
const HASH512_H7: u64 = 0x5be0cd19137e2179; | use super::*; | projects__incubator-milagro-crypto__rust__src__hash512__.rs__function__10.txt |
projects/incubator-milagro-crypto/c/src/hash.c | void HASH384_init(hash384 *sh)
{
/* re-initialise */
for (int i=0; i<80; i++) sh->w[i]=0;
sh->length[0]=sh->length[1]=0;
sh->h[0]=H8_512;
sh->h[1]=H9_512;
sh->h[2]=HA_512;
sh->h[3]=HB_512;
sh->h[4]=HC_512;
sh->h[5]=HD_512;
sh->h[6]=HE_512;
sh->h[7]=HF_512;
} | projects/incubator-milagro-crypto/rust/src/hash384.rs | pub fn init(&mut self) {
// initialise
for i in 0..64 {
self.w[i] = 0
}
self.length[0] = 0;
self.length[1] = 0;
self.h[0] = HASH384_H0;
self.h[1] = HASH384_H1;
self.h[2] = HASH384_H2;
self.h[3] = HASH384_H3;
self.h[4] = HASH384_H4;
self.h[5] = HASH384_H5;
self.h[6] = HASH384_H6;
self.h[7] = HASH384_H7;
} | pub struct HASH384 {
length: [u64; 2],
h: [u64; 8],
w: [u64; 80],
}
const HASH384_H0: u64 = 0xcbbb9d5dc1059ed8;
const HASH384_H1: u64 = 0x629a292a367cd507;
const HASH384_H2: u64 = 0x9159015a3070dd17;
const HASH384_H3: u64 = 0x152fecd8f70e5939;
const HASH384_H4: u64 = 0x67332667ffc00b31;
const HASH384_H5: u64 = 0x8eb44a8768581511;
const HASH384_H6: u64 = 0xdb0c2e0d64f98fa7;
const HASH384_H7: u64 = 0x47b5481dbefa4fa4; | use super::*; | projects__incubator-milagro-crypto__rust__src__hash384__.rs__function__10.txt |
projects/incubator-milagro-crypto/c/src/rand.c | void RAND_clean(csprng *rng)
{
/* kill internal state */
int i;
rng->pool_ptr=rng->rndptr=0;
for (i=0; i<32; i++) rng->pool[i]=0;
for (i=0; i<NK; i++) rng->ira[i]=0;
rng->borrow=0;
} | projects/incubator-milagro-crypto/rust/src/rand.rs | pub fn clean(&mut self) {
self.pool_ptr = 0;
self.rndptr = 0;
for i in 0..32 {
self.pool[i] = 0
}
for i in 0..RAND_NK {
self.ira[i] = 0
}
self.borrow = 0;
} | pub struct RAND {
ira: [u32; RAND_NK], /* random number... */
rndptr: usize,
borrow: u32,
pool_ptr: usize,
pool: [u8; 32],
}
const RAND_NK: usize = 21; | use crate::hash256::HASH256; | projects__incubator-milagro-crypto__rust__src__rand__.rs__function__2.txt |
projects/incubator-milagro-crypto/c/src/pbc_support.c | void HASH_ID(int sha,const octet *ID,octet *HID)
{
mhashit(sha,0,ID,HID);
} | projects/incubator-milagro-crypto/rust/src/mpin192.rs | pub fn hash_id(sha: usize, id: &[u8], w: &mut [u8]) -> bool {
return hashit(sha, 0, id, w);
} | fn hashit(sha: usize, n: usize, id: &[u8], w: &mut [u8]) -> bool {
let mut r: [u8; 64] = [0; 64];
let mut didit = false;
if sha == SHA256 {
let mut h = HASH256::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if sha == SHA384 {
let mut h = HASH384::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if sha == SHA512 {
let mut h = HASH512::new();
if n > 0 {
h.process_num(n as i32)
}
h.process_array(id);
let hs = h.hash();
for i in 0..sha {
r[i] = hs[i];
}
didit = true;
}
if !didit {
return false;
}
let rm = big::MODBYTES as usize;
if sha > rm {
for i in 0..rm {
w[i] = r[i]
}
} else {
for i in 0..sha {
w[i + rm - sha] = r[i]
}
for i in 0..(rm - sha) {
w[i] = 0
}
}
return true;
} | use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use super::big;
use super::big::Big;
use super::ecp;
use super::ecp::ECP;
use super::ecp4::ECP4;
use super::fp24::FP24;
use super::fp8::FP8;
use super::pair192;
use super::rom;
use crate::hash256::HASH256;
use crate::hash384::HASH384;
use crate::hash512::HASH512;
use crate::rand::RAND;
use super::*;
use crate::test_utils::*; | projects__incubator-milagro-crypto__rust__src__mpin192__.rs__function__6.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.