/** @file
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 2001 Gerald Combs
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#ifndef DFILTER_H
#define DFILTER_H

#include <wireshark.h>

#include "dfilter-loc.h"
#include <epan/proto.h>

/* Passed back to user */
typedef struct epan_dfilter dfilter_t;

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

struct epan_dissect;

#define DF_ERROR_GENERIC		-1
#define DF_ERROR_UNEXPECTED_END		-2

/**
 * @brief Represents a display filter error, including an error code, message, and source location.
 */
typedef struct {
    int      code; /**< Numeric error code identifying the type of error. */
    char*    msg;  /**< Human-readable error message describing the failure. */
    df_loc_t loc;  /**< Location within the filter string where the error was detected. */
} df_error_t;

/**
 * @brief Create a new error object with a specific code and message.
 *
 * @param code Error code.
 * @param msg Error message.
 * @param loc Location information for the error (can be NULL).
 * @return Pointer to the newly created error object.
 */
df_error_t *
df_error_new(int code, char *msg, df_loc_t *loc);

/**
 * @brief Create a new error with formatted message.
 *
 * @param code Error code.
 * @param loc Location information for the error.
 * @param fmt Format string for the error message.
 * @return Pointer to the newly created error object.
 */
df_error_t *
df_error_new_printf(int code, df_loc_t *loc, const char *fmt, ...)
G_GNUC_PRINTF(3, 4);

#define df_error_new_msg(msg) \
	df_error_new_printf(DF_ERROR_GENERIC, NULL, "%s", msg)

/**
 * @brief Create a new error with formatted message and location information.
 *
 * @param code Error code.
 * @param loc Location information for the error, or NULL if not applicable.
 * @param fmt Format string for the error message.
 * @param ap Variable argument list corresponding to the format string.
 * @return Pointer to the newly created error object.
 */
df_error_t *
df_error_new_vprintf(int code, df_loc_t *loc, const char *fmt, va_list ap);

/**
 * @brief Frees a df_error_t structure.
 *
 * This function releases memory associated with a df_error_t structure and sets the pointer to NULL.
 *
 * @param ep Pointer to a pointer to the df_error_t structure to be freed.
 */
WS_DLL_PUBLIC
void
df_error_free(df_error_t **ep);

/* Module-level initialization */

/**
 * @brief Initialize the display filter module.
 *
 * This function initializes the display filter module by setting up the parser,
 * syntax-tree subsystem, functions, macros, and plugins using the provided environment variable prefix.
 *
 * @param app_env_var_prefix The prefix for application environment variables.
 */
void
dfilter_init(const char* app_env_var_prefix);

/* Module-level cleanup */
/**
 * @brief Perform module-level cleanup for the dfilter subsystem.
 *
 * This function cleans up resources used by the dfilter system, including
 * plugins, macros, and syntax trees.
 */
void
 dfilter_cleanup(void);

/* Perform macro expansion. */
/**
 * @brief Expand a display filter expression.
 *
 * This function expands a display filter expression by applying macros and performing optimizations.
 *
 * @param expr The input display filter expression to be expanded.
 * @param err_ret Pointer to a pointer for storing any error that occurs during expansion.
 * @return A string representing the expanded display filter, or NULL if an error occurred.
 */
WS_DLL_PUBLIC
char *
dfilter_expand(const char *expr, df_error_t **err_ret);

/* Save textual representation of syntax tree (for debugging purposes). */
#define DF_SAVE_TREE		(1U << 0)
/* Perform macro substitution on filter text. */
#define DF_EXPAND_MACROS	(1U << 1)
/* Do an optimization pass on the compiled filter. */
#define DF_OPTIMIZE		(1U << 2)
/* Enable debug trace for flex. */
#define DF_DEBUG_FLEX		(1U << 3)
/* Enable debug trace for lemon. */
#define DF_DEBUG_LEMON		(1U << 4)
/* If the root of the syntax tree is a field, load and return the field values.
 * By default the field is only checked for existence. */
#define DF_RETURN_VALUES        (1U << 5)

