7¤0ì×-k>°š80Ã0Ã0ÃÀ
tÿ·Ñ[d7Ê·�BJ™ª¥Z§i×þ×°‚ß6S¤q¸†Vô¿Ò«%€óqJc    ä‰\:£`À˜Ž%‡i”9£BÆc!0#22"    „7eQ2d                         char keyword);
/* Returns keyword character for given index, or \0 if keyword couldn't be
   added. */
char maildir_keywords_idx_char(struct maildir_keywords_sync_ctx *ctx,
			       unsigned int idx);

#endif
#ifndef PASSDB_H
#define PASSDB_H

#define IS_VALID_PASSWD(pass) \
	((pass)[0] != '\0' && (pass)[0] != '*' && (pass)[0] != '!')

struct auth_request;
struct auth_passdb_settings;
struct passdb error is left untouched */
void fs_write_stream_abort_parent(struct fs_file *file, struct ostream **output);

#endif
#ifndef ISTREAM_CALLBACK_H
#define ISTREAM_CALLBACK_H

/* istream-callback can be used to implement an istream that returns data
   by calling the specified callback. The callback needs to do:

   a) Add data to buffer unless the buffer size is already too large
   (the callback can decide by itself what is too large). Return TRUE
   regardless of whether any data was added.

   b) Return FALSE when it's finished adregister fs_api_module_register;

struct fs_vfuncs {
	struct fs *(*alloc)(void);
	int (*init)(struct fs *fs, const struct fs_parameters *params,
		    const char **error_r);
	void (*deinit)(struct fs *fs);
	void (*free)(struct fs *fs);

	enum fs_properties (*get_properties)(struct fs *fs);

	struct fs_file *(*file_alloc)(void);
	void (*file_init)(struct fs_file *file, const char *path,
			  enum fs_open_mode mode, enum fs_open_flags flags);
	void (*file_deinit)(struct fs_file *file);
	void (*file_close)(struct fs_file *file);
	cons;

/* return raw public key
   Only ECC supported currently

   returns OID bytes and public key in compressed form (z||x)
*/
bool dcrypt_key_store_public_raw(struct dcrypt_public_key *key,
				 pool_t pool,
				 enum dcrypt_key_type *key_type_r,
				 ARRAY_TYPE(dcrypt_raw_key) *keys_r,
				 const char **error_r);

/* load raw private key:
   Only ECC supported currently

   expects OID bytes and private key in bigendian bytes
*/
bool dcrypt_key_load_private_raw(struct dcrypt_private_key **key_r,
				 enum dcrypt_key_type key_type,ata_len,
			   buffer_t *result, const char **error_r);

/**
 * perform final step (may or may not emit data)
 */
bool dcrypt_ctx_sym_final(struct dcrypt_context_symmetric *ctx,
			  buffer_t *result, const char **error_r);

/**
 * create HMAC context, algorithm is digest algorithm
 */
bool dcrypt_ctx_hmac_create(const char *algorithm,
			    struct dcrypt_context_hmac **ctx_r,
			    const char **error_r);
/**
 * destroy HMAC context and free memory
 */
void dcrypt_ctx_hmac_destroy(struct dcrypt_context_hmac **ctx);

/**
 * hmac kreated_hook_set(pop3_client_created_func_t *new_hook);

void pop3_refresh_proctitle(void);

#endif
#ifndef DCRYPT_H
#define DCRYPT_H 1
#include "array.h"

struct dcrypt_context_symmetric;
struct dcrypt_context_hmac;
struct dcrypt_public_key;
struct dcrypt_private_key;

struct dcrypt_keypair {
	struct dcrypt_public_key *pub;
	struct dcrypt_private_key *priv;
};

enum dcrypt_sym_mode {
	DCRYPT_MODE_ENCRYPT,
	DCRYPT_MODE_DECRYPT
};

enum dcrypt_key_type {
	DCRYPT_KEY_RSA = 0x1,
	DCRYPT_KEY_EC  = 0x2
};

/**
 * dovecot key format:
 * vr_r = "Missing parameters"; \
	return -1; \
} } STMT_END

/* Error out if filter got any parameters */
#define ERROR_IF_ANY_PARAMETERS \
STMT_START { if (stmt->params != NULL) { \
	const char *key = var_expand_parameter_key(stmt->params); \
	if (key != NULL) { \
		ERROR_UNSUPPORTED_KEY(key); \
	} else { \
		ERROR_TOO_MANY_UNNAMED_PARAMETERS; \
	} \
} } STMT_END

/* Error out if transfer is not set. */
#define ERROR_IF_NO_TRANSFER_TO(action) \
STMT_START { if (!state->transfer_set) { \
	*error_r = t_strdup_printf("No value to %s", aME,
	/* Something went wrong passing the login username to the backend */
	AUTH_SCRAM_SERVER_ERROR_BAD_LOGIN_USERNAME,
	/* Credentials lookup failed (nonexistent user or internal error). */
	AUTH_SCRAM_SERVER_ERROR_LOOKUP_FAILED,
	/* Credentials provided by client failed to verify against the
	   credentials looked up earlier. */
	AUTH_SCRAM_SERVER_ERROR_VERIFICATION_FAILED,
};

enum auth_scram_server_state {
	AUTH_SCRAM_SERVER_STATE_INIT = 0,
	AUTH_SCRAM_SERVER_STATE_CLIENT_FIRST,
	AUTH_SCRAM_SERVER_STATE_CREDENTIALS_LOOKUP,
	AUTH *name, const char **client_error_r);

/* Set IMAP metadata entry to value. */
int imap_metadata_set(struct imap_metadata_transaction *imtrans,
	const char *entry, const struct mail_attribute_value *value);
/* Delete IMAP metadata entry. This is just a wrapper to
   imap_metadata_set() with value->value=NULL. */
int imap_metadata_unset(struct imap_metadata_transaction *imtrans,
	const char *entry);
/* Returns value for IMAP metadata entry. Returns 1 if value was returned,
   0 if value wasn't found (set to NULL), -1 if error */
int, filter_value="inbox" }.
   Returns 0 on success, -1 on error.

   Settings for the requested "info" must exist inside the specified filter,
   or this lookup fails. This means that you can safely call this to lookup
   e.g. mail_namespace_setting_parser_info for a given namespace, because it's
   required to exist. Using it to lookup any other infos for a namespace will
   fail if settings in it haven't been explicitly used within the namespace
   filter. */
int settings_get_filter(struct event *event,
			const char *filter_key, S_EVENT_VAR_EXPAND_* macros for more details. */
int settings_get(struct event *event,
		 const struct setting_parser_info *info,
		 enum settings_get_flags flags,
		 const char *source_filename,
		 unsigned int source_linenum,
		 const void **set_r, const char **error_r);
#ifdef HAVE_TYPE_CHECKS
#  define settings_get(event, info, flags, set_r, error_r) \
	settings_get(event, info, flags, \
		__FILE__, __LINE__, (void *)set_r, 1 ? (error_r) : \
	COMPILE_ERROR_IF_TRUE( \
		!__builtin_types_compatible_p(typeof((*set_r)->pool), pool_connection_get_event(struct imapc_connection *conn);

#endif
#ifndef SETTINGS_H
#define SETTINGS_H

#include "var-expand.h"
#include "settings-parser.h"

struct settings_root;
struct settings_mmap;
struct settings_instance;
struct var_expand_params;

enum settings_override_type {
	/* Setting is a built-in default. This is used only when the defaults
	   aren't coming from configuration (e.g. -O parameter or with unit
	   tests). */
	SETTINGS_OVERRIDE_TYPE_DEFAULT,
	/* Setting is from userdb. */
	SETTINGS_OVERRIDE_TYPE_USERDB,
	/* S,
	/* proxy failed - other side's ostream returned an error */
	IOSTREAM_PROXY_STATUS_OTHER_SIDE_OUTPUT_ERROR,
};

/* The callback maybe be called once or twice. Usually the first call should
   destroy the proxy, but it's possible for it to just wait for the other
   direction of the proxy to finish as well and call the callback.

   Note that the sides mean which side is the reader side. If the failure is in
   ostream, it's the other side's ostream that failed. So for example if
   side=left, the write failed to the right side'ssize);
void iostream_rawlog_flush(struct rawlog_iostream *rstream);
void iostream_rawlog_close(struct rawlog_iostream *rstream);

#endif
#ifndef MESSAGE_HEADER_ENCODE_H
#define MESSAGE_HEADER_ENCODE_H

/* Encode UTF-8 input into output wherever necessary using either Q or B
   encoding depending on which takes less space (approximately). The encoded
   output is split into multiple lines if necessary (max 76 chars/line).
   Existing folding whitespace is preserved. Bare [CR]LF will be preserved by
   adding a TAB after it to make i   list instead of adding to it. The boollist can still be updated afterwards,
   as long as this function is called again after modifications. */
void settings_boollist_finish(ARRAY_TYPE(const_string) *array, bool stop);

/* Checks if boollist is marked as replacing the full list */
bool settings_boollist_is_stopped(const ARRAY_TYPE(const_string) *array);
/* Split the settings value into path and content. The path is allocated from
   the path_pool, while content points directly to the value string. */
void settings_file_get(const *default_settings;

	size_t struct_size;
	size_t pool_offset1; /* 1 + offset to pool_t field */

	/* This is called for every setting that is parsed. *value is already
	   the final pointer stored into the settings struct. If it's modified,
	   it should usually be allocated from set->pool. */
	bool (*setting_apply)(struct event *event, void *set,
			      const char *key, const char **value,
			      enum setting_apply_flags flags, const char **error_r);
	/* This is called after %variable expansion. */
	bool (*check_func)(void *stting_filter_array_order *filter_array_order;
	const char *required_setting;
};

#define SETTING_DEFINE_STRUCT_TYPE(_enum_type, _flags, _c_type, _key, _name, _struct_name) \
	{ .type = (_enum_type) + COMPILE_ERROR_IF_TYPES_NOT_COMPATIBLE( \
		((_struct_name *)0)->_name, _c_type), \
	  .flags = _flags, .key = _key, \
	  .offset = offsetof(_struct_name, _name) }

#define SETTING_DEFINE_STRUCT_BOOL(key, name, struct_name) \
	SETTING_DEFINE_STRUCT_TYPE(SET_BOOL, 0, bool, key, name, struct_name)
#define SETTING_DEFINE_STRUCT_UINTMAX(key and settings. If it succeeds,
   returns 1 and lock_r, which needs to be freed once finished with the lock.
   If lock_set->lock_timeout_secs is reached, returns 0 and error_r. Returns
   -1 and sets error_r on other errors. */
int mail_storage_lock_create(const char *lock_path,
			     const struct file_create_settings *lock_set,
			     const struct mail_storage_settings *mail_set,
			     struct file_lock **lock_r, const char **error_r);
/* Create a lock file to the mailbox with the given filename. Returns the same
   as mail_sxt *transaction;

	struct mail_search_args *args;
	struct mail_search_sort_program *sort_program;
	enum mail_fetch_field wanted_fields;
	struct mailbox_header_lookup_ctx *wanted_headers;
	normalizer_func_t *normalizer;

	struct timeval search_start_time, last_notify;
	unsigned int search_notify_passes;

	/* if non-NULL, specifies that a search resulting is being updated.
	   this can be used as a search optimization: if searched message
	   already exists in search result, it's not necessary to check if
	   static data matches. */
t mail_private {
	struct mail mail;
	struct mail_vfuncs v, *vlast;
	/* normally NULL, but in case this is a "backend mail" for a mail
	   created by virtual storage, this points back to the original virtual
	   mail. at least mailbox_copy() bypasses the virtual storage, so this
	   allows mail_log plugin to log the copy operation using the original
	   mailbox name. */
	struct mail *vmail;
	/* Event is created lazily. Use mail_event() to access it. */
	struct event *_event;

	uint32_t seq_pvt;

	/* initial wanted fields/headers, sehar *_path;
	/* Filled lazily when mailbox is opened, use mailbox_get_index_path()
	   to access it */
	const char *_index_path;

	/* default vfuncs for new struct mails. */
	const struct mail_vfuncs *mail_vfuncs;
	/* Mailbox settings, or NULL if defaults */
	const struct mailbox_settings *set;

	/* If non-zero, fail mailbox_open() with this error. mailbox_alloc()
	   can set this to force open to fail. */
	enum mail_error open_error;

	struct istream *input;
	const char *index_prefix;
	enum mailbox_flags flags;
	unsigned int transruct mailbox_update *update);
	int (*delete_box)(struct mailbox *box);
	int (*rename_box)(struct mailbox *src, struct mailbox *dest);

	int (*get_status)(struct mailbox *box, enum mailbox_status_items items,
			  struct mailbox_status *status_r);
	int (*get_metadata)(struct mailbox *box,
			    enum mailbox_metadata_items items,
			    struct mailbox_metadata *metadata_r);
	int (*set_subscribed)(struct mailbox *box, bool set);

	int (*attribute_set)(struct mailbox_transaction_context *t,
			     enum mail_attribute_type type_flags,t index rebuild is requested.
	   The callback should add any missing mailboxes to the list index.
	   Returns 0 on success, -1 on temporary failure that didn't properly
	   rebuild the index. */
	int (*list_index_rebuild)(struct mail_storage *storage,
				  enum mail_storage_list_index_rebuild_reason reason);
};

union mail_storage_module_context {
	struct mail_storage_vfuncs super;
	struct mail_storage_module_register *reg;
};

enum mail_storage_class_flags {
	/* mailboxes are files, not directories */
	MAIL_STORAGE_CLASS_FLAG_MAiance */
double stats_dist_get_variance(const struct stats_dist *stats);
/* Returns events' approximate (through random subsampling) percentile.
   fraction parameter is in the range (0., 1.], so 95th %-ile is 0.95. */
uint64_t stats_dist_get_percentile(struct stats_dist *stats, double fraction);
/* Returns events' approximate (through random subsampling) 95th percentile. */
static inline uint64_t stats_dist_get_95th(struct stats_dist *stats)
{
	return stats_dist_get_percentile(stats, 0.95);
}
/* Returns the sample array */
const u_ibc_send_finish(struct dsync_ibc *ibc, const char *error,
			   enum mail_error mail_error,
			   bool require_full_resync);
enum dsync_ibc_recv_ret
dsync_ibc_recv_finish(struct dsync_ibc *ibc, const char **error_r,
		      enum mail_error *mail_error_r,
		      bool *require_full_resync_r);

/* Close any mail input streams that are kept open. This needs to be called
   before the mail is attempted to be freed (usually on error conditions). */
void dsync_ibc_close_mail_streams(struct dsync_ibc *ibc);

bool dsync_ibc_has_failed(strL_MAIL_CHANGES,
	DSYNC_IBC_EOL_MAIL_REQUESTS,
	DSYNC_IBC_EOL_MAILS
};

struct dsync_ibc_settings {
	/* Server hostname. Used for determining which server does the
	   locking. */
	const char *hostname;
	/* if non-NULL, sync only these namespaces (LF-separated) */
	const char *sync_ns_prefixes;
	/* if non-NULL, sync only this mailbox name */
	const char *sync_box;
	/* if non-NULL, use this mailbox for finding messages with GUIDs and
	   copying them instead of saving them again. */
	const char *virtual_all_box;
	/* if non-empty, syns of these that allow for different key types
 * and different value types.  In general, the function name scheme is:
 *
 *	dlua_table_get_<return type>_by_<key type>
 *
 * The _by_{str,int} variants use the supplied field value as the table key.
 *
 * The _by_thread variants use the current thread's thread object as the
 * table key.
 *
 * Returns:
 *   -1 = incompatible value type
 *    0 = nil or not found
 *    1 = value found
 */
int dlua_table_get_luainteger_by_str(lua_State *L, int idx, const char *field, lua_Integer *value_ the next block of a message. Returns 1 if block is returned, 0 if
   input stream is non-blocking and more data needs to be read, -1 when all is
   done or error occurred (see stream's error status). */
int message_parser_parse_next_block(struct message_parser_ctx *ctx,
				    struct message_block *block_r);

/* Read and parse header. */
void message_parser_parse_header(struct message_parser_ctx *ctx,
				 struct message_size *hdr_size,
				 message_part_header_callback_t *callback,
				 void *context) ATTR_NULL(4);
#define messat config_module_parser *root_module_parsers;
	struct config_section_stack *cur_section;
	struct input_stack *cur_input;
	uint8_t change_counter;
	unsigned int create_order_counter;

	string_t *value;
	const char *error;

	const char *dovecot_config_version;

	const char *const *filter_name_prefixes;
	unsigned int filter_name_prefixes_count;

	struct old_set_parser *old;

	HASH_TABLE(const char *, const char *) seen_settings;
	struct config_filter_context *filter;
	bool dump_defaults:1;
	bool expand_values:1;
	bool hide_errors:1;
	bk_encode(buffer_t *buf, uint64_t num);
int numpack_decode(const uint8_t **p, const uint8_t *end, uint64_t *num_r);
int numpack_decode32(const uint8_t **p, const uint8_t *end, uint32_t *num_r);

#endif
#ifndef CONFIG_PARSER_PRIVATE_H
#define CONFIG_PARSER_PRIVATE_H

#include "config-parser.h"
#include "config-filter.h"

enum config_line_type {
	/* empty line, or only a #comment in the line */
	CONFIG_LINE_TYPE_SKIP,
	/* line ended with '\' - need to continue parsing the next line */
	CONFIG_LINE_TYPE_CONTINUE,
	/* value contains the		enum mail_thread_type thread_type;
		struct mail_search_modseq *modseq;
		struct mail_search_result *search_result;
		struct mail_search_mime_part *mime_part;
	} value;
	/* set by mail_search_args_init(): */
	struct {
		struct mail_search_args *search_args;
		/* Note that initialized keywords may be empty if the keyword
		   wasn't valid in this mailbox. */
		struct mail_keywords *keywords;
		struct imap_match_glob *mailbox_glob;
	} initialized;

	void *context;
	const char *hdr_field_name; /* for SEARCH_HEADER* */
	bool match_noILBOX_GUID,
	SEARCH_MAILBOX_GLOB,
	SEARCH_REAL_UID,
	SEARCH_MIMEPART
};

enum mail_search_date_type {
	MAIL_SEARCH_DATE_TYPE_SENT = 1,
	MAIL_SEARCH_DATE_TYPE_RECEIVED,
	MAIL_SEARCH_DATE_TYPE_SAVED
};

enum mail_search_arg_flag {
	/* Used by *BEFORE/SINCE/ON searches.

	   When NOT set: Adjust search timestamps so that the email's timezone
	   is included in the comparisons. For example
	   "04-Nov-2016 00:00:00 +0200" would match 4th day. This allows
	   searching for mails with dates from the email sender's point of
	   view. For id *data, size_t size,
		    uoff_t offset);

/* Return the last timestamp when something was successfully sent to the
   ostream's internal buffers (no guarantees that anything was sent further).
   The timestamp is 0 if nothing has ever been written. */
void o_stream_get_last_write_time(struct ostream *stream, struct timeval *tv_r);

/* If there are any I/O loop items associated with the stream, move all of
   them to provided/current ioloop. */
void o_stream_switch_ioloop_to(struct ostream *stream, struct ioloop *ioloop);
void ons the (minimum) number of bytes we can still write without failing.
   This is commonly used by callers to find out how many bytes they're
   guaranteed to be able to send, and then generate that much data and send
   it. */
size_t o_stream_get_buffer_avail_size(const struct ostream *stream) ATTR_PURE;

/* Seek to specified position from beginning of file. This works only for
   files. Returns 1 if successful, -1 if error. */
int o_stream_seek(struct ostream *stream, uoff_t offset);
/* Returns number of bytes sent, -1 = error */
sribute_iter_next(struct mailbox_attribute_iter *iter);
int acl_attribute_iter_deinit(struct mailbox_attribute_iter *iter);

#endif
#ifndef OSTREAM_H
#define OSTREAM_H

#include "ioloop.h"

enum ostream_send_istream_result {
	/* All of the istream was successfully sent to ostream. */
	OSTREAM_SEND_ISTREAM_RESULT_FINISHED,
	/* Caller needs to wait for more input from non-blocking istream. */
	OSTREAM_SEND_ISTREAM_RESULT_WAIT_INPUT,
	/* Caller needs to wait for output to non-blocking ostream.
	   o_stream_set_flush_pending() is automaall letter u with grave, acute and circumflex */ \
	 (c) == 0x00F9 || (c) == 0x00FA || (c) == 0x00FB || \
	 /* latin small letter y with acute */ \
	 (c) == 0x00FD )
#define IS_VOWEL(c) \
	(IS_ASCII_VOWEL(c) || IS_NONASCII_VOWEL(c))
#endif
#ifndef MAILBOX_LIST_NOTIFY_H
#define MAILBOX_LIST_NOTIFY_H

#include "guid.h"

struct mailbox_list_notify;

enum mailbox_list_notify_event {
	MAILBOX_LIST_NOTIFY_CREATE		= 0x01,
	MAILBOX_LIST_NOTIFY_DELETE		= 0x02,
	MAILBOX_LIST_NOTIFY_RENAME		= 0x04,
	MAILBOX_LIST_NOTIFY_SUBSCRIBE		= 0x08,
	MAIoff_t physical_size;
	uoff_t virtual_size;
	unsigned int lines;
};

/* Calculate size of message header. Leave the input point to first
   character in body. */
int message_get_header_size(struct istream *input, struct message_size *hdr,
			    bool *has_nuls_r);
/* Calculate size of message body. */
int message_get_body_size(struct istream *input, struct message_size *body,
			  bool *has_nuls_r);

/* Sum contents of src into dest. */
void message_size_add(struct message_size *dest,
		      const struct message_size *src);

/* Skitring is nothing more than a valid number
   in valid range. Otherwise -1 is returned and num_r is left untouched

   str_parse_*() helpers do not require the number to be the entire string
   and pass back the pointer just past a valid parsed integer in endp_r if
   it is non-NULL. What is written to endp_r in error cases is undefined.
*/

/*
 * Unsigned decimal
 */

int str_to_uint(const char *str, unsigned int *num_r)
	ATTR_WARN_UNUSED_RESULT;
int str_parse_uint(const char *str, unsigned int *num_r,
	const char **endp_r) ATTR_WAis used internally only via %{ldap_ptr},
	   it shouldn't be returned in iteration. */
	bool skip;
};
ARRAY_DEFINE_TYPE(ldap_field, struct ldap_field);

struct ldap_request {
	enum ldap_request_type type;

	/* msgid for sent requests, -1 if not sent */
	int msgid;
	/* timestamp when request was created */
	time_t create_time;

	/* Number of times this request has been sent to LDAP server. This
	   increases when LDAP gets disconnected and reconnect send the request
	   again. */
	unsigned int send_count;

	bool failed:1;
	/* This isted help_requested;

	const char *username;
	struct ip_addr local_ip, remote_ip;
	in_port_t local_port, remote_port;
	/* extra fields (e.g. forward_*) sent via doveadm protocol */
	const char *const *extra_fields;

	enum doveadm_client_type conn_type;
	struct istream *input;
	struct ostream *output;
	struct event *event;
	/* Command should use this event to lookup settings. By default it's
	   the same as event. */
	struct event *set_event;

	/* non-NULL if doveadm-server should return referral to another
	   server instead. */
	ced independent of their ordering against
	   the current argument.

	   The parameter key is by default the same as the parameter name,
	   unless DOVEADM_CMD_PARAMKV is used to specify a distinct key.

	   If the current argument doesn't match any key_value parameter for
	   the current position, the next plain positional argument will be
	   filled (if any).

	   See test-doveadm-cmd-parse.c for more details.
	  */
	CMD_PARAM_FLAG_KEY_VALUE	= 0x8,
} doveadm_cmd_param_flag_t;

typedef enum {
	CMD_FLAG_NONE			= 0x0,
	CMD_FLAG_HIDDEc_key *enc_key,
				  const char **error_r);
	bool (*store_public_key)(struct dcrypt_public_key *key,
				 enum dcrypt_key_format format,
				 buffer_t *destination, const char **error_r);

	void (*private_to_public_key)(struct dcrypt_private_key *priv_key,
				      struct dcrypt_public_key **pub_key_r);

	bool (*key_string_get_info)(
		const char *key_data, enum dcrypt_key_format *format_r,
		enum dcrypt_key_version *version_r,
		enum dcrypt_key_kind *kind_r,
		enum dcrypt_key_encryption_type *encryption_type_r,
		const char **en, va_list args)
	ATTR_NORETURN ATTR_FORMAT(2, 0);
void i_syslog_error_handler(const struct failure_context *ctx,
			    const char *format, va_list args)
	ATTR_FORMAT(2, 0);

/* Open syslog and set failure/info/debug handlers to use it. */
void i_set_failure_syslog(const char *ident, int options, int facility);

/* Send failures to specified log file instead of stderr. */
void i_set_failure_file(const char *path, const char *prefix);

/* Send errors to stderr using internal error protocol. */
void i_set_failure_internal(void);
/* R
/* Default exit status codes that we could use. */
enum fatal_exit_status {
	FATAL_LOGOPEN	= 80, /* Can't open log file */
	FATAL_LOGWRITE  = 81, /* Can't write to log file */
	FATAL_LOGERROR  = 82, /* Internal logging error */
	FATAL_OUTOFMEM	= 83, /* Out of memory */
	FATAL_EXEC	= 84, /* exec() failed */

	FATAL_DEFAULT	= 89
};

enum log_type {
	LOG_TYPE_DEBUG,
	LOG_TYPE_INFO,
	LOG_TYPE_WARNING,
	LOG_TYPE_ERROR,
	LOG_TYPE_FATAL,
	LOG_TYPE_PANIC,

	LOG_TYPE_COUNT,
	/* special case */
	LOG_TYPE_OPTION
};

struct failure_line {
	pid dlua_push_dict(lua_State *L, struct dict *dict);
struct dict *dlua_check_dict(lua_State *L, int idx);

void dlua_dovecot_dict_register(struct dlua_script *script);

#endif

#endif
#ifndef AUTH_CLIENT_CONNECTION_H
#define AUTH_CLIENT_CONNECTION_H

#include "login-interface.h"

#define AUTH_CLIENT_MINOR_VERSION_CHANNEL_BINDING 3

struct auth_client_connection {
	struct connection conn;
	struct auth *auth;
	struct event *event;
	int refcount;

	unsigned int pid;
	unsigned int connect_uid;
	uint8_t cookie[LOGIN_REQUEST_COOKIE_SIZE];
ormat, size_t *len_r)
	ATTR_FORMAT_ARG(1);
/* Like printf_format_fix(), except the format string is written to data
   stack without actually allocating it. Data stack must not be used until
   format string is no longer needed. */
const char *printf_format_fix_unsafe(const char *format) ATTR_FORMAT_ARG(1);

#endif
#ifndef DSASL_CLIENT_H
#define DSASL_CLIENT_H

#include "iostream-ssl.h"

struct dsasl_client_settings {
	/* authentication ID - must be set with most mechanisms */
	const char *authid;
	/* authorization ID (who to log i_mech_ssl_required"
#define AUTH_CLIENT_FAIL_CODE_ANONYMOUS_DENIED  "anonymous_denied"

#endif
#ifndef MASTER_INSTANCE_H
#define MASTER_INSTANCE_H

#define MASTER_INSTANCE_FNAME "instances"

struct master_instance_list;

struct master_instance {
	time_t last_used;
	const char *name;
	const char *base_dir;
	const char *config_path;
};

struct master_instance_list *master_instance_list_init(const char *path);
void master_instance_list_deinit(struct master_instance_list **list);

/* Add/update last_used timestamp for an instance. Retuack_t *log_message_callback;
	void *log_message_callback_context;
	ARRAY(struct event_pointer) pointers;
	/* If the event's log level is at least this high, log it. If it's
	   lower, check for debug log filters etc. */
	enum log_type min_log_level;

	bool log_prefix_from_system_pool:1;
	bool log_prefix_replace:1;
	bool passthrough:1;
	bool forced_debug:1;
	bool forced_never_debug:1;
	bool always_log_source:1;
	bool sending_debug_log:1;
	bool disable_callbacks:1;

/* Fields that are exported & imported: */
	struct timeval tv_createrch_arg *arg,
	struct index_search_context *ctx);

#endif
#ifndef SMTP_COMMAND_PARSER_H
#define SMTP_COMMAND_PARSER_H

#include "smtp-command.h"

/* FIXME: drop unused */
enum smtp_command_parse_error {
	/* No error */
	SMTP_COMMAND_PARSE_ERROR_NONE = 0,
	/* Stream error */
	SMTP_COMMAND_PARSE_ERROR_BROKEN_STREAM,
	/* Unrecoverable generic error */
	SMTP_COMMAND_PARSE_ERROR_BROKEN_COMMAND,
	/* Recoverable generic error */
	SMTP_COMMAND_PARSE_ERROR_BAD_COMMAND,
	/* Stream error */
	SMTP_COMMAND_PARSE_ERROR_LINE_TOO_LONG,
	/* Data tostream, const char *name);
/* Try to write the boolean value to the output stream. Returns 1 if
   buffered, 0 if not, -1 if error. */
int json_ostream_write_bool(struct json_ostream *stream,
			    const char *name, bool value);
void json_ostream_nwrite_bool(struct json_ostream *stream,
			      const char *name, bool value);

/* object */

/* Try to descend into a JSON object by writing '{' to the output stream.
   Returns 1 if buffered, 0 if not, -1 if error. */
int json_ostream_descend_object(struct json_ostream *stream,
      ust like an ostream, the 'n' functions send their data with delayed error
   handling. json_ostream_nfinish() or json_ostream_ignore_last_errors()
   must be called after these functions before the stream is destroyed. If
   any of the data can't be sent due to stream's buffer getting full, all
   further 'n' function calls are ignored and json_ostream_nfinish() will
   fail.
 */

/* value */

/* object member */

int json_ostream_write_object_member(struct json_ostream *stream,
				     const char *name);
void json_ostream_nwrite_E_PAGER "pager"
#define DOVEADM_PRINT_TYPE_TABLE "table"
#define DOVEADM_PRINT_TYPE_SERVER "server"
#define DOVEADM_PRINT_TYPE_JSON "json"
#define DOVEADM_PRINT_TYPE_FORMATTED "formatted"

enum doveadm_print_header_flags {
	DOVEADM_PRINT_HEADER_FLAG_RIGHT_JUSTIFY 	= 0x01,
	/* Sticky headers work only on the doveadm client side. Trying to use
	   them via doveadm proxy won't work correctly. Practically this
	   restricts their usage only to the username. */
	DOVEADM_PRINT_HEADER_FLAG_STICKY	 	= 0x02,
	DOVEADM_PRINT_HEADER_FLAG_HIDE_line bool ATTR_NULL(1) ATTR_PURE
smtp_address_is_broken(const struct smtp_address *address)
{
	return (address != NULL &&
		smtp_address_isnull(address) &&
		(address->raw != NULL && *address->raw != '\0'));
}

#endif
#ifndef RESTRICT_ACCESS_H
#define RESTRICT_ACCESS_H

enum restrict_access_flags {
	/* If flags given to restrict_access() include
	 * RESTRICT_ACCESS_FLAG_ALLOW_ROOT, we won't kill
	 * ourself when we have root privileges. */
	RESTRICT_ACCESS_FLAG_ALLOW_ROOT = 1,
};

struct restrict_access_settings {
	/* UID to use, o_address **address_r,
			       const char **error_r) ATTR_NULL(4, 5);
/* Parse the RFC 5321 address from the provided path string. Returns 0 when
   the address was parsed successfully and -1 upon error. The address is
   returned in address_r. When address_r is NULL, the provided string will be
   verified for validity as a path only. The endp_r parameter is used to
   return a pointer to the end of the path string, so that the caller can
   continue parsing from there. When the SMTP_ADDRESS_PARSE_FLAG_IGNORE_BROKEN
   flag is seinput_line_default(struct connection *conn, const char *line);

/* Change handlers, calls connection_input_halt and connection_input_resume */
void connection_set_handlers(struct connection *conn, const struct connection_vfuncs *vfuncs);
void connection_set_default_handlers(struct connection *conn);

/* Checks if the given name is a valid DNS servername as per RFC1123 section 1.2,
   RFC8591 section 4.2.1 and for practicality, the '_' character.
   IP address like values are also accepted.
*/
bool connection_is_valid_dns_name(constlush callback */
	void *flush_callback;
	void *flush_context;

	/* Errno for connect() failure. */
	int connect_failed_errno;
	/* Reason for disconnection */
	enum connection_disconnect_reason disconnect_reason;

	/* We have received a version from remote end. */
	bool version_received:1;
	/* Set if this is a unix socket. */
	bool unix_socket:1;
	/* Unix peer credentials have been attempted to look up. */
	bool unix_peer_checked:1;
	/* Unix peer credentials were successfully looked up. */
	bool have_unix_credentials:1;
	/* ConnectiRWARD"
#define LMTP_RCPT_FORWARD_PARAMETER  "XRCPTFORWARD"

typedef void lmtp_client_created_func_t(struct client **client);

extern lmtp_client_created_func_t *hook_client_created;
extern struct event_category event_category_lmtp;

extern char *dns_client_socket_path, *base_dir;
extern struct mail_storage_service_ctx *storage_service;
extern struct anvil_client *anvil;

extern struct smtp_server *lmtp_server;

/* Sets the hook_client_created and returns the previous hook,
   which the new_hook should call if it's non-NULL. */
lmtpr *reason,
	const char *code) ATTR_NULL(3);
/* Called when client asks for SASL authentication to be aborted by sending
   "*" line. */
void sasl_server_auth_abort(struct client *client);

#endif
#ifndef OSTREAM_UNIX_H
#define OSTREAM_UNIX_H

struct ostream *o_stream_create_unix(int fd, size_t max_buffer_size);
/* Write fd to UNIX socket along with the next outgoing data block.
   Returns TRUE if fd is accepted, and FALSE if a previous fd still
   needs to be sent. */
bool o_stream_unix_write_fd(struct ostream *output, int fd);

#euery;

	/* #fragment (still encoded) */
	const char *enc_fragment;

	bool have_ssl:1;
};

/*
 * HTTP URL parsing
 */

enum http_url_parse_flags {
	/* Scheme part 'http:' is already parsed externally. This implies that
	   this is an absolute HTTP URL. */
	HTTP_URL_PARSE_SCHEME_EXTERNAL	= 0x01,
	/* Allow '#fragment' part in HTTP URL */
	HTTP_URL_ALLOW_FRAGMENT_PART = 0x02,
	/* Allow 'user:password@' part in HTTP URL */
	HTTP_URL_ALLOW_USERINFO_PART = 0x04,
	/* Allow URL to contain %00 */
	HTTP_URL_ALLOW_PCT_NUL = 0x08,
};

int http_ate highest modseq to be at least min_modseq. */
void mail_index_update_highest_modseq(struct mail_index_transaction *t,
				      uint64_t min_modseq);
/* Reset the index before committing this transaction. This is usually done
   only when UIDVALIDITY changes. */
void mail_index_reset(struct mail_index_transaction *t);
/* Remove MAIL_INDEX_HDR_FLAG_FSCKD from header if it exists. This must be
   called only during syncing so that the mailbox is locked. */
void mail_index_unset_fscked(struct mail_index_transaction *t);
/* Mark ind);
/* Convert UID range to sequence range. If no UIDs are found, returns FALSE and
   sequences are set to 0. Note that any of the returned sequences may have
   been expunged already. */
bool mail_index_lookup_seq_range(struct mail_index_view *view,
				 uint32_t first_uid, uint32_t last_uid,
				 uint32_t *first_seq_r, uint32_t *last_seq_r);
bool mail_index_lookup_seq(struct mail_index_view *view,
			   uint32_t uid, uint32_t *seq_r);
/* Find first mail with (mail->flags & flags_mask) == flags. Useful mostly for
   taking advantaon are expected to describe the
   mailbox's current state.

   The returned view already contains all the changes (except expunge
   requests). After applying sync records on top of backend flags they should
   match flags in the view. If they don't, there have been external changes.

   Returned expunges are treated as expunge requests. They're not really
   removed from the index until you mark them expunged to the returned
   transaction. If it's not possible to expunge the message (e.g. permission
   denied), simply don't mark called. */
bool mail_index_use_existing_permissions(struct mail_index *index);
void mail_index_set_permissions(struct mail_index *index,
				mode_t mode, gid_t gid, const char *gid_origin);
/* Set locking method and maximum time to wait for a lock
   (UINT_MAX = default). */
void mail_index_set_lock_method(struct mail_index *index,
				enum file_lock_method lock_method,
				unsigned int max_timeout_secs);
/* Override the default optimization-related settings. Anything set to 0 will
   use the default. */
void mail_index_set_optimiturn 0 in mail_index_sync_begin() */
	MAIL_INDEX_SYNC_FLAG_REQUIRE_CHANGES	= 0x08,
	/* Create the transaction with FSYNC flag */
	MAIL_INDEX_SYNC_FLAG_FSYNC		= 0x10,
	/* If we see "delete index" request transaction, finish it.
	   This flag also allows committing more changes to a deleted index. */
	MAIL_INDEX_SYNC_FLAG_DELETING_INDEX	= 0x20,
	/* Same as MAIL_INDEX_SYNC_FLAG_DELETING_INDEX, but finish index
	   deletion only once and fail the rest (= avoid race conditions when
	   multiple processes try to mark the index deleted) *by backend. Replacing flags doesn't change this. */
	MAIL_INDEX_MAIL_FLAG_BACKEND		= 0x40,
	/* Message flags haven't been written to backend. If
	   MAIL_INDEX_OPEN_FLAG_NO_DIRTY is set, this is treated as a
	   backend-specific flag with no special internal handling. */
	MAIL_INDEX_MAIL_FLAG_DIRTY		= 0x80,

	/* Force updating this message's modseq via a flag update record.
	   Note that this flag isn't saved to disk. */
	MAIL_INDEX_MAIL_FLAG_UPDATE_MODSEQ	= 0x100
};

enum mail_index_error_code {
	MAIL_INDEX_ERROR_CODE_NONE,
	MAIL_truct mail_transaction_keyword_reset *r);

void mail_index_sync_set_corrupted(struct mail_index_sync_map_ctx *ctx,
				   const char *fmt, ...)
	ATTR_FORMAT(2, 3) ATTR_COLD;

#ifdef DEBUG
void mail_index_map_check(struct mail_index_map *map);
#endif

#endif
#ifndef INDEX_MAILBOX_SIZE_H
#define INDEX_MAILBOX_SIZE_H

struct mailbox;

struct mailbox_vsize_update *
index_mailbox_vsize_update_init(struct mailbox *box);
void index_mailbox_vsize_update_deinit(struct mailbox_vsize_update **update);

void index_mailbox_vsize_hdr_expunge(strterate_visible_deinit(struct acl_lookup_dict_iter **iter);

#endif
#ifndef ISTREAM_HEADER_FILTER_H
#define ISTREAM_HEADER_FILTER_H

struct header_filter_istream;

enum header_filter_flags {
	/* Include only specified headers in output.*/
	HEADER_FILTER_INCLUDE		= 0x01,
	/* Exclude specified headers from output. */
	HEADER_FILTER_EXCLUDE		= 0x02,

	/* Use LF linefeeds instead of CRLF. */
	HEADER_FILTER_NO_CR		= 0x04,
	/* Return EOF at the beginning of message body. */
	HEADER_FILTER_HIDE_BODY		= 0x08,
	/* If the empty "end of headergroups that have any settings in the given
   module parser index. Returns TRUE if any groups were returned. */
bool config_parsed_get_includes(struct config_parsed *config,
				const struct config_filter_parser *filter,
				unsigned int parser_idx,
				ARRAY_TYPE(config_include_group) *groups);

void config_parsed_free(struct config_parsed **config);

void config_parse_load_modules(bool dump_config_import);

void config_parser_deinit(void);

#endif
#ifndef AUTH_MASTER_CONNECTION_H
#define AUTH_MASTER_CONNECTION_H

struct stat;
strges. */
	unsigned int import_commit_msgs_interval;
	/* Input state for DSYNC_BRAIN_SYNC_TYPE_STATE */
	const char *state;
};

#define DSYNC_LIST_CONTEXT(obj) \
	MODULE_CONTEXT(obj, dsync_mailbox_list_module)
struct dsync_mailbox_list {
	union mailbox_list_module_context module_ctx;
	bool have_orig_escape_char;
};
extern MODULE_CONTEXT_DEFINE(dsync_mailbox_list_module,
			     &mailbox_list_module_register);

struct dsync_brain *
dsync_brain_master_init(struct mail_user *user, struct dsync_ibc *ibc,
			enum dsync_brain_sync_type synstruct dsync_ibc;

enum dsync_brain_flags {
	DSYNC_BRAIN_FLAG_SEND_MAIL_REQUESTS	= 0x01,
	DSYNC_BRAIN_FLAG_BACKUP_SEND		= 0x02,
	DSYNC_BRAIN_FLAG_BACKUP_RECV		= 0x04,
	DSYNC_BRAIN_FLAG_DEBUG			= 0x08,
	DSYNC_BRAIN_FLAG_SYNC_VISIBLE_NAMESPACES= 0x10,
	/* Sync everything but the actual mails (e.g. mailbox creates,
	   deletes) */
	DSYNC_BRAIN_FLAG_NO_MAIL_SYNC		= 0x20,
	/* Used with BACKUP_SEND/RECV: Don't force the
	   Use the two-way syncing algorithm, but don't actually modify
	   anything locally. (Useful during migration.) */
	Ddress *path, bool add);

void smtp_server_reply_submit(struct smtp_server_reply *reply);
void smtp_server_reply_submit_duplicate(struct smtp_server_cmd_ctx *_cmd,
					unsigned int index,
					unsigned int from_index);

/* Submit a reply for the command at the specified index (> 0 only if more than
   a single reply is expected). */
void smtp_server_reply_indexv(struct smtp_server_cmd_ctx *_cmd,
			      unsigned int index, unsigned int status,
			      const char *enh_code,
			      const char *fmt, va_list args) ATTR_FORMAT(5, 0)		      ATTR_NULL(3);
void smtp_server_connection_terminate_full(struct smtp_server_connection **_conn,
					   const char *enh_code,
					   const char *reply_reason,
					   const char *log_reason);

bool smtp_server_connection_data_check_state(struct smtp_server_cmd_ctx *cmd);
void smtp_server_connection_data_chunk_init(struct smtp_server_cmd_ctx *cmd);
int smtp_server_connection_data_chunk_add(struct smtp_server_cmd_ctx *cmd,
					  struct istream *chunk,
					  uoff_t chunk_size, bool chunk_last,
					  bool client_input);

enmeters */
	const char *const *rcpt_param_extensions;
	/* Accept these additional custom XCLIENT fields */
	const char *const *xclient_extensions;

	/* The kernel send/receive buffer sizes used for the connection sockets.
	   Configuring this is mainly useful for the test suite. The kernel
	   defaults are used when these settings are 0. */
	size_t socket_send_buffer_size;
	size_t socket_recv_buffer_size;

	/* Event to use for the smtp server. */
	struct event *event_parent;

	/* Enable logging debug messages */
	bool debug:1;
	/* A The SMTP server API takes care of transaction state checking.
	   However, until all previous commands are handled, a transaction
	   command cannot rely on the transaction state being final. Use
	   cmd->hook_next to get notified when all previous commands are
	   finished and the current command is next in line to reply.

	   If the implementation does not need asynchronous behavior, set
	   max_pipelined_commands=1 and don't return 0 from any command handler.
	  */

	/* HELO/EHLO/LHLO */
	int (*conn_cmd_helo)(void *conn_ctx, st smtp_server_recipient *rcpt,
	enum smtp_server_recipient_hook_type type,
	smtp_server_rcpt_func_t *func);
#define smtp_server_recipient_remove_hook(_rcpt, _type, _func) \
	smtp_server_recipient_remove_hook((_rcpt), (_type), \
		(smtp_server_rcpt_func_t *)(_func));

/*
 * Transaction
 */

enum smtp_server_trace_rcpt_to_address {
	/* Don't add recipient address to trace header. */
	SMTP_SERVER_TRACE_RCPT_TO_ADDRESS_NONE,
	/* Add final recipient address to trace header. */
	SMTP_SERVER_TRACE_RCPT_TO_ADDRESS_FINAL,
	/* Add original re_COUNT 100
/* readdir() should be pretty fast to do, but check anyway every n files
   to see if we need to touch the uidlist lock. */
#define MAILDIR_SLOW_CHECK_COUNT 10000
/* If syncing takes longer than this, log a warning. */
#define MAILDIR_SYNC_TIME_WARN_SECS MAIL_TRANSACTION_LOG_LOCK_WARN_SECS

struct maildir_mailbox;
struct maildir_sync_context;
struct maildir_keywords_sync_ctx;
struct maildir_index_sync_context;

int maildir_sync_is_synced(struct maildir_mailbox *mbox);

struct mailbox_sync_context *
maildir_storage_sync_i
	/* offset in input stream where part begins */
	uoff_t start_offset;
	uoff_t size;

	/* If non-zero, this attachment was saved as base64-decoded and it
	   need to be encoded back before presenting it to client. Each line
	   (except last one) consists of this many base64 blocks (4 chars of
	   base64 encoded data). */
	unsigned int base64_blocks_per_line;
	/* Line feeds are CRLF instead of LF */
	bool base64_have_crlf;
};
ARRAY_DEFINE_TYPE(mail_attachment_extref, struct mail_attachment_extref);

void index_attachment_save_begin(x_list_path_type type);
/* Returns mailbox's change log, or NULL if it doesn't have one. */
struct mailbox_log *mailbox_list_get_changelog(struct mailbox_list *list);
/* Specify timestamp to use when writing mailbox changes to changelog.
   The same timestamp is used until stamp is set to (time_t)-1, after which
   current time is used */
void mailbox_list_set_changelog_timestamp(struct mailbox_list *list,
					  time_t stamp);
/* Get the number of mailboxes in the list, ignoring any ACLs. Auto-created
   mailboxes that haven't beeX_LIST_PATH_TYPE_COUNT
};

enum mailbox_list_file_type {
	MAILBOX_LIST_FILE_TYPE_UNKNOWN = 0,
	MAILBOX_LIST_FILE_TYPE_FILE,
	MAILBOX_LIST_FILE_TYPE_DIR,
	MAILBOX_LIST_FILE_TYPE_SYMLINK,
	MAILBOX_LIST_FILE_TYPE_OTHER
};

enum mailbox_list_get_storage_flags {
	MAILBOX_LIST_GET_STORAGE_FLAG_SAVEONLY = BIT(0),
};

struct mailbox_permissions {
	/* The actual uid/gid of the mailbox */
	uid_t file_uid;
	gid_t file_gid;

	/* mode and GID to use for newly created files/dirs.
	   (gid_t)-1 is used if the default GID can be used. */
	mode_t fv))), \
	array_sort_i(&(array)->arr, (int (*)(const void *, const void *))cmp))

#define ARRAY_SEARCH_CALL(func, array, key, cmp) \
	TYPE_CHECKS(void *, \
		CALLBACK_TYPECHECK(cmp, int (*)(typeof(const typeof(*key) *), \
						typeof(*(array)->v))), \
		array_##func##_i( \
			&(array)->arr, (const void *)key, \
			(int (*)(const void *, const void *))cmp))

const void *array_bsearch_i(const struct array *array, const void *key,
		            int (*cmp)(const void *, const void *));
static inline void *array_bsearch_modifiable_i(strPE_CHECKS(void, ARRAY_TYPE_CHECK(array, data), \
	array_insert_i(&(array)->arr, idx, data, count))

static inline void
array_delete_i(struct array *array, unsigned int idx, unsigned int count)
{
	buffer_delete(array->buffer, idx * array->element_size,
		      count * array->element_size);
}
#define array_delete(array, idx, count) \
	array_delete_i(&(array)->arr, idx, count)

static inline const void *
array_get_i(const struct array *array, unsigned int *count_r)
{
	*count_r = array_count_i(array);
	return array->buffer->data;
}
#de!= elem ## __foreach_end; (elem)++)
#define array_foreach_modifiable(array, elem) \
	for (const void *elem ## _end = \
		(const char *)(elem = ARRAY_TYPE_CAST_MODIFIABLE(array) \
			buffer_get_modifiable_data((array)->arr.buffer, NULL)) + \
			(array)->arr.buffer->used; \
	     elem != elem ## _end; (elem)++)

/* Iterate the array in reverse order. */
#define array_foreach_reverse(array, elem) \
	for (elem = CONST_PTR_OFFSET(*(array)->v, (array)->arr.buffer->used); \
	     (const char *)(elem--) > (const char *)*(array)->v; )
#defi *append_ctx,
				   enum mail_index_transaction_change *changes_r);
int mail_transaction_expunge_guid_cmp(const struct mail_transaction_expunge_guid *e1,
				      const struct mail_transaction_expunge_guid *e2);
unsigned int
mail_index_transaction_get_flag_update_pos(struct mail_index_transaction *t,
					   unsigned int left_idx,
					   unsigned int right_idx,
					   uint32_t seq);

void mail_index_ext_using_reset_id(struct mail_index_transaction *t,
				   uint32_t ext_id, uint32_t reset_id);

#endif
#ifndef RFC822_PARSER_H
#vent *event_parent, const char **error_r);

/* run dlua_script_init function */
int dlua_script_init(struct dlua_script *script, const char **error_r);

/* Reference lua script */
void dlua_script_ref(struct dlua_script *script);

/* Unreference a script, calls deinit and frees when no more
   references exist */
void dlua_script_unref(struct dlua_script **_script);

/* see if particular function is registered */
bool dlua_script_has_function(struct dlua_script *script, const char *fn);

#endif
#ifndef MAIL_INDEX_TRANSACTION_PRIVAT given string (e.g. for
   logging). The output is a single valid UTF-8 line without control
   characters. Multi-line literals are replaced with a generic placeholder. */
void imap_write_args_for_human(string_t *dest, const struct imap_arg *args);
/* Like imap_write_args(), but return the string allocated from data stack. */
const char *imap_args_to_str(const struct imap_arg *args);

/* Writes capabilities from boollist to string.
   Capabilities beginning with IMAP4 are written first
   to avoid breaking clients that expect IMAP4L:
		literal = "null";
		*size_r = strlen(literal);
		return (const unsigned char *)literal;
	default:
		i_unreached();
	}
	return json_value_get_data(&jnode->value, size_r);
}

static inline int
json_node_get_stream(const struct json_node *jnode,
		      struct istream **stream_r)
{
	if (jnode->type != JSON_TYPE_STRING)
		return -1;

	return json_value_get_stream(&jnode->value, stream_r);
}

/* number */

static inline ATTR_PURE bool
json_node_is_number(const struct json_node *jnode)
{
	return (jnode->type == JSON_TYPE_NUMBER);
}
n (jnode->value.content_type == JSON_CONTENT_TYPE_NONE);
	default:
		break;
	}
	return FALSE;
}

/* string */

static inline ATTR_PURE bool
json_node_is_string(const struct json_node *jnode)
{
	return (jnode->type == JSON_TYPE_STRING);
}

static inline ATTR_PURE const char *
json_node_get_str(const struct json_node *jnode)
{
	switch (jnode->type) {
	case JSON_TYPE_STRING:
	case JSON_TYPE_NUMBER:
	case JSON_TYPE_TEXT:
		break;
	case JSON_TYPE_TRUE:
		return "true";
	case JSON_TYPE_FALSE:
		return "false";
	case JSON_TYPE_NULL:
		retalue_get_uintmax(const struct json_value *jvalue, uintmax_t *num_r)
{
	i_assert(jvalue->content_type == JSON_CONTENT_TYPE_INTEGER);
	if (jvalue->content.intnum < 0)
		return -1;
	*num_r = (uintmax_t)jvalue->content.intnum;
	return 0;
}

static inline int
json_value_get_intmax(const struct json_value *jvalue, intmax_t *num_r)
{
	i_assert(jvalue->content_type == JSON_CONTENT_TYPE_INTEGER);
	*num_r = jvalue->content.intnum;
	return 0;
}

#define JSON_VALUE_GET_U__TEMPLATE(name, type, uint_max)                \
static inline int       CATION_EVENT_TRIGGER_MBOX_SUBSCRIBE	= 0x008,

	/* Message actions */
	PUSH_NOTIFICATION_EVENT_TRIGGER_MSG_SAVE_NEW	  = 0x010,
	PUSH_NOTIFICATION_EVENT_TRIGGER_MSG_SAVE_APPEND   = 0x020,
	PUSH_NOTIFICATION_EVENT_TRIGGER_MSG_EXPUNGE	   = 0x040,
	PUSH_NOTIFICATION_EVENT_TRIGGER_MSG_FLAGCHANGE	= 0x080,
	PUSH_NOTIFICATION_EVENT_TRIGGER_MSG_KEYWORDCHANGE = 0x100,
};

/* Mailbox actions. */
void push_notification_trigger_mbox_create(
	struct push_notification_txn *txn, struct mailbox *box,
	struct push_notification_txn_mbox *mbox);
void py the application immediately about any error condition set earlier
   using wrapper_ostream_set_error() by calling the ostream flush callback
   right now.
 */
void wrapper_ostream_notify_error(struct wrapper_ostream *wostream);

#endif
#ifndef ACL_API_H
#define ACL_API_H

#include <sys/stat.h>

#include "acl-rights.h"

struct mailbox_list;
struct mail_storage;
struct mailbox;
struct acl_object;
struct acl_backend;

#define MAILBOX_ATTRIBUTE_PREFIX_ACL \
	MAILBOX_ATTRIBUTE_PREFIX_DOVECOT_PVT"acl/"

int acl_backend_init_auto(structtream_trigger_flush(struct wrapper_ostream *wostream);

/* This function returns the size of the data buffered in the wrapper stream,
   but only when the output stream is finished using o_stream_finish(). When the
   output stream is finished, the data is complete and this function returns
   TRUE and size_r is set to the size. If it is not complete, this function
   returns FALSE and size_r is not assigned. This function is meant to be called
   just before sending the first block of data internally for deciding between
   sendinwill implicitly run its own
   ioloop.

   It is possible to have the wrapper output stream object available even before
   the data can be written anywhere, even before any form of output object (a
   connection) exists. In that case, any data written to the wrapper stream is
   buffered until the buffer is full. Once that happens, the stream will block
   or refuse writes until the underlying output becomes available.

   The wrapper output stream is not meant to be used directly. Instead, it is
   to be used as part of the imple pool, void *mem,
			 size_t old_size, size_t new_size)
		ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL;

	/* Frees all the memory in pool. NOTE: system_pool doesn't support
	   this and crashes if it's used */
	void (*clear)(pool_t pool);

	/* Returns the maximum amount of bytes that can be allocated with
	   minimal trouble. If there's no such concept, always returns 0. */
	size_t (*get_max_easy_alloc_size)(pool_t pool);
};

struct pool {
	const struct pool_vfuncs *v;
	ARRAY(pool_t) external_refs;

	bool alloconly_pool:1;
	bool daigher precision time, i.e. a maximum of 6 digits is allowed. Note that
   ".1" is handled as ".1000000" so the string should have been written using
   "%06u" printf format. */
int str_to_timeval(const char *str, struct timeval *tv_r)
	ATTR_WARN_UNUSED_RESULT;

#endif
#ifndef RESTRICT_PROCESS_SIZE_H
#define RESTRICT_PROCESS_SIZE_H

#include <sys/time.h>
#ifdef HAVE_SYS_RESOURCE_H
#  include <sys/resource.h>
#endif

/* Restrict max. process size. */
void restrict_process_size(rlim_t bytes);
/* Restrict max. number of processes. */
v to specified length, but also make sure the truncation
   doesn't happen in the middle of an UTF-8 character sequence. In that case,
   the string will end up being up to a few bytes smaller than len. If it's
   already smaller to begin with, do nothing. */
void str_truncate_utf8(string_t *str, size_t len);

#endif
#ifndef AUTH_REQUEST_HANDLER_H
#define AUTH_REQUEST_HANDLER_H

struct auth_request;
struct auth_client_connection;
struct auth_master_connection;
struct auth_stream_reply;

enum auth_client_result {
	AUTH_CLIENT_RESULT_**cache);

/* Change cached file descriptor. Invalidates the whole cache. */
void file_cache_set_fd(struct file_cache *cache, int fd);

/* Change the memory allocated for the cache. This can be used to immediately
   set the maximum size so there's no need to grow the memory area with
   possibly slow copying. */
int file_cache_set_size(struct file_cache *cache, uoff_t size);

/* Read data from file, returns how many bytes was actually read or -1 if
   error occurred. */
ssize_t file_cache_read(struct file_cache *cache, uoff_t offso special notify support */
/* #undef IOLOOP_NOTIFY_NONE */

/* Implement I/O loop with poll() */
/* #undef IOLOOP_POLL */

/* Implement I/O loop with select() */
/* #undef IOLOOP_SELECT */

/* Define to the sub-directory where libtool stores uninstalled libraries. */
#define LT_OBJDIR ".libs/"

/* Required memory alignment */
#define MEM_ALIGN_SIZE 8

/* Define if shared mmaps don't get updated by write()s */
/* #undef MMAP_CONFLICTS_WRITE */

/* Dynamic module suffix */
#define MODULE_SUFFIX ".so"

/* Maximum value of off_t */
#d/* Define if you want textcat support for lib-language */
/* #undef HAVE_LANG_TEXTCAT */

/* Define this if you have libbsd */
/* #undef HAVE_LIBBSD */

/* libcap is installed for cap_init() */
#define HAVE_LIBCAP /**/

/* Define to 1 if you have the <libexttextcat/textcat.h> header file. */
/* #undef HAVE_LIBEXTTEXTCAT_TEXTCAT_H */

/* Define if you want ICU normalization support for lib-language */
#define HAVE_LIBICU /**/

/* Define if you have libsodium */
/* #undef HAVE_LIBSODIUM */

/* Define to 1 if you have libsystemd */
/*ou have the <gssapi_krb5.h> header file. */
/* #undef HAVE_GSSAPI_KRB5_H */

/* GSSAPI supports SPNEGO */
/* #undef HAVE_GSSAPI_SPNEGO */

/* Define to 1 if you have the `gsskrb5_register_acceptor_identity' function.
   */
/* #undef HAVE_GSSKRB5_REGISTER_ACCEPTOR_IDENTITY */

/* Define if you have the iconv() function and it works. */
#define HAVE_ICONV 1

/* Define to 1 if you have the `inotify_init' function. */
#define HAVE_INOTIFY_INIT 1

/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1

/* ite support */
/* #undef BUILD_SQLITE */

/* GSSAPI support is built in */
/* #undef BUILTIN_GSSAPI */

/* LDAP support is built in */
/* #undef BUILTIN_LDAP */

/* Lua support is builtin */
#define BUILTIN_LUA /**/

/* Define if _XPG6 macro is needed for crypt() */
#define CRYPT_USE_XPG6 /**/

/* Build with extra debugging checks */
/* #undef DEBUG */

/* Path to random source */
#define DEV_URANDOM_PATH "/dev/urandom"

/* Disable asserts */
/* #undef DISABLE_ASSERTS */

/* Lua scripts will be able to yield */
#define DLUA_WITH_YIMAND_STATE_AUTH_FAILED,
	/* Client was unexpectedly disconnected. */
	IMAPC_COMMAND_STATE_DISCONNECTED
};
extern const char *imapc_command_state_names[];