/**
 * @brief Compiles a string to a dfilter_t.
 *
 * On success, sets the dfilter* pointed to by dfp
 * to either a NULL pointer (if the filter is a null
 * filter, as generated by an all-blank string) or to
 * a pointer to the newly-allocated dfilter_t
 * structure.
 *
 * On failure, *err_msg is set to point to the error
 * message.  This error message is allocated with
 * g_malloc(), and must be freed with g_free().
 * The dfilter* will be set to NULL after a failure.
 *
 * Returns true on success, false on failure.
 */
WS_DLL_PUBLIC
bool
dfilter_compile_full(const char *text, dfilter_t **dfp,
			df_error_t **errpp, unsigned flags,
			const char *caller);

#define dfilter_compile(text, dfp, errp) \
	dfilter_compile_full(text, dfp, errp, \
				DF_EXPAND_MACROS|DF_OPTIMIZE, \
				__func__)

struct stnode;

/**
 * @brief Build a syntax tree for a filter
 * @param text A display filter.
 * @return The root node of a syntax tree on success or NULL on failure.
 */
WS_DLL_PUBLIC
struct stnode *dfilter_get_syntax_tree(const char *text);

/**
 * @brief Free a compiled dfilter.
 *
 * Frees all memory used by dfilter, and frees
 * the dfilter itself.
 *
 * @param df Pointer to the dfilter_t structure to be freed.
 */
WS_DLL_PUBLIC
void
dfilter_free(dfilter_t *df);

/**
 * @brief Apply a compiled display filter to an epan_dissect structure.
 *
 * @param df The compiled display filter.
 * @param edt The epan_dissect structure to apply the filter to.
 * @return true if the filter matches, false otherwise.
 */
WS_DLL_PUBLIC
bool
dfilter_apply_edt(dfilter_t *df, struct epan_dissect *edt);

/**
 * @brief Apply a compiled dfilter to a protocol tree.
 *
 * @param df The compiled dfilter to apply.
 * @param tree The protocol tree to which the dfilter will be applied.
 */
bool
dfilter_apply(dfilter_t *df, proto_tree *tree);

/**
 * @brief Apply a dfilter to a proto_tree and populate fvals.
 *
 * Apply compiled dfilter and return final set of fvalues (if they
 * exist) in addition to true/false determination.
 *
 * @param df The dfilter to apply.
 * @param tree The proto_tree to prime with fields/protocols used in the dfilter.
 * @param fvals A pointer to a GPtrArray that will be populated with filter values.
 */
bool
dfilter_apply_full(dfilter_t *df, proto_tree *tree, GPtrArray **fvals);

/**
 * @brief Prime a proto_tree using the fields/protocols used in a dfilter.
 *
 * @param df The display filter to use for priming the tree.
 * @param tree The protocol tree to prime.
 */
void
dfilter_prime_proto_tree(const dfilter_t *df, proto_tree *tree);

/**
 * @brief Prime a proto_tree using the fields/protocols used in a dfilter, marked for print.
 *
 * @param df Pointer to the compiled display filter.
 * @param tree Pointer to the protocol tree.
 */
void
dfilter_prime_proto_tree_print(const dfilter_t *df, proto_tree *tree);

/**
 * @brief Refresh references in a compiled display filter.
 *
 * @param df Pointer to the display filter.
 * @param tree Protocol tree where field references will be loaded.
 */
WS_DLL_PUBLIC
void
dfilter_load_field_references(const dfilter_t *df, proto_tree *tree);

/**
 * @brief Load field references for a display filter into an epan_dissect_t structure.
 *
 * @param df The display filter to process.
 * @param edt The epan_dissect_t structure where field references will be loaded.
 */
WS_DLL_PUBLIC
void
dfilter_load_field_references_edt(const dfilter_t *df, struct epan_dissect *edt);

/**
 * @brief Check if a display filter has any interesting fields.
 *
 * @param df The display filter to check.
 * @return true if the display filter is interested in at least one field, false otherwise.
 */
bool
dfilter_has_interesting_fields(const dfilter_t *df);

/**
 * @brief Check if dfilter is interested in a given field
 *
 * @param df The dfilter
 * @param hfid The header field info ID to check
 * @return true if the field is interesting to the dfilter
 */
bool
dfilter_interested_in_field(const dfilter_t *df, int hfid);

/**
 * @brief Check if dfilter is interested in a given protocol
 *
 * @param df The dfilter
 * @param proto_id The protocol ID to check
 * @return true if the dfilter is interested in a field whose
 * parent is proto_id
 */
bool
dfilter_interested_in_proto(const dfilter_t *df, int proto_id);

/**
 * @brief Check if a display filter requires specific columns.
 *
 * @param df The display filter to check.
 * @return true If the filter requires specific columns, false otherwise.
 */
WS_DLL_PUBLIC
bool
dfilter_requires_columns(const dfilter_t *df);

/**
 * @brief Get deprecated tokens from a dfilter.
 *
 * @param df Pointer to the dfilter_t structure.
 * @return GSList* List of deprecated tokens, or NULL if none are present.
 */
WS_DLL_PUBLIC
GPtrArray *
dfilter_deprecated_tokens(dfilter_t *df);

/**
 * @brief Get warnings associated with a display filter.
 *
 * @param df Pointer to the dfilter_t structure.
 * @return The warnings associated with the display filter.
 */
WS_DLL_PUBLIC
GSList *
dfilter_get_warnings(dfilter_t *df);

#define DF_DUMP_REFERENCES	(1U << 0)
#define DF_DUMP_SHOW_FTYPE	(1U << 1)

/* Print bytecode of dfilter to fp */
/**
 * @brief Dump a dfilter to a file.
 *
 * @param fp File pointer where the dfilter will be dumped.
 * @param df The dfilter to dump.
 * @param flags Flags controlling the dumping process.
 */
WS_DLL_PUBLIC
void
dfilter_dump(FILE *fp, dfilter_t *df, uint16_t flags);

/* Text after macro expansion. */
/**
 * @brief Get the text representation of a syntax tree.
 *
 * @param df Pointer to the dfilter_t structure.
 * @return const char* The text representation of the syntax tree, or NULL if not saved.
 */
WS_DLL_PUBLIC
const char *
dfilter_text(dfilter_t *df);

/**
 * @brief Get the syntax tree of a dfilter.
 *
 * Text representation of syntax tree (if it was saved, NULL otherwise).
 *
 * @param df Pointer to the dfilter_t structure.
 * @return const char* The syntax tree string.
 */
WS_DLL_PUBLIC
const char *
dfilter_syntax_tree(dfilter_t *df);

/**
 * @brief Get the return type of a display filter.
 *
 * @param df Pointer to the dfilter_t structure.
 * @return ftenum_t The return type of the display filter.
 */
WS_DLL_PUBLIC
ftenum_t
dfilter_get_return_type(dfilter_t *df);

/* Print bytecode of dfilter to log */
/**
 * @brief Log a display filter with full details.
 *
 * Logs a display filter along with its bytecode and an optional message at a specified log level.
 *
 * @param domain The logging domain.
 * @param level The log level.
 * @param file The source file name where the log is generated.
 * @param line The line number in the source file.
 * @param func The function name where the log is generated.
 * @param dfcode The display filter to log.
 * @param msg An optional message to include with the log entry.
 */
WS_DLL_PUBLIC
void
dfilter_log_full(const char *domain, enum ws_log_level level,
			const char *file, long line, const char *func,
			dfilter_t *dfcode, const char *msg);

#ifdef WS_DEBUG
#define dfilter_log(dfcode, msg) \
	dfilter_log_full(LOG_DOMAIN_DFILTER, LOG_LEVEL_NOISY,	\
				__FILE__, __LINE__, __func__,	\
				dfcode, msg)
#else
#define dfilter_log(dfcode, msg) (void)0
#endif

#define DFILTER_DEBUG_HERE(dfcode) \
	dfilter_log_full(LOG_DOMAIN_DFILTER, LOG_LEVEL_ECHO,	\
				__FILE__, __LINE__, __func__,	\
				dfcode, #dfcode);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* DFILTER_H */