enum imapc_capability {
	IMAPC_CAPABILITY_SASL_IR	= 0x01,
	IMAPC_CAPABILITY_LITERALPLUS	= 0x02,
	IMAPC_CAPABILITY_QRESYNC	= 0x04,
	IMAPC_CAPABILITY_IDLE		= 0x08,
	IMAPC_CAPABILITY_UIDPLUS	= 0x10,
	IMAPC_CAPABILITY_AUTH_PLAIN	= 0x20,
	IMAPC_CAPABILITY_STARTTLS	= 0x40,
	IMAPC_CAPABILITY_X_GM_EXT_1	= 0x80,
	IMAPC_CAPABILITY_CONDSTORE	= 0x100,
	IMAPC_CAPABILITY_NAMESPACE	= 0x200,
	IM rename()ing it to trash_dir and afterwards
   recursively deleting the trash_dir. If the rename() fails because trash_dir
   already exists, the trash_dir is first deleted and rename() is retried.

   Returns 1 if the rename() succeeded. Returns 0 if rename() fails with EXDEV,
   which means the source and destination are on different filesystems and
   the rename can never succeed.

   If the path didn't exist, returns -1 and sets the list error to
   MAIL_ERROR_NOTFOUND.

   Attempting to delete INBOX or the namespace root returD_SUBSCRIBED flags,
   clearing them if they already are there when they shouldn't. */
void mailbox_list_set_subscription_flags(struct mailbox_list *list,
					 const char *vname,
					 enum mailbox_info_flags *flags);

/* Add subscriptions matching the iteration to the given tree */
void mailbox_list_subscriptions_fill(struct mailbox_list_iterate_context *ctx,
				     struct mailbox_tree_context *tree,
				     bool default_nonexistent);

/* Iterate through subscriptions, call mailbox_list.get_mailbox_flags()
   if necessary for mespace(struct client_command_context *cmd, const char **mailbox);
struct mail_namespace *
client_find_namespace_full(struct client *client,
			   const char **mailbox, const char **client_error_r);

/* Returns TRUE if mailbox is selected. If not, sends "No mailbox selected"
   error message to client. */
bool client_verify_open_mailbox(struct client_command_context *cmd);
/* Close the selected mailbox. */
void imap_client_close_mailbox(struct client *client);

/* Open APPEND/COPY destination mailbox. */
int client_open_save_dest_ber for every created parser. Used by sorting. */
	unsigned int create_order;
	/* Number of filters in this parser and parent parsers that have
	   filter.filter_name_array=TRUE. */
	unsigned int named_list_filter_count;

	/* Filter parser tree. These are used only for doveconf's human output
	   to write the filters in nice nested hierarchies. */
	struct config_filter_parser *parent;
	struct config_filter_parser *children_head, *children_tail, *prev, *next;

	/* When this filter is used, it includes settings from these groups. */
	k(), but reads strings bigger than
  `threshold' octets as an istream with `max_buffer_size'. When
  `temp_path_prefix' is not NULL, the returned stream is made seekable and
   can be read at a later time.
 */
int json_istream_walk_stream(struct json_istream *stream,
			     size_t threshold, size_t max_buffer_size,
			     const char *temp_path_prefix,
			     struct json_node *node_r);

/* Read a full JSON tree starting at the current position. If a node was
   already read using json_istream_read(), is used as the tree root. Retdiately. Returns 1 on success, 0 if more data is
   needed from the input stream, or -1 upon error or EOF. The last node in
   an object/array reads as JSON_TYPE_OBJECT/JSON_TYPE_ARRAY with
   JSON_CONTENT_TYPE_NONE. Use json_node_is_end() or the more specific
   json_node_is_object_end()/json_node_is_array_end() to check for these.
 */
int json_istream_read(struct json_istream *stream,
		      struct json_node *node_r);
/* Read the next JSON node from the stream. This is equivalent to calling
   json_istream_read() and subsequentl const ARRAY_TYPE(seq_range) *array);
/* Get the nth sequence (0 = first). Returns FALSE if idx is too large. */
bool seq_range_array_iter_nth(struct seq_range_iter *iter, unsigned int n,
			      uint32_t *seq_r);

#endif
#ifndef MESSAGE_ADDRESS_H
#define MESSAGE_ADDRESS_H

struct smtp_address;

enum message_address_parse_flags {
	/* If enabled, missing mailbox and domain are set to MISSING_MAILBOX
	   and MISSING_DOMAIN strings. Otherwise they're set to "". */
	MESSAGE_ADDRESS_PARSE_FLAG_FILL_MISSING = BIT(0),
	/* Require local-pe is achieved. Note that the overriding function then
	   assumes the responsibility to submit the default reply when none is
	   submitted and the base implementation returns 1.

	   Also note that only the default backend actually triggers all of
	   these command callbacks. Secondary backends only get called for
	   transaction commands and only when that backend is tied to the
	   transaction somehow; e.g., as the primary transaction backend or when
	   it is tied to one of the approved recipients.
	  */
	int (*cmd_helo)(strucackend,
			   struct smtp_server_transaction *trans);

	/* Command handlers:

	   These implement the behavior of the various core SMTP commands.
	   SMTP commands are handled asynchronously, which means that the
	   command is not necessarily finished when these handlers end. A
	   command is finished either when 1 is returned or a reply is submitted
	   for it. When a handler returns 0, the command implementation is
	   waiting for an external event and when it returns -1 an error
	   occurred. When 1 is returned, a default succebuffer.
 */
void uri_data_encode(string_t *out, const unsigned char esc_table[256],
		     unsigned char esc_mask, const char *esc_extra,
		     const char *data) ATTR_NULL(4);

/* Append the provided scheme to the out buffer */
void uri_append_scheme(string_t *out, const char *scheme);

/* Append partial user data (i.e. some part of what comes before '@') to the out
   buffer. No '@' is produced. Characters are percent-encoded when necessary.
   Characters in esc are always percent-encoded, even when these are valid
   'userinfo' on 3.5 of RFC 1034 and Section 2.1 of
   RFC 1123. An IP address literal is always allowed. Returns 1 if successful, 0
   if the first character is not valid for a host name, and -1 in case of error.
   The provided host struct is filled in with the parsed data, all allocated
   from the parser pool. The host parameter can be NULL to use this function for
   merely checking for valid 'host' syntax.
 */
int uri_parse_host(struct uri_parser *parser, struct uri_host *host)
		   ATTR_NULL(2);

/* Parse the URI 'authority' syntax. Returemote_ip, local_ip, real_local_ip, real_remote_ip;
	in_port_t remote_port, local_port, real_local_port, real_remote_port;
	const char *local_name;

	struct mail_user *raw_mail_user;
	const char *my_domain;

	pool_t state_pool;
	struct client_state state;
	struct istream *dot_input;
	struct lmtp_local *local;
	struct lmtp_proxy *proxy;

	/* Module-specific contexts. */
	ARRAY(union lmtp_module_context *) module_contexts;

	bool disconnected:1;
	bool destroyed:1;
	bool end_client_tls_secured:1;
	bool end_client_tls_secured_set:1;
};
ame. Returns NULL if handshake
   has not yet been made.

   This returns values like SSLv3, TLSv1, TLSv1.1, TLSv1.2
*/
const char *ssl_iostream_get_protocol_name(struct ssl_iostream *ssl_io);
/* Returns currently used SSL protocol version. */
enum ssl_iostream_protocol_version
ssl_iostream_get_protocol_version(struct ssl_iostream *ssl_io);
/* Returns 0 if channel binding type is supported with channel binding data of
   requested type in data_r. Returns -1 if channel binding (of that type) is not
   supported and error message is server_context_cache_get() to
   get the context and call io_stream_create_ssl_server(). */
int io_stream_autocreate_ssl_server(
	const struct ssl_iostream_server_autocreate_parameters *parameters,
	struct istream **input, struct ostream **output,
	struct ssl_iostream **iostream_r,
	const char **error_r);
/* Shutdown SSL connection and unreference ssl iostream.
   The returned input and output streams must also be unreferenced. */
void ssl_iostream_destroy(struct ssl_iostream **ssl_io);

/* If verbose logging is enabled, use the spcol */
	SSL_IOSTREAM_PROTOCOL_VERSION_TLS1_3,
	/* Protocol version newer than Dovecot recognizes. */
	SSL_IOSTREAM_PROTOCOL_VERSION_NEW,
};

enum ssl_iostream_flags {
	/* Enable ssl_iostream_settings.allow_invalid_cert after context is
	   already created. If the context already has
	   ssl_iostream_settings.allow_invalid_cert enabled, it can't
	   be anymore disabled. */
	SSL_IOSTREAM_FLAG_ALLOW_INVALID_CERT = BIT(0),
	/* Disable ssl_iostream_settings.ca_file and ca_dir settings in
	   io_stream_autocreate_ssl_client() when creatih counting command statistics. This is called automatically when
   command_exec() returns, but it should be called explicitly if the stats are
   needed during command_exec(). */
void command_stats_flush(struct client_command_context *cmd);

const struct command *command_find(const char *name);

void commands_init(void);
void commands_deinit(void);

/* IMAP4rev1 commands: */

/* Non-Authenticated State */
bool cmd_logout(struct client_command_context *cmd);

bool cmd_capability(struct client_command_context *cmd);
bool cmd_noop(stint module_id = module_get_context_id(id);
	if (module_id >= array_count_i(array))
		return NULL;
	void **ctx = (void **)array_idx_modifiable_i(array, module_id);
	return *ctx;
}
#define MODULE_CONTEXT(obj, id_ctx) \
	(TRUE ? module_context_get(&(obj)->module_contexts.arr, &(id_ctx).id) : \
	OBJ_REGISTER_COMPATIBLE(obj, id_ctx))

static inline void *
module_context_get_require(struct array *array, struct module_context_id *id,
			   const char *panic_message)
{
	void *ctx = module_context_get(array, id);
	if (ctx == NULL)
		i_panicfndef FS_SIS_COMMON_H
#define FS_SIS_COMMON_H

#include "fs-api-private.h"

#define HASH_DIR_NAME "hashes"

int fs_sis_path_parse(struct fs_file *file, const char *path,
		      const char **dir_r, const char **hash_r);
void fs_sis_try_unlink_hash_file(struct fs_file *sis_file,
				 struct fs_file *super_file);

#endif

#ifndef TEST_SUBPROCESS_H
#define TEST_SUBPROCESS_H

#define TEST_SIGNALS_DEFAULT_TIMEOUT_MS 10000

struct test_subprocess;

/* Fork a sub-process for this test. The func is the main function for the
   forked sub-p_r);
/* Like mail_search_mime_part_to_imap(), but append only a single MIMEPART
   key. */
bool mail_search_mime_arg_to_imap(string_t *dest,
	const struct mail_search_mime_arg *arg, const char **error_r);

#endif
#ifndef JSON_TEXT_H
#define JSON_TEXT_H

#include "json-parser.h"
#include "json-generator.h"

int json_text_format_data(const void *data, size_t size,
			  enum json_parser_flags parser_flags,
			  const struct json_limits *limits,
			  const struct json_format *format,
			  buffer_t *outbuf, const char **error_r);
int jscache that the mail is now closed. Any records added with
   mail_cache_add() are unlikely to be required again. This mainly tells
   mail_index_path=MEMORY that it can free up the memory used by the mail. */
void mail_cache_close_mail(struct mail_cache_transaction_ctx *ctx,
			   uint32_t seq);

/* Returns 1 if field exists, 0 if not, -1 if error. */
int mail_cache_field_exists(struct mail_cache_view *view, uint32_t seq,
			    unsigned int field_idx);
/* Returns TRUE if something is cached for the message, FALSE if not. */
bool mnd the TABs or spaces
	   for continued lines. */
	MAIL_CACHE_FIELD_HEADER,

	MAIL_CACHE_FIELD_COUNT
};

struct mail_cache_field {
	/* Unique name for the cache field. The field name doesn't matter
	   internally. */
	const char *name;
	/* Field index name. Used to optimize accessing the cache field. */
	unsigned int idx;

	/* Type of the field */
	enum mail_cache_field_type type;
	/* Size of the field, if it's a fixed size type. */
	unsigned int field_size;
	/* Current caching decision */
	enum mail_cache_decision_type decision;
	BACKEND_FLAG_NORMALIZE_INPUT	= 0x02,
	/* Send only fully indexable words rather than randomly sized blocks */
	FTS_BACKEND_FLAG_BUILD_FULL_WORDS	= 0x04,
	/* Fuzzy search works */
	FTS_BACKEND_FLAG_FUZZY_SEARCH		= 0x08,
	/* Tokenize all the input. update_build_more() will be called a single
	   directly indexable token at a time. Searching will modify the search
	   args so that lookup() sees only tokens that can be directly
	   searched. */
	FTS_BACKEND_FLAG_TOKENIZED_INPUT	= 0x10
};

struct fts_header_filters {
	pool_t pool;
	ARRAthe other hand if you have a tee-istream, it's not a good idea
	   to let it get to "buffer full" state. */
	bool drain_parent_input;

	/* Returns TRUE if message part is wanted to be stored as separate
	   attachment. If NULL, assume we want the attachment. */
	bool (*want_attachment)(const struct istream_attachment_header *hdr,
				void *context);
	/* Create a temporary file. */
	int (*open_temp_fd)(void *context);
	/* Create output stream for attachment */
	int (*open_attachment_ostream)(struct istream_attachment_info *info,
			ked as corrupted earlier */
	MDBOX_REBUILD_REASON_CORRUPTED = BIT(0),
	/* Mailbox index was marked fsck'd */
	MDBOX_REBUILD_REASON_MAILBOX_FSCKD = BIT(1),
	/* dovecot.map.index was marked fsck'd */
	MDBOX_REBUILD_REASON_MAP_FSCKD = BIT(2),
	/* Forced rebuild (e.g. doveadm force-resync) */
	MDBOX_REBUILD_REASON_FORCED = BIT(3),
};

int mdbox_storage_rebuild(struct mdbox_storage *storage,
			  struct mailbox *fsckd_box,
			  enum mdbox_rebuild_reason reason);

#endif
#ifndef POP3_COMMANDS_H
#define POP3_COMMANDS_H

struct pop3_commanp UID for the map sequence. */
uint32_t mdbox_map_lookup_uid(struct mdbox_map *map, uint32_t seq);
/* Returns the total number of messages in the map. */
unsigned int mdbox_map_get_messages_count(struct mdbox_map *map);

/* Get all messages from file */
int mdbox_map_get_file_msgs(struct mdbox_map *map, uint32_t file_id,
			    ARRAY_TYPE(mdbox_map_file_msg) *recs);

/* Begin atomic context. There can be multiple transactions/appends within the
   same atomic context. */
struct mdbox_map_atomic_context *mdbox_map_atomic_begin(strucmtp_client_login_callback {
	smtp_client_command_callback_t *callback;
	void *context;
};

struct smtp_client_connection {
	struct connection conn;
	pool_t pool;
	int refcount;
	struct event *event;

	struct smtp_client *client;

	enum smtp_protocol protocol;
	const char *path, *host;
	in_port_t port;
	enum smtp_client_connection_ssl_mode ssl_mode;

	struct smtp_client_settings set;
	char *password;
	ARRAY(struct smtp_client_capability_extra) extra_capabilities;

	pool_t cap_pool;
	struct {
		enum smtp_capability standard;
		ARRAY(pe *)doveadm_mail_cmd_alloc_size(sizeof(type))

void doveadm_mail_failed_error(struct doveadm_mail_cmd_context *ctx,
			       enum mail_error error);
void doveadm_mail_failed_storage(struct doveadm_mail_cmd_context *ctx,
				 struct mail_storage *storage);
void doveadm_mail_failed_mailbox(struct doveadm_mail_cmd_context *ctx,
				 struct mailbox *box);
void doveadm_mail_failed_list(struct doveadm_mail_cmd_context *ctx,
			      struct mailbox_list *list);

extern struct doveadm_cmd_ver2 doveadm_cmd_mailbox_metadata_set_ver2;
exter_handle_full(struct doveadm_server *server,
				     struct doveadm_client *conn,
				     struct doveadm_mail_cmd_context *cmd_ctx,
				     const char *username,
				     const char *cmd_name,
				     const char *const *cmd_args,
				     bool print_username);
void doveadm_mail_server_flush(struct doveadm_mail_cmd_context *ctx);

int doveadm_cmd_pass_lookup(struct doveadm_mail_cmd_context *ctx,
			    const char *const *extra_fields, pool_t pool,
			    const char *const **fields_r,
			    const char **auth_socket_path_r);
int dpe type)
{
	return cpu_limit_get_usage_msecs(climit, type) / 1000;
}

#endif
#ifndef DOVEADM_MAIL_H
#define DOVEADM_MAIL_H

#include <stdio.h>
#include "doveadm.h"
#include "doveadm-util.h"
#include "module-context.h"
#include "mail-error.h"
#include "mail-storage.h"
#include "mail-storage-service.h"

struct auth_proxy_settings;
struct mailbox;
struct mailbox_list;
struct mail_storage;
struct mail_user;
struct doveadm_client;
struct doveadm_mail_cmd_context;

struct doveadm_mail_cmd_vfuncs {
	/* Usually not needed. The preinit() isalways seeks parent stream to here before calling read(). */
	uoff_t parent_expected_offset;

	struct memarea *memarea;
	struct istream_snapshot *prev_snapshot;
	/* increased every time the stream is changed (e.g. seek, read).
	   this way streams can check if their parent streams have been
	   accessed behind them. */
	unsigned int access_counter;
	/* Timestamp when read() last returned >0 */
	struct timeval last_read_timeval;

	string_t *line_str; /* for i_stream_next_line() if w_buffer == NULL */
	bool line_crlf:1;
	bool return_h_state *search_state;

	bool virtual_mailbox:1;
	bool fts_lookup_success:1;
	bool indexing_timed_out:1;
	bool virtual_seen_unindexed_gaps:1;
	bool mailbox_failed:1;
};

/* Figure out if we want to use full text search indexes and update
   backends in fctx accordingly. */
void fts_search_analyze(struct fts_search_context *fctx);
/* Perform the actual index lookup and update definite_uids and maybe_uids. */
void fts_search_lookup(struct fts_search_context *fctx);
/* Returns 1 if everything is already indexed, 0 if not, -1 on error.enough to check for stream->eof instead of
   calling this function. Note that if the stream isn't at EOF, this function
   has now read data into the stream buffer. */
bool i_stream_read_eof(struct istream *stream);
/* Returns the absolute offset of the stream. This is the stream's current
   v_offset + the parent's absolute offset when the stream was created. */
uoff_t i_stream_get_absolute_offset(struct istream *stream);

/* Gets the next line from stream and returns it, or NULL if more data is
   needed to make a full line. i_stream, bool blocking);

/* Returns number of bytes read if read was ok, 0 if stream is non-blocking and
   no more data is available, -1 if EOF or error, -2 if the input buffer is
   full. If <=0 is returned, pointers to existing data returned by the previous
   i_stream_get_data() will stay valid, although calling it again may return
   a different pointer. The pointers to old data are invalidated again when
   return value is >0. */
ssize_t i_stream_read(struct istream *stream);
/* Skip forward a number of bytes. Never fails, the*input);
struct istream *i_stream_create_limit(struct istream *input, uoff_t v_size);
struct istream *i_stream_create_range(struct istream *input,
				      uoff_t v_offset, uoff_t v_size);
struct istream *i_stream_create_error(int stream_errno);
struct istream *
i_stream_create_error_str(int stream_errno, const char *fmt, ...)
	ATTR_FORMAT(2, 3);

/* Set name (e.g. path) for input stream. */
void i_stream_set_name(struct istream *stream, const char *name);
/* Get input stream's name. If stream itself doesn't have a name,
   it looil_user_module_register {
	unsigned int id;
};

union mail_user_module_context {
	struct mail_user_vfuncs super;
	struct mail_user_module_register *reg;
};
extern struct mail_user_module_register mail_user_module_register;
extern struct auth_master_connection *mail_user_auth_master_conn;
extern const struct var_expand_provider *mail_user_var_expand_providers;

struct mail_user *
mail_user_alloc(struct mail_storage_service_user *service_user);
/* Returns -1 if settings were invalid. */
int mail_user_init(struct mail_user *user, const. This will assert fail if called out of sequence.
 */			    
void auth_scram_client_output(struct auth_scram_client *client,
			      const unsigned char **output_r,
			      size_t *output_len_r);

#endif
#ifndef MAIL_USER_H
#define MAIL_USER_H

#include "net.h"
#include "unichar.h"
#include "mail-storage-settings.h"
#include "process-stat.h"

#define SETTINGS_EVENT_MAIL_USER "mail_user"

struct module;
struct fs_parameters;
struct ssl_iostream_settings;
struct master_service_anvil_session;
struct mail_user;
struct dict_op_settihts_update_import(struct acl_rights_update *update,
			     const char *id, const char *const *rights,
			     const char **error_r);

/* Exports ACL rights to string */
const char *acl_rights_export(const struct acl_rights *rights);

/* <settings checks> */
/* Parses line containing identifier and rights */
int acl_rights_parse_line(const char *line, pool_t pool,
			  struct acl_rights *rights_r, const char **error_r);
/* </settings checks> */

/* Duplicates a right */
void acl_rights_dup(const struct acl_rights *src,
		    pool_tredirect_callback);
/* Free the proxy. This should be called if authentication fails. */
void login_proxy_free(struct login_proxy **proxy);

/* Append to str host:ip[,host2:ip[,...]] path of redirects followed so far. */
void login_proxy_get_redirect_path(struct login_proxy *proxy, string_t *str);
/* Finish redirection to ip:port from a redirect callback. */
void login_proxy_redirect_finish(struct login_proxy *proxy,
				 const struct ip_addr *ip, in_port_t port);

/* Login proxying session has failed. Returns TRUE if the reconnecthutdown(void);

void auth_worker_connections_destroy_all(void);

/* Stop master service after this many requests. 0 is unlimited. */
void auth_worker_set_max_restart_request_count(unsigned int count);

#endif
/* Copyright (c) 2015-2018 Dovecot authors, see the included COPYING file */

#ifndef PUSH_NOTIFICATION_EVENT_MESSAGENEW_H
#define PUSH_NOTIFICATION_EVENT_MESSAGENEW_H

#include "push-notification-event-message-common.h"

struct push_notification_event_messagenew_config {
	enum push_notification_event_message_flags flags;
};

 NULL if it doesn't exist. If the key
   isn't found from the event itself, find it from parent events, including
   from the global event. */
const struct event_field *
event_find_field_recursive(const struct event *event, const char *key);
/* Same as event_find_field(), but return the value converted to a string.
   If the field isn't stored as a string, the result is allocated from
   data stack. */
const char *
event_find_field_recursive_str(const struct event *event, const char *key);
/* Returns all key=value fields that the eor uppercase characters. */
const char *event_reason_code_prefix(const char *module,
				     const char *name_prefix, const char *name);

/* Set the appended log prefix string for this event. All the parent events'
   log prefixes will be concatenated together when logging. The log type
   text (e.g. "Info: ") will be inserted before appended log prefixes (but
   after replaced log prefix).

   Clears log_prefix callback.
 */
struct event *
event_set_append_log_prefix(struct event *event, const char *prefix);
/* Replace the full l *event);
/* Unreference the event. If the reference count drops to 0, the event is
   freed. The current global event's refcount must not drop to 0. */
void event_unref(struct event **event);

/* Set the event to be the global event and push it at the top of the global
   event stack. Returns the event parameter. The event must be explicitly
   popped before it's freed.

   The global event acts as the root event for all the events while they are
   being emitted. The global events don't permanently affect the event
   hierarchy. ct event_passthrough *
		(*strlist_replace)(const char *key, const char *const *value,
				   unsigned int count);

	struct event_passthrough *
		(*clear_field)(const char *key);

	struct event *(*event)(void);
};

typedef const char *
event_log_prefix_callback_t(void *context);
typedef const char *
event_log_message_callback_t(void *context, enum log_type log_type,
			     const char *message);

/* Returns TRUE if the event has all the categories that the "other" event has
   (and maybe more). */
bool event_has_all_categories(struOP3 UIDL overriding the default format */
	MAILDIR_UIDLIST_REC_EXT_POP3_UIDL	= 'P',
	/* POP3 message ordering number. Lower numbered messages are listed
	   first. Messages without ordering number are listed after them.
	   The idea is to be able to preserve POP3 UIDL list and IMAP UIDs
	   perfectly when migrating from other servers. */
	MAILDIR_UIDLIST_REC_EXT_POP3_ORDER	= 'O',
	/* Message GUID (default is the base filename) */
	MAILDIR_UIDLIST_REC_EXT_GUID		= 'G'
};

int maildir_uidlist_lock(struct maildir_uidlist *uidlist);
int*path, const char **dest_r, const char **error_r);

/* Update binpath to be absolute:
 * a) begins with '/' -> no change
 * b) contains '/' -> assume relative to working directory
 * c) set to first executable that's found from $PATH
 *
 * error_r is set on failure, and cannot be NULL.
 */
bool t_binary_abspath(const char **binpath, const char **error_r);

#endif
#ifndef EVENT_FILTER_PRIVATE_H
#define EVENT_FILTER_PRIVATE_H

#include "event-filter.h"

enum event_filter_node_op {
	/* leaf nodes */
	EVENT_FILTER_OP_CMP_EQ = 1,
	EVENT char *key_prefix);

/* Return mailbox_settings->name as vname (with namespace prefix). */
const char *
mailbox_settings_get_vname(pool_t pool, const struct mail_namespace *ns,
			   const struct mailbox_settings *set);

bool mail_user_settings_update_special_use(struct mail_user *user,
					   const struct mail_storage_settings *set,
					   const char **error_r);

#endif
#ifndef LLIST_H
#define LLIST_H

/* Doubly linked list */
#define DLLIST_PREPEND_FULL(list, item, prev, next) STMT_START { \
	(item)->prev = NULL; \
	(item)->nexlags;
	bool parsed_mail_attachment_detection_no_flags_on_fetch;
	/* Filename part of mailbox_list_index_prefix */
	const char *parsed_list_index_fname;
	/* Directory part of mailbox_list_index_prefix. NULL defaults to index
	   directory. The path may be relative to the index directory. */
	const char *parsed_list_index_dir;
	/* If set, store mailboxes under root_dir/mailbox_dir_name/.
	   This setting contains either "" or "dir/" with trailing "/". */
	const char *parsed_mailbox_root_directory_prefix;

	const char *unexpanded_mailerror_r);

const struct quota_backend *quota_backend_find(const char *name);
void quota_backend_register(const struct quota_backend *backend);
void quota_backend_unregister(const struct quota_backend *backend);

#define QUOTA_UNKNOWN_RESOURCE_ERROR_STRING "Unknown quota resource"

#endif
#ifndef MAIL_STORAGE_SETTINGS_H
#define MAIL_STORAGE_SETTINGS_H

#include "file-lock.h"
#include "fsync-mode.h"
#include "mailbox-list.h"

/* mail_index_path setting points to using in-memory indexes */
#define MAIL_INDEX_PATH_MEMORY "MEMORY"

struh_client_connection *conn;

	auth_master_request_callback_t *master_callback;
	auth_request_handler_reply_callback_t *reply_callback;
	auth_request_handler_reply_continue_callback_t *reply_continue_callback;
	verify_plain_continue_callback_t *verify_plain_continue_callback;

	bool destroyed:1;
	bool token_auth:1;
};


#endif
#ifndef PUNYCODE_H
#define PUNYCODE_H

/* Parse input as a punycode-encoded string and append it to
   output. Returns 0 on success and -1 on failure. */
int punycode_decode(const char *input, size_t len, strinlt, any CR, LF characters are ignored, as well as any whitespace.
   This can be overridden using the BASE64_DECODE_FLAG_NO_WHITESPACE flag.

   If src_pos is non-NULL, it's updated to first non-translated character in
   src.
 */
int base64_decode_more(struct base64_decoder *dec,
		       const void *src, size_t src_size, size_t *src_pos_r,
		       buffer_t *dest) ATTR_NULL(4);
/* Finishes Base64 decoding. This function checks whether the encoded data ends
   in the proper padding. Returns 0 if all ok, and -1 if data is invalid.
 finishing:1;
	bool finished:1;
};

/* Returns TRUE when base64_encode_finish() was called on this encoder. */
static inline bool
base64_encode_is_finished(struct base64_encoder *enc)
{
	return enc->finished;
}

/* Initialize the Base64 encoder. The b64 parameter is the definition of the
   particular Base64 encoding scheme that is used.
 */
static inline void
base64_encode_init(struct base64_encoder *enc,
		   const struct base64_scheme *b64,
		   enum base64_encode_flags flags,
		   size_t max_line_len)
{
	i_zero(enc);
	enc->b64 iostream *ssl_io);

	const char *(*get_application_protocol)(struct ssl_iostream *ssl_io);
	void (*set_application_protocols)(struct ssl_iostream_context *ctx,
					  const char *const *names);

	int (*get_channel_binding)(struct ssl_iostream *ssl_io,
				   const char *type, const buffer_t **data_r,
				   const char **error_r);
};

void iostream_ssl_module_init(const struct iostream_ssl_vfuncs *vfuncs);

/* Returns TRUE if both settings are equal. Note that NULL and "" aren't
   treated equal. */
bool ssl_iostream_settings_equals_rebuild_count;
	char *corrupted_reason;

	bool rebuilding_storage:1;
	bool preallocate_space:1;
};

struct mdbox_mail_index_record {
	uint32_t map_uid;
	/* UNIX timestamp of when the message was saved/copied to this
	   mailbox */
	uint32_t save_date;
};

struct mdbox_mailbox {
	struct mailbox box;
	struct mdbox_storage *storage;

	uint32_t map_uid_validity;
	uint32_t ext_id, hdr_ext_id, guid_ext_id;

	bool mdbox_deleted_synced:1;
	bool creating:1;
};

#define MDBOX_DBOX_STORAGE(s)	container_of(s, struct mdbox_storage, storage)
#dent_content_type(struct message_decoder_context *ctx);

/* Call whenever message changes */
void message_decoder_decode_reset(struct message_decoder_context *ctx);

/* Decode Content-Transfer-Encoding header. */
enum message_cte message_decoder_parse_cte(const struct message_header_line *hdr);

#endif
#ifndef SMTP_SYNTAX_H
#define SMTP_SYNTAX_H

struct smtp_parser;

/*
 * String
 */

int smtp_string_parse(const char *string, const char **value_r,
		      const char **error_r);
void smtp_string_write(string_t *out, const char *value/* guaranteed to be >0 on success */
	const struct ip_addr *ips;
	/* for PTR lookup: */
	const char *name;
};

typedef void dns_lookup_callback_t(const struct dns_lookup_result *result,
				   void *context);

/* Do asynchronous DNS lookup via dns-client UNIX socket. Returns 0 if lookup
   started, -1 if there was an error communicating with the UNIX socket.
   When failing with -1, the callback is called before returning from the
   function. */
int dns_lookup(const char *host, const struct dns_lookup_settings *set,
	       dns_loo_notify_auth_ready;
	struct timeout *to_disconnect;

	unsigned char *master_data_prefix;
	unsigned int master_data_prefix_len;

	struct login_proxy *login_proxy;
	char *proxy_user, *proxy_master_user, *proxy_password;
	const struct dsasl_client_mech *proxy_mech;
	struct dsasl_client *proxy_sasl_client;
	unsigned int proxy_ttl;

	char *auth_mech_name;
	enum sasl_server_auth_flags auth_flags;
	/* Auth request set while the client is authenticating.
	   During this time authenticating=TRUE also. */
	struct auth_client_request *auth_rconst char *data);
	bool (*auth_parse_response)(struct client *client);
	void (*auth_result)(struct client *client,
			    enum client_auth_result result,
			    const struct client_auth_reply *reply,
			    const char *text);
	void (*proxy_reset)(struct client *client);
	int (*proxy_parse_line)(struct client *client, const char *line);
	int (*proxy_side_channel_input)(struct client *client,
					const char *const *args,
					const char **error_r);
	void (*proxy_failed)(struct client *client,
			     enum login_proxy_failure_type tver_connection *conn);
void smtp_server_connection_set_state(struct smtp_server_connection *conn,
				      enum smtp_server_state state,
				      const char *args) ATTR_NULL(3);

int smtp_server_connection_ssl_init(struct smtp_server_connection *conn);

void smtp_server_connection_clear(struct smtp_server_connection *conn);

/*
 * Recipient
 */

struct smtp_server_recipient *
smtp_server_recipient_create(struct smtp_server_cmd_ctx *cmd,
			     const struct smtp_address *rcpt_to,
			     const struct smtp_params_rcpt *params);
vo_command_reg) commands_reg;

	struct connection_list *conn_list;

	bool commands_unsorted:1;
};

bool smtp_server_connection_pending_command_data(
	struct smtp_server_connection *conn);

/*
 * Reply
 */

void smtp_server_reply_free(struct smtp_server_command *cmd);

int smtp_server_reply_send(struct smtp_server_reply *resp);

const char *
smtp_server_reply_get_one_line(const struct smtp_server_reply *reply);
const char *
smtp_server_reply_get_message(const struct smtp_server_reply *reply);

void smtp_server_reply_add_to_event(constrver_request *request,
				const char *errormsg);

struct login_server_settings {
	const char *auth_socket_path;
	const char *postlogin_socket_path;
	unsigned int postlogin_timeout_secs;

	login_server_callback_t *callback;
	login_server_failure_callback_t *failure_callback;

	bool update_proctitle:1;
	bool request_auth_token:1;
};

struct login_server *
login_server_init(struct master_service *service,
		  const struct login_server_settings *set);
void login_server_deinit(struct login_server **server);

void login_server_add(struc when there are no more users */
typedef void userdb_iter_callback_t(const char *user, void *context);

struct userdb_module {
	/* The default caching key for this module, or NULL if caching isn't
	   wanted. This is updated by settings in auth_userdb. */
	const char *default_cache_key;

	/* If blocking is set to TRUE, use child processes to access
	   this userdb. */
	bool blocking;
        /* id is used by blocking userdb to identify the userdb */
	unsigned int id;

	/* number of time init() has been called */
	int init_refcount;essage_part *part,
				 bool include_hdr,
				 struct mail_binary_properties *bprops_r,
				 struct istream **stream_r);
int index_mail_get_special(struct mail *_mail, enum mail_fetch_field field,
			   const char **value_r);
int index_mail_get_backend_mail(struct mail *mail, struct mail **real_mail_r);

void index_mail_update_flags(struct mail *mail, enum modify_type modify_type,
			     enum mail_flags flags);
void index_mail_update_keywords(struct mail *mail, enum modify_type modify_type,
				struct mail_keywords *keywords);
voicache_field_idx;
	enum mail_fetch_field wanted_fields;
	struct mailbox_header_lookup_ctx *wanted_headers;

	buffer_t *search_results;

	struct istream *stream, *filter_stream;
	struct tee_istream *tee_stream;
	struct message_size hdr_size, body_size;
	struct istream *parser_input;
	struct message_parser_ctx *parser_ctx;
	int parsing_count;
	ARRAY_TYPE(keywords) keywords;
	ARRAY_TYPE(keyword_indexes) keyword_indexes;

	bool initialized:1;
	bool save_sent_date:1;
	bool sent_date_parsed:1;
	bool save_envelope:1;
	bool save_bodystructurocesses are intentionally limited to their process_limit,
	   and they can regularly reach it. There shouldn't be unnecessary
	   warnings about temporarily reaching the limit. */
	SERVICE_TYPE_WORKER,
};

struct config_service {
	const struct service_settings *set;
	const struct setting_keyvalue *defaults;
};
ARRAY_DEFINE_TYPE(config_service, struct config_service);
/* </settings checks> */

struct file_listener_settings {
	pool_t pool;
	const char *path;
	const char *type;
	unsigned int mode;
	const char *user;
	const char *grouurns 1 on
   unlink() success, 0 if errno=ENOENT, -1 on other errors. */
int i_unlink_if_exists(const char *path, const char *source_fname,
		       unsigned int source_linenum);
#define i_unlink_if_exists(path) i_unlink_if_exists(path, __FILE__, __LINE__)
/* Reset getopt() so it can be used for the next args. */
void i_getopt_reset(void);

/* Call the given callback at the beginning of lib_deinit(). The main
   difference to atexit() is that liblib's memory allocation and logging
   functions are still available. Also if lib_atexinst char *mailbox_list_join_refpattern(struct mailbox_list *list,
					 const char *ref, const char *pattern);

/* Initialize new mailbox list request. Pattern may contain '%' and '*'
   wildcards as defined by RFC-3501. */
struct mailbox_list_iterate_context *
mailbox_list_iter_init(struct mailbox_list *list, const char *pattern,
		       enum mailbox_list_iter_flags flags);
/* Like mailbox_list_iter_init(), but support multiple patterns. Patterns is
   a NULL-terminated list of strings. It must contain at least one pattern. */
st_iter *iter);
/* Returns 0 if ok, -1 if I/O error. */
int mailbox_log_iter_deinit(struct mailbox_log_iter **iter);

#endif
#ifndef ISTREAM_NONULS_H
#define ISTREAM_NONULS_H

/* Translate all NUL characters to the specified replace_chr. */
struct istream *i_stream_create_nonuls(struct istream *input, char replace_chr);

#endif
#ifndef MAILBOX_LIST_ITER_H
#define MAILBOX_LIST_ITER_H

#include "mail-namespace.h"
#include "mailbox-list.h"

enum mailbox_list_iter_flags {
	/* Ignore index file and ACLs (used by ACL plugin internally) */
g *args);
/* Build a parser parsing the given command line args. */
struct mail_search_parser *
mail_search_parser_init_cmdline(const char *const args[]);

void mail_search_parser_deinit(struct mail_search_parser **parser);

/* Key is set to the next search key, or MAIL_SEARCH_PARSER_KEY_LIST for
   beginning of a list. Returns 1 if ok, 0 if no more keys in this
   list/query, -1 if parsing error. */
int mail_search_parse_key(struct mail_search_parser *parser,
			  const char **key_r);
/* Get the next string. Returns 0 if ok, -1 ifails, e.g. simple will cut "a.b" and tr29 will
   not. The default is "simple" */
extern const struct lang_tokenizer *lang_tokenizer_generic;

enum lang_tokenizer_flags {
	/* Remove addresses from parent data stream, so they are not
	   processed further. */
	LANG_TOKENIZER_FLAG_SEARCH = 0x01,
};

/*
 Tokenizing workflow, find --> create --> filter --> destroy.
 Do init before first use and deinit after all done.
 */

/* Register all built-in tokenizers. */
void lang_tokenizers_init(void);
void lang_tokenizers_deinit(void);

const t;
}
static inline unsigned int ATTR_CONST ATTR_NO_SANITIZE_INTEGER
	ATTR_NO_SANITIZE_IMPLICIT_CONVERSION
bits_fraclog_bucket_end(unsigned int bucket, unsigned int fracbits)
{
	unsigned int bandnum = bucket >> fracbits;
	if (bandnum <= 1)
		return bucket;
	if (fracbits == 0)
		return BIT(bucket - 1) * 2 - 1;
	unsigned int fracoffs = bucket & (BIT(fracbits)-1);
	unsigned int nextfracoffs1 = 1 + BIT(fracbits) + fracoffs;
	unsigned int nextbandstart = nextfracoffs1 << (bandnum - 1);
	return nextbandstart - 1;
}
/* UNSAFE: multiple useins invalid input, UNICODE_REPLACEMENT_CHAR is placed in such
   positions and the invalid input is skipped over. Return value is also
   CHARSET_RET_INCOMPLETE_INPUT in that case. */
enum charset_result
charset_to_utf8(struct charset_translation *t,
		const unsigned char *src, size_t *src_size, buffer_t *dest);

/* Translate a single string to UTF8. */
int charset_to_utf8_str(const char *charset, normalizer_func_t *normalizer,
			const char *input, string_t *output,
			enum charset_result *result_r) ATTR_NULL(2);

/* INTERNAL: */
ef> = the function to remove a reference from the C structure,
 *       called from the automatically generated __gc metamethod
 *   <extra_fxns_arg> = a C array of luaL_Reg structs passed to luaL_setfuncs
 *       to add Lua methods to the type
 *
 * For example, to expose struct timespec with a tostring method, one would
 * use the following in a .c file:
 *
 *   // struct timespec isn't refcounted
 *   static inline void timespec_putref(struct timespec *ts)
 *   {
 *   }
 *
 *   static int timespec_tostring(lua_State *L);
 *
 * p_reply *reply,
			     struct event_passthrough *e);

#endif
#ifndef RAW_STORAGE_H
#define RAW_STORAGE_H

#include "index-storage.h"

struct setting_parser_context;
struct settings_instance;
struct mail_storage_service_ctx;

#define RAW_STORAGE_NAME "raw"

struct raw_storage {
	struct mail_storage storage;
};

struct raw_mailbox {
	struct mailbox box;
	struct raw_storage *storage;

	time_t mtime, ctime;
	uoff_t size;
	const char *envelope_sender;

	bool synced:1;
	bool have_filename:1;
};

#define RAW_STORAGE(s)		container_of(s, s
/* Returns all enabled features as strings. */
const char *const *client_enabled_features(struct client *client);

/* Send client processing to imap-idle process. If successful, returns TRUE
   and destroys the client. If hibernation failed, the exact reason is
   returned (mainly for unit tests). */
bool imap_client_hibernate(struct client **client, const char **reason_r);

struct imap_search_update *
client_search_update_lookup(struct client *client, const char *tag,
			    unsigned int *idx_r);
void client_search_updates_free(sd_count;
	unsigned int autoexpunged_count, append_count;

	/* SEARCHRES extension: Last saved SEARCH result */
	ARRAY_TYPE(seq_range) search_saved_uidset;
	/* SEARCH=CONTEXT extension: Searches that get updated */
	ARRAY(struct imap_search_update) search_updates;
	/* NOTIFY extension */
	struct imap_notify_context *notify_ctx;
	uint32_t notify_uidnext;
	/* COMPRESS extension */
	const struct compression_handler *compress_handler;

	/* client input/output is locked by this command */
	struct client_command_context *input_lock;
	struD_STATE_WAIT_SYNC,
	/* Command is finished */
	CLIENT_COMMAND_STATE_DONE
};

struct client_command_stats {
	/* time when command handling was started - typically this is after
	   reading all the parameters. */
	struct timeval start_time;
	/* time when command handling was last finished. this is before
	   mailbox syncing is done. */
	struct timeval last_run_timeval;
	/* io_loop_get_wait_usecs()'s value when the command was started */
	uint64_t start_ioloop_wait_usecs;
	/* how many usecs this command itself has spent running */
	uiontext must be currently
   active or it assert-crashes. This should be called only after a context
   was explicitly activated with io_loop_context_activate(). */
void io_loop_context_deactivate(struct ioloop_context *ctx);
/* If there's an active ioloop context, deactivate it. Then activate the given
   context. Usually used after creating a new context. */
void io_loop_context_switch(struct ioloop_context *ctx);

/* Returns fd, which contains all of the ioloop's current notifications.
   When it becomes readable, there is a new *context)
	ATTR_NULL(3);
#define io_add_istream_to(ioloop, input, callback, context) \
	io_add_istream_to(ioloop, input, __FILE__, __LINE__ - \
		CALLBACK_TYPECHECK(callback, void (*)(typeof(context))), \
		(io_callback_t *)callback, context)

/* Remove I/O handler, and set io pointer to NULL. */
void io_remove(struct io **io);
/* Like io_remove(), but assume that the file descriptor is already closed.
   With some backends this simply frees the memory. */
void io_remove_closed(struct io **io);

/* Make sure the I/O callback is calack)(void *), void *context);
void io_stream_remove_destroy_callback(struct iostream_private *stream,
				       void (*callback)(void *));
/* Set a specific error for the stream. This shouldn't be used for regular
   syscall errors where stream's errno is enough, since it's used by default.
   The stream errno must always be set even if the error string is also set.
   Setting this error replaces the previously set error. */
void io_stream_set_error(struct iostream_private *stream,
			 const char *fmt, ...) ATTR_FORMAT(2, 3);
voidPONGE_WORDS * 8];
	};
	unsigned byteIndex; /* 0..7--the next byte after the set one
			     * (starts from 0; 0--none are buffered) */
	unsigned wordIndex; /* 0..24--the next word to integrate input
			     * (starts from 0) */
	unsigned capacityWords; /* the double size of the hash output in
				 * words (e.g. 16 for Keccak 512) */
};

void sha3_256_init(void *context);
void sha3_256_result(void *context,
		   unsigned char digest[STATIC_ARRAY SHA256_RESULTLEN]);
void sha3_256_get_digest(const void *data, size_t size,
		       unsAPS __attribute__((no_sanitize("integer")))
#else
#  define ATTR_UNSIGNED_WRAPS
#endif

/* Provide macros for error handling. */
#ifdef DISABLE_ASSERTS
#  define i_assert(expr)
#else
#  define i_assert(expr)			STMT_START{			\
     if (unlikely(!(expr)))						\
       i_panic("file %s: line %d (%s): assertion failed: (%s)",		\
		__FILE__,						\
		__LINE__,						\
		__func__,					\
		#expr);			}STMT_END
#endif

/* Convenience macro to test the versions of dovecot. */
#define DOVECOT_PREREQ(maj, min, micro) \
	((DOVECOT_VERSION_MAJOR (void *)(value_r)))
#else
/* C++ requires (void **) casting, but that's not possible with strict
   aliasing, so .. we'll just disable the type checks */
#  define hash_table_iterate(ctx, table, key_r, value_r) \
	hash_table_iterate(ctx, key_r, value_r)
#endif

void hash_table_iterate_deinit(struct hash_iterate_context **ctx);

/* Hash table isn't resized, and removed nodes aren't removed from
   the list while hash table is freezed. Supports nesting. */
void hash_table_freeze(struct hash_table *table);
void hash_table_thaw(struct void *key) ATTR_PURE;
#define hash_table_lookup(table, key) \
	TYPE_CHECKS(void *, \
	COMPILE_ERROR_IF_TYPES2_NOT_COMPATIBLE((table)._key, (table)._const_key, key), \
	HASH_VALUE_CAST(table)hash_table_lookup((table)._table, (key)))

bool hash_table_lookup_full(const struct hash_table *table,
			    const void *lookup_key,
			    void **orig_key_r, void **value_r);
#ifndef __cplusplus
#  define hash_table_lookup_full(table, lookup_key, orig_key_r, value_r) \
	TYPE_CHECKS(bool, \
	/* NOLINTBEGIN(bugprone-sizeof-expression) */ \
	COMlient);

void smtp_client_switch_ioloop(struct smtp_client *client);

#endif
#ifndef IOSTREAM_TEMP_H
#define IOSTREAM_TEMP_H

enum iostream_temp_flags {
	/* if o_stream_send_istream() is called with a readable fd, don't
	   actually copy the input stream, just have iostream_temp_finish()
	   return a new iostream pointing to the fd dup()ed */
	IOSTREAM_TEMP_FLAG_TRY_FD_DUP	= 0x01
};

/* Start writing to given output stream. The data is initially written to
   memory, and later to a temporary file that is immediately unlinked. */
stLAG_VERIFY_OWNER	= 0x01,
	/* Don't close the file descriptor. */
	DOTLOCK_REPLACE_FLAG_DONT_CLOSE_FD	= 0x02
};

/* Create dotlock. Returns 1 if successful, 0 if timeout or -1 if error.
   When returning 0, errno is also set to EAGAIN. */
int file_dotlock_create(const struct dotlock_settings *set, const char *path,
			enum dotlock_create_flags flags,
			struct dotlock **dotlock_r);

/* Delete the dotlock file. Returns 1 if successful, 0 if the file had already
   been deleted or reused by someone else, -1 if I/O error. */
int ATTR_Nuct mail_save_context *ctx, struct mail *mail);

int imapc_transaction_save_commit(struct mailbox_transaction_context *t);
int imapc_transaction_save_commit_pre(struct mail_save_context *ctx);
void imapc_transaction_save_commit_post(struct mail_save_context *ctx,
					struct mail_index_transaction_commit_result *result);
void imapc_transaction_save_rollback(struct mail_save_context *ctx);

void imapc_mailbox_run(struct imapc_mailbox *mbox);
void imapc_mailbox_run_nofetch(struct imapc_mailbox *mbox);
void imapc_mail_cache_free(struc imapc_mailbox_list *_list;

	struct imapc_client *client;
	const struct imapc_settings *set;

	ARRAY(struct imapc_storage_event_callback) untagged_callbacks;

	/* IMAPC_COMMAND_STATE_OK if no auth failure (yet), otherwise result to
	   the LOGIN/AUTHENTICATE command. */
	enum imapc_command_state auth_failed_state;
	char *auth_failed_reason;

	/* Authentication reply was received (success or failure) */
	bool auth_returned:1;
	bool destroying:1;
};

struct imapc_storage_attribute_context {
	pool_t pool;
	const char *const *keys;
	cap_fetch_failure;
	bool imap_metadata;
	bool imap_literal_minus;
	bool mail_utf8_extensions;
	unsigned int imap_hibernate_timeout;
	ARRAY_TYPE(const_string) imap_id_send;

	/* imap urlauth: */
	const char *imap_urlauth_host;
	in_port_t imap_urlauth_port;

	enum imap_client_workarounds parsed_workarounds;
	enum imap_client_fetch_failure parsed_fetch_failure;
};

extern const struct setting_parser_info imap_setting_parser_info;

#endif
#ifndef IMAP_MASTER_CLIENT_H
#define IMAP_MASTER_CLIENT_H

void imap_master_client_create(int fd);
_header_fields_get_next_offset(struct mail_cache *cache,
					     uint32_t *offset_r);
void mail_cache_expunge_count(struct mail_cache *cache, unsigned int count);

uint32_t mail_cache_lookup_cur_offset(struct mail_index_view *view,
				      uint32_t seq, uint32_t *reset_id_r);
int mail_cache_get_record(struct mail_cache *cache, uint32_t offset,
			  const struct mail_cache_record **rec_r);
uint32_t mail_cache_get_first_new_seq(struct mail_index_view *view);

/* Returns TRUE if offset..size area has been tracked before.
   Returned within this session. This is used to track whether messages
	   are accessed in non-ascending order, which indicates an IMAP client
	   that doesn't have a local cache. That will result in the caching
	   decision to change from TEMP to YES. */
	uint32_t uid_highwater;

	/* Unused fields aren't written to cache file */
	bool used:1;
	/* field.decision is pending a write to cache file header. If the
	   cache header is read from disk, don't overwrite it. */
	bool decision_dirty:1;
};

struct mail_cache {
	struct mail_index *indexfine MAIL_CACHE_IS_UNUSABLE(cache) \
	((cache)->hdr == NULL)

struct mail_cache_header {
	/* Major version is increased only when you can't have backwards
	   compatibility. If the field doesn't match MAIL_CACHE_MAJOR_VERSION,
	   don't even try to read it. */
	uint8_t major_version;
	/* If this isn't the same as sizeof(uoff_t), the cache file can't be
	   safely used with the current implementation. */
	uint8_t compat_sizeof_uoff_t;
	/* Minor version is increased when the file format changes in a
	   backwards compatible way. */
	ruct http_url *target);

	/* Called once the connection is destroyed. */
	void (*connection_destroy)(void *context, const char *reason);
};

/* Create a HTTP server connection object for the provided fd pair. The
   callbacks structure is described above. */
struct http_server_connection *
http_server_connection_create(struct http_server *server,
			      int fd_in, int fd_out, bool ssl,
			      const struct http_server_callbacks *callbacks,
			      void *context);
/* Reference the connection */
void http_server_connection_ref(st,
				   const char *format, ...) ATTR_FORMAT(4, 5);
/* Send an authentication failure response for the request with given reason.
   The provided challenge is set in the WWW-Authenticate header of the
   response. */
void http_server_request_fail_auth(struct http_server_request *req,
				   const char *reason,
				   const struct http_auth_challenge *chlng)
				   ATTR_NULL(2);
/* Send a authentication failure response for the request with given reason.
   The provided realm is used to construct an Basic challenge in the
   WWW-Aulback_t)(void *context,
				 const struct http_server_tunnel *tunnel);

/* Start creating the response for the request. This function can be called
   only once for each request. */
struct http_server_response *
http_server_response_create(struct http_server_request *req,
			    unsigned int status, const char *reason);

/* Reference a server response */
void http_server_response_ref(struct http_server_response *resp);
/* Unreference a server response. Returns TRUE if there are still more
   references, FALSE if not. */
bool http_sver_resource;
struct http_server_request;
struct http_server_request_limits;
struct http_server_response;

struct ssl_iostream_settings;

#define HTTP_SERVER_DEFAULT_MAX_PAYLOAD_SIZE (1024 * 1024 * 1024 * 10ULL)

/*
 * Server settings
 */

struct http_server_settings {
	pool_t pool;
	const char *base_dir;
	const char *rawlog_dir;

	/* The maximum time in milliseconds a client is allowed to be idle
	   before it is disconnected. */
	unsigned int max_client_idle_time_msecs;

	/* Maximum number of pipelined requests per connection (deparser *parser, bool request);

#endif
#ifndef MASTER_SERVICE_PRIVATE_H
#define MASTER_SERVICE_PRIVATE_H

#include "master-interface.h"
#include "master-service.h"

#include <signal.h>

struct master_service_haproxy_conn;

struct master_service_listener {
	struct master_service *service;
	char *name;
	char *type;

	/* settings */
	bool ssl;
	bool haproxy;

	/* state */
	bool closed;
	int fd;
	struct io *io;
};

struct master_service {
	struct ioloop *ioloop;
	struct event *event;

	char *name;
	char *configured_name;
	char *getopt_        (fatal) */
};

enum http_message_parse_flags {
	/* Strictly adhere to the HTTP protocol specification */
	HTTP_MESSAGE_PARSE_FLAG_STRICT = BIT(0)
};

struct http_message {
	pool_t pool;

	unsigned int version_major;
	unsigned int version_minor;

	struct http_header *header;

	time_t date;
	uoff_t content_length;
	const char *location;
	ARRAY_TYPE(http_transfer_coding) transfer_encoding;
	ARRAY_TYPE(const_string) connection_options;

	bool connection_close:1;
	bool have_content_length:1;
};

struct http_message_parser {
	str
			  unsigned long long *num_r)
{
	return json_node_get_ullong(json_tree_node_get(jtnode), num_r);
}

static inline int
json_tree_node_get_uint32(const struct json_tree_node *jtnode, uint32_t *num_r)
{
	return json_node_get_uint32(json_tree_node_get(jtnode), num_r);
}

static inline int
json_tree_node_get_uint64(const struct json_tree_node *jtnode, uint64_t *num_r)
{
	return json_node_get_uint64(json_tree_node_get(jtnode), num_r);
}

/*
 * Tree object
 */

struct json_tree_node *json_tree_get_root(struct json_tree *jtree);
const s_type type,
			 const struct json_value *value);

/* string */
struct json_tree_node * ATTR_NOWARN_UNUSED_RESULT
json_tree_node_add_string(struct json_tree_node *parent, const char *name,
			  const char *str);
struct json_tree_node * ATTR_NOWARN_UNUSED_RESULT
json_tree_node_add_data(struct json_tree_node *parent, const char *name,
			const unsigned char *data, size_t size);
struct json_tree_node * ATTR_NOWARN_UNUSED_RESULT
json_tree_node_add_string_stream(struct json_tree_node *parent,
				 const char *name, struct istream *input)t()s on matching events. */
void event_set_global_core_log_filter(struct event_filter *filter);
/* Return the current global core filter. */
struct event_filter *event_get_global_core_log_filter(void);
/* Unset the global core filter, if one exists. */
void event_unset_global_core_log_filter(void);

#endif
#ifndef DBOX_STORAGE_H
#define DBOX_STORAGE_H

#include "mail-storage-private.h"

struct dbox_file;
struct dbox_mail;
struct dbox_storage;
struct dbox_save_context;

#define DBOX_UIDVALIDITY_FILE_NAME "dovecot-uidvalidity"
#defin	      const void *data, size_t data_len);

static inline
buffer_t *t_hash_buffer(const struct hash_method *meth,
			const buffer_t *data)
{
	return t_hash_data(meth, data->data, data->used);
}

static inline
buffer_t *t_hash_str(const struct hash_method *meth,
		     const char *data)
{
	return t_hash_data(meth, data, strlen(data));
}

#endif
#ifndef EVENT_LOG_H
#define EVENT_LOG_H

struct event_filter;

#include "lib-event.h"

struct event_log_params {
	enum log_type log_type;
	const char *source_filename;
	unsigned int source_lio match this or the fatal test fails. */
void test_expect_fatal_string(const char *substr);
/* Call the specified callback when a fatal is being triggered. This is mainly
   intended to allow freeing memory so valgrind won't complain about memory
   leaks. */
void test_fatal_set_callback(test_fatal_callback_t *callback, void *context);
#define test_fatal_set_callback(callback, context) \
	test_fatal_set_callback(1 ? (test_fatal_callback_t *)callback : \
		CALLBACK_TYPECHECK(callback, void (*)(typeof(context))), \
		context)

#definrnal buffer reaches max_internal_buffer_size, start returning 0 for
   o_stream_send*(). */
void test_ostream_set_max_output_size(struct ostream *output, size_t max_size);

void test_begin(const char *name);
#define test_failed(reason) test_assert_failed(reason, __FILE__, __LINE__)
#define test_assert(code) STMT_START { \
	if (!(code)) test_assert_failed(#code, __FILE__, __LINE__); \
	} STMT_END
/* Additional parameter may be int or unsigned int, to indicate which of
 * a barrage of tests have failed (such as in a loop).
 */
#definerver_cmd_ctx *cmd);
};

struct client {
	struct client *prev, *next;
	pool_t pool;

	struct submission_client_vfuncs v;
	struct event *event;

	const struct setting_parser_info *user_set_info;
	const struct submission_settings *set;

	struct smtp_server_connection *conn;
	guid_128_t anvil_conn_guid;
	struct client_state state;
	ARRAY(struct submission_backend *) pending_backends;
	ARRAY(struct submission_recipient *) rcpt_to;
	ARRAY(struct submission_backend *) rcpt_backends;

	struct mail_user *user;

	/* IMAP URLAUTH context (RFt smtp_reply;

struct submission_recipient;
struct submission_backend;
struct submission_backend_relay;
struct client;

struct client_state {
	pool_t pool;
	enum smtp_server_state state;
	char *args;

	struct submission_backend *backend;
	struct istream *data_input;
	uoff_t data_size;
};

struct client_extra_capability {
	const char *capability;
	const char *params;
};

struct submission_client_vfuncs {
	void (*destroy)(struct client *client);

	void (*trans_start)(struct client *client,
			    struct smtp_server_transaction *transtent_existence(struct mailbox *box,
					     const char *path);

bool index_storage_is_readonly(struct mailbox *box);
bool index_storage_is_inconsistent(struct mailbox *box);

enum mail_index_sync_flags index_storage_get_sync_flags(struct mailbox *box);
bool index_mailbox_want_full_sync(struct mailbox *box,
				  enum mailbox_sync_flags flags);
struct mailbox_sync_context *
index_mailbox_sync_init(struct mailbox *box, enum mailbox_sync_flags flags,
			bool failed);
bool index_mailbox_sync_next(struct mailbox_sync_context *ctx,
			all allocated from the given pool. */
	struct fts_result *box_results;
};

extern struct event_category event_category_fts;

int fts_backend_init(const char *backend_name, struct mail_namespace *ns,
		     struct event *event, const char **error_r,
		     struct fts_backend **backend_r);
void fts_backend_deinit(struct fts_backend **backend);

/* Get the last_uid for the mailbox. */
int fts_backend_get_last_uid(struct fts_backend *backend, struct mailbox *box,
			     uint32_t *last_uid_r);
/* Returns 1 if uid has already been indexg);

/* Returns TRUE if arg is atom and case-insensitively matches str */
bool imap_arg_atom_equals(const struct imap_arg *arg, const char *str);

#endif
#ifndef FTS_API_H
#define FTS_API_H

struct mail;
struct mailbox;
struct mail_namespace;
struct mail_search_arg;

struct fts_backend;

#include "seq-range-array.h"

enum fts_lookup_flags {
	/* Specifies if the args should be ANDed or ORed together. */
	FTS_LOOKUP_FLAG_AND_ARGS	= 0x01,
};

enum fts_backend_build_key_type {
	/* Header */
	FTS_BACKEND_BUILD_KEY_HDR,
	/* MIME part hea passdb_result result,
					   const unsigned char *credentials,
					   size_t size,
					   struct auth_request *request);
typedef void set_credentials_callback_t(bool success,
					struct auth_request *request);

struct passdb_module_interface {
	const char *name;

	/* Create a new passdb_module based on the settings looked up via the
	   given event. */
	int (*preinit)(pool_t po