id
int64
1
722k
file_path
stringlengths
8
177
funcs
stringlengths
1
35.8M
201
./sleepd/src/pwrevents/sawmill_logger.c
/* @@@LICENSE * * Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ /** * @file sawmill_logger.c * * @brief This module's purpose is to log periodic statistics * to /var/log/messages for processing by sawmill * */ #include <glib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <time.h> #include <stdlib.h> #include <luna-service2/lunaservice.h> #include "init.h" #include "sysfs.h" #define PRINT_INTERVAL_MS 60000 static long unsigned int sTimeOnWake = 0; static long unsigned int sTimeOnPrint = 0; static long unsigned int sTimeScreenOn = 0; static long unsigned int sTimeScreenOff = 0; static int sMSUntilPrint = 0; static bool sScreenIsOn = false; //static timespec sTimeOnSuspended = 0; static long unsigned int sTotalMSAwake = 0; static long unsigned int sTotalMSAsleep = 0; static long unsigned int sTotalMSScreenOn = 0; static long unsigned int sTotalMSScreenOff = 0; static bool sIsAwake = true; static guint sTimerEventSource = 0; #define NS_PER_MS 1000000 #define MS_PER_S 1000 long int time_to_ms(struct timespec t) { return (t.tv_sec * MS_PER_S) + (t.tv_nsec/NS_PER_MS); } /** * * @return A relative timestamp that can be used to compute * elapsed times. */ void get_time_now(struct timespec *time_now) { clock_gettime(CLOCK_REALTIME, time_now); } /** * @brief Return a monotonic time, in ms. * * @return A relative timestamp that can be used to compute * elapsed times. */ long int time_now_ms() { struct timespec time_now; get_time_now(&time_now); return time_to_ms(time_now); } void sawmill_logger_record_sleep(struct timespec time_awake) { sTotalMSAwake += time_to_ms(time_awake); sIsAwake = false; // calculate the amnt of time left to fire sMSUntilPrint = CLAMP(PRINT_INTERVAL_MS - (time_now_ms() - sTimeOnPrint), 0, PRINT_INTERVAL_MS); } void read_lvdisplay(char **buf) { FILE* stream = popen("lvdisplay -c", "r"); int i=0; //char *buf[100]; for (i=0; i<100; i++) buf[i]= calloc(100, sizeof(char)); i=0; while(fgets(buf[i], 100, stream)){ //g_message("lvdisplay: %s", buf[i]); ++i; } // g_message("%s: i is: %d",__func__,i); } void read_proc_loadavg() { char* path = "/proc/loadavg"; GError *gerror = NULL; char *contents = NULL; gsize len; //int n; gchar **arr_file; //, **arr_line; if (!path || !g_file_get_contents(path, &contents, &len, &gerror)) { if (gerror) { g_critical("%s: %s", __FUNCTION__, gerror->message); g_error_free(gerror); } } arr_file = g_strsplit_set(contents," ", -1); g_message("loadavg:1m:%s:5m:%s:15m:%s kr/ke:%s pid:%s", arr_file[0], arr_file[1], arr_file[2], arr_file[3], arr_file[4]); g_strfreev(arr_file); g_free(contents); } void read_proc_diskstats() { GError *gerror = NULL; char *contents = NULL; gsize len; int n; gchar **arr_file, **arr_line; char *path = "/proc/diskstats"; if (!path || !g_file_get_contents(path, &contents, &len, &gerror)) { if (gerror) { g_critical("%s: %s", __FUNCTION__, gerror->message); g_error_free(gerror); } } /* mapping device to mount points char *buf[100]={}; read_lvdisplay(buf); int i=0; while(buf[i]){ //g_message("while loop: i:%d buf:%s:", i, buf[i]); if(!g_strcmp0(buf[i],"")) break; //gchar **mapping_str = g_strsplit_set(buf[i],"/", -1); //g_message("%s", mapping_str[3]); i++; } */ arr_file = g_strsplit_set(contents,"\n", -1); int newlines = g_strv_length(arr_file) - 1; char *all_devices=NULL, *one_device=NULL; for(n=0; n < newlines ; n++){ arr_line = g_strsplit_set(arr_file[n], " ", -1); // cpu0 int k=0, skip=0; int device_index=0; while(arr_line[k]){ if(!g_strcmp0(arr_line[k],"")){ ++k; continue; } if(skip<2){ ++skip; // the initial 2 fields are major and minor numbers. } else { device_index = k; break; } //g_message("%d:%s",k,arr_line[k]); k = k+1; } //g_message("device: %s", arr_line[device_index]); if(g_str_has_prefix(arr_line[device_index],"ram")) { g_strfreev(arr_line); continue; } if(g_str_has_prefix(arr_line[device_index],"loop")) { g_strfreev(arr_line); continue; } if(g_str_has_prefix(arr_line[device_index],"mmcblk0p")) { g_strfreev(arr_line); continue; } //if(g_str_has_prefix(arr_line[device_index],"mmcblk1p")) continue; one_device = g_strdup_printf("%s:r:%s:w:%s:ip:%s", //path, arr_line[device_index], arr_line[device_index + 1], // reads_completed //arr_line[device_index+2], // reads_merged //arr_line[+3], // sectors_read //arr_line[+4], // ms_reading arr_line[device_index + 5], // writes_completed //arr_line[device_index+6], // writes_merged //arr_line[+7], // sectors_written //arr_line[+8], // ms_writing arr_line[device_index + 9] // io_inprogress //arr_line[22] // ms_io //arr_line[8] // ms_weighted_io );//g_strconcat( char* delete_this= all_devices; all_devices = g_strjoin(" ",one_device, all_devices, NULL); g_free(one_device); g_free(delete_this); g_strfreev(arr_line); } g_message("io:%s",all_devices); g_free(all_devices); g_strfreev(arr_file); g_free(contents); } void read_proc_stat() { GError *gerror = NULL; char *contents = NULL; gsize len; int n; gchar **arr_file, **arr_line; char *path = "/proc/stat"; if (!path || !g_file_get_contents(path, &contents, &len, &gerror)) { if (gerror) { g_critical("%s: %s", __FUNCTION__, gerror->message); g_error_free(gerror); } } arr_file = g_strsplit_set(contents,"\n", -1); int newlines = g_strv_length(arr_file) - 1; char* ctxt=NULL; char* procs_running = NULL; for(n=0; n < newlines ; n++){ arr_line = g_strsplit_set(arr_file[n], " ", -1); if(!g_strcmp0(arr_line[0],"ctxt")){ ctxt = g_strdup(arr_line[1]); } if(!g_strcmp0(arr_line[0],"procs_running")){ procs_running = g_strdup(arr_line[1]); } g_strfreev(arr_line); } arr_line = g_strsplit(arr_file[0], " ", -1); // cpu0 g_message("%s_stat: u:%s ulp:%s sys:%s i:%s iow:%s int:%s sint:%s cs:%s pr:%s", //path, arr_line[0], arr_line[2], // arr_line[1] is an empty string arr_line[3], arr_line[4], arr_line[5], arr_line[6], arr_line[7], arr_line[8], ctxt, procs_running ); g_strfreev(arr_line); g_free(ctxt); g_free(procs_running); g_strfreev(arr_file); g_free(contents); } void read_proc_meminfo() { GError *gerror = NULL; char *contents = NULL; gsize len; int n; gchar **arr_file, **arr_line; char *path = "/proc/meminfo"; if (!path || !g_file_get_contents(path, &contents, &len, &gerror)) { if (gerror) { g_critical("%s: %s", __FUNCTION__, gerror->message); g_error_free(gerror); } } arr_file = g_strsplit_set(contents,"\n", -1); int newlines = g_strv_length(arr_file) - 1; char* MemTotal=NULL; char* MemFree = NULL; char* SwapTotal=NULL; char* SwapFree = NULL; for(n=0; n < newlines ; n++){ arr_line = g_strsplit_set(arr_file[n], ":", -1); if(!g_strcmp0(arr_line[0],"MemTotal")){ MemTotal = g_strdup(arr_line[1]); } if(!g_strcmp0(arr_line[0],"MemFree")){ MemFree = g_strdup(arr_line[1]); } if(!g_strcmp0(arr_line[0],"SwapTotal")){ SwapTotal = g_strdup(arr_line[1]); } if(!g_strcmp0(arr_line[0],"SwapFree")){ SwapFree = g_strdup(arr_line[1]); } g_strfreev(arr_line); } g_message("mem:mt:%s mf:%s st:%s sf:%s", g_strstrip(MemTotal), g_strstrip(MemFree), g_strstrip(SwapTotal), g_strstrip(SwapFree)); g_free(MemTotal); g_free(MemFree); g_free(SwapTotal); g_free(SwapFree); g_strfreev(arr_file); g_free(contents); } void read_proc_net_dev() { GError *gerror = NULL; char *contents = NULL; gsize len; int n; gchar **arr_file, **arr_line; char *path = "/proc/net/dev"; if (!path || !g_file_get_contents(path, &contents, &len, &gerror)) { if (gerror) { g_critical("%s: %s", __FUNCTION__, gerror->message); g_error_free(gerror); } } arr_file = g_strsplit_set(contents,"\n", -1); int newlines = g_strv_length(arr_file) - 1; for(n=2; n < newlines ; n++){ arr_line = g_strsplit(arr_file[n], ":", -1); // if((!g_strcmp0(g_strstrip(arr_line[0]),"eth0")) || (!g_strcmp0(g_strstrip(arr_line[0]),"ppp0"))){ char **arr_fields = g_strsplit(arr_line[1], " ", -1); int k=0; int nth_field=0; int received_packets=0; int transmitted_packets=0; while(arr_fields[k]){ if(!g_strcmp0(arr_fields[k],"")){ ++k; continue; } if(nth_field == 1) received_packets = k; if(nth_field == 9) transmitted_packets = k; ++k; ++nth_field; } g_message("net:%s:rp:%s tp:%s", //path, arr_line[0], arr_fields[received_packets], // hack, values seem to start from arr_line[2] arr_fields[transmitted_packets] ); g_strfreev(arr_fields); } g_strfreev(arr_line); } g_strfreev(arr_file); g_free(contents); } void get_battery_coulomb_reading(double *rc, double *c) { #define SYSFS_A6_DEVICE "/sys/class/misc/a6_0/regs/" #define DEF_BATTERY_PATH "/sys/devices/w1 bus master/w1_master_slaves/" if (g_file_test(SYSFS_A6_DEVICE, G_FILE_TEST_IS_DIR)) { SysfsGetDouble(SYSFS_A6_DEVICE "getrawcoulomb", rc); SysfsGetDouble(SYSFS_A6_DEVICE "getcoulomb", c); } else { SysfsGetDouble(DEF_BATTERY_PATH "getrawcoulomb", rc); SysfsGetDouble(DEF_BATTERY_PATH "getcoulomb", c); } } gboolean sawmill_logger_update(gpointer data) { if (sIsAwake) { double rc , c; get_battery_coulomb_reading(&rc, &c); sTimeOnPrint = time_now_ms(); long unsigned int diff_awake = sTimeOnPrint - sTimeOnWake; g_message("%s: raw_coulomb: %f coulomb: %f time_awake_ms: %lu time_asleep_ms: %lu time_screen_on_ms: %lu time_screen_off_ms: %lu", __func__, rc, c, sTotalMSAwake + diff_awake, sTotalMSAsleep, sTotalMSScreenOn + ( sScreenIsOn ? (time_now_ms() - sTimeScreenOn): 0), sTotalMSScreenOff + ( sScreenIsOn ? 0 : (time_now_ms() - sTimeScreenOff)) ); read_proc_loadavg(); read_proc_stat(); read_proc_diskstats(); read_proc_meminfo(); read_proc_net_dev(); } //TODO: use g_timer_source_set_interval(GTimerSource *tsource, guint interval_ms, gboolean from_poll) g_source_remove(sTimerEventSource); sTimerEventSource = g_timeout_add_full(G_PRIORITY_DEFAULT, PRINT_INTERVAL_MS, sawmill_logger_update, GINT_TO_POINTER(TRUE), NULL); return FALSE; } // note we dont get ms resolution here void sawmill_logger_record_wake(struct timespec time_asleep) { unsigned long int ms_asleep = time_to_ms(time_asleep); sTotalMSAsleep += ms_asleep; sTimeOnWake = time_now_ms(); sIsAwake = true; //TODO: use g_timer_source_set_interval(GTimerSource *tsource, guint interval_ms, gboolean from_poll) g_source_remove(sTimerEventSource); sTimerEventSource = g_timeout_add_full(G_PRIORITY_DEFAULT, CLAMP(sMSUntilPrint - ms_asleep, 0, PRINT_INTERVAL_MS), sawmill_logger_update, GINT_TO_POINTER(FALSE), NULL); } void sawmill_logger_record_screen_toggle(bool set_on) { // ignoring duplicate calls if (set_on == sScreenIsOn) return; if (set_on) { sTimeScreenOn = time_now_ms(); sTotalMSScreenOff += (sTimeScreenOn - sTimeScreenOff); } else { sTimeScreenOff = time_now_ms(); sTotalMSScreenOn += (sTimeScreenOff - sTimeScreenOn); } sScreenIsOn = set_on; } static int _sawlog_init(void) { sTimeOnWake = time_now_ms(); sTimeOnPrint = time_now_ms(); sTimeScreenOn = time_now_ms(); sTimeScreenOff = time_now_ms(); sTimerEventSource = g_timeout_add_full(G_PRIORITY_DEFAULT, PRINT_INTERVAL_MS, sawmill_logger_update, GINT_TO_POINTER(TRUE), NULL); return 0; } INIT_FUNC(INIT_FUNC_MIDDLE, _sawlog_init);
202
./sleepd/src/pwrevents/shutdown.c
/* @@@LICENSE * * Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ /** * @file shutdown.c * * @brief Two-tiered shutdown system sequence. * * */ #include <glib.h> #include <cjson/json.h> #include <syslog.h> #include <luna-service2/lunaservice.h> #include "lunaservice_utils.h" #include "debug.h" #include "main.h" #include "logging.h" #include "machine.h" #include "init.h" #define LOG_DOMAIN "SHUTDOWN: " /** * @brief Contains list of applications and services * interested in shutdown. */ typedef struct { GHashTable *applications; GHashTable *services; int num_ack; int num_nack; } ShutdownClientList; typedef enum { kShutdownReplyNoRsp, kShutdownReplyAck, kShutdownReplyNack, kShutdownReplyLast } ShutdownReply; const char* ShutdownReplyString[kShutdownReplyLast] = { "No_Response", "Ack", "Nack", }; static const char* shutdown_reply_to_string(ShutdownReply reply) { if (reply < 0 || reply >= kShutdownReplyLast) return ""; return ShutdownReplyString[reply]; } /** * @brief Client information. */ typedef struct { char *id; char *name; ShutdownReply ack_shutdown; double elapsed; } ShutdownClient; /** * @brief States. */ enum { kPowerShutdownNone, kPowerShutdownApps, kPowerShutdownAppsProcess, kPowerShutdownServices, kPowerShutdownServicesProcess, kPowerShutdownAction, kPowerShutdownLast }; typedef int ShutdownState; /** * @brief Events types that drive the state machine. */ typedef enum { kShutdownEventNone, kShutdownEventShutdownInit, kShutdownEventAbort, kShutdownEventAck, kShutdownEventAllAck, kShutdownEventTimeout, } ShutdownEventType; /** * @brief Event */ typedef struct { ShutdownEventType id; ShutdownClient *client; } ShutdownEvent; /** * PowerShutdownProc the current state and returns the next state */ typedef bool (*PowerShutdownProc)(ShutdownEvent *event, ShutdownState *next); typedef struct { const char *name; ShutdownState state; PowerShutdownProc function; } ShutdownStateNode; static bool state_idle(ShutdownEvent *event, ShutdownState *next); static bool state_shutdown_apps(ShutdownEvent *event, ShutdownState *next); static bool state_shutdown_apps_process(ShutdownEvent *event, ShutdownState *next); static bool state_shutdown_services(ShutdownEvent *event, ShutdownState *next); static bool state_shutdown_services_process(ShutdownEvent *event, ShutdownState *next); static bool state_shutdown_action(ShutdownEvent *event, ShutdownState *next); static void send_shutdown_apps(); static void send_shutdown_services(); static bool shutdown_timeout(void *data); /** * Mapping from state to function handling state. */ static const ShutdownStateNode kStateMachine[kPowerShutdownLast] = { { "ShutdownIdle", kPowerShutdownNone, state_idle }, { "ShutdownApps", kPowerShutdownApps, state_shutdown_apps }, { "ShutdownAppsProcess", kPowerShutdownAppsProcess, state_shutdown_apps_process }, { "ShutdownServices", kPowerShutdownServices, state_shutdown_services }, { "ShutdownServicesProcess", kPowerShutdownServicesProcess, state_shutdown_services_process }, { "ShutdownAction", kPowerShutdownAction, state_shutdown_action }, }; /* Globals */ const ShutdownStateNode *gCurrentState = NULL; ShutdownClientList *sClientList = NULL; LSMessage *shutdown_message = NULL; guint shutdown_apps_timeout_id = 0; GTimer *shutdown_timer = NULL; /** * @defgroup ShutdownProcess Shutdown Process * @ingroup PowerEvents * @brief The Shutdown Process: * * When sleepd receives the /shutdown/initiate luna-call, it sends the shutdown signal * (shutdownApplications) to all the registered applications. It will proceed to the next * stage i.e sending shutdown signal (shutdownServices) to all the registered services, if * all the registered applications respond back by "Ack" or after a timeout of 15 sec. * * Again after sending the shutdownServices signal, it will allow a max timeout of 15 sec * for all the registered services to respond back. Finally it will respond back to the * caller of the "initiate" luna-call with success to indicate the completion of the * shutdown process. */ /** * @addtogroup ShutdownProcess * @{ */ /* Voting */ /** * @brief Allocate memory for a new shutdown client */ static ShutdownClient * client_new(const char *key, const char *clientName) { ShutdownClient *client = g_new0(ShutdownClient, 1); client->id = g_strdup(key); client->name = g_strdup(clientName); client->ack_shutdown = kShutdownReplyNoRsp; return client; } /** * @brief Destroy the client */ static void client_free(ShutdownClient *client) { if (client) { g_free(client->id); g_free(client->name); g_free(client); } } /** * @brief Create a client structure for an application and add it to the global application list * * @param key Unique key for this client * @param clientName Name of the application */ static void client_new_application(const char *key, const char *clientName) { ShutdownClient *client = client_new(key, clientName); g_hash_table_replace(sClientList->applications, client->id, client); } /** * @brief Create a client structure for a service and add it to the global service list * * @param key Unique key for this client * @param clientName Name of the application */ static void client_new_service(const char *key, const char *clientName) { ShutdownClient *client = client_new(key, clientName); g_hash_table_replace(sClientList->services, client->id, client); } /** * @brief Clear the vote count for the given client */ static void client_vote_clear(const char *key, ShutdownClient *client, void *data) { _assert(client != NULL); client->ack_shutdown = kShutdownReplyNoRsp; client->elapsed = 0.0; } /** * @brief Remove the application from the global shutdown application list */ static void client_unregister_application(const char *uid) { g_hash_table_remove(sClientList->applications, uid); } /** * @brief Remove the service from the global shutdown service list */ static void client_unregister_service(const char *uid) { g_hash_table_remove(sClientList->services, uid); } /** * @brief Lookup a service in the service hash list */ static ShutdownClient * client_lookup_service(const char *uid) { return (ShutdownClient*)g_hash_table_lookup( sClientList->services, uid); } /** * @brief Lookup an application in the application hash list */ static ShutdownClient * client_lookup_app(const char *uid) { return (ShutdownClient*)g_hash_table_lookup( sClientList->applications, uid); } /** * @brief Reset global ACK & NACK counts. */ static void client_list_reset_ack_count() { sClientList->num_ack = 0; sClientList->num_nack = 0; } /** * @brief Clear the ACK & NACK counts for all the registered applications and services. */ static void client_list_vote_init() { g_hash_table_foreach(sClientList->applications, (GHFunc)client_vote_clear, NULL); g_hash_table_foreach(sClientList->services, (GHFunc)client_vote_clear, NULL); client_list_reset_ack_count(); } /** * @brief Add an ACK or NACK vote for a client */ static void client_vote(ShutdownClient *client, bool ack) { if (!client) return; client->ack_shutdown = ack ? kShutdownReplyAck : kShutdownReplyNack; client->elapsed = g_timer_elapsed(shutdown_timer, NULL); if (ack) { sClientList->num_ack++; } else { sClientList->num_nack++; } } /** * @brief Log the client's response for the current shutdown voting process */ static void client_vote_print(const char *key, ShutdownClient *client, void *data) { SLEEPDLOG(LOG_INFO, " %s %s %s @ %fs", client->id, client->name, shutdown_reply_to_string(client->ack_shutdown), client->elapsed); } /** * @brief Go through all the clients in the given hash table and log their responses */ static void client_list_print(GHashTable *client_table) { int size = g_hash_table_size(client_table); SLEEPDLOG(LOG_INFO, "clients:"); if (size > 0) { g_hash_table_foreach(client_table, (GHFunc)client_vote_print, NULL); } else { SLEEPDLOG(LOG_INFO, " No clients registered."); } } /** * @brief Return tristate on apps readiness for shutdown. * * @retval 1 if ready, 0 if not ready, -1 if someone nacked. */ static int shutdown_apps_ready() { if (0 == sClientList->num_nack) { int num_clients = g_hash_table_size(sClientList->applications); return sClientList->num_ack >= num_clients; } else { return -1; } } /** * @brief Return tristate on services readiness for shutdown. * * @retval 1 if ready, 0 if not ready, -1 if someone nacked. */ static int shutdown_services_ready() { if (0 == sClientList->num_nack) { int num_clients = g_hash_table_size(sClientList->services); return sClientList->num_ack >= num_clients; } else { return -1; } } /** * @brief The dispatcher for the next state in the shutdown process */ static void shutdown_state_dispatch(ShutdownEvent *event) { ShutdownState next_state = gCurrentState->state; bool running = true; while (running) { running = gCurrentState->function(event, &next_state); _assert(next_state >= gCurrentState->state); if (next_state != gCurrentState->state) { SLEEPDLOG(LOG_DEBUG, "Shutdown: entering state: %s @ %fs", kStateMachine[next_state].name, g_timer_elapsed(shutdown_timer, NULL)); } gCurrentState = &kStateMachine[next_state]; } } /** * @brief Broadcast the "shutdownApplications" signal */ static void send_shutdown_apps() { bool retVal; LSError lserror; LSErrorInit(&lserror); retVal = LSSignalSend(GetLunaServiceHandle(), "luna://com.palm.sleep/shutdown/shutdownApplications", "{}", &lserror); if (!retVal) { g_critical("%s Could not send shutdown applications", __FUNCTION__); LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } } /** * @brief Broadcast the "shutdownServices" signal */ static void send_shutdown_services() { bool retVal; LSError lserror; LSErrorInit(&lserror); retVal = LSSignalSend(GetLunaServiceHandle(), "luna://com.palm.sleep/shutdown/shutdownServices", "{}", &lserror); if (!retVal) { g_critical("%s Could not send shutdown applications", __FUNCTION__); LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } } /** * @brief Unregister te application/service with the given ID. * Called by the cancel function set by LSSubscriptionSetCancelFunction. * * @param clientId */ void shutdown_client_cancel_registration(const char *clientId) { client_unregister_application(clientId); client_unregister_service(clientId); } /** * @brief Unregister te application/service with the given name. * * @param clientName */ void shutdown_client_cancel_registration_by_name(char * clientName) { if (NULL == clientName) return; ShutdownClient *clientInfo=NULL; GHashTableIter iter; gpointer key, value; g_hash_table_iter_init (&iter, sClientList->applications); while (g_hash_table_iter_next (&iter, &key, &value)) { clientInfo=value; if(!strcmp(clientInfo->name,clientName)) { client_unregister_service(clientInfo->id); break; } } g_hash_table_iter_init (&iter, sClientList->services); while (g_hash_table_iter_next (&iter, &key, &value)) { clientInfo=value; if(!strcmp(clientInfo->name,clientName)) { client_unregister_service(clientInfo->id); return; } } return; } /** * @brief The Idle state : Sleepd will always be in this state until the "initiate" shutdown * message is received. */ static bool state_idle(ShutdownEvent *event, ShutdownState *next) { switch (event->id) { case kShutdownEventShutdownInit: client_list_vote_init(); *next = kPowerShutdownApps; return true; default: return false; } } /** * @brief This is the first state that sleepd will go into once the shutdown process has begun. * In this state the "shutdownApplications" signal is sent to all the registered clients. */ static bool state_shutdown_apps(ShutdownEvent *event, ShutdownState *next) { client_list_reset_ack_count(); event->id = kShutdownEventNone; *next = kPowerShutdownAppsProcess; shutdown_apps_timeout_id = g_timeout_add_seconds(15, (GSourceFunc)shutdown_timeout, NULL); send_shutdown_apps(); return true; } /** * @brief This function is called when any of the clients haven't responded back even after 15 sec. */ static bool shutdown_timeout(void *data) { ShutdownEvent event; event.id = kShutdownEventTimeout; event.client = NULL; shutdown_state_dispatch(&event); return FALSE; } /** * @brief Check the client response for the "shutdownApplications" signal. We get to this state either when * a client ACKs or we have timed out. */ static bool state_shutdown_apps_process(ShutdownEvent *event, ShutdownState *next) { bool timeout = false; switch (event->id) { case kShutdownEventAck: client_vote(event->client, true); break; case kShutdownEventTimeout: timeout = true; break; default: break; } int readiness = shutdown_apps_ready(); if (readiness > 0 || timeout) { if (timeout) { SLEEPDLOG(LOG_CRIT, "Shutdown apps timed out: "); } client_list_print(sClientList->applications); g_source_remove(shutdown_apps_timeout_id); *next = kPowerShutdownServices; return true; } else if (readiness < 0) { *next = kPowerShutdownNone; return false; } else { *next = kPowerShutdownAppsProcess; return false; } } /** * @brief This is the first state that sleepd will go into once the shutdown process has begun. * In this state the "shutdownServices" signal is sent to all the registered clients. */ static bool state_shutdown_services(ShutdownEvent *event, ShutdownState *next) { client_list_reset_ack_count(); event->id = kShutdownEventNone; *next = kPowerShutdownServicesProcess; shutdown_apps_timeout_id = g_timeout_add_seconds(15, (GSourceFunc)shutdown_timeout, NULL); send_shutdown_services(); return true; } /** * @brief Check the client response for the "shutdownServices" signal. We get to this state either when * a client ACKs or we have timed out. */ static bool state_shutdown_services_process(ShutdownEvent *event, ShutdownState *next) { bool timeout = false; switch (event->id) { case kShutdownEventAck: client_vote(event->client, true); break; case kShutdownEventTimeout: timeout = true; break; default: break; } int readiness = shutdown_services_ready(); if (readiness > 0 || timeout) { if (timeout) { SLEEPDLOG(LOG_CRIT, "Shutdown services timed out: "); } client_list_print(sClientList->services); *next = kPowerShutdownAction; g_source_remove(shutdown_apps_timeout_id); return true; } else if (readiness < 0) { *next = kPowerShutdownNone; return false; } else { *next = kPowerShutdownServicesProcess; return false; } } /** * @brief This is the final state in the shutdown process when we notify the caller of the "initiate" method * that shutdown polling has been successfully completed. */ static bool state_shutdown_action(ShutdownEvent *event, ShutdownState *next) { bool retVal = LSMessageReply(GetLunaServiceHandle(), shutdown_message, "{\"success\":true}", NULL); if (!retVal) { g_critical("%s: Could not send shutdown success message", __FUNCTION__); } if (shutdown_message) { LSMessageUnref(shutdown_message); shutdown_message = NULL; } nyx_system_set_alarm(GetNyxSystemDevice(),0,NULL,NULL); return false; } /** * @brief Send response to the caller of the luna call. */ static void send_reply(LSHandle *sh, LSMessage *message, const char *format, ...) { bool retVal; char *payload; va_list vargs; va_start(vargs, format); payload = g_strdup_vprintf(format, vargs); va_end(vargs); retVal = LSMessageReply(sh, message, payload, NULL); if (!retVal) { g_critical("Could not send reply with payload %s", payload); } g_free(payload); } /** * @brief The callback function for "initiate" method. This will initiate the shutdown process. * * @param sh * @param message This method doesn't need any arguments. * @param user_data */ static bool initiateShutdown(LSHandle *sh, LSMessage *message, void *user_data) { ShutdownEvent event; event.id = kShutdownEventShutdownInit; event.client = NULL; LSMessageRef(message); shutdown_message = message; g_timer_start(shutdown_timer); shutdown_state_dispatch(&event); return true; } /** * @brief Called by test code to reset state machine to square 1. * * @param sh * @param message * @param user_data * * @retval */ static bool TESTresetShutdownState(LSHandle *sh, LSMessage *message, void *user_data) { g_debug("Resetting shutdown state."); gCurrentState = &kStateMachine[kPowerShutdownNone]; return true; } /** * @brief Callback function for "shutdownApplicationsAck" method. This will set the client's response * as ACK for the "shutdownApplications" signal and trigger the dispatcher for the shutdown state * machine, so that if the total client ACK count exceeds total number of clients, it can proceed * to the next state. * * @param sh * @param message with "clientId" string to retrieve client information * @param user_data */ static bool shutdownApplicationsAck(LSHandle *sh, LSMessage *message, void *user_data) { struct json_object *object = json_tokener_parse( LSMessageGetPayload(message)); if (is_error(object)) { LSMessageReplyErrorBadJSON(sh, message); goto cleanup; } const char *clientId = json_object_get_string( json_object_object_get(object, "clientId")); if (!clientId) { LSMessageReplyErrorInvalidParams(sh, message); goto cleanup; } ShutdownEvent event; event.id = kShutdownEventAck; event.client = client_lookup_app(clientId); shutdown_state_dispatch(&event); cleanup: if (!is_error(object)) json_object_put(object); return true; } /** * @brief Callback function for "shutdownServicesAck" method. This will set the client's response * as ACK for the "shutdownServices" signal and trigger the dispatcher for the shutdown state * machine, so that if the total client ACK count exceeds total number of clients, it can proceed * to the next state. * * @param sh * @param message with "clientId" string to retrieve client information * @param user_data */ static bool shutdownServicesAck(LSHandle *sh, LSMessage *message, void *user_data) { struct json_object *object = json_tokener_parse( LSMessageGetPayload(message)); if (is_error(object)) { LSMessageReplyErrorBadJSON(sh, message); goto cleanup; } const char *clientId = json_object_get_string( json_object_object_get(object, "clientId")); if (!clientId) { LSMessageReplyErrorInvalidParams(sh, message); goto cleanup; } ShutdownEvent event; event.id = kShutdownEventAck; event.client = client_lookup_service(clientId); shutdown_state_dispatch(&event); cleanup: if (!is_error(object)) json_object_put(object); return true; } /** * @brief Register an application for the "shutdownApplications" signal. Send the client id of the client * added. * * @param sh * @param message contains "clientName" for application's name. * @param user_data */ static bool shutdownApplicationsRegister(LSHandle *sh, LSMessage *message, void *user_data) { struct json_object *object = json_tokener_parse(LSMessageGetPayload(message)); if (is_error(object)) goto end; const char *clientId = LSMessageGetUniqueToken(message); const char *clientName = json_object_get_string(json_object_object_get( object, "clientName")); client_new_application(clientId, clientName); bool retVal; LSError lserror; LSErrorInit(&lserror); retVal = LSSubscriptionAdd(sh, "shutdownClient", message, &lserror); if (!retVal) { g_critical("LSSubscriptionAdd failed."); LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } send_reply(sh, message, "{\"clientId\":\"%s\"}", clientId); json_object_put(object); end: return true; } /** * @brief Register an application for the "shutdownServices" signal. Send the client id of the client * added. * * @param sh * @param message contains "clientName" for service name. * @param user_data */ static bool shutdownServicesRegister(LSHandle *sh, LSMessage *message, void *user_data) { struct json_object *object = json_tokener_parse(LSMessageGetPayload(message)); if (is_error(object)) goto end; const char *clientId = LSMessageGetUniqueToken(message); const char *clientName = json_object_get_string(json_object_object_get( object, "clientName")); client_new_service(clientId, clientName); bool retVal; LSError lserror; LSErrorInit(&lserror); retVal = LSSubscriptionAdd(sh, "shutdownClient", message, &lserror); if (!retVal) { g_critical("LSSubscriptionAdd failed."); LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } send_reply(sh, message, "{\"clientId\":\"%s\"}", clientId); json_object_put(object); end: return true; } /** * @brief Shutdown the machine forcefully * * @param sh * @param message with "reason" field for shutdown reason. * @param user_data */ static bool machineOff(LSHandle *sh, LSMessage *message, void *user_data) { struct json_object *object = json_tokener_parse( LSMessageGetPayload(message)); if (is_error(object)) { LSMessageReplyErrorBadJSON(sh, message); goto cleanup; } const char *reason = json_object_get_string( json_object_object_get(object, "reason")); if (!reason) { LSMessageReplyErrorInvalidParams(sh, message); goto cleanup; } MachineForceShutdown(reason); LSMessageReplySuccess(sh, message); cleanup: if (!is_error(object)) json_object_put(object); return true; } /** * @brief Reboot the machine forcefully by calling "reboot" * * @param sh * @param message with "reason" field for reboot reason. * @param user_data */ static bool machineReboot(LSHandle *sh, LSMessage *message, void *user_data) { struct json_object *object = json_tokener_parse( LSMessageGetPayload(message)); if (is_error(object)) { LSMessageReplyErrorBadJSON(sh, message); goto cleanup; } const char *reason = json_object_get_string( json_object_object_get(object, "reason")); if (!reason) { LSMessageReplyErrorInvalidParams(sh, message); goto cleanup; } MachineForceReboot(reason); LSMessageReplySuccess(sh, message); cleanup: if (!is_error(object)) json_object_put(object); return true; } LSMethod shutdown_methods[] = { { "initiate", initiateShutdown, }, { "shutdownApplicationsRegister", shutdownApplicationsRegister }, { "shutdownApplicationsAck", shutdownApplicationsAck }, { "shutdownServicesRegister", shutdownServicesRegister }, { "shutdownServicesAck", shutdownServicesAck }, { "TESTresetShutdownState", TESTresetShutdownState }, { "machineOff", machineOff }, { "machineReboot", machineReboot }, { }, }; LSSignal shutdown_signals[] = { { "shutdownApplications" }, { "shutdownServices" }, { }, }; static int shutdown_init(void) { sClientList = g_new0(ShutdownClientList, 1); sClientList->applications = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, (GDestroyNotify)client_free); sClientList->services = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, (GDestroyNotify)client_free); sClientList->num_ack = 0; sClientList->num_nack = 0; shutdown_timer = g_timer_new(); gCurrentState = &kStateMachine[kPowerShutdownNone]; LSError lserror; LSErrorInit(&lserror); if (!LSRegisterCategory(GetLunaServiceHandle(), "/shutdown", shutdown_methods, shutdown_signals, NULL, &lserror)) { goto error; } return 0; error: LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); return -1; } INIT_FUNC(INIT_FUNC_MIDDLE, shutdown_init); /* @} END OF ShutdownProcess */
203
./sleepd/src/utils/timesaver.c
/* @@@LICENSE * * Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ #include <glib.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include "config.h" #include "logging.h" #include "main.h" #define LOG_DOMAIN "timesaver: " #define POWERD_RESTORES_TIME static char *time_db = NULL; static char *time_db_tmp = NULL; /** * @brief Save the current time in the file "time_saver" so that it can be used in future. * * @retval */ void timesaver_save() { if (!time_db) { time_db = g_build_filename( gSleepConfig.preference_dir, "time_saver", NULL); time_db_tmp = g_build_filename( gSleepConfig.preference_dir, "time_saver.tmp", NULL); } if (NULL == time_db) { // This can happen if we goto ls_error in main() g_warning("%s called with time database name (time_db) uninitialized", __FUNCTION__); goto cleanup; } // First write the contents to tmp file and then rename to "time_saver" file // to ensure file integrity with power cut or battery pull. int file = open(time_db_tmp, O_CREAT | O_WRONLY, S_IRWXU | S_IRGRP | S_IROTH); if (!file) { g_warning("%s: Could not save time to \"%s\"", __FUNCTION__, time_db_tmp); goto cleanup; } struct timespec tp; clock_gettime(CLOCK_REALTIME, &tp); SLEEPDLOG(LOG_DEBUG, "%s Saving to file %ld", __FUNCTION__, tp.tv_sec); char timestamp[16]; snprintf(timestamp,sizeof(timestamp),"%ld", tp.tv_sec); write(file,timestamp,strlen(timestamp)); fsync(file); close(file); int ret = rename(time_db_tmp,time_db); if (ret) { g_warning("%s : Unable to rename %s to %s",__FUNCTION__,time_db_tmp,time_db); } unlink(time_db_tmp); cleanup: return; }
204
./sleepd/src/utils/timersource.c
/* @@@LICENSE * * Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ /** * @file sysfs.c * * @brief GTimerSource - a source needed because the typical GSources do not have necessary features. * I write this utility with the intention that this might be contributed back to glib * in the future. * * GTimerSource * 1) Can be forced to expire. * 2) The expiration interval may be changed. * 3) Uses a montonic clock. * */ #include <glib.h> #include "timersource.h" #include "clock.h" struct _GTimerSource { GSource source; GTimeVal expiration; /* Should I just make this use Clock* API? */ guint interval_ms; /* In milisecs */ guint granularity; }; static gboolean g_timer_source_prepare(GSource *source, gint *timeout_ms); static gboolean g_timer_source_check(GSource *source); static gboolean g_timer_source_dispatch(GSource *source, GSourceFunc callback, gpointer user_data); GSourceFuncs g_timer_source_funcs= { .prepare = g_timer_source_prepare, .check = g_timer_source_check, .dispatch = g_timer_source_dispatch, .finalize = NULL, }; #define USECS_PER_SEC 1000000 #define USECS_PER_MSEC 1000 static void g_timer_set_expiration(GTimerSource *rsource, GTimeVal *now) { guint interval_secs = rsource->interval_ms / 1000; glong interval_usecs = (rsource->interval_ms - interval_secs * 1000) * 1000; rsource->expiration.tv_sec = now->tv_sec + interval_secs; rsource->expiration.tv_usec = now->tv_usec + interval_usecs; if (rsource->expiration.tv_usec >= USECS_PER_SEC) { rsource->expiration.tv_usec -= USECS_PER_SEC; rsource->expiration.tv_sec++; } if (rsource->granularity) { gint gran; gint remainder; gran = rsource->granularity * USECS_PER_MSEC; remainder = rsource->expiration.tv_usec % gran; if (remainder >= gran / 4) rsource->expiration.tv_usec += gran; rsource->expiration.tv_usec -= remainder; while (rsource->expiration.tv_usec > USECS_PER_SEC) { rsource->expiration.tv_usec -= USECS_PER_SEC; rsource->expiration.tv_sec++; } } } static void g_timer_get_current_time(GTimerSource *tsource, GTimeVal *now) { g_return_if_fail (now != NULL); // TODO: We should do a time_is_current and skip syscalls struct timespec tv; ClockGetTime(&tv); now->tv_sec = tv.tv_sec; now->tv_usec = tv.tv_nsec / 1000; } static gboolean g_timer_source_prepare(GSource *source, gint *timeout_ms) { GTimeVal now; GTimerSource *tsource = (GTimerSource*)source; g_timer_get_current_time (tsource, &now); // assume monotic clock glong msec = (tsource->expiration.tv_sec - now.tv_sec) * 1000; if (msec < 0) { msec = 0; } else { msec += (tsource->expiration.tv_usec - now.tv_usec)/1000; if (msec < 0) { msec = 0; } } *timeout_ms = (gint)msec; return (msec == 0); } static gboolean g_timer_source_check(GSource *source) { GTimeVal now; GTimerSource *tsource = (GTimerSource*)source; g_timer_get_current_time(tsource, &now); return (tsource->expiration.tv_sec < now.tv_sec) || ((tsource->expiration.tv_sec == now.tv_sec) && (tsource->expiration.tv_usec <= now.tv_usec)); } static gboolean g_timer_source_dispatch(GSource *source, GSourceFunc callback, gpointer user_data) { GTimerSource *tsource = (GTimerSource*)source; if (!callback) { g_warning("Timeout source dispatched without callback\n" "Call g_source_set_callback()."); return FALSE; } if (callback(user_data)) { GTimeVal now; g_timer_get_current_time(tsource, &now); g_timer_set_expiration(tsource, &now); return TRUE; } else { return FALSE; } } /** Public Functions */ /** * @brief A create a timer with 100 ms resolution. * * @param interval_ms * * @retval */ GTimerSource * g_timer_source_new(guint interval_ms, guint granularity_ms) { GSource *source; GTimerSource *tsource; source = g_source_new(&g_timer_source_funcs, sizeof(GTimerSource)); tsource = (GTimerSource*)source; GTimeVal now; tsource->interval_ms = interval_ms; tsource->granularity = granularity_ms; g_timer_get_current_time(tsource, &now); g_timer_set_expiration(tsource, &now); return tsource; } GTimerSource * g_timer_source_new_seconds(guint interval_sec) { GSource *source; GTimerSource *tsource; source = g_source_new(&g_timer_source_funcs, sizeof(GTimerSource)); tsource = (GTimerSource*)source; GTimeVal now; tsource->interval_ms = 1000*interval_sec; tsource->granularity = 1000; g_timer_get_current_time(tsource, &now); g_timer_set_expiration(tsource, &now); return tsource; } void g_timer_source_set_interval_seconds(GTimerSource *tsource, guint interval_sec, gboolean from_poll) { g_timer_source_set_interval(tsource, interval_sec * 1000, from_poll); } void g_timer_source_set_interval(GTimerSource *tsource, guint interval_ms, gboolean from_poll) { GTimeVal now; g_timer_get_current_time(tsource, &now); tsource->interval_ms = interval_ms; g_timer_set_expiration(tsource, &now); if (!from_poll) { GMainContext *context = g_source_get_context((GSource*)tsource); if (!context) { g_critical("Cannot get context for timer_source.\n" "Maybe you didn't call g_source_attach()\n"); return; } g_main_context_wakeup(context); } } guint g_timer_source_get_interval_ms(GTimerSource *tsource) { return tsource->interval_ms; }
205
./sleepd/src/utils/sysfs.c
/* @@@LICENSE * * Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ /** * @file sysfs.c * * @brief Get or set sysfs entries. * */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <glib.h> #include "logging.h" #include "debug.h" #define LOG_DOMAIN "sysfs:" /** * Returns string in pre-allocated buffer. */ int SysfsGetString(const char *path, char *ret_string, size_t maxlen) { GError *gerror = NULL; char *contents = NULL; gsize len; if (!path || !g_file_get_contents(path, &contents, &len, &gerror)) { if (gerror) { SLEEPDLOG(LOG_CRIT, "%s: %s", __FUNCTION__, gerror->message); g_error_free(gerror); } return -1; } g_strstrip(contents); g_strlcpy(ret_string, contents, maxlen); g_free(contents); return 0; } int SysfsGetInt(const char *path, int *ret_data) { GError *gerror = NULL; char *contents = NULL; char *endptr; gsize len; long int val; if (!path || !g_file_get_contents(path, &contents, &len, &gerror)) { if (gerror) { SLEEPDLOG(LOG_CRIT, "%s: %s", __FUNCTION__, gerror->message); g_error_free(gerror); } return -1; } val = strtol(contents, &endptr, 10); if (endptr == contents) { SLEEPDLOG(LOG_CRIT, "%s: Invalid input in %s.", __FUNCTION__, path); goto end; } if (ret_data) *ret_data = val; end: g_free(contents); return 0; } int SysfsGetDouble(const char *path, double *ret_data) { GError *gerror = NULL; char *contents = NULL; char *endptr; gsize len; float val; if (!path || !g_file_get_contents(path, &contents, &len, &gerror)) { if (gerror) { SLEEPDLOG(LOG_CRIT, "%s: %s", __FUNCTION__, gerror->message); g_error_free(gerror); } return -1; } val = strtod(contents, &endptr); if (endptr == contents) { SLEEPDLOG(LOG_CRIT, "%s: Invalid input in %s.", __FUNCTION__, path); goto end; } if (ret_data) *ret_data = val; end: g_free(contents); return 0; } /** * @returns 0 on success or -1 on error */ int SysfsWriteString(const char *path, const char *string) { int fd; ssize_t n; fd = open(path, O_WRONLY); if (fd < 0) return -1; n = write(fd, string, strlen(string)); close(fd); return n >= 0 ? 0 : -1; }
206
./sleepd/src/utils/lunaservice_utils.c
/* @@@LICENSE * * Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ #include "lunaservice_utils.h" void LSMessageReplyErrorUnknown(LSHandle *sh, LSMessage *message) { LSError lserror; LSErrorInit(&lserror); bool retVal = LSMessageReply(sh, message, "{\"returnValue\":false," "\"errorText\":\"Unknown Error.\"}", &lserror); if (!retVal) { LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } } void LSMessageReplyErrorInvalidParams(LSHandle *sh, LSMessage *message) { LSError lserror; LSErrorInit(&lserror); bool retVal = LSMessageReply(sh, message, "{\"returnValue\":false," "\"errorText\":\"Invalid parameters.\"}", NULL); if (!retVal) { LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } } void LSMessageReplyErrorBadJSON(LSHandle *sh, LSMessage *message) { LSError lserror; LSErrorInit(&lserror); bool retVal = LSMessageReply(sh, message, "{\"returnValue\":false," "\"errorText\":\"Malformed json.\"}", NULL); if (!retVal) { LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } } void LSMessageReplySuccess(LSHandle *sh, LSMessage *message) { LSError lserror; LSErrorInit(&lserror); bool retVal = LSMessageReply(sh, message, "{\"returnValue\":true}", NULL); if (!retVal) { LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } }
207
./sleepd/src/utils/logging.c
/* @@@LICENSE * * Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ /** * @file logging.c * * @brief Logging interface. * * This is for redirecting GLib's logging commands (g_message, g_debug, g_error) * to the appropriate handlers */ #include <stdio.h> #include <stdlib.h> #include <glib.h> #include <syslog.h> #include <stdbool.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdarg.h> #include "logging.h" static int sLogLevel = G_LOG_LEVEL_MESSAGE; static LOGHandler sHandler = LOGGlibLog; void _good_assert(const char * cond_str, bool cond) { if (G_UNLIKELY(!(cond))) { g_critical("%s", cond_str); *(int*)0x00 = 0; } } int get_glib_from_syslog_level(int syslog_level) { switch(syslog_level) { case LOG_EMERG: /* system is unusable */ return G_LOG_LEVEL_ERROR; case LOG_ALERT: /* action must be taken immediately */ return G_LOG_LEVEL_CRITICAL; case LOG_CRIT: /* critical conditions */ return G_LOG_LEVEL_CRITICAL; case LOG_ERR: /* error conditions */ return G_LOG_LEVEL_CRITICAL; case LOG_WARNING: /* warning conditions */ return G_LOG_LEVEL_WARNING; case LOG_NOTICE: /* normal but significant condition */ return G_LOG_LEVEL_MESSAGE; case LOG_INFO: /* informational */ return G_LOG_LEVEL_INFO; case LOG_DEBUG: /* debug-level messages */ return G_LOG_LEVEL_DEBUG; } return G_LOG_LEVEL_INFO; } int get_syslog_from_glib_level(int glib_level) { switch (glib_level & G_LOG_LEVEL_MASK) { case G_LOG_LEVEL_ERROR: return LOG_CRIT; case G_LOG_LEVEL_CRITICAL: return LOG_ERR; case G_LOG_LEVEL_WARNING: return LOG_WARNING; case G_LOG_LEVEL_MESSAGE: return LOG_NOTICE; case G_LOG_LEVEL_INFO: return LOG_INFO; case G_LOG_LEVEL_DEBUG: return LOG_DEBUG; } return LOG_NOTICE; } /** * @brief LOGSetLevel * * @param level */ void LOGSetLevel(int level) { // asserting this is a log level g_assert( (level & G_LOG_LEVEL_MASK) != 0 ); g_assert( (level | G_LOG_LEVEL_MASK) == G_LOG_LEVEL_MASK ); sLogLevel = level; } /* int LOGGetLevel() { return sLogLevel; } */ /** * @brief logFilter * filter we use to redirect glib's messages * * @param log_domain * @param log_level * @param message * @param unused_data */ static void logFilter(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer unused_data) { if (log_level > sLogLevel) return; g_assert( sHandler < LOG_NUM_HANDLERS ); g_assert( sHandler >= 0 ); switch (sHandler) { case LOGSyslog: syslog(get_syslog_from_glib_level(log_level), "%s", message); break; case LOGGlibLog: g_log_default_handler(log_domain, log_level, message, unused_data); break; default: fprintf(stderr, "%s: no handler %d for log message\n", __func__, sHandler); abort(); } } /** * @brief LOGSetHandler * * @param h */ void LOGSetHandler(LOGHandler h) { g_assert( h < LOG_NUM_HANDLERS ); g_assert( h >= 0 ); sHandler = h; } /** * @brief LOGInit */ void LOGInit() { g_log_set_default_handler(logFilter, NULL); } void write_console(char *format, ...) { int fd; fd = open("/dev/console", O_RDWR | O_NOCTTY); if (fd < 0) { perror("open"); return; } va_list args; va_start(args, format); char buffer[1024]; int len = vsnprintf(buffer, sizeof(buffer), format, args); if (len > 0) { write(fd, buffer, len); } va_end(args); close(fd); }
208
./sleepd/src/utils/init.c
/* @@@LICENSE * * Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ #include <glib.h> #include <stdlib.h> #include <string.h> #include "init.h" #include "config.h" #include "machine.h" #include "debug.h" typedef struct _GNamedHookList { GHookList hookList; const char *name; } GNamedHookList; /* hash from string -> GNamedHookList */ static GHashTable *namedInitFuncs = NULL; static void HookInit(gpointer func) { InitFunc f = func; int ret = f(); if (ret < 0) { g_error("%s: Could not initialize %p\n", __FUNCTION__, func); } } typedef struct { GHook base; const char *func_name; InitFuncPriority priority; } GPrioritizedHook; /** * @returns 1 if new_hook should be inserted after sibling, * and <= 0 if new_hook should be inserted before sibling. */ static gint GPrioritizedHookCompare(GHook *new_hook, GHook *sibling) { GPrioritizedHook *new_hook_pr = (GPrioritizedHook*)new_hook; GPrioritizedHook *sibling_pr = (GPrioritizedHook*)sibling; return (new_hook_pr->priority > sibling_pr->priority); } /** * Add an InitFunc to the hooklist with the name 'name' */ void NamedInitFuncAdd(const char *name, InitFuncPriority priority, InitFunc func, const char *func_name) { if (!namedInitFuncs) { namedInitFuncs = g_hash_table_new(g_str_hash, g_str_equal); if (!namedInitFuncs) { g_error("%s: Out of memory on initialization.\n", __FUNCTION__); abort(); } } if (g_hash_table_lookup(namedInitFuncs, (gconstpointer)name) == NULL) { GNamedHookList *namedHookList = malloc(sizeof (GNamedHookList)); if (!namedHookList) { g_error("%s: Out of memory on initialization.\n", __FUNCTION__); abort(); } g_hook_list_init((GHookList*)namedHookList, sizeof(GPrioritizedHook)); namedHookList->name = name; g_hash_table_insert(namedInitFuncs, (char*)name, namedHookList); } GHookList *hookList = (GHookList*)g_hash_table_lookup(namedInitFuncs, (gconstpointer)name); GPrioritizedHook *hook = (GPrioritizedHook*)g_hook_alloc(hookList); hook->base.data = func; hook->base.func = HookInit; hook->priority = priority; hook->func_name = func_name; g_hook_insert_sorted(hookList, (GHook*)hook, GPrioritizedHookCompare); } void GProritizedHookPrint(GHook *hook, gpointer data) { GPrioritizedHook *gphook = (GPrioritizedHook*)hook; g_info("%d. %s", gphook->priority, gphook->func_name); } void GHookListPrint(gpointer key, gpointer value, gpointer data) { const char *hookName = (const char*)key; GHookList *hookList = (GHookList*)value; g_info("InitList: %s", hookName); g_hook_list_marshal(hookList, TRUE, GProritizedHookPrint, NULL); } /** * Print out the hook lists (for debug). */ void PrintHookLists(void) { g_hash_table_foreach(namedInitFuncs, GHookListPrint, NULL); } /** * Instantiates all the */ void TheOneInit(void) { if (gSleepConfig.debug) { PrintHookLists(); } /** Run common init funcs **/ GHookList *commonInitFuncs = g_hash_table_lookup(namedInitFuncs, COMMON_INIT_NAME); if (commonInitFuncs) { g_info("\n%s Running common Inits", __FUNCTION__); g_hook_list_invoke(commonInitFuncs, FALSE); } }
209
./sleepd/src/alarms/timeout_alarm.c
/* @@@LICENSE * * Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ /** * @file timeout_alarm.c * * @brief New interface add/clear alarms using RTC. * */ #include <glib.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <cjson/json.h> #include <sys/stat.h> #include <luna-service2/lunaservice.h> #include "main.h" #include "logging.h" #include "smartsql.h" #include "lunaservice_utils.h" #include "timersource.h" #include "timeout_alarm.h" #include "config.h" #include "init.h" #define LOG_DOMAIN "ALARMS-TIMEOUT: " #define ACTIVITY_DURATION_MS_MINIMUM 5000 #define ACTIVITY_DURATION_MS_MINIMUM_AS_TEXT "5000 ms" /* Always define these so we can warn (but allow) a timeout below TIMEOUT_MINIMUM_HANDSET_SEC on the desktop or emulator builds */ #define TIMEOUT_MINIMUM_HANDSET_SEC (5*60) #define TIMEOUT_MINIMUM_HANDSET_AS_TEXT "5 minutes" #define TIMEOUT_MINIMUM_SEC (5) #define TIMEOUT_MINIMUM_AS_TEXT "5 seconds" // keep the device on for at least 5s. #define TIMEOUT_KEEP_ALIVE_MS 5000 #define DEFAULT_ACTIVITY_ID "com.palm.sleepd.timeout_fired" #define STD_ASCTIME_BUF_SIZE 26 // This allows testing the SQL commands to add the new columns. Set to false for production code #define CREATE_DB_WITHOUT_ACTIVITY_COLUMNS 0 #define TIMEOUT_DATABASE_NAME "SysTimeouts.db" typedef enum { AlarmTimeoutRelative, AlarmTimeoutCalendar, } AlarmTimeoutType; static LSPalmService *psh = NULL; static sqlite3 *timeout_db = NULL; static GTimerSource *sTimerCheck = NULL; /* Database Schema. We use an sqlite3 database to store all pending events. The schema is designed so that the event list can be quickly sorted and the next item to fire can be quickly read. expiry is the absolute system time of when the next event is to be fired. It is GMT, so all math performed with it needs to be in GMT as well. */ #if CREATE_DB_WITHOUT_ACTIVITY_COLUMNS static const char* kSysTimeoutDatabaseCreateSchema = "\ CREATE TABLE IF NOT EXISTS AlarmTimeout (t1key INTEGER PRIMARY KEY,\ app_id TEXT,\ key TEXT,\ uri TEXT,\ params TEXT,\ public_bus INTEGER,\ wakeup INTEGER,\ calendar INTEGER,\ expiry DATE);"; #else static const char* kSysTimeoutDatabaseCreateSchema = "\ CREATE TABLE IF NOT EXISTS AlarmTimeout (t1key INTEGER PRIMARY KEY,\ app_id TEXT,\ key TEXT,\ uri TEXT,\ params TEXT,\ public_bus INTEGER,\ wakeup INTEGER,\ calendar INTEGER,\ expiry DATE,\ activity_id TEXT,\ activity_duration_ms INTEGER);"; #endif static const char* kSysTimeoutDatabaseCreateIndex = "\ CREATE INDEX IF NOT EXISTS expiry_index on AlarmTimeout (expiry);"; /** * @defgroup NewInterface New interface * @ingroup RTCAlarms * @brief New interface for RTC alarms using SQLite. */ /** * @addtogroup NewInterface * @{ */ static time_t rtc_to_wall = 0; /** * @brief Convert to rtc time. * * @param t * * @retval */ static time_t to_rtc(time_t t) { return t - rtc_to_wall; } /** * @brief Last wall time. * * @retval */ time_t rtc_wall_time(void) { time_t rtctime = 0; nyx_system_query_rtc_time(GetNyxSystemDevice(),&rtctime); return rtctime + rtc_to_wall; } /** * @brief Calculate the time difference between RTC time and wall time */ bool wall_rtc_diff(time_t *ret_delta) { time_t rtc_time_now = 0; time_t wall_time_now = 0; nyx_system_query_rtc_time(GetNyxSystemDevice(),&rtc_time_now); time(&wall_time_now); /* Calculate the time difference */ time_t delta = wall_time_now - rtc_time_now; if (ret_delta) { *ret_delta = delta; } return true; } /** * @brief Update the rtc and return the difference rtc changed by. * * @retval */ static time_t update_rtc(time_t *ret_delta) { bool retVal; time_t new_delta = 0; time_t delta = 0; retVal = wall_rtc_diff(&new_delta); if (!retVal) return false; if (new_delta != rtc_to_wall) { delta = new_delta - rtc_to_wall; rtc_to_wall = new_delta; } if (ret_delta) *ret_delta = delta; return true; } static void _print_timeout(const char *message, const char *app_id, const char *key, bool public_bus, time_t expiry) { struct tm expiry_tm; char buf[STD_ASCTIME_BUF_SIZE]; gmtime_r(&expiry, &expiry_tm); asctime_r(&expiry_tm, buf); SLEEPDLOG(LOG_DEBUG, "%s, timeout for (\"%s\", \"%s\", %s) at %ld, %s", message, app_id, key, public_bus ? "public" : "private", expiry, buf); } void _update_timeouts(void); /** * @brief Called when a new alarm from the RTC is fired. */ static void _rtc_alarm_fired(nyx_device_handle_t handle, nyx_callback_status_t status, void* data) { g_debug(LOG_DOMAIN "%s ", __FUNCTION__); _update_timeouts(); } /** * @brief Response to timeout message. * * @param sh * @param msg * @param ctx * * @retval */ static bool _timeout_response(LSHandle *sh, LSMessage *message, void *ctx) { struct json_object *object; object = json_tokener_parse(LSMessageGetPayload(message)); if ( is_error(object) ) { goto cleanup; } struct json_object *retValObject; retValObject = json_object_object_get(object, "returnValue"); if (retValObject) { bool retVal = json_object_get_boolean(retValObject); if (!retVal) { SLEEPDLOG(LOG_ERR, "%s: Error not send timeout message because of %s", __FUNCTION__, LSMessageGetPayload(message)); } } cleanup: if (!is_error(object)) json_object_put(object); return true; } /** * @brief Send a message to the (uri, params) associated with the timeout. * * @param timeout */ static void _timeout_fire(_AlarmTimeout *timeout) { g_return_if_fail( timeout_db != NULL ); g_return_if_fail( timeout != NULL ); GString *payload = g_string_new(""); SLEEPDLOG(LOG_INFO, "%s (%s,%s => %s)", __FUNCTION__, timeout->app_id, timeout->key, timeout->uri); LSHandle *sh = NULL; bool retVal; LSError lserror; LSErrorInit(&lserror); sh = GetLunaServiceHandle(); /* Give system some time to process this timeout before * going to sleep again. The client can provide a specific * activity ID and duration. Otherwise we use a common default. */ if ( timeout->activity_id && strlen(timeout->activity_id) && 0 != timeout->activity_duration_ms ) { g_string_append_printf(payload, "{\"id\":\"%s\"," "\"duration_ms\":%d}", timeout->activity_id, timeout->activity_duration_ms); } else { g_string_append_printf(payload, "{\"id\":\"%s\"," "\"duration_ms\":%d}", DEFAULT_ACTIVITY_ID, TIMEOUT_KEEP_ALIVE_MS); } LSCallOneReply(sh, "palm://com.palm.power/com/palm/power/activityStart", payload->str, NULL, NULL, NULL, NULL); if (timeout->public_bus) { sh = LSPalmServiceGetPublicConnection(psh); } else { sh = LSPalmServiceGetPrivateConnection(psh); } // Call Luna-service bus with the uri/params. retVal = LSCallFromApplicationOneReply( sh, timeout->uri, timeout->params, timeout->app_id, _timeout_response, NULL, NULL, &lserror ); if (!retVal) { SLEEPDLOG(LOG_WARNING, "%s: Could not send (%s %s): %s", __FUNCTION__, timeout->uri, timeout->params, lserror.message); LSErrorFree (&lserror); } g_string_free(payload, TRUE); } bool _sql_step_finalize(const char *func, sqlite3_stmt *st) { int rc; rc = sqlite3_step( st ); if( rc != SQLITE_DONE ) { SLEEPDLOG(LOG_ERR,"%s(), sqlite3_step failed with %d\n", func, rc ); return false; } rc = sqlite3_finalize( st ); if( rc != SQLITE_OK ) { SLEEPDLOG(LOG_ERR,"%s(), sqlite3_finalize failed with %d\n", func, rc ); return false; } return true; } /** * @brief Adjusts all relative (non-calendar alarms) by the delta amount. * * @param delta */ static void _recalculate_timeouts(time_t delta) { g_debug(LOG_DOMAIN "%s(%ld)", __FUNCTION__, delta); if (delta) { int rc; char** table; int noRows, noCols; char* zErrMsg; int i; /* Find all relative (non-calendar alarms) */ const char *sqlquery = "SELECT t1key,expiry FROM AlarmTimeout WHERE calendar=0"; rc = sqlite3_get_table( timeout_db, sqlquery, &table, &noRows, &noCols, &zErrMsg ); if (SQLITE_OK != rc) { SLEEPDLOG( LOG_ERR, "%s() select... failed %s, rc=%d\n", __FUNCTION__, zErrMsg, rc ); sqlite3_free(zErrMsg); return; } int base = 0; for (i = 0; i < noRows; i++) { base += noCols; const char *table_id = table[base]; const char *expiry = table[base+1]; time_t new_expiry = atoi(expiry) + delta; /* Delete the timeout.*/ sqlite3_stmt* st = NULL; const char* tail; rc=sqlite3_prepare_v2( timeout_db, "UPDATE AlarmTimeout SET expiry=$1 WHERE t1key=$2", -1, &st, &tail); if( rc != SQLITE_OK ) { SLEEPDLOG(LOG_ERR, "%s() cannot update expiry", __FUNCTION__); } else { rc=sqlite3_bind_int( st, 1, new_expiry ); rc=sqlite3_bind_int( st, 2, atoi(table_id) ); _sql_step_finalize(__func__, st); } } sqlite3_free_table( table ); } } /** * @brief Trigger all expired timeouts. */ static void _expire_timeouts(void) { g_debug(LOG_DOMAIN "%s ", __FUNCTION__); int rc; char** table; int noRows, noCols; char* zErrMsg; int i; time_t now; int base; _AlarmTimeout timeout; now = rtc_wall_time(); /* Find all expired calendar timeouts */ char *sqlquery = g_strdup_printf( "SELECT t1key,app_id,key,uri,params,public_bus,activity_id,activity_duration_ms FROM AlarmTimeout " "WHERE expiry<=%ld ORDER BY expiry", now); rc = sqlite3_get_table( timeout_db, sqlquery, &table, &noRows, &noCols, &zErrMsg ); g_free(sqlquery); if (SQLITE_OK != rc) { SLEEPDLOG( LOG_ERR, "%s() select... failed %s, rc=%d\n", __FUNCTION__, zErrMsg, rc ); sqlite3_free(zErrMsg); return; } for (i = 0, base = 0; i < noRows; i++) { base += noCols; timeout.table_id = table[base]; timeout.app_id = table[base+1]; timeout.key = table[base+2]; timeout.uri = table[base+3]; timeout.params = table[base+4]; timeout.public_bus = atoi(table[base+5]); /* If we have an upgraded db where the activity_id and activity_duration_ms columns were added and there were existing rows then these two fields will return NULL. */ if (!table[base+6] || !table[base+7]) { g_debug(LOG_DOMAIN "%s: null activity_id or activity_duration_ms fields for \"%s\":\"%s\"", __func__, timeout.app_id, timeout.key); } timeout.activity_id = table[base+6]; // _timeout_fire can handle a null activity_id timeout.activity_duration_ms = table[base+7] ? atoi(table[base+7]) : 0; // _timeout_fire will fill-in the default duration /* Fire timeout */ _timeout_fire(&timeout); /* Delete the timeout.*/ sqlite3_stmt* st = NULL; const char* tail; rc=sqlite3_prepare_v2( timeout_db, "DELETE FROM AlarmTimeout WHERE t1key=$1",-1,&st,&tail); if( rc == SQLITE_OK ) { rc=sqlite3_bind_int( st, 1, atoi(timeout.table_id) ); _sql_step_finalize(__func__, st); } else { SLEEPDLOG(LOG_ERR, "%s prepare failed because of %d", __FUNCTION__, rc); } } sqlite3_free_table( table ); } bool timeout_get_next_wakeup(time_t *expiry, gchar ** app_id, gchar ** key) { g_return_val_if_fail(expiry != NULL, false); g_return_val_if_fail(app_id != NULL, false); g_return_val_if_fail(key != NULL, false); bool ret = false; char** table; int noRows, noCols; char* zErrMsg; int rc; rc = sqlite3_get_table( timeout_db, "SELECT expiry, app_id, key FROM AlarmTimeout " "WHERE wakeup=1 ORDER BY expiry LIMIT 1", &table, &noRows, &noCols, &zErrMsg ); if( rc != SQLITE_OK ) { g_critical("%s() failed select expiry %s, rc=%d", __func__, zErrMsg, rc ); sqlite3_free(zErrMsg ); return false; } if( noRows ) { *expiry = atol( table[ noCols ] ); *app_id = g_strdup(table[ noCols + 1 ]); *key = g_strdup(table[ noCols + 2 ]); ret = true; } sqlite3_free_table( table ); return ret; } /** * @brief Queues both a RTC alarm for wakeup timeouts * and a timer for non-wakeup timeouts. * * @param set_callback_fn * If set_callback_fn is set to true, the callback function _rtc_alarm_fired * will be triggered as soon as the alarm is fired. * It will be set to true as long as device is awake, and will be set to false when * the device suspends. * * The non-wakeup timeout timer is necessary so that * these timeouts do not wake the device when they fire. * Case 1: non-wakeup timeout expires when device is awake (trivial). * Case 2: non-wakeup timeout expires when device is asleep. * On resume, we will check to see if any alarms are expired and fire them. */ void _queue_next_timeout(bool set_callback_fn) { g_debug(LOG_DOMAIN "%s ", __FUNCTION__); int rc; char** table; int noRows, noCols; char* zErrMsg; time_t rtc_expiry = 0; time_t timer_expiry = 0; time_t now = rtc_wall_time(); // TODO wall clock? or RTC? g_return_if_fail(timeout_db != NULL); rc = sqlite3_get_table( timeout_db, "SELECT expiry FROM AlarmTimeout " "WHERE wakeup=1 ORDER BY expiry LIMIT 1", &table, &noRows, &noCols, &zErrMsg ); if( rc != SQLITE_OK ) { SLEEPDLOG( LOG_ERR, "%s() failed select expiry %s, rc=%d\n", __FUNCTION__, zErrMsg, rc ); sqlite3_free(zErrMsg ); return; } if( !noRows ) { nyx_system_set_alarm(GetNyxSystemDevice(),0,NULL,NULL); } else { rtc_expiry = atol( table[ noCols ]); if(set_callback_fn) nyx_system_set_alarm(GetNyxSystemDevice(),to_rtc(rtc_expiry),_rtc_alarm_fired,NULL); else nyx_system_set_alarm(GetNyxSystemDevice(),to_rtc(rtc_expiry),NULL,NULL); } sqlite3_free_table( table ); rc = sqlite3_get_table( timeout_db, "SELECT expiry FROM AlarmTimeout " "ORDER BY expiry LIMIT 1", &table, &noRows, &noCols, &zErrMsg ); if( rc != SQLITE_OK ) { SLEEPDLOG( LOG_ERR, "%s() failed select expiry %s, rc=%d\n", __FUNCTION__, zErrMsg, rc ); sqlite3_free(zErrMsg ); return; } if ( !noRows ) { g_timer_source_set_interval_seconds(sTimerCheck, 60*60, true); } else { timer_expiry = atol( table[ noCols ] ); long wakeInSeconds = timer_expiry - now; if( wakeInSeconds < 0 ) { wakeInSeconds = 0; } g_timer_source_set_interval_seconds(sTimerCheck, wakeInSeconds, true); } sqlite3_free_table( table ); } /** * @brief Trigger expired timeouts, and queue up the next one. */ void _update_timeouts(void) { g_debug(LOG_DOMAIN "%s ", __FUNCTION__); time_t delta = 0; // prevent compile error "may be used uninitialized" when optimization is cranked up update_rtc(&delta); if (delta) { _recalculate_timeouts(delta); void update_alarms_delta(time_t delta); update_alarms_delta(delta); } _expire_timeouts(); _queue_next_timeout(true); } void _timeout_create(_AlarmTimeout *timeout, const char *app_id, const char *key, const char *uri, const char *params, bool public_bus, bool wakeup, const char *activity_id, int activity_duration_ms, bool calendar, time_t expiry) { g_debug(LOG_DOMAIN "%s ", __FUNCTION__); g_return_if_fail(timeout != NULL); timeout->app_id = app_id; timeout->key = key; timeout->uri = uri; timeout->params = params; timeout->public_bus = public_bus; timeout->wakeup = wakeup; timeout->activity_id = activity_id; timeout->activity_duration_ms = activity_duration_ms; timeout->calendar = calendar; timeout->expiry = expiry; } bool _timeout_set(_AlarmTimeout *timeout) { g_debug(LOG_DOMAIN "%s ", __FUNCTION__); int rc; sqlite3_stmt* st = NULL; const char* tail; g_return_val_if_fail(timeout != NULL, false); /* Delete (app_id,key,public_bus) if it already exists */ _timeout_delete(timeout->app_id, timeout->key, timeout->public_bus); rc = sqlite3_prepare_v2( timeout_db, "INSERT INTO AlarmTimeout (app_id,key,uri,params,public_bus,wakeup,calendar,expiry,activity_id,activity_duration_ms) " "VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10 )", -1, &st, &tail ); if( rc != SQLITE_OK ) { SLEEPDLOG(LOG_ERR,"Insert into AlarmTimeout failed with %d\n", rc ); return false; } sqlite3_bind_text( st, 1, timeout->app_id, timeout->app_id ? strlen(timeout->app_id) : -1, SQLITE_STATIC ); sqlite3_bind_text( st, 2, timeout->key, strlen(timeout->key), SQLITE_STATIC ); sqlite3_bind_text( st, 3, timeout->uri, strlen(timeout->uri), SQLITE_STATIC ); sqlite3_bind_text( st, 4, timeout->params, strlen(timeout->params), SQLITE_STATIC ); sqlite3_bind_int( st, 5, timeout->public_bus ); sqlite3_bind_int( st, 6, timeout->wakeup ); sqlite3_bind_int( st, 7, timeout->calendar ); sqlite3_bind_int( st, 8, timeout->expiry ); sqlite3_bind_text( st, 9, timeout->activity_id, strlen(timeout->activity_id), SQLITE_STATIC ); sqlite3_bind_int( st, 10, timeout->activity_duration_ms ); if (!_sql_step_finalize(__func__, st)) { return false; } _update_timeouts(); return true; } void _free_timeout_fields(_AlarmTimeoutNonConst *timeout) { g_free(timeout->table_id); g_free(timeout->app_id); g_free(timeout->key); g_free(timeout->uri); g_free(timeout->params); g_free(timeout->activity_id); memset(timeout, 0, sizeof(*timeout)); } /** * @brief Read an existing timeout from the database. * * @param timeout * @param app_id * @param key * @param public_bus * * @retval true if at least one row matched * * Call _free_timeout_fields() with the timeout when done. * */ bool _timeout_read(_AlarmTimeoutNonConst *timeout, const char *app_id, const char *key, bool public_bus) { bool ret = false; int rc; char** table; int noRows, noCols; char* zErrMsg; if (!app_id) { app_id = ""; } if (!key) { key = ""; } g_debug(LOG_DOMAIN "%s: SELECT (\"%s\", \"%s\", %s)", __FUNCTION__, app_id, key, public_bus ? "public" : "private"); char *sqlquery = g_strdup_printf( "SELECT t1key,app_id,key,uri,params,public_bus,wakeup,calendar,expiry,activity_id,activity_duration_ms FROM AlarmTimeout " "WHERE app_id=\"%s\" AND key=\"%s\" AND public_bus=%d", app_id, key, public_bus); rc = sqlite3_get_table( timeout_db, sqlquery, &table, &noRows, &noCols, &zErrMsg ); g_free(sqlquery); if( rc != SQLITE_OK ) { SLEEPDLOG( LOG_ERR, "%s() failed select on %s, rc=%d\n", __FUNCTION__, zErrMsg, rc ); sqlite3_free(zErrMsg ); goto exit; } if( noRows ) { if (noRows > 1) { g_warning(LOG_DOMAIN "%s: ERROR, %d rows for (\"%s\", \"%s\", %s)", __func__, noRows, app_id, key, public_bus ? "public" : "private"); } timeout->table_id = g_strdup( table[ noCols ]); timeout->app_id = g_strdup( table[ noCols + 1 ]); timeout->key = g_strdup( table[ noCols + 2 ]); timeout->uri = g_strdup( table[ noCols + 3 ]); timeout->params = g_strdup( table[ noCols + 4 ]); timeout->public_bus = atoi( table[ noCols + 5 ]); timeout->wakeup = atoi( table[ noCols + 6 ]); timeout->calendar = atoi( table[ noCols + 7 ]); timeout->expiry = atol( table[ noCols + 8 ]); // The two "activity" fields could be null if this is an // old record where the new columns were inserted. timeout->activity_id = table[noCols + 9] ? g_strdup(table[noCols + 9]) : g_strdup(DEFAULT_ACTIVITY_ID); timeout->activity_duration_ms = table[noCols + 10] ? atoi(table[noCols + 10]) : TIMEOUT_KEEP_ALIVE_MS; ret = true; } sqlite3_free_table( table ); exit: return ret; } // _timeout_read /** * @brief Delete an existing timeout. * * @param app_id * @param key * @param public_bus * * @retval */ bool _timeout_delete(const char *app_id, const char *key, bool public_bus) { sqlite3_stmt* st = NULL; const char* tail; int rc; if (!app_id) { app_id = ""; } if (!key) { key = ""; } g_debug(LOG_DOMAIN "%s (\"%s\", \"%s\", %s)", __FUNCTION__, app_id, key, public_bus ? "public" : "private"); /* Delete the matching timeout.*/ rc=sqlite3_prepare_v2( timeout_db, "DELETE FROM AlarmTimeout WHERE " "app_id=$1 AND key=$2 AND public_bus=$3",-1,&st,&tail); if( rc != SQLITE_OK ) { SLEEPDLOG(LOG_DEBUG, "Could not remove AlarmTimeout, failed with %d\n", rc ); return false; } sqlite3_bind_text( st, 1, app_id, app_id ? strlen(app_id) : -1, SQLITE_STATIC ); sqlite3_bind_text( st, 2, key, key ? strlen(key) : -1, SQLITE_STATIC ); sqlite3_bind_int( st, 3, public_bus ); return _sql_step_finalize(__func__, st); } // _timeout_delete /** * @brief Clear an existing timeout & reschedule the next. * * @param app_id * @param key */ bool _timeout_clear(const char *app_id, const char *key, bool public_bus) { bool retVal; retVal = _timeout_delete(app_id, key, public_bus); if (retVal) { _update_timeouts(); } return retVal; } /** * @brief To help us track down NOV-80968, where rtc dies... * * @param data * * @retval */ static gboolean _rtc_check(gpointer data) { static long int sLastRTCTime = 0; static long int sNumTimes = 0; long int this_time = 0; nyx_system_query_rtc_time(GetNyxSystemDevice(),(time_t *)&this_time); if (this_time == sLastRTCTime) { sNumTimes++; g_critical("%s: RTC appears not to be ticking! nyx_query_time(NULL) returned %ld, number of times showing same RTC time : %ld", __func__, this_time, sNumTimes); } else { sNumTimes = 0; } sLastRTCTime=this_time; return TRUE; } /** * @brief Triggered for non-wakeup source. * * @param data * * @retval */ static gboolean _timer_check(gpointer data) { g_debug(LOG_DOMAIN "%s ", __FUNCTION__); _update_timeouts(); return TRUE; } static char * _get_appid_dup(const char *app_instance_id) { if (!app_instance_id) { return NULL; } char *s = strstr(app_instance_id, " "); if (s) { int len = s - app_instance_id; return g_strndup(app_instance_id, len); } else { return g_strdup(app_instance_id); } } static bool _timeout_exists(const char *app_id, const char *key, bool public_bus) { _AlarmTimeoutNonConst timeout; bool ret = _timeout_read(&timeout, app_id, key, public_bus); if (ret) { _print_timeout(LOG_DOMAIN "timeout exists", app_id, key, public_bus, timeout.expiry); _free_timeout_fields(&timeout); } return ret; } /** * @brief Handle a timeout/set message and add a new power timeout. * Relative timeouts can be set by passing the "in" parameter. * Absolute timeouts can be set by passing the "at" parameter. * * @param sh * @param message * @param ctx * * @retval */ static bool _alarm_timeout_set(LSHandle *sh, LSMessage *message, void *ctx) { g_debug(LOG_DOMAIN "%s ", __FUNCTION__); bool retVal; const char *app_instance_id; const char *key; const char *at; const char *in; const char *uri; const char *params; bool wakeup; const char *activity_id; int activity_duration_ms; bool calendar; time_t expiry; _AlarmTimeout timeout; char *app_id = NULL; bool public_bus; AlarmTimeoutType timeout_type; struct json_object *object; struct json_object *duration_object; bool duration_provided; // for optional "keep_existing" boolean argument bool keep_existing_provided; bool keep_existing = false; struct json_object *keep_existing_object; object = json_tokener_parse(LSMessageGetPayload(message)); if ( is_error(object) ) { goto malformed_json; } app_instance_id = LSMessageGetApplicationID(message); key = json_object_get_string(json_object_object_get(object, "key")); at = json_object_get_string(json_object_object_get(object, "at")); in = json_object_get_string(json_object_object_get(object, "in")); uri = json_object_get_string(json_object_object_get(object, "uri")); params = json_object_get_string(json_object_object_get(object, "params")); wakeup = json_object_get_boolean(json_object_object_get(object, "wakeup")); if (!key || !strlen(key) || !uri || !strlen(uri) || !params || !strlen(params)) goto invalid_json; if (!app_instance_id) app_instance_id = ""; // optional arguments to allow caller to specify activity name and duration activity_id = json_object_get_string(json_object_object_get(object, "activity_id")); duration_provided = json_object_object_get_ex(object, "activity_duration_ms", &duration_object); if (activity_id) { if (!duration_provided) { g_debug(LOG_DOMAIN "activity_id w/o activity_duration_ms"); goto invalid_json; } activity_duration_ms = json_object_get_int(duration_object); if (activity_duration_ms < ACTIVITY_DURATION_MS_MINIMUM) { goto activity_duration_too_short; } } else { if (duration_provided) { g_debug(LOG_DOMAIN "activity_duration_ms w/o activity_id"); goto invalid_json; } activity_id = DEFAULT_ACTIVITY_ID; activity_duration_ms = TIMEOUT_KEEP_ALIVE_MS; } // optional argument which tells us to keep a pre-existing alarm with the same key keep_existing_provided = json_object_object_get_ex(object, "keep_existing", &keep_existing_object); if (keep_existing_provided) { keep_existing = json_object_get_boolean(keep_existing_object); } app_id = _get_appid_dup(app_instance_id); if (at) { SLEEPDLOG(LOG_INFO, "%s (%s,%s,%s) at %s", __FUNCTION__, app_id, key, wakeup ? "wakeup" : "_", at); timeout_type = AlarmTimeoutCalendar; int mm, dd, yyyy; int HH, MM, SS; int ret = sscanf(at, "%02d/%02d/%04d %02d:%02d:%02d", &mm, &dd, &yyyy, &HH, &MM, &SS); if (ret != 6) goto invalid_json; int valid_days[12]= {31,28,31,30,31,30,31,31,30,31,30,31}; int valid_leapyr_days[12]= {31,29,31,30,31,30,31,31,30,31,30,31}; if(yyyy % 4 != 0) { if ((mm < 0 || mm > 12) || (dd < 0 || dd > valid_days[mm-1])) // Not a leap year goto invalid_json; } else if ((mm < 0 || mm > 12) || (dd < 0 || dd > valid_leapyr_days[mm-1])) // Leap year goto invalid_json; struct tm gm_time; memset(&gm_time, 0, sizeof(struct tm)); gm_time.tm_hour = HH; gm_time.tm_min = MM; gm_time.tm_sec = SS; gm_time.tm_mon = mm - 1; // month-of-year [0-11] gm_time.tm_mday = dd; // day-of-month [1-31] gm_time.tm_year = yyyy - 1900; /* timegm converts time(GMT) -> seconds since epoch */ expiry = timegm(&gm_time); if (expiry < 0) expiry = 0; } else if (in) { SLEEPDLOG(LOG_INFO, "%s (%s,%s,%s) in %s", __FUNCTION__, app_id, key, wakeup ? "wakeup" : "_", in); timeout_type = AlarmTimeoutRelative; int HH, MM, SS; if (sscanf(in, "%02d:%02d:%02d", &HH, &MM, &SS) != 3) goto invalid_json; else if(HH < 0 || HH > 24 || MM < 0 || MM > 59 || SS < 0 || SS > 59) goto invalid_json; int delta = SS + MM*60 + HH*60*60; #if 0 if (delta < TIMEOUT_MINIMUM_SEC) { goto timeout_relative_too_short; } #endif if (delta < TIMEOUT_MINIMUM_HANDSET_SEC) { SLEEPDLOG( LOG_WARNING, "%s: alarm timeout interval of %d seconds is below limit of " "%d seconds enforced on actual handsets", __FUNCTION__, delta, TIMEOUT_MINIMUM_HANDSET_SEC ); } expiry = rtc_wall_time() + delta; } else { goto invalid_json; } public_bus = LSMessageIsPublic(psh, message); calendar = (timeout_type == AlarmTimeoutCalendar); bool kept_existing = false; char *payload; if (keep_existing && _timeout_exists(app_id, key, public_bus)) { kept_existing = true; SLEEPDLOG(LOG_DEBUG, "%s: keeping existing timeout for (\"%s\", \"%s\", %s)", __FUNCTION__, app_id, key, public_bus ? "public" : "private"); } else { _timeout_create(&timeout, app_id, key, uri, params, public_bus, wakeup, activity_id, activity_duration_ms, calendar, expiry); retVal = _timeout_set(&timeout); if (!retVal) goto unknown_error; } char *escaped_key = g_strescape(key, NULL); if (keep_existing_provided) { payload = g_strdup_printf( "{\"returnValue\":true,\"key\":\"%s\",\"kept_existing\":%s}", escaped_key, kept_existing ? "true" : "false"); } else { payload = g_strdup_printf( "{\"returnValue\":true,\"key\":\"%s\"}", escaped_key); } retVal = LSMessageReply(sh, message, payload, NULL); if (!retVal) { SLEEPDLOG(LOG_WARNING, "%s could not send reply.", __FUNCTION__); } g_free(payload); g_free(escaped_key); goto cleanup; #if 0 timeout_relative_too_short: retVal = LSMessageReply(sh, message, "{\"returnValue\":false," "\"errorText\":\"Timeout value for 'in' less than " TIMEOUT_MINIMUM_AS_TEXT ".\"}", NULL); if (!retVal) { SLEEPDLOG(LOG_WARNING, "%s could not send reply <timeout_too_short>.", __FUNCTION__); } goto cleanup; #endif activity_duration_too_short: retVal = LSMessageReply(sh, message, "{\"returnValue\":false," "\"errorText\":\"activity_duration_ms less than " ACTIVITY_DURATION_MS_MINIMUM_AS_TEXT ".\"}", NULL); if (!retVal) { SLEEPDLOG(LOG_WARNING, "%s could not send reply <activity duration too short>.", __FUNCTION__); } goto cleanup; unknown_error: retVal = LSMessageReply(sh, message, "{\"returnValue\":false," "\"errorText\":\"Could not set timeout.\"}", NULL); if (!retVal) { SLEEPDLOG(LOG_WARNING, "%s could not send reply <unknown error>.", __FUNCTION__); } goto cleanup; invalid_json: retVal = LSMessageReply(sh, message, "{\"returnValue\":false," "\"errorText\":\"Invalid format for 'timeout/set'.\"}", NULL); if (!retVal) { SLEEPDLOG(LOG_WARNING, "%s could not send reply <invalid format>.", __FUNCTION__); } goto cleanup; malformed_json: LSMessageReplyErrorBadJSON(sh, message); goto cleanup; cleanup: if (!is_error(object)) json_object_put(object); g_free(app_id); return true; } /** * @brief Handle a timeout/clear message and delete a timeout by its key. * * @param sh * @param message * @param ctx * * @retval */ static bool _alarm_timeout_clear(LSHandle *sh, LSMessage *message, void *ctx) { bool retVal; struct json_object *object; const char *app_instance_id; const char *key; bool public_bus; LSError lserror; LSErrorInit(&lserror); char *app_id = NULL; object = json_tokener_parse(LSMessageGetPayload(message)); if ( is_error(object) ) { goto malformed_json; } app_instance_id = LSMessageGetApplicationID(message); key = json_object_get_string(json_object_object_get(object, "key")); public_bus = LSMessageIsPublic(psh, message); if (!key) { goto invalid_json; } if (!app_instance_id) app_instance_id = ""; app_id = _get_appid_dup(app_instance_id); SLEEPDLOG(LOG_INFO, "%s (%s,%s,%s)", __FUNCTION__, app_id, key, public_bus ? "public" : "private"); retVal = _timeout_clear(app_id, key, public_bus); if (!retVal) { retVal = LSMessageReply(sh, message, "{\"returnValue\":false,\"errorText\":\"Could not find key.\"}", &lserror); if (!retVal) { LSErrorPrint(&lserror, stderr); } } else { char *escaped_key = g_strescape(key, NULL); char *payload = g_strdup_printf( "{\"returnValue\":true,\"key\":\"%s\"}", escaped_key); retVal = LSMessageReply(sh, message, payload, &lserror); if (!retVal) { LSErrorPrint(&lserror, stderr); } g_free(payload); g_free(escaped_key); } goto cleanup; invalid_json: LSMessageReplyErrorInvalidParams(sh, message); goto cleanup; malformed_json: LSMessageReplyErrorBadJSON(sh, message); goto cleanup; cleanup: if (!is_error(object)) json_object_put(object); g_free(app_id); LSErrorFree(&lserror); return true; } static LSMethod timeout_methods[] = { { "set", _alarm_timeout_set }, { "clear", _alarm_timeout_clear }, { }, }; /** * @brief When we wake, we should check to see if any non-wakeup timeouts * have expired. * * @param sh * @param message * @param ctx * * @retval */ static bool _resume_callback(LSHandle *sh, LSMessage *message, void *ctx) { _update_timeouts(); return true; } static int _alarms_timeout_init(void) { bool retVal; gchar* timeout_db_name = g_build_filename(gSleepConfig.preference_dir, TIMEOUT_DATABASE_NAME, NULL); if (gSleepConfig.disable_rtc_alarms) { SLEEPDLOG(LOG_INFO, "%s: RTC alarms disabled", __FUNCTION__); return 0; } gchar* timeout_db_path = g_path_get_dirname(timeout_db_name); g_mkdir_with_parents(timeout_db_path, S_IRWXU); g_free(timeout_db_path); retVal = smart_sql_open( timeout_db_name, &timeout_db ); if( !retVal ) { SLEEPDLOG(LOG_ERR,"Failed to open database %s\n", timeout_db_name ); goto error; } g_free(timeout_db_name); retVal = smart_sql_exec( timeout_db, kSysTimeoutDatabaseCreateSchema ); if( !retVal ) { SLEEPDLOG(LOG_ERR, "%s could not create database\n", __FUNCTION__); goto error; } retVal = smart_sql_exec( timeout_db, kSysTimeoutDatabaseCreateIndex); if( !retVal ) { SLEEPDLOG(LOG_ERR, "%s could not create index\n", __FUNCTION__); goto error; } /* Set up luna service */ psh = GetPalmService(); LSError lserror; LSErrorInit(&lserror); if (!LSPalmServiceRegisterCategory(psh, "/timeout", timeout_methods /*public*/, NULL /*private*/, NULL, NULL, &lserror)) { SLEEPDLOG(LOG_ERR, "%s could not register category: %s", __FUNCTION__, lserror.message); LSErrorFree(&lserror); goto error; } retVal = LSCall(LSPalmServiceGetPrivateConnection(psh), "palm://com.palm.bus/signal/addmatch", "{\"category\":\"/com/palm/power\",\"method\":\"resume\"}", _resume_callback, NULL, NULL, &lserror); if (!retVal) { SLEEPDLOG(LOG_ERR, "%s could not register for suspend resume signal: %s", __FUNCTION__, lserror.message); LSErrorFree(&lserror); goto error; } retVal = update_rtc(NULL); if (!retVal) { SLEEPDLOG(LOG_ERR, "%s could not get wall-rtc offset.", __FUNCTION__); } else { SLEEPDLOG(LOG_INFO, "Initial WALL-RTC = %ld", rtc_to_wall); } GTimerSource *timer_rtc_check = g_timer_source_new_seconds(5*60); g_source_set_callback((GSource*)timer_rtc_check, (GSourceFunc)_rtc_check, NULL, NULL); g_source_attach((GSource*)timer_rtc_check, GetMainLoopContext()); sTimerCheck = g_timer_source_new_seconds(60*60); g_source_set_callback((GSource*)sTimerCheck, (GSourceFunc)_timer_check, NULL, NULL); g_source_attach((GSource*)sTimerCheck, GetMainLoopContext()); /** To support the deprecated interface */ int alarm_init(void); alarm_init(); /*************/ _update_timeouts(); return 0; error: return -1; } INIT_FUNC(INIT_FUNC_END, _alarms_timeout_init); /* @} END OF NewInterface */
210
./sleepd/src/alarms/smartsql.c
/* @@@LICENSE * * Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ /** * @file smartsql.c * * @brief Convenience functions to interact with the rtc driver. * */ #include <sqlite3.h> #include <stdbool.h> #include <string.h> #include <glib.h> #include <luna-service2/lunaservice.h> #include "logging.h" #define LOG_DOMAIN "POWERD-SMARTSQL: " /** * @addtogroup NewInterface * @{ */ static bool _check_integrity(sqlite3 *db) { const char *cmd = "PRAGMA integrity_check;"; int rc; sqlite3_stmt *stmt; const char* tail; rc=sqlite3_prepare_v2( db, cmd,-1,&stmt,&tail); if (!stmt) goto fail; rc = sqlite3_step(stmt); if (rc == SQLITE_OK) goto success; if (rc != SQLITE_ROW) goto fail; int columns = sqlite3_data_count(stmt); if (columns != 1) goto fail; const char *column_text = (const char*)sqlite3_column_text(stmt, 0); // A successful, no-error integrity check will be "ok" - all other strings imply failure if (strcmp(column_text,"ok") == 0) goto success; goto fail; success: sqlite3_finalize(stmt); return true; fail: sqlite3_finalize(stmt); fprintf(stderr, "integrity check failed"); return false; } bool smart_sql_exec(sqlite3 *db, const char *cmd) { int rc; sqlite3_stmt *stmt; const char *tail; rc = sqlite3_prepare_v2( db, cmd, -1, &stmt, &tail); if (!stmt) { g_warning("%s: sqlite3_prepare error %d for cmd \"%s\"", __FUNCTION__, rc, cmd); return false; } rc = sqlite3_step(stmt); if (rc != SQLITE_DONE) { g_warning("%s: sqlite3_step error %d for cmd \"%s\"", __FUNCTION__, rc, cmd); sqlite3_finalize(stmt); return false; } sqlite3_finalize(stmt); return true; } static sqlite3 * _open(const char *path) { sqlite3 *db; int rc; bool retVal; rc = sqlite3_open(path, &db); if (rc != SQLITE_OK) { return NULL; } retVal = smart_sql_exec(db, "PRAGMA temp_store = MEMORY;"); if (!retVal) { return NULL; } // TODO might want to enable sqlite3_palm_extension.so for // perf reasons. // SyncOff retVal = smart_sql_exec(db, "PRAGMA synchronous = 0"); if (!retVal) { fprintf(stderr, "Could not set syncoff on %s\n", path); } return db; } static void _close(sqlite3 *db) { sqlite3_close(db); } bool smart_sql_open(const char *path, sqlite3 **ret_db) { bool retVal; sqlite3 *db =_open(path); if (!db) return false; retVal = _check_integrity(db); if (!retVal) { SLEEPDLOG(LOG_ERR, "%s: %s corrupted... clearing.", __FUNCTION__, path); _close(db); char *journal = g_strdup_printf("%s-journal", path); remove(journal); remove(path); g_free(journal); db = _open(path); if (!db) return false; } *ret_db = db; return true; } void smart_sql_close(sqlite3 *db) { _close(db); } /* @} END OF NewInterface */
211
./sleepd/src/alarms/alarm.c
/* @@@LICENSE * * Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ /** * @file alarm.c * * @brief Old interface (deprecated) to add/clear alarms using RTC. * */ #include <glib.h> #include <stdbool.h> #include <time.h> #include <string.h> #include <luna-service2/lunaservice.h> #include <cjson/json.h> #include <libxml/xmlmemory.h> #include <libxml/parser.h> #include "lunaservice_utils.h" #include "main.h" #include "logging.h" #include "config.h" #include "timeout_alarm.h" #define LOG_DOMAIN "ALARM: " /** * @defgroup RTCAlarms RTC alarms * @ingroup Sleepd * @brief Alarms for RTC wakeup. */ /** * @defgroup OldInterface Old Interface * @ingroup RTCAlarms * @brief Old (deprecated) interface to add/clear RTC alarms */ /** * @addtogroup OldInterface * @{ */ /** * @brief A single alarm. */ typedef struct { int id; time_t expiry; /*< Number of seconds since 1/1/1970 epoch */ bool calendar; /*< If true, Alarm represents a calendar time. * (i.e. Jan 5, 2009, 10:00am). * * If false, Alarm is X seconds in future * (i.e. T+X). */ char *key; /*< alarm key */ char *serviceName; /*< serviceName to notify */ char *applicationName; /*< app source of alarm. */ LSMessage *message; /*< Message to reply to. */ } _Alarm; /** * @brief Alarm queue. */ typedef struct { GSequence *alarms; uint32_t seq_id; // points to the next available id char *alarm_db; } _AlarmQueue; _AlarmQueue *gAlarmQueue = NULL; static bool alarm_queue_add(uint32_t id, const char *key, bool calendar, time_t expiry, const char *serviceName, const char *applicationName, bool subscribe, LSMessage *message); bool alarm_queue_new(const char *key, bool calendar, time_t expiry, const char *serviceName, const char *applicationName, bool subscribe, LSMessage *message, int *ret_id); static bool alarm_write_db(void); static void notify_alarms(void); static void update_alarms(void); /** * @brief Set alarm to fire in a fixed time in the future. * * luna://com.palm.sleep/time/alarmAdd * * Set alarm to expire in T+5hrs. Response will be sent * as a call to "luna://com.palm.X/alarm". * * {"key":"calendarAlarm", "serviceName":"com.palm.X", * "relative_time":"05:00:00"} * * Subscribing indicates that you want the alarm message as a response to * the current call. * * {"subscribe":true, "key":"calendarAlarm", "serviceName":"com.palm.X", * "relative_time":"05:00:00"} * * Alarm is sucessfully registered. * {"alarmId":1} * * Alarm failed to be registered: * * {"returnValue":false, ...} * {"returnValue":false,"serivceName":"com.palm.sleep", * "errorText":"com.palm.sleep is not running"} * * @param sh * @param message * @param ctx * * @retval */ static bool alarmAdd(LSHandle *sh, LSMessage *message, void *ctx) { time_t alarm_time = 0; int rel_hour, rel_min, rel_sec; const char *key, *serviceName, *applicationName, *rel_time; bool subscribe; struct json_object *object; int alarm_id; bool retVal = false; LSError lserror; LSErrorInit(&lserror); time_t rtctime = 0; object = json_tokener_parse(LSMessageGetPayload(message)); if ( is_error(object) ) { goto malformed_json; } SLEEPDLOG(LOG_DEBUG, "%s: %s", __FUNCTION__, LSMessageGetPayload(message)); serviceName = json_object_get_string( json_object_object_get(object, "serviceName")); applicationName = LSMessageGetApplicationID(message); key = json_object_get_string(json_object_object_get(object, "key")); rel_time = json_object_get_string( json_object_object_get(object, "relative_time")); if (!rel_time) { goto invalid_format; } if (sscanf(rel_time, "%02d:%02d:%02d", &rel_hour, &rel_min, &rel_sec) != 3) { goto invalid_format; } nyx_system_query_rtc_time(GetNyxSystemDevice(),&rtctime); SLEEPDLOG(LOG_INFO, "%s: (%s %s %s) in %s (rtc %ld)", __FUNCTION__, serviceName, applicationName, key, rel_time, rtctime); struct json_object *subscribe_json = json_object_object_get(object, "subscribe"); subscribe = json_object_get_boolean(subscribe_json); alarm_time = rtc_wall_time(); alarm_time += rel_sec; alarm_time += rel_min * 60; alarm_time += rel_hour * 60 * 60; retVal = alarm_queue_new(key, false, alarm_time, serviceName, applicationName, subscribe, message, &alarm_id); if (!retVal) goto error; /***************** * Use new timeout API */ { char *timeout_key = g_strdup_printf("%s-%d", key, alarm_id); _AlarmTimeout timeout; _timeout_create(&timeout, "com.palm.sleep", timeout_key, "luna://com.palm.sleep/time/internalAlarmFired", "{}", false /*public bus*/, true /*wakeup*/, "" /*activity_id*/, 0 /*activity_duration_ms*/, false /*calendar*/, alarm_time); retVal = _timeout_set(&timeout); g_free(timeout_key); if (!retVal) goto error; } /*****************/ /* Send alarm id of sucessful alarm add. */ GString *reply = g_string_sized_new(512); g_string_append_printf(reply, "{\"alarmId\":%d", alarm_id); if (subscribe_json) { g_string_append_printf(reply, ",\"subscribed\":%s", subscribe ? "true":"false"); } g_string_append_printf(reply, "}"); retVal = LSMessageReply(sh, message, reply->str, &lserror); g_string_free(reply, TRUE); goto cleanup; error: retVal = LSMessageReply(sh, message, "{\"returnValue\":false," "\"errorText\":\"Unknown error\"}", &lserror); goto cleanup; invalid_format: retVal = LSMessageReply(sh, message, "{\"returnValue\":false," "\"errorText\":\"Invalid format for alarm time.\"}", &lserror); goto cleanup; malformed_json: LSMessageReplyErrorBadJSON(sh, message); goto cleanup; cleanup: if (!is_error(object)) json_object_put(object); if (!retVal && LSErrorIsSet(&lserror)) { LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } return true; } /** * @brief Set a calendar event. * * luna://com.palm.sleep/time/alarmAddCalendar * * Message: * Set alarm to expire at a fixed calendar time in UTC. Response will be sent * as a call to "luna://com.palm.X/alarm". * * {"key":"calendarAlarm", "serviceName":"com.palm.X", * "date":"01-02-2009", "time":"13:40:03"} * * Subscribing indicates that you want the alarm message as a response to * the current call. * * {"subscribe":true, "key":"calendarAlarm", "serviceName":"com.palm.X", * "date":"01-02-2009", "time":"13:40:03"} * * Response: * * Alarm is sucessfully registered for calendar date * {"alarmId":1} * * Subscribe case: * {"alarmId":1,"subscribed":true} * {"alarmId":1,"fired":true} * * Alarm failed to be registered: * * {"returnValue":false, ...} * {"returnValue":false,"serivceName":"com.palm.sleep", * "errorText":"com.palm.sleep is not running"} * * @param sh * @param message * @param ctx * * @retval */ static bool alarmAddCalendar(LSHandle *sh, LSMessage *message, void *ctx) { int alarm_id; struct json_object *object; const char *key, *serviceName, *applicationName, *cal_date, *cal_time; struct tm gm_time; bool subscribe; bool retVal = false; time_t alarm_time = 0; LSError lserror; LSErrorInit(&lserror); object = json_tokener_parse(LSMessageGetPayload(message)); if ( is_error(object) ) { goto malformed_json; } SLEEPDLOG(LOG_DEBUG, "%s: %s", __FUNCTION__, LSMessageGetPayload(message)); serviceName = json_object_get_string( json_object_object_get(object, "serviceName")); applicationName = LSMessageGetApplicationID(message); key = json_object_get_string(json_object_object_get(object, "key")); cal_date = json_object_get_string( json_object_object_get(object, "date")); cal_time = json_object_get_string( json_object_object_get(object, "time")); if (!cal_date || !cal_time) { goto invalid_format; } int hour, min, sec; int month, day, year; if (sscanf(cal_time, "%02d:%02d:%02d", &hour, &min, &sec) != 3) { goto invalid_format; } if (sscanf(cal_date, "%02d-%02d-%04d", &month, &day, &year) != 3) { goto invalid_format; } if (hour < 0 || hour > 24 || min < 0 || min > 60 || sec < 0 || sec > 60 || month < 1 || month > 12 || day < 1 || day > 31 || year < 0) { goto invalid_format; } SLEEPDLOG(LOG_INFO, "%s: (%s %s %s) at %s %s", __FUNCTION__, serviceName, applicationName, key, cal_date, cal_time); struct json_object *subscribe_json = json_object_object_get(object, "subscribe"); subscribe = json_object_get_boolean(subscribe_json); memset(&gm_time, 0, sizeof(struct tm)); gm_time.tm_hour = hour; gm_time.tm_min = min; gm_time.tm_sec = sec; gm_time.tm_mon = month - 1; // month-of-year [0-11] gm_time.tm_mday = day; // day-of-month [1-31] gm_time.tm_year = year - 1900; /* timegm converts time(GMT) -> seconds since epoch */ alarm_time = timegm(&gm_time); if (alarm_time < 0) { goto invalid_format; } retVal = alarm_queue_new(key, true, alarm_time, serviceName, applicationName, subscribe, message, &alarm_id); if (!retVal) goto error; /***************** * Use new timeout API */ { char *timeout_key = g_strdup_printf("%s-%d", key, alarm_id); _AlarmTimeout timeout; _timeout_create(&timeout, "com.palm.sleep", timeout_key, "luna://com.palm.sleep/time/internalAlarmFired", "{}", false /*public bus*/, true /*wakeup*/, "" /*activity_id*/, 0 /*activity_duration_ms*/, true /*calendar*/, alarm_time); retVal = _timeout_set(&timeout); g_free(timeout_key); if (!retVal) goto error; } /*****************/ /* Send alarm id of sucessful alarm add. */ GString *reply = g_string_sized_new(512); g_string_append_printf(reply, "{\"alarmId\":%d", alarm_id); if (subscribe_json) { g_string_append_printf(reply, ",\"subscribed\":%s", subscribe ? "true":"false"); } g_string_append_printf(reply, "}"); retVal = LSMessageReply(sh, message, reply->str, &lserror); g_string_free(reply, TRUE); goto cleanup; error: retVal = LSMessageReply(sh, message, "{\"returnValue\":false," "\"errorText\":\"Unknown error\"}", &lserror); goto cleanup; invalid_format: retVal = LSMessageReply(sh, message, "{\"returnValue\":false," "\"errorText\":\"Invalid format for alarm time.\"}", &lserror); goto cleanup; malformed_json: LSMessageReplyErrorBadJSON(sh, message); goto cleanup; cleanup: if (!is_error(object)) json_object_put(object); if (!retVal && LSErrorIsSet(&lserror)) { LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } return true; } /** * @brief Query for set of alarms identified by 'serviceName' & 'key'. * * {"serviceName":"com.palm.X", "key":"calendarAlarm"} * * Response: * * {"alarms": * [{"alarmId":1,"key":"calendarAlarm"}, * {"alarmId":2,"key":"calendarAlarm"}, * ]} * * @param sh * @param message * @param ctx * * @retval */ static bool alarmQuery(LSHandle *sh, LSMessage *message, void *ctx) { bool retVal; const char *serviceName, *key; struct json_object *object; GString *alarm_str = NULL; GString *buf = NULL; object = json_tokener_parse(LSMessageGetPayload(message)); if ( is_error(object) ) { goto malformed_json; } serviceName = json_object_get_string( json_object_object_get(object, "serviceName")); key = json_object_get_string( json_object_object_get(object, "key")); if (!serviceName || !key) goto invalid_format; alarm_str = g_string_sized_new(512); if (!alarm_str) goto cleanup; bool first = true; GSequenceIter *iter = g_sequence_get_begin_iter(gAlarmQueue->alarms); while (!g_sequence_iter_is_end (iter)) { _Alarm *alarm = (_Alarm*)g_sequence_get(iter); GSequenceIter *next = g_sequence_iter_next(iter); if (alarm && alarm->serviceName && alarm->key && (strcmp(alarm->serviceName, serviceName) == 0) && (strcmp(alarm->key, key) == 0)) { g_string_append_printf(alarm_str, "%s{\"alarmId\":%d,\"key\":\"%s\"}", first ? "" : "\n,", alarm->id, alarm->key); first = false; } iter = next; } buf = g_string_sized_new(512); g_string_append_printf(buf, "{\"alarms\": [%s]}", alarm_str->str); LSError lserror; LSErrorInit(&lserror); retVal = LSMessageReply(sh, message, buf->str, &lserror); if (!retVal) { LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } goto cleanup; invalid_format: retVal = LSMessageReply(sh, message, "{\"returnValue\":false," "\"errorText\":\"alarmQuery parameters are missing.\"}", &lserror); goto cleanup; malformed_json: LSMessageReplyErrorBadJSON(sh, message); goto cleanup; cleanup: if (alarm_str) g_string_free(alarm_str, TRUE); if (buf) g_string_free(buf, TRUE); if (!is_error(object)) json_object_put(object); return true; } /** * @brief Remove an alarm by id. * * {"alarmId":1} * * Response: * * {"returnValue":true} * * @param sh * @param message * @param ctx * * @retval */ static bool alarmRemove(LSHandle *sh, LSMessage *message, void *ctx) { LSError lserror; LSErrorInit(&lserror); bool found = false; bool retVal; const char *payload = LSMessageGetPayload(message); struct json_object *object = json_tokener_parse(payload); if (is_error(object)) { goto malformed_json; } SLEEPDLOG(LOG_DEBUG, "%s: %s", __FUNCTION__, LSMessageGetPayload(message)); int alarmId = json_object_get_int(json_object_object_get(object, "alarmId")); GSequenceIter *iter = g_sequence_get_begin_iter(gAlarmQueue->alarms); while (!g_sequence_iter_is_end (iter)) { _Alarm *alarm = (_Alarm*)g_sequence_get(iter); GSequenceIter *next = g_sequence_iter_next(iter); if (alarm && alarm->id == alarmId) { char *timeout_key = g_strdup_printf("%s-%d", alarm->key, alarm->id); _timeout_clear("com.palm.sleep", timeout_key, false /*public_bus*/); g_free(timeout_key); g_sequence_remove(iter); found = true; } iter = next; } const char *response; if (found) { alarm_write_db(); response = "{\"returnValue\":true}"; } else { response = "{\"returnValue\":false}"; } retVal = LSMessageReply(sh, message, response, &lserror); if (!retVal) { LSErrorPrint(&lserror,stderr); LSErrorFree(&lserror); } goto cleanup; malformed_json: LSMessageReplyErrorBadJSON(sh, message); goto cleanup; cleanup: if (!is_error(object)) json_object_put(object); return true; } /** * @brief Called when a RTC alarm is fired. * * @param sh * @param message * @param ctx * * @retval */ static bool internalAlarmFired(LSHandle *sh, LSMessage *message, void *ctx) { g_debug(LOG_DOMAIN "%s ", __FUNCTION__); update_alarms(); return true; } LSMethod time_methods[] = { { "alarmAddCalendar", alarmAddCalendar }, { "alarmAdd", alarmAdd }, { "alarmQuery", alarmQuery }, { "alarmRemove", alarmRemove }, { "internalAlarmFired", internalAlarmFired }, { }, }; static void alarm_free(_Alarm *a) { g_debug("Freeing alarm with id %d", a->id); g_free(a->serviceName); g_free(a->applicationName); if (a->message) LSMessageUnref(a->message); g_free(a); } static gint alarm_cmp_func(_Alarm *a, _Alarm *b, gpointer data) { return (a->expiry < b->expiry) ? -1 : (a->expiry == b->expiry) ? 0 : 1; } static int alarm_queue_create(void) { gAlarmQueue = g_new0(_AlarmQueue, 1); gAlarmQueue->alarms = g_sequence_new((GDestroyNotify)alarm_free); gAlarmQueue->seq_id = 0; gAlarmQueue->alarm_db = g_build_filename(gSleepConfig.preference_dir, "alarms.xml", NULL); return 0; } #define STD_ASCTIME_BUF_SIZE 26 static void alarm_print(_Alarm *a) { char buf[STD_ASCTIME_BUF_SIZE]; struct tm tm; gmtime_r(&a->expiry, &tm); asctime_r(&tm, buf); SLEEPDLOG(LOG_DEBUG, "(%s, %s) set alarm id %d @ %s", a->serviceName ?: "null", a->applicationName ?: "null", a->id, buf); } static void alarm_read_db(void) { bool retVal; xmlDocPtr db = xmlReadFile(gAlarmQueue->alarm_db, NULL, 0); if (!db) return; xmlNodePtr cur = xmlDocGetRootElement(db); xmlNodePtr sub; if (!cur) return; sub = cur->children; while (sub != NULL) { if (!xmlStrcmp(sub->name, (const xmlChar*)"alarm")) { xmlChar *id = xmlGetProp(sub, (const xmlChar*)"id"); xmlChar *key = xmlGetProp(sub, (const xmlChar*)"key"); xmlChar *expiry = xmlGetProp(sub, (const xmlChar*)"expiry"); xmlChar *calendar = xmlGetProp(sub, (const xmlChar*)"calendar"); xmlChar *service = xmlGetProp(sub, (const xmlChar*)"serviceName"); xmlChar *app = xmlGetProp(sub, (const xmlChar*)"applicationName"); if (!id || !expiry) { goto clean_round; } unsigned long expiry_secs = 0; uint32_t alarmId = 0; bool isCalendar = false; if (expiry) { expiry_secs = atol((const char*)expiry); } if (id) { alarmId = atoi((const char*)id); } if (calendar) { isCalendar = atoi((const char*)calendar) > 0; } retVal = alarm_queue_add(alarmId, (const char *)key, isCalendar, expiry_secs, (const char*)service, (const char*)app, false, NULL); if (!retVal) { g_critical("%s: could not add alarm.", __FUNCTION__); } clean_round: xmlFree(expiry); xmlFree(service); xmlFree(app); } sub = sub->next; } xmlFreeDoc(db); } static void alarm_save(_Alarm *a, FILE *file) { char buf[STD_ASCTIME_BUF_SIZE]; struct tm tm; gmtime_r(&a->expiry, &tm); asctime_r(&tm, buf); g_strchomp(buf); fprintf(file, "<alarm id='%d' expiry='%ld' calendar='%d'" " key='%s'" " expiry_text='%s'" " serviceName='%s'" " applicationName='%s'/>\n", a->id, a->expiry, a->calendar, a->key, buf, a->serviceName ?: "", a->applicationName ?: ""); } static bool alarm_write_db(void) { bool retVal = false; FILE *file = fopen(gAlarmQueue->alarm_db, "w"); if (!file) goto cleanup; fprintf(file, "<alarms>\n"); g_sequence_foreach(gAlarmQueue->alarms, (GFunc)alarm_save, file); fprintf(file, "</alarms>\n"); fclose(file); retVal = true; cleanup: return retVal; } /** * @brief Create a new alarm and assign it an new id. * * @param key * @param calendar_time * @param expiry * @param serviceName * @param applicationName * @param subscribe * @param message * @param ret_id * */ bool alarm_queue_new(const char *key, bool calendar_time, time_t expiry, const char *serviceName, const char *applicationName, bool subscribe, LSMessage *message, int *ret_id) { bool retVal; uint32_t id = gAlarmQueue->seq_id++; if (ret_id) *ret_id = id; retVal = alarm_queue_add(id, key, calendar_time, expiry, serviceName, applicationName, subscribe, message); if (retVal) { alarm_write_db(); } return retVal; } /** * @brief Obtain the next alarm that will fire. * */ _Alarm * alarm_queue_get_first(void) { GSequenceIter *seq = g_sequence_get_begin_iter(gAlarmQueue->alarms); if (g_sequence_iter_is_end(seq)) return NULL; _Alarm *alarm = (_Alarm*)g_sequence_get(seq); return alarm; } /** * @brief Adjusts the alarm when a time set occurs and the wall clock * and rtc clock diverge. * * This should also be called on init, in case of a crash before we * were able to adjust the alarms successfully. * */ void recalculate_alarms(time_t delta) { if (delta) { /* Adjust each fixed time alarm by the delta. * i.e. 5 seconds in the future + delta = T + 5 + delta */ GSequenceIter *iter = g_sequence_get_begin_iter(gAlarmQueue->alarms); while (!g_sequence_iter_is_end (iter)) { _Alarm *alarm = (_Alarm*)g_sequence_get(iter); GSequenceIter *next = g_sequence_iter_next(iter); if (alarm && !alarm->calendar) { alarm->expiry += delta; } iter = next; } /* resort */ g_sequence_sort(gAlarmQueue->alarms, (GCompareDataFunc)alarm_cmp_func, NULL); /* persist */ alarm_write_db(); } return; } void update_alarms_delta(time_t delta) { /* If the time changed, we need to readjust alarms, * and persist the changes. */ if (delta) { recalculate_alarms(delta); } /* Trigger any pending alarms and remove them from the queue. */ notify_alarms(); } /** * @brief Set the next alarm. */ static void update_alarms(void) { update_alarms_delta(0); } /** * @brief Add a new alarm to the queue. * * @param id * @param calendar_time * @param expiry * @param serviceName * @param applicationName * * @retval */ static bool alarm_queue_add(uint32_t id, const char *key, bool calendar_time, time_t expiry, const char *serviceName, const char *applicationName, bool subscribe, LSMessage *message) { _Alarm *alarm = g_new0(_Alarm, 1); alarm->key = g_strdup(key); alarm->id = id; alarm->calendar = calendar_time; alarm->expiry = expiry; alarm->serviceName = g_strdup(serviceName); alarm->applicationName = g_strdup(applicationName); if (subscribe) { LSError lserror; LSErrorInit(&lserror); bool retVal = LSSubscriptionAdd( GetLunaServiceHandle(), "alarm", message, &lserror); if (!retVal) { LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); goto error; } LSMessageRef(message); alarm->message = message; } alarm_print(alarm); if (alarm->id >= gAlarmQueue->seq_id) { gAlarmQueue->seq_id = alarm->id+1; } g_sequence_insert_sorted(gAlarmQueue->alarms, alarm, (GCompareDataFunc)alarm_cmp_func, NULL); update_alarms(); return true; error: return false; } /** * @brief Sends a "/alarm" message to the service associated with this alarm. * * {"alarmId":1,"fired":true,"key":"appkey"} * * @param alarm */ static void fire_alarm(_Alarm *alarm) { bool retVal; char buf_alarm[STD_ASCTIME_BUF_SIZE]; struct tm tm_alarm; time_t rtctime = 0; gmtime_r(&alarm->expiry, &tm_alarm); asctime_r(&tm_alarm, buf_alarm); nyx_system_query_rtc_time(GetNyxSystemDevice(),&rtctime); SLEEPDLOG(LOG_INFO, "Alarm (%s %s %s) fired at %s (rtc %ld)", alarm->serviceName, alarm->applicationName, alarm->key, buf_alarm, rtctime); GString *payload = g_string_sized_new(255); g_string_append_printf(payload, "{\"alarmId\":%d,\"fired\":true", alarm->id); if (alarm->key) { g_string_append_printf(payload, ",\"key\":\"%s\"", alarm->key); } if (alarm->applicationName && strcmp(alarm->applicationName, "") != 0) { g_string_append_printf(payload, ",\"applicationName\":\"%s\"", alarm->applicationName); } g_string_append_printf(payload, "}"); LSError lserror; LSErrorInit(&lserror); if (alarm->serviceName && strcmp(alarm->serviceName, "") != 0) { char *uri = g_strdup_printf("luna://%s/alarm", alarm->serviceName); retVal = LSCall(GetLunaServiceHandle(), uri, payload->str, NULL, NULL, NULL, &lserror); if (!retVal) { LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } g_free(uri); } if (alarm->message) { retVal = LSMessageReply(GetLunaServiceHandle(), alarm->message, payload->str, &lserror); if (!retVal) { LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } } g_string_free(payload, TRUE); } /** * @brief Send message to each expired alarm. */ static void notify_alarms(void) { time_t now; bool fired = false; now = rtc_wall_time(); GSequenceIter *iter = g_sequence_get_begin_iter(gAlarmQueue->alarms); while (!g_sequence_iter_is_end (iter)) { _Alarm *alarm = (_Alarm*)g_sequence_get(iter); GSequenceIter *next = g_sequence_iter_next(iter); if (alarm && alarm->expiry <= now) { fire_alarm(alarm); g_sequence_remove(iter); fired = true; } iter = next; } if (fired) { alarm_write_db(); } } /** * @brief Init registers with bus and udev. * */ int alarm_init(void) { LSError lserror; LSErrorInit(&lserror); if (!LSRegisterCategory(GetLunaServiceHandle(), "/time", time_methods, NULL, NULL, &lserror)) { goto error; } alarm_queue_create(); alarm_read_db(); update_alarms(); return 0; error: return -1; } /* @} END OF OldInterface */
212
./ssh4py/src/channel.c
/* * channel.c * * Copyright (C) 2005 Keyphrene.com * Copyright (C) 2010-2011 Sebastian Noack * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ssh2.h" /* * Constructor for Channel objects, never called by Python code directly * * Arguments: cert - A "real" Channel certificate object * session - The Python object reperesenting the session * Returns: The newly created Channel object */ SSH2_ChannelObj * SSH2_Channel_New(LIBSSH2_CHANNEL *channel, SSH2_SessionObj *session) { SSH2_ChannelObj *self; if ((self = PyObject_New(SSH2_ChannelObj, &SSH2_Channel_Type)) == NULL) return NULL; self->channel = channel; Py_INCREF(session); self->session = session; return self; } static PyObject * channel_close(SSH2_ChannelObj *self) { int ret; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_close(self->channel); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * channel_request_pty(SSH2_ChannelObj *self, PyObject *args) { char *term; char *modes = NULL; Py_ssize_t lt; Py_ssize_t lm = 0; int ret; int w = 80; int h = 24; int pw = 0; int ph = 0; if (!PyArg_ParseTuple(args, "s#|s#iiii:request_pty", &term, &lt, &modes, &lm, &w, &h, &pw, &ph)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_request_pty_ex(self->channel, term, lt, modes, lm, w, h, pw, ph); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * channel_request_pty_size(SSH2_ChannelObj *self, PyObject *args) { int ret; int w = 80; int h = 24; if (!PyArg_ParseTuple(args, "ii:request_pty_size", &w, &h)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_request_pty_size(self->channel, w, h); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * channel_x11_req(SSH2_ChannelObj *self, PyObject *args, PyObject *kwds) { int screen_number; int single_connection = 0; int ret; char *auth_proto = NULL; char *auth_cookie = NULL; static char *kwlist[] = {"screen_number", "single_connection", "auth_proto", "auth_cookie", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "i|iss", kwlist, &screen_number, &single_connection, &auth_proto, &auth_cookie)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_x11_req_ex(self->channel, single_connection, auth_proto, auth_cookie, screen_number); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * channel_shell(SSH2_ChannelObj *self) { int ret; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_process_startup(self->channel, "shell", 5, NULL, 0); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } /* Can not be called just 'Channel.exec' like in the C API, * because of 'exec' is a reserved keyword in Python 2. */ static PyObject * channel_execute(SSH2_ChannelObj *self, PyObject *args) { char *cmd; Py_ssize_t cmd_len; int ret; if (!PyArg_ParseTuple(args, "s#:execute", &cmd, &cmd_len)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_process_startup(self->channel, "exec", 4, cmd, cmd_len); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * channel_subsystem(SSH2_ChannelObj *self, PyObject *args) { char *subsys; Py_ssize_t subsys_len; int ret; if (!PyArg_ParseTuple(args, "s#:subsystem", &subsys, &subsys_len)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_process_startup(self->channel, "subsystem", 9, subsys, subsys_len); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * channel_setenv(SSH2_ChannelObj *self, PyObject *args) { char *key; char *val; Py_ssize_t key_len; Py_ssize_t val_len; int ret; if (!PyArg_ParseTuple(args, "s#s#:setenv", &key, &key_len, &val, &val_len)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_setenv_ex(self->channel, key, key_len, val, val_len); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * channel_read(SSH2_ChannelObj *self, PyObject *args) { int ret; int bufsiz; int stream_id = 0; PyObject *buf; if (!PyArg_ParseTuple(args, "i|i:read", &bufsiz, &stream_id)) return NULL; if (bufsiz < 0) { PyErr_SetString(PyExc_ValueError, "negative size"); return NULL; } if ((buf = PyBytes_FromStringAndSize(NULL, bufsiz)) == NULL) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_read_ex(self->channel, stream_id, PyBytes_AS_STRING(buf), bufsiz); Py_END_ALLOW_THREADS if (ret < 0) { Py_DECREF(buf); /* We have to work around a bug in libssh2, that _libssh2_error() is not * called by libssh2_channel_read_ex() when the transport layer returns * LIBSSH2_ERROR_EAGAIN. So in that case the last error is not set and * the RAISE_SSH2_ERROR macro will not be able to raise the correct exception. * Thanks to Daniel Stenberg, who has fixed that issue now (see 2db4863). * However in order that our bindings work correctly with older versions * of libssh2, we need the workaround below. */ if (ret == LIBSSH2_ERROR_EAGAIN) { PyObject *exc; exc = PyObject_CallFunction(SSH2_Error, "s", "Would block"); PyObject_SetAttrString(exc, "errno", Py_BuildValue("i", ret)); PyErr_SetObject(SSH2_Error, exc); return NULL; } RAISE_SSH2_ERROR(self->session) } if (bufsiz != ret && _PyBytes_Resize(&buf, ret) != 0) return NULL; return buf; } static PyObject * channel_write(SSH2_ChannelObj *self, PyObject *args) { char *msg; Py_ssize_t len; Py_ssize_t ret; #if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTuple(args, "y#:write", &msg, &len)) #else if (!PyArg_ParseTuple(args, "s#:write", &msg, &len)) #endif return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_write(self->channel, msg, len); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) return Py_BuildValue("n", ret); } static PyObject * channel_flush(SSH2_ChannelObj *self) { int ret=0; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_flush(self->channel); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * channel_send_eof(SSH2_ChannelObj *self) { int ret; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_send_eof(self->channel); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * channel_receive_window_adjust(SSH2_ChannelObj *self, PyObject *args) { unsigned long adjustment; unsigned char force = 0; unsigned int window; int ret; if (!PyArg_ParseTuple(args, "k|B:window_adjust", &adjustment, &force)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_receive_window_adjust2(self->channel, adjustment, force, &window); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) return Py_BuildValue("k", window); } static PyObject * channel_window_read(SSH2_ChannelObj *self) { unsigned long ret=0; unsigned long read_avail; unsigned long window_size_initial; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_window_read_ex(self->channel, &read_avail, &window_size_initial); Py_END_ALLOW_THREADS return Py_BuildValue("(kkk)", ret, read_avail, window_size_initial); } static PyObject * channel_window_write(SSH2_ChannelObj *self) { unsigned long ret=0; unsigned long window_size_initial; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_window_write_ex(self->channel, &window_size_initial); Py_END_ALLOW_THREADS return Py_BuildValue("(kk)", ret, window_size_initial); } static PyObject * channel_get_exit_status(SSH2_ChannelObj *self) { int ret; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_get_exit_status(self->channel); Py_END_ALLOW_THREADS return Py_BuildValue("i", ret); } static PyObject * channel_wait_closed(SSH2_ChannelObj *self) { int ret; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_wait_closed(self->channel); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * channel_wait_eof(SSH2_ChannelObj *self) { int ret; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_wait_eof(self->channel); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyMethodDef channel_methods[] = { {"close", (PyCFunction)channel_close, METH_NOARGS}, {"request_pty", (PyCFunction)channel_request_pty, METH_VARARGS}, {"request_pty_size", (PyCFunction)channel_request_pty_size, METH_VARARGS}, {"x11_req", (PyCFunction)channel_x11_req, METH_VARARGS | METH_KEYWORDS}, {"shell", (PyCFunction)channel_shell, METH_NOARGS}, {"execute", (PyCFunction)channel_execute, METH_VARARGS}, {"subsystem", (PyCFunction)channel_subsystem, METH_VARARGS}, {"setenv", (PyCFunction)channel_setenv, METH_VARARGS}, {"read", (PyCFunction)channel_read, METH_VARARGS}, {"write", (PyCFunction)channel_write, METH_VARARGS}, {"flush", (PyCFunction)channel_flush, METH_NOARGS}, {"send_eof", (PyCFunction)channel_send_eof, METH_NOARGS}, {"receive_window_adjust", (PyCFunction)channel_receive_window_adjust, METH_VARARGS}, {"window_read", (PyCFunction)channel_window_read, METH_NOARGS}, {"window_write", (PyCFunction)channel_window_write, METH_NOARGS}, {"get_exit_status", (PyCFunction)channel_get_exit_status, METH_NOARGS}, {"wait_closed", (PyCFunction)channel_wait_closed, METH_NOARGS}, {"wait_eof", (PyCFunction)channel_wait_eof, METH_NOARGS}, {NULL, NULL} }; static int channel_set_blocking(SSH2_ChannelObj *self, PyObject *value, void *closure) { libssh2_channel_set_blocking(self->channel, PyObject_IsTrue(value)); return 0; } PyObject * channel_get_eof(SSH2_ChannelObj *self, void *closure) { return PyBool_FromLong(libssh2_channel_eof(self->channel)); } static PyGetSetDef channel_getsets[] = { {"blocking", NULL, (setter)channel_set_blocking, NULL}, {"eof", (getter)channel_get_eof, NULL, NULL}, {NULL} }; /* * Deallocate the memory used by the Channel object * * Arguments: self - The Channel object * Returns: None */ static void channel_dealloc(SSH2_ChannelObj *self) { Py_BEGIN_ALLOW_THREADS while (libssh2_channel_close(self->channel) == LIBSSH2_ERROR_EAGAIN) {} Py_END_ALLOW_THREADS libssh2_channel_free(self->channel); self->channel = NULL; Py_CLEAR(self->session); PyObject_Del(self); } PyTypeObject SSH2_Channel_Type = { PyVarObject_HEAD_INIT(NULL, 0) "Channel", /* tp_name */ sizeof(SSH2_ChannelObj), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)channel_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ channel_methods, /* tp_methods */ 0, /* tp_members */ channel_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; /* * Initialize the Channel * * Arguments: module - The SSH2 module * Returns: None */ int init_SSH2_Channel(PyObject *module) { if (PyType_Ready(&SSH2_Channel_Type) != 0) return -1; Py_INCREF(&SSH2_Channel_Type); if (PyModule_AddObject(module, "Channel", (PyObject *)&SSH2_Channel_Type) == 0) return 0; Py_DECREF(&SSH2_Channel_Type); return -1; }
213
./ssh4py/src/sftp.c
/* * sftp.c * * Copyright (C) 2005 Keyphrene.com * Copyright (C) 2010-2011 Sebastian Noack * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ssh2.h" /* * Constructor for SFTP objects, never called by Python code directly * * Arguments: cert - A "real" SFTP certificate object * session - The Python object reperesenting the session * Returns: The newly created SFTP object */ SSH2_SFTPObj * SSH2_SFTP_New(LIBSSH2_SFTP *sftp, SSH2_SessionObj *session) { SSH2_SFTPObj *self; if ((self = PyObject_New(SSH2_SFTPObj, &SSH2_SFTP_Type)) == NULL) return NULL; self->sftp = sftp; Py_INCREF(session); self->session = session; return self; } unsigned long get_flags(char *mode) { unsigned long flags = 0; if (strchr(mode, 'a')) flags |= LIBSSH2_FXF_APPEND; if (strchr(mode, 'w')) flags |= LIBSSH2_FXF_WRITE | LIBSSH2_FXF_TRUNC | LIBSSH2_FXF_CREAT; if (strchr(mode, 'r')) flags |= LIBSSH2_FXF_READ; if (strchr(mode, '+')) flags |= LIBSSH2_FXF_READ | LIBSSH2_FXF_WRITE; if (strchr(mode, 'x')) flags |= LIBSSH2_FXF_WRITE | LIBSSH2_FXF_TRUNC | LIBSSH2_FXF_EXCL | LIBSSH2_FXF_CREAT; return flags; } PyObject * get_attrs(LIBSSH2_SFTP_ATTRIBUTES *attr) { return Py_BuildValue("(Kkkkkk)", attr->filesize, attr->uid, attr->gid, attr->permissions, attr->atime, attr->mtime); } static PyObject * SFTP_open_dir(SSH2_SFTPObj *self, PyObject *args) { LIBSSH2_SFTP_HANDLE *handle; char *path; Py_ssize_t path_len; if (!PyArg_ParseTuple(args, "s#:open_dir", &path, &path_len)) return NULL; Py_BEGIN_ALLOW_THREADS handle = libssh2_sftp_open_ex(self->sftp, path, path_len, 0, 0, LIBSSH2_SFTP_OPENDIR); Py_END_ALLOW_THREADS CHECK_RETURN_POINTER(handle, self->session) return (PyObject *)SSH2_SFTP_handle_New(handle, self->session); } static PyObject * SFTP_read_dir(SSH2_SFTPObj *self, PyObject *args) { LIBSSH2_SFTP_ATTRIBUTES attr; SSH2_SFTP_handleObj *handle; char buf[MAX_FILENAME_LENGHT]; int ret; if (!PyArg_ParseTuple(args, "O!:read_dir", &SSH2_SFTP_handle_Type, &handle)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_readdir(handle->sftphandle, buf, sizeof(buf), &attr); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) if (ret == 0) Py_RETURN_NONE; return Py_BuildValue("(s#O)", buf, ret, get_attrs(&attr)); } static PyObject * SFTP_open(SSH2_SFTPObj *self, PyObject *args) { LIBSSH2_SFTP_HANDLE *handle; char *path; char *flags = "r"; Py_ssize_t path_len; long mode = 0755; if (!PyArg_ParseTuple(args, "s#|si:open", &path, &path_len, &flags, &mode)) return NULL; Py_BEGIN_ALLOW_THREADS handle = libssh2_sftp_open_ex(self->sftp, path, path_len, get_flags(flags), mode, LIBSSH2_SFTP_OPENFILE); Py_END_ALLOW_THREADS CHECK_RETURN_POINTER(handle, self->session) return (PyObject *)SSH2_SFTP_handle_New(handle, self->session); } static PyObject * SFTP_shutdown(SSH2_SFTPObj *self) { int ret; // libssh2_sftp_shutdown == libssh2_channel_free(sftp->channel) Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_shutdown(self->sftp); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * SFTP_read(SSH2_SFTPObj *self, PyObject *args) { int ret; int bufsiz; PyObject *buf; SSH2_SFTP_handleObj *handle; if (!PyArg_ParseTuple(args, "O!i:read", &SSH2_SFTP_handle_Type, &handle, &bufsiz)) return NULL; if (bufsiz < 0) { PyErr_SetString(PyExc_ValueError, "negative size"); return NULL; } if ((buf = PyBytes_FromStringAndSize(NULL, bufsiz)) == NULL) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_read(handle->sftphandle, PyBytes_AS_STRING(buf), bufsiz); Py_END_ALLOW_THREADS if (ret < 0) { Py_DECREF(buf); RAISE_SSH2_ERROR(self->session) } if (bufsiz != ret && _PyBytes_Resize(&buf, ret) != 0) return NULL; return buf; } static PyObject * SFTP_write(SSH2_SFTPObj *self, PyObject *args) { char *msg; Py_ssize_t len; Py_ssize_t ret; SSH2_SFTP_handleObj *handle; #if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTuple(args, "O!y#:write", &SSH2_SFTP_handle_Type, &handle, &msg, &len)) #else if (!PyArg_ParseTuple(args, "O!s#:write", &SSH2_SFTP_handle_Type, &handle, &msg, &len)) #endif return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_write(handle->sftphandle, msg, len); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) #if PY_VERSION_HEX < 0x02050000 return Py_BuildValue("i", ret); #else return Py_BuildValue("n", ret); #endif } static PyObject * SFTP_tell(SSH2_SFTPObj *self, PyObject *args) { Py_ssize_t ret; SSH2_SFTP_handleObj *handle; if (!PyArg_ParseTuple(args, "O!:tell", &SSH2_SFTP_handle_Type, &handle)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_tell(handle->sftphandle); Py_END_ALLOW_THREADS #if PY_VERSION_HEX < 0x02050000 return Py_BuildValue("i", ret); #else return Py_BuildValue("n", ret); #endif } static PyObject * SFTP_seek(SSH2_SFTPObj *self, PyObject *args) { SSH2_SFTP_handleObj *handle; unsigned long offset=0; if (!PyArg_ParseTuple(args, "O!k:seek", &SSH2_SFTP_handle_Type, &handle, &offset)) return NULL; Py_BEGIN_ALLOW_THREADS libssh2_sftp_seek(handle->sftphandle, offset); Py_END_ALLOW_THREADS Py_RETURN_NONE; } static PyObject * SFTP_unlink(SSH2_SFTPObj *self, PyObject *args) { char *path; Py_ssize_t path_len; int ret; if (!PyArg_ParseTuple(args, "s#:unlink", &path, &path_len)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_unlink_ex(self->sftp, path, path_len); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * SFTP_rename(SSH2_SFTPObj *self, PyObject *args) { char *src; char *dst; Py_ssize_t src_len; Py_ssize_t dst_len; int ret; if (!PyArg_ParseTuple(args, "s#s#:rename", &src, &src_len, &dst, &dst_len)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_rename_ex(self->sftp, src, src_len, dst, dst_len, LIBSSH2_SFTP_RENAME_OVERWRITE | LIBSSH2_SFTP_RENAME_ATOMIC | LIBSSH2_SFTP_RENAME_NATIVE); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * SFTP_mkdir(SSH2_SFTPObj *self, PyObject *args) { char *path; Py_ssize_t path_len; long mode = 0755; int ret; if (!PyArg_ParseTuple(args, "s#|i:mkdir", &path, &path_len, &mode)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_mkdir_ex(self->sftp, path, path_len, mode); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * SFTP_rmdir(SSH2_SFTPObj *self, PyObject *args) { char *path; Py_ssize_t path_len; int ret; if (!PyArg_ParseTuple(args, "s#:rmdir", &path, &path_len)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_rmdir_ex(self->sftp, path, path_len); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * SFTP_symlink(SSH2_SFTPObj *self, PyObject *args) { char *path; char *target; Py_ssize_t path_len; Py_ssize_t target_len; int ret; if (!PyArg_ParseTuple(args, "s#s#:symlink", &path, &path_len, &target, &target_len)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_symlink_ex(self->sftp, path, path_len, target, target_len, LIBSSH2_SFTP_SYMLINK); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyObject * SFTP_readlink(SSH2_SFTPObj *self, PyObject *args) { char *path; char target[MAX_FILENAME_LENGHT]; Py_ssize_t path_len; int ret; if (!PyArg_ParseTuple(args, "s#:readlink", &path, &path_len)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_symlink_ex(self->sftp, path, path_len, target, sizeof(target), LIBSSH2_SFTP_READLINK); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) if (ret == 0) Py_RETURN_NONE; return Py_BuildValue("s#", target, ret); } static PyObject * SFTP_realpath(SSH2_SFTPObj *self, PyObject *args) { char *path; char target[MAX_FILENAME_LENGHT]; Py_ssize_t path_len; int ret; if (!PyArg_ParseTuple(args, "s#:realpath", &path, &path_len)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_symlink_ex(self->sftp, path, path_len, target, sizeof(target), LIBSSH2_SFTP_REALPATH); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) if (ret == 0) Py_RETURN_NONE; return Py_BuildValue("s#", target, ret); } static PyObject * SFTP_get_stat(SSH2_SFTPObj *self, PyObject *args) { char *path; Py_ssize_t path_len; int type = LIBSSH2_SFTP_STAT; int ret; LIBSSH2_SFTP_ATTRIBUTES attr; if (!PyArg_ParseTuple(args, "s#|i:get_stat", &path, &path_len, &type)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_stat_ex(self->sftp, path, path_len, type, &attr); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) return get_attrs(&attr); } static PyObject * SFTP_set_stat(SSH2_SFTPObj *self, PyObject *args, PyObject *kwds) { char *path; char has_uid = 0; char has_gid = 0; char has_atime = 0; char has_mtime = 0; Py_ssize_t path_len; Py_ssize_t pos = 0; PyObject *key; PyObject *val; LIBSSH2_SFTP_ATTRIBUTES attr; int ret; if (!PyArg_ParseTuple(args, "s#:set_stat", &path, &path_len)) return NULL; while (PyDict_Next(kwds, &pos, &key, &val)) { char *s; unsigned long *field; #if PY_MAJOR_VERSION < 3 if (!PyString_Check(key)) { PyErr_SetString(PyExc_TypeError, "keywords must be strings"); return NULL; } s = PyString_AS_STRING(key); #else if (!PyUnicode_Check(key)) { PyErr_SetString(PyExc_TypeError, "keywords must be strings"); return NULL; } s = (char *)PyUnicode_AS_DATA(key); #endif if (!strcmp(s, "uid")) { has_uid = 1; attr.flags |= LIBSSH2_SFTP_ATTR_UIDGID; field = &(attr.uid); } else if (!strcmp(s, "gid")) { has_gid = 1; field = &(attr.gid); } else if (!strcmp(s, "permissions")) { attr.flags |= LIBSSH2_SFTP_ATTR_PERMISSIONS; field = &(attr.permissions); } else if (!strcmp(s, "atime")) { has_atime = 1; attr.flags |= LIBSSH2_SFTP_ATTR_ACMODTIME; field = &(attr.atime); } else if (!strcmp(s, "mtime")) { has_mtime = 1; field = &(attr.mtime); } else return PyErr_Format(PyExc_TypeError, "'%s' is an invalid keyword " "argument for set_stat()", s); #if PY_MAJOR_VERSION < 3 if (PyInt_Check(val)) { *field = PyInt_AsUnsignedLongMask(val); continue; } #endif if (PyLong_Check(val)) { *field = PyLong_AsUnsignedLongMask(val); continue; } PyErr_SetString(PyExc_TypeError, "keyword arguments for set_stat() must be integers"); return NULL; } if (has_uid != has_gid) { PyErr_SetString(PyExc_TypeError, "set_stat() requires the keyword " "arguments 'uid' and 'gid' or none " "of them"); return NULL; } if (has_atime != has_mtime) { PyErr_SetString(PyExc_TypeError, "set_stat() requires the keyword " "arguments 'atime' and 'mtime' or " "none of them"); return NULL; } Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_stat_ex(self->sftp, path, path_len, LIBSSH2_SFTP_SETSTAT, &attr); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyMethodDef SFTP_methods[] = { {"open_dir", (PyCFunction)SFTP_open_dir, METH_VARARGS}, {"read_dir", (PyCFunction)SFTP_read_dir, METH_VARARGS}, {"open", (PyCFunction)SFTP_open, METH_VARARGS}, {"shutdown", (PyCFunction)SFTP_shutdown, METH_NOARGS}, {"read", (PyCFunction)SFTP_read, METH_VARARGS}, {"write", (PyCFunction)SFTP_write, METH_VARARGS}, {"tell", (PyCFunction)SFTP_tell, METH_VARARGS}, {"seek", (PyCFunction)SFTP_seek, METH_VARARGS}, {"unlink", (PyCFunction)SFTP_unlink, METH_VARARGS}, {"rename", (PyCFunction)SFTP_rename, METH_VARARGS}, {"mkdir", (PyCFunction)SFTP_mkdir, METH_VARARGS}, {"rmdir", (PyCFunction)SFTP_rmdir, METH_VARARGS}, {"symlink", (PyCFunction)SFTP_symlink, METH_VARARGS}, {"readlink", (PyCFunction)SFTP_readlink, METH_VARARGS}, {"realpath", (PyCFunction)SFTP_realpath, METH_VARARGS}, {"get_stat", (PyCFunction)SFTP_get_stat, METH_VARARGS}, {"set_stat", (PyCFunction)SFTP_set_stat, METH_VARARGS | METH_KEYWORDS}, {NULL, NULL} }; /* * Deallocate the memory used by the SFTP object * * Arguments: self - The SFTP object * Returns: None */ static void SFTP_dealloc(SSH2_SFTPObj *self) { Py_CLEAR(self->session); PyObject_Del(self); } PyTypeObject SSH2_SFTP_Type = { PyVarObject_HEAD_INIT(NULL, 0) "SFTP", /* tp_name */ sizeof(SSH2_SFTPObj), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SFTP_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ SFTP_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; /* * Initialize the SFTP * * Arguments: module - The SSH2 module * Returns: None */ int init_SSH2_SFTP(PyObject *module) { if (PyType_Ready(&SSH2_SFTP_Type) != 0) return -1; Py_INCREF(&SSH2_SFTP_Type); if (PyModule_AddObject(module, "SFTP", (PyObject *)&SSH2_SFTP_Type) == 0) return 0; Py_DECREF(&SSH2_SFTP_Type); return -1; }
214
./ssh4py/src/session.c
/* * session.c * * Copyright (C) 2005 Keyphrene.com * Copyright (C) 2010-2011 Sebastian Noack * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ssh2.h" /* * Constructor for Session objects, never called by Python code directly * * Arguments: cert - A "real" Session certificate object * Returns: The newly created Session object */ SSH2_SessionObj * SSH2_Session_New(LIBSSH2_SESSION *session) { SSH2_SessionObj *self; if ((self = PyObject_New(SSH2_SessionObj, &SSH2_Session_Type)) == NULL) return NULL; self->session = session; self->opened = 0; self->socket = Py_None; self->cb_ignore = Py_None; self->cb_debug = Py_None; self->cb_disconnect = Py_None; self->cb_macerror = Py_None; self->cb_x11 = Py_None; self->cb_passwd_changereq = Py_None; self->cb_kbdint_response = Py_None; Py_INCREF(Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); *libssh2_session_abstract(session) = self; libssh2_banner_set(session, LIBSSH2_SSH_DEFAULT_BANNER " Python"); return self; } static PyObject * session_banner_set(SSH2_SessionObj *self, PyObject *args) { char *banner; if (!PyArg_ParseTuple(args, "s:banner_set", &banner)) return NULL; libssh2_banner_set(self->session, banner); Py_RETURN_NONE; } static PyObject * session_startup(SSH2_SessionObj *self, PyObject *args) { PyObject *sock; int ret; int fd; if (!PyArg_ParseTuple(args, "O:startup", &sock)) return NULL; if ((fd = PyObject_AsFileDescriptor(sock)) == -1) { PyErr_SetString(PyExc_ValueError, "argument must be a file descriptor"); return NULL; } Py_BEGIN_ALLOW_THREADS ret=libssh2_session_startup(self->session, fd); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self) Py_DECREF(self->socket); Py_INCREF(sock); self->socket = sock; self->opened = 1; Py_RETURN_NONE; } static PyObject * session_disconnect(SSH2_SessionObj *self, PyObject *args, PyObject *kwds) { int ret; int reason = SSH_DISCONNECT_BY_APPLICATION; char *description = ""; char *lang = ""; static char *kwlist[] = {"reason", "description", "lang", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iss:disconnect", kwlist, &reason, &description, &lang)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_session_disconnect_ex(self->session, reason, description, lang); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self) self->opened = 0; Py_RETURN_NONE; } static PyObject * session_hostkey_hash(SSH2_SessionObj *self, PyObject *args) { int hashtype = LIBSSH2_HOSTKEY_HASH_MD5, size; const char *hash; if (!PyArg_ParseTuple(args, "|i:hostkey_hash", &hashtype)) return NULL; Py_BEGIN_ALLOW_THREADS hash = libssh2_hostkey_hash(self->session, hashtype); Py_END_ALLOW_THREADS switch(hashtype) { case LIBSSH2_HOSTKEY_HASH_MD5: size = 16; break; case LIBSSH2_HOSTKEY_HASH_SHA1: size = 20; break; default: size = 0; } #if PY_MAJOR_VERSION < 3 return Py_BuildValue("s#", hash, size); #else return Py_BuildValue("y#", hash, size); #endif } static PyObject * session_userauth_list(SSH2_SessionObj *self, PyObject *args) { char *username; char *ret; Py_ssize_t username_len; if (!PyArg_ParseTuple(args, "s#:userauth_list", &username, &username_len)) return NULL; if ((ret = libssh2_userauth_list(self->session, username, username_len)) == NULL) Py_RETURN_NONE; return Py_BuildValue("s", ret); } static void passwd_changereq_callback(LIBSSH2_SESSION *session, char **newpw, int *newpw_len, void **abstract) { PyObject *callback = ((SSH2_SessionObj *) *abstract)->cb_passwd_changereq; PyObject *rv; PyGILState_STATE gstate = PyGILState_Ensure(); char *s; int ret; if ((rv = PyObject_CallObject(callback, NULL)) == NULL) goto failure; #if PY_MAJOR_VERSION < 3 ret = PyString_AsStringAndSize(rv, &s, newpw_len); #else { PyObject *enc; if ((enc = PyUnicode_AsEncodedString(rv, NULL, "strict")) == NULL) goto failure; ret = PyBytes_AsStringAndSize(enc, &s, newpw_len); Py_DECREF(enc); } #endif Py_DECREF(rv); if (ret == 0) { *newpw = strndup(s, *newpw_len); goto exit; } failure: PyErr_WriteUnraisable(callback); exit: PyGILState_Release(gstate); } static PyObject * session_userauth_password(SSH2_SessionObj *self, PyObject *args) { char *username; char *password; Py_ssize_t username_len; Py_ssize_t password_len; PyObject *callback = NULL; int ret; if (!PyArg_ParseTuple(args, "s#s#|O:userauth_password", &username, &username_len, &password, &password_len, &callback)) return NULL; if (callback != NULL) { if (!PyCallable_Check(callback)) return PyErr_Format(PyExc_TypeError, "'%s' is not callable", callback->ob_type->tp_name); Py_DECREF(self->cb_passwd_changereq); Py_INCREF(callback); self->cb_passwd_changereq = callback; Py_BEGIN_ALLOW_THREADS ret = libssh2_userauth_password_ex(self->session, username, username_len, password, password_len, passwd_changereq_callback); Py_END_ALLOW_THREADS Py_DECREF(self->cb_passwd_changereq); Py_INCREF(Py_None); self->cb_passwd_changereq = Py_None; } else { Py_BEGIN_ALLOW_THREADS ret = libssh2_userauth_password_ex(self->session, username, username_len, password, password_len, NULL); Py_END_ALLOW_THREADS } CHECK_RETURN_CODE(ret, self) Py_RETURN_NONE; } static PyObject * session_userauth_publickey_fromfile(SSH2_SessionObj *self, PyObject *args) { char *username; char *publickey; char *privatekey; char *passphrase = ""; Py_ssize_t username_len; int ret; if (!PyArg_ParseTuple(args, "s#ss|s:userauth_publickey_fromfile", &username, &username_len, &publickey, &privatekey, &passphrase)) return NULL; Py_BEGIN_ALLOW_THREADS ret = libssh2_userauth_publickey_fromfile_ex(self->session, username, username_len, publickey, privatekey, passphrase); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self) Py_RETURN_NONE; } #if LIBSSH2_VERSION_NUM >= 0x010203 static int publickey_sign_callback(LIBSSH2_SESSION *session, unsigned char **sig, size_t *sig_len, const unsigned char *data, size_t data_len, void **abstract) { PyObject *callback = (PyObject *) *abstract; PyObject *rv; PyGILState_STATE gstate = PyGILState_Ensure(); char *s; int ret = -1; #if PY_MAJOR_VERSION < 3 rv = PyObject_CallFunction(callback, "s#", data, data_len); #else rv = PyObject_CallFunction(callback, "y#", data, data_len); #endif if (rv == NULL) goto failure; ret = PyBytes_AsStringAndSize(rv, &s, (Py_ssize_t *) sig_len); Py_DECREF(rv); if (ret == 0) { *sig = (unsigned char*) strndup(s, *sig_len); goto exit; } failure: PyErr_WriteUnraisable(callback); exit: PyGILState_Release(gstate); return ret; } static PyObject * session_userauth_publickey(SSH2_SessionObj *self, PyObject *args) { char *username; char *pubkeydata; Py_ssize_t pubkeydata_len; PyObject *callback; int ret; #if PY_MAJOR_VERSION < 3 if (!PyArg_ParseTuple(args, "ss#O:userauth_publickey", &username, &pubkeydata, &pubkeydata_len, &callback)) #else if (!PyArg_ParseTuple(args, "sy#O:userauth_publickey", &username, &pubkeydata, &pubkeydata_len, &callback)) #endif return NULL; if (!PyCallable_Check(callback)) return PyErr_Format(PyExc_TypeError, "'%s' is not callable", callback->ob_type->tp_name); Py_BEGIN_ALLOW_THREADS ret = libssh2_userauth_publickey(self->session, username, (unsigned char*)pubkeydata, pubkeydata_len, publickey_sign_callback, (void **)&callback); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self) Py_RETURN_NONE; } #endif static PyObject * session_userauth_hostbased_fromfile(SSH2_SessionObj *self, PyObject *args) { char *username; char *publickey; char *privatekey; char *passphrase; char *hostname; char *local_username = NULL; Py_ssize_t username_len; Py_ssize_t hostname_len; Py_ssize_t local_username_len; int ret; if (!PyArg_ParseTuple(args, "s#ssss#|s#:userauth_hostbased_fromfile", &username, &username_len, &publickey, &privatekey, &passphrase, &hostname, &hostname_len, &local_username, &local_username_len)) return NULL; if (local_username == NULL) { local_username = username; local_username_len = username_len; } Py_BEGIN_ALLOW_THREADS ret = libssh2_userauth_hostbased_fromfile_ex(self->session, username, username_len, publickey, privatekey, passphrase, hostname, hostname_len, local_username, local_username_len); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self) Py_RETURN_NONE; } static void kbdint_response_callback(const char* name, int name_len, const char* instruction, int instruction_len, int num_prompts, const LIBSSH2_USERAUTH_KBDINT_PROMPT* prompts, LIBSSH2_USERAUTH_KBDINT_RESPONSE* responses, void **abstract) { PyGILState_STATE gstate = PyGILState_Ensure(); PyObject *callback = ((SSH2_SessionObj*) *abstract)->cb_kbdint_response; PyObject *lprompts = PyList_New(num_prompts); PyObject *rv = NULL; PyObject *it = NULL; int i; for (i = 0; i < num_prompts; i++) { PyList_SET_ITEM(lprompts, i, Py_BuildValue("(s#O)", prompts[i].text, prompts[i].length, prompts[i].echo ? Py_True : Py_False)); } rv = PyObject_CallFunction(callback, "s#s#O", name, name_len, instruction, instruction_len, lprompts); Py_DECREF(lprompts); if (rv == NULL) goto failure; it = PyObject_GetIter(rv); Py_DECREF(rv); if (it == NULL) goto failure; for (i = 0; i < num_prompts; i++) { PyObject *item = PyIter_Next(it); char *s; Py_ssize_t length; int ret; if (item == NULL) { Py_DECREF(it); if (!PyErr_Occurred()) { PyErr_Format(PyExc_ValueError, "callback returned %i reponse(s), " "but %i prompt(s) were given", i, num_prompts); } goto failure; } #if PY_MAJOR_VERSION < 3 ret = PyString_AsStringAndSize(item, &s, &length); #else { PyObject *enc; if ((enc = PyUnicode_AsEncodedString(item, NULL, "strict")) == NULL) { Py_DECREF(item); Py_DECREF(it); goto failure; } ret = PyBytes_AsStringAndSize(enc, &s, &length); Py_DECREF(enc); } #endif Py_DECREF(item); if (ret == -1) { Py_DECREF(it); goto failure; } responses[i].text = strndup(s, length); responses[i].length = length; } Py_DECREF(it); goto exit; failure: PyErr_WriteUnraisable(callback); exit: PyGILState_Release(gstate); } static PyObject * session_userauth_keyboard_interactive(SSH2_SessionObj *self, PyObject *args) { char *username; Py_ssize_t username_len; PyObject *callback; int ret; if (!PyArg_ParseTuple(args, "s#O:userauth_keyboard_interactive", &username, &username_len, &callback)) return NULL; if (!PyCallable_Check(callback)) return PyErr_Format(PyExc_TypeError, "'%s' is not callable", callback->ob_type->tp_name); Py_DECREF(self->cb_kbdint_response); Py_INCREF(callback); self->cb_kbdint_response = callback; Py_BEGIN_ALLOW_THREADS ret = libssh2_userauth_keyboard_interactive_ex(self->session, username, username_len, kbdint_response_callback); Py_END_ALLOW_THREADS Py_DECREF(self->cb_kbdint_response); Py_INCREF(Py_None); self->cb_kbdint_response = Py_None; CHECK_RETURN_CODE(ret, self) Py_RETURN_NONE; } static PyObject * session_get_methods(SSH2_SessionObj *self, PyObject *args) { int method_type; const char *ret; if (!PyArg_ParseTuple(args, "i:methods", &method_type)) return NULL; if ((ret = libssh2_session_methods(self->session, method_type)) == NULL) Py_RETURN_NONE; return Py_BuildValue("s", ret); } static PyObject * session_method_pref(SSH2_SessionObj *self, PyObject *args) { int ret; int method; char *pref; if (!PyArg_ParseTuple(args, "is:method_pref", &method, &pref)) return NULL; ret = libssh2_session_method_pref(self->session, method, pref); CHECK_RETURN_CODE(ret, self) Py_RETURN_NONE; } static void ignore_callback(LIBSSH2_SESSION *session, const char *msg, int msg_len, void **abstract) { PyObject *callback = ((SSH2_SessionObj *) *abstract)->cb_ignore; PyObject *rv; PyGILState_STATE gstate = PyGILState_Ensure(); rv = PyObject_CallFunction(callback, "s#", msg, msg_len); if (rv == NULL) PyErr_WriteUnraisable(callback); else Py_DECREF(rv); PyGILState_Release(gstate); } static void debug_callback(LIBSSH2_SESSION *session, int always_display, const char *msg, int msg_len, const char *lang, int lang_len, void **abstract) { PyObject *callback = ((SSH2_SessionObj *) *abstract)->cb_debug; PyObject *rv; PyGILState_STATE gstate = PyGILState_Ensure(); rv = PyObject_CallFunction(callback, "Os#s#", always_display ? Py_True : Py_False, msg, msg_len, lang, lang_len); if (rv == NULL) PyErr_WriteUnraisable(callback); else Py_DECREF(rv); PyGILState_Release(gstate); } static void disconnect_callback(LIBSSH2_SESSION *session, int reason, const char *msg, int msg_len, const char *lang, int lang_len, void **abstract) { PyObject *callback = ((SSH2_SessionObj *) *abstract)->cb_disconnect; PyObject *rv; PyGILState_STATE gstate = PyGILState_Ensure(); rv = PyObject_CallFunction(callback, "is#s#", reason, msg, msg_len, lang, lang_len); if (rv == NULL) PyErr_WriteUnraisable(callback); else Py_DECREF(rv); PyGILState_Release(gstate); } static int macerror_callback(LIBSSH2_SESSION *session, const char *packet, int packet_len, void **abstract) { PyObject *callback = ((SSH2_SessionObj *) *abstract)->cb_macerror; PyObject *rv; PyGILState_STATE gstate = PyGILState_Ensure(); int ret = -1; #if PY_MAJOR_VERSION < 3 rv = PyObject_CallFunction(callback, "s#", packet, packet_len); #else rv = PyObject_CallFunction(callback, "y#", packet, packet_len); #endif if (rv == NULL || (ret = PyObject_Not(rv)) == -1) PyErr_WriteUnraisable(callback); Py_XDECREF(rv); PyGILState_Release(gstate); return ret; } static void x11_callback(LIBSSH2_SESSION *session, LIBSSH2_CHANNEL *channel, const char *host, int port, void **abstract) { SSH2_SessionObj *session_obj = (SSH2_SessionObj *) *abstract; SSH2_ChannelObj *channel_obj = SSH2_Channel_New(channel, session_obj); PyObject *rv; PyGILState_STATE gstate = PyGILState_Ensure(); rv = PyObject_CallFunction(session_obj->cb_x11, "Osi", channel_obj, host, port); if (rv == NULL) PyErr_WriteUnraisable(session_obj->cb_x11); else Py_DECREF(rv); Py_DECREF(channel_obj); PyGILState_Release(gstate); } static PyObject * session_callback_set(SSH2_SessionObj *self, PyObject *args) { int type; PyObject* new_callback; PyObject* old_callback; void *raw_callback; if (!PyArg_ParseTuple(args, "iO:callback_set", &type, &new_callback)) return NULL; if (new_callback != Py_None && !PyCallable_Check(new_callback)) return PyErr_Format(PyExc_TypeError, "'%s' is not callable", new_callback->ob_type->tp_name); switch (type) { case LIBSSH2_CALLBACK_IGNORE: old_callback = self->cb_ignore; self->cb_ignore = new_callback; raw_callback = ignore_callback; break; case LIBSSH2_CALLBACK_DEBUG: old_callback = self->cb_debug; self->cb_debug = new_callback; raw_callback = debug_callback; break; case LIBSSH2_CALLBACK_DISCONNECT: old_callback = self->cb_disconnect; self->cb_disconnect = new_callback; raw_callback = disconnect_callback; break; case LIBSSH2_CALLBACK_MACERROR: old_callback = self->cb_macerror; self->cb_macerror = new_callback; raw_callback = macerror_callback; break; case LIBSSH2_CALLBACK_X11: old_callback = self->cb_x11; self->cb_x11 = new_callback; raw_callback = x11_callback; break; default: PyErr_SetString(PyExc_ValueError, "invalid callback type"); return NULL; } libssh2_session_callback_set(self->session, type, new_callback != Py_None ? raw_callback : NULL); Py_INCREF(new_callback); return old_callback; } static PyObject * session_channel(SSH2_SessionObj *self) { LIBSSH2_CHANNEL *channel; Py_BEGIN_ALLOW_THREADS channel = libssh2_channel_open_session(self->session); Py_END_ALLOW_THREADS CHECK_RETURN_POINTER(channel, self) return (PyObject *)SSH2_Channel_New(channel, self); } static PyObject * session_scp_recv(SSH2_SessionObj *self, PyObject *args, PyObject *kwds) { char *path; LIBSSH2_CHANNEL *channel; struct stat sb; PyObject* get_stat = NULL; int get_stat_is_true = 0; PyObject* chan; static char *kwlist[] = {"path", "get_stat", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:scp_recv", kwlist, &path, &get_stat)) return NULL; if (get_stat && (get_stat_is_true = PyObject_IsTrue(get_stat)) < 0) return NULL; Py_BEGIN_ALLOW_THREADS channel = libssh2_scp_recv(self->session, path, get_stat_is_true ? &sb : 0); Py_END_ALLOW_THREADS CHECK_RETURN_POINTER(channel, self) /* Return a tuple of the channel and (size, mode, mtime, atime) * of the remote file if the get_stat argument is true else return * a tuple of the channel and None. */ chan = (PyObject *)SSH2_Channel_New(channel, self); if (!get_stat_is_true) return Py_BuildValue("(OO)", chan, Py_None); return Py_BuildValue("(O(LlLL))", chan, (PY_LONG_LONG)sb.st_size, (long)sb.st_mode, (PY_LONG_LONG)sb.st_mtime, (PY_LONG_LONG)sb.st_atime); } static PyObject * session_scp_send(SSH2_SessionObj *self, PyObject *args) { char *path; int mode; unsigned long filesize; long mtime = 0; long atime = 0; LIBSSH2_CHANNEL *channel; if (!PyArg_ParseTuple(args, "sik|ll:scp_send", &path, &mode, &filesize, &mtime, &atime)) return NULL; Py_BEGIN_ALLOW_THREADS channel = libssh2_scp_send_ex(self->session, path, mode, filesize, mtime, atime); Py_END_ALLOW_THREADS CHECK_RETURN_POINTER(channel, self) return (PyObject *)SSH2_Channel_New(channel, self); } static PyObject * session_sftp(SSH2_SessionObj *self) { LIBSSH2_SFTP *sftp; Py_BEGIN_ALLOW_THREADS sftp = libssh2_sftp_init(self->session); Py_END_ALLOW_THREADS if (sftp == NULL) Py_RETURN_NONE; return (PyObject *)SSH2_SFTP_New(sftp, self); } static PyObject * session_direct_tcpip(SSH2_SessionObj *self, PyObject *args) { char *host; char *shost = "127.0.0.1"; int port; int sport = 22; LIBSSH2_CHANNEL *channel; if (!PyArg_ParseTuple(args, "si|si:direct_tcpip", &host, &port, &shost, &sport)) return NULL; Py_BEGIN_ALLOW_THREADS channel = libssh2_channel_direct_tcpip_ex(self->session, host, port, shost, sport); Py_END_ALLOW_THREADS CHECK_RETURN_POINTER(channel, self) return (PyObject *)SSH2_Channel_New(channel, self); } static PyObject * session_forward_listen(SSH2_SessionObj *self, PyObject *args) { char *host; int port; int queue_maxsize; int *bound_port; LIBSSH2_LISTENER *listener; if (!PyArg_ParseTuple(args, "siii:forward_listen", &host, &port, &bound_port, &queue_maxsize)) return NULL; Py_BEGIN_ALLOW_THREADS listener = libssh2_channel_forward_listen_ex(self->session, host, port, bound_port, queue_maxsize); Py_END_ALLOW_THREADS CHECK_RETURN_POINTER(listener, self) return (PyObject *)SSH2_Listener_New(listener, self); } #if LIBSSH2_VERSION_NUM >= 0x010205 static PyObject * session_keepalive_config(SSH2_SessionObj *self, PyObject *args) { int want_reply; unsigned int interval; if (!PyArg_ParseTuple(args, "iI:keepalive_config", &want_reply, &interval)) return NULL; libssh2_keepalive_config(self->session, want_reply, interval); Py_RETURN_NONE; } static PyObject * session_keepalive_send(SSH2_SessionObj *self) { int seconds_to_next; int ret; ret = libssh2_keepalive_send(self->session, &seconds_to_next); CHECK_RETURN_CODE(ret, self) return Py_BuildValue("i", seconds_to_next); } #endif static PyMethodDef session_methods[] = { {"banner_set", (PyCFunction)session_banner_set, METH_VARARGS}, {"startup", (PyCFunction)session_startup, METH_VARARGS}, {"disconnect", (PyCFunction)session_disconnect, METH_VARARGS | METH_KEYWORDS}, {"hostkey_hash", (PyCFunction)session_hostkey_hash, METH_VARARGS}, {"userauth_list", (PyCFunction)session_userauth_list, METH_VARARGS}, {"userauth_password", (PyCFunction)session_userauth_password, METH_VARARGS}, {"userauth_publickey_fromfile", (PyCFunction)session_userauth_publickey_fromfile, METH_VARARGS}, #if LIBSSH2_VERSION_NUM >= 0x010203 {"userauth_publickey", (PyCFunction)session_userauth_publickey, METH_VARARGS}, #endif {"userauth_hostbased_fromfile", (PyCFunction)session_userauth_hostbased_fromfile, METH_VARARGS}, {"userauth_keyboard_interactive", (PyCFunction)session_userauth_keyboard_interactive, METH_VARARGS}, {"methods", (PyCFunction)session_get_methods, METH_VARARGS}, {"method_pref", (PyCFunction)session_method_pref, METH_VARARGS}, {"callback_set", (PyCFunction)session_callback_set, METH_VARARGS}, {"channel", (PyCFunction)session_channel, METH_NOARGS}, {"scp_recv", (PyCFunction)session_scp_recv, METH_VARARGS | METH_KEYWORDS}, {"scp_send", (PyCFunction)session_scp_send, METH_VARARGS}, {"sftp", (PyCFunction)session_sftp, METH_NOARGS}, {"direct_tcpip", (PyCFunction)session_direct_tcpip, METH_VARARGS}, {"forward_listen", (PyCFunction)session_forward_listen, METH_VARARGS}, #if LIBSSH2_VERSION_NUM >= 0x010205 {"keepalive_config", (PyCFunction)session_keepalive_config, METH_VARARGS}, {"keepalive_send", (PyCFunction)session_keepalive_send, METH_NOARGS}, #endif {NULL, NULL} }; static PyObject * session_authenticated(SSH2_SessionObj *self) { return PyBool_FromLong(libssh2_userauth_authenticated(self->session)); } static PyObject * session_get_blocking(SSH2_SessionObj *self, void *closure) { return PyBool_FromLong(libssh2_session_get_blocking(self->session)); } static int session_set_blocking(SSH2_SessionObj *self, PyObject *value, void *closure) { libssh2_session_set_blocking(self->session, PyObject_IsTrue(value)); return 0; } #if LIBSSH2_VERSION_NUM >= 0x010209 static PyObject * session_get_timeout(SSH2_SessionObj *self, void *closure) { return Py_BuildValue("l", libssh2_session_get_timeout(self->session)); } static int session_set_timeout(SSH2_SessionObj *self, PyObject *value, void *closure) { long timeout = PyLong_AsLong(value); if (timeout == -1 && PyErr_Occurred()) { /* older versions of python don't set TypeError */ if (PyErr_ExceptionMatches(PyExc_SystemError)) PyErr_SetString(PyExc_TypeError, "an integer is required"); return -1; } libssh2_session_set_timeout(self->session, timeout); return 0; } #endif static PyGetSetDef session_getsets[] = { {"authenticated", (getter)session_authenticated, NULL, NULL}, {"blocking", (getter)session_get_blocking, (setter)session_set_blocking, NULL}, #if LIBSSH2_VERSION_NUM >= 0x010209 {"timeout", (getter)session_get_timeout, (setter)session_set_timeout, NULL}, #endif {NULL} }; static PyObject * session_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { return (PyObject *) SSH2_Session_New(libssh2_session_init()); } /* * Deallocate the memory used by the Session object * * Arguments: self - The Session object * Returns: None */ static void session_dealloc(SSH2_SessionObj *self) { if (self->opened) { Py_BEGIN_ALLOW_THREADS while (libssh2_session_disconnect(self->session, "") == LIBSSH2_ERROR_EAGAIN) {} Py_END_ALLOW_THREADS } libssh2_session_free(self->session); self->session = NULL; Py_CLEAR(self->socket); Py_CLEAR(self->cb_ignore); Py_CLEAR(self->cb_debug); Py_CLEAR(self->cb_disconnect); Py_CLEAR(self->cb_macerror); Py_CLEAR(self->cb_x11); Py_CLEAR(self->cb_passwd_changereq); Py_CLEAR(self->cb_kbdint_response); PyObject_Del(self); } PyTypeObject SSH2_Session_Type = { PyVarObject_HEAD_INIT(NULL, 0) "Session", /* tp_name */ sizeof(SSH2_SessionObj), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)session_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ session_methods, /* tp_methods */ 0, /* tp_members */ session_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ session_new, /* tp_new */ }; /* * Initialize the Session * * Arguments: module - The SSH2 module * Returns: None */ int init_SSH2_Session(PyObject *module) { if (PyType_Ready(&SSH2_Session_Type) != 0) return -1; Py_INCREF(&SSH2_Session_Type); if (PyModule_AddObject(module, "Session", (PyObject *)&SSH2_Session_Type) == 0) return 0; Py_DECREF(&SSH2_Session_Type); return -1; }
215
./ssh4py/src/listener.c
/* * listener.c * * Copyright (C) 2006 Keyphrene.com * Copyright (C) 2010-2011 Sebastian Noack * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ssh2.h" /* * Constructor for Listener objects, never called by Python code directly * * Arguments: listener - A listener object * session - The Python object reperesenting the session * Returns: The newly created listener object */ SSH2_ListenerObj * SSH2_Listener_New(LIBSSH2_LISTENER *listener, SSH2_SessionObj *session) { SSH2_ListenerObj *self; if ((self = PyObject_New(SSH2_ListenerObj, &SSH2_Listener_Type)) == NULL) return NULL; self->listener = listener; Py_INCREF(session); self->session = session; return self; } static PyObject * listener_accept(SSH2_ListenerObj *self) { LIBSSH2_CHANNEL *channel; Py_BEGIN_ALLOW_THREADS channel = libssh2_channel_forward_accept(self->listener); Py_END_ALLOW_THREADS CHECK_RETURN_POINTER(channel, self->session) return (PyObject *)SSH2_Channel_New(channel, self->session); } static PyObject * listener_cancel(SSH2_ListenerObj *self) { int ret; Py_BEGIN_ALLOW_THREADS ret = libssh2_channel_forward_cancel(self->listener); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyMethodDef listener_methods[] = { {"accept", (PyCFunction)listener_accept, METH_NOARGS}, {"cancel", (PyCFunction)listener_cancel, METH_NOARGS}, {NULL, NULL} }; /* * Deallocate the memory used by the Listener object * * Arguments: self - The Listener object * Returns: None */ static void listener_dealloc(SSH2_ListenerObj *self) { Py_CLEAR(self->session); PyObject_Del(self); } PyTypeObject SSH2_Listener_Type = { PyVarObject_HEAD_INIT(NULL, 0) "Listener", /* tp_name */ sizeof(SSH2_ListenerObj), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)listener_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ listener_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; /* * Initialize a Listener * * Arguments: module - The SSH2 module * Returns: None */ int init_SSH2_Listener(PyObject *module) { if (PyType_Ready(&SSH2_Listener_Type) != 0) return -1; Py_INCREF(&SSH2_Listener_Type); if (PyModule_AddObject(module, "Listener", (PyObject *)&SSH2_Listener_Type) == 0) return 0; Py_DECREF(&SSH2_Listener_Type); return -1; }
216
./ssh4py/src/sftphandle.c
/* * sftphandle.c * * Copyright (C) 2005 Keyphrene.com * Copyright (C) 2010-2011 Sebastian Noack * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ssh2.h" /* * Constructor for SFTP_handle objects, never called by Python code directly * * Arguments: cert - A "real" SFTP_handle certificate object * session - The Python object reperesenting the session * Returns: The newly created SFTP_handle object */ SSH2_SFTP_handleObj * SSH2_SFTP_handle_New(LIBSSH2_SFTP_HANDLE *sftphandle, SSH2_SessionObj *session) { SSH2_SFTP_handleObj *self; if ((self = PyObject_New(SSH2_SFTP_handleObj, &SSH2_SFTP_handle_Type)) == NULL) return NULL; self->sftphandle = sftphandle; Py_INCREF(session); self->session = session; return self; } static PyObject * SFTP_handle_close(SSH2_SFTP_handleObj *self) { int ret; Py_BEGIN_ALLOW_THREADS ret = libssh2_sftp_close_handle(self->sftphandle); Py_END_ALLOW_THREADS CHECK_RETURN_CODE(ret, self->session) Py_RETURN_NONE; } static PyMethodDef SFTP_handle_methods[] = { {"close", (PyCFunction)SFTP_handle_close, METH_NOARGS}, {NULL, NULL} }; /* * Deallocate the memory used by the SFTP_handle object * * Arguments: self - The SFTP_handle object * Returns: None */ static void SFTP_handle_dealloc(SSH2_SFTP_handleObj *self) { Py_BEGIN_ALLOW_THREADS while (libssh2_sftp_close_handle(self->sftphandle) == LIBSSH2_ERROR_EAGAIN) {} Py_END_ALLOW_THREADS Py_CLEAR(self->session); PyObject_Del(self); } PyTypeObject SSH2_SFTP_handle_Type = { PyVarObject_HEAD_INIT(NULL, 0) "SFTP_handle", /* tp_name */ sizeof(SSH2_SFTP_handleObj), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SFTP_handle_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ SFTP_handle_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; /* * Initialize the SFTP_handle * * Arguments: module - The SSH2 module * Returns: None */ int init_SSH2_SFTP_handle(PyObject *module) { if (PyType_Ready(&SSH2_SFTP_handle_Type) != 0) return -1; Py_INCREF(&SSH2_SFTP_handle_Type); if (PyModule_AddObject(module, "SFTP_handle", (PyObject *)&SSH2_SFTP_handle_Type) == 0) return 0; Py_DECREF(&SSH2_SFTP_handle_Type); return -1; }
217
./ssh4py/src/ssh2.c
/* * ssh.c * * Copyright (C) 2005 Keyphrene.com * Copyright (C) 2010-2011 Sebastian Noack * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ssh2.h" PyObject *SSH2_Error; #if PY_MAJOR_VERSION >= 3 struct PyModuleDef SSH2_moduledef = { PyModuleDef_HEAD_INIT, "libssh2", NULL, -1, NULL, NULL, NULL, NULL, NULL }; #endif /* * Initialize ssh sub module * * Arguments: None * Returns: None */ PyMODINIT_FUNC #if PY_MAJOR_VERSION >= 3 PyInit_libssh2(void) #else initlibssh2(void) #endif { PyObject *module; #if PY_MAJOR_VERSION >= 3 if ((module = PyModule_Create(&SSH2_moduledef)) == NULL) return NULL; #else if ((module = Py_InitModule("libssh2", NULL)) == NULL) return; #endif SSH2_Error = PyErr_NewException("libssh2.Error", NULL, NULL); if (SSH2_Error == NULL) goto error; if (PyModule_AddObject(module, "Error", SSH2_Error) != 0) goto error; PyModule_AddStringConstant(module, "__version__", MODULE_VERSION); // for getFingerprint PyModule_AddIntConstant(module, "FINGERPRINT_MD5", 0x0000); PyModule_AddIntConstant(module, "FINGERPRINT_SHA1", 0x0001); PyModule_AddIntConstant(module, "FINGERPRINT_HEX", 0x0000); PyModule_AddIntConstant(module, "FINGERPRINT_RAW", 0x0002); // for getFingerprint PyModule_AddIntConstant(module, "HOSTKEY_HASH_MD5", LIBSSH2_HOSTKEY_HASH_MD5); PyModule_AddIntConstant(module, "HOSTKEY_HASH_SHA1", LIBSSH2_HOSTKEY_HASH_SHA1); // methods PyModule_AddIntConstant(module, "METHOD_KEX", LIBSSH2_METHOD_KEX); PyModule_AddIntConstant(module, "METHOD_HOSTKEY", LIBSSH2_METHOD_HOSTKEY); PyModule_AddIntConstant(module, "METHOD_CRYPT_CS", LIBSSH2_METHOD_CRYPT_CS); PyModule_AddIntConstant(module, "METHOD_CRYPT_SC", LIBSSH2_METHOD_CRYPT_SC); PyModule_AddIntConstant(module, "METHOD_MAC_CS", LIBSSH2_METHOD_MAC_CS); PyModule_AddIntConstant(module, "METHOD_MAC_SC", LIBSSH2_METHOD_MAC_SC); PyModule_AddIntConstant(module, "METHOD_COMP_CS", LIBSSH2_METHOD_COMP_CS); PyModule_AddIntConstant(module, "METHOD_COMP_SC", LIBSSH2_METHOD_COMP_SC); PyModule_AddIntConstant(module, "METHOD_LANG_CS", LIBSSH2_METHOD_LANG_CS); PyModule_AddIntConstant(module, "METHOD_LANG_SC", LIBSSH2_METHOD_LANG_SC); PyModule_AddIntConstant(module, "SFTP_STAT", LIBSSH2_SFTP_STAT); PyModule_AddIntConstant(module, "SFTP_LSTAT", LIBSSH2_SFTP_LSTAT); PyModule_AddStringConstant(module, "DEFAULT_BANNER", LIBSSH2_SSH_DEFAULT_BANNER); PyModule_AddStringConstant(module, "LIBSSH2_VERSION", LIBSSH2_VERSION); PyModule_AddIntConstant(module, "CALLBACK_IGNORE", LIBSSH2_CALLBACK_IGNORE); PyModule_AddIntConstant(module, "CALLBACK_DEBUG", LIBSSH2_CALLBACK_DEBUG); PyModule_AddIntConstant(module, "CALLBACK_DISCONNECT", LIBSSH2_CALLBACK_DISCONNECT); PyModule_AddIntConstant(module, "CALLBACK_MACERROR", LIBSSH2_CALLBACK_MACERROR); PyModule_AddIntConstant(module, "CALLBACK_X11", LIBSSH2_CALLBACK_X11); PyModule_AddIntConstant(module, "ERROR_SOCKET_NONE", LIBSSH2_ERROR_SOCKET_NONE); PyModule_AddIntConstant(module, "ERROR_BANNER_NONE", LIBSSH2_ERROR_BANNER_NONE); PyModule_AddIntConstant(module, "ERROR_BANNER_SEND", LIBSSH2_ERROR_BANNER_SEND); PyModule_AddIntConstant(module, "ERROR_INVALID_MAC", LIBSSH2_ERROR_INVALID_MAC); PyModule_AddIntConstant(module, "ERROR_KEX_FAILURE", LIBSSH2_ERROR_KEX_FAILURE); PyModule_AddIntConstant(module, "ERROR_ALLOC", LIBSSH2_ERROR_ALLOC); PyModule_AddIntConstant(module, "ERROR_SOCKET_SEND", LIBSSH2_ERROR_SOCKET_SEND); PyModule_AddIntConstant(module, "ERROR_KEY_EXCHANGE_FAILURE", LIBSSH2_ERROR_KEY_EXCHANGE_FAILURE); PyModule_AddIntConstant(module, "ERROR_TIMEOUT", LIBSSH2_ERROR_TIMEOUT); PyModule_AddIntConstant(module, "ERROR_HOSTKEY_INIT", LIBSSH2_ERROR_HOSTKEY_INIT); PyModule_AddIntConstant(module, "ERROR_HOSTKEY_SIGN", LIBSSH2_ERROR_HOSTKEY_SIGN); PyModule_AddIntConstant(module, "ERROR_DECRYPT", LIBSSH2_ERROR_DECRYPT); PyModule_AddIntConstant(module, "ERROR_SOCKET_DISCONNECT", LIBSSH2_ERROR_SOCKET_DISCONNECT); PyModule_AddIntConstant(module, "ERROR_PROTO", LIBSSH2_ERROR_PROTO); PyModule_AddIntConstant(module, "ERROR_PASSWORD_EXPIRED", LIBSSH2_ERROR_PASSWORD_EXPIRED); PyModule_AddIntConstant(module, "ERROR_FILE", LIBSSH2_ERROR_FILE); PyModule_AddIntConstant(module, "ERROR_METHOD_NONE", LIBSSH2_ERROR_METHOD_NONE); PyModule_AddIntConstant(module, "ERROR_PUBLICKEY_UNRECOGNIZED", LIBSSH2_ERROR_PUBLICKEY_UNRECOGNIZED); PyModule_AddIntConstant(module, "ERROR_PUBLICKEY_UNVERIFIED", LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED); PyModule_AddIntConstant(module, "ERROR_CHANNEL_OUTOFORDER", LIBSSH2_ERROR_CHANNEL_OUTOFORDER); PyModule_AddIntConstant(module, "ERROR_CHANNEL_FAILURE", LIBSSH2_ERROR_CHANNEL_FAILURE); PyModule_AddIntConstant(module, "ERROR_CHANNEL_REQUEST_DENIED", LIBSSH2_ERROR_CHANNEL_REQUEST_DENIED); PyModule_AddIntConstant(module, "ERROR_CHANNEL_UNKNOWN", LIBSSH2_ERROR_CHANNEL_UNKNOWN); PyModule_AddIntConstant(module, "ERROR_CHANNEL_WINDOW_EXCEEDED", LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED); PyModule_AddIntConstant(module, "ERROR_CHANNEL_PACKET_EXCEEDED", LIBSSH2_ERROR_CHANNEL_PACKET_EXCEEDED); PyModule_AddIntConstant(module, "ERROR_CHANNEL_CLOSED", LIBSSH2_ERROR_CHANNEL_CLOSED); PyModule_AddIntConstant(module, "ERROR_CHANNEL_EOF_SENT", LIBSSH2_ERROR_CHANNEL_EOF_SENT); PyModule_AddIntConstant(module, "ERROR_SCP_PROTOCOL", LIBSSH2_ERROR_SCP_PROTOCOL); PyModule_AddIntConstant(module, "ERROR_ZLIB", LIBSSH2_ERROR_ZLIB); PyModule_AddIntConstant(module, "ERROR_SOCKET_TIMEOUT", LIBSSH2_ERROR_SOCKET_TIMEOUT); PyModule_AddIntConstant(module, "ERROR_SFTP_PROTOCOL", LIBSSH2_ERROR_SFTP_PROTOCOL); PyModule_AddIntConstant(module, "ERROR_REQUEST_DENIED", LIBSSH2_ERROR_REQUEST_DENIED); PyModule_AddIntConstant(module, "ERROR_METHOD_NOT_SUPPORTED", LIBSSH2_ERROR_METHOD_NOT_SUPPORTED); PyModule_AddIntConstant(module, "ERROR_INVAL", LIBSSH2_ERROR_INVAL); PyModule_AddIntConstant(module, "ERROR_INVALID_POLL_TYPE", LIBSSH2_ERROR_INVALID_POLL_TYPE); PyModule_AddIntConstant(module, "ERROR_PUBLICKEY_PROTOCOL", LIBSSH2_ERROR_PUBLICKEY_PROTOCOL); PyModule_AddIntConstant(module, "ERROR_EAGAIN", LIBSSH2_ERROR_EAGAIN); PyModule_AddIntConstant(module, "ERROR_BUFFER_TOO_SMALL", LIBSSH2_ERROR_BUFFER_TOO_SMALL); PyModule_AddIntConstant(module, "ERROR_BAD_USE", LIBSSH2_ERROR_BAD_USE); PyModule_AddIntConstant(module, "ERROR_COMPRESS", LIBSSH2_ERROR_COMPRESS); PyModule_AddIntConstant(module, "ERROR_OUT_OF_BOUNDARY", LIBSSH2_ERROR_OUT_OF_BOUNDARY); #if LIBSSH2_VERSION_NUM >= 0x010203 PyModule_AddIntConstant(module, "ERROR_AUTHENTICATION_FAILED", LIBSSH2_ERROR_AUTHENTICATION_FAILED); PyModule_AddIntConstant(module, "ERROR_AGENT_PROTOCOL", LIBSSH2_ERROR_AGENT_PROTOCOL); #endif PyModule_AddIntConstant(module, "STDERR", SSH_EXTENDED_DATA_STDERR); if (init_SSH2_Session(module) != 0) goto error; if (init_SSH2_Channel(module) != 0) goto error; if (init_SSH2_SFTP(module) != 0) goto error; if (init_SSH2_SFTP_handle(module) != 0) goto error; if (init_SSH2_Listener(module) != 0) goto error; #if PY_MAJOR_VERSION >= 3 return module; #else return; #endif error: Py_DECREF(module); #if PY_MAJOR_VERSION >= 3 return NULL; #endif }
218
./objective-zip/MiniZip/ioapi.c
/* ioapi.c -- IO base function header for compress/uncompress .zip files using zlib + zip or unzip API Version 1.01e, February 12th, 2005 Copyright (C) 1998-2005 Gilles Vollant */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "zlib.h" #include "ioapi.h" /* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */ #ifndef SEEK_CUR #define SEEK_CUR 1 #endif #ifndef SEEK_END #define SEEK_END 2 #endif #ifndef SEEK_SET #define SEEK_SET 0 #endif voidpf ZCALLBACK fopen_file_func OF(( voidpf opaque, const char* filename, int mode)); uLong ZCALLBACK fread_file_func OF(( voidpf opaque, voidpf stream, void* buf, uLong size)); uLong ZCALLBACK fwrite_file_func OF(( voidpf opaque, voidpf stream, const void* buf, uLong size)); long ZCALLBACK ftell_file_func OF(( voidpf opaque, voidpf stream)); long ZCALLBACK fseek_file_func OF(( voidpf opaque, voidpf stream, uLong offset, int origin)); int ZCALLBACK fclose_file_func OF(( voidpf opaque, voidpf stream)); int ZCALLBACK ferror_file_func OF(( voidpf opaque, voidpf stream)); voidpf ZCALLBACK fopen_file_func (opaque, filename, mode) voidpf opaque; const char* filename; int mode; { FILE* file = NULL; const char* mode_fopen = NULL; if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) mode_fopen = "rb"; else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) mode_fopen = "r+b"; else if (mode & ZLIB_FILEFUNC_MODE_CREATE) mode_fopen = "wb"; if ((filename!=NULL) && (mode_fopen != NULL)) file = fopen(filename, mode_fopen); return file; } uLong ZCALLBACK fread_file_func (opaque, stream, buf, size) voidpf opaque; voidpf stream; void* buf; uLong size; { uLong ret; ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream); return ret; } uLong ZCALLBACK fwrite_file_func (opaque, stream, buf, size) voidpf opaque; voidpf stream; const void* buf; uLong size; { uLong ret; ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream); return ret; } long ZCALLBACK ftell_file_func (opaque, stream) voidpf opaque; voidpf stream; { long ret; ret = ftell((FILE *)stream); return ret; } long ZCALLBACK fseek_file_func (opaque, stream, offset, origin) voidpf opaque; voidpf stream; uLong offset; int origin; { int fseek_origin=0; long ret; switch (origin) { case ZLIB_FILEFUNC_SEEK_CUR : fseek_origin = SEEK_CUR; break; case ZLIB_FILEFUNC_SEEK_END : fseek_origin = SEEK_END; break; case ZLIB_FILEFUNC_SEEK_SET : fseek_origin = SEEK_SET; break; default: return -1; } ret = 0; fseek((FILE *)stream, offset, fseek_origin); return ret; } int ZCALLBACK fclose_file_func (opaque, stream) voidpf opaque; voidpf stream; { int ret; ret = fclose((FILE *)stream); return ret; } int ZCALLBACK ferror_file_func (opaque, stream) voidpf opaque; voidpf stream; { int ret; ret = ferror((FILE *)stream); return ret; } void fill_fopen_filefunc (pzlib_filefunc_def) zlib_filefunc_def* pzlib_filefunc_def; { pzlib_filefunc_def->zopen_file = fopen_file_func; pzlib_filefunc_def->zread_file = fread_file_func; pzlib_filefunc_def->zwrite_file = fwrite_file_func; pzlib_filefunc_def->ztell_file = ftell_file_func; pzlib_filefunc_def->zseek_file = fseek_file_func; pzlib_filefunc_def->zclose_file = fclose_file_func; pzlib_filefunc_def->zerror_file = ferror_file_func; pzlib_filefunc_def->opaque = NULL; }
219
./objective-zip/MiniZip/unzip.c
/* unzip.c -- IO for uncompress .zip files using zlib Version 1.01e, February 12th, 2005 Copyright (C) 1998-2005 Gilles Vollant Read unzip.h for more info */ /* Decryption code comes from crypt.c by Info-ZIP but has been greatly reduced in terms of compatibility with older software. The following is from the original crypt.c. Code woven in by Terry Thorsen 1/2003. */ /* Copyright (c) 1990-2000 Info-ZIP. All rights reserved. See the accompanying file LICENSE, version 2000-Apr-09 or later (the contents of which are also included in zip.h) for terms of use. If, for some reason, all these files are missing, the Info-ZIP license also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html */ /* crypt.c (full version) by Info-ZIP. Last revised: [see crypt.h] The encryption/decryption parts of this source code (as opposed to the non-echoing password parts) were originally written in Europe. The whole source package can be freely distributed, including from the USA. (Prior to January 2000, re-export from the US was a violation of US law.) */ /* This encryption code is a direct transcription of the algorithm from Roger Schlafly, described by Phil Katz in the file appnote.txt. This file (appnote.txt) is distributed with the PKZIP program (even in the version without encryption capabilities). */ #define NOCRYPT #define NOUNCRYPT #include <stdio.h> #include <stdlib.h> #include <string.h> #include "zlib.h" #include "unzip.h" #ifdef STDC # include <stddef.h> # include <string.h> # include <stdlib.h> #endif #ifdef NO_ERRNO_H extern int errno; #else # include <errno.h> #endif #ifndef local # define local static #endif /* compile with -Dlocal if your debugger can't find static symbols */ #ifndef CASESENSITIVITYDEFAULT_NO # if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) # define CASESENSITIVITYDEFAULT_NO # endif #endif #ifndef UNZ_BUFSIZE #define UNZ_BUFSIZE (16384) #endif #ifndef UNZ_MAXFILENAMEINZIP #define UNZ_MAXFILENAMEINZIP (256) #endif #ifndef ALLOC # define ALLOC(size) (malloc(size)) #endif #ifndef TRYFREE # define TRYFREE(p) {if (p) free(p);} #endif #define SIZECENTRALDIRITEM (0x2e) #define SIZEZIPLOCALHEADER (0x1e) const char unz_copyright[] = " unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; /* unz_file_info_interntal contain internal info about a file in zipfile*/ typedef struct unz_file_info_internal_s { uLong offset_curfile;/* relative offset of local header 4 bytes */ } unz_file_info_internal; /* file_in_zip_read_info_s contain internal information about a file in zipfile, when reading and decompress it */ typedef struct { char *read_buffer; /* internal buffer for compressed data */ z_stream stream; /* zLib stream structure for inflate */ uLong pos_in_zipfile; /* position in byte on the zipfile, for fseek*/ uLong stream_initialised; /* flag set if stream structure is initialised*/ uLong offset_local_extrafield;/* offset of the local extra field */ uInt size_local_extrafield;/* size of the local extra field */ uLong pos_local_extrafield; /* position in the local extra field in read*/ uLong crc32; /* crc32 of all data uncompressed */ uLong crc32_wait; /* crc32 we must obtain after decompress all */ uLong rest_read_compressed; /* number of byte to be decompressed */ uLong rest_read_uncompressed;/*number of byte to be obtained after decomp*/ zlib_filefunc_def z_filefunc; voidpf filestream; /* io structore of the zipfile */ uLong compression_method; /* compression method (0==store) */ uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ int raw; } file_in_zip_read_info_s; /* unz_s contain internal information about the zipfile */ typedef struct { zlib_filefunc_def z_filefunc; voidpf filestream; /* io structore of the zipfile */ unz_global_info gi; /* public global information */ uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ uLong num_file; /* number of the current file in the zipfile*/ uLong pos_in_central_dir; /* pos of the current file in the central dir*/ uLong current_file_ok; /* flag about the usability of the current file*/ uLong central_pos; /* position of the beginning of the central dir*/ uLong size_central_dir; /* size of the central directory */ uLong offset_central_dir; /* offset of start of central directory with respect to the starting disk number */ unz_file_info cur_file_info; /* public info about the current file in zip*/ unz_file_info_internal cur_file_info_internal; /* private info about it*/ file_in_zip_read_info_s* pfile_in_zip_read; /* structure about the current file if we are decompressing it */ int encrypted; # ifndef NOUNCRYPT unsigned long keys[3]; /* keys defining the pseudo-random sequence */ const unsigned long* pcrc_32_tab; # endif } unz_s; #ifndef NOUNCRYPT #include "crypt.h" #endif /* =========================================================================== Read a byte from a gz_stream; update next_in and avail_in. Return EOF for end of file. IN assertion: the stream s has been sucessfully opened for reading. */ local int unzlocal_getByte OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, int *pi)); local int unzlocal_getByte(pzlib_filefunc_def,filestream,pi) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; int *pi; { unsigned char c; int err = (int)ZREAD(*pzlib_filefunc_def,filestream,&c,1); if (err==1) { *pi = (int)c; return UNZ_OK; } else { if (ZERROR(*pzlib_filefunc_def,filestream)) return UNZ_ERRNO; else return UNZ_EOF; } } /* =========================================================================== Reads a long in LSB order from the given gz_stream. Sets */ local int unzlocal_getShort OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); local int unzlocal_getShort (pzlib_filefunc_def,filestream,pX) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; uLong *pX; { uLong x ; int i; int err; err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); x = (uLong)i; if (err==UNZ_OK) err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<8; if (err==UNZ_OK) *pX = x; else *pX = 0; return err; } local int unzlocal_getLong OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); local int unzlocal_getLong (pzlib_filefunc_def,filestream,pX) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; uLong *pX; { uLong x ; int i; int err; err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); x = (uLong)i; if (err==UNZ_OK) err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<8; if (err==UNZ_OK) err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<16; if (err==UNZ_OK) err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<24; if (err==UNZ_OK) *pX = x; else *pX = 0; return err; } /* My own strcmpi / strcasecmp */ local int strcmpcasenosensitive_internal (fileName1,fileName2) const char* fileName1; const char* fileName2; { for (;;) { char c1=*(fileName1++); char c2=*(fileName2++); if ((c1>='a') && (c1<='z')) c1 -= 0x20; if ((c2>='a') && (c2<='z')) c2 -= 0x20; if (c1=='\0') return ((c2=='\0') ? 0 : -1); if (c2=='\0') return 1; if (c1<c2) return -1; if (c1>c2) return 1; } } #ifdef CASESENSITIVITYDEFAULT_NO #define CASESENSITIVITYDEFAULTVALUE 2 #else #define CASESENSITIVITYDEFAULTVALUE 1 #endif #ifndef STRCMPCASENOSENTIVEFUNCTION #define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal #endif /* Compare two filename (fileName1,fileName2). If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi or strcasecmp) If iCaseSenisivity = 0, case sensitivity is defaut of your operating system (like 1 on Unix, 2 on Windows) */ extern int ZEXPORT unzStringFileNameCompare (fileName1,fileName2,iCaseSensitivity) const char* fileName1; const char* fileName2; int iCaseSensitivity; { if (iCaseSensitivity==0) iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE; if (iCaseSensitivity==1) return strcmp(fileName1,fileName2); return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2); } #ifndef BUFREADCOMMENT #define BUFREADCOMMENT (0x400) #endif /* Locate the Central directory of a zipfile (at the end, just before the global comment) */ local uLong unzlocal_SearchCentralDir OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream)); local uLong unzlocal_SearchCentralDir(pzlib_filefunc_def,filestream) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; { unsigned char* buf; uLong uSizeFile; uLong uBackRead; uLong uMaxBack=0xffff; /* maximum size of global comment */ uLong uPosFound=0; if (ZSEEK(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) return 0; uSizeFile = ZTELL(*pzlib_filefunc_def,filestream); if (uMaxBack>uSizeFile) uMaxBack = uSizeFile; buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); if (buf==NULL) return 0; uBackRead = 4; while (uBackRead<uMaxBack) { uLong uReadSize,uReadPos ; int i; if (uBackRead+BUFREADCOMMENT>uMaxBack) uBackRead = uMaxBack; else uBackRead+=BUFREADCOMMENT; uReadPos = uSizeFile-uBackRead ; uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? (BUFREADCOMMENT+4) : (uSizeFile-uReadPos); if (ZSEEK(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) break; if (ZREAD(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) break; for (i=(int)uReadSize-3; (i--)>0;) if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) { uPosFound = uReadPos+i; break; } if (uPosFound!=0) break; } TRYFREE(buf); return uPosFound; } /* Open a Zip file. path contain the full pathname (by example, on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer "zlib/zlib114.zip". If the zipfile cannot be opened (file doesn't exist or in not valid), the return value is NULL. Else, the return value is a unzFile Handle, usable with other function of this unzip package. */ extern unzFile ZEXPORT unzOpen2 (path, pzlib_filefunc_def) const char *path; zlib_filefunc_def* pzlib_filefunc_def; { unz_s us; unz_s *s; uLong central_pos,uL; uLong number_disk; /* number of the current dist, used for spaning ZIP, unsupported, always 0*/ uLong number_disk_with_CD; /* number the the disk with central dir, used for spaning ZIP, unsupported, always 0*/ uLong number_entry_CD; /* total number of entries in the central dir (same than number_entry on nospan) */ int err=UNZ_OK; if (unz_copyright[0]!=' ') return NULL; if (pzlib_filefunc_def==NULL) fill_fopen_filefunc(&us.z_filefunc); else us.z_filefunc = *pzlib_filefunc_def; us.filestream= (*(us.z_filefunc.zopen_file))(us.z_filefunc.opaque, path, ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_EXISTING); if (us.filestream==NULL) return NULL; central_pos = unzlocal_SearchCentralDir(&us.z_filefunc,us.filestream); if (central_pos==0) err=UNZ_ERRNO; if (ZSEEK(us.z_filefunc, us.filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) err=UNZ_ERRNO; /* the signature, already checked */ if (unzlocal_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) err=UNZ_ERRNO; /* number of this disk */ if (unzlocal_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK) err=UNZ_ERRNO; /* number of the disk with the start of the central directory */ if (unzlocal_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK) err=UNZ_ERRNO; /* total number of entries in the central dir on this disk */ if (unzlocal_getShort(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK) err=UNZ_ERRNO; /* total number of entries in the central dir */ if (unzlocal_getShort(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK) err=UNZ_ERRNO; if ((number_entry_CD!=us.gi.number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) err=UNZ_BADZIPFILE; /* size of the central directory */ if (unzlocal_getLong(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK) err=UNZ_ERRNO; /* offset of start of central directory with respect to the starting disk number */ if (unzlocal_getLong(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK) err=UNZ_ERRNO; /* zipfile comment length */ if (unzlocal_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK) err=UNZ_ERRNO; if ((central_pos<us.offset_central_dir+us.size_central_dir) && (err==UNZ_OK)) err=UNZ_BADZIPFILE; if (err!=UNZ_OK) { ZCLOSE(us.z_filefunc, us.filestream); return NULL; } us.byte_before_the_zipfile = central_pos - (us.offset_central_dir+us.size_central_dir); us.central_pos = central_pos; us.pfile_in_zip_read = NULL; us.encrypted = 0; s=(unz_s*)ALLOC(sizeof(unz_s)); *s=us; unzGoToFirstFile((unzFile)s); return (unzFile)s; } extern unzFile ZEXPORT unzOpen (path) const char *path; { return unzOpen2(path, NULL); } /* Close a ZipFile opened with unzipOpen. If there is files inside the .Zip opened with unzipOpenCurrentFile (see later), these files MUST be closed with unzipCloseCurrentFile before call unzipClose. return UNZ_OK if there is no problem. */ extern int ZEXPORT unzClose (file) unzFile file; { unz_s* s; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (s->pfile_in_zip_read!=NULL) unzCloseCurrentFile(file); ZCLOSE(s->z_filefunc, s->filestream); TRYFREE(s); return UNZ_OK; } /* Write info about the ZipFile in the *pglobal_info structure. No preparation of the structure is needed return UNZ_OK if there is no problem. */ extern int ZEXPORT unzGetGlobalInfo (file,pglobal_info) unzFile file; unz_global_info *pglobal_info; { unz_s* s; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; *pglobal_info=s->gi; return UNZ_OK; } /* Translate date/time from Dos format to tm_unz (readable more easilty) */ local void unzlocal_DosDateToTmuDate (ulDosDate, ptm) uLong ulDosDate; tm_unz* ptm; { uLong uDate; uDate = (uLong)(ulDosDate>>16); ptm->tm_mday = (uInt)(uDate&0x1f) ; ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ; ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ; ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800); ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ; ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ; } /* Get Info about the current file in the zipfile, with internal only info */ local int unzlocal_GetCurrentFileInfoInternal OF((unzFile file, unz_file_info *pfile_info, unz_file_info_internal *pfile_info_internal, char *szFileName, uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize, char *szComment, uLong commentBufferSize)); local int unzlocal_GetCurrentFileInfoInternal (file, pfile_info, pfile_info_internal, szFileName, fileNameBufferSize, extraField, extraFieldBufferSize, szComment, commentBufferSize) unzFile file; unz_file_info *pfile_info; unz_file_info_internal *pfile_info_internal; char *szFileName; uLong fileNameBufferSize; void *extraField; uLong extraFieldBufferSize; char *szComment; uLong commentBufferSize; { unz_s* s; unz_file_info file_info; unz_file_info_internal file_info_internal; int err=UNZ_OK; uLong uMagic; long lSeek=0; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (ZSEEK(s->z_filefunc, s->filestream, s->pos_in_central_dir+s->byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET)!=0) err=UNZ_ERRNO; /* we check the magic */ if (err==UNZ_OK) { if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) err=UNZ_ERRNO; else if (uMagic!=0x02014b50) err=UNZ_BADZIPFILE; } if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.version) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.version_needed) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.flag) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.compression_method) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.dosDate) != UNZ_OK) err=UNZ_ERRNO; unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date); if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.crc) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.compressed_size) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.uncompressed_size) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.size_filename) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_extra) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_comment) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.disk_num_start) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.internal_fa) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.external_fa) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info_internal.offset_curfile) != UNZ_OK) err=UNZ_ERRNO; lSeek+=file_info.size_filename; if ((err==UNZ_OK) && (szFileName!=NULL)) { uLong uSizeRead ; if (file_info.size_filename<fileNameBufferSize) { *(szFileName+file_info.size_filename)='\0'; uSizeRead = file_info.size_filename; } else uSizeRead = fileNameBufferSize; if ((file_info.size_filename>0) && (fileNameBufferSize>0)) if (ZREAD(s->z_filefunc, s->filestream,szFileName,uSizeRead)!=uSizeRead) err=UNZ_ERRNO; lSeek -= uSizeRead; } if ((err==UNZ_OK) && (extraField!=NULL)) { uLong uSizeRead ; if (file_info.size_file_extra<extraFieldBufferSize) uSizeRead = file_info.size_file_extra; else uSizeRead = extraFieldBufferSize; if (lSeek!=0) { if (ZSEEK(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) lSeek=0; else err=UNZ_ERRNO; } if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0)) if (ZREAD(s->z_filefunc, s->filestream,extraField,uSizeRead)!=uSizeRead) err=UNZ_ERRNO; lSeek += file_info.size_file_extra - uSizeRead; } else lSeek+=file_info.size_file_extra; if ((err==UNZ_OK) && (szComment!=NULL)) { uLong uSizeRead ; if (file_info.size_file_comment<commentBufferSize) { *(szComment+file_info.size_file_comment)='\0'; uSizeRead = file_info.size_file_comment; } else uSizeRead = commentBufferSize; if (lSeek!=0) { if (ZSEEK(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) lSeek=0; else err=UNZ_ERRNO; } if ((file_info.size_file_comment>0) && (commentBufferSize>0)) if (ZREAD(s->z_filefunc, s->filestream,szComment,uSizeRead)!=uSizeRead) err=UNZ_ERRNO; lSeek+=file_info.size_file_comment - uSizeRead; } else lSeek+=file_info.size_file_comment; if ((err==UNZ_OK) && (pfile_info!=NULL)) *pfile_info=file_info; if ((err==UNZ_OK) && (pfile_info_internal!=NULL)) *pfile_info_internal=file_info_internal; return err; } /* Write info about the ZipFile in the *pglobal_info structure. No preparation of the structure is needed return UNZ_OK if there is no problem. */ extern int ZEXPORT unzGetCurrentFileInfo (file, pfile_info, szFileName, fileNameBufferSize, extraField, extraFieldBufferSize, szComment, commentBufferSize) unzFile file; unz_file_info *pfile_info; char *szFileName; uLong fileNameBufferSize; void *extraField; uLong extraFieldBufferSize; char *szComment; uLong commentBufferSize; { return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL, szFileName,fileNameBufferSize, extraField,extraFieldBufferSize, szComment,commentBufferSize); } /* Set the current file of the zipfile to the first file. return UNZ_OK if there is no problem */ extern int ZEXPORT unzGoToFirstFile (file) unzFile file; { int err=UNZ_OK; unz_s* s; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; s->pos_in_central_dir=s->offset_central_dir; s->num_file=0; err=unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, &s->cur_file_info_internal, NULL,0,NULL,0,NULL,0); s->current_file_ok = (err == UNZ_OK); return err; } /* Set the current file of the zipfile to the next file. return UNZ_OK if there is no problem return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. */ extern int ZEXPORT unzGoToNextFile (file) unzFile file; { unz_s* s; int err; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (!s->current_file_ok) return UNZ_END_OF_LIST_OF_FILE; if (s->gi.number_entry != 0xffff) /* 2^16 files overflow hack */ if (s->num_file+1==s->gi.number_entry) return UNZ_END_OF_LIST_OF_FILE; s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ; s->num_file++; err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, &s->cur_file_info_internal, NULL,0,NULL,0,NULL,0); s->current_file_ok = (err == UNZ_OK); return err; } /* Try locate the file szFileName in the zipfile. For the iCaseSensitivity signification, see unzipStringFileNameCompare return value : UNZ_OK if the file is found. It becomes the current file. UNZ_END_OF_LIST_OF_FILE if the file is not found */ extern int ZEXPORT unzLocateFile (file, szFileName, iCaseSensitivity) unzFile file; const char *szFileName; int iCaseSensitivity; { unz_s* s; int err; /* We remember the 'current' position in the file so that we can jump * back there if we fail. */ unz_file_info cur_file_infoSaved; unz_file_info_internal cur_file_info_internalSaved; uLong num_fileSaved; uLong pos_in_central_dirSaved; if (file==NULL) return UNZ_PARAMERROR; if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP) return UNZ_PARAMERROR; s=(unz_s*)file; if (!s->current_file_ok) return UNZ_END_OF_LIST_OF_FILE; /* Save the current state */ num_fileSaved = s->num_file; pos_in_central_dirSaved = s->pos_in_central_dir; cur_file_infoSaved = s->cur_file_info; cur_file_info_internalSaved = s->cur_file_info_internal; err = unzGoToFirstFile(file); while (err == UNZ_OK) { char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; err = unzGetCurrentFileInfo(file,NULL, szCurrentFileName,sizeof(szCurrentFileName)-1, NULL,0,NULL,0); if (err == UNZ_OK) { if (unzStringFileNameCompare(szCurrentFileName, szFileName,iCaseSensitivity)==0) return UNZ_OK; err = unzGoToNextFile(file); } } /* We failed, so restore the state of the 'current file' to where we * were. */ s->num_file = num_fileSaved ; s->pos_in_central_dir = pos_in_central_dirSaved ; s->cur_file_info = cur_file_infoSaved; s->cur_file_info_internal = cur_file_info_internalSaved; return err; } /* /////////////////////////////////////////// // Contributed by Ryan Haksi (mailto://[email protected]) // I need random access // // Further optimization could be realized by adding an ability // to cache the directory in memory. The goal being a single // comprehensive file read to put the file I need in a memory. */ /* typedef struct unz_file_pos_s { uLong pos_in_zip_directory; // offset in file uLong num_of_file; // # of file } unz_file_pos; */ extern int ZEXPORT unzGetFilePos(file, file_pos) unzFile file; unz_file_pos* file_pos; { unz_s* s; if (file==NULL || file_pos==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (!s->current_file_ok) return UNZ_END_OF_LIST_OF_FILE; file_pos->pos_in_zip_directory = s->pos_in_central_dir; file_pos->num_of_file = s->num_file; return UNZ_OK; } extern int ZEXPORT unzGoToFilePos(file, file_pos) unzFile file; unz_file_pos* file_pos; { unz_s* s; int err; if (file==NULL || file_pos==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; /* jump to the right spot */ s->pos_in_central_dir = file_pos->pos_in_zip_directory; s->num_file = file_pos->num_of_file; /* set the current file */ err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, &s->cur_file_info_internal, NULL,0,NULL,0,NULL,0); /* return results */ s->current_file_ok = (err == UNZ_OK); return err; } /* // Unzip Helper Functions - should be here? /////////////////////////////////////////// */ /* Read the local header of the current zipfile Check the coherency of the local header and info in the end of central directory about this file store in *piSizeVar the size of extra info in local header (filename and size of extra field data) */ local int unzlocal_CheckCurrentFileCoherencyHeader (s,piSizeVar, poffset_local_extrafield, psize_local_extrafield) unz_s* s; uInt* piSizeVar; uLong *poffset_local_extrafield; uInt *psize_local_extrafield; { uLong uMagic,uData,uFlags; uLong size_filename; uLong size_extra_field; int err=UNZ_OK; *piSizeVar = 0; *poffset_local_extrafield = 0; *psize_local_extrafield = 0; if (ZSEEK(s->z_filefunc, s->filestream,s->cur_file_info_internal.offset_curfile + s->byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0) return UNZ_ERRNO; if (err==UNZ_OK) { if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) err=UNZ_ERRNO; else if (uMagic!=0x04034b50) err=UNZ_BADZIPFILE; } if (unzlocal_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) err=UNZ_ERRNO; /* else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) err=UNZ_BADZIPFILE; */ if (unzlocal_getShort(&s->z_filefunc, s->filestream,&uFlags) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) err=UNZ_ERRNO; else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method)) err=UNZ_BADZIPFILE; if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) && (s->cur_file_info.compression_method!=Z_DEFLATED)) err=UNZ_BADZIPFILE; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* date/time */ err=UNZ_ERRNO; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* crc */ err=UNZ_ERRNO; else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) && ((uFlags & 8)==0)) err=UNZ_BADZIPFILE; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size compr */ err=UNZ_ERRNO; else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) && ((uFlags & 8)==0)) err=UNZ_BADZIPFILE; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size uncompr */ err=UNZ_ERRNO; else if ((err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && ((uFlags & 8)==0)) err=UNZ_BADZIPFILE; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&size_filename) != UNZ_OK) err=UNZ_ERRNO; else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename)) err=UNZ_BADZIPFILE; *piSizeVar += (uInt)size_filename; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&size_extra_field) != UNZ_OK) err=UNZ_ERRNO; *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + size_filename; *psize_local_extrafield = (uInt)size_extra_field; *piSizeVar += (uInt)size_extra_field; return err; } /* Open for reading data the current file in the zipfile. If there is no error and the file is opened, the return value is UNZ_OK. */ extern int ZEXPORT unzOpenCurrentFile3 (file, method, level, raw, password) unzFile file; int* method; int* level; int raw; const char* password; { int err=UNZ_OK; uInt iSizeVar; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; uLong offset_local_extrafield; /* offset of the local extra field */ uInt size_local_extrafield; /* size of the local extra field */ # ifndef NOUNCRYPT char source[12]; # else if (password != NULL) return UNZ_PARAMERROR; # endif if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (!s->current_file_ok) return UNZ_PARAMERROR; if (s->pfile_in_zip_read != NULL) unzCloseCurrentFile(file); if (unzlocal_CheckCurrentFileCoherencyHeader(s,&iSizeVar, &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK) return UNZ_BADZIPFILE; pfile_in_zip_read_info = (file_in_zip_read_info_s*) ALLOC(sizeof(file_in_zip_read_info_s)); if (pfile_in_zip_read_info==NULL) return UNZ_INTERNALERROR; pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE); pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield; pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield; pfile_in_zip_read_info->pos_local_extrafield=0; pfile_in_zip_read_info->raw=raw; if (pfile_in_zip_read_info->read_buffer==NULL) { TRYFREE(pfile_in_zip_read_info); return UNZ_INTERNALERROR; } pfile_in_zip_read_info->stream_initialised=0; if (method!=NULL) *method = (int)s->cur_file_info.compression_method; if (level!=NULL) { *level = 6; switch (s->cur_file_info.flag & 0x06) { case 6 : *level = 1; break; case 4 : *level = 2; break; case 2 : *level = 9; break; } } if ((s->cur_file_info.compression_method!=0) && (s->cur_file_info.compression_method!=Z_DEFLATED)) err=UNZ_BADZIPFILE; pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc; pfile_in_zip_read_info->crc32=0; pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method; pfile_in_zip_read_info->filestream=s->filestream; pfile_in_zip_read_info->z_filefunc=s->z_filefunc; pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile; pfile_in_zip_read_info->stream.total_out = 0; if ((s->cur_file_info.compression_method==Z_DEFLATED) && (!raw)) { pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; pfile_in_zip_read_info->stream.zfree = (free_func)0; pfile_in_zip_read_info->stream.opaque = (voidpf)0; pfile_in_zip_read_info->stream.next_in = (voidpf)0; pfile_in_zip_read_info->stream.avail_in = 0; err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS); if (err == Z_OK) pfile_in_zip_read_info->stream_initialised=1; else { TRYFREE(pfile_in_zip_read_info); return err; } /* windowBits is passed < 0 to tell that there is no zlib header. * Note that in this case inflate *requires* an extra "dummy" byte * after the compressed stream in order to complete decompression and * return Z_STREAM_END. * In unzip, i don't wait absolutely Z_STREAM_END because I known the * size of both compressed and uncompressed data */ } pfile_in_zip_read_info->rest_read_compressed = s->cur_file_info.compressed_size ; pfile_in_zip_read_info->rest_read_uncompressed = s->cur_file_info.uncompressed_size ; pfile_in_zip_read_info->pos_in_zipfile = s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + iSizeVar; pfile_in_zip_read_info->stream.avail_in = (uInt)0; s->pfile_in_zip_read = pfile_in_zip_read_info; # ifndef NOUNCRYPT if (password != NULL) { int i; s->pcrc_32_tab = get_crc_table(); init_keys(password,s->keys,s->pcrc_32_tab); if (ZSEEK(s->z_filefunc, s->filestream, s->pfile_in_zip_read->pos_in_zipfile + s->pfile_in_zip_read->byte_before_the_zipfile, SEEK_SET)!=0) return UNZ_INTERNALERROR; if(ZREAD(s->z_filefunc, s->filestream,source, 12)<12) return UNZ_INTERNALERROR; for (i = 0; i<12; i++) zdecode(s->keys,s->pcrc_32_tab,source[i]); s->pfile_in_zip_read->pos_in_zipfile+=12; s->encrypted=1; } # endif return UNZ_OK; } extern int ZEXPORT unzOpenCurrentFile (file) unzFile file; { return unzOpenCurrentFile3(file, NULL, NULL, 0, NULL); } extern int ZEXPORT unzOpenCurrentFilePassword (file, password) unzFile file; const char* password; { return unzOpenCurrentFile3(file, NULL, NULL, 0, password); } extern int ZEXPORT unzOpenCurrentFile2 (file,method,level,raw) unzFile file; int* method; int* level; int raw; { return unzOpenCurrentFile3(file, method, level, raw, NULL); } /* Read bytes from the current file. buf contain buffer where data must be copied len the size of buf. return the number of byte copied if somes bytes are copied return 0 if the end of file was reached return <0 with error code if there is an error (UNZ_ERRNO for IO error, or zLib error for uncompress error) */ extern int ZEXPORT unzReadCurrentFile (file, buf, len) unzFile file; voidp buf; unsigned len; { int err=UNZ_OK; uInt iRead = 0; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; if (pfile_in_zip_read_info->read_buffer == NULL) return UNZ_END_OF_LIST_OF_FILE; if (len==0) return 0; pfile_in_zip_read_info->stream.next_out = (Bytef*)buf; pfile_in_zip_read_info->stream.avail_out = (uInt)len; if ((len>pfile_in_zip_read_info->rest_read_uncompressed) && (!(pfile_in_zip_read_info->raw))) pfile_in_zip_read_info->stream.avail_out = (uInt)pfile_in_zip_read_info->rest_read_uncompressed; if ((len>pfile_in_zip_read_info->rest_read_compressed+ pfile_in_zip_read_info->stream.avail_in) && (pfile_in_zip_read_info->raw)) pfile_in_zip_read_info->stream.avail_out = (uInt)pfile_in_zip_read_info->rest_read_compressed+ pfile_in_zip_read_info->stream.avail_in; while (pfile_in_zip_read_info->stream.avail_out>0) { if ((pfile_in_zip_read_info->stream.avail_in==0) && (pfile_in_zip_read_info->rest_read_compressed>0)) { uInt uReadThis = UNZ_BUFSIZE; if (pfile_in_zip_read_info->rest_read_compressed<uReadThis) uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed; if (uReadThis == 0) return UNZ_EOF; if (ZSEEK(pfile_in_zip_read_info->z_filefunc, pfile_in_zip_read_info->filestream, pfile_in_zip_read_info->pos_in_zipfile + pfile_in_zip_read_info->byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET)!=0) return UNZ_ERRNO; if (ZREAD(pfile_in_zip_read_info->z_filefunc, pfile_in_zip_read_info->filestream, pfile_in_zip_read_info->read_buffer, uReadThis)!=uReadThis) return UNZ_ERRNO; # ifndef NOUNCRYPT if(s->encrypted) { uInt i; for(i=0;i<uReadThis;i++) pfile_in_zip_read_info->read_buffer[i] = zdecode(s->keys,s->pcrc_32_tab, pfile_in_zip_read_info->read_buffer[i]); } # endif pfile_in_zip_read_info->pos_in_zipfile += uReadThis; pfile_in_zip_read_info->rest_read_compressed-=uReadThis; pfile_in_zip_read_info->stream.next_in = (Bytef*)pfile_in_zip_read_info->read_buffer; pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis; } if ((pfile_in_zip_read_info->compression_method==0) || (pfile_in_zip_read_info->raw)) { uInt uDoCopy,i ; if ((pfile_in_zip_read_info->stream.avail_in == 0) && (pfile_in_zip_read_info->rest_read_compressed == 0)) return (iRead==0) ? UNZ_EOF : iRead; if (pfile_in_zip_read_info->stream.avail_out < pfile_in_zip_read_info->stream.avail_in) uDoCopy = pfile_in_zip_read_info->stream.avail_out ; else uDoCopy = pfile_in_zip_read_info->stream.avail_in ; for (i=0;i<uDoCopy;i++) *(pfile_in_zip_read_info->stream.next_out+i) = *(pfile_in_zip_read_info->stream.next_in+i); pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32, pfile_in_zip_read_info->stream.next_out, uDoCopy); pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy; pfile_in_zip_read_info->stream.avail_in -= uDoCopy; pfile_in_zip_read_info->stream.avail_out -= uDoCopy; pfile_in_zip_read_info->stream.next_out += uDoCopy; pfile_in_zip_read_info->stream.next_in += uDoCopy; pfile_in_zip_read_info->stream.total_out += uDoCopy; iRead += uDoCopy; } else { uLong uTotalOutBefore,uTotalOutAfter; const Bytef *bufBefore; uLong uOutThis; int flush=Z_SYNC_FLUSH; uTotalOutBefore = pfile_in_zip_read_info->stream.total_out; bufBefore = pfile_in_zip_read_info->stream.next_out; /* if ((pfile_in_zip_read_info->rest_read_uncompressed == pfile_in_zip_read_info->stream.avail_out) && (pfile_in_zip_read_info->rest_read_compressed == 0)) flush = Z_FINISH; */ err=inflate(&pfile_in_zip_read_info->stream,flush); if ((err>=0) && (pfile_in_zip_read_info->stream.msg!=NULL)) err = Z_DATA_ERROR; uTotalOutAfter = pfile_in_zip_read_info->stream.total_out; uOutThis = uTotalOutAfter-uTotalOutBefore; pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,bufBefore, (uInt)(uOutThis)); pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis; iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); if (err==Z_STREAM_END) return (iRead==0) ? UNZ_EOF : iRead; if (err!=Z_OK) break; } } if (err==Z_OK) return iRead; return err; } /* Give the current position in uncompressed data */ extern z_off_t ZEXPORT unztell (file) unzFile file; { unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; return (z_off_t)pfile_in_zip_read_info->stream.total_out; } /* return 1 if the end of file was reached, 0 elsewhere */ extern int ZEXPORT unzeof (file) unzFile file; { unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; if (pfile_in_zip_read_info->rest_read_uncompressed == 0) return 1; else return 0; } /* Read extra field from the current file (opened by unzOpenCurrentFile) This is the local-header version of the extra field (sometimes, there is more info in the local-header version than in the central-header) if buf==NULL, it return the size of the local extra field that can be read if buf!=NULL, len is the size of the buffer, the extra header is copied in buf. the return value is the number of bytes copied in buf, or (if <0) the error code */ extern int ZEXPORT unzGetLocalExtrafield (file,buf,len) unzFile file; voidp buf; unsigned len; { unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; uInt read_now; uLong size_to_read; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; size_to_read = (pfile_in_zip_read_info->size_local_extrafield - pfile_in_zip_read_info->pos_local_extrafield); if (buf==NULL) return (int)size_to_read; if (len>size_to_read) read_now = (uInt)size_to_read; else read_now = (uInt)len ; if (read_now==0) return 0; if (ZSEEK(pfile_in_zip_read_info->z_filefunc, pfile_in_zip_read_info->filestream, pfile_in_zip_read_info->offset_local_extrafield + pfile_in_zip_read_info->pos_local_extrafield, ZLIB_FILEFUNC_SEEK_SET)!=0) return UNZ_ERRNO; if (ZREAD(pfile_in_zip_read_info->z_filefunc, pfile_in_zip_read_info->filestream, buf,read_now)!=read_now) return UNZ_ERRNO; return (int)read_now; } /* Close the file in zip opened with unzipOpenCurrentFile Return UNZ_CRCERROR if all the file was read but the CRC is not good */ extern int ZEXPORT unzCloseCurrentFile (file) unzFile file; { int err=UNZ_OK; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; if ((pfile_in_zip_read_info->rest_read_uncompressed == 0) && (!pfile_in_zip_read_info->raw)) { if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait) err=UNZ_CRCERROR; } TRYFREE(pfile_in_zip_read_info->read_buffer); pfile_in_zip_read_info->read_buffer = NULL; if (pfile_in_zip_read_info->stream_initialised) inflateEnd(&pfile_in_zip_read_info->stream); pfile_in_zip_read_info->stream_initialised = 0; TRYFREE(pfile_in_zip_read_info); s->pfile_in_zip_read=NULL; return err; } /* Get the global comment string of the ZipFile, in the szComment buffer. uSizeBuf is the size of the szComment buffer. return the number of byte copied or an error code <0 */ extern int ZEXPORT unzGetGlobalComment (file, szComment, uSizeBuf) unzFile file; char *szComment; uLong uSizeBuf; { // int err=UNZ_OK; unz_s* s; uLong uReadThis ; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; uReadThis = uSizeBuf; if (uReadThis>s->gi.size_comment) uReadThis = s->gi.size_comment; if (ZSEEK(s->z_filefunc,s->filestream,s->central_pos+22,ZLIB_FILEFUNC_SEEK_SET)!=0) return UNZ_ERRNO; if (uReadThis>0) { *szComment='\0'; if (ZREAD(s->z_filefunc,s->filestream,szComment,uReadThis)!=uReadThis) return UNZ_ERRNO; } if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) *(szComment+s->gi.size_comment)='\0'; return (int)uReadThis; } /* Additions by RX '2004 */ extern uLong ZEXPORT unzGetOffset (file) unzFile file; { unz_s* s; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (!s->current_file_ok) return 0; if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff) if (s->num_file==s->gi.number_entry) return 0; return s->pos_in_central_dir; } extern int ZEXPORT unzSetOffset (file, pos) unzFile file; uLong pos; { unz_s* s; int err; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; s->pos_in_central_dir = pos; s->num_file = s->gi.number_entry; /* hack */ err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, &s->cur_file_info_internal, NULL,0,NULL,0,NULL,0); s->current_file_ok = (err == UNZ_OK); return err; }
220
./objective-zip/MiniZip/zip.c
/* zip.c -- IO on .zip files using zlib Version 1.01e, February 12th, 2005 27 Dec 2004 Rolf Kalbermatter Modification to zipOpen2 to support globalComment retrieval. Copyright (C) 1998-2005 Gilles Vollant Read zip.h for more info */ #define NOCRYPT #define NOUNCRYPT #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "zlib.h" #include "zip.h" #ifdef STDC # include <stddef.h> # include <string.h> # include <stdlib.h> #endif #ifdef NO_ERRNO_H extern int errno; #else # include <errno.h> #endif #ifndef local # define local static #endif /* compile with -Dlocal if your debugger can't find static symbols */ #ifndef VERSIONMADEBY # define VERSIONMADEBY (0x0) /* platform depedent */ #endif #ifndef Z_BUFSIZE #define Z_BUFSIZE (16384) #endif #ifndef Z_MAXFILENAMEINZIP #define Z_MAXFILENAMEINZIP (256) #endif #ifndef ALLOC # define ALLOC(size) (malloc(size)) #endif #ifndef TRYFREE # define TRYFREE(p) {if (p) free(p);} #endif /* #define SIZECENTRALDIRITEM (0x2e) #define SIZEZIPLOCALHEADER (0x1e) */ /* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */ #ifndef SEEK_CUR #define SEEK_CUR 1 #endif #ifndef SEEK_END #define SEEK_END 2 #endif #ifndef SEEK_SET #define SEEK_SET 0 #endif #ifndef DEF_MEM_LEVEL #if MAX_MEM_LEVEL >= 8 # define DEF_MEM_LEVEL 8 #else # define DEF_MEM_LEVEL MAX_MEM_LEVEL #endif #endif const char zip_copyright[] = " zip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; #define SIZEDATA_INDATABLOCK (4096-(4*4)) #define LOCALHEADERMAGIC (0x04034b50) #define CENTRALHEADERMAGIC (0x02014b50) #define ENDHEADERMAGIC (0x06054b50) #define FLAG_LOCALHEADER_OFFSET (0x06) #define CRC_LOCALHEADER_OFFSET (0x0e) #define SIZECENTRALHEADER (0x2e) /* 46 */ typedef struct linkedlist_datablock_internal_s { struct linkedlist_datablock_internal_s* next_datablock; uLong avail_in_this_block; uLong filled_in_this_block; uLong unused; /* for future use and alignement */ unsigned char data[SIZEDATA_INDATABLOCK]; } linkedlist_datablock_internal; typedef struct linkedlist_data_s { linkedlist_datablock_internal* first_block; linkedlist_datablock_internal* last_block; } linkedlist_data; typedef struct { z_stream stream; /* zLib stream structure for inflate */ int stream_initialised; /* 1 is stream is initialised */ uInt pos_in_buffered_data; /* last written byte in buffered_data */ uLong pos_local_header; /* offset of the local header of the file currenty writing */ char* central_header; /* central header data for the current file */ uLong size_centralheader; /* size of the central header for cur file */ uLong flag; /* flag of the file currently writing */ int method; /* compression method of file currenty wr.*/ int raw; /* 1 for directly writing raw data */ Byte buffered_data[Z_BUFSIZE];/* buffer contain compressed data to be writ*/ uLong dosDate; uLong crc32; int encrypt; #ifndef NOCRYPT unsigned long keys[3]; /* keys defining the pseudo-random sequence */ const unsigned long* pcrc_32_tab; int crypt_header_size; #endif } curfile_info; typedef struct { zlib_filefunc_def z_filefunc; voidpf filestream; /* io structore of the zipfile */ linkedlist_data central_dir;/* datablock with central dir in construction*/ int in_opened_file_inzip; /* 1 if a file in the zip is currently writ.*/ curfile_info ci; /* info on the file curretly writing */ uLong begin_pos; /* position of the beginning of the zipfile */ uLong add_position_when_writting_offset; uLong number_entry; #ifndef NO_ADDFILEINEXISTINGZIP char *globalcomment; #endif } zip_internal; #ifndef NOCRYPT #define INCLUDECRYPTINGCODE_IFCRYPTALLOWED #include "crypt.h" #endif local linkedlist_datablock_internal* allocate_new_datablock() { linkedlist_datablock_internal* ldi; ldi = (linkedlist_datablock_internal*) ALLOC(sizeof(linkedlist_datablock_internal)); if (ldi!=NULL) { ldi->next_datablock = NULL ; ldi->filled_in_this_block = 0 ; ldi->avail_in_this_block = SIZEDATA_INDATABLOCK ; } return ldi; } local void free_datablock(ldi) linkedlist_datablock_internal* ldi; { while (ldi!=NULL) { linkedlist_datablock_internal* ldinext = ldi->next_datablock; TRYFREE(ldi); ldi = ldinext; } } local void init_linkedlist(ll) linkedlist_data* ll; { ll->first_block = ll->last_block = NULL; } local int add_data_in_datablock(ll,buf,len) linkedlist_data* ll; const void* buf; uLong len; { linkedlist_datablock_internal* ldi; const unsigned char* from_copy; if (ll==NULL) return ZIP_INTERNALERROR; if (ll->last_block == NULL) { ll->first_block = ll->last_block = allocate_new_datablock(); if (ll->first_block == NULL) return ZIP_INTERNALERROR; } ldi = ll->last_block; from_copy = (unsigned char*)buf; while (len>0) { uInt copy_this; uInt i; unsigned char* to_copy; if (ldi->avail_in_this_block==0) { ldi->next_datablock = allocate_new_datablock(); if (ldi->next_datablock == NULL) return ZIP_INTERNALERROR; ldi = ldi->next_datablock ; ll->last_block = ldi; } if (ldi->avail_in_this_block < len) copy_this = (uInt)ldi->avail_in_this_block; else copy_this = (uInt)len; to_copy = &(ldi->data[ldi->filled_in_this_block]); for (i=0;i<copy_this;i++) *(to_copy+i)=*(from_copy+i); ldi->filled_in_this_block += copy_this; ldi->avail_in_this_block -= copy_this; from_copy += copy_this ; len -= copy_this; } return ZIP_OK; } /****************************************************************************/ #ifndef NO_ADDFILEINEXISTINGZIP /* =========================================================================== Inputs a long in LSB order to the given file nbByte == 1, 2 or 4 (byte, short or long) */ local int ziplocal_putValue OF((const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, uLong x, int nbByte)); local int ziplocal_putValue (pzlib_filefunc_def, filestream, x, nbByte) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; uLong x; int nbByte; { unsigned char buf[4]; int n; for (n = 0; n < nbByte; n++) { buf[n] = (unsigned char)(x & 0xff); x >>= 8; } if (x != 0) { /* data overflow - hack for ZIP64 (X Roche) */ for (n = 0; n < nbByte; n++) { buf[n] = 0xff; } } if (ZWRITE(*pzlib_filefunc_def,filestream,buf,nbByte)!=(uLong)nbByte) return ZIP_ERRNO; else return ZIP_OK; } local void ziplocal_putValue_inmemory OF((void* dest, uLong x, int nbByte)); local void ziplocal_putValue_inmemory (dest, x, nbByte) void* dest; uLong x; int nbByte; { unsigned char* buf=(unsigned char*)dest; int n; for (n = 0; n < nbByte; n++) { buf[n] = (unsigned char)(x & 0xff); x >>= 8; } if (x != 0) { /* data overflow - hack for ZIP64 */ for (n = 0; n < nbByte; n++) { buf[n] = 0xff; } } } /****************************************************************************/ local uLong ziplocal_TmzDateToDosDate(ptm,dosDate) const tm_zip* ptm; uLong dosDate; { uLong year = (uLong)ptm->tm_year; if (year>1980) year-=1980; else if (year>80) year-=80; return (uLong) (((ptm->tm_mday) + (32 * (ptm->tm_mon+1)) + (512 * year)) << 16) | ((ptm->tm_sec/2) + (32* ptm->tm_min) + (2048 * (uLong)ptm->tm_hour)); } /****************************************************************************/ local int ziplocal_getByte OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, int *pi)); local int ziplocal_getByte(pzlib_filefunc_def,filestream,pi) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; int *pi; { unsigned char c; int err = (int)ZREAD(*pzlib_filefunc_def,filestream,&c,1); if (err==1) { *pi = (int)c; return ZIP_OK; } else { if (ZERROR(*pzlib_filefunc_def,filestream)) return ZIP_ERRNO; else return ZIP_EOF; } } /* =========================================================================== Reads a long in LSB order from the given gz_stream. Sets */ local int ziplocal_getShort OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); local int ziplocal_getShort (pzlib_filefunc_def,filestream,pX) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; uLong *pX; { uLong x ; int i; int err; err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); x = (uLong)i; if (err==ZIP_OK) err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<8; if (err==ZIP_OK) *pX = x; else *pX = 0; return err; } local int ziplocal_getLong OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); local int ziplocal_getLong (pzlib_filefunc_def,filestream,pX) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; uLong *pX; { uLong x ; int i; int err; err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); x = (uLong)i; if (err==ZIP_OK) err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<8; if (err==ZIP_OK) err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<16; if (err==ZIP_OK) err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<24; if (err==ZIP_OK) *pX = x; else *pX = 0; return err; } #ifndef BUFREADCOMMENT #define BUFREADCOMMENT (0x400) #endif /* Locate the Central directory of a zipfile (at the end, just before the global comment) */ local uLong ziplocal_SearchCentralDir OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream)); local uLong ziplocal_SearchCentralDir(pzlib_filefunc_def,filestream) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; { unsigned char* buf; uLong uSizeFile; uLong uBackRead; uLong uMaxBack=0xffff; /* maximum size of global comment */ uLong uPosFound=0; if (ZSEEK(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) return 0; uSizeFile = ZTELL(*pzlib_filefunc_def,filestream); if (uMaxBack>uSizeFile) uMaxBack = uSizeFile; buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); if (buf==NULL) return 0; uBackRead = 4; while (uBackRead<uMaxBack) { uLong uReadSize,uReadPos ; int i; if (uBackRead+BUFREADCOMMENT>uMaxBack) uBackRead = uMaxBack; else uBackRead+=BUFREADCOMMENT; uReadPos = uSizeFile-uBackRead ; uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? (BUFREADCOMMENT+4) : (uSizeFile-uReadPos); if (ZSEEK(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) break; if (ZREAD(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) break; for (i=(int)uReadSize-3; (i--)>0;) if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) { uPosFound = uReadPos+i; break; } if (uPosFound!=0) break; } TRYFREE(buf); return uPosFound; } #endif /* !NO_ADDFILEINEXISTINGZIP*/ /************************************************************/ extern zipFile ZEXPORT zipOpen2 (pathname, append, globalcomment, pzlib_filefunc_def) const char *pathname; int append; zipcharpc* globalcomment; zlib_filefunc_def* pzlib_filefunc_def; { zip_internal ziinit; zip_internal* zi; int err=ZIP_OK; if (pzlib_filefunc_def==NULL) fill_fopen_filefunc(&ziinit.z_filefunc); else ziinit.z_filefunc = *pzlib_filefunc_def; ziinit.filestream = (*(ziinit.z_filefunc.zopen_file)) (ziinit.z_filefunc.opaque, pathname, (append == APPEND_STATUS_CREATE) ? (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_CREATE) : (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_EXISTING)); if (ziinit.filestream == NULL) return NULL; ziinit.begin_pos = ZTELL(ziinit.z_filefunc,ziinit.filestream); ziinit.in_opened_file_inzip = 0; ziinit.ci.stream_initialised = 0; ziinit.number_entry = 0; ziinit.add_position_when_writting_offset = 0; init_linkedlist(&(ziinit.central_dir)); zi = (zip_internal*)ALLOC(sizeof(zip_internal)); if (zi==NULL) { ZCLOSE(ziinit.z_filefunc,ziinit.filestream); return NULL; } /* now we add file in a zipfile */ # ifndef NO_ADDFILEINEXISTINGZIP ziinit.globalcomment = NULL; if (append == APPEND_STATUS_ADDINZIP) { uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ uLong size_central_dir; /* size of the central directory */ uLong offset_central_dir; /* offset of start of central directory */ uLong central_pos,uL; uLong number_disk; /* number of the current dist, used for spaning ZIP, unsupported, always 0*/ uLong number_disk_with_CD; /* number the the disk with central dir, used for spaning ZIP, unsupported, always 0*/ uLong number_entry; uLong number_entry_CD; /* total number of entries in the central dir (same than number_entry on nospan) */ uLong size_comment; central_pos = ziplocal_SearchCentralDir(&ziinit.z_filefunc,ziinit.filestream); if (central_pos==0) err=ZIP_ERRNO; if (ZSEEK(ziinit.z_filefunc, ziinit.filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) err=ZIP_ERRNO; /* the signature, already checked */ if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&uL)!=ZIP_OK) err=ZIP_ERRNO; /* number of this disk */ if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_disk)!=ZIP_OK) err=ZIP_ERRNO; /* number of the disk with the start of the central directory */ if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_disk_with_CD)!=ZIP_OK) err=ZIP_ERRNO; /* total number of entries in the central dir on this disk */ if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_entry)!=ZIP_OK) err=ZIP_ERRNO; /* total number of entries in the central dir */ if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_entry_CD)!=ZIP_OK) err=ZIP_ERRNO; if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) err=ZIP_BADZIPFILE; /* size of the central directory */ if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&size_central_dir)!=ZIP_OK) err=ZIP_ERRNO; /* offset of start of central directory with respect to the starting disk number */ if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&offset_central_dir)!=ZIP_OK) err=ZIP_ERRNO; /* zipfile global comment length */ if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&size_comment)!=ZIP_OK) err=ZIP_ERRNO; if ((central_pos<offset_central_dir+size_central_dir) && (err==ZIP_OK)) err=ZIP_BADZIPFILE; if (err!=ZIP_OK) { ZCLOSE(ziinit.z_filefunc, ziinit.filestream); return NULL; } if (size_comment>0) { ziinit.globalcomment = ALLOC(size_comment+1); if (ziinit.globalcomment) { size_comment = ZREAD(ziinit.z_filefunc, ziinit.filestream,ziinit.globalcomment,size_comment); ziinit.globalcomment[size_comment]=0; } } byte_before_the_zipfile = central_pos - (offset_central_dir+size_central_dir); ziinit.add_position_when_writting_offset = byte_before_the_zipfile; { uLong size_central_dir_to_read = size_central_dir; size_t buf_size = SIZEDATA_INDATABLOCK; void* buf_read = (void*)ALLOC(buf_size); if (ZSEEK(ziinit.z_filefunc, ziinit.filestream, offset_central_dir + byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET) != 0) err=ZIP_ERRNO; while ((size_central_dir_to_read>0) && (err==ZIP_OK)) { uLong read_this = SIZEDATA_INDATABLOCK; if (read_this > size_central_dir_to_read) read_this = size_central_dir_to_read; if (ZREAD(ziinit.z_filefunc, ziinit.filestream,buf_read,read_this) != read_this) err=ZIP_ERRNO; if (err==ZIP_OK) err = add_data_in_datablock(&ziinit.central_dir,buf_read, (uLong)read_this); size_central_dir_to_read-=read_this; } TRYFREE(buf_read); } ziinit.begin_pos = byte_before_the_zipfile; ziinit.number_entry = number_entry_CD; if (ZSEEK(ziinit.z_filefunc, ziinit.filestream, offset_central_dir+byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0) err=ZIP_ERRNO; } if (globalcomment) { *globalcomment = ziinit.globalcomment; } # endif /* !NO_ADDFILEINEXISTINGZIP*/ if (err != ZIP_OK) { # ifndef NO_ADDFILEINEXISTINGZIP TRYFREE(ziinit.globalcomment); # endif /* !NO_ADDFILEINEXISTINGZIP*/ TRYFREE(zi); return NULL; } else { *zi = ziinit; return (zipFile)zi; } } extern zipFile ZEXPORT zipOpen (pathname, append) const char *pathname; int append; { return zipOpen2(pathname,append,NULL,NULL); } extern int ZEXPORT zipOpenNewFileInZip3 (file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, method, level, raw, windowBits, memLevel, strategy, password, crcForCrypting) zipFile file; const char* filename; const zip_fileinfo* zipfi; const void* extrafield_local; uInt size_extrafield_local; const void* extrafield_global; uInt size_extrafield_global; const char* comment; int method; int level; int raw; int windowBits; int memLevel; int strategy; const char* password; uLong crcForCrypting; { zip_internal* zi; uInt size_filename; uInt size_comment; uInt i; int err = ZIP_OK; # ifdef NOCRYPT if (password != NULL) return ZIP_PARAMERROR; # endif if (file == NULL) return ZIP_PARAMERROR; if ((method!=0) && (method!=Z_DEFLATED)) return ZIP_PARAMERROR; zi = (zip_internal*)file; if (zi->in_opened_file_inzip == 1) { err = zipCloseFileInZip (file); if (err != ZIP_OK) return err; } if (filename==NULL) filename="-"; if (comment==NULL) size_comment = 0; else size_comment = (uInt)strlen(comment); size_filename = (uInt)strlen(filename); if (zipfi == NULL) zi->ci.dosDate = 0; else { if (zipfi->dosDate != 0) zi->ci.dosDate = zipfi->dosDate; else zi->ci.dosDate = ziplocal_TmzDateToDosDate(&zipfi->tmz_date,zipfi->dosDate); } zi->ci.flag = 0; if ((level==8) || (level==9)) zi->ci.flag |= 2; if (level==2) zi->ci.flag |= 4; if (level==1) zi->ci.flag |= 6; if (password != NULL) zi->ci.flag |= 1; zi->ci.crc32 = 0; zi->ci.method = method; zi->ci.encrypt = 0; zi->ci.stream_initialised = 0; zi->ci.pos_in_buffered_data = 0; zi->ci.raw = raw; zi->ci.pos_local_header = ZTELL(zi->z_filefunc,zi->filestream) ; zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename + size_extrafield_global + size_comment; zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader); ziplocal_putValue_inmemory(zi->ci.central_header,(uLong)CENTRALHEADERMAGIC,4); /* version info */ ziplocal_putValue_inmemory(zi->ci.central_header+4,(uLong)VERSIONMADEBY,2); ziplocal_putValue_inmemory(zi->ci.central_header+6,(uLong)20,2); ziplocal_putValue_inmemory(zi->ci.central_header+8,(uLong)zi->ci.flag,2); ziplocal_putValue_inmemory(zi->ci.central_header+10,(uLong)zi->ci.method,2); ziplocal_putValue_inmemory(zi->ci.central_header+12,(uLong)zi->ci.dosDate,4); ziplocal_putValue_inmemory(zi->ci.central_header+16,(uLong)0,4); /*crc*/ ziplocal_putValue_inmemory(zi->ci.central_header+20,(uLong)0,4); /*compr size*/ ziplocal_putValue_inmemory(zi->ci.central_header+24,(uLong)0,4); /*uncompr size*/ ziplocal_putValue_inmemory(zi->ci.central_header+28,(uLong)size_filename,2); ziplocal_putValue_inmemory(zi->ci.central_header+30,(uLong)size_extrafield_global,2); ziplocal_putValue_inmemory(zi->ci.central_header+32,(uLong)size_comment,2); ziplocal_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/ if (zipfi==NULL) ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2); else ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2); if (zipfi==NULL) ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4); else ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4); ziplocal_putValue_inmemory(zi->ci.central_header+42,(uLong)zi->ci.pos_local_header- zi->add_position_when_writting_offset,4); for (i=0;i<size_filename;i++) *(zi->ci.central_header+SIZECENTRALHEADER+i) = *(filename+i); for (i=0;i<size_extrafield_global;i++) *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+i) = *(((const char*)extrafield_global)+i); for (i=0;i<size_comment;i++) *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+ size_extrafield_global+i) = *(comment+i); if (zi->ci.central_header == NULL) return ZIP_INTERNALERROR; /* write the local header */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)LOCALHEADERMAGIC,4); if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)20,2);/* version needed to extract */ if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.flag,2); if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.method,2); if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.dosDate,4); if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* crc 32, unknown */ if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* compressed size, unknown */ if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* uncompressed size, unknown */ if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_filename,2); if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_extrafield_local,2); if ((err==ZIP_OK) && (size_filename>0)) if (ZWRITE(zi->z_filefunc,zi->filestream,filename,size_filename)!=size_filename) err = ZIP_ERRNO; if ((err==ZIP_OK) && (size_extrafield_local>0)) if (ZWRITE(zi->z_filefunc,zi->filestream,extrafield_local,size_extrafield_local) !=size_extrafield_local) err = ZIP_ERRNO; zi->ci.stream.avail_in = (uInt)0; zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; zi->ci.stream.next_out = zi->ci.buffered_data; zi->ci.stream.total_in = 0; zi->ci.stream.total_out = 0; if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) { zi->ci.stream.zalloc = (alloc_func)0; zi->ci.stream.zfree = (free_func)0; zi->ci.stream.opaque = (voidpf)0; if (windowBits>0) windowBits = -windowBits; err = deflateInit2(&zi->ci.stream, level, Z_DEFLATED, windowBits, memLevel, strategy); if (err==Z_OK) zi->ci.stream_initialised = 1; } # ifndef NOCRYPT zi->ci.crypt_header_size = 0; if ((err==Z_OK) && (password != NULL)) { unsigned char bufHead[RAND_HEAD_LEN]; unsigned int sizeHead; zi->ci.encrypt = 1; zi->ci.pcrc_32_tab = get_crc_table(); /*init_keys(password,zi->ci.keys,zi->ci.pcrc_32_tab);*/ sizeHead=crypthead(password,bufHead,RAND_HEAD_LEN,zi->ci.keys,zi->ci.pcrc_32_tab,crcForCrypting); zi->ci.crypt_header_size = sizeHead; if (ZWRITE(zi->z_filefunc,zi->filestream,bufHead,sizeHead) != sizeHead) err = ZIP_ERRNO; } # endif if (err==Z_OK) zi->in_opened_file_inzip = 1; return err; } extern int ZEXPORT zipOpenNewFileInZip2(file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, method, level, raw) zipFile file; const char* filename; const zip_fileinfo* zipfi; const void* extrafield_local; uInt size_extrafield_local; const void* extrafield_global; uInt size_extrafield_global; const char* comment; int method; int level; int raw; { return zipOpenNewFileInZip3 (file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, method, level, raw, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, NULL, 0); } extern int ZEXPORT zipOpenNewFileInZip (file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, method, level) zipFile file; const char* filename; const zip_fileinfo* zipfi; const void* extrafield_local; uInt size_extrafield_local; const void* extrafield_global; uInt size_extrafield_global; const char* comment; int method; int level; { return zipOpenNewFileInZip2 (file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, method, level, 0); } local int zipFlushWriteBuffer(zi) zip_internal* zi; { int err=ZIP_OK; if (zi->ci.encrypt != 0) { #ifndef NOCRYPT uInt i; int t; for (i=0;i<zi->ci.pos_in_buffered_data;i++) zi->ci.buffered_data[i] = zencode(zi->ci.keys, zi->ci.pcrc_32_tab, zi->ci.buffered_data[i],t); #endif } if (ZWRITE(zi->z_filefunc,zi->filestream,zi->ci.buffered_data,zi->ci.pos_in_buffered_data) !=zi->ci.pos_in_buffered_data) err = ZIP_ERRNO; zi->ci.pos_in_buffered_data = 0; return err; } extern int ZEXPORT zipWriteInFileInZip (file, buf, len) zipFile file; const void* buf; unsigned len; { zip_internal* zi; int err=ZIP_OK; if (file == NULL) return ZIP_PARAMERROR; zi = (zip_internal*)file; if (zi->in_opened_file_inzip == 0) return ZIP_PARAMERROR; zi->ci.stream.next_in = (void*)buf; zi->ci.stream.avail_in = len; zi->ci.crc32 = crc32(zi->ci.crc32,buf,len); while ((err==ZIP_OK) && (zi->ci.stream.avail_in>0)) { if (zi->ci.stream.avail_out == 0) { if (zipFlushWriteBuffer(zi) == ZIP_ERRNO) err = ZIP_ERRNO; zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; zi->ci.stream.next_out = zi->ci.buffered_data; } if(err != ZIP_OK) break; if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) { uLong uTotalOutBefore = zi->ci.stream.total_out; err=deflate(&zi->ci.stream, Z_NO_FLUSH); zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ; } else { uInt copy_this,i; if (zi->ci.stream.avail_in < zi->ci.stream.avail_out) copy_this = zi->ci.stream.avail_in; else copy_this = zi->ci.stream.avail_out; for (i=0;i<copy_this;i++) *(((char*)zi->ci.stream.next_out)+i) = *(((const char*)zi->ci.stream.next_in)+i); { zi->ci.stream.avail_in -= copy_this; zi->ci.stream.avail_out-= copy_this; zi->ci.stream.next_in+= copy_this; zi->ci.stream.next_out+= copy_this; zi->ci.stream.total_in+= copy_this; zi->ci.stream.total_out+= copy_this; zi->ci.pos_in_buffered_data += copy_this; } } } return err; } extern int ZEXPORT zipCloseFileInZipRaw (file, uncompressed_size, crc32) zipFile file; uLong uncompressed_size; uLong crc32; { zip_internal* zi; uLong compressed_size; int err=ZIP_OK; if (file == NULL) return ZIP_PARAMERROR; zi = (zip_internal*)file; if (zi->in_opened_file_inzip == 0) return ZIP_PARAMERROR; zi->ci.stream.avail_in = 0; if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) while (err==ZIP_OK) { uLong uTotalOutBefore; if (zi->ci.stream.avail_out == 0) { if (zipFlushWriteBuffer(zi) == ZIP_ERRNO) err = ZIP_ERRNO; zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; zi->ci.stream.next_out = zi->ci.buffered_data; } uTotalOutBefore = zi->ci.stream.total_out; err=deflate(&zi->ci.stream, Z_FINISH); zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ; } if (err==Z_STREAM_END) err=ZIP_OK; /* this is normal */ if ((zi->ci.pos_in_buffered_data>0) && (err==ZIP_OK)) if (zipFlushWriteBuffer(zi)==ZIP_ERRNO) err = ZIP_ERRNO; if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) { err=deflateEnd(&zi->ci.stream); zi->ci.stream_initialised = 0; } if (!zi->ci.raw) { crc32 = (uLong)zi->ci.crc32; uncompressed_size = (uLong)zi->ci.stream.total_in; } compressed_size = (uLong)zi->ci.stream.total_out; # ifndef NOCRYPT compressed_size += zi->ci.crypt_header_size; # endif ziplocal_putValue_inmemory(zi->ci.central_header+16,crc32,4); /*crc*/ ziplocal_putValue_inmemory(zi->ci.central_header+20, compressed_size,4); /*compr size*/ if (zi->ci.stream.data_type == Z_ASCII) ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)Z_ASCII,2); ziplocal_putValue_inmemory(zi->ci.central_header+24, uncompressed_size,4); /*uncompr size*/ if (err==ZIP_OK) err = add_data_in_datablock(&zi->central_dir,zi->ci.central_header, (uLong)zi->ci.size_centralheader); free(zi->ci.central_header); if (err==ZIP_OK) { long cur_pos_inzip = ZTELL(zi->z_filefunc,zi->filestream); if (ZSEEK(zi->z_filefunc,zi->filestream, zi->ci.pos_local_header + 14,ZLIB_FILEFUNC_SEEK_SET)!=0) err = ZIP_ERRNO; if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,crc32,4); /* crc 32, unknown */ if (err==ZIP_OK) /* compressed size, unknown */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,compressed_size,4); if (err==ZIP_OK) /* uncompressed size, unknown */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,uncompressed_size,4); if (ZSEEK(zi->z_filefunc,zi->filestream, cur_pos_inzip,ZLIB_FILEFUNC_SEEK_SET)!=0) err = ZIP_ERRNO; } zi->number_entry ++; zi->in_opened_file_inzip = 0; return err; } extern int ZEXPORT zipCloseFileInZip (file) zipFile file; { return zipCloseFileInZipRaw (file,0,0); } extern int ZEXPORT zipClose (file, global_comment) zipFile file; const char* global_comment; { zip_internal* zi; int err = 0; uLong size_centraldir = 0; uLong centraldir_pos_inzip; uInt size_global_comment; if (file == NULL) return ZIP_PARAMERROR; zi = (zip_internal*)file; if (zi->in_opened_file_inzip == 1) { err = zipCloseFileInZip (file); } #ifndef NO_ADDFILEINEXISTINGZIP if (global_comment==NULL) global_comment = zi->globalcomment; #endif if (global_comment==NULL) size_global_comment = 0; else size_global_comment = (uInt)strlen(global_comment); centraldir_pos_inzip = ZTELL(zi->z_filefunc,zi->filestream); if (err==ZIP_OK) { linkedlist_datablock_internal* ldi = zi->central_dir.first_block ; while (ldi!=NULL) { if ((err==ZIP_OK) && (ldi->filled_in_this_block>0)) if (ZWRITE(zi->z_filefunc,zi->filestream, ldi->data,ldi->filled_in_this_block) !=ldi->filled_in_this_block ) err = ZIP_ERRNO; size_centraldir += ldi->filled_in_this_block; ldi = ldi->next_datablock; } } free_datablock(zi->central_dir.first_block); if (err==ZIP_OK) /* Magic End */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)ENDHEADERMAGIC,4); if (err==ZIP_OK) /* number of this disk */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2); if (err==ZIP_OK) /* number of the disk with the start of the central directory */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2); if (err==ZIP_OK) /* total number of entries in the central dir on this disk */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2); if (err==ZIP_OK) /* total number of entries in the central dir */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2); if (err==ZIP_OK) /* size of the central directory */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_centraldir,4); if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream, (uLong)(centraldir_pos_inzip - zi->add_position_when_writting_offset),4); if (err==ZIP_OK) /* zipfile comment length */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_global_comment,2); if ((err==ZIP_OK) && (size_global_comment>0)) if (ZWRITE(zi->z_filefunc,zi->filestream, global_comment,size_global_comment) != size_global_comment) err = ZIP_ERRNO; if (ZCLOSE(zi->z_filefunc,zi->filestream) != 0) if (err == ZIP_OK) err = ZIP_ERRNO; #ifndef NO_ADDFILEINEXISTINGZIP TRYFREE(zi->globalcomment); #endif TRYFREE(zi); return err; }
221
./objective-zip/MiniZip/mztools.c
/* Additional tools for Minizip Code: Xavier Roche '2004 License: Same as ZLIB (www.gzip.org) */ /* Code */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "zlib.h" #include "unzip.h" #include "mztools.h" #define READ_8(adr) ((unsigned char)*(adr)) #define READ_16(adr) ( READ_8(adr) | (READ_8(adr+1) << 8) ) #define READ_32(adr) ( READ_16(adr) | (READ_16((adr)+2) << 16) ) #define WRITE_8(buff, n) do { \ *((unsigned char*)(buff)) = (unsigned char) ((n) & 0xff); \ } while(0) #define WRITE_16(buff, n) do { \ WRITE_8((unsigned char*)(buff), n); \ WRITE_8(((unsigned char*)(buff)) + 1, (n) >> 8); \ } while(0) #define WRITE_32(buff, n) do { \ WRITE_16((unsigned char*)(buff), (n) & 0xffff); \ WRITE_16((unsigned char*)(buff) + 2, (n) >> 16); \ } while(0) extern int ZEXPORT unzRepair(file, fileOut, fileOutTmp, nRecovered, bytesRecovered) const char* file; const char* fileOut; const char* fileOutTmp; uLong* nRecovered; uLong* bytesRecovered; { int err = Z_OK; FILE* fpZip = fopen(file, "rb"); FILE* fpOut = fopen(fileOut, "wb"); FILE* fpOutCD = fopen(fileOutTmp, "wb"); if (fpZip != NULL && fpOut != NULL) { int entries = 0; uLong totalBytes = 0; char header[30]; char filename[256]; char extra[1024]; int offset = 0; int offsetCD = 0; while ( fread(header, 1, 30, fpZip) == 30 ) { int currentOffset = offset; /* File entry */ if (READ_32(header) == 0x04034b50) { unsigned int version = READ_16(header + 4); unsigned int gpflag = READ_16(header + 6); unsigned int method = READ_16(header + 8); unsigned int filetime = READ_16(header + 10); unsigned int filedate = READ_16(header + 12); unsigned int crc = READ_32(header + 14); /* crc */ unsigned int cpsize = READ_32(header + 18); /* compressed size */ unsigned int uncpsize = READ_32(header + 22); /* uncompressed sz */ unsigned int fnsize = READ_16(header + 26); /* file name length */ unsigned int extsize = READ_16(header + 28); /* extra field length */ filename[0] = extra[0] = '\0'; /* Header */ if (fwrite(header, 1, 30, fpOut) == 30) { offset += 30; } else { err = Z_ERRNO; break; } /* Filename */ if (fnsize > 0) { if (fread(filename, 1, fnsize, fpZip) == fnsize) { if (fwrite(filename, 1, fnsize, fpOut) == fnsize) { offset += fnsize; } else { err = Z_ERRNO; break; } } else { err = Z_ERRNO; break; } } else { err = Z_STREAM_ERROR; break; } /* Extra field */ if (extsize > 0) { if (fread(extra, 1, extsize, fpZip) == extsize) { if (fwrite(extra, 1, extsize, fpOut) == extsize) { offset += extsize; } else { err = Z_ERRNO; break; } } else { err = Z_ERRNO; break; } } /* Data */ { int dataSize = cpsize; if (dataSize == 0) { dataSize = uncpsize; } if (dataSize > 0) { char* data = malloc(dataSize); if (data != NULL) { if ((int)fread(data, 1, dataSize, fpZip) == dataSize) { if ((int)fwrite(data, 1, dataSize, fpOut) == dataSize) { offset += dataSize; totalBytes += dataSize; } else { err = Z_ERRNO; } } else { err = Z_ERRNO; } free(data); if (err != Z_OK) { break; } } else { err = Z_MEM_ERROR; break; } } } /* Central directory entry */ { char cdeHeader[46]; char* comment = ""; int comsize = (int) strlen(comment); WRITE_32(cdeHeader, 0x02014b50); WRITE_16(cdeHeader + 4, version); WRITE_16(cdeHeader + 6, version); WRITE_16(cdeHeader + 8, gpflag); WRITE_16(cdeHeader + 10, method); WRITE_16(cdeHeader + 12, filetime); WRITE_16(cdeHeader + 14, filedate); WRITE_32(cdeHeader + 16, crc); WRITE_32(cdeHeader + 20, cpsize); WRITE_32(cdeHeader + 24, uncpsize); WRITE_16(cdeHeader + 28, fnsize); WRITE_16(cdeHeader + 30, extsize); WRITE_16(cdeHeader + 32, comsize); WRITE_16(cdeHeader + 34, 0); /* disk # */ WRITE_16(cdeHeader + 36, 0); /* int attrb */ WRITE_32(cdeHeader + 38, 0); /* ext attrb */ WRITE_32(cdeHeader + 42, currentOffset); /* Header */ if (fwrite(cdeHeader, 1, 46, fpOutCD) == 46) { offsetCD += 46; /* Filename */ if (fnsize > 0) { if (fwrite(filename, 1, fnsize, fpOutCD) == fnsize) { offsetCD += fnsize; } else { err = Z_ERRNO; break; } } else { err = Z_STREAM_ERROR; break; } /* Extra field */ if (extsize > 0) { if (fwrite(extra, 1, extsize, fpOutCD) == extsize) { offsetCD += extsize; } else { err = Z_ERRNO; break; } } /* Comment field */ if (comsize > 0) { if ((int)fwrite(comment, 1, comsize, fpOutCD) == comsize) { offsetCD += comsize; } else { err = Z_ERRNO; break; } } } else { err = Z_ERRNO; break; } } /* Success */ entries++; } else { break; } } /* Final central directory */ { int entriesZip = entries; char fcdHeader[22]; char* comment = ""; // "ZIP File recovered by zlib/minizip/mztools"; int comsize = (int) strlen(comment); if (entriesZip > 0xffff) { entriesZip = 0xffff; } WRITE_32(fcdHeader, 0x06054b50); WRITE_16(fcdHeader + 4, 0); /* disk # */ WRITE_16(fcdHeader + 6, 0); /* disk # */ WRITE_16(fcdHeader + 8, entriesZip); /* hack */ WRITE_16(fcdHeader + 10, entriesZip); /* hack */ WRITE_32(fcdHeader + 12, offsetCD); /* size of CD */ WRITE_32(fcdHeader + 16, offset); /* offset to CD */ WRITE_16(fcdHeader + 20, comsize); /* comment */ /* Header */ if (fwrite(fcdHeader, 1, 22, fpOutCD) == 22) { /* Comment field */ if (comsize > 0) { if ((int)fwrite(comment, 1, comsize, fpOutCD) != comsize) { err = Z_ERRNO; } } } else { err = Z_ERRNO; } } /* Final merge (file + central directory) */ fclose(fpOutCD); if (err == Z_OK) { fpOutCD = fopen(fileOutTmp, "rb"); if (fpOutCD != NULL) { int nRead; char buffer[8192]; while ( (nRead = (int)fread(buffer, 1, sizeof(buffer), fpOutCD)) > 0) { if ((int)fwrite(buffer, 1, nRead, fpOut) != nRead) { err = Z_ERRNO; break; } } fclose(fpOutCD); } } /* Close */ fclose(fpZip); fclose(fpOut); /* Wipe temporary file */ (void)remove(fileOutTmp); /* Number of recovered entries */ if (err == Z_OK) { if (nRecovered != NULL) { *nRecovered = entries; } if (bytesRecovered != NULL) { *bytesRecovered = totalBytes; } } } else { err = Z_STREAM_ERROR; } return err; }
222
./osx-keychain-java/src/c/com_mcdermottroe_apple_OSXKeychain.c
/* * Copyright (c) 2011, Conor McDermottroe * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - 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. * * 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 HOLDER 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 <Security/Security.h> #include "com_mcdermottroe_apple_OSXKeychain.h" #include <string.h> #include <strings.h> #define OSXKeychainException "com/mcdermottroe/apple/OSXKeychainException" /* A simplified structure for dealing with jstring objects. Use jstring_unpack * and jstring_unpacked_free to manage these. */ typedef struct { int len; const char* str; } jstring_unpacked; /* Throw an exception. * * Parameters: * env The JNI environment. * exceptionClass The name of the exception class. * message The message to pass to the Exception. */ void throw_exception(JNIEnv* env, const char* exceptionClass, const char* message) { jclass cls = (*env)->FindClass(env, exceptionClass); /* if cls is NULL, an exception has already been thrown */ if (cls != NULL) { (*env)->ThrowNew(env, cls, message); } /* free the local ref, utility funcs must delete local refs. */ (*env)->DeleteLocalRef(env, cls); } /* Shorthand for throwing an OSXKeychainException from an OSStatus. * * Parameters: * env The JNI environment. * status The non-error status returned from a keychain call. */ void throw_osxkeychainexception(JNIEnv* env, OSStatus status) { CFStringRef errorMessage = SecCopyErrorMessageString(status, NULL); throw_exception( env, OSXKeychainException, CFStringGetCStringPtr(errorMessage, kCFStringEncodingMacRoman) ); CFRelease(errorMessage); } /* Unpack the data from a jstring and put it in a jstring_unpacked. * * Parameters: * env The JNI environment. * js The jstring to unpack. * ret The jstring_unpacked in which to store the result. */ void jstring_unpack(JNIEnv* env, jstring js, jstring_unpacked* ret) { if (ret == NULL) { return; } if (env == NULL || js == NULL) { ret->len = 0; ret->str = NULL; return; } /* Get the length of the string. */ ret->len = (int)((*env)->GetStringUTFLength(env, js)); if (ret->len <= 0) { ret->len = 0; ret->str = NULL; return; } ret->str = (*env)->GetStringUTFChars(env, js, NULL); } /* Clean up a jstring_unpacked after it's no longer needed. * * Parameters: * jsu A jstring_unpacked structure to clean up. */ void jstring_unpacked_free(JNIEnv *env, jstring js, jstring_unpacked* jsu) { if (jsu != NULL && jsu->str != NULL) { (*env)->ReleaseStringUTFChars(env, js, jsu->str); jsu->len = 0; jsu->str = NULL; } } /* Implementation of OSXKeychain.addGenericPassword(). See the Java docs for * explanations of the parameters. */ JNIEXPORT void JNICALL Java_com_mcdermottroe_apple_OSXKeychain__1addGenericPassword(JNIEnv* env, jobject obj, jstring serviceName, jstring accountName, jstring password) { OSStatus status; jstring_unpacked service_name; jstring_unpacked account_name; jstring_unpacked service_password; /* Unpack the params */ jstring_unpack(env, serviceName, &service_name); jstring_unpack(env, accountName, &account_name); jstring_unpack(env, password, &service_password); /* check for allocation failures */ if (service_name.str == NULL || account_name.str == NULL || service_password.str == NULL) { jstring_unpacked_free(env, serviceName, &service_name); jstring_unpacked_free(env, accountName, &account_name); jstring_unpacked_free(env, password, &service_password); return; } /* Add the details to the keychain. */ status = SecKeychainAddGenericPassword( NULL, service_name.len, service_name.str, account_name.len, account_name.str, service_password.len, service_password.str, NULL ); if (status != errSecSuccess) { throw_osxkeychainexception(env, status); } /* Clean up. */ jstring_unpacked_free(env, serviceName, &service_name); jstring_unpacked_free(env, accountName, &account_name); jstring_unpacked_free(env, password, &service_password); } JNIEXPORT void JNICALL Java_com_mcdermottroe_apple_OSXKeychain__1modifyGenericPassword(JNIEnv *env, jobject obj, jstring serviceName, jstring accountName, jstring password) { OSStatus status; jstring_unpacked service_name; jstring_unpacked account_name; jstring_unpacked service_password; SecKeychainItemRef existingItem; /* Unpack the params */ jstring_unpack(env, serviceName, &service_name); jstring_unpack(env, accountName, &account_name); jstring_unpack(env, password, &service_password); /* check for allocation failures */ if (service_name.str == NULL || account_name.str == NULL || service_password.str == NULL) { jstring_unpacked_free(env, serviceName, &service_name); jstring_unpacked_free(env, accountName, &account_name); jstring_unpacked_free(env, password, &service_password); return; } status = SecKeychainFindGenericPassword( NULL, service_name.len, service_name.str, account_name.len, account_name.str, NULL, NULL, &existingItem ); if (status != errSecSuccess) { throw_osxkeychainexception(env, status); } else { /* Update the details in the keychain. */ status = SecKeychainItemModifyContent( existingItem, NULL, service_password.len, service_password.str ); if (status != errSecSuccess) { throw_osxkeychainexception(env, status); } } /* Clean up. */ jstring_unpacked_free(env, serviceName, &service_name); jstring_unpacked_free(env, accountName, &account_name); jstring_unpacked_free(env, password, &service_password); } /* Implementation of OSXKeychain.addInternetPassword(). See the Java docs for * explanation of the parameters. */ JNIEXPORT void JNICALL Java_com_mcdermottroe_apple_OSXKeychain__1addInternetPassword(JNIEnv* env, jobject obj, jstring serverName, jstring securityDomain, jstring accountName, jstring path, jint port, jint protocol, jint authenticationType, jstring password) { OSStatus status; jstring_unpacked server_name; jstring_unpacked security_domain; jstring_unpacked account_name; jstring_unpacked server_path; jstring_unpacked server_password; /* Unpack the string params. */ jstring_unpack(env, serverName, &server_name); jstring_unpack(env, securityDomain, &security_domain); jstring_unpack(env, accountName, &account_name); jstring_unpack(env, path, &server_path); jstring_unpack(env, password, &server_password); /* check for allocation failures */ if (server_name.str == NULL || security_domain.str == NULL || account_name.str == NULL || server_path.str == NULL || server_password.str == NULL) { jstring_unpacked_free(env, serverName, &server_name); jstring_unpacked_free(env, securityDomain, &security_domain); jstring_unpacked_free(env, accountName, &account_name); jstring_unpacked_free(env, path, &server_path); jstring_unpacked_free(env, password, &server_password); return; } /* Add the details to the keychain. */ status = SecKeychainAddInternetPassword( NULL, server_name.len, server_name.str, security_domain.len, security_domain.str, account_name.len, account_name.str, server_path.len, server_path.str, port, protocol, authenticationType, server_password.len, server_password.str, NULL ); if (status != errSecSuccess) { throw_osxkeychainexception(env, status); } /* Clean up. */ jstring_unpacked_free(env, serverName, &server_name); jstring_unpacked_free(env, securityDomain, &security_domain); jstring_unpacked_free(env, accountName, &account_name); jstring_unpacked_free(env, path, &server_path); jstring_unpacked_free(env, password, &server_password); } /* Implementation of OSXKeychain.findGenericPassword(). See the Java docs for * explanations of the parameters. */ JNIEXPORT jstring JNICALL Java_com_mcdermottroe_apple_OSXKeychain__1findGenericPassword(JNIEnv* env, jobject obj, jstring serviceName, jstring accountName) { OSStatus status; jstring_unpacked service_name; jstring_unpacked account_name; jstring result = NULL; /* Buffer for the return from SecKeychainFindGenericPassword. */ void* password; UInt32 password_length; /* Query the keychain. */ status = SecKeychainSetPreferenceDomain(kSecPreferencesDomainUser); if (status != errSecSuccess) { throw_osxkeychainexception(env, status); return NULL; } /* Unpack the params. */ jstring_unpack(env, serviceName, &service_name); jstring_unpack(env, accountName, &account_name); if (service_name.str == NULL || account_name.str == NULL) { jstring_unpacked_free(env, serviceName, &service_name); jstring_unpacked_free(env, accountName, &account_name); return NULL; } status = SecKeychainFindGenericPassword( NULL, service_name.len, service_name.str, account_name.len, account_name.str, &password_length, &password, NULL ); if (status != errSecSuccess) { throw_osxkeychainexception(env, status); } else { // the returned value from keychain is not // null terminated, so a copy is created. char *password_buffer = malloc(password_length+1); memcpy(password_buffer, password, password_length); password_buffer[password_length] = 0; /* Create the return value. */ result = (*env)->NewStringUTF(env, password_buffer); /* Clean up. */ bzero(password_buffer, password_length); free(password_buffer); SecKeychainItemFreeContent(NULL, password); } jstring_unpacked_free(env, serviceName, &service_name); jstring_unpacked_free(env, accountName, &account_name); return result; } /* Implementation of OSXKeychain.findInternetPassword(). See the Java docs for * explanations of the parameters. */ JNIEXPORT jstring JNICALL Java_com_mcdermottroe_apple_OSXKeychain__1findInternetPassword(JNIEnv* env, jobject obj, jstring serverName, jstring securityDomain, jstring accountName, jstring path, jint port) { OSStatus status; jstring_unpacked server_name; jstring_unpacked security_domain; jstring_unpacked account_name; jstring_unpacked server_path; jstring result = NULL; /* This is the password buffer which will be used by * SecKeychainFindInternetPassword */ void* password; UInt32 password_length; /* Query the keychain */ status = SecKeychainSetPreferenceDomain(kSecPreferencesDomainUser); if (status != errSecSuccess) { throw_osxkeychainexception(env, status); return NULL; } /* Unpack all the jstrings into useful structures. */ jstring_unpack(env, serverName, &server_name); jstring_unpack(env, securityDomain, &security_domain); jstring_unpack(env, accountName, &account_name); jstring_unpack(env, path, &server_path); if (server_name.str == NULL || security_domain.str == NULL || account_name.str == NULL || server_path.str == NULL) { jstring_unpacked_free(env, serverName, &server_name); jstring_unpacked_free(env, securityDomain, &security_domain); jstring_unpacked_free(env, accountName, &account_name); jstring_unpacked_free(env, path, &server_path); return NULL; } status = SecKeychainFindInternetPassword( NULL, server_name.len, server_name.str, security_domain.len, security_domain.str, account_name.len, account_name.str, server_path.len, server_path.str, port, kSecProtocolTypeAny, kSecAuthenticationTypeAny, &password_length, &password, NULL ); if (status != errSecSuccess) { throw_osxkeychainexception(env, status); } else { // the returned value from keychain is not // null terminated, so a copy is created. char* password_buffer = (char *) malloc(password_length+1); memcpy(password_buffer, password, password_length); password_buffer[password_length] = 0; /* Create the return value. */ result = (*env)->NewStringUTF(env, password_buffer); /* Clean up. */ bzero(password_buffer, password_length); free(password_buffer); SecKeychainItemFreeContent(NULL, password); } jstring_unpacked_free(env, serverName, &server_name); jstring_unpacked_free(env, securityDomain, &security_domain); jstring_unpacked_free(env, accountName, &account_name); jstring_unpacked_free(env, path, &server_path); return result; } /* Implementation of OSXKeychain.deleteGenericPassword(). See the Java docs for * explanations of the parameters. */ JNIEXPORT void JNICALL Java_com_mcdermottroe_apple_OSXKeychain__1deleteGenericPassword(JNIEnv* env, jobject obj, jstring serviceName, jstring accountName) { OSStatus status; jstring_unpacked service_name; jstring_unpacked account_name; SecKeychainItemRef itemToDelete; /* Query the keychain. */ status = SecKeychainSetPreferenceDomain(kSecPreferencesDomainUser); if (status != errSecSuccess) { throw_osxkeychainexception(env, status); return; } /* Unpack the params. */ jstring_unpack(env, serviceName, &service_name); jstring_unpack(env, accountName, &account_name); if (service_name.str == NULL || account_name.str == NULL) { jstring_unpacked_free(env, serviceName, &service_name); jstring_unpacked_free(env, accountName, &account_name); return; } status = SecKeychainFindGenericPassword( NULL, service_name.len, service_name.str, account_name.len, account_name.str, NULL, NULL, &itemToDelete ); if (status != errSecSuccess) { throw_osxkeychainexception(env, status); } else { status = SecKeychainItemDelete(itemToDelete); if (status != errSecSuccess) { throw_osxkeychainexception(env, status); } } /* Clean up. */ jstring_unpacked_free(env, serviceName, &service_name); jstring_unpacked_free(env, accountName, &account_name); }
223
./osx-keychain-java/src/c/codegen/generate_enums.c
/* * Copyright (c) 2011, Conor McDermottroe * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - 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. * * 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 HOLDER 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. */ /* This short program is used to generate OSXKeychainAuthenticationType.java * and OSXKeychainProtocolType.java which are simply mirrors of * kSecAuthenticationType* and kSecProtocolType*. */ #include <Security/Security.h> #define ENUM_CLASS_HEAD(file, classname) fprintf(file, "\ package com.mcdermottroe.apple;\n\ \n\ /** Auto-generated from Security.h, see the Keychain Services Reference for\n\ * descriptions of what these constants mean.\n\ */\n\ public enum %s {\n", classname); #define ENUM_VALUE(file, name, value) fprintf(file, "\t/** " #value " */\n\t" name "(\"" name "\", %d)", value) #define ENUM_VALUE_DEF(file, name, value) ENUM_VALUE(file, name, value); fprintf(file, ",\n\n"); #define ENUM_VALUE_LAST(file, name, value) ENUM_VALUE(file, name, value); fprintf(file, ";\n"); #define ENUM_CLASS_TAIL(file, classname) fprintf(file, "\ \n\ \t/** The name of the constant. */\n\ \tprivate final String symbol;\n\ \n\ \t/** The value of the constant. */\n\ \tprivate final int value;\n\ \n\ \t/** Create the constant. \n\ \t *\n\ \t *\t@param sym The name of the constant.\n\ \t *\t@param val The value of the constant.\n\ \t */\n\ \t" classname "(String sym, int val) {\n\ \t\tsymbol = sym;\n\ \t\tvalue = val;\n\ \t}\n\ \n\ \t/** Get the value of the constant.\n\ \t *\n\ \t *\t@return The value of the constant.\n\ \t */\n\ \tpublic int getValue() {\n\ \t\treturn value;\n\ \t}\n\ \n\ \t/** {@inheritDoc} */\n\ \t@Override\n\ \tpublic String toString() {\n\ \t\treturn symbol;\n\ \t}\n\ }\n\ "); /* Create OSXKeychainAuthenticationType.java. */ void generateOSXKeychainAuthenticationType(const char* filename) { FILE* file; file = fopen(filename, "w"); ENUM_CLASS_HEAD(file, "OSXKeychainAuthenticationType"); ENUM_VALUE_DEF(file, "Any", kSecAuthenticationTypeAny); ENUM_VALUE_DEF(file, "DPA", kSecAuthenticationTypeDPA); ENUM_VALUE_DEF(file, "Default", kSecAuthenticationTypeDefault); ENUM_VALUE_DEF(file, "HTMLForm", kSecAuthenticationTypeHTMLForm); ENUM_VALUE_DEF(file, "HTTPBasic", kSecAuthenticationTypeHTTPBasic); ENUM_VALUE_DEF(file, "HTTPDigest", kSecAuthenticationTypeHTTPDigest); ENUM_VALUE_DEF(file, "MSN", kSecAuthenticationTypeMSN); ENUM_VALUE_DEF(file, "NTLM", kSecAuthenticationTypeNTLM); ENUM_VALUE_LAST(file, "RPA", kSecAuthenticationTypeRPA); ENUM_CLASS_TAIL(file, "OSXKeychainAuthenticationType"); fclose(file); } /* Create OSXKeychainProtocolType.java. */ void generateOSXKeychainProtocolType(const char* filename) { FILE* file; file = fopen(filename, "w"); ENUM_CLASS_HEAD(file, "OSXKeychainProtocolType"); ENUM_VALUE_DEF(file, "AFP", kSecProtocolTypeAFP); ENUM_VALUE_DEF(file, "Any", kSecProtocolTypeAny); ENUM_VALUE_DEF(file, "AppleTalk", kSecProtocolTypeAppleTalk); ENUM_VALUE_DEF(file, "CIFS", kSecProtocolTypeCIFS); ENUM_VALUE_DEF(file, "CVSpserver", kSecProtocolTypeCVSpserver); ENUM_VALUE_DEF(file, "DAAP", kSecProtocolTypeDAAP); ENUM_VALUE_DEF(file, "EPPC", kSecProtocolTypeEPPC); ENUM_VALUE_DEF(file, "FTP", kSecProtocolTypeFTP); ENUM_VALUE_DEF(file, "FTPAccount", kSecProtocolTypeFTPAccount); ENUM_VALUE_DEF(file, "FTPProxy", kSecProtocolTypeFTPProxy); ENUM_VALUE_DEF(file, "FTPS", kSecProtocolTypeFTPS); ENUM_VALUE_DEF(file, "HTTP", kSecProtocolTypeHTTP); ENUM_VALUE_DEF(file, "HTTPProxy", kSecProtocolTypeHTTPProxy); ENUM_VALUE_DEF(file, "HTTPS", kSecProtocolTypeHTTPS); ENUM_VALUE_DEF(file, "HTTPSProxy", kSecProtocolTypeHTTPSProxy); ENUM_VALUE_DEF(file, "IMAP", kSecProtocolTypeIMAP); ENUM_VALUE_DEF(file, "IMAPS", kSecProtocolTypeIMAPS); ENUM_VALUE_DEF(file, "IPP", kSecProtocolTypeIPP); ENUM_VALUE_DEF(file, "IRC", kSecProtocolTypeIRC); ENUM_VALUE_DEF(file, "IRCS", kSecProtocolTypeIRCS); ENUM_VALUE_DEF(file, "LDAP", kSecProtocolTypeLDAP); ENUM_VALUE_DEF(file, "LDAPS", kSecProtocolTypeLDAPS); ENUM_VALUE_DEF(file, "NNTP", kSecProtocolTypeNNTP); ENUM_VALUE_DEF(file, "NNTPS", kSecProtocolTypeNNTPS); ENUM_VALUE_DEF(file, "POP3", kSecProtocolTypePOP3); ENUM_VALUE_DEF(file, "POP3S", kSecProtocolTypePOP3S); ENUM_VALUE_DEF(file, "RTSP", kSecProtocolTypeRTSP); ENUM_VALUE_DEF(file, "RTSPProxy", kSecProtocolTypeRTSPProxy); ENUM_VALUE_DEF(file, "SMB", kSecProtocolTypeSMB); ENUM_VALUE_DEF(file, "SMTP", kSecProtocolTypeSMTP); ENUM_VALUE_DEF(file, "SOCKS", kSecProtocolTypeSOCKS); ENUM_VALUE_DEF(file, "SSH", kSecProtocolTypeSSH); ENUM_VALUE_DEF(file, "SVN", kSecProtocolTypeSVN); ENUM_VALUE_DEF(file, "Telnet", kSecProtocolTypeTelnet); ENUM_VALUE_LAST(file, "TelnetS", kSecProtocolTypeTelnetS); ENUM_CLASS_TAIL(file, "OSXKeychainProtocolType"); fclose(file); } /* The program takes two arguments, the first is the path to * OSXKeychainAuthenticationType.java, the second is the path to * OSXKeychainProtocolType.java. */ int main(int argc, char** argv, char** envp) { if (argc != 3) { printf("Usage: %s /path/to/OSXKeychainAuthenticationType.java /path/to/OSXKeychainProtocolType.java\n", argv[0]); return 1; } generateOSXKeychainAuthenticationType(argv[1]); generateOSXKeychainProtocolType(argv[2]); return 0; }
224
./osx-keychain-java/test/c/test.c
/* * Copyright (c) 2011, Conor McDermottroe * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - 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. * * 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 HOLDER 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. */ /* A very simple set of tests for the C portion of this library. */ #include "fakejni.h" #include "../../src/c/com_mcdermottroe_apple_OSXKeychain.c" #define SERVICE_NAME "Test OS X Keychain from Java" #define USERNAME "Test OS X Keychain User" #define PASSWORD "Test OS X Keychain Password" int main() { JNIEnv env; fakejni_env fakejni; jstring genericPassword; fakejni_init(&fakejni); env = &fakejni; /* Test a round-trip for a generic password. */ Java_com_mcdermottroe_apple_OSXKeychain__1addGenericPassword(&env, NULL, SERVICE_NAME, USERNAME, PASSWORD); genericPassword = Java_com_mcdermottroe_apple_OSXKeychain__1findGenericPassword(&env, NULL, SERVICE_NAME, USERNAME); if (strncmp(genericPassword, PASSWORD, strlen(PASSWORD)) != 0) { printf("Failed to round-trip the generic password.\n"); return 1; } Java_com_mcdermottroe_apple_OSXKeychain__1deleteGenericPassword(&env, NULL, SERVICE_NAME, USERNAME); return 0; }
225
./osx-keychain-java/test/c/fakejni.c
/* * Copyright (c) 2011, Conor McDermottroe * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - 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. * * 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 HOLDER 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 <stdio.h> #include <stdlib.h> #include <string.h> #include "fakejni.h" void fakejni_DeleteLocalRef(void *env, jobject lref) { } /* A replacement for JNI's (*env)->FindClass. Don't use the result of this * function for anything, bad things will happen if you do. */ void* fakejni_FindClass(void* env, const char* exceptionClass) { return (void*)"Don't use this"; } /* A replacement for JNI's (*env)->GetStringLength. */ int fakejni_GetStringLength(void* env, jstring str) { return strlen(str); } const jbyte * fakejni_GetStringUTFChars(void*env, jstring str, jboolean *isCopy) { int len = strlen(str); char *utf = (char *) calloc(len+1, sizeof(char)); memcpy(utf, str, len*sizeof(char)); utf[len] = '\0'; if (isCopy != NULL) { *isCopy = 1; } return utf; } jsize fakejni_GetStringUTFLength(void *env, jstring string) { return strlen(string); } /* A replacement for JNI's (*env)->GetStringUTFRegion. */ void fakejni_GetStringUTFRegion(void* env, jstring src, int offset, int length, char* dst) { int dstidx; int srcidx; for (dstidx = 0, srcidx = offset; dstidx < length; srcidx++, dstidx++) { dst[dstidx] = src[srcidx]; } } /* A replacement for JNI's (*env)->NewStringUTF. */ char* fakejni_NewStringUTF(void* env, char* str) { int len = strlen(str); char *utf = (char *) calloc(len+1, sizeof(char)); memcpy(utf, str, len*sizeof(char)); utf[len] = '\0'; return utf; } void fakejni_ReleaseStringUTFChars(void *env, jstring string, const char *utf) { free((void *) utf); } /* A replacement for JNI's (*env)->ThrowNew. */ void fakejni_ThrowNew(void* env, jclass cls, const char* message) { printf("Exception: %s\n", message); exit(1); } /* Initialise a fakejni_env. */ void fakejni_init(fakejni_env* env) { env->DeleteLocalRef = &fakejni_DeleteLocalRef; env->FindClass = &fakejni_FindClass; env->GetStringLength = &fakejni_GetStringLength; env->GetStringUTFRegion = &fakejni_GetStringUTFRegion; env->GetStringUTFChars = &fakejni_GetStringUTFChars; env->GetStringUTFLength = &fakejni_GetStringUTFLength; env->NewStringUTF = &fakejni_NewStringUTF; env->ReleaseStringUTFChars = fakejni_ReleaseStringUTFChars; env->ThrowNew = &fakejni_ThrowNew; }
226
./readme/mod.c
// ╨▐╕─╕├╬─╝■ #include<stdio.h> int main() { //│┬╦½╠φ╝╙╡─╫ó╩═ printf("Hello World!\n"); return 0; } // ═⌡═⌠╨▐╕─
227
./readme/del.c
// ╔╛│²╕├╬─╝■ #include<stdio.h> int main() { printf("Hello World!\n"); return 0; } // ═⌡═⌠╨▐╕─
228
./readme/wangwang.c
// ═⌡═⌠╘÷╝╙╕├╬─╝■ #include<stdio.h> int main() { printf("Hello World!\n"); return 0; } // #include<stdio.h> int main() { printf("Hello World!\n"); return 0; }
229
./pidgin-gpg/src/pidgin-gpg.c
/* * Pidgin - GPG Pidgin Plugin * * Copyright (C) 2010, Aerol <[email protected]> * Alexander Murauer <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #define PURPLE_PLUGINS #ifndef TRUE #define TRUE (1==1) #endif #ifndef FALSE #define FALSE (1==0) #endif #define PLUGIN_ID "core-segler-pidgin-gpg" #define PREF_ROOT "/plugins/core/core-segler-pidgin-gpg" #define PREF_MY_KEY "/plugins/core/core-segler-pidgin-gpg/my_key_fpr" #include "../config.h" #include <locale.h> #include <string.h> #include "notify.h" #include "plugin.h" #include "version.h" #include <pluginpref.h> #include <prefs.h> #include <debug.h> #include <gpgme.h> static GHashTable *list_fingerprints = NULL; struct list_item{ // the key-fingerprint of the receiver char* fpr; // true if connection mode is encrypted int mode_sec; // old mode_sec value, used to check if user has already been informed on possible mode_sec change int mode_sec_old; }; /* ------------------ * xmlnode.h lacks a method for clearing the data of a node * ------------------ */ void xmlnode_clear_data(xmlnode *node) { xmlnode *data_node, *sibling = NULL; g_return_if_fail(node != NULL); data_node = node->child; while (data_node) { if(data_node->type == XMLNODE_TYPE_DATA) { if (node->lastchild == data_node) { node->lastchild = sibling; } if (sibling == NULL) { node->child = data_node->next; xmlnode_free(data_node); data_node = node->child; } else { sibling->next = data_node->next; xmlnode_free(data_node); data_node = sibling->next; } }else{ sibling = data_node; data_node = data_node->next; } } } /* ------------------ * armor a string * FREE MEMORY AFTER USAGE OF RETURN VALUE! * ------------------ */ static char* str_armor(const char* unarmored) { char* header = "-----BEGIN PGP SIGNATURE-----\n\n"; char* footer = "\n-----END PGP SIGNATURE-----"; char* buffer = malloc(strlen(header)+strlen(footer)+strlen(unarmored)+1); strcpy(buffer, header); strcat(buffer, unarmored); strcat(buffer, footer); return buffer; } /* ------------------ * unarmor a string * FREE MEMORY AFTER USAGE OF RETURN VALUE! * ------------------ */ static char* str_unarmor(const char* armored) { char* pointer; int newlines = 0; char* footer = "-----END PGP SIGNATURE-----"; char* unarmored = NULL; pointer = (char*)armored; // jump over the first 3 lines while (newlines < 3) { if (pointer[0] == '\n') newlines++; pointer++; // return NULL if armored is too short if (strlen(pointer) == 0) return NULL; } unarmored = malloc(strlen(pointer)+1-strlen(footer)); strncpy(unarmored,pointer,strlen(pointer)-strlen(footer)); unarmored[strlen(pointer)-strlen(footer)] = 0; return unarmored; } /* ------------------ * strips resource info from jid * FREE MEMORY AFTER USAGE OF RETURN VALUE! * ------------------ */ static char* get_bare_jid(const char* jid) { int len = strcspn(jid,"/"); char* str = malloc(len+1); strncpy(str,jid,len); str[len] = 0; return str; } /* ------------------ * check if a key is locally available * ------------------ */ int is_key_available(const char* fpr,int secret, int servermode, char** userid) { gpgme_error_t error; gpgme_ctx_t ctx; gpgme_key_t key; gpgme_key_t key_arr[2]; gpgme_keylist_mode_t current_keylist_mode; key_arr[0] = NULL; key_arr[1] = NULL; // connect to gpgme gpgme_check_version (NULL); error = gpgme_new(&ctx); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_new failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); return FALSE; } // set to server search mode if servermode == TRUE if (servermode == TRUE) { purple_debug_info(PLUGIN_ID,"set keylist mode to server\n"); current_keylist_mode = gpgme_get_keylist_mode(ctx); gpgme_set_keylist_mode(ctx,(current_keylist_mode | GPGME_KEYLIST_MODE_EXTERN) &(~GPGME_KEYLIST_MODE_LOCAL)); } // get key by fingerprint error = gpgme_get_key(ctx,fpr,&key,secret); if (error || !key) { purple_debug_error(PLUGIN_ID,"gpgme_get_key failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); gpgme_release (ctx); return FALSE; } // if we have parameter, tell caller about userid if (userid != NULL) { *userid = g_strdup(key->uids->uid); } // import key key_arr[0] = key; error = gpgme_op_import_keys (ctx, key_arr); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_op_import_keys failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); gpgme_release (ctx); return FALSE; } // close gpgme connection gpgme_release (ctx); // we got the key, YEAH :) return TRUE; } /* ------------------ * get ascii armored public key * FREE MEMORY AFTER USAGE OF RETURN VALUE! * ------------------ */ char* get_key_armored(const char* fpr) { gpgme_error_t error; gpgme_ctx_t ctx; gpgme_data_t key_data; gpgme_key_t key; gpgme_key_t key_arr[2]; key_arr[0] = key_arr[1] = NULL; size_t len = 0; char* key_str = NULL; char* key_str_dup = NULL; // connect to gpgme gpgme_check_version (NULL); error = gpgme_new(&ctx); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_new failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); return NULL; } // get key by fingerprint error = gpgme_get_key(ctx,fpr,&key,0); if (error || !key) { purple_debug_error(PLUGIN_ID,"gpgme_get_key failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); gpgme_release (ctx); return NULL; } key_arr[0] = key; // create data containers gpgme_data_new(&key_data); // export key gpgme_set_armor(ctx,1); error = gpgme_op_export_keys (ctx, key_arr, 0, key_data); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_op_export_keys failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); gpgme_release (ctx); return NULL; } // release memory for data containers key_str = gpgme_data_release_and_get_mem(key_data,&len); if (key_str != NULL) { key_str[len] = 0; key_str_dup = g_strdup(key_str); } gpgme_free(key_str); // close gpgme connection gpgme_release (ctx); // we got the key, YEAH :) return key_str_dup; } /* ------------------ * import ascii armored key * ------------------ */ int import_key(char* armored_key) { gpgme_error_t error; gpgme_ctx_t ctx; gpgme_data_t keydata; gpgme_import_result_t result; // connect to gpgme gpgme_check_version (NULL); error = gpgme_new(&ctx); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_new failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); return FALSE; } purple_debug_info(PLUGIN_ID,"try to import key: %s\n",armored_key); // create data containers gpgme_data_new_from_mem (&keydata, armored_key,strlen(armored_key),1); // import key, ascii armored gpgme_set_armor(ctx,1); error = gpgme_op_import (ctx, keydata); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_op_import: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); gpgme_release (ctx); return FALSE; } result = gpgme_op_import_result (ctx); purple_debug_info(PLUGIN_ID,"considered keys: %d; imported keys: %d; not imported keys: %d\n",result->considered,result->imported,result->not_imported); // release memory for data containers gpgme_data_release(keydata); // close gpgme connection gpgme_release (ctx); return TRUE; } /* ------------------ * sign a plain string with the key found with fingerprint fpr * FREE MEMORY AFTER USAGE OF RETURN VALUE! * ------------------ */ static char* sign(const char* plain_str,const char* fpr) { gpgme_error_t error; gpgme_ctx_t ctx; gpgme_key_t key; gpgme_data_t plain,sig; const int MAX_LEN = 10000; char *sig_str = NULL; char *sig_str_dup = NULL; size_t len = 0; // connect to gpgme gpgme_check_version (NULL); error = gpgme_new(&ctx); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_new failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); return NULL; } // get key by fingerprint error = gpgme_get_key(ctx,fpr,&key,1); if (error || !key) { purple_debug_error(PLUGIN_ID,"gpgme_get_key failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); gpgme_release (ctx); return NULL; } // select signers gpgme_signers_clear(ctx); error = gpgme_signers_add (ctx,key); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_signers_add failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); gpgme_release (ctx); return NULL; } // create data containers gpgme_data_new_from_mem (&plain, plain_str,strlen(plain_str),1); gpgme_data_new(&sig); // sign message, ascii armored gpgme_set_armor(ctx,1); error = gpgme_op_sign(ctx,plain,sig,GPGME_SIG_MODE_DETACH); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_op_sign failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); gpgme_release (ctx); return NULL; } // release memory for data containers gpgme_data_release(plain); sig_str = gpgme_data_release_and_get_mem(sig,&len); if (sig_str != NULL) { sig_str[len] = 0; sig_str_dup = str_unarmor(sig_str); } gpgme_free(sig_str); // close gpgme connection gpgme_release (ctx); return sig_str_dup; } /* ------------------ * verify a signed string with the key found with fingerprint fpr * FREE MEMORY AFTER USAGE OF RETURN VALUE! * ------------------ */ static char* verify(const char* sig_str) { gpgme_error_t error; gpgme_ctx_t ctx; gpgme_data_t plain,sig,sig_text; gpgme_verify_result_t result; char* fpr = NULL; char* armored_sig_str = NULL; if (sig_str == NULL) { purple_debug_error(PLUGIN_ID,"verify got null parameter\n"); return NULL; } // connect to gpgme gpgme_check_version (NULL); error = gpgme_new(&ctx); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_new failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); return NULL; } // armor sig_str armored_sig_str = str_armor(sig_str); // create data containers gpgme_data_new_from_mem (&sig, armored_sig_str,strlen(armored_sig_str),1); gpgme_data_new(&plain); // try to verify error = gpgme_op_verify(ctx,sig,NULL,plain); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_op_verify failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); gpgme_release (ctx); return NULL; } // get result result = gpgme_op_verify_result (ctx); if (result != NULL) { if (result->signatures != NULL) { // return the fingerprint of the key that made the signature fpr = g_strdup(result->signatures->fpr); } } // release memory for data containers gpgme_data_release(sig); gpgme_data_release(plain); return fpr; } /* ------------------ * encrypt a plain string with the key found with fingerprint fpr * ------------------ */ static char* encrypt(const char* plain_str, const char* fpr) { gpgme_error_t error; gpgme_ctx_t ctx; gpgme_key_t key; gpgme_data_t plain,cipher; char* cipher_str = NULL; char* cipher_str_dup = NULL; size_t len; gpgme_key_t key_arr[2]; key_arr[0] = NULL; key_arr[1] = NULL; // connect to gpgme gpgme_check_version (NULL); error = gpgme_new(&ctx); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_new failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); return NULL; } // get key by fingerprint error = gpgme_get_key(ctx,fpr,&key,0); if (error || !key) { purple_debug_error(PLUGIN_ID,"gpgme_get_key failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); gpgme_release (ctx); return NULL; } key_arr[0] = key; // create data containers gpgme_data_new_from_mem (&plain, plain_str,strlen(plain_str),1); gpgme_data_new(&cipher); // encrypt, ascii armored gpgme_set_armor(ctx,1); error = gpgme_op_encrypt (ctx, key_arr,GPGME_ENCRYPT_ALWAYS_TRUST,plain,cipher); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_op_encrypt failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); gpgme_release (ctx); return NULL; } // release memory for data containers gpgme_data_release(plain); cipher_str = gpgme_data_release_and_get_mem(cipher,&len); if (cipher_str != NULL) { cipher_str[len] = 0; cipher_str_dup = str_unarmor(cipher_str); } gpgme_free(cipher_str); // close gpgme connection gpgme_release (ctx); return cipher_str_dup; } /* ------------------ * decrypt a plain string with the key found with fingerprint fpr * FREE MEMORY AFTER USAGE OF RETURN VALUE * ------------------ */ static char* decrypt(char* cipher_str) { gpgme_error_t error; gpgme_ctx_t ctx; gpgme_data_t plain,cipher; size_t len = 0; char* plain_str = NULL; char* plain_str_dup = NULL; char* armored_buffer; // add header and footer: armored_buffer = str_armor(cipher_str); // connect to gpgme gpgme_check_version (NULL); error = gpgme_new(&ctx); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_new failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); return NULL; } // create data containers gpgme_data_new_from_mem (&cipher, armored_buffer,strlen(armored_buffer),1); gpgme_data_new(&plain); // decrypt error = gpgme_op_decrypt(ctx,cipher,plain); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_op_decrypt failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); gpgme_release (ctx); return NULL; } // release memory for data containers gpgme_data_release(cipher); plain_str = gpgme_data_release_and_get_mem(plain,&len); if (plain_str != NULL) { plain_str[len] = 0; plain_str_dup = g_strdup(plain_str); } gpgme_free(plain_str); // close gpgme connection gpgme_release (ctx); return plain_str_dup; } /* ------------------ * initialize gpgme lib on module load * ------------------ */ static void init_gpgme () { const char* version; /* Initialize the locale environment. */ setlocale (LC_ALL, ""); version = gpgme_check_version (NULL); purple_debug_info(PLUGIN_ID,"Found gpgme version: %s\n",version); gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL)); // For W32 portability. #ifdef LC_MESSAGES gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL)); #endif } static const char* NS_SIGNED = "jabber:x:signed"; static const char* NS_ENC = "jabber:x:encrypted"; /* ------------------ * called on received message * ------------------ */ static gboolean jabber_message_received(PurpleConnection *pc, const char *type, const char *id, const char *from, const char *to, xmlnode *message) { const xmlnode* parent_node = message; xmlnode* x_node = NULL; xmlnode* body_node = NULL; if (parent_node == NULL) return FALSE; // check if message is a key body_node = xmlnode_get_child(parent_node,"body"); if (body_node != NULL) { char* data = xmlnode_get_data(body_node); if (data != NULL) { char* header = "-----BEGIN PGP PUBLIC KEY BLOCK-----"; if (strncmp(data,header,strlen(header)) == 0) { // if we received a ascii armored key // try to import it //purple_conversation_write(conv,"","received key",PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG,time(NULL)); if (import_key(data) == TRUE) { xmlnode_clear_data(body_node); xmlnode_insert_data(body_node,"key import ok",-1); } else { xmlnode_clear_data(body_node); xmlnode_insert_data(body_node,"key import failed",-1); } } } } // check if the user with the jid=from has signed his presence char* bare_jid = get_bare_jid(from); // get stored info about user struct list_item* item = g_hash_table_lookup(list_fingerprints,bare_jid); if (item == NULL) { //TODO: maybe create item in list? }else { // set default value to "not encrypted mode" item->mode_sec = FALSE; } free(bare_jid); // check if message has special "x" child node => encrypted message x_node = xmlnode_get_child_with_namespace(parent_node,"x",NS_ENC); if (x_node != NULL) { purple_debug_info(PLUGIN_ID, "user %s sent us an encrypted message\n",from); // get data of "x" node char* cipher_str = xmlnode_get_data(x_node); if (cipher_str != NULL) { // try to decrypt char* plain_str = decrypt(cipher_str); if (plain_str != NULL) { purple_debug_info(PLUGIN_ID, "decrypted message: %s\n",plain_str); // find body node xmlnode *body_node = xmlnode_get_child(parent_node,"body"); if (body_node != NULL) { // clear body node data if it is found xmlnode_clear_data(body_node); }else { // add body node if it is not found body_node = xmlnode_new_child(message,"body"); } // set "body" content node to decrypted string //xmlnode_insert_data(body_node,"Encrypted message: ",-1); xmlnode_insert_data(body_node,plain_str,-1); // only set to encrypted mode, if we know other users key fingerprint if (item != NULL) { // all went well, we received an encrypted message item->mode_sec = TRUE; } }else { purple_debug_error(PLUGIN_ID, "could not decrypt message!\n"); } }else { purple_debug_error(PLUGIN_ID, "xml token had no data!\n"); } } /* We don't want the plugin to stop processing */ return FALSE; } /* ------------------ * called on received presence * ------------------ */ static gboolean jabber_presence_received(PurpleConnection *pc, const char *type, const char *from, xmlnode *presence) { const xmlnode* parent_node = presence; xmlnode* x_node = NULL; // check if presence has special "x" childnode x_node = xmlnode_get_child_with_namespace(parent_node,"x",NS_SIGNED); if (x_node != NULL) { // user supports openpgp encryption purple_debug_info(PLUGIN_ID, "user %s supports openpgp encryption!\n",from); char* x_node_data = xmlnode_get_data(x_node); if (x_node_data != NULL) { // try to verify char* fpr = verify(x_node_data); if (fpr != NULL) { char* bare_jid = get_bare_jid(from); purple_debug_info(PLUGIN_ID, "user %s has fingerprint %s\n",bare_jid,fpr); // add key to list struct list_item *item = malloc(sizeof(struct list_item)); item->fpr = fpr; g_hash_table_replace(list_fingerprints,bare_jid,item); }else { purple_debug_error(PLUGIN_ID, "could not verify presence of user %s\n",from); } }else { purple_debug_info(PLUGIN_ID, "user %s sent empty signed presence\n",from); } } /* We don't want the plugin to stop processing */ return FALSE; } /* ------------------ * called on every sent packet * ------------------ */ void jabber_send_signal_cb(PurpleConnection *pc, xmlnode **packet, gpointer unused) { if (NULL == packet) return; g_return_if_fail(PURPLE_CONNECTION_IS_VALID(pc)); // if we are sending a presence stanza, add new child node // so others know we support openpgp if (g_str_equal((*packet)->name, "presence")) { const char* status_str = NULL; xmlnode* status_node; // check if user selected a main key const char* fpr = purple_prefs_get_string(PREF_MY_KEY); if (fpr == NULL) fpr = ""; if (strcmp(fpr,"") != 0) {// user did select a key // get status message from packet status_node = xmlnode_get_child(*packet,"status"); if (status_node != NULL) { status_str = xmlnode_get_data(status_node); } // sign status message if (status_str == NULL) status_str = ""; purple_debug_info(PLUGIN_ID, "signing status '%s' with key %s\n",status_str,fpr); char* sig_str = sign(status_str,fpr); if (sig_str == NULL) { purple_debug_error(PLUGIN_ID,"sign failed\n"); return; } // create special "x" childnode purple_debug_info(PLUGIN_ID, "sending presence with signature\n"); xmlnode *x_node = xmlnode_new_child(*packet,"x"); xmlnode_set_namespace(x_node, NS_SIGNED); xmlnode_insert_data(x_node, sig_str,-1); }else { purple_debug_info(PLUGIN_ID, "no key selecteded!\n"); } }else if (g_str_equal((*packet)->name, "message")) { const char* to = xmlnode_get_attrib(*packet,"to"); xmlnode* body_node = xmlnode_get_child(*packet,"body"); if (body_node != NULL && to != NULL) { // get message char* message = g_strdup(xmlnode_get_data(body_node)); char* enc_str = NULL; char* bare_jid = get_bare_jid(to); // get encryption key struct list_item *item = g_hash_table_lookup(list_fingerprints,bare_jid); if (item == NULL) { purple_debug_info(PLUGIN_ID, "there is no key for encrypting message to %s\n",bare_jid); return; } // do not encrypt if mode_sec is disabled if (item->mode_sec == FALSE) return; char* fpr_to = item->fpr; purple_debug_info(PLUGIN_ID, "found key for encryption to user %s: %s\n",bare_jid,fpr_to); free(bare_jid); // encrypt message enc_str = encrypt(message,fpr_to); if (enc_str != NULL) { // remove message from body xmlnode_clear_data(body_node); xmlnode_insert_data(body_node,"[ERROR: This message is encrypted, and you are unable to decrypt it.]",-1); // add special "x" childnode for encrypted text purple_debug_info(PLUGIN_ID, "sending encrypted message\n"); xmlnode *x_node = xmlnode_new_child(*packet,"x"); xmlnode_set_namespace(x_node, NS_ENC); xmlnode_insert_data(x_node, enc_str,-1); }else { purple_debug_error(PLUGIN_ID, "could not encrypt message\n"); } }else { // ignore this type of messages //purple_debug_warning(PLUGIN_ID, "empty message or empty 'to'\n"); } } } /* ------------------ * called on new conversations * ------------------ */ void conversation_created_cb(PurpleConversation *conv, char* data) { char sys_msg_buffer[1000]; if (purple_conversation_get_type(conv) != PURPLE_CONV_TYPE_IM) return; purple_debug_info(PLUGIN_ID, "conversation name: %s\n",conv->name); // check if the user with the jid=conv->name has signed his presence char* bare_jid = get_bare_jid(conv->name); // get stored info about user struct list_item* item = g_hash_table_lookup(list_fingerprints,bare_jid); if (item == NULL) { sprintf(sys_msg_buffer,"No encryption support in client of '%s'",bare_jid); }else { sprintf(sys_msg_buffer,"Client of user %s supports encryption",bare_jid); } // display a basic message purple_conversation_write(conv,"",sys_msg_buffer,PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG,time(NULL)); if (item != NULL) { char* userid = NULL; // check if we have key locally if (is_key_available(item->fpr,FALSE,FALSE,&userid) == FALSE) { if (userid != NULL) free(userid); userid = NULL; sprintf(sys_msg_buffer,"User has key with ID '%s', but we do not have it locally, try Options->\"Try to retrieve key of '%s' from server\"",item->fpr,bare_jid); purple_conversation_write(conv,"",sys_msg_buffer,PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG,time(NULL)); }else { // key is already available locally -> enable mode_enc sprintf(sys_msg_buffer,"'%s' uses key with id '%s'/'%s'",bare_jid,userid,item->fpr); purple_conversation_write(conv,"",sys_msg_buffer,PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG,time(NULL)); item->mode_sec = TRUE; } if (userid != NULL) free(userid); userid = NULL; // if we have the key now, move to secure mode if (item->mode_sec == TRUE) sprintf(sys_msg_buffer,"Encryption enabled"); else sprintf(sys_msg_buffer,"Encryption disabled"); }else sprintf(sys_msg_buffer,"Encryption disabled"); // display message about received message purple_conversation_write(conv,"",sys_msg_buffer,PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG,time(NULL)); free(bare_jid); } /* ------------------ * called before display of received messages * ------------------ */ static gboolean receiving_im_msg_cb(PurpleAccount *account, char **sender, char **buffer, PurpleConversation *conv, PurpleMessageFlags *flags, void *data) { char sys_msg_buffer[1000]; // check if the user with the jid=conv->name has signed his presence char* bare_jid = get_bare_jid(*sender); // set default message sprintf(sys_msg_buffer,"Encryption disabled"); // get encryption key struct list_item* item = g_hash_table_lookup(list_fingerprints,bare_jid); if (item != NULL) { if (item->mode_sec == TRUE) sprintf(sys_msg_buffer,"Encryption enabled"); // display a basic message, only if mode changed if (item->mode_sec != item->mode_sec_old) purple_conversation_write(conv,"",sys_msg_buffer,PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG,time(NULL)); item->mode_sec_old = item->mode_sec; } free(bare_jid); return FALSE; } /* ------------------ * conversation menu action, that toggles mode_sec * ------------------ */ static void menu_action_toggle_cb(PurpleConversation *conv, void* data) { // check if the user with the jid=conv->name has signed his presence char* bare_jid = get_bare_jid(conv->name); // get stored info about user struct list_item* item = g_hash_table_lookup(list_fingerprints,bare_jid); if (item != NULL) { item->mode_sec = !(item->mode_sec); item->mode_sec_old = item->mode_sec; // tell user, that we toggled mode purple_conversation_write(conv,"",item->mode_sec?"Encryption enabled":"Encryption disabled",PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG,time(NULL)); } free(bare_jid); } /* ------------------ * send public key to other person in conversation * ------------------ */ static void menu_action_sendkey_cb(PurpleConversation *conv, void* data) { // check if user selected a main key const char* fpr = purple_prefs_get_string(PREF_MY_KEY); if (fpr == NULL) fpr = ""; if (strcmp(fpr,"") != 0) { char* key = NULL; // get key key = get_key_armored(fpr); if (key != NULL) { // send key PurpleConvIm* im_data = purple_conversation_get_im_data(conv); if (im_data != NULL) { purple_conv_im_send_with_flags(im_data,key,PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_INVISIBLE | PURPLE_MESSAGE_RAW ); purple_conversation_write(conv,"","Public key sent!",PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG,time(NULL)); } } }else { purple_conversation_write(conv,"","You haven't selected a personal key yet.",PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG,time(NULL)); } } /* ------------------ * try to retrieve key from server * ------------------ */ static void menu_action_retrievekey_cb(PurpleConversation *conv, void* data) { char sys_msg_buffer[1000]; // check if the user with the jid=conv->name has signed his presence char* bare_jid = get_bare_jid(conv->name); // get stored info about user struct list_item* item = g_hash_table_lookup(list_fingerprints,bare_jid); if (item != NULL) { char* userid = NULL; if (is_key_available(item->fpr,FALSE,TRUE,&userid) == FALSE) { sprintf(sys_msg_buffer,"Did not find key with ID '%s' on keyservers.",item->fpr); purple_conversation_write(conv,"",sys_msg_buffer,PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG,time(NULL)); }else { // found key -> enable mode_enc sprintf(sys_msg_buffer,"Found key with ID '%s'/'%s' for '%s' on keyservers.",item->fpr,userid,bare_jid); purple_conversation_write(conv,"",sys_msg_buffer,PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG,time(NULL)); purple_conversation_write(conv,"","Encryption enabled",PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG,time(NULL)); item->mode_sec = TRUE; } if (userid != NULL) free(userid); } free(bare_jid); } /* ------------------ * conversation extended menu * ------------------ */ void conversation_extended_menu_cb(PurpleConversation *conv, GList **list) { char buffer[1000]; PurpleMenuAction *action = NULL; // check if the user with the jid=conv->name has signed his presence char* bare_jid = get_bare_jid(conv->name); // get stored info about user struct list_item* item = g_hash_table_lookup(list_fingerprints,bare_jid); if (item != NULL) { // on display encryption menu item, if user sent signed presence action = purple_menu_action_new("Toggle OPENPGP encryption", PURPLE_CALLBACK(menu_action_toggle_cb),NULL,NULL); *list = g_list_append(*list, action); sprintf(buffer,"Send own public key to '%s'",bare_jid); action = purple_menu_action_new(buffer, PURPLE_CALLBACK(menu_action_sendkey_cb),NULL,NULL); *list = g_list_append(*list, action); sprintf(buffer,"Try to retrieve key of '%s' from server",bare_jid); action = purple_menu_action_new(buffer, PURPLE_CALLBACK(menu_action_retrievekey_cb),NULL,NULL); *list = g_list_append(*list, action); } free(bare_jid); } /* ------------------ * called before message is sent * ------------------ */ void sending_im_msg_cb(PurpleAccount *account, const char *receiver, char **message) { PurpleConversation *gconv = NULL; // search for conversation gconv = purple_find_conversation_with_account(PURPLE_CONV_TYPE_IM, receiver, account); if(gconv) { // check if the user with the jid=conv->name has signed his presence char* bare_jid = get_bare_jid(gconv->name); // get stored info about user struct list_item* item = g_hash_table_lookup(list_fingerprints,bare_jid); if (item != NULL) { // if we are in private mode if (item->mode_sec == TRUE) { // try to get key if (is_key_available(item->fpr,FALSE,FALSE,NULL) == FALSE) { // we do not have key of receiver // -> cancel message sending free (*message); *message = NULL; // tell user of this purple_conversation_write(gconv,"","The key of the receiver is not available, please ask the receiver for the key before trying to encrypt messages.",PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG,time(NULL)); } } } free(bare_jid); } } /* ------------------ * called on module load * ------------------ */ static gboolean plugin_load(PurplePlugin *plugin) { // check if hashtable already created if (list_fingerprints == NULL) list_fingerprints = g_hash_table_new(g_str_hash,g_str_equal); // register presence receiver handler void *jabber_handle = purple_plugins_find_with_id("prpl-jabber"); void *conv_handle = purple_conversations_get_handle(); if (conv_handle != NULL) { purple_signal_connect(conv_handle, "conversation-created", plugin, PURPLE_CALLBACK(conversation_created_cb), NULL); purple_signal_connect(conv_handle, "receiving-im-msg", plugin, PURPLE_CALLBACK(receiving_im_msg_cb), NULL); purple_signal_connect(conv_handle, "conversation-extended-menu", plugin, PURPLE_CALLBACK(conversation_extended_menu_cb), NULL); purple_signal_connect(conv_handle, "sending-im-msg", plugin, PURPLE_CALLBACK(sending_im_msg_cb), NULL); }else return FALSE; if (jabber_handle) { purple_signal_connect(jabber_handle, "jabber-receiving-message", plugin,PURPLE_CALLBACK(jabber_message_received), NULL); purple_signal_connect(jabber_handle, "jabber-receiving-presence", plugin,PURPLE_CALLBACK(jabber_presence_received), NULL); purple_signal_connect(jabber_handle, "jabber-sending-xmlnode", plugin, PURPLE_CALLBACK(jabber_send_signal_cb), NULL); }else return FALSE; /* Initialize everything needed; get the passphrase for encrypting and decrypting messages. Attach to all windows the chat windows. */ /* attach_to_all_windows(); purple_signal_connect(pidgin_conversations_get_handle(), "conversation-displayed", plugin, PURPLE_CALLBACK(conv_created), NULL); purple_signal_connect(purple_conversations_get_handle(), "conversation-extended-menu", plugin, PURPLE_CALLBACK(conv_menu_cb), NULL);*/ // initialize gpgme lib on module load init_gpgme(); return TRUE; } /*static gboolean plugin_unload(PurplePlugin *plugin) { detach_from_all_windows(); return TRUE; }*/ /* ------------------ * preferences dialog function * ------------------ */ static PurplePluginPrefFrame * get_plugin_pref_frame(PurplePlugin *plugin) { PurplePluginPrefFrame *frame; PurplePluginPref *ppref; gpgme_error_t error; gpgme_ctx_t ctx; gpgme_key_t key; // create preferences frame frame = purple_plugin_pref_frame_new(); // connect to gpgme gpgme_check_version (NULL); error = gpgme_new(&ctx); if (error) { purple_debug_error(PLUGIN_ID,"gpgme_new failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); return NULL; } // create key chooser preference ppref = purple_plugin_pref_new_with_name_and_label(PREF_MY_KEY,"My key"); purple_plugin_pref_set_type(ppref, PURPLE_PLUGIN_PREF_CHOICE); purple_plugin_pref_add_choice(ppref, "None", ""); // list keys (secret keys) error = gpgme_op_keylist_start (ctx,NULL,1); if (error == GPG_ERR_NO_ERROR) { while (!error) { error = gpgme_op_keylist_next (ctx, &key); if (error) break; // add key to preference chooser //TODO: find something better for g_strdup, or some possibility to free memory after preferences dialog closed purple_plugin_pref_add_choice(ppref, g_strdup(key->uids->uid), g_strdup(key->subkeys->fpr)); purple_debug_info(PLUGIN_ID,"Found secret key for: %s has fpr %s\n",key->uids->uid,key->subkeys->fpr); gpgme_key_release (key); } }else { purple_debug_error(PLUGIN_ID,"gpgme_op_keylist_start failed: %s %s\n",gpgme_strsource (error), gpgme_strerror (error)); } // close gpgme connection gpgme_release (ctx); purple_plugin_pref_frame_add(frame, ppref); return frame; } /* ------------------ * The plugin ui info struct for preferences dialog * ------------------ */ static PurplePluginUiInfo prefs_info = { get_plugin_pref_frame, 0, /* page_num (Reserved) */ NULL, /* frame (Reserved) */ /* Padding */ NULL, NULL, NULL, NULL }; /* ------------------ * The plugin info struct * ------------------ */ static PurplePluginInfo info = { PURPLE_PLUGIN_MAGIC, PURPLE_MAJOR_VERSION, PURPLE_MINOR_VERSION, PURPLE_PLUGIN_STANDARD, NULL, 0, NULL, PURPLE_PRIORITY_DEFAULT, PLUGIN_ID, "GPG/OPENPGP (XEP-0027)", "0.9", "GPG Plugin for Pidgin", "Simple GPG Plugin for Pidgin.", "Alexander Murauer <[email protected]>", "https://github.com/segler-alex/Pidgin-GPG", plugin_load, NULL, NULL, NULL, NULL, &prefs_info, NULL, NULL, NULL, NULL, NULL }; /* ------------------ * plugin init * ------------------ */ static void init_plugin(PurplePlugin *plugin) { // create entries in prefs if they are not there purple_prefs_add_none(PREF_ROOT); purple_prefs_add_string(PREF_MY_KEY, ""); } PURPLE_INIT_PLUGIN(pidgin-gpg, init_plugin, info)
230
./android_firewall/external/iptables/utils/nfnl_osf.c
/* * Copyright (c) 2005 Evgeniy Polyakov <[email protected]> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <sys/types.h> #include <sys/socket.h> #include <sys/poll.h> #include <sys/time.h> #include <arpa/inet.h> #include <ctype.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <time.h> #include <unistd.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <linux/connector.h> #include <linux/types.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/unistd.h> #include <libnfnetlink/libnfnetlink.h> #include <linux/netfilter/nfnetlink.h> #include <linux/netfilter/xt_osf.h> #define OPTDEL ',' #define OSFPDEL ':' #define MAXOPTSTRLEN 128 #ifndef NIPQUAD #define NIPQUAD(addr) \ ((unsigned char *)&addr)[0], \ ((unsigned char *)&addr)[1], \ ((unsigned char *)&addr)[2], \ ((unsigned char *)&addr)[3] #endif static struct nfnl_handle *nfnlh; static struct nfnl_subsys_handle *nfnlssh; static struct xt_osf_opt IANA_opts[] = { { .kind = 0, .length = 1,}, { .kind=1, .length=1,}, { .kind=2, .length=4,}, { .kind=3, .length=3,}, { .kind=4, .length=2,}, { .kind=5, .length=1,}, /* SACK length is not defined */ { .kind=6, .length=6,}, { .kind=7, .length=6,}, { .kind=8, .length=10,}, { .kind=9, .length=2,}, { .kind=10, .length=3,}, { .kind=11, .length=1,}, /* CC: Suppose 1 */ { .kind=12, .length=1,}, /* the same */ { .kind=13, .length=1,}, /* and here too */ { .kind=14, .length=3,}, { .kind=15, .length=1,}, /* TCP Alternate Checksum Data. Length is not defined */ { .kind=16, .length=1,}, { .kind=17, .length=1,}, { .kind=18, .length=3,}, { .kind=19, .length=18,}, { .kind=20, .length=1,}, { .kind=21, .length=1,}, { .kind=22, .length=1,}, { .kind=23, .length=1,}, { .kind=24, .length=1,}, { .kind=25, .length=1,}, { .kind=26, .length=1,}, }; static FILE *osf_log_stream; static void uloga(const char *f, ...) { va_list ap; if (!osf_log_stream) osf_log_stream = stdout; va_start(ap, f); vfprintf(osf_log_stream, f, ap); va_end(ap); fflush(osf_log_stream); } static void ulog(const char *f, ...) { char str[64]; struct tm tm; struct timeval tv; va_list ap; if (!osf_log_stream) osf_log_stream = stdout; gettimeofday(&tv, NULL); localtime_r((time_t *)&tv.tv_sec, &tm); strftime(str, sizeof(str), "%F %R:%S", &tm); fprintf(osf_log_stream, "%s.%lu %ld ", str, tv.tv_usec, syscall(__NR_gettid)); va_start(ap, f); vfprintf(osf_log_stream, f, ap); va_end(ap); fflush(osf_log_stream); } #define ulog_err(f, a...) uloga(f ": %s [%d].\n", ##a, strerror(errno), errno) static char *xt_osf_strchr(char *ptr, char c) { char *tmp; tmp = strchr(ptr, c); if (tmp) *tmp = '\0'; while (tmp && tmp + 1 && isspace(*(tmp + 1))) tmp++; return tmp; } static void xt_osf_parse_opt(struct xt_osf_opt *opt, __u16 *optnum, char *obuf, int olen) { int i, op; char *ptr, wc; unsigned long val; ptr = &obuf[0]; i = 0; while (ptr != NULL && i < olen && *ptr != 0) { val = 0; op = 0; wc = OSF_WSS_PLAIN; switch (obuf[i]) { case 'N': op = OSFOPT_NOP; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { *ptr = '\0'; ptr++; i += (int)(ptr - &obuf[i]); } else i++; break; case 'S': op = OSFOPT_SACKP; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { *ptr = '\0'; ptr++; i += (int)(ptr - &obuf[i]); } else i++; break; case 'T': op = OSFOPT_TS; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { *ptr = '\0'; ptr++; i += (int)(ptr - &obuf[i]); } else i++; break; case 'W': op = OSFOPT_WSO; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { switch (obuf[i + 1]) { case '%': wc = OSF_WSS_MODULO; break; case 'S': wc = OSF_WSS_MSS; break; case 'T': wc = OSF_WSS_MTU; break; default: wc = OSF_WSS_PLAIN; break; } *ptr = '\0'; ptr++; if (wc) val = strtoul(&obuf[i + 2], NULL, 10); else val = strtoul(&obuf[i + 1], NULL, 10); i += (int)(ptr - &obuf[i]); } else i++; break; case 'M': op = OSFOPT_MSS; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { if (obuf[i + 1] == '%') wc = OSF_WSS_MODULO; *ptr = '\0'; ptr++; if (wc) val = strtoul(&obuf[i + 2], NULL, 10); else val = strtoul(&obuf[i + 1], NULL, 10); i += (int)(ptr - &obuf[i]); } else i++; break; case 'E': op = OSFOPT_EOL; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { *ptr = '\0'; ptr++; i += (int)(ptr - &obuf[i]); } else i++; break; default: op = OSFOPT_EMPTY; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { ptr++; i += (int)(ptr - &obuf[i]); } else i++; break; } if (op != OSFOPT_EMPTY) { opt[*optnum].kind = IANA_opts[op].kind; opt[*optnum].length = IANA_opts[op].length; opt[*optnum].wc.wc = wc; opt[*optnum].wc.val = val; (*optnum)++; } } } static int osf_load_line(char *buffer, int len, int del) { int i, cnt = 0; char obuf[MAXOPTSTRLEN]; struct xt_osf_user_finger f; char *pbeg, *pend; char buf[NFNL_HEADER_LEN + NFA_LENGTH(sizeof(struct xt_osf_user_finger))]; struct nlmsghdr *nmh = (struct nlmsghdr *) buf; memset(&f, 0, sizeof(struct xt_osf_user_finger)); ulog("Loading '%s'.\n", buffer); for (i = 0; i < len && buffer[i] != '\0'; ++i) { if (buffer[i] == ':') cnt++; } if (cnt != 8) { ulog("Wrong input line '%s': cnt: %d, must be 8, i: %d, must be %d.\n", buffer, cnt, i, len); return -EINVAL; } memset(obuf, 0, sizeof(obuf)); pbeg = buffer; pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; if (pbeg[0] == 'S') { f.wss.wc = OSF_WSS_MSS; if (pbeg[1] == '%') f.wss.val = strtoul(&pbeg[2], NULL, 10); else if (pbeg[1] == '*') f.wss.val = 0; else f.wss.val = strtoul(&pbeg[1], NULL, 10); } else if (pbeg[0] == 'T') { f.wss.wc = OSF_WSS_MTU; if (pbeg[1] == '%') f.wss.val = strtoul(&pbeg[2], NULL, 10); else if (pbeg[1] == '*') f.wss.val = 0; else f.wss.val = strtoul(&pbeg[1], NULL, 10); } else if (pbeg[0] == '%') { f.wss.wc = OSF_WSS_MODULO; f.wss.val = strtoul(&pbeg[1], NULL, 10); } else if (isdigit(pbeg[0])) { f.wss.wc = OSF_WSS_PLAIN; f.wss.val = strtoul(&pbeg[0], NULL, 10); } pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; f.ttl = strtoul(pbeg, NULL, 10); pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; f.df = strtoul(pbeg, NULL, 10); pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; f.ss = strtoul(pbeg, NULL, 10); pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; cnt = snprintf(obuf, sizeof(obuf), "%s,", pbeg); pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; if (pbeg[0] == '@' || pbeg[0] == '*') cnt = snprintf(f.genre, sizeof(f.genre), "%s", pbeg + 1); else cnt = snprintf(f.genre, sizeof(f.genre), "%s", pbeg); pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; cnt = snprintf(f.version, sizeof(f.version), "%s", pbeg); pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; cnt = snprintf(f.subtype, sizeof(f.subtype), "%s", pbeg); pbeg = pend + 1; } xt_osf_parse_opt(f.opt, &f.opt_num, obuf, sizeof(obuf)); memset(buf, 0, sizeof(buf)); if (del) nfnl_fill_hdr(nfnlssh, nmh, 0, AF_UNSPEC, 0, OSF_MSG_REMOVE, NLM_F_REQUEST); else nfnl_fill_hdr(nfnlssh, nmh, 0, AF_UNSPEC, 0, OSF_MSG_ADD, NLM_F_REQUEST | NLM_F_CREATE); nfnl_addattr_l(nmh, sizeof(buf), OSF_ATTR_FINGER, &f, sizeof(struct xt_osf_user_finger)); return nfnl_talk(nfnlh, nmh, 0, 0, NULL, NULL, NULL); } static int osf_load_entries(char *path, int del) { FILE *inf; int err = 0; char buf[1024]; inf = fopen(path, "r"); if (!inf) { ulog_err("Failed to open file '%s'", path); return -1; } while(fgets(buf, sizeof(buf), inf)) { int len; if (buf[0] == '#' || buf[0] == '\n' || buf[0] == '\r') continue; len = strlen(buf) - 1; if (len <= 0) continue; buf[len] = '\0'; err = osf_load_line(buf, len, del); if (err) break; memset(buf, 0, sizeof(buf)); } fclose(inf); return err; } int main(int argc, char *argv[]) { int ch, del = 0, err; char *fingerprints = NULL; while ((ch = getopt(argc, argv, "f:dh")) != -1) { switch (ch) { case 'f': fingerprints = optarg; break; case 'd': del = 1; break; default: fprintf(stderr, "Usage: %s -f fingerprints -d <del rules> -h\n", argv[0]); return -1; } } if (!fingerprints) { err = -ENOENT; goto err_out_exit; } nfnlh = nfnl_open(); if (!nfnlh) { err = -EINVAL; ulog_err("Failed to create nfnl handler"); goto err_out_exit; } #ifndef NFNL_SUBSYS_OSF #define NFNL_SUBSYS_OSF 5 #endif nfnlssh = nfnl_subsys_open(nfnlh, NFNL_SUBSYS_OSF, OSF_MSG_MAX, 0); if (!nfnlssh) { err = -EINVAL; ulog_err("Faied to create nfnl subsystem"); goto err_out_close; } err = osf_load_entries(fingerprints, del); if (err) goto err_out_close_subsys; nfnl_subsys_close(nfnlssh); nfnl_close(nfnlh); return 0; err_out_close_subsys: nfnl_subsys_close(nfnlssh); err_out_close: nfnl_close(nfnlh); err_out_exit: return err; }
231
./android_firewall/external/iptables/libiptc/libip6tc.c
/* Library which manipulates firewall rules. Version 0.1. */ /* Architecture of firewall rules is as follows: * * Chains go INPUT, FORWARD, OUTPUT then user chains. * Each user chain starts with an ERROR node. * Every chain ends with an unconditional jump: a RETURN for user chains, * and a POLICY for built-ins. */ /* (C)1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See COPYING for details). */ #include <assert.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <arpa/inet.h> #ifdef DEBUG_CONNTRACK #define inline #endif #if !defined(__GLIBC__) || (__GLIBC__ < 2) typedef unsigned int socklen_t; #endif #include "libiptc/libip6tc.h" #define HOOK_PRE_ROUTING NF_IP6_PRE_ROUTING #define HOOK_LOCAL_IN NF_IP6_LOCAL_IN #define HOOK_FORWARD NF_IP6_FORWARD #define HOOK_LOCAL_OUT NF_IP6_LOCAL_OUT #define HOOK_POST_ROUTING NF_IP6_POST_ROUTING #define STRUCT_ENTRY_TARGET struct xt_entry_target #define STRUCT_ENTRY struct ip6t_entry #define STRUCT_ENTRY_MATCH struct xt_entry_match #define STRUCT_GETINFO struct ip6t_getinfo #define STRUCT_GET_ENTRIES struct ip6t_get_entries #define STRUCT_COUNTERS struct xt_counters #define STRUCT_COUNTERS_INFO struct xt_counters_info #define STRUCT_STANDARD_TARGET struct xt_standard_target #define STRUCT_REPLACE struct ip6t_replace #define ENTRY_ITERATE IP6T_ENTRY_ITERATE #define TABLE_MAXNAMELEN XT_TABLE_MAXNAMELEN #define FUNCTION_MAXNAMELEN XT_FUNCTION_MAXNAMELEN #define GET_TARGET ip6t_get_target #define ERROR_TARGET XT_ERROR_TARGET #define NUMHOOKS NF_IP6_NUMHOOKS #define IPT_CHAINLABEL xt_chainlabel #define TC_DUMP_ENTRIES dump_entries6 #define TC_IS_CHAIN ip6tc_is_chain #define TC_FIRST_CHAIN ip6tc_first_chain #define TC_NEXT_CHAIN ip6tc_next_chain #define TC_FIRST_RULE ip6tc_first_rule #define TC_NEXT_RULE ip6tc_next_rule #define TC_GET_TARGET ip6tc_get_target #define TC_BUILTIN ip6tc_builtin #define TC_GET_POLICY ip6tc_get_policy #define TC_INSERT_ENTRY ip6tc_insert_entry #define TC_REPLACE_ENTRY ip6tc_replace_entry #define TC_APPEND_ENTRY ip6tc_append_entry #define TC_CHECK_ENTRY ip6tc_check_entry #define TC_DELETE_ENTRY ip6tc_delete_entry #define TC_DELETE_NUM_ENTRY ip6tc_delete_num_entry #define TC_FLUSH_ENTRIES ip6tc_flush_entries #define TC_ZERO_ENTRIES ip6tc_zero_entries #define TC_ZERO_COUNTER ip6tc_zero_counter #define TC_READ_COUNTER ip6tc_read_counter #define TC_SET_COUNTER ip6tc_set_counter #define TC_CREATE_CHAIN ip6tc_create_chain #define TC_GET_REFERENCES ip6tc_get_references #define TC_DELETE_CHAIN ip6tc_delete_chain #define TC_RENAME_CHAIN ip6tc_rename_chain #define TC_SET_POLICY ip6tc_set_policy #define TC_GET_RAW_SOCKET ip6tc_get_raw_socket #define TC_INIT ip6tc_init #define TC_FREE ip6tc_free #define TC_COMMIT ip6tc_commit #define TC_STRERROR ip6tc_strerror #define TC_NUM_RULES ip6tc_num_rules #define TC_GET_RULE ip6tc_get_rule #define TC_OPS ip6tc_ops #define TC_AF AF_INET6 #define TC_IPPROTO IPPROTO_IPV6 #define SO_SET_REPLACE IP6T_SO_SET_REPLACE #define SO_SET_ADD_COUNTERS IP6T_SO_SET_ADD_COUNTERS #define SO_GET_INFO IP6T_SO_GET_INFO #define SO_GET_ENTRIES IP6T_SO_GET_ENTRIES #define SO_GET_VERSION IP6T_SO_GET_VERSION #define STANDARD_TARGET XT_STANDARD_TARGET #define LABEL_RETURN IP6TC_LABEL_RETURN #define LABEL_ACCEPT IP6TC_LABEL_ACCEPT #define LABEL_DROP IP6TC_LABEL_DROP #define LABEL_QUEUE IP6TC_LABEL_QUEUE #define ALIGN XT_ALIGN #define RETURN XT_RETURN #include "libiptc.c" #define BIT6(a, l) \ ((ntohl(a->s6_addr32[(l) / 32]) >> (31 - ((l) & 31))) & 1) int ipv6_prefix_length(const struct in6_addr *a) { int l, i; for (l = 0; l < 128; l++) { if (BIT6(a, l) == 0) break; } for (i = l + 1; i < 128; i++) { if (BIT6(a, i) == 1) return -1; } return l; } static int dump_entry(struct ip6t_entry *e, struct xtc_handle *const handle) { size_t i; char buf[40]; int len; struct xt_entry_target *t; printf("Entry %u (%lu):\n", iptcb_entry2index(handle, e), iptcb_entry2offset(handle, e)); puts("SRC IP: "); inet_ntop(AF_INET6, &e->ipv6.src, buf, sizeof buf); puts(buf); putchar('/'); len = ipv6_prefix_length(&e->ipv6.smsk); if (len != -1) printf("%d", len); else { inet_ntop(AF_INET6, &e->ipv6.smsk, buf, sizeof buf); puts(buf); } putchar('\n'); puts("DST IP: "); inet_ntop(AF_INET6, &e->ipv6.dst, buf, sizeof buf); puts(buf); putchar('/'); len = ipv6_prefix_length(&e->ipv6.dmsk); if (len != -1) printf("%d", len); else { inet_ntop(AF_INET6, &e->ipv6.dmsk, buf, sizeof buf); puts(buf); } putchar('\n'); printf("Interface: `%s'/", e->ipv6.iniface); for (i = 0; i < IFNAMSIZ; i++) printf("%c", e->ipv6.iniface_mask[i] ? 'X' : '.'); printf("to `%s'/", e->ipv6.outiface); for (i = 0; i < IFNAMSIZ; i++) printf("%c", e->ipv6.outiface_mask[i] ? 'X' : '.'); printf("\nProtocol: %u\n", e->ipv6.proto); if (e->ipv6.flags & IP6T_F_TOS) printf("TOS: %u\n", e->ipv6.tos); printf("Flags: %02X\n", e->ipv6.flags); printf("Invflags: %02X\n", e->ipv6.invflags); printf("Counters: %llu packets, %llu bytes\n", (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt); printf("Cache: %08X\n", e->nfcache); IP6T_MATCH_ITERATE(e, print_match); t = ip6t_get_target(e); printf("Target name: `%s' [%u]\n", t->u.user.name, t->u.target_size); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0) { const unsigned char *data = t->data; int pos = *(const int *)data; if (pos < 0) printf("verdict=%s\n", pos == -NF_ACCEPT-1 ? "NF_ACCEPT" : pos == -NF_DROP-1 ? "NF_DROP" : pos == XT_RETURN ? "RETURN" : "UNKNOWN"); else printf("verdict=%u\n", pos); } else if (strcmp(t->u.user.name, XT_ERROR_TARGET) == 0) printf("error=`%s'\n", t->data); printf("\n"); return 0; } static unsigned char * is_same(const STRUCT_ENTRY *a, const STRUCT_ENTRY *b, unsigned char *matchmask) { unsigned int i; unsigned char *mptr; /* Always compare head structures: ignore mask here. */ if (memcmp(&a->ipv6.src, &b->ipv6.src, sizeof(struct in6_addr)) || memcmp(&a->ipv6.dst, &b->ipv6.dst, sizeof(struct in6_addr)) || memcmp(&a->ipv6.smsk, &b->ipv6.smsk, sizeof(struct in6_addr)) || memcmp(&a->ipv6.dmsk, &b->ipv6.dmsk, sizeof(struct in6_addr)) || a->ipv6.proto != b->ipv6.proto || a->ipv6.tos != b->ipv6.tos || a->ipv6.flags != b->ipv6.flags || a->ipv6.invflags != b->ipv6.invflags) return NULL; for (i = 0; i < IFNAMSIZ; i++) { if (a->ipv6.iniface_mask[i] != b->ipv6.iniface_mask[i]) return NULL; if ((a->ipv6.iniface[i] & a->ipv6.iniface_mask[i]) != (b->ipv6.iniface[i] & b->ipv6.iniface_mask[i])) return NULL; if (a->ipv6.outiface_mask[i] != b->ipv6.outiface_mask[i]) return NULL; if ((a->ipv6.outiface[i] & a->ipv6.outiface_mask[i]) != (b->ipv6.outiface[i] & b->ipv6.outiface_mask[i])) return NULL; } if (a->target_offset != b->target_offset || a->next_offset != b->next_offset) return NULL; mptr = matchmask + sizeof(STRUCT_ENTRY); if (IP6T_MATCH_ITERATE(a, match_different, a->elems, b->elems, &mptr)) return NULL; mptr += XT_ALIGN(sizeof(struct xt_entry_target)); return mptr; } /* All zeroes == unconditional rule. */ static inline int unconditional(const struct ip6t_ip6 *ipv6) { unsigned int i; for (i = 0; i < sizeof(*ipv6); i++) if (((char *)ipv6)[i]) break; return (i == sizeof(*ipv6)); } #ifdef IPTC_DEBUG /* Do every conceivable sanity check on the handle */ static void do_check(struct xtc_handle *h, unsigned int line) { unsigned int i, n; unsigned int user_offset; /* Offset of first user chain */ int was_return; assert(h->changed == 0 || h->changed == 1); if (strcmp(h->info.name, "filter") == 0) { assert(h->info.valid_hooks == (1 << NF_IP6_LOCAL_IN | 1 << NF_IP6_FORWARD | 1 << NF_IP6_LOCAL_OUT)); /* Hooks should be first three */ assert(h->info.hook_entry[NF_IP6_LOCAL_IN] == 0); n = get_chain_end(h, 0); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP6_FORWARD] == n); n = get_chain_end(h, n); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP6_LOCAL_OUT] == n); user_offset = h->info.hook_entry[NF_IP6_LOCAL_OUT]; } else if (strcmp(h->info.name, "nat") == 0) { assert((h->info.valid_hooks == (1 << NF_IP6_PRE_ROUTING | 1 << NF_IP6_LOCAL_OUT | 1 << NF_IP6_POST_ROUTING)) || (h->info.valid_hooks == (1 << NF_IP6_PRE_ROUTING | 1 << NF_IP6_LOCAL_IN | 1 << NF_IP6_LOCAL_OUT | 1 << NF_IP6_POST_ROUTING))); assert(h->info.hook_entry[NF_IP6_PRE_ROUTING] == 0); n = get_chain_end(h, 0); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP6_POST_ROUTING] == n); n = get_chain_end(h, n); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP6_LOCAL_OUT] == n); user_offset = h->info.hook_entry[NF_IP6_LOCAL_OUT]; if (h->info.valid_hooks & (1 << NF_IP6_LOCAL_IN)) { n = get_chain_end(h, n); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP6_LOCAL_IN] == n); user_offset = h->info.hook_entry[NF_IP6_LOCAL_IN]; } } else if (strcmp(h->info.name, "mangle") == 0) { /* This code is getting ugly because linux < 2.4.18-pre6 had * two mangle hooks, linux >= 2.4.18-pre6 has five mangle hooks * */ assert((h->info.valid_hooks == (1 << NF_IP6_PRE_ROUTING | 1 << NF_IP6_LOCAL_OUT)) || (h->info.valid_hooks == (1 << NF_IP6_PRE_ROUTING | 1 << NF_IP6_LOCAL_IN | 1 << NF_IP6_FORWARD | 1 << NF_IP6_LOCAL_OUT | 1 << NF_IP6_POST_ROUTING))); /* Hooks should be first five */ assert(h->info.hook_entry[NF_IP6_PRE_ROUTING] == 0); n = get_chain_end(h, 0); if (h->info.valid_hooks & (1 << NF_IP6_LOCAL_IN)) { n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP6_LOCAL_IN] == n); n = get_chain_end(h, n); } if (h->info.valid_hooks & (1 << NF_IP6_FORWARD)) { n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP6_FORWARD] == n); n = get_chain_end(h, n); } n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP6_LOCAL_OUT] == n); user_offset = h->info.hook_entry[NF_IP6_LOCAL_OUT]; if (h->info.valid_hooks & (1 << NF_IP6_POST_ROUTING)) { n = get_chain_end(h, n); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP6_POST_ROUTING] == n); user_offset = h->info.hook_entry[NF_IP6_POST_ROUTING]; } } else if (strcmp(h->info.name, "raw") == 0) { assert(h->info.valid_hooks == (1 << NF_IP6_PRE_ROUTING | 1 << NF_IP6_LOCAL_OUT)); /* Hooks should be first three */ assert(h->info.hook_entry[NF_IP6_PRE_ROUTING] == 0); n = get_chain_end(h, n); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP6_LOCAL_OUT] == n); user_offset = h->info.hook_entry[NF_IP6_LOCAL_OUT]; } else { fprintf(stderr, "Unknown table `%s'\n", h->info.name); abort(); } /* User chain == end of last builtin + policy entry */ user_offset = get_chain_end(h, user_offset); user_offset += get_entry(h, user_offset)->next_offset; /* Overflows should be end of entry chains, and unconditional policy nodes. */ for (i = 0; i < NUMHOOKS; i++) { STRUCT_ENTRY *e; STRUCT_STANDARD_TARGET *t; if (!(h->info.valid_hooks & (1 << i))) continue; assert(h->info.underflow[i] == get_chain_end(h, h->info.hook_entry[i])); e = get_entry(h, get_chain_end(h, h->info.hook_entry[i])); assert(unconditional(&e->ipv6)); assert(e->target_offset == sizeof(*e)); t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e); printf("target_size=%u, align=%u\n", t->target.u.target_size, ALIGN(sizeof(*t))); assert(t->target.u.target_size == ALIGN(sizeof(*t))); assert(e->next_offset == sizeof(*e) + ALIGN(sizeof(*t))); assert(strcmp(t->target.u.user.name, STANDARD_TARGET)==0); assert(t->verdict == -NF_DROP-1 || t->verdict == -NF_ACCEPT-1); /* Hooks and underflows must be valid entries */ iptcb_entry2index(h, get_entry(h, h->info.hook_entry[i])); iptcb_entry2index(h, get_entry(h, h->info.underflow[i])); } assert(h->info.size >= h->info.num_entries * (sizeof(STRUCT_ENTRY) +sizeof(STRUCT_STANDARD_TARGET))); assert(h->entries.size >= (h->new_number * (sizeof(STRUCT_ENTRY) + sizeof(STRUCT_STANDARD_TARGET)))); assert(strcmp(h->info.name, h->entries.name) == 0); i = 0; n = 0; was_return = 0; #if 0 /* Check all the entries. */ ENTRY_ITERATE(h->entries.entrytable, h->entries.size, check_entry, &i, &n, user_offset, &was_return, h); assert(i == h->new_number); assert(n == h->entries.size); /* Final entry must be error node */ assert(strcmp(GET_TARGET(index2entry(h, h->new_number-1)) ->u.user.name, ERROR_TARGET) == 0); #endif } #endif /*IPTC_DEBUG*/
232
./android_firewall/external/iptables/libiptc/libiptc.c
/* Library which manipulates firewall rules. Version $Revision$ */ /* Architecture of firewall rules is as follows: * * Chains go INPUT, FORWARD, OUTPUT then user chains. * Each user chain starts with an ERROR node. * Every chain ends with an unconditional jump: a RETURN for user chains, * and a POLICY for built-ins. */ /* (C) 1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See * COPYING for details). * (C) 2000-2004 by the Netfilter Core Team <[email protected]> * * 2003-Jun-20: Harald Welte <[email protected]>: * - Reimplementation of chain cache to use offsets instead of entries * 2003-Jun-23: Harald Welte <[email protected]>: * - performance optimization, sponsored by Astaro AG (http://www.astaro.com/) * don't rebuild the chain cache after every operation, instead fix it * up after a ruleset change. * 2004-Aug-18: Harald Welte <[email protected]>: * - further performance work: total reimplementation of libiptc. * - libiptc now has a real internal (linked-list) represntation of the * ruleset and a parser/compiler from/to this internal representation * - again sponsored by Astaro AG (http://www.astaro.com/) * * 2008-Jan+Jul: Jesper Dangaard Brouer <[email protected]> * - performance work: speedup chain list "name" searching. * - performance work: speedup initial ruleset parsing. * - sponsored by ComX Networks A/S (http://www.comx.dk/) */ #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <stdbool.h> #include <xtables.h> #include <libiptc/xtcshared.h> #include "linux_list.h" //#define IPTC_DEBUG2 1 #ifdef IPTC_DEBUG2 #include <fcntl.h> #define DEBUGP(x, args...) fprintf(stderr, "%s: " x, __FUNCTION__, ## args) #define DEBUGP_C(x, args...) fprintf(stderr, x, ## args) #else #define DEBUGP(x, args...) #define DEBUGP_C(x, args...) #endif #ifdef DEBUG #define debug(x, args...) fprintf(stderr, x, ## args) #else #define debug(x, args...) #endif static void *iptc_fn = NULL; static const char *hooknames[] = { [HOOK_PRE_ROUTING] = "PREROUTING", [HOOK_LOCAL_IN] = "INPUT", [HOOK_FORWARD] = "FORWARD", [HOOK_LOCAL_OUT] = "OUTPUT", [HOOK_POST_ROUTING] = "POSTROUTING", }; /* Convenience structures */ struct chain_head; struct rule_head; struct counter_map { enum { COUNTER_MAP_NOMAP, COUNTER_MAP_NORMAL_MAP, COUNTER_MAP_ZEROED, COUNTER_MAP_SET } maptype; unsigned int mappos; }; enum iptcc_rule_type { IPTCC_R_STANDARD, /* standard target (ACCEPT, ...) */ IPTCC_R_MODULE, /* extension module (SNAT, ...) */ IPTCC_R_FALLTHROUGH, /* fallthrough rule */ IPTCC_R_JUMP, /* jump to other chain */ }; struct rule_head { struct list_head list; struct chain_head *chain; struct counter_map counter_map; unsigned int index; /* index (needed for counter_map) */ unsigned int offset; /* offset in rule blob */ enum iptcc_rule_type type; struct chain_head *jump; /* jump target, if IPTCC_R_JUMP */ unsigned int size; /* size of entry data */ STRUCT_ENTRY entry[0]; }; struct chain_head { struct list_head list; char name[TABLE_MAXNAMELEN]; unsigned int hooknum; /* hook number+1 if builtin */ unsigned int references; /* how many jumps reference us */ int verdict; /* verdict if builtin */ STRUCT_COUNTERS counters; /* per-chain counters */ struct counter_map counter_map; unsigned int num_rules; /* number of rules in list */ struct list_head rules; /* list of rules */ unsigned int index; /* index (needed for jump resolval) */ unsigned int head_offset; /* offset in rule blob */ unsigned int foot_index; /* index (needed for counter_map) */ unsigned int foot_offset; /* offset in rule blob */ }; struct xtc_handle { int sockfd; int changed; /* Have changes been made? */ struct list_head chains; struct chain_head *chain_iterator_cur; struct rule_head *rule_iterator_cur; unsigned int num_chains; /* number of user defined chains */ struct chain_head **chain_index; /* array for fast chain list access*/ unsigned int chain_index_sz;/* size of chain index array */ int sorted_offsets; /* if chains are received sorted from kernel, * then the offsets are also sorted. Says if its * possible to bsearch offsets using chain_index. */ STRUCT_GETINFO info; STRUCT_GET_ENTRIES *entries; }; enum bsearch_type { BSEARCH_NAME, /* Binary search after chain name */ BSEARCH_OFFSET, /* Binary search based on offset */ }; /* allocate a new chain head for the cache */ static struct chain_head *iptcc_alloc_chain_head(const char *name, int hooknum) { struct chain_head *c = malloc(sizeof(*c)); if (!c) return NULL; memset(c, 0, sizeof(*c)); strncpy(c->name, name, TABLE_MAXNAMELEN); c->hooknum = hooknum; INIT_LIST_HEAD(&c->rules); return c; } /* allocate and initialize a new rule for the cache */ static struct rule_head *iptcc_alloc_rule(struct chain_head *c, unsigned int size) { struct rule_head *r = malloc(sizeof(*r)+size); if (!r) return NULL; memset(r, 0, sizeof(*r)); r->chain = c; r->size = size; return r; } /* notify us that the ruleset has been modified by the user */ static inline void set_changed(struct xtc_handle *h) { h->changed = 1; } #ifdef IPTC_DEBUG static void do_check(struct xtc_handle *h, unsigned int line); #define CHECK(h) do { if (!getenv("IPTC_NO_CHECK")) do_check((h), __LINE__); } while(0) #else #define CHECK(h) #endif /********************************************************************** * iptc blob utility functions (iptcb_*) **********************************************************************/ static inline int iptcb_get_number(const STRUCT_ENTRY *i, const STRUCT_ENTRY *seek, unsigned int *pos) { if (i == seek) return 1; (*pos)++; return 0; } static inline int iptcb_get_entry_n(STRUCT_ENTRY *i, unsigned int number, unsigned int *pos, STRUCT_ENTRY **pe) { if (*pos == number) { *pe = i; return 1; } (*pos)++; return 0; } static inline STRUCT_ENTRY * iptcb_get_entry(struct xtc_handle *h, unsigned int offset) { return (STRUCT_ENTRY *)((char *)h->entries->entrytable + offset); } static unsigned int iptcb_entry2index(struct xtc_handle *const h, const STRUCT_ENTRY *seek) { unsigned int pos = 0; if (ENTRY_ITERATE(h->entries->entrytable, h->entries->size, iptcb_get_number, seek, &pos) == 0) { fprintf(stderr, "ERROR: offset %u not an entry!\n", (unsigned int)((char *)seek - (char *)h->entries->entrytable)); abort(); } return pos; } static inline STRUCT_ENTRY * iptcb_offset2entry(struct xtc_handle *h, unsigned int offset) { return (STRUCT_ENTRY *) ((void *)h->entries->entrytable+offset); } static inline unsigned long iptcb_entry2offset(struct xtc_handle *const h, const STRUCT_ENTRY *e) { return (void *)e - (void *)h->entries->entrytable; } static inline unsigned int iptcb_offset2index(struct xtc_handle *const h, unsigned int offset) { return iptcb_entry2index(h, iptcb_offset2entry(h, offset)); } /* Returns 0 if not hook entry, else hooknumber + 1 */ static inline unsigned int iptcb_ent_is_hook_entry(STRUCT_ENTRY *e, struct xtc_handle *h) { unsigned int i; for (i = 0; i < NUMHOOKS; i++) { if ((h->info.valid_hooks & (1 << i)) && iptcb_get_entry(h, h->info.hook_entry[i]) == e) return i+1; } return 0; } /********************************************************************** * Chain index (cache utility) functions ********************************************************************** * The chain index is an array with pointers into the chain list, with * CHAIN_INDEX_BUCKET_LEN spacing. This facilitates the ability to * speedup chain list searching, by find a more optimal starting * points when searching the linked list. * * The starting point can be found fast by using a binary search of * the chain index. Thus, reducing the previous search complexity of * O(n) to O(log(n/k) + k) where k is CHAIN_INDEX_BUCKET_LEN. * * A nice property of the chain index, is that the "bucket" list * length is max CHAIN_INDEX_BUCKET_LEN (when just build, inserts will * change this). Oppose to hashing, where the "bucket" list length can * vary a lot. */ #ifndef CHAIN_INDEX_BUCKET_LEN #define CHAIN_INDEX_BUCKET_LEN 40 #endif /* Another nice property of the chain index is that inserting/creating * chains in chain list don't change the correctness of the chain * index, it only causes longer lists in the buckets. * * To mitigate the performance penalty of longer bucket lists and the * penalty of rebuilding, the chain index is rebuild only when * CHAIN_INDEX_INSERT_MAX chains has been added. */ #ifndef CHAIN_INDEX_INSERT_MAX #define CHAIN_INDEX_INSERT_MAX 355 #endif static inline unsigned int iptcc_is_builtin(struct chain_head *c); /* Use binary search in the chain index array, to find a chain_head * pointer closest to the place of the searched name element. * * Notes that, binary search (obviously) requires that the chain list * is sorted by name. * * The not so obvious: The chain index array, is actually both sorted * by name and offset, at the same time!. This is only true because, * chain are stored sorted in the kernel (as we pushed it in sorted). * */ static struct list_head * __iptcc_bsearch_chain_index(const char *name, unsigned int offset, unsigned int *idx, struct xtc_handle *handle, enum bsearch_type type) { unsigned int pos, end; int res; struct list_head *list_pos; list_pos=&handle->chains; /* Check for empty array, e.g. no user defined chains */ if (handle->chain_index_sz == 0) { debug("WARNING: handle->chain_index_sz == 0\n"); return list_pos; } /* Init */ end = handle->chain_index_sz; pos = end / 2; debug("bsearch Find chain:%s (pos:%d end:%d) (offset:%d)\n", name, pos, end, offset); /* Loop */ loop: if (!handle->chain_index[pos]) { fprintf(stderr, "ERROR: NULL pointer chain_index[%d]\n", pos); return &handle->chains; /* Be safe, return orig start pos */ } debug("bsearch Index[%d] name:%s ", pos, handle->chain_index[pos]->name); /* Support for different compare functions */ switch (type) { case BSEARCH_NAME: res = strcmp(name, handle->chain_index[pos]->name); break; case BSEARCH_OFFSET: debug("head_offset:[%d] foot_offset:[%d] ", handle->chain_index[pos]->head_offset, handle->chain_index[pos]->foot_offset); res = offset - handle->chain_index[pos]->head_offset; break; default: fprintf(stderr, "ERROR: %d not a valid bsearch type\n", type); abort(); break; } debug("res:%d ", res); list_pos = &handle->chain_index[pos]->list; *idx = pos; if (res == 0) { /* Found element, by direct hit */ debug("[found] Direct hit pos:%d end:%d\n", pos, end); return list_pos; } else if (res < 0) { /* Too far, jump back */ end = pos; pos = pos / 2; /* Exit case: First element of array */ if (end == 0) { debug("[found] Reached first array elem (end%d)\n",end); return list_pos; } debug("jump back to pos:%d (end:%d)\n", pos, end); goto loop; } else { /* res > 0; Not far enough, jump forward */ /* Exit case: Last element of array */ if (pos == handle->chain_index_sz-1) { debug("[found] Last array elem (end:%d)\n", end); return list_pos; } /* Exit case: Next index less, thus elem in this list section */ switch (type) { case BSEARCH_NAME: res = strcmp(name, handle->chain_index[pos+1]->name); break; case BSEARCH_OFFSET: res = offset - handle->chain_index[pos+1]->head_offset; break; } if (res < 0) { debug("[found] closest list (end:%d)\n", end); return list_pos; } pos = (pos+end)/2; debug("jump forward to pos:%d (end:%d)\n", pos, end); goto loop; } } /* Wrapper for string chain name based bsearch */ static struct list_head * iptcc_bsearch_chain_index(const char *name, unsigned int *idx, struct xtc_handle *handle) { return __iptcc_bsearch_chain_index(name, 0, idx, handle, BSEARCH_NAME); } /* Wrapper for offset chain based bsearch */ static struct list_head * iptcc_bsearch_chain_offset(unsigned int offset, unsigned int *idx, struct xtc_handle *handle) { struct list_head *pos; /* If chains were not received sorted from kernel, then the * offset bsearch is not possible. */ if (!handle->sorted_offsets) pos = handle->chains.next; else pos = __iptcc_bsearch_chain_index(NULL, offset, idx, handle, BSEARCH_OFFSET); return pos; } #ifdef DEBUG /* Trivial linear search of chain index. Function used for verifying the output of bsearch function */ static struct list_head * iptcc_linearly_search_chain_index(const char *name, struct xtc_handle *handle) { unsigned int i=0; int res=0; struct list_head *list_pos; list_pos = &handle->chains; if (handle->chain_index_sz) list_pos = &handle->chain_index[0]->list; /* Linearly walk of chain index array */ for (i=0; i < handle->chain_index_sz; i++) { if (handle->chain_index[i]) { res = strcmp(handle->chain_index[i]->name, name); if (res > 0) break; // One step too far list_pos = &handle->chain_index[i]->list; if (res == 0) break; // Direct hit } } return list_pos; } #endif static int iptcc_chain_index_alloc(struct xtc_handle *h) { unsigned int list_length = CHAIN_INDEX_BUCKET_LEN; unsigned int array_elems; unsigned int array_mem; /* Allocate memory for the chain index array */ array_elems = (h->num_chains / list_length) + (h->num_chains % list_length ? 1 : 0); array_mem = sizeof(h->chain_index) * array_elems; debug("Alloc Chain index, elems:%d mem:%d bytes\n", array_elems, array_mem); h->chain_index = malloc(array_mem); if (h->chain_index == NULL && array_mem > 0) { h->chain_index_sz = 0; return -ENOMEM; } memset(h->chain_index, 0, array_mem); h->chain_index_sz = array_elems; return 1; } static void iptcc_chain_index_free(struct xtc_handle *h) { h->chain_index_sz = 0; free(h->chain_index); } #ifdef DEBUG static void iptcc_chain_index_dump(struct xtc_handle *h) { unsigned int i = 0; /* Dump: contents of chain index array */ for (i=0; i < h->chain_index_sz; i++) { if (h->chain_index[i]) { fprintf(stderr, "Chain index[%d].name: %s\n", i, h->chain_index[i]->name); } } } #endif /* Build the chain index */ static int iptcc_chain_index_build(struct xtc_handle *h) { unsigned int list_length = CHAIN_INDEX_BUCKET_LEN; unsigned int chains = 0; unsigned int cindex = 0; struct chain_head *c; /* Build up the chain index array here */ debug("Building chain index\n"); debug("Number of user defined chains:%d bucket_sz:%d array_sz:%d\n", h->num_chains, list_length, h->chain_index_sz); if (h->chain_index_sz == 0) return 0; list_for_each_entry(c, &h->chains, list) { /* Issue: The index array needs to start after the * builtin chains, as they are not sorted */ if (!iptcc_is_builtin(c)) { cindex=chains / list_length; /* Safe guard, break out on array limit, this * is useful if chains are added and array is * rebuild, without realloc of memory. */ if (cindex >= h->chain_index_sz) break; if ((chains % list_length)== 0) { debug("\nIndex[%d] Chains:", cindex); h->chain_index[cindex] = c; } chains++; } debug("%s, ", c->name); } debug("\n"); return 1; } static int iptcc_chain_index_rebuild(struct xtc_handle *h) { debug("REBUILD chain index array\n"); iptcc_chain_index_free(h); if ((iptcc_chain_index_alloc(h)) < 0) return -ENOMEM; iptcc_chain_index_build(h); return 1; } /* Delete chain (pointer) from index array. Removing an element from * the chain list only affects the chain index array, if the chain * index points-to/uses that list pointer. * * There are different strategies, the simple and safe is to rebuild * the chain index every time. The more advanced is to update the * array index to point to the next element, but that requires some * house keeping and boundry checks. The advanced is implemented, as * the simple approach behaves badly when all chains are deleted * because list_for_each processing will always hit the first chain * index, thus causing a rebuild for every chain. */ static int iptcc_chain_index_delete_chain(struct chain_head *c, struct xtc_handle *h) { struct list_head *index_ptr, *next; struct chain_head *c2; unsigned int idx, idx2; index_ptr = iptcc_bsearch_chain_index(c->name, &idx, h); debug("Del chain[%s] c->list:%p index_ptr:%p\n", c->name, &c->list, index_ptr); /* Save the next pointer */ next = c->list.next; list_del(&c->list); if (index_ptr == &c->list) { /* Chain used as index ptr */ /* See if its possible to avoid a rebuild, by shifting * to next pointer. Its possible if the next pointer * is located in the same index bucket. */ c2 = list_entry(next, struct chain_head, list); iptcc_bsearch_chain_index(c2->name, &idx2, h); if (idx != idx2) { /* Rebuild needed */ return iptcc_chain_index_rebuild(h); } else { /* Avoiding rebuild */ debug("Update cindex[%d] with next ptr name:[%s]\n", idx, c2->name); h->chain_index[idx]=c2; return 0; } } return 0; } /********************************************************************** * iptc cache utility functions (iptcc_*) **********************************************************************/ /* Is the given chain builtin (1) or user-defined (0) */ static inline unsigned int iptcc_is_builtin(struct chain_head *c) { return (c->hooknum ? 1 : 0); } /* Get a specific rule within a chain */ static struct rule_head *iptcc_get_rule_num(struct chain_head *c, unsigned int rulenum) { struct rule_head *r; unsigned int num = 0; list_for_each_entry(r, &c->rules, list) { num++; if (num == rulenum) return r; } return NULL; } /* Get a specific rule within a chain backwards */ static struct rule_head *iptcc_get_rule_num_reverse(struct chain_head *c, unsigned int rulenum) { struct rule_head *r; unsigned int num = 0; list_for_each_entry_reverse(r, &c->rules, list) { num++; if (num == rulenum) return r; } return NULL; } /* Returns chain head if found, otherwise NULL. */ static struct chain_head * iptcc_find_chain_by_offset(struct xtc_handle *handle, unsigned int offset) { struct list_head *pos; struct list_head *list_start_pos; unsigned int i; if (list_empty(&handle->chains)) return NULL; /* Find a smart place to start the search */ list_start_pos = iptcc_bsearch_chain_offset(offset, &i, handle); /* Note that iptcc_bsearch_chain_offset() skips builtin * chains, but this function is only used for finding jump * targets, and a buildin chain is not a valid jump target */ debug("Offset:[%u] starting search at index:[%u]\n", offset, i); // list_for_each(pos, &handle->chains) { list_for_each(pos, list_start_pos->prev) { struct chain_head *c = list_entry(pos, struct chain_head, list); debug("."); if (offset >= c->head_offset && offset <= c->foot_offset) { debug("Offset search found chain:[%s]\n", c->name); return c; } } return NULL; } /* Returns chain head if found, otherwise NULL. */ static struct chain_head * iptcc_find_label(const char *name, struct xtc_handle *handle) { struct list_head *pos; struct list_head *list_start_pos; unsigned int i=0; int res; if (list_empty(&handle->chains)) return NULL; /* First look at builtin chains */ list_for_each(pos, &handle->chains) { struct chain_head *c = list_entry(pos, struct chain_head, list); if (!iptcc_is_builtin(c)) break; if (!strcmp(c->name, name)) return c; } /* Find a smart place to start the search via chain index */ //list_start_pos = iptcc_linearly_search_chain_index(name, handle); list_start_pos = iptcc_bsearch_chain_index(name, &i, handle); /* Handel if bsearch bails out early */ if (list_start_pos == &handle->chains) { list_start_pos = pos; } #ifdef DEBUG else { /* Verify result of bsearch against linearly index search */ struct list_head *test_pos; struct chain_head *test_c, *tmp_c; test_pos = iptcc_linearly_search_chain_index(name, handle); if (list_start_pos != test_pos) { debug("BUG in chain_index search\n"); test_c=list_entry(test_pos, struct chain_head,list); tmp_c =list_entry(list_start_pos,struct chain_head,list); debug("Verify search found:\n"); debug(" Chain:%s\n", test_c->name); debug("BSearch found:\n"); debug(" Chain:%s\n", tmp_c->name); exit(42); } } #endif /* Initial/special case, no user defined chains */ if (handle->num_chains == 0) return NULL; /* Start searching through the chain list */ list_for_each(pos, list_start_pos->prev) { struct chain_head *c = list_entry(pos, struct chain_head, list); res = strcmp(c->name, name); debug("List search name:%s == %s res:%d\n", name, c->name, res); if (res==0) return c; /* We can stop earlier as we know list is sorted */ if (res>0 && !iptcc_is_builtin(c)) { /* Walked too far*/ debug(" Not in list, walked too far, sorted list\n"); return NULL; } /* Stop on wrap around, if list head is reached */ if (pos == &handle->chains) { debug("Stop, list head reached\n"); return NULL; } } debug("List search NOT found name:%s\n", name); return NULL; } /* called when rule is to be removed from cache */ static void iptcc_delete_rule(struct rule_head *r) { DEBUGP("deleting rule %p (offset %u)\n", r, r->offset); /* clean up reference count of called chain */ if (r->type == IPTCC_R_JUMP && r->jump) r->jump->references--; list_del(&r->list); free(r); } /********************************************************************** * RULESET PARSER (blob -> cache) **********************************************************************/ /* Delete policy rule of previous chain, since cache doesn't contain * chain policy rules. * WARNING: This function has ugly design and relies on a lot of context, only * to be called from specific places within the parser */ static int __iptcc_p_del_policy(struct xtc_handle *h, unsigned int num) { const unsigned char *data; if (h->chain_iterator_cur) { /* policy rule is last rule */ struct rule_head *pr = (struct rule_head *) h->chain_iterator_cur->rules.prev; /* save verdict */ data = GET_TARGET(pr->entry)->data; h->chain_iterator_cur->verdict = *(const int *)data; /* save counter and counter_map information */ h->chain_iterator_cur->counter_map.maptype = COUNTER_MAP_ZEROED; h->chain_iterator_cur->counter_map.mappos = num-1; memcpy(&h->chain_iterator_cur->counters, &pr->entry->counters, sizeof(h->chain_iterator_cur->counters)); /* foot_offset points to verdict rule */ h->chain_iterator_cur->foot_index = num; h->chain_iterator_cur->foot_offset = pr->offset; /* delete rule from cache */ iptcc_delete_rule(pr); h->chain_iterator_cur->num_rules--; return 1; } return 0; } /* alphabetically insert a chain into the list */ static void iptc_insert_chain(struct xtc_handle *h, struct chain_head *c) { struct chain_head *tmp; struct list_head *list_start_pos; unsigned int i=1; /* Find a smart place to start the insert search */ list_start_pos = iptcc_bsearch_chain_index(c->name, &i, h); /* Handle the case, where chain.name is smaller than index[0] */ if (i==0 && strcmp(c->name, h->chain_index[0]->name) <= 0) { h->chain_index[0] = c; /* Update chain index head */ list_start_pos = h->chains.next; debug("Update chain_index[0] with %s\n", c->name); } /* Handel if bsearch bails out early */ if (list_start_pos == &h->chains) { list_start_pos = h->chains.next; } /* sort only user defined chains */ if (!c->hooknum) { list_for_each_entry(tmp, list_start_pos->prev, list) { if (!tmp->hooknum && strcmp(c->name, tmp->name) <= 0) { list_add(&c->list, tmp->list.prev); return; } /* Stop if list head is reached */ if (&tmp->list == &h->chains) { debug("Insert, list head reached add to tail\n"); break; } } } /* survived till end of list: add at tail */ list_add_tail(&c->list, &h->chains); } /* Another ugly helper function split out of cache_add_entry to make it less * spaghetti code */ static void __iptcc_p_add_chain(struct xtc_handle *h, struct chain_head *c, unsigned int offset, unsigned int *num) { struct list_head *tail = h->chains.prev; struct chain_head *ctail; __iptcc_p_del_policy(h, *num); c->head_offset = offset; c->index = *num; /* Chains from kernel are already sorted, as they are inserted * sorted. But there exists an issue when shifting to 1.4.0 * from an older version, as old versions allow last created * chain to be unsorted. */ if (iptcc_is_builtin(c)) /* Only user defined chains are sorted*/ list_add_tail(&c->list, &h->chains); else { ctail = list_entry(tail, struct chain_head, list); if (strcmp(c->name, ctail->name) > 0 || iptcc_is_builtin(ctail)) list_add_tail(&c->list, &h->chains);/* Already sorted*/ else { iptc_insert_chain(h, c);/* Was not sorted */ /* Notice, if chains were not received sorted * from kernel, then an offset bsearch is no * longer valid. */ h->sorted_offsets = 0; debug("NOTICE: chain:[%s] was NOT sorted(ctail:%s)\n", c->name, ctail->name); } } h->chain_iterator_cur = c; } /* main parser function: add an entry from the blob to the cache */ static int cache_add_entry(STRUCT_ENTRY *e, struct xtc_handle *h, STRUCT_ENTRY **prev, unsigned int *num) { unsigned int builtin; unsigned int offset = (char *)e - (char *)h->entries->entrytable; DEBUGP("entering..."); /* Last entry ("policy rule"). End it.*/ if (iptcb_entry2offset(h,e) + e->next_offset == h->entries->size) { /* This is the ERROR node at the end of the chain */ DEBUGP_C("%u:%u: end of table:\n", *num, offset); __iptcc_p_del_policy(h, *num); h->chain_iterator_cur = NULL; goto out_inc; } /* We know this is the start of a new chain if it's an ERROR * target, or a hook entry point */ if (strcmp(GET_TARGET(e)->u.user.name, ERROR_TARGET) == 0) { struct chain_head *c = iptcc_alloc_chain_head((const char *)GET_TARGET(e)->data, 0); DEBUGP_C("%u:%u:new userdefined chain %s: %p\n", *num, offset, (char *)c->name, c); if (!c) { errno = -ENOMEM; return -1; } h->num_chains++; /* New user defined chain */ __iptcc_p_add_chain(h, c, offset, num); } else if ((builtin = iptcb_ent_is_hook_entry(e, h)) != 0) { struct chain_head *c = iptcc_alloc_chain_head((char *)hooknames[builtin-1], builtin); DEBUGP_C("%u:%u new builtin chain: %p (rules=%p)\n", *num, offset, c, &c->rules); if (!c) { errno = -ENOMEM; return -1; } c->hooknum = builtin; __iptcc_p_add_chain(h, c, offset, num); /* FIXME: this is ugly. */ goto new_rule; } else { /* has to be normal rule */ struct rule_head *r; new_rule: if (!(r = iptcc_alloc_rule(h->chain_iterator_cur, e->next_offset))) { errno = ENOMEM; return -1; } DEBUGP_C("%u:%u normal rule: %p: ", *num, offset, r); r->index = *num; r->offset = offset; memcpy(r->entry, e, e->next_offset); r->counter_map.maptype = COUNTER_MAP_NORMAL_MAP; r->counter_map.mappos = r->index; /* handling of jumps, etc. */ if (!strcmp(GET_TARGET(e)->u.user.name, STANDARD_TARGET)) { STRUCT_STANDARD_TARGET *t; t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e); if (t->target.u.target_size != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) { errno = EINVAL; free(r); return -1; } if (t->verdict < 0) { DEBUGP_C("standard, verdict=%d\n", t->verdict); r->type = IPTCC_R_STANDARD; } else if (t->verdict == r->offset+e->next_offset) { DEBUGP_C("fallthrough\n"); r->type = IPTCC_R_FALLTHROUGH; } else { DEBUGP_C("jump, target=%u\n", t->verdict); r->type = IPTCC_R_JUMP; /* Jump target fixup has to be deferred * until second pass, since we migh not * yet have parsed the target */ } } else { DEBUGP_C("module, target=%s\n", GET_TARGET(e)->u.user.name); r->type = IPTCC_R_MODULE; } list_add_tail(&r->list, &h->chain_iterator_cur->rules); h->chain_iterator_cur->num_rules++; } out_inc: (*num)++; return 0; } /* parse an iptables blob into it's pieces */ static int parse_table(struct xtc_handle *h) { STRUCT_ENTRY *prev; unsigned int num = 0; struct chain_head *c; /* Assume that chains offsets are sorted, this verified during parsing of ruleset (in __iptcc_p_add_chain())*/ h->sorted_offsets = 1; /* First pass: over ruleset blob */ ENTRY_ITERATE(h->entries->entrytable, h->entries->size, cache_add_entry, h, &prev, &num); /* Build the chain index, used for chain list search speedup */ if ((iptcc_chain_index_alloc(h)) < 0) return -ENOMEM; iptcc_chain_index_build(h); /* Second pass: fixup parsed data from first pass */ list_for_each_entry(c, &h->chains, list) { struct rule_head *r; list_for_each_entry(r, &c->rules, list) { struct chain_head *lc; STRUCT_STANDARD_TARGET *t; if (r->type != IPTCC_R_JUMP) continue; t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry); lc = iptcc_find_chain_by_offset(h, t->verdict); if (!lc) return -1; r->jump = lc; lc->references++; } } return 1; } /********************************************************************** * RULESET COMPILATION (cache -> blob) **********************************************************************/ /* Convenience structures */ struct iptcb_chain_start{ STRUCT_ENTRY e; struct xt_error_target name; }; #define IPTCB_CHAIN_START_SIZE (sizeof(STRUCT_ENTRY) + \ ALIGN(sizeof(struct xt_error_target))) struct iptcb_chain_foot { STRUCT_ENTRY e; STRUCT_STANDARD_TARGET target; }; #define IPTCB_CHAIN_FOOT_SIZE (sizeof(STRUCT_ENTRY) + \ ALIGN(sizeof(STRUCT_STANDARD_TARGET))) struct iptcb_chain_error { STRUCT_ENTRY entry; struct xt_error_target target; }; #define IPTCB_CHAIN_ERROR_SIZE (sizeof(STRUCT_ENTRY) + \ ALIGN(sizeof(struct xt_error_target))) /* compile rule from cache into blob */ static inline int iptcc_compile_rule (struct xtc_handle *h, STRUCT_REPLACE *repl, struct rule_head *r) { /* handle jumps */ if (r->type == IPTCC_R_JUMP) { STRUCT_STANDARD_TARGET *t; t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry); /* memset for memcmp convenience on delete/replace */ memset(t->target.u.user.name, 0, FUNCTION_MAXNAMELEN); strcpy(t->target.u.user.name, STANDARD_TARGET); /* Jumps can only happen to builtin chains, so we * can safely assume that they always have a header */ t->verdict = r->jump->head_offset + IPTCB_CHAIN_START_SIZE; } else if (r->type == IPTCC_R_FALLTHROUGH) { STRUCT_STANDARD_TARGET *t; t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry); t->verdict = r->offset + r->size; } /* copy entry from cache to blob */ memcpy((char *)repl->entries+r->offset, r->entry, r->size); return 1; } /* compile chain from cache into blob */ static int iptcc_compile_chain(struct xtc_handle *h, STRUCT_REPLACE *repl, struct chain_head *c) { int ret; struct rule_head *r; struct iptcb_chain_start *head; struct iptcb_chain_foot *foot; /* only user-defined chains have heaer */ if (!iptcc_is_builtin(c)) { /* put chain header in place */ head = (void *)repl->entries + c->head_offset; head->e.target_offset = sizeof(STRUCT_ENTRY); head->e.next_offset = IPTCB_CHAIN_START_SIZE; strcpy(head->name.target.u.user.name, ERROR_TARGET); head->name.target.u.target_size = ALIGN(sizeof(struct xt_error_target)); strcpy(head->name.errorname, c->name); } else { repl->hook_entry[c->hooknum-1] = c->head_offset; repl->underflow[c->hooknum-1] = c->foot_offset; } /* iterate over rules */ list_for_each_entry(r, &c->rules, list) { ret = iptcc_compile_rule(h, repl, r); if (ret < 0) return ret; } /* put chain footer in place */ foot = (void *)repl->entries + c->foot_offset; foot->e.target_offset = sizeof(STRUCT_ENTRY); foot->e.next_offset = IPTCB_CHAIN_FOOT_SIZE; strcpy(foot->target.target.u.user.name, STANDARD_TARGET); foot->target.target.u.target_size = ALIGN(sizeof(STRUCT_STANDARD_TARGET)); /* builtin targets have verdict, others return */ if (iptcc_is_builtin(c)) foot->target.verdict = c->verdict; else foot->target.verdict = RETURN; /* set policy-counters */ memcpy(&foot->e.counters, &c->counters, sizeof(STRUCT_COUNTERS)); return 0; } /* calculate offset and number for every rule in the cache */ static int iptcc_compile_chain_offsets(struct xtc_handle *h, struct chain_head *c, unsigned int *offset, unsigned int *num) { struct rule_head *r; c->head_offset = *offset; DEBUGP("%s: chain_head %u, offset=%u\n", c->name, *num, *offset); if (!iptcc_is_builtin(c)) { /* Chain has header */ *offset += sizeof(STRUCT_ENTRY) + ALIGN(sizeof(struct xt_error_target)); (*num)++; } list_for_each_entry(r, &c->rules, list) { DEBUGP("rule %u, offset=%u, index=%u\n", *num, *offset, *num); r->offset = *offset; r->index = *num; *offset += r->size; (*num)++; } DEBUGP("%s; chain_foot %u, offset=%u, index=%u\n", c->name, *num, *offset, *num); c->foot_offset = *offset; c->foot_index = *num; *offset += sizeof(STRUCT_ENTRY) + ALIGN(sizeof(STRUCT_STANDARD_TARGET)); (*num)++; return 1; } /* put the pieces back together again */ static int iptcc_compile_table_prep(struct xtc_handle *h, unsigned int *size) { struct chain_head *c; unsigned int offset = 0, num = 0; int ret = 0; /* First pass: calculate offset for every rule */ list_for_each_entry(c, &h->chains, list) { ret = iptcc_compile_chain_offsets(h, c, &offset, &num); if (ret < 0) return ret; } /* Append one error rule at end of chain */ num++; offset += sizeof(STRUCT_ENTRY) + ALIGN(sizeof(struct xt_error_target)); /* ruleset size is now in offset */ *size = offset; return num; } static int iptcc_compile_table(struct xtc_handle *h, STRUCT_REPLACE *repl) { struct chain_head *c; struct iptcb_chain_error *error; /* Second pass: copy from cache to offsets, fill in jumps */ list_for_each_entry(c, &h->chains, list) { int ret = iptcc_compile_chain(h, repl, c); if (ret < 0) return ret; } /* Append error rule at end of chain */ error = (void *)repl->entries + repl->size - IPTCB_CHAIN_ERROR_SIZE; error->entry.target_offset = sizeof(STRUCT_ENTRY); error->entry.next_offset = IPTCB_CHAIN_ERROR_SIZE; error->target.target.u.user.target_size = ALIGN(sizeof(struct xt_error_target)); strcpy((char *)&error->target.target.u.user.name, ERROR_TARGET); strcpy((char *)&error->target.errorname, "ERROR"); return 1; } /********************************************************************** * EXTERNAL API (operates on cache only) **********************************************************************/ /* Allocate handle of given size */ static struct xtc_handle * alloc_handle(const char *tablename, unsigned int size, unsigned int num_rules) { struct xtc_handle *h; h = malloc(sizeof(*h)); if (!h) { errno = ENOMEM; return NULL; } memset(h, 0, sizeof(*h)); INIT_LIST_HEAD(&h->chains); strcpy(h->info.name, tablename); h->entries = malloc(sizeof(STRUCT_GET_ENTRIES) + size); if (!h->entries) goto out_free_handle; strcpy(h->entries->name, tablename); h->entries->size = size; return h; out_free_handle: free(h); return NULL; } struct xtc_handle * TC_INIT(const char *tablename) { struct xtc_handle *h; STRUCT_GETINFO info; unsigned int tmp; socklen_t s; int sockfd; retry: iptc_fn = TC_INIT; if (strlen(tablename) >= TABLE_MAXNAMELEN) { errno = EINVAL; return NULL; } sockfd = socket(TC_AF, SOCK_RAW, IPPROTO_RAW); if (sockfd < 0) return NULL; if (fcntl(sockfd, F_SETFD, FD_CLOEXEC) == -1) { fprintf(stderr, "Could not set close on exec: %s\n", strerror(errno)); abort(); } s = sizeof(info); strcpy(info.name, tablename); if (getsockopt(sockfd, TC_IPPROTO, SO_GET_INFO, &info, &s) < 0) { close(sockfd); return NULL; } DEBUGP("valid_hooks=0x%08x, num_entries=%u, size=%u\n", info.valid_hooks, info.num_entries, info.size); if ((h = alloc_handle(info.name, info.size, info.num_entries)) == NULL) { close(sockfd); return NULL; } /* Initialize current state */ h->sockfd = sockfd; h->info = info; h->entries->size = h->info.size; tmp = sizeof(STRUCT_GET_ENTRIES) + h->info.size; if (getsockopt(h->sockfd, TC_IPPROTO, SO_GET_ENTRIES, h->entries, &tmp) < 0) goto error; #ifdef IPTC_DEBUG2 { int fd = open("/tmp/libiptc-so_get_entries.blob", O_CREAT|O_WRONLY); if (fd >= 0) { write(fd, h->entries, tmp); close(fd); } } #endif if (parse_table(h) < 0) goto error; CHECK(h); return h; error: TC_FREE(h); /* A different process changed the ruleset size, retry */ if (errno == EAGAIN) goto retry; return NULL; } void TC_FREE(struct xtc_handle *h) { struct chain_head *c, *tmp; iptc_fn = TC_FREE; close(h->sockfd); list_for_each_entry_safe(c, tmp, &h->chains, list) { struct rule_head *r, *rtmp; list_for_each_entry_safe(r, rtmp, &c->rules, list) { free(r); } free(c); } iptcc_chain_index_free(h); free(h->entries); free(h); } static inline int print_match(const STRUCT_ENTRY_MATCH *m) { printf("Match name: `%s'\n", m->u.user.name); return 0; } static int dump_entry(STRUCT_ENTRY *e, struct xtc_handle *const handle); void TC_DUMP_ENTRIES(struct xtc_handle *const handle) { iptc_fn = TC_DUMP_ENTRIES; CHECK(handle); printf("libiptc v%s. %u bytes.\n", XTABLES_VERSION, handle->entries->size); printf("Table `%s'\n", handle->info.name); printf("Hooks: pre/in/fwd/out/post = %x/%x/%x/%x/%x\n", handle->info.hook_entry[HOOK_PRE_ROUTING], handle->info.hook_entry[HOOK_LOCAL_IN], handle->info.hook_entry[HOOK_FORWARD], handle->info.hook_entry[HOOK_LOCAL_OUT], handle->info.hook_entry[HOOK_POST_ROUTING]); printf("Underflows: pre/in/fwd/out/post = %x/%x/%x/%x/%x\n", handle->info.underflow[HOOK_PRE_ROUTING], handle->info.underflow[HOOK_LOCAL_IN], handle->info.underflow[HOOK_FORWARD], handle->info.underflow[HOOK_LOCAL_OUT], handle->info.underflow[HOOK_POST_ROUTING]); ENTRY_ITERATE(handle->entries->entrytable, handle->entries->size, dump_entry, handle); } /* Does this chain exist? */ int TC_IS_CHAIN(const char *chain, struct xtc_handle *const handle) { iptc_fn = TC_IS_CHAIN; return iptcc_find_label(chain, handle) != NULL; } static void iptcc_chain_iterator_advance(struct xtc_handle *handle) { struct chain_head *c = handle->chain_iterator_cur; if (c->list.next == &handle->chains) handle->chain_iterator_cur = NULL; else handle->chain_iterator_cur = list_entry(c->list.next, struct chain_head, list); } /* Iterator functions to run through the chains. */ const char * TC_FIRST_CHAIN(struct xtc_handle *handle) { struct chain_head *c = list_entry(handle->chains.next, struct chain_head, list); iptc_fn = TC_FIRST_CHAIN; if (list_empty(&handle->chains)) { DEBUGP(": no chains\n"); return NULL; } handle->chain_iterator_cur = c; iptcc_chain_iterator_advance(handle); DEBUGP(": returning `%s'\n", c->name); return c->name; } /* Iterator functions to run through the chains. Returns NULL at end. */ const char * TC_NEXT_CHAIN(struct xtc_handle *handle) { struct chain_head *c = handle->chain_iterator_cur; iptc_fn = TC_NEXT_CHAIN; if (!c) { DEBUGP(": no more chains\n"); return NULL; } iptcc_chain_iterator_advance(handle); DEBUGP(": returning `%s'\n", c->name); return c->name; } /* Get first rule in the given chain: NULL for empty chain. */ const STRUCT_ENTRY * TC_FIRST_RULE(const char *chain, struct xtc_handle *handle) { struct chain_head *c; struct rule_head *r; iptc_fn = TC_FIRST_RULE; DEBUGP("first rule(%s): ", chain); c = iptcc_find_label(chain, handle); if (!c) { errno = ENOENT; return NULL; } /* Empty chain: single return/policy rule */ if (list_empty(&c->rules)) { DEBUGP_C("no rules, returning NULL\n"); return NULL; } r = list_entry(c->rules.next, struct rule_head, list); handle->rule_iterator_cur = r; DEBUGP_C("%p\n", r); return r->entry; } /* Returns NULL when rules run out. */ const STRUCT_ENTRY * TC_NEXT_RULE(const STRUCT_ENTRY *prev, struct xtc_handle *handle) { struct rule_head *r; iptc_fn = TC_NEXT_RULE; DEBUGP("rule_iterator_cur=%p...", handle->rule_iterator_cur); if (handle->rule_iterator_cur == NULL) { DEBUGP_C("returning NULL\n"); return NULL; } r = list_entry(handle->rule_iterator_cur->list.next, struct rule_head, list); iptc_fn = TC_NEXT_RULE; DEBUGP_C("next=%p, head=%p...", &r->list, &handle->rule_iterator_cur->chain->rules); if (&r->list == &handle->rule_iterator_cur->chain->rules) { handle->rule_iterator_cur = NULL; DEBUGP_C("finished, returning NULL\n"); return NULL; } handle->rule_iterator_cur = r; /* NOTE: prev is without any influence ! */ DEBUGP_C("returning rule %p\n", r); return r->entry; } /* Returns a pointer to the target name of this position. */ static const char *standard_target_map(int verdict) { switch (verdict) { case RETURN: return LABEL_RETURN; break; case -NF_ACCEPT-1: return LABEL_ACCEPT; break; case -NF_DROP-1: return LABEL_DROP; break; case -NF_QUEUE-1: return LABEL_QUEUE; break; default: fprintf(stderr, "ERROR: %d not a valid target)\n", verdict); abort(); break; } /* not reached */ return NULL; } /* Returns a pointer to the target name of this position. */ const char *TC_GET_TARGET(const STRUCT_ENTRY *ce, struct xtc_handle *handle) { STRUCT_ENTRY *e = (STRUCT_ENTRY *)ce; struct rule_head *r = container_of(e, struct rule_head, entry[0]); const unsigned char *data; iptc_fn = TC_GET_TARGET; switch(r->type) { int spos; case IPTCC_R_FALLTHROUGH: return ""; break; case IPTCC_R_JUMP: DEBUGP("r=%p, jump=%p, name=`%s'\n", r, r->jump, r->jump->name); return r->jump->name; break; case IPTCC_R_STANDARD: data = GET_TARGET(e)->data; spos = *(const int *)data; DEBUGP("r=%p, spos=%d'\n", r, spos); return standard_target_map(spos); break; case IPTCC_R_MODULE: return GET_TARGET(e)->u.user.name; break; } return NULL; } /* Is this a built-in chain? Actually returns hook + 1. */ int TC_BUILTIN(const char *chain, struct xtc_handle *const handle) { struct chain_head *c; iptc_fn = TC_BUILTIN; c = iptcc_find_label(chain, handle); if (!c) { errno = ENOENT; return 0; } return iptcc_is_builtin(c); } /* Get the policy of a given built-in chain */ const char * TC_GET_POLICY(const char *chain, STRUCT_COUNTERS *counters, struct xtc_handle *handle) { struct chain_head *c; iptc_fn = TC_GET_POLICY; DEBUGP("called for chain %s\n", chain); c = iptcc_find_label(chain, handle); if (!c) { errno = ENOENT; return NULL; } if (!iptcc_is_builtin(c)) return NULL; *counters = c->counters; return standard_target_map(c->verdict); } static int iptcc_standard_map(struct rule_head *r, int verdict) { STRUCT_ENTRY *e = r->entry; STRUCT_STANDARD_TARGET *t; t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e); if (t->target.u.target_size != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) { errno = EINVAL; return 0; } /* memset for memcmp convenience on delete/replace */ memset(t->target.u.user.name, 0, FUNCTION_MAXNAMELEN); strcpy(t->target.u.user.name, STANDARD_TARGET); t->verdict = verdict; r->type = IPTCC_R_STANDARD; return 1; } static int iptcc_map_target(struct xtc_handle *const handle, struct rule_head *r) { STRUCT_ENTRY *e = r->entry; STRUCT_ENTRY_TARGET *t = GET_TARGET(e); /* Maybe it's empty (=> fall through) */ if (strcmp(t->u.user.name, "") == 0) { r->type = IPTCC_R_FALLTHROUGH; return 1; } /* Maybe it's a standard target name... */ else if (strcmp(t->u.user.name, LABEL_ACCEPT) == 0) return iptcc_standard_map(r, -NF_ACCEPT - 1); else if (strcmp(t->u.user.name, LABEL_DROP) == 0) return iptcc_standard_map(r, -NF_DROP - 1); else if (strcmp(t->u.user.name, LABEL_QUEUE) == 0) return iptcc_standard_map(r, -NF_QUEUE - 1); else if (strcmp(t->u.user.name, LABEL_RETURN) == 0) return iptcc_standard_map(r, RETURN); else if (TC_BUILTIN(t->u.user.name, handle)) { /* Can't jump to builtins. */ errno = EINVAL; return 0; } else { /* Maybe it's an existing chain name. */ struct chain_head *c; DEBUGP("trying to find chain `%s': ", t->u.user.name); c = iptcc_find_label(t->u.user.name, handle); if (c) { DEBUGP_C("found!\n"); r->type = IPTCC_R_JUMP; r->jump = c; c->references++; return 1; } DEBUGP_C("not found :(\n"); } /* Must be a module? If not, kernel will reject... */ /* memset to all 0 for your memcmp convenience: don't clear version */ memset(t->u.user.name + strlen(t->u.user.name), 0, FUNCTION_MAXNAMELEN - 1 - strlen(t->u.user.name)); r->type = IPTCC_R_MODULE; set_changed(handle); return 1; } /* Insert the entry `fw' in chain `chain' into position `rulenum'. */ int TC_INSERT_ENTRY(const IPT_CHAINLABEL chain, const STRUCT_ENTRY *e, unsigned int rulenum, struct xtc_handle *handle) { struct chain_head *c; struct rule_head *r; struct list_head *prev; iptc_fn = TC_INSERT_ENTRY; if (!(c = iptcc_find_label(chain, handle))) { errno = ENOENT; return 0; } /* first rulenum index = 0 first c->num_rules index = 1 */ if (rulenum > c->num_rules) { errno = E2BIG; return 0; } /* If we are inserting at the end just take advantage of the double linked list, insert will happen before the entry prev points to. */ if (rulenum == c->num_rules) { prev = &c->rules; } else if (rulenum + 1 <= c->num_rules/2) { r = iptcc_get_rule_num(c, rulenum + 1); prev = &r->list; } else { r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum); prev = &r->list; } if (!(r = iptcc_alloc_rule(c, e->next_offset))) { errno = ENOMEM; return 0; } memcpy(r->entry, e, e->next_offset); r->counter_map.maptype = COUNTER_MAP_SET; if (!iptcc_map_target(handle, r)) { free(r); return 0; } list_add_tail(&r->list, prev); c->num_rules++; set_changed(handle); return 1; } /* Atomically replace rule `rulenum' in `chain' with `fw'. */ int TC_REPLACE_ENTRY(const IPT_CHAINLABEL chain, const STRUCT_ENTRY *e, unsigned int rulenum, struct xtc_handle *handle) { struct chain_head *c; struct rule_head *r, *old; iptc_fn = TC_REPLACE_ENTRY; if (!(c = iptcc_find_label(chain, handle))) { errno = ENOENT; return 0; } if (rulenum >= c->num_rules) { errno = E2BIG; return 0; } /* Take advantage of the double linked list if possible. */ if (rulenum + 1 <= c->num_rules/2) { old = iptcc_get_rule_num(c, rulenum + 1); } else { old = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum); } if (!(r = iptcc_alloc_rule(c, e->next_offset))) { errno = ENOMEM; return 0; } memcpy(r->entry, e, e->next_offset); r->counter_map.maptype = COUNTER_MAP_SET; if (!iptcc_map_target(handle, r)) { free(r); return 0; } list_add(&r->list, &old->list); iptcc_delete_rule(old); set_changed(handle); return 1; } /* Append entry `fw' to chain `chain'. Equivalent to insert with rulenum = length of chain. */ int TC_APPEND_ENTRY(const IPT_CHAINLABEL chain, const STRUCT_ENTRY *e, struct xtc_handle *handle) { struct chain_head *c; struct rule_head *r; iptc_fn = TC_APPEND_ENTRY; if (!(c = iptcc_find_label(chain, handle))) { DEBUGP("unable to find chain `%s'\n", chain); errno = ENOENT; return 0; } if (!(r = iptcc_alloc_rule(c, e->next_offset))) { DEBUGP("unable to allocate rule for chain `%s'\n", chain); errno = ENOMEM; return 0; } memcpy(r->entry, e, e->next_offset); r->counter_map.maptype = COUNTER_MAP_SET; if (!iptcc_map_target(handle, r)) { DEBUGP("unable to map target of rule for chain `%s'\n", chain); free(r); return 0; } list_add_tail(&r->list, &c->rules); c->num_rules++; set_changed(handle); return 1; } static inline int match_different(const STRUCT_ENTRY_MATCH *a, const unsigned char *a_elems, const unsigned char *b_elems, unsigned char **maskptr) { const STRUCT_ENTRY_MATCH *b; unsigned int i; /* Offset of b is the same as a. */ b = (void *)b_elems + ((unsigned char *)a - a_elems); if (a->u.match_size != b->u.match_size) return 1; if (strcmp(a->u.user.name, b->u.user.name) != 0) return 1; *maskptr += ALIGN(sizeof(*a)); for (i = 0; i < a->u.match_size - ALIGN(sizeof(*a)); i++) if (((a->data[i] ^ b->data[i]) & (*maskptr)[i]) != 0) return 1; *maskptr += i; return 0; } static inline int target_same(struct rule_head *a, struct rule_head *b,const unsigned char *mask) { unsigned int i; STRUCT_ENTRY_TARGET *ta, *tb; if (a->type != b->type) return 0; ta = GET_TARGET(a->entry); tb = GET_TARGET(b->entry); switch (a->type) { case IPTCC_R_FALLTHROUGH: return 1; case IPTCC_R_JUMP: return a->jump == b->jump; case IPTCC_R_STANDARD: return ((STRUCT_STANDARD_TARGET *)ta)->verdict == ((STRUCT_STANDARD_TARGET *)tb)->verdict; case IPTCC_R_MODULE: if (ta->u.target_size != tb->u.target_size) return 0; if (strcmp(ta->u.user.name, tb->u.user.name) != 0) return 0; for (i = 0; i < ta->u.target_size - sizeof(*ta); i++) if (((ta->data[i] ^ tb->data[i]) & mask[i]) != 0) return 0; return 1; default: fprintf(stderr, "ERROR: bad type %i\n", a->type); abort(); } } static unsigned char * is_same(const STRUCT_ENTRY *a, const STRUCT_ENTRY *b, unsigned char *matchmask); /* find the first rule in `chain' which matches `fw' and remove it unless dry_run is set */ static int delete_entry(const IPT_CHAINLABEL chain, const STRUCT_ENTRY *origfw, unsigned char *matchmask, struct xtc_handle *handle, bool dry_run) { struct chain_head *c; struct rule_head *r, *i; iptc_fn = TC_DELETE_ENTRY; if (!(c = iptcc_find_label(chain, handle))) { errno = ENOENT; return 0; } /* Create a rule_head from origfw. */ r = iptcc_alloc_rule(c, origfw->next_offset); if (!r) { errno = ENOMEM; return 0; } memcpy(r->entry, origfw, origfw->next_offset); r->counter_map.maptype = COUNTER_MAP_NOMAP; if (!iptcc_map_target(handle, r)) { DEBUGP("unable to map target of rule for chain `%s'\n", chain); free(r); return 0; } else { /* iptcc_map_target increment target chain references * since this is a fake rule only used for matching * the chain references count is decremented again. */ if (r->type == IPTCC_R_JUMP && r->jump) r->jump->references--; } list_for_each_entry(i, &c->rules, list) { unsigned char *mask; mask = is_same(r->entry, i->entry, matchmask); if (!mask) continue; if (!target_same(r, i, mask)) continue; /* if we are just doing a dry run, we simply skip the rest */ if (dry_run){ free(r); return 1; } /* If we are about to delete the rule that is the * current iterator, move rule iterator back. next * pointer will then point to real next node */ if (i == handle->rule_iterator_cur) { handle->rule_iterator_cur = list_entry(handle->rule_iterator_cur->list.prev, struct rule_head, list); } c->num_rules--; iptcc_delete_rule(i); set_changed(handle); free(r); return 1; } free(r); errno = ENOENT; return 0; } /* check whether a specified rule is present */ int TC_CHECK_ENTRY(const IPT_CHAINLABEL chain, const STRUCT_ENTRY *origfw, unsigned char *matchmask, struct xtc_handle *handle) { /* do a dry-run delete to find out whether a matching rule exists */ return delete_entry(chain, origfw, matchmask, handle, true); } /* Delete the first rule in `chain' which matches `fw'. */ int TC_DELETE_ENTRY(const IPT_CHAINLABEL chain, const STRUCT_ENTRY *origfw, unsigned char *matchmask, struct xtc_handle *handle) { return delete_entry(chain, origfw, matchmask, handle, false); } /* Delete the rule in position `rulenum' in `chain'. */ int TC_DELETE_NUM_ENTRY(const IPT_CHAINLABEL chain, unsigned int rulenum, struct xtc_handle *handle) { struct chain_head *c; struct rule_head *r; iptc_fn = TC_DELETE_NUM_ENTRY; if (!(c = iptcc_find_label(chain, handle))) { errno = ENOENT; return 0; } if (rulenum >= c->num_rules) { errno = E2BIG; return 0; } /* Take advantage of the double linked list if possible. */ if (rulenum + 1 <= c->num_rules/2) { r = iptcc_get_rule_num(c, rulenum + 1); } else { r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum); } /* If we are about to delete the rule that is the current * iterator, move rule iterator back. next pointer will then * point to real next node */ if (r == handle->rule_iterator_cur) { handle->rule_iterator_cur = list_entry(handle->rule_iterator_cur->list.prev, struct rule_head, list); } c->num_rules--; iptcc_delete_rule(r); set_changed(handle); return 1; } /* Flushes the entries in the given chain (ie. empties chain). */ int TC_FLUSH_ENTRIES(const IPT_CHAINLABEL chain, struct xtc_handle *handle) { struct chain_head *c; struct rule_head *r, *tmp; iptc_fn = TC_FLUSH_ENTRIES; if (!(c = iptcc_find_label(chain, handle))) { errno = ENOENT; return 0; } list_for_each_entry_safe(r, tmp, &c->rules, list) { iptcc_delete_rule(r); } c->num_rules = 0; set_changed(handle); return 1; } /* Zeroes the counters in a chain. */ int TC_ZERO_ENTRIES(const IPT_CHAINLABEL chain, struct xtc_handle *handle) { struct chain_head *c; struct rule_head *r; iptc_fn = TC_ZERO_ENTRIES; if (!(c = iptcc_find_label(chain, handle))) { errno = ENOENT; return 0; } if (c->counter_map.maptype == COUNTER_MAP_NORMAL_MAP) c->counter_map.maptype = COUNTER_MAP_ZEROED; list_for_each_entry(r, &c->rules, list) { if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP) r->counter_map.maptype = COUNTER_MAP_ZEROED; } set_changed(handle); return 1; } STRUCT_COUNTERS * TC_READ_COUNTER(const IPT_CHAINLABEL chain, unsigned int rulenum, struct xtc_handle *handle) { struct chain_head *c; struct rule_head *r; iptc_fn = TC_READ_COUNTER; CHECK(*handle); if (!(c = iptcc_find_label(chain, handle))) { errno = ENOENT; return NULL; } if (!(r = iptcc_get_rule_num(c, rulenum))) { errno = E2BIG; return NULL; } return &r->entry[0].counters; } int TC_ZERO_COUNTER(const IPT_CHAINLABEL chain, unsigned int rulenum, struct xtc_handle *handle) { struct chain_head *c; struct rule_head *r; iptc_fn = TC_ZERO_COUNTER; CHECK(handle); if (!(c = iptcc_find_label(chain, handle))) { errno = ENOENT; return 0; } if (!(r = iptcc_get_rule_num(c, rulenum))) { errno = E2BIG; return 0; } if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP) r->counter_map.maptype = COUNTER_MAP_ZEROED; set_changed(handle); return 1; } int TC_SET_COUNTER(const IPT_CHAINLABEL chain, unsigned int rulenum, STRUCT_COUNTERS *counters, struct xtc_handle *handle) { struct chain_head *c; struct rule_head *r; STRUCT_ENTRY *e; iptc_fn = TC_SET_COUNTER; CHECK(handle); if (!(c = iptcc_find_label(chain, handle))) { errno = ENOENT; return 0; } if (!(r = iptcc_get_rule_num(c, rulenum))) { errno = E2BIG; return 0; } e = r->entry; r->counter_map.maptype = COUNTER_MAP_SET; memcpy(&e->counters, counters, sizeof(STRUCT_COUNTERS)); set_changed(handle); return 1; } /* Creates a new chain. */ /* To create a chain, create two rules: error node and unconditional * return. */ int TC_CREATE_CHAIN(const IPT_CHAINLABEL chain, struct xtc_handle *handle) { static struct chain_head *c; int capacity; int exceeded; iptc_fn = TC_CREATE_CHAIN; /* find_label doesn't cover built-in targets: DROP, ACCEPT, QUEUE, RETURN. */ if (iptcc_find_label(chain, handle) || strcmp(chain, LABEL_DROP) == 0 || strcmp(chain, LABEL_ACCEPT) == 0 || strcmp(chain, LABEL_QUEUE) == 0 || strcmp(chain, LABEL_RETURN) == 0) { DEBUGP("Chain `%s' already exists\n", chain); errno = EEXIST; return 0; } if (strlen(chain)+1 > sizeof(IPT_CHAINLABEL)) { DEBUGP("Chain name `%s' too long\n", chain); errno = EINVAL; return 0; } c = iptcc_alloc_chain_head(chain, 0); if (!c) { DEBUGP("Cannot allocate memory for chain `%s'\n", chain); errno = ENOMEM; return 0; } handle->num_chains++; /* New user defined chain */ DEBUGP("Creating chain `%s'\n", chain); iptc_insert_chain(handle, c); /* Insert sorted */ /* Inserting chains don't change the correctness of the chain * index (except if its smaller than index[0], but that * handled by iptc_insert_chain). It only causes longer lists * in the buckets. Thus, only rebuild chain index when the * capacity is exceed with CHAIN_INDEX_INSERT_MAX chains. */ capacity = handle->chain_index_sz * CHAIN_INDEX_BUCKET_LEN; exceeded = handle->num_chains - capacity; if (exceeded > CHAIN_INDEX_INSERT_MAX) { debug("Capacity(%d) exceeded(%d) rebuild (chains:%d)\n", capacity, exceeded, handle->num_chains); iptcc_chain_index_rebuild(handle); } set_changed(handle); return 1; } /* Get the number of references to this chain. */ int TC_GET_REFERENCES(unsigned int *ref, const IPT_CHAINLABEL chain, struct xtc_handle *handle) { struct chain_head *c; iptc_fn = TC_GET_REFERENCES; if (!(c = iptcc_find_label(chain, handle))) { errno = ENOENT; return 0; } *ref = c->references; return 1; } /* Deletes a chain. */ int TC_DELETE_CHAIN(const IPT_CHAINLABEL chain, struct xtc_handle *handle) { unsigned int references; struct chain_head *c; iptc_fn = TC_DELETE_CHAIN; if (!(c = iptcc_find_label(chain, handle))) { DEBUGP("cannot find chain `%s'\n", chain); errno = ENOENT; return 0; } if (TC_BUILTIN(chain, handle)) { DEBUGP("cannot remove builtin chain `%s'\n", chain); errno = EINVAL; return 0; } if (!TC_GET_REFERENCES(&references, chain, handle)) { DEBUGP("cannot get references on chain `%s'\n", chain); return 0; } if (references > 0) { DEBUGP("chain `%s' still has references\n", chain); errno = EMLINK; return 0; } if (c->num_rules) { DEBUGP("chain `%s' is not empty\n", chain); errno = ENOTEMPTY; return 0; } /* If we are about to delete the chain that is the current * iterator, move chain iterator forward. */ if (c == handle->chain_iterator_cur) iptcc_chain_iterator_advance(handle); handle->num_chains--; /* One user defined chain deleted */ //list_del(&c->list); /* Done in iptcc_chain_index_delete_chain() */ iptcc_chain_index_delete_chain(c, handle); free(c); DEBUGP("chain `%s' deleted\n", chain); set_changed(handle); return 1; } /* Renames a chain. */ int TC_RENAME_CHAIN(const IPT_CHAINLABEL oldname, const IPT_CHAINLABEL newname, struct xtc_handle *handle) { struct chain_head *c; iptc_fn = TC_RENAME_CHAIN; /* find_label doesn't cover built-in targets: DROP, ACCEPT, QUEUE, RETURN. */ if (iptcc_find_label(newname, handle) || strcmp(newname, LABEL_DROP) == 0 || strcmp(newname, LABEL_ACCEPT) == 0 || strcmp(newname, LABEL_QUEUE) == 0 || strcmp(newname, LABEL_RETURN) == 0) { errno = EEXIST; return 0; } if (!(c = iptcc_find_label(oldname, handle)) || TC_BUILTIN(oldname, handle)) { errno = ENOENT; return 0; } if (strlen(newname)+1 > sizeof(IPT_CHAINLABEL)) { errno = EINVAL; return 0; } /* This only unlinks "c" from the list, thus no free(c) */ iptcc_chain_index_delete_chain(c, handle); /* Change the name of the chain */ strncpy(c->name, newname, sizeof(IPT_CHAINLABEL)); /* Insert sorted into to list again */ iptc_insert_chain(handle, c); set_changed(handle); return 1; } /* Sets the policy on a built-in chain. */ int TC_SET_POLICY(const IPT_CHAINLABEL chain, const IPT_CHAINLABEL policy, STRUCT_COUNTERS *counters, struct xtc_handle *handle) { struct chain_head *c; iptc_fn = TC_SET_POLICY; if (!(c = iptcc_find_label(chain, handle))) { DEBUGP("cannot find chain `%s'\n", chain); errno = ENOENT; return 0; } if (!iptcc_is_builtin(c)) { DEBUGP("cannot set policy of userdefinedchain `%s'\n", chain); errno = ENOENT; return 0; } if (strcmp(policy, LABEL_ACCEPT) == 0) c->verdict = -NF_ACCEPT - 1; else if (strcmp(policy, LABEL_DROP) == 0) c->verdict = -NF_DROP - 1; else { errno = EINVAL; return 0; } if (counters) { /* set byte and packet counters */ memcpy(&c->counters, counters, sizeof(STRUCT_COUNTERS)); c->counter_map.maptype = COUNTER_MAP_SET; } else { c->counter_map.maptype = COUNTER_MAP_NOMAP; } set_changed(handle); return 1; } /* Without this, on gcc 2.7.2.3, we get: libiptc.c: In function `TC_COMMIT': libiptc.c:833: fixed or forbidden register was spilled. This may be due to a compiler bug or to impossible asm statements or clauses. */ static void subtract_counters(STRUCT_COUNTERS *answer, const STRUCT_COUNTERS *a, const STRUCT_COUNTERS *b) { answer->pcnt = a->pcnt - b->pcnt; answer->bcnt = a->bcnt - b->bcnt; } static void counters_nomap(STRUCT_COUNTERS_INFO *newcounters, unsigned int idx) { newcounters->counters[idx] = ((STRUCT_COUNTERS) { 0, 0}); DEBUGP_C("NOMAP => zero\n"); } static void counters_normal_map(STRUCT_COUNTERS_INFO *newcounters, STRUCT_REPLACE *repl, unsigned int idx, unsigned int mappos) { /* Original read: X. * Atomic read on replacement: X + Y. * Currently in kernel: Z. * Want in kernel: X + Y + Z. * => Add in X + Y * => Add in replacement read. */ newcounters->counters[idx] = repl->counters[mappos]; DEBUGP_C("NORMAL_MAP => mappos %u \n", mappos); } static void counters_map_zeroed(STRUCT_COUNTERS_INFO *newcounters, STRUCT_REPLACE *repl, unsigned int idx, unsigned int mappos, STRUCT_COUNTERS *counters) { /* Original read: X. * Atomic read on replacement: X + Y. * Currently in kernel: Z. * Want in kernel: Y + Z. * => Add in Y. * => Add in (replacement read - original read). */ subtract_counters(&newcounters->counters[idx], &repl->counters[mappos], counters); DEBUGP_C("ZEROED => mappos %u\n", mappos); } static void counters_map_set(STRUCT_COUNTERS_INFO *newcounters, unsigned int idx, STRUCT_COUNTERS *counters) { /* Want to set counter (iptables-restore) */ memcpy(&newcounters->counters[idx], counters, sizeof(STRUCT_COUNTERS)); DEBUGP_C("SET\n"); } int TC_COMMIT(struct xtc_handle *handle) { /* Replace, then map back the counters. */ STRUCT_REPLACE *repl; STRUCT_COUNTERS_INFO *newcounters; struct chain_head *c; int ret; size_t counterlen; int new_number; unsigned int new_size; iptc_fn = TC_COMMIT; CHECK(*handle); /* Don't commit if nothing changed. */ if (!handle->changed) goto finished; new_number = iptcc_compile_table_prep(handle, &new_size); if (new_number < 0) { errno = ENOMEM; goto out_zero; } repl = malloc(sizeof(*repl) + new_size); if (!repl) { errno = ENOMEM; goto out_zero; } memset(repl, 0, sizeof(*repl) + new_size); #if 0 TC_DUMP_ENTRIES(*handle); #endif counterlen = sizeof(STRUCT_COUNTERS_INFO) + sizeof(STRUCT_COUNTERS) * new_number; /* These are the old counters we will get from kernel */ repl->counters = malloc(sizeof(STRUCT_COUNTERS) * handle->info.num_entries); if (!repl->counters) { errno = ENOMEM; goto out_free_repl; } /* These are the counters we're going to put back, later. */ newcounters = malloc(counterlen); if (!newcounters) { errno = ENOMEM; goto out_free_repl_counters; } memset(newcounters, 0, counterlen); strcpy(repl->name, handle->info.name); repl->num_entries = new_number; repl->size = new_size; repl->num_counters = handle->info.num_entries; repl->valid_hooks = handle->info.valid_hooks; DEBUGP("num_entries=%u, size=%u, num_counters=%u\n", repl->num_entries, repl->size, repl->num_counters); ret = iptcc_compile_table(handle, repl); if (ret < 0) { errno = ret; goto out_free_newcounters; } #ifdef IPTC_DEBUG2 { int fd = open("/tmp/libiptc-so_set_replace.blob", O_CREAT|O_WRONLY); if (fd >= 0) { write(fd, repl, sizeof(*repl) + repl->size); close(fd); } } #endif ret = setsockopt(handle->sockfd, TC_IPPROTO, SO_SET_REPLACE, repl, sizeof(*repl) + repl->size); if (ret < 0) goto out_free_newcounters; /* Put counters back. */ strcpy(newcounters->name, handle->info.name); newcounters->num_counters = new_number; list_for_each_entry(c, &handle->chains, list) { struct rule_head *r; /* Builtin chains have their own counters */ if (iptcc_is_builtin(c)) { DEBUGP("counter for chain-index %u: ", c->foot_index); switch(c->counter_map.maptype) { case COUNTER_MAP_NOMAP: counters_nomap(newcounters, c->foot_index); break; case COUNTER_MAP_NORMAL_MAP: counters_normal_map(newcounters, repl, c->foot_index, c->counter_map.mappos); break; case COUNTER_MAP_ZEROED: counters_map_zeroed(newcounters, repl, c->foot_index, c->counter_map.mappos, &c->counters); break; case COUNTER_MAP_SET: counters_map_set(newcounters, c->foot_index, &c->counters); break; } } list_for_each_entry(r, &c->rules, list) { DEBUGP("counter for index %u: ", r->index); switch (r->counter_map.maptype) { case COUNTER_MAP_NOMAP: counters_nomap(newcounters, r->index); break; case COUNTER_MAP_NORMAL_MAP: counters_normal_map(newcounters, repl, r->index, r->counter_map.mappos); break; case COUNTER_MAP_ZEROED: counters_map_zeroed(newcounters, repl, r->index, r->counter_map.mappos, &r->entry->counters); break; case COUNTER_MAP_SET: counters_map_set(newcounters, r->index, &r->entry->counters); break; } } } #ifdef IPTC_DEBUG2 { int fd = open("/tmp/libiptc-so_set_add_counters.blob", O_CREAT|O_WRONLY); if (fd >= 0) { write(fd, newcounters, counterlen); close(fd); } } #endif ret = setsockopt(handle->sockfd, TC_IPPROTO, SO_SET_ADD_COUNTERS, newcounters, counterlen); if (ret < 0) goto out_free_newcounters; free(repl->counters); free(repl); free(newcounters); finished: return 1; out_free_newcounters: free(newcounters); out_free_repl_counters: free(repl->counters); out_free_repl: free(repl); out_zero: return 0; } /* Translates errno numbers into more human-readable form than strerror. */ const char * TC_STRERROR(int err) { unsigned int i; struct table_struct { void *fn; int err; const char *message; } table [] = { { TC_INIT, EPERM, "Permission denied (you must be root)" }, { TC_INIT, EINVAL, "Module is wrong version" }, { TC_INIT, ENOENT, "Table does not exist (do you need to insmod?)" }, { TC_DELETE_CHAIN, ENOTEMPTY, "Chain is not empty" }, { TC_DELETE_CHAIN, EINVAL, "Can't delete built-in chain" }, { TC_DELETE_CHAIN, EMLINK, "Can't delete chain with references left" }, { TC_CREATE_CHAIN, EEXIST, "Chain already exists" }, { TC_INSERT_ENTRY, E2BIG, "Index of insertion too big" }, { TC_REPLACE_ENTRY, E2BIG, "Index of replacement too big" }, { TC_DELETE_NUM_ENTRY, E2BIG, "Index of deletion too big" }, { TC_READ_COUNTER, E2BIG, "Index of counter too big" }, { TC_ZERO_COUNTER, E2BIG, "Index of counter too big" }, { TC_INSERT_ENTRY, ELOOP, "Loop found in table" }, { TC_INSERT_ENTRY, EINVAL, "Target problem" }, /* ENOENT for DELETE probably means no matching rule */ { TC_DELETE_ENTRY, ENOENT, "Bad rule (does a matching rule exist in that chain?)" }, { TC_SET_POLICY, ENOENT, "Bad built-in chain name" }, { TC_SET_POLICY, EINVAL, "Bad policy name" }, { NULL, 0, "Incompatible with this kernel" }, { NULL, ENOPROTOOPT, "iptables who? (do you need to insmod?)" }, { NULL, ENOSYS, "Will be implemented real soon. I promise ;)" }, { NULL, ENOMEM, "Memory allocation problem" }, { NULL, ENOENT, "No chain/target/match by that name" }, }; for (i = 0; i < sizeof(table)/sizeof(struct table_struct); i++) { if ((!table[i].fn || table[i].fn == iptc_fn) && table[i].err == err) return table[i].message; } return strerror(err); } const struct xtc_ops TC_OPS = { .commit = TC_COMMIT, .free = TC_FREE, .builtin = TC_BUILTIN, .is_chain = TC_IS_CHAIN, .flush_entries = TC_FLUSH_ENTRIES, .create_chain = TC_CREATE_CHAIN, .set_policy = TC_SET_POLICY, .strerror = TC_STRERROR, };
233
./android_firewall/external/iptables/libiptc/libip4tc.c
/* Library which manipulates firewall rules. Version 0.1. */ /* Architecture of firewall rules is as follows: * * Chains go INPUT, FORWARD, OUTPUT then user chains. * Each user chain starts with an ERROR node. * Every chain ends with an unconditional jump: a RETURN for user chains, * and a POLICY for built-ins. */ /* (C)1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See COPYING for details). */ #include <assert.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #ifdef DEBUG_CONNTRACK #define inline #endif #if !defined(__GLIBC__) || (__GLIBC__ < 2) typedef unsigned int socklen_t; #endif #include "libiptc/libiptc.h" #define IP_VERSION 4 #define IP_OFFSET 0x1FFF #define HOOK_PRE_ROUTING NF_IP_PRE_ROUTING #define HOOK_LOCAL_IN NF_IP_LOCAL_IN #define HOOK_FORWARD NF_IP_FORWARD #define HOOK_LOCAL_OUT NF_IP_LOCAL_OUT #define HOOK_POST_ROUTING NF_IP_POST_ROUTING #define STRUCT_ENTRY_TARGET struct xt_entry_target #define STRUCT_ENTRY struct ipt_entry #define STRUCT_ENTRY_MATCH struct xt_entry_match #define STRUCT_GETINFO struct ipt_getinfo #define STRUCT_GET_ENTRIES struct ipt_get_entries #define STRUCT_COUNTERS struct xt_counters #define STRUCT_COUNTERS_INFO struct xt_counters_info #define STRUCT_STANDARD_TARGET struct xt_standard_target #define STRUCT_REPLACE struct ipt_replace #define ENTRY_ITERATE IPT_ENTRY_ITERATE #define TABLE_MAXNAMELEN XT_TABLE_MAXNAMELEN #define FUNCTION_MAXNAMELEN XT_FUNCTION_MAXNAMELEN #define GET_TARGET ipt_get_target #define ERROR_TARGET XT_ERROR_TARGET #define NUMHOOKS NF_IP_NUMHOOKS #define IPT_CHAINLABEL xt_chainlabel #define TC_DUMP_ENTRIES dump_entries #define TC_IS_CHAIN iptc_is_chain #define TC_FIRST_CHAIN iptc_first_chain #define TC_NEXT_CHAIN iptc_next_chain #define TC_FIRST_RULE iptc_first_rule #define TC_NEXT_RULE iptc_next_rule #define TC_GET_TARGET iptc_get_target #define TC_BUILTIN iptc_builtin #define TC_GET_POLICY iptc_get_policy #define TC_INSERT_ENTRY iptc_insert_entry #define TC_REPLACE_ENTRY iptc_replace_entry #define TC_APPEND_ENTRY iptc_append_entry #define TC_CHECK_ENTRY iptc_check_entry #define TC_DELETE_ENTRY iptc_delete_entry #define TC_DELETE_NUM_ENTRY iptc_delete_num_entry #define TC_FLUSH_ENTRIES iptc_flush_entries #define TC_ZERO_ENTRIES iptc_zero_entries #define TC_READ_COUNTER iptc_read_counter #define TC_ZERO_COUNTER iptc_zero_counter #define TC_SET_COUNTER iptc_set_counter #define TC_CREATE_CHAIN iptc_create_chain #define TC_GET_REFERENCES iptc_get_references #define TC_DELETE_CHAIN iptc_delete_chain #define TC_RENAME_CHAIN iptc_rename_chain #define TC_SET_POLICY iptc_set_policy #define TC_GET_RAW_SOCKET iptc_get_raw_socket #define TC_INIT iptc_init #define TC_FREE iptc_free #define TC_COMMIT iptc_commit #define TC_STRERROR iptc_strerror #define TC_NUM_RULES iptc_num_rules #define TC_GET_RULE iptc_get_rule #define TC_OPS iptc_ops #define TC_AF AF_INET #define TC_IPPROTO IPPROTO_IP #define SO_SET_REPLACE IPT_SO_SET_REPLACE #define SO_SET_ADD_COUNTERS IPT_SO_SET_ADD_COUNTERS #define SO_GET_INFO IPT_SO_GET_INFO #define SO_GET_ENTRIES IPT_SO_GET_ENTRIES #define SO_GET_VERSION IPT_SO_GET_VERSION #define STANDARD_TARGET XT_STANDARD_TARGET #define LABEL_RETURN IPTC_LABEL_RETURN #define LABEL_ACCEPT IPTC_LABEL_ACCEPT #define LABEL_DROP IPTC_LABEL_DROP #define LABEL_QUEUE IPTC_LABEL_QUEUE #define ALIGN XT_ALIGN #define RETURN XT_RETURN #include "libiptc.c" #define IP_PARTS_NATIVE(n) \ (unsigned int)((n)>>24)&0xFF, \ (unsigned int)((n)>>16)&0xFF, \ (unsigned int)((n)>>8)&0xFF, \ (unsigned int)((n)&0xFF) #define IP_PARTS(n) IP_PARTS_NATIVE(ntohl(n)) static int dump_entry(struct ipt_entry *e, struct xtc_handle *const handle) { size_t i; STRUCT_ENTRY_TARGET *t; printf("Entry %u (%lu):\n", iptcb_entry2index(handle, e), iptcb_entry2offset(handle, e)); printf("SRC IP: %u.%u.%u.%u/%u.%u.%u.%u\n", IP_PARTS(e->ip.src.s_addr),IP_PARTS(e->ip.smsk.s_addr)); printf("DST IP: %u.%u.%u.%u/%u.%u.%u.%u\n", IP_PARTS(e->ip.dst.s_addr),IP_PARTS(e->ip.dmsk.s_addr)); printf("Interface: `%s'/", e->ip.iniface); for (i = 0; i < IFNAMSIZ; i++) printf("%c", e->ip.iniface_mask[i] ? 'X' : '.'); printf("to `%s'/", e->ip.outiface); for (i = 0; i < IFNAMSIZ; i++) printf("%c", e->ip.outiface_mask[i] ? 'X' : '.'); printf("\nProtocol: %u\n", e->ip.proto); printf("Flags: %02X\n", e->ip.flags); printf("Invflags: %02X\n", e->ip.invflags); printf("Counters: %llu packets, %llu bytes\n", (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt); printf("Cache: %08X\n", e->nfcache); IPT_MATCH_ITERATE(e, print_match); t = GET_TARGET(e); printf("Target name: `%s' [%u]\n", t->u.user.name, t->u.target_size); if (strcmp(t->u.user.name, STANDARD_TARGET) == 0) { const unsigned char *data = t->data; int pos = *(const int *)data; if (pos < 0) printf("verdict=%s\n", pos == -NF_ACCEPT-1 ? "NF_ACCEPT" : pos == -NF_DROP-1 ? "NF_DROP" : pos == -NF_QUEUE-1 ? "NF_QUEUE" : pos == RETURN ? "RETURN" : "UNKNOWN"); else printf("verdict=%u\n", pos); } else if (strcmp(t->u.user.name, XT_ERROR_TARGET) == 0) printf("error=`%s'\n", t->data); printf("\n"); return 0; } static unsigned char * is_same(const STRUCT_ENTRY *a, const STRUCT_ENTRY *b, unsigned char *matchmask) { unsigned int i; unsigned char *mptr; /* Always compare head structures: ignore mask here. */ if (a->ip.src.s_addr != b->ip.src.s_addr || a->ip.dst.s_addr != b->ip.dst.s_addr || a->ip.smsk.s_addr != b->ip.smsk.s_addr || a->ip.dmsk.s_addr != b->ip.dmsk.s_addr || a->ip.proto != b->ip.proto || a->ip.flags != b->ip.flags || a->ip.invflags != b->ip.invflags) return NULL; for (i = 0; i < IFNAMSIZ; i++) { if (a->ip.iniface_mask[i] != b->ip.iniface_mask[i]) return NULL; if ((a->ip.iniface[i] & a->ip.iniface_mask[i]) != (b->ip.iniface[i] & b->ip.iniface_mask[i])) return NULL; if (a->ip.outiface_mask[i] != b->ip.outiface_mask[i]) return NULL; if ((a->ip.outiface[i] & a->ip.outiface_mask[i]) != (b->ip.outiface[i] & b->ip.outiface_mask[i])) return NULL; } if (a->target_offset != b->target_offset || a->next_offset != b->next_offset) return NULL; mptr = matchmask + sizeof(STRUCT_ENTRY); if (IPT_MATCH_ITERATE(a, match_different, a->elems, b->elems, &mptr)) return NULL; mptr += XT_ALIGN(sizeof(struct xt_entry_target)); return mptr; } #if 0 /***************************** DEBUGGING ********************************/ static inline int unconditional(const struct ipt_ip *ip) { unsigned int i; for (i = 0; i < sizeof(*ip)/sizeof(uint32_t); i++) if (((uint32_t *)ip)[i]) return 0; return 1; } static inline int check_match(const STRUCT_ENTRY_MATCH *m, unsigned int *off) { assert(m->u.match_size >= sizeof(STRUCT_ENTRY_MATCH)); assert(ALIGN(m->u.match_size) == m->u.match_size); (*off) += m->u.match_size; return 0; } static inline int check_entry(const STRUCT_ENTRY *e, unsigned int *i, unsigned int *off, unsigned int user_offset, int *was_return, struct xtc_handle *h) { unsigned int toff; STRUCT_STANDARD_TARGET *t; assert(e->target_offset >= sizeof(STRUCT_ENTRY)); assert(e->next_offset >= e->target_offset + sizeof(STRUCT_ENTRY_TARGET)); toff = sizeof(STRUCT_ENTRY); IPT_MATCH_ITERATE(e, check_match, &toff); assert(toff == e->target_offset); t = (STRUCT_STANDARD_TARGET *) GET_TARGET((STRUCT_ENTRY *)e); /* next_offset will have to be multiple of entry alignment. */ assert(e->next_offset == ALIGN(e->next_offset)); assert(e->target_offset == ALIGN(e->target_offset)); assert(t->target.u.target_size == ALIGN(t->target.u.target_size)); assert(!TC_IS_CHAIN(t->target.u.user.name, h)); if (strcmp(t->target.u.user.name, STANDARD_TARGET) == 0) { assert(t->target.u.target_size == ALIGN(sizeof(STRUCT_STANDARD_TARGET))); assert(t->verdict == -NF_DROP-1 || t->verdict == -NF_ACCEPT-1 || t->verdict == RETURN || t->verdict < (int)h->entries->size); if (t->verdict >= 0) { STRUCT_ENTRY *te = get_entry(h, t->verdict); int idx; idx = iptcb_entry2index(h, te); assert(strcmp(GET_TARGET(te)->u.user.name, XT_ERROR_TARGET) != 0); assert(te != e); /* Prior node must be error node, or this node. */ assert(t->verdict == iptcb_entry2offset(h, e)+e->next_offset || strcmp(GET_TARGET(index2entry(h, idx-1)) ->u.user.name, XT_ERROR_TARGET) == 0); } if (t->verdict == RETURN && unconditional(&e->ip) && e->target_offset == sizeof(*e)) *was_return = 1; else *was_return = 0; } else if (strcmp(t->target.u.user.name, XT_ERROR_TARGET) == 0) { assert(t->target.u.target_size == ALIGN(sizeof(struct ipt_error_target))); /* If this is in user area, previous must have been return */ if (*off > user_offset) assert(*was_return); *was_return = 0; } else *was_return = 0; if (*off == user_offset) assert(strcmp(t->target.u.user.name, XT_ERROR_TARGET) == 0); (*off) += e->next_offset; (*i)++; return 0; } #ifdef IPTC_DEBUG /* Do every conceivable sanity check on the handle */ static void do_check(struct xtc_handle *h, unsigned int line) { unsigned int i, n; unsigned int user_offset; /* Offset of first user chain */ int was_return; assert(h->changed == 0 || h->changed == 1); if (strcmp(h->info.name, "filter") == 0) { assert(h->info.valid_hooks == (1 << NF_IP_LOCAL_IN | 1 << NF_IP_FORWARD | 1 << NF_IP_LOCAL_OUT)); /* Hooks should be first three */ assert(h->info.hook_entry[NF_IP_LOCAL_IN] == 0); n = get_chain_end(h, 0); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP_FORWARD] == n); n = get_chain_end(h, n); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP_LOCAL_OUT] == n); user_offset = h->info.hook_entry[NF_IP_LOCAL_OUT]; } else if (strcmp(h->info.name, "nat") == 0) { assert((h->info.valid_hooks == (1 << NF_IP_PRE_ROUTING | 1 << NF_IP_POST_ROUTING | 1 << NF_IP_LOCAL_OUT)) || (h->info.valid_hooks == (1 << NF_IP_PRE_ROUTING | 1 << NF_IP_LOCAL_IN | 1 << NF_IP_POST_ROUTING | 1 << NF_IP_LOCAL_OUT))); assert(h->info.hook_entry[NF_IP_PRE_ROUTING] == 0); n = get_chain_end(h, 0); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP_POST_ROUTING] == n); n = get_chain_end(h, n); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP_LOCAL_OUT] == n); user_offset = h->info.hook_entry[NF_IP_LOCAL_OUT]; if (h->info.valid_hooks & (1 << NF_IP_LOCAL_IN)) { n = get_chain_end(h, n); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP_LOCAL_IN] == n); user_offset = h->info.hook_entry[NF_IP_LOCAL_IN]; } } else if (strcmp(h->info.name, "mangle") == 0) { /* This code is getting ugly because linux < 2.4.18-pre6 had * two mangle hooks, linux >= 2.4.18-pre6 has five mangle hooks * */ assert((h->info.valid_hooks == (1 << NF_IP_PRE_ROUTING | 1 << NF_IP_LOCAL_OUT)) || (h->info.valid_hooks == (1 << NF_IP_PRE_ROUTING | 1 << NF_IP_LOCAL_IN | 1 << NF_IP_FORWARD | 1 << NF_IP_LOCAL_OUT | 1 << NF_IP_POST_ROUTING))); /* Hooks should be first five */ assert(h->info.hook_entry[NF_IP_PRE_ROUTING] == 0); n = get_chain_end(h, 0); if (h->info.valid_hooks & (1 << NF_IP_LOCAL_IN)) { n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP_LOCAL_IN] == n); n = get_chain_end(h, n); } if (h->info.valid_hooks & (1 << NF_IP_FORWARD)) { n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP_FORWARD] == n); n = get_chain_end(h, n); } n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP_LOCAL_OUT] == n); user_offset = h->info.hook_entry[NF_IP_LOCAL_OUT]; if (h->info.valid_hooks & (1 << NF_IP_POST_ROUTING)) { n = get_chain_end(h, n); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP_POST_ROUTING] == n); user_offset = h->info.hook_entry[NF_IP_POST_ROUTING]; } } else if (strcmp(h->info.name, "raw") == 0) { assert(h->info.valid_hooks == (1 << NF_IP_PRE_ROUTING | 1 << NF_IP_LOCAL_OUT)); /* Hooks should be first three */ assert(h->info.hook_entry[NF_IP_PRE_ROUTING] == 0); n = get_chain_end(h, n); n += get_entry(h, n)->next_offset; assert(h->info.hook_entry[NF_IP_LOCAL_OUT] == n); user_offset = h->info.hook_entry[NF_IP_LOCAL_OUT]; } else { fprintf(stderr, "Unknown table `%s'\n", h->info.name); abort(); } /* User chain == end of last builtin + policy entry */ user_offset = get_chain_end(h, user_offset); user_offset += get_entry(h, user_offset)->next_offset; /* Overflows should be end of entry chains, and unconditional policy nodes. */ for (i = 0; i < NUMHOOKS; i++) { STRUCT_ENTRY *e; STRUCT_STANDARD_TARGET *t; if (!(h->info.valid_hooks & (1 << i))) continue; assert(h->info.underflow[i] == get_chain_end(h, h->info.hook_entry[i])); e = get_entry(h, get_chain_end(h, h->info.hook_entry[i])); assert(unconditional(&e->ip)); assert(e->target_offset == sizeof(*e)); t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e); assert(t->target.u.target_size == ALIGN(sizeof(*t))); assert(e->next_offset == sizeof(*e) + ALIGN(sizeof(*t))); assert(strcmp(t->target.u.user.name, STANDARD_TARGET)==0); assert(t->verdict == -NF_DROP-1 || t->verdict == -NF_ACCEPT-1); /* Hooks and underflows must be valid entries */ entry2index(h, get_entry(h, h->info.hook_entry[i])); entry2index(h, get_entry(h, h->info.underflow[i])); } assert(h->info.size >= h->info.num_entries * (sizeof(STRUCT_ENTRY) +sizeof(STRUCT_STANDARD_TARGET))); assert(h->entries.size >= (h->new_number * (sizeof(STRUCT_ENTRY) + sizeof(STRUCT_STANDARD_TARGET)))); assert(strcmp(h->info.name, h->entries.name) == 0); i = 0; n = 0; was_return = 0; /* Check all the entries. */ ENTRY_ITERATE(h->entries.entrytable, h->entries.size, check_entry, &i, &n, user_offset, &was_return, h); assert(i == h->new_number); assert(n == h->entries.size); /* Final entry must be error node */ assert(strcmp(GET_TARGET(index2entry(h, h->new_number-1)) ->u.user.name, ERROR_TARGET) == 0); } #endif /*IPTC_DEBUG*/ #endif
234
./android_firewall/external/iptables/libipq/libipq.c
/* * libipq.c * * IPQ userspace library. * * Please note that this library is still developmental, and there may * be some API changes. * * Author: James Morris <[email protected]> * * 07-11-2001 Modified by Fernando Anton to add support for IPv6. * * Copyright (c) 2000-2001 Netfilter Core Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <sys/types.h> #include <libipq/libipq.h> #include <netinet/in.h> #include <linux/netfilter.h> /**************************************************************************** * * Private interface * ****************************************************************************/ enum { IPQ_ERR_NONE = 0, IPQ_ERR_IMPL, IPQ_ERR_HANDLE, IPQ_ERR_SOCKET, IPQ_ERR_BIND, IPQ_ERR_BUFFER, IPQ_ERR_RECV, IPQ_ERR_NLEOF, IPQ_ERR_ADDRLEN, IPQ_ERR_STRUNC, IPQ_ERR_RTRUNC, IPQ_ERR_NLRECV, IPQ_ERR_SEND, IPQ_ERR_SUPP, IPQ_ERR_RECVBUF, IPQ_ERR_TIMEOUT, IPQ_ERR_PROTOCOL }; #define IPQ_MAXERR IPQ_ERR_PROTOCOL struct ipq_errmap_t { int errcode; char *message; } ipq_errmap[] = { { IPQ_ERR_NONE, "Unknown error" }, { IPQ_ERR_IMPL, "Implementation error" }, { IPQ_ERR_HANDLE, "Unable to create netlink handle" }, { IPQ_ERR_SOCKET, "Unable to create netlink socket" }, { IPQ_ERR_BIND, "Unable to bind netlink socket" }, { IPQ_ERR_BUFFER, "Unable to allocate buffer" }, { IPQ_ERR_RECV, "Failed to receive netlink message" }, { IPQ_ERR_NLEOF, "Received EOF on netlink socket" }, { IPQ_ERR_ADDRLEN, "Invalid peer address length" }, { IPQ_ERR_STRUNC, "Sent message truncated" }, { IPQ_ERR_RTRUNC, "Received message truncated" }, { IPQ_ERR_NLRECV, "Received error from netlink" }, { IPQ_ERR_SEND, "Failed to send netlink message" }, { IPQ_ERR_SUPP, "Operation not supported" }, { IPQ_ERR_RECVBUF, "Receive buffer size invalid" }, { IPQ_ERR_TIMEOUT, "Timeout"}, { IPQ_ERR_PROTOCOL, "Invalid protocol specified" } }; static int ipq_errno = IPQ_ERR_NONE; static ssize_t ipq_netlink_sendto(const struct ipq_handle *h, const void *msg, size_t len); static ssize_t ipq_netlink_recvfrom(const struct ipq_handle *h, unsigned char *buf, size_t len, int timeout); static ssize_t ipq_netlink_sendmsg(const struct ipq_handle *h, const struct msghdr *msg, unsigned int flags); static char *ipq_strerror(int errcode); static ssize_t ipq_netlink_sendto(const struct ipq_handle *h, const void *msg, size_t len) { int status = sendto(h->fd, msg, len, 0, (struct sockaddr *)&h->peer, sizeof(h->peer)); if (status < 0) ipq_errno = IPQ_ERR_SEND; return status; } static ssize_t ipq_netlink_sendmsg(const struct ipq_handle *h, const struct msghdr *msg, unsigned int flags) { int status = sendmsg(h->fd, msg, flags); if (status < 0) ipq_errno = IPQ_ERR_SEND; return status; } static ssize_t ipq_netlink_recvfrom(const struct ipq_handle *h, unsigned char *buf, size_t len, int timeout) { unsigned int addrlen; int status; struct nlmsghdr *nlh; if (len < sizeof(struct nlmsgerr)) { ipq_errno = IPQ_ERR_RECVBUF; return -1; } addrlen = sizeof(h->peer); if (timeout != 0) { int ret; struct timeval tv; fd_set read_fds; if (timeout < 0) { /* non-block non-timeout */ tv.tv_sec = 0; tv.tv_usec = 0; } else { tv.tv_sec = timeout / 1000000; tv.tv_usec = timeout % 1000000; } FD_ZERO(&read_fds); FD_SET(h->fd, &read_fds); ret = select(h->fd+1, &read_fds, NULL, NULL, &tv); if (ret < 0) { if (errno == EINTR) { return 0; } else { ipq_errno = IPQ_ERR_RECV; return -1; } } if (!FD_ISSET(h->fd, &read_fds)) { ipq_errno = IPQ_ERR_TIMEOUT; return 0; } } status = recvfrom(h->fd, buf, len, 0, (struct sockaddr *)&h->peer, &addrlen); if (status < 0) { ipq_errno = IPQ_ERR_RECV; return status; } if (addrlen != sizeof(h->peer)) { ipq_errno = IPQ_ERR_RECV; return -1; } if (h->peer.nl_pid != 0) { ipq_errno = IPQ_ERR_RECV; return -1; } if (status == 0) { ipq_errno = IPQ_ERR_NLEOF; return -1; } nlh = (struct nlmsghdr *)buf; if (nlh->nlmsg_flags & MSG_TRUNC || nlh->nlmsg_len > status) { ipq_errno = IPQ_ERR_RTRUNC; return -1; } return status; } static char *ipq_strerror(int errcode) { if (errcode < 0 || errcode > IPQ_MAXERR) errcode = IPQ_ERR_IMPL; return ipq_errmap[errcode].message; } /**************************************************************************** * * Public interface * ****************************************************************************/ /* * Create and initialise an ipq handle. */ struct ipq_handle *ipq_create_handle(uint32_t flags, uint32_t protocol) { int status; struct ipq_handle *h; h = (struct ipq_handle *)malloc(sizeof(struct ipq_handle)); if (h == NULL) { ipq_errno = IPQ_ERR_HANDLE; return NULL; } memset(h, 0, sizeof(struct ipq_handle)); if (protocol == NFPROTO_IPV4) h->fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_FIREWALL); else if (protocol == NFPROTO_IPV6) h->fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_IP6_FW); else { ipq_errno = IPQ_ERR_PROTOCOL; free(h); return NULL; } if (h->fd == -1) { ipq_errno = IPQ_ERR_SOCKET; free(h); return NULL; } memset(&h->local, 0, sizeof(struct sockaddr_nl)); h->local.nl_family = AF_NETLINK; h->local.nl_pid = getpid(); h->local.nl_groups = 0; status = bind(h->fd, (struct sockaddr *)&h->local, sizeof(h->local)); if (status == -1) { ipq_errno = IPQ_ERR_BIND; close(h->fd); free(h); return NULL; } memset(&h->peer, 0, sizeof(struct sockaddr_nl)); h->peer.nl_family = AF_NETLINK; h->peer.nl_pid = 0; h->peer.nl_groups = 0; return h; } /* * No error condition is checked here at this stage, but it may happen * if/when reliable messaging is implemented. */ int ipq_destroy_handle(struct ipq_handle *h) { if (h) { close(h->fd); free(h); } return 0; } int ipq_set_mode(const struct ipq_handle *h, uint8_t mode, size_t range) { struct { struct nlmsghdr nlh; ipq_peer_msg_t pm; } req; memset(&req, 0, sizeof(req)); req.nlh.nlmsg_len = NLMSG_LENGTH(sizeof(req)); req.nlh.nlmsg_flags = NLM_F_REQUEST; req.nlh.nlmsg_type = IPQM_MODE; req.nlh.nlmsg_pid = h->local.nl_pid; req.pm.msg.mode.value = mode; req.pm.msg.mode.range = range; return ipq_netlink_sendto(h, (void *)&req, req.nlh.nlmsg_len); } /* * timeout is in microseconds (1 second is 1000000 (1 million) microseconds) * */ ssize_t ipq_read(const struct ipq_handle *h, unsigned char *buf, size_t len, int timeout) { return ipq_netlink_recvfrom(h, buf, len, timeout); } int ipq_message_type(const unsigned char *buf) { return ((struct nlmsghdr*)buf)->nlmsg_type; } int ipq_get_msgerr(const unsigned char *buf) { struct nlmsghdr *h = (struct nlmsghdr *)buf; struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h); return -err->error; } ipq_packet_msg_t *ipq_get_packet(const unsigned char *buf) { return NLMSG_DATA((struct nlmsghdr *)(buf)); } int ipq_set_verdict(const struct ipq_handle *h, ipq_id_t id, unsigned int verdict, size_t data_len, unsigned char *buf) { unsigned char nvecs; size_t tlen; struct nlmsghdr nlh; ipq_peer_msg_t pm; struct iovec iov[3]; struct msghdr msg; memset(&nlh, 0, sizeof(nlh)); nlh.nlmsg_flags = NLM_F_REQUEST; nlh.nlmsg_type = IPQM_VERDICT; nlh.nlmsg_pid = h->local.nl_pid; memset(&pm, 0, sizeof(pm)); pm.msg.verdict.value = verdict; pm.msg.verdict.id = id; pm.msg.verdict.data_len = data_len; iov[0].iov_base = &nlh; iov[0].iov_len = sizeof(nlh); iov[1].iov_base = &pm; iov[1].iov_len = sizeof(pm); tlen = sizeof(nlh) + sizeof(pm); nvecs = 2; if (data_len && buf) { iov[2].iov_base = buf; iov[2].iov_len = data_len; tlen += data_len; nvecs++; } msg.msg_name = (void *)&h->peer; msg.msg_namelen = sizeof(h->peer); msg.msg_iov = iov; msg.msg_iovlen = nvecs; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_flags = 0; nlh.nlmsg_len = tlen; return ipq_netlink_sendmsg(h, &msg, 0); } /* Not implemented yet */ int ipq_ctl(const struct ipq_handle *h, int request, ...) { return 1; } char *ipq_errstr(void) { return ipq_strerror(ipq_errno); } void ipq_perror(const char *s) { if (s) fputs(s, stderr); else fputs("ERROR", stderr); if (ipq_errno) fprintf(stderr, ": %s", ipq_errstr()); if (errno) fprintf(stderr, ": %s", strerror(errno)); fputc('\n', stderr); }
235
./android_firewall/external/iptables/extensions/libxt_connlimit.c
#include <stdio.h> #include <netdb.h> #include <string.h> #include <xtables.h> #include <linux/netfilter/xt_connlimit.h> enum { O_UPTO = 0, O_ABOVE, O_MASK, O_SADDR, O_DADDR, F_UPTO = 1 << O_UPTO, F_ABOVE = 1 << O_ABOVE, F_MASK = 1 << O_MASK, F_SADDR = 1 << O_SADDR, F_DADDR = 1 << O_DADDR, }; static void connlimit_help(void) { printf( "connlimit match options:\n" " --connlimit-upto n match if the number of existing connections is 0..n\n" " --connlimit-above n match if the number of existing connections is >n\n" " --connlimit-mask n group hosts using prefix length (default: max len)\n" " --connlimit-saddr select source address for grouping\n" " --connlimit-daddr select destination addresses for grouping\n"); } #define s struct xt_connlimit_info static const struct xt_option_entry connlimit_opts[] = { {.name = "connlimit-upto", .id = O_UPTO, .excl = F_ABOVE, .type = XTTYPE_UINT32, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, limit)}, {.name = "connlimit-above", .id = O_ABOVE, .excl = F_UPTO, .type = XTTYPE_UINT32, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, limit)}, {.name = "connlimit-mask", .id = O_MASK, .type = XTTYPE_PLENMASK, .flags = XTOPT_PUT, XTOPT_POINTER(s, mask)}, {.name = "connlimit-saddr", .id = O_SADDR, .excl = F_DADDR, .type = XTTYPE_NONE}, {.name = "connlimit-daddr", .id = O_DADDR, .excl = F_SADDR, .type = XTTYPE_NONE}, XTOPT_TABLEEND, }; #undef s static void connlimit_init(struct xt_entry_match *match) { struct xt_connlimit_info *info = (void *)match->data; /* This will also initialize the v4 mask correctly */ memset(info->v6_mask, 0xFF, sizeof(info->v6_mask)); } static void connlimit_parse(struct xt_option_call *cb, uint8_t family) { struct xt_connlimit_info *info = cb->data; const unsigned int revision = (*cb->match)->u.user.revision; xtables_option_parse(cb); switch (cb->entry->id) { case O_ABOVE: if (cb->invert) info->flags |= XT_CONNLIMIT_INVERT; break; case O_UPTO: if (!cb->invert) info->flags |= XT_CONNLIMIT_INVERT; break; case O_SADDR: if (revision < 1) xtables_error(PARAMETER_PROBLEM, "xt_connlimit.0 does not support " "--connlimit-daddr"); info->flags &= ~XT_CONNLIMIT_DADDR; break; case O_DADDR: if (revision < 1) xtables_error(PARAMETER_PROBLEM, "xt_connlimit.0 does not support " "--connlimit-daddr"); info->flags |= XT_CONNLIMIT_DADDR; break; } } static void connlimit_parse4(struct xt_option_call *cb) { return connlimit_parse(cb, NFPROTO_IPV4); } static void connlimit_parse6(struct xt_option_call *cb) { return connlimit_parse(cb, NFPROTO_IPV6); } static void connlimit_check(struct xt_fcheck_call *cb) { if ((cb->xflags & (F_UPTO | F_ABOVE)) == 0) xtables_error(PARAMETER_PROBLEM, "You must specify \"--connlimit-above\" or " "\"--connlimit-upto\"."); } static unsigned int count_bits4(uint32_t mask) { unsigned int bits = 0; for (mask = ~ntohl(mask); mask != 0; mask >>= 1) ++bits; return 32 - bits; } static unsigned int count_bits6(const uint32_t *mask) { unsigned int bits = 0, i; uint32_t tmp[4]; for (i = 0; i < 4; ++i) for (tmp[i] = ~ntohl(mask[i]); tmp[i] != 0; tmp[i] >>= 1) ++bits; return 128 - bits; } static void connlimit_print4(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_connlimit_info *info = (const void *)match->data; printf(" #conn %s/%u %s %u", (info->flags & XT_CONNLIMIT_DADDR) ? "dst" : "src", count_bits4(info->v4_mask), (info->flags & XT_CONNLIMIT_INVERT) ? "<=" : ">", info->limit); } static void connlimit_print6(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_connlimit_info *info = (const void *)match->data; printf(" #conn %s/%u %s %u", (info->flags & XT_CONNLIMIT_DADDR) ? "dst" : "src", count_bits6(info->v6_mask), (info->flags & XT_CONNLIMIT_INVERT) ? "<=" : ">", info->limit); } static void connlimit_save4(const void *ip, const struct xt_entry_match *match) { const struct xt_connlimit_info *info = (const void *)match->data; const int revision = match->u.user.revision; if (info->flags & XT_CONNLIMIT_INVERT) printf(" --connlimit-upto %u", info->limit); else printf(" --connlimit-above %u", info->limit); printf(" --connlimit-mask %u", count_bits4(info->v4_mask)); if (revision >= 1) { if (info->flags & XT_CONNLIMIT_DADDR) printf(" --connlimit-daddr"); else printf(" --connlimit-saddr"); } } static void connlimit_save6(const void *ip, const struct xt_entry_match *match) { const struct xt_connlimit_info *info = (const void *)match->data; const int revision = match->u.user.revision; if (info->flags & XT_CONNLIMIT_INVERT) printf(" --connlimit-upto %u", info->limit); else printf(" --connlimit-above %u", info->limit); printf(" --connlimit-mask %u", count_bits6(info->v6_mask)); if (revision >= 1) { if (info->flags & XT_CONNLIMIT_DADDR) printf(" --connlimit-daddr"); else printf(" --connlimit-saddr"); } } static struct xtables_match connlimit_mt_reg[] = { { .name = "connlimit", .revision = 0, .family = NFPROTO_IPV4, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_connlimit_info)), .userspacesize = offsetof(struct xt_connlimit_info, data), .help = connlimit_help, .init = connlimit_init, .x6_parse = connlimit_parse4, .x6_fcheck = connlimit_check, .print = connlimit_print4, .save = connlimit_save4, .x6_options = connlimit_opts, }, { .name = "connlimit", .revision = 0, .family = NFPROTO_IPV6, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_connlimit_info)), .userspacesize = offsetof(struct xt_connlimit_info, data), .help = connlimit_help, .init = connlimit_init, .x6_parse = connlimit_parse6, .x6_fcheck = connlimit_check, .print = connlimit_print6, .save = connlimit_save6, .x6_options = connlimit_opts, }, { .name = "connlimit", .revision = 1, .family = NFPROTO_IPV4, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_connlimit_info)), .userspacesize = offsetof(struct xt_connlimit_info, data), .help = connlimit_help, .init = connlimit_init, .x6_parse = connlimit_parse4, .x6_fcheck = connlimit_check, .print = connlimit_print4, .save = connlimit_save4, .x6_options = connlimit_opts, }, { .name = "connlimit", .revision = 1, .family = NFPROTO_IPV6, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_connlimit_info)), .userspacesize = offsetof(struct xt_connlimit_info, data), .help = connlimit_help, .init = connlimit_init, .x6_parse = connlimit_parse6, .x6_fcheck = connlimit_check, .print = connlimit_print6, .save = connlimit_save6, .x6_options = connlimit_opts, }, }; void _init(void) { xtables_register_matches(connlimit_mt_reg, ARRAY_SIZE(connlimit_mt_reg)); }
236
./android_firewall/external/iptables/extensions/libxt_connmark.c
/* Shared library add-on to iptables to add connmark matching support. * * (C) 2002,2004 MARA Systems AB <http://www.marasystems.com> * by Henrik Nordstrom <[email protected]> * * Version 1.1 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_connmark.h> struct xt_connmark_info { unsigned long mark, mask; uint8_t invert; }; enum { O_MARK = 0, }; static void connmark_mt_help(void) { printf( "connmark match options:\n" "[!] --mark value[/mask] Match ctmark value with optional mask\n"); } static const struct xt_option_entry connmark_mt_opts[] = { {.name = "mark", .id = O_MARK, .type = XTTYPE_MARKMASK32, .flags = XTOPT_MAND | XTOPT_INVERT}, XTOPT_TABLEEND, }; static void connmark_mt_parse(struct xt_option_call *cb) { struct xt_connmark_mtinfo1 *info = cb->data; xtables_option_parse(cb); if (cb->invert) info->invert = true; info->mark = cb->val.mark; info->mask = cb->val.mask; } static void connmark_parse(struct xt_option_call *cb) { struct xt_connmark_info *markinfo = cb->data; xtables_option_parse(cb); markinfo->mark = cb->val.mark; markinfo->mask = cb->val.mask; if (cb->invert) markinfo->invert = 1; } static void print_mark(unsigned int mark, unsigned int mask) { if (mask != 0xffffffffU) printf(" 0x%x/0x%x", mark, mask); else printf(" 0x%x", mark); } static void connmark_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_connmark_info *info = (const void *)match->data; printf(" CONNMARK match "); if (info->invert) printf("!"); print_mark(info->mark, info->mask); } static void connmark_mt_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_connmark_mtinfo1 *info = (const void *)match->data; printf(" connmark match "); if (info->invert) printf("!"); print_mark(info->mark, info->mask); } static void connmark_save(const void *ip, const struct xt_entry_match *match) { const struct xt_connmark_info *info = (const void *)match->data; if (info->invert) printf(" !"); printf(" --mark"); print_mark(info->mark, info->mask); } static void connmark_mt_save(const void *ip, const struct xt_entry_match *match) { const struct xt_connmark_mtinfo1 *info = (const void *)match->data; if (info->invert) printf(" !"); printf(" --mark"); print_mark(info->mark, info->mask); } static struct xtables_match connmark_mt_reg[] = { { .family = NFPROTO_UNSPEC, .name = "connmark", .revision = 0, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_connmark_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_connmark_info)), .help = connmark_mt_help, .print = connmark_print, .save = connmark_save, .x6_parse = connmark_parse, .x6_options = connmark_mt_opts, }, { .version = XTABLES_VERSION, .name = "connmark", .revision = 1, .family = NFPROTO_UNSPEC, .size = XT_ALIGN(sizeof(struct xt_connmark_mtinfo1)), .userspacesize = XT_ALIGN(sizeof(struct xt_connmark_mtinfo1)), .help = connmark_mt_help, .print = connmark_mt_print, .save = connmark_mt_save, .x6_parse = connmark_mt_parse, .x6_options = connmark_mt_opts, }, }; void _init(void) { xtables_register_matches(connmark_mt_reg, ARRAY_SIZE(connmark_mt_reg)); }
237
./android_firewall/external/iptables/extensions/libxt_TCPOPTSTRIP.c
/* * Shared library add-on to iptables to add TCPOPTSTRIP target support. * Copyright (c) 2007 Sven Schnelle <[email protected]> * Copyright ┬⌐ CC Computer Consultants GmbH, 2007 * Jan Engelhardt <[email protected]> */ #include <stdio.h> #include <string.h> #include <xtables.h> #include <netinet/tcp.h> #include <linux/netfilter/xt_TCPOPTSTRIP.h> #ifndef TCPOPT_MD5SIG # define TCPOPT_MD5SIG 19 #endif enum { O_STRIP_OPTION = 0, }; struct tcp_optionmap { const char *name, *desc; const unsigned int option; }; static const struct xt_option_entry tcpoptstrip_tg_opts[] = { {.name = "strip-options", .id = O_STRIP_OPTION, .type = XTTYPE_STRING}, XTOPT_TABLEEND, }; static const struct tcp_optionmap tcp_optionmap[] = { {"wscale", "Window scale", TCPOPT_WINDOW}, {"mss", "Maximum Segment Size", TCPOPT_MAXSEG}, {"sack-permitted", "SACK permitted", TCPOPT_SACK_PERMITTED}, {"sack", "Selective ACK", TCPOPT_SACK}, {"timestamp", "Timestamp", TCPOPT_TIMESTAMP}, {"md5", "MD5 signature", TCPOPT_MD5SIG}, {NULL}, }; static void tcpoptstrip_tg_help(void) { const struct tcp_optionmap *w; printf( "TCPOPTSTRIP target options:\n" " --strip-options value strip specified TCP options denoted by value\n" " (separated by comma) from TCP header\n" " Instead of the numeric value, you can also use the following names:\n" ); for (w = tcp_optionmap; w->name != NULL; ++w) printf(" %-14s strip \"%s\" option\n", w->name, w->desc); } static void parse_list(struct xt_tcpoptstrip_target_info *info, const char *arg) { unsigned int option; char *p; int i; while (true) { p = strchr(arg, ','); if (p != NULL) *p = '\0'; option = 0; for (i = 0; tcp_optionmap[i].name != NULL; ++i) if (strcmp(tcp_optionmap[i].name, arg) == 0) { option = tcp_optionmap[i].option; break; } if (option == 0 && !xtables_strtoui(arg, NULL, &option, 0, UINT8_MAX)) xtables_error(PARAMETER_PROBLEM, "Bad TCP option value \"%s\"", arg); if (option < 2) xtables_error(PARAMETER_PROBLEM, "Option value may not be 0 or 1"); if (tcpoptstrip_test_bit(info->strip_bmap, option)) xtables_error(PARAMETER_PROBLEM, "Option \"%s\" already specified", arg); tcpoptstrip_set_bit(info->strip_bmap, option); if (p == NULL) break; arg = p + 1; } } static void tcpoptstrip_tg_parse(struct xt_option_call *cb) { struct xt_tcpoptstrip_target_info *info = cb->data; xtables_option_parse(cb); parse_list(info, cb->arg); } static void tcpoptstrip_print_list(const struct xt_tcpoptstrip_target_info *info, bool numeric) { unsigned int i, j; const char *name; bool first = true; for (i = 0; i < 256; ++i) { if (!tcpoptstrip_test_bit(info->strip_bmap, i)) continue; if (!first) printf(","); first = false; name = NULL; if (!numeric) for (j = 0; tcp_optionmap[j].name != NULL; ++j) if (tcp_optionmap[j].option == i) name = tcp_optionmap[j].name; if (name != NULL) printf("%s", name); else printf("%u", i); } } static void tcpoptstrip_tg_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_tcpoptstrip_target_info *info = (const void *)target->data; printf(" TCPOPTSTRIP options "); tcpoptstrip_print_list(info, numeric); } static void tcpoptstrip_tg_save(const void *ip, const struct xt_entry_target *target) { const struct xt_tcpoptstrip_target_info *info = (const void *)target->data; printf(" --strip-options "); tcpoptstrip_print_list(info, true); } static struct xtables_target tcpoptstrip_tg_reg = { .version = XTABLES_VERSION, .name = "TCPOPTSTRIP", .family = NFPROTO_UNSPEC, .size = XT_ALIGN(sizeof(struct xt_tcpoptstrip_target_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_tcpoptstrip_target_info)), .help = tcpoptstrip_tg_help, .print = tcpoptstrip_tg_print, .save = tcpoptstrip_tg_save, .x6_parse = tcpoptstrip_tg_parse, .x6_options = tcpoptstrip_tg_opts, }; void _init(void) { xtables_register_target(&tcpoptstrip_tg_reg); }
238
./android_firewall/external/iptables/extensions/libipt_MIRROR.c
/* Shared library add-on to iptables to add MIRROR target support. */ #include <xtables.h> static struct xtables_target mirror_tg_reg = { .name = "MIRROR", .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(0), .userspacesize = XT_ALIGN(0), }; void _init(void) { xtables_register_target(&mirror_tg_reg); }
239
./android_firewall/external/iptables/extensions/libxt_SET.c
/* Copyright (C) 2000-2002 Joakim Axelsson <[email protected]> * Patrick Schaaf <[email protected]> * Martin Josefsson <[email protected]> * Copyright (C) 2003-2010 Jozsef Kadlecsik <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ /* Shared library add-on to iptables to add IP set mangling target. */ #include <stdbool.h> #include <stdio.h> #include <netdb.h> #include <string.h> #include <stdlib.h> #include <getopt.h> #include <ctype.h> #include <xtables.h> #include <linux/netfilter/xt_set.h> #include "libxt_set.h" /* Revision 0 */ static void set_target_help_v0(void) { printf("SET target options:\n" " --add-set name flags\n" " --del-set name flags\n" " add/del src/dst IP/port from/to named sets,\n" " where flags are the comma separated list of\n" " 'src' and 'dst' specifications.\n"); } static const struct option set_target_opts_v0[] = { {.name = "add-set", .has_arg = true, .val = '1'}, {.name = "del-set", .has_arg = true, .val = '2'}, XT_GETOPT_TABLEEND, }; static void set_target_check_v0(unsigned int flags) { if (!flags) xtables_error(PARAMETER_PROBLEM, "You must specify either `--add-set' or `--del-set'"); } static void set_target_init_v0(struct xt_entry_target *target) { struct xt_set_info_target_v0 *info = (struct xt_set_info_target_v0 *) target->data; info->add_set.index = info->del_set.index = IPSET_INVALID_ID; } static void parse_target_v0(char **argv, int invert, unsigned int *flags, struct xt_set_info_v0 *info, const char *what) { if (info->u.flags[0]) xtables_error(PARAMETER_PROBLEM, "--%s can be specified only once", what); if (!argv[optind] || argv[optind][0] == '-' || argv[optind][0] == '!') xtables_error(PARAMETER_PROBLEM, "--%s requires two args.", what); if (strlen(optarg) > IPSET_MAXNAMELEN - 1) xtables_error(PARAMETER_PROBLEM, "setname `%s' too long, max %d characters.", optarg, IPSET_MAXNAMELEN - 1); get_set_byname(optarg, (struct xt_set_info *)info); parse_dirs_v0(argv[optind], info); optind++; *flags = 1; } static int set_target_parse_v0(int c, char **argv, int invert, unsigned int *flags, const void *entry, struct xt_entry_target **target) { struct xt_set_info_target_v0 *myinfo = (struct xt_set_info_target_v0 *) (*target)->data; switch (c) { case '1': /* --add-set <set> <flags> */ parse_target_v0(argv, invert, flags, &myinfo->add_set, "add-set"); break; case '2': /* --del-set <set>[:<flags>] <flags> */ parse_target_v0(argv, invert, flags, &myinfo->del_set, "del-set"); break; } return 1; } static void print_target_v0(const char *prefix, const struct xt_set_info_v0 *info) { int i; char setname[IPSET_MAXNAMELEN]; if (info->index == IPSET_INVALID_ID) return; get_set_byid(setname, info->index); printf(" %s %s", prefix, setname); for (i = 0; i < IPSET_DIM_MAX; i++) { if (!info->u.flags[i]) break; printf("%s%s", i == 0 ? " " : ",", info->u.flags[i] & IPSET_SRC ? "src" : "dst"); } } static void set_target_print_v0(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_set_info_target_v0 *info = (const void *)target->data; print_target_v0("add-set", &info->add_set); print_target_v0("del-set", &info->del_set); } static void set_target_save_v0(const void *ip, const struct xt_entry_target *target) { const struct xt_set_info_target_v0 *info = (const void *)target->data; print_target_v0("--add-set", &info->add_set); print_target_v0("--del-set", &info->del_set); } /* Revision 1 */ static void set_target_init_v1(struct xt_entry_target *target) { struct xt_set_info_target_v1 *info = (struct xt_set_info_target_v1 *) target->data; info->add_set.index = info->del_set.index = IPSET_INVALID_ID; } #define SET_TARGET_ADD 0x1 #define SET_TARGET_DEL 0x2 #define SET_TARGET_EXIST 0x4 #define SET_TARGET_TIMEOUT 0x8 static void parse_target(char **argv, int invert, struct xt_set_info *info, const char *what) { if (info->dim) xtables_error(PARAMETER_PROBLEM, "--%s can be specified only once", what); if (!argv[optind] || argv[optind][0] == '-' || argv[optind][0] == '!') xtables_error(PARAMETER_PROBLEM, "--%s requires two args.", what); if (strlen(optarg) > IPSET_MAXNAMELEN - 1) xtables_error(PARAMETER_PROBLEM, "setname `%s' too long, max %d characters.", optarg, IPSET_MAXNAMELEN - 1); get_set_byname(optarg, info); parse_dirs(argv[optind], info); optind++; } static int set_target_parse_v1(int c, char **argv, int invert, unsigned int *flags, const void *entry, struct xt_entry_target **target) { struct xt_set_info_target_v1 *myinfo = (struct xt_set_info_target_v1 *) (*target)->data; switch (c) { case '1': /* --add-set <set> <flags> */ parse_target(argv, invert, &myinfo->add_set, "add-set"); *flags |= SET_TARGET_ADD; break; case '2': /* --del-set <set>[:<flags>] <flags> */ parse_target(argv, invert, &myinfo->del_set, "del-set"); *flags |= SET_TARGET_DEL; break; } return 1; } static void print_target(const char *prefix, const struct xt_set_info *info) { int i; char setname[IPSET_MAXNAMELEN]; if (info->index == IPSET_INVALID_ID) return; get_set_byid(setname, info->index); printf(" %s %s", prefix, setname); for (i = 1; i <= info->dim; i++) { printf("%s%s", i == 1 ? " " : ",", info->flags & (1 << i) ? "src" : "dst"); } } static void set_target_print_v1(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_set_info_target_v1 *info = (const void *)target->data; print_target("add-set", &info->add_set); print_target("del-set", &info->del_set); } static void set_target_save_v1(const void *ip, const struct xt_entry_target *target) { const struct xt_set_info_target_v1 *info = (const void *)target->data; print_target("--add-set", &info->add_set); print_target("--del-set", &info->del_set); } /* Revision 2 */ static void set_target_help_v2(void) { printf("SET target options:\n" " --add-set name flags [--exist] [--timeout n]\n" " --del-set name flags\n" " add/del src/dst IP/port from/to named sets,\n" " where flags are the comma separated list of\n" " 'src' and 'dst' specifications.\n"); } static const struct option set_target_opts_v2[] = { {.name = "add-set", .has_arg = true, .val = '1'}, {.name = "del-set", .has_arg = true, .val = '2'}, {.name = "exist", .has_arg = false, .val = '3'}, {.name = "timeout", .has_arg = true, .val = '4'}, XT_GETOPT_TABLEEND, }; static void set_target_check_v2(unsigned int flags) { if (!(flags & (SET_TARGET_ADD|SET_TARGET_DEL))) xtables_error(PARAMETER_PROBLEM, "You must specify either `--add-set' or `--del-set'"); if (!(flags & SET_TARGET_ADD)) { if (flags & SET_TARGET_EXIST) xtables_error(PARAMETER_PROBLEM, "Flag `--exist' can be used with `--add-set' only"); if (flags & SET_TARGET_TIMEOUT) xtables_error(PARAMETER_PROBLEM, "Option `--timeout' can be used with `--add-set' only"); } } static void set_target_init_v2(struct xt_entry_target *target) { struct xt_set_info_target_v2 *info = (struct xt_set_info_target_v2 *) target->data; info->add_set.index = info->del_set.index = IPSET_INVALID_ID; info->timeout = UINT32_MAX; } static int set_target_parse_v2(int c, char **argv, int invert, unsigned int *flags, const void *entry, struct xt_entry_target **target) { struct xt_set_info_target_v2 *myinfo = (struct xt_set_info_target_v2 *) (*target)->data; unsigned int timeout; switch (c) { case '1': /* --add-set <set> <flags> */ parse_target(argv, invert, &myinfo->add_set, "add-set"); *flags |= SET_TARGET_ADD; break; case '2': /* --del-set <set>[:<flags>] <flags> */ parse_target(argv, invert, &myinfo->del_set, "del-set"); *flags |= SET_TARGET_DEL; break; case '3': myinfo->flags |= IPSET_FLAG_EXIST; *flags |= SET_TARGET_EXIST; break; case '4': if (!xtables_strtoui(optarg, NULL, &timeout, 0, UINT32_MAX - 1)) xtables_error(PARAMETER_PROBLEM, "Invalid value for option --timeout " "or out of range 0-%u", UINT32_MAX - 1); myinfo->timeout = timeout; *flags |= SET_TARGET_TIMEOUT; break; } return 1; } static void set_target_print_v2(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_set_info_target_v2 *info = (const void *)target->data; print_target("add-set", &info->add_set); if (info->flags & IPSET_FLAG_EXIST) printf(" exist"); if (info->timeout != UINT32_MAX) printf(" timeout %u", info->timeout); print_target("del-set", &info->del_set); } static void set_target_save_v2(const void *ip, const struct xt_entry_target *target) { const struct xt_set_info_target_v2 *info = (const void *)target->data; print_target("--add-set", &info->add_set); if (info->flags & IPSET_FLAG_EXIST) printf(" --exist"); if (info->timeout != UINT32_MAX) printf(" --timeout %u", info->timeout); print_target("--del-set", &info->del_set); } static struct xtables_target set_tg_reg[] = { { .name = "SET", .revision = 0, .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct xt_set_info_target_v0)), .userspacesize = XT_ALIGN(sizeof(struct xt_set_info_target_v0)), .help = set_target_help_v0, .init = set_target_init_v0, .parse = set_target_parse_v0, .final_check = set_target_check_v0, .print = set_target_print_v0, .save = set_target_save_v0, .extra_opts = set_target_opts_v0, }, { .name = "SET", .revision = 1, .version = XTABLES_VERSION, .family = NFPROTO_UNSPEC, .size = XT_ALIGN(sizeof(struct xt_set_info_target_v1)), .userspacesize = XT_ALIGN(sizeof(struct xt_set_info_target_v1)), .help = set_target_help_v0, .init = set_target_init_v1, .parse = set_target_parse_v1, .final_check = set_target_check_v0, .print = set_target_print_v1, .save = set_target_save_v1, .extra_opts = set_target_opts_v0, }, { .name = "SET", .revision = 2, .version = XTABLES_VERSION, .family = NFPROTO_UNSPEC, .size = XT_ALIGN(sizeof(struct xt_set_info_target_v2)), .userspacesize = XT_ALIGN(sizeof(struct xt_set_info_target_v2)), .help = set_target_help_v2, .init = set_target_init_v2, .parse = set_target_parse_v2, .final_check = set_target_check_v2, .print = set_target_print_v2, .save = set_target_save_v2, .extra_opts = set_target_opts_v2, }, }; void _init(void) { xtables_register_targets(set_tg_reg, ARRAY_SIZE(set_tg_reg)); }
240
./android_firewall/external/iptables/extensions/libxt_hashlimit.c
/* ip6tables match extension for limiting packets per destination * * (C) 2003-2004 by Harald Welte <[email protected]> * * Development of this code was funded by Astaro AG, http://www.astaro.com/ * * Based on ipt_limit.c by * J├⌐r├┤me de Vivie <[email protected]> * Herv├⌐ Eychenne <[email protected]> * * Error corections by [email protected] (22.01.2005) */ #define _BSD_SOURCE 1 #define _ISOC99_SOURCE 1 #include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <xtables.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter/xt_hashlimit.h> #define XT_HASHLIMIT_BURST 5 #define XT_HASHLIMIT_BURST_MAX 10000 #define XT_HASHLIMIT_BYTE_EXPIRE 15 #define XT_HASHLIMIT_BYTE_EXPIRE_BURST 60 /* miliseconds */ #define XT_HASHLIMIT_GCINTERVAL 1000 struct hashlimit_mt_udata { uint32_t mult; }; static void hashlimit_help(void) { printf( "hashlimit match options:\n" "--hashlimit <avg> max average match rate\n" " [Packets per second unless followed by \n" " /sec /minute /hour /day postfixes]\n" "--hashlimit-mode <mode> mode is a comma-separated list of\n" " dstip,srcip,dstport,srcport\n" "--hashlimit-name <name> name for /proc/net/ipt_hashlimit/\n" "[--hashlimit-burst <num>] number to match in a burst, default %u\n" "[--hashlimit-htable-size <num>] number of hashtable buckets\n" "[--hashlimit-htable-max <num>] number of hashtable entries\n" "[--hashlimit-htable-gcinterval] interval between garbage collection runs\n" "[--hashlimit-htable-expire] after which time are idle entries expired?\n", XT_HASHLIMIT_BURST); } enum { O_UPTO = 0, O_ABOVE, O_LIMIT, O_MODE, O_SRCMASK, O_DSTMASK, O_NAME, O_BURST, O_HTABLE_SIZE, O_HTABLE_MAX, O_HTABLE_GCINT, O_HTABLE_EXPIRE, F_BURST = 1 << O_BURST, F_UPTO = 1 << O_UPTO, F_ABOVE = 1 << O_ABOVE, F_HTABLE_EXPIRE = 1 << O_HTABLE_EXPIRE, }; static void hashlimit_mt_help(void) { printf( "hashlimit match options:\n" " --hashlimit-upto <avg> max average match rate\n" " [Packets per second unless followed by \n" " /sec /minute /hour /day postfixes]\n" " --hashlimit-above <avg> min average match rate\n" " --hashlimit-mode <mode> mode is a comma-separated list of\n" " dstip,srcip,dstport,srcport (or none)\n" " --hashlimit-srcmask <length> source address grouping prefix length\n" " --hashlimit-dstmask <length> destination address grouping prefix length\n" " --hashlimit-name <name> name for /proc/net/ipt_hashlimit\n" " --hashlimit-burst <num> number to match in a burst, default %u\n" " --hashlimit-htable-size <num> number of hashtable buckets\n" " --hashlimit-htable-max <num> number of hashtable entries\n" " --hashlimit-htable-gcinterval interval between garbage collection runs\n" " --hashlimit-htable-expire after which time are idle entries expired?\n" "\n", XT_HASHLIMIT_BURST); } #define s struct xt_hashlimit_info static const struct xt_option_entry hashlimit_opts[] = { {.name = "hashlimit", .id = O_UPTO, .excl = F_ABOVE, .type = XTTYPE_STRING}, {.name = "hashlimit-burst", .id = O_BURST, .type = XTTYPE_UINT32, .min = 1, .max = XT_HASHLIMIT_BURST_MAX, .flags = XTOPT_PUT, XTOPT_POINTER(s, cfg.burst)}, {.name = "hashlimit-htable-size", .id = O_HTABLE_SIZE, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, cfg.size)}, {.name = "hashlimit-htable-max", .id = O_HTABLE_MAX, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, cfg.max)}, {.name = "hashlimit-htable-gcinterval", .id = O_HTABLE_GCINT, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, cfg.gc_interval)}, {.name = "hashlimit-htable-expire", .id = O_HTABLE_EXPIRE, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, cfg.expire)}, {.name = "hashlimit-mode", .id = O_MODE, .type = XTTYPE_STRING, .flags = XTOPT_MAND}, {.name = "hashlimit-name", .id = O_NAME, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_PUT, XTOPT_POINTER(s, name), .min = 1}, XTOPT_TABLEEND, }; #undef s #define s struct xt_hashlimit_mtinfo1 static const struct xt_option_entry hashlimit_mt_opts[] = { {.name = "hashlimit-upto", .id = O_UPTO, .excl = F_ABOVE, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, {.name = "hashlimit-above", .id = O_ABOVE, .excl = F_UPTO, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, {.name = "hashlimit", .id = O_UPTO, .excl = F_ABOVE, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, /* old name */ {.name = "hashlimit-srcmask", .id = O_SRCMASK, .type = XTTYPE_PLEN}, {.name = "hashlimit-dstmask", .id = O_DSTMASK, .type = XTTYPE_PLEN}, {.name = "hashlimit-burst", .id = O_BURST, .type = XTTYPE_STRING}, {.name = "hashlimit-htable-size", .id = O_HTABLE_SIZE, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, cfg.size)}, {.name = "hashlimit-htable-max", .id = O_HTABLE_MAX, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, cfg.max)}, {.name = "hashlimit-htable-gcinterval", .id = O_HTABLE_GCINT, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, cfg.gc_interval)}, {.name = "hashlimit-htable-expire", .id = O_HTABLE_EXPIRE, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, cfg.expire)}, {.name = "hashlimit-mode", .id = O_MODE, .type = XTTYPE_STRING}, {.name = "hashlimit-name", .id = O_NAME, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_PUT, XTOPT_POINTER(s, name), .min = 1}, XTOPT_TABLEEND, }; #undef s static uint32_t cost_to_bytes(uint32_t cost) { uint32_t r; r = cost ? UINT32_MAX / cost : UINT32_MAX; r = (r - 1) << XT_HASHLIMIT_BYTE_SHIFT; return r; } static uint64_t bytes_to_cost(uint32_t bytes) { uint32_t r = bytes >> XT_HASHLIMIT_BYTE_SHIFT; return UINT32_MAX / (r+1); } static uint32_t get_factor(int chr) { switch (chr) { case 'm': return 1024 * 1024; case 'k': return 1024; } return 1; } static void burst_error(void) { xtables_error(PARAMETER_PROBLEM, "bad value for option " "\"--hashlimit-burst\", or out of range (1-%u).", XT_HASHLIMIT_BURST_MAX); } static uint32_t parse_burst(const char *burst, struct xt_hashlimit_mtinfo1 *info) { uintmax_t v; char *end; if (!xtables_strtoul(burst, &end, &v, 1, UINT32_MAX) || (*end == 0 && v > XT_HASHLIMIT_BURST_MAX)) burst_error(); v *= get_factor(*end); if (v > UINT32_MAX) xtables_error(PARAMETER_PROBLEM, "bad value for option " "\"--hashlimit-burst\", value \"%s\" too large " "(max %umb).", burst, UINT32_MAX/1024/1024); return v; } static bool parse_bytes(const char *rate, uint32_t *val, struct hashlimit_mt_udata *ud) { unsigned int factor = 1; uint64_t tmp; int r; const char *mode = strstr(rate, "b/s"); if (!mode || mode == rate) return false; mode--; r = atoi(rate); if (r == 0) return false; factor = get_factor(*mode); tmp = (uint64_t) r * factor; if (tmp > UINT32_MAX) xtables_error(PARAMETER_PROBLEM, "Rate value too large \"%llu\" (max %u)\n", (unsigned long long)tmp, UINT32_MAX); *val = bytes_to_cost(tmp); if (*val == 0) xtables_error(PARAMETER_PROBLEM, "Rate too high \"%s\"\n", rate); ud->mult = XT_HASHLIMIT_BYTE_EXPIRE; return true; } static int parse_rate(const char *rate, uint32_t *val, struct hashlimit_mt_udata *ud) { const char *delim; uint32_t r; ud->mult = 1; /* Seconds by default. */ delim = strchr(rate, '/'); if (delim) { if (strlen(delim+1) == 0) return 0; if (strncasecmp(delim+1, "second", strlen(delim+1)) == 0) ud->mult = 1; else if (strncasecmp(delim+1, "minute", strlen(delim+1)) == 0) ud->mult = 60; else if (strncasecmp(delim+1, "hour", strlen(delim+1)) == 0) ud->mult = 60*60; else if (strncasecmp(delim+1, "day", strlen(delim+1)) == 0) ud->mult = 24*60*60; else return 0; } r = atoi(rate); if (!r) return 0; *val = XT_HASHLIMIT_SCALE * ud->mult / r; if (*val == 0) /* * The rate maps to infinity. (1/day is the minimum they can * specify, so we are ok at that end). */ xtables_error(PARAMETER_PROBLEM, "Rate too fast \"%s\"\n", rate); return 1; } static void hashlimit_init(struct xt_entry_match *m) { struct xt_hashlimit_info *r = (struct xt_hashlimit_info *)m->data; r->cfg.burst = XT_HASHLIMIT_BURST; r->cfg.gc_interval = XT_HASHLIMIT_GCINTERVAL; } static void hashlimit_mt4_init(struct xt_entry_match *match) { struct xt_hashlimit_mtinfo1 *info = (void *)match->data; info->cfg.mode = 0; info->cfg.burst = XT_HASHLIMIT_BURST; info->cfg.gc_interval = XT_HASHLIMIT_GCINTERVAL; info->cfg.srcmask = 32; info->cfg.dstmask = 32; } static void hashlimit_mt6_init(struct xt_entry_match *match) { struct xt_hashlimit_mtinfo1 *info = (void *)match->data; info->cfg.mode = 0; info->cfg.burst = XT_HASHLIMIT_BURST; info->cfg.gc_interval = XT_HASHLIMIT_GCINTERVAL; info->cfg.srcmask = 128; info->cfg.dstmask = 128; } /* Parse a 'mode' parameter into the required bitmask */ static int parse_mode(uint32_t *mode, const char *option_arg) { char *tok; char *arg = strdup(option_arg); if (!arg) return -1; for (tok = strtok(arg, ",|"); tok; tok = strtok(NULL, ",|")) { if (!strcmp(tok, "dstip")) *mode |= XT_HASHLIMIT_HASH_DIP; else if (!strcmp(tok, "srcip")) *mode |= XT_HASHLIMIT_HASH_SIP; else if (!strcmp(tok, "srcport")) *mode |= XT_HASHLIMIT_HASH_SPT; else if (!strcmp(tok, "dstport")) *mode |= XT_HASHLIMIT_HASH_DPT; else { free(arg); return -1; } } free(arg); return 0; } static void hashlimit_parse(struct xt_option_call *cb) { struct xt_hashlimit_info *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_UPTO: if (!parse_rate(cb->arg, &info->cfg.avg, cb->udata)) xtables_param_act(XTF_BAD_VALUE, "hashlimit", "--hashlimit-upto", cb->arg); break; case O_MODE: if (parse_mode(&info->cfg.mode, cb->arg) < 0) xtables_param_act(XTF_BAD_VALUE, "hashlimit", "--hashlimit-mode", cb->arg); break; } } static void hashlimit_mt_parse(struct xt_option_call *cb) { struct xt_hashlimit_mtinfo1 *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_BURST: info->cfg.burst = parse_burst(cb->arg, info); break; case O_UPTO: if (cb->invert) info->cfg.mode |= XT_HASHLIMIT_INVERT; if (parse_bytes(cb->arg, &info->cfg.avg, cb->udata)) info->cfg.mode |= XT_HASHLIMIT_BYTES; else if (!parse_rate(cb->arg, &info->cfg.avg, cb->udata)) xtables_param_act(XTF_BAD_VALUE, "hashlimit", "--hashlimit-upto", cb->arg); break; case O_ABOVE: if (!cb->invert) info->cfg.mode |= XT_HASHLIMIT_INVERT; if (parse_bytes(cb->arg, &info->cfg.avg, cb->udata)) info->cfg.mode |= XT_HASHLIMIT_BYTES; else if (!parse_rate(cb->arg, &info->cfg.avg, cb->udata)) xtables_param_act(XTF_BAD_VALUE, "hashlimit", "--hashlimit-above", cb->arg); break; case O_MODE: if (parse_mode(&info->cfg.mode, cb->arg) < 0) xtables_param_act(XTF_BAD_VALUE, "hashlimit", "--hashlimit-mode", cb->arg); break; case O_SRCMASK: info->cfg.srcmask = cb->val.hlen; break; case O_DSTMASK: info->cfg.dstmask = cb->val.hlen; break; } } static void hashlimit_check(struct xt_fcheck_call *cb) { const struct hashlimit_mt_udata *udata = cb->udata; struct xt_hashlimit_info *info = cb->data; if (!(cb->xflags & (F_UPTO | F_ABOVE))) xtables_error(PARAMETER_PROBLEM, "You have to specify --hashlimit"); if (!(cb->xflags & F_HTABLE_EXPIRE)) info->cfg.expire = udata->mult * 1000; /* from s to msec */ } static void hashlimit_mt_check(struct xt_fcheck_call *cb) { const struct hashlimit_mt_udata *udata = cb->udata; struct xt_hashlimit_mtinfo1 *info = cb->data; if (!(cb->xflags & (F_UPTO | F_ABOVE))) xtables_error(PARAMETER_PROBLEM, "You have to specify --hashlimit"); if (!(cb->xflags & F_HTABLE_EXPIRE)) info->cfg.expire = udata->mult * 1000; /* from s to msec */ if (info->cfg.mode & XT_HASHLIMIT_BYTES) { uint32_t burst = 0; if (cb->xflags & F_BURST) { if (info->cfg.burst < cost_to_bytes(info->cfg.avg)) xtables_error(PARAMETER_PROBLEM, "burst cannot be smaller than %ub", cost_to_bytes(info->cfg.avg)); burst = info->cfg.burst; burst /= cost_to_bytes(info->cfg.avg); if (info->cfg.burst % cost_to_bytes(info->cfg.avg)) burst++; if (!(cb->xflags & F_HTABLE_EXPIRE)) info->cfg.expire = XT_HASHLIMIT_BYTE_EXPIRE_BURST * 1000; } info->cfg.burst = burst; } else if (info->cfg.burst > XT_HASHLIMIT_BURST_MAX) burst_error(); } static const struct rates { const char *name; uint32_t mult; } rates[] = { { "day", XT_HASHLIMIT_SCALE*24*60*60 }, { "hour", XT_HASHLIMIT_SCALE*60*60 }, { "min", XT_HASHLIMIT_SCALE*60 }, { "sec", XT_HASHLIMIT_SCALE } }; static uint32_t print_rate(uint32_t period) { unsigned int i; if (period == 0) { printf(" %f", INFINITY); return 0; } for (i = 1; i < ARRAY_SIZE(rates); ++i) if (period > rates[i].mult || rates[i].mult/period < rates[i].mult%period) break; printf(" %u/%s", rates[i-1].mult / period, rates[i-1].name); /* return in msec */ return rates[i-1].mult / XT_HASHLIMIT_SCALE * 1000; } static const struct { const char *name; uint32_t thresh; } units[] = { { "m", 1024 * 1024 }, { "k", 1024 }, { "", 1 }, }; static uint32_t print_bytes(uint32_t avg, uint32_t burst, const char *prefix) { unsigned int i; unsigned long long r; r = cost_to_bytes(avg); for (i = 0; i < ARRAY_SIZE(units) -1; ++i) if (r >= units[i].thresh && bytes_to_cost(r & ~(units[i].thresh - 1)) == avg) break; printf(" %llu%sb/s", r/units[i].thresh, units[i].name); if (burst == 0) return XT_HASHLIMIT_BYTE_EXPIRE * 1000; r *= burst; printf(" %s", prefix); for (i = 0; i < ARRAY_SIZE(units) -1; ++i) if (r >= units[i].thresh) break; printf("burst %llu%sb", r / units[i].thresh, units[i].name); return XT_HASHLIMIT_BYTE_EXPIRE_BURST * 1000; } static void print_mode(unsigned int mode, char separator) { bool prevmode = false; putchar(' '); if (mode & XT_HASHLIMIT_HASH_SIP) { fputs("srcip", stdout); prevmode = 1; } if (mode & XT_HASHLIMIT_HASH_SPT) { if (prevmode) putchar(separator); fputs("srcport", stdout); prevmode = 1; } if (mode & XT_HASHLIMIT_HASH_DIP) { if (prevmode) putchar(separator); fputs("dstip", stdout); prevmode = 1; } if (mode & XT_HASHLIMIT_HASH_DPT) { if (prevmode) putchar(separator); fputs("dstport", stdout); } } static void hashlimit_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_hashlimit_info *r = (const void *)match->data; uint32_t quantum; fputs(" limit: avg", stdout); quantum = print_rate(r->cfg.avg); printf(" burst %u", r->cfg.burst); fputs(" mode", stdout); print_mode(r->cfg.mode, '-'); if (r->cfg.size) printf(" htable-size %u", r->cfg.size); if (r->cfg.max) printf(" htable-max %u", r->cfg.max); if (r->cfg.gc_interval != XT_HASHLIMIT_GCINTERVAL) printf(" htable-gcinterval %u", r->cfg.gc_interval); if (r->cfg.expire != quantum) printf(" htable-expire %u", r->cfg.expire); } static void hashlimit_mt_print(const struct xt_hashlimit_mtinfo1 *info, unsigned int dmask) { uint32_t quantum; if (info->cfg.mode & XT_HASHLIMIT_INVERT) fputs(" limit: above", stdout); else fputs(" limit: up to", stdout); if (info->cfg.mode & XT_HASHLIMIT_BYTES) { quantum = print_bytes(info->cfg.avg, info->cfg.burst, ""); } else { quantum = print_rate(info->cfg.avg); printf(" burst %u", info->cfg.burst); } if (info->cfg.mode & (XT_HASHLIMIT_HASH_SIP | XT_HASHLIMIT_HASH_SPT | XT_HASHLIMIT_HASH_DIP | XT_HASHLIMIT_HASH_DPT)) { fputs(" mode", stdout); print_mode(info->cfg.mode, '-'); } if (info->cfg.size != 0) printf(" htable-size %u", info->cfg.size); if (info->cfg.max != 0) printf(" htable-max %u", info->cfg.max); if (info->cfg.gc_interval != XT_HASHLIMIT_GCINTERVAL) printf(" htable-gcinterval %u", info->cfg.gc_interval); if (info->cfg.expire != quantum) printf(" htable-expire %u", info->cfg.expire); if (info->cfg.srcmask != dmask) printf(" srcmask %u", info->cfg.srcmask); if (info->cfg.dstmask != dmask) printf(" dstmask %u", info->cfg.dstmask); } static void hashlimit_mt4_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_hashlimit_mtinfo1 *info = (const void *)match->data; hashlimit_mt_print(info, 32); } static void hashlimit_mt6_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_hashlimit_mtinfo1 *info = (const void *)match->data; hashlimit_mt_print(info, 128); } static void hashlimit_save(const void *ip, const struct xt_entry_match *match) { const struct xt_hashlimit_info *r = (const void *)match->data; uint32_t quantum; fputs(" --hashlimit", stdout); quantum = print_rate(r->cfg.avg); printf(" --hashlimit-burst %u", r->cfg.burst); fputs(" --hashlimit-mode", stdout); print_mode(r->cfg.mode, ','); printf(" --hashlimit-name %s", r->name); if (r->cfg.size) printf(" --hashlimit-htable-size %u", r->cfg.size); if (r->cfg.max) printf(" --hashlimit-htable-max %u", r->cfg.max); if (r->cfg.gc_interval != XT_HASHLIMIT_GCINTERVAL) printf(" --hashlimit-htable-gcinterval %u", r->cfg.gc_interval); if (r->cfg.expire != quantum) printf(" --hashlimit-htable-expire %u", r->cfg.expire); } static void hashlimit_mt_save(const struct xt_hashlimit_mtinfo1 *info, unsigned int dmask) { uint32_t quantum; if (info->cfg.mode & XT_HASHLIMIT_INVERT) fputs(" --hashlimit-above", stdout); else fputs(" --hashlimit-upto", stdout); if (info->cfg.mode & XT_HASHLIMIT_BYTES) { quantum = print_bytes(info->cfg.avg, info->cfg.burst, "--hashlimit-"); } else { quantum = print_rate(info->cfg.avg); printf(" --hashlimit-burst %u", info->cfg.burst); } if (info->cfg.mode & (XT_HASHLIMIT_HASH_SIP | XT_HASHLIMIT_HASH_SPT | XT_HASHLIMIT_HASH_DIP | XT_HASHLIMIT_HASH_DPT)) { fputs(" --hashlimit-mode", stdout); print_mode(info->cfg.mode, ','); } printf(" --hashlimit-name %s", info->name); if (info->cfg.size != 0) printf(" --hashlimit-htable-size %u", info->cfg.size); if (info->cfg.max != 0) printf(" --hashlimit-htable-max %u", info->cfg.max); if (info->cfg.gc_interval != XT_HASHLIMIT_GCINTERVAL) printf(" --hashlimit-htable-gcinterval %u", info->cfg.gc_interval); if (info->cfg.expire != quantum) printf(" --hashlimit-htable-expire %u", info->cfg.expire); if (info->cfg.srcmask != dmask) printf(" --hashlimit-srcmask %u", info->cfg.srcmask); if (info->cfg.dstmask != dmask) printf(" --hashlimit-dstmask %u", info->cfg.dstmask); } static void hashlimit_mt4_save(const void *ip, const struct xt_entry_match *match) { const struct xt_hashlimit_mtinfo1 *info = (const void *)match->data; hashlimit_mt_save(info, 32); } static void hashlimit_mt6_save(const void *ip, const struct xt_entry_match *match) { const struct xt_hashlimit_mtinfo1 *info = (const void *)match->data; hashlimit_mt_save(info, 128); } static struct xtables_match hashlimit_mt_reg[] = { { .family = NFPROTO_UNSPEC, .name = "hashlimit", .version = XTABLES_VERSION, .revision = 0, .size = XT_ALIGN(sizeof(struct xt_hashlimit_info)), .userspacesize = offsetof(struct xt_hashlimit_info, hinfo), .help = hashlimit_help, .init = hashlimit_init, .x6_parse = hashlimit_parse, .x6_fcheck = hashlimit_check, .print = hashlimit_print, .save = hashlimit_save, .x6_options = hashlimit_opts, .udata_size = sizeof(struct hashlimit_mt_udata), }, { .version = XTABLES_VERSION, .name = "hashlimit", .revision = 1, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct xt_hashlimit_mtinfo1)), .userspacesize = offsetof(struct xt_hashlimit_mtinfo1, hinfo), .help = hashlimit_mt_help, .init = hashlimit_mt4_init, .x6_parse = hashlimit_mt_parse, .x6_fcheck = hashlimit_mt_check, .print = hashlimit_mt4_print, .save = hashlimit_mt4_save, .x6_options = hashlimit_mt_opts, .udata_size = sizeof(struct hashlimit_mt_udata), }, { .version = XTABLES_VERSION, .name = "hashlimit", .revision = 1, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct xt_hashlimit_mtinfo1)), .userspacesize = offsetof(struct xt_hashlimit_mtinfo1, hinfo), .help = hashlimit_mt_help, .init = hashlimit_mt6_init, .x6_parse = hashlimit_mt_parse, .x6_fcheck = hashlimit_mt_check, .print = hashlimit_mt6_print, .save = hashlimit_mt6_save, .x6_options = hashlimit_mt_opts, .udata_size = sizeof(struct hashlimit_mt_udata), }, }; void _init(void) { xtables_register_matches(hashlimit_mt_reg, ARRAY_SIZE(hashlimit_mt_reg)); }
241
./android_firewall/external/iptables/extensions/libxt_cpu.c
#include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_cpu.h> enum { O_CPU = 0, }; static void cpu_help(void) { printf( "cpu match options:\n" "[!] --cpu number Match CPU number\n"); } static const struct xt_option_entry cpu_opts[] = { {.name = "cpu", .id = O_CPU, .type = XTTYPE_UINT32, .flags = XTOPT_INVERT | XTOPT_MAND | XTOPT_PUT, XTOPT_POINTER(struct xt_cpu_info, cpu)}, XTOPT_TABLEEND, }; static void cpu_parse(struct xt_option_call *cb) { struct xt_cpu_info *cpuinfo = cb->data; xtables_option_parse(cb); if (cb->invert) cpuinfo->invert = true; } static void cpu_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_cpu_info *info = (void *)match->data; printf(" cpu %s%u", info->invert ? "! ":"", info->cpu); } static void cpu_save(const void *ip, const struct xt_entry_match *match) { const struct xt_cpu_info *info = (void *)match->data; printf("%s --cpu %u", info->invert ? " !" : "", info->cpu); } static struct xtables_match cpu_match = { .family = NFPROTO_UNSPEC, .name = "cpu", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_cpu_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_cpu_info)), .help = cpu_help, .print = cpu_print, .save = cpu_save, .x6_parse = cpu_parse, .x6_options = cpu_opts, }; void _init(void) { xtables_register_match(&cpu_match); }
242
./android_firewall/external/iptables/extensions/libip6t_HL.c
/* * IPv6 Hop Limit Target module * Maciej Soltysiak <[email protected]> * Based on HW's ttl target * This program is distributed under the terms of GNU GPL */ #include <stdio.h> #include <xtables.h> #include <linux/netfilter_ipv6/ip6t_HL.h> enum { O_HL_SET = 0, O_HL_INC, O_HL_DEC, F_HL_SET = 1 << O_HL_SET, F_HL_INC = 1 << O_HL_INC, F_HL_DEC = 1 << O_HL_DEC, F_ANY = F_HL_SET | F_HL_INC | F_HL_DEC, }; #define s struct ip6t_HL_info static const struct xt_option_entry HL_opts[] = { {.name = "hl-set", .type = XTTYPE_UINT8, .id = O_HL_SET, .excl = F_ANY, .flags = XTOPT_PUT, XTOPT_POINTER(s, hop_limit)}, {.name = "hl-dec", .type = XTTYPE_UINT8, .id = O_HL_DEC, .excl = F_ANY, .flags = XTOPT_PUT, XTOPT_POINTER(s, hop_limit), .min = 1}, {.name = "hl-inc", .type = XTTYPE_UINT8, .id = O_HL_INC, .excl = F_ANY, .flags = XTOPT_PUT, XTOPT_POINTER(s, hop_limit), .min = 1}, XTOPT_TABLEEND, }; #undef s static void HL_help(void) { printf( "HL target options\n" " --hl-set value Set HL to <value 0-255>\n" " --hl-dec value Decrement HL by <value 1-255>\n" " --hl-inc value Increment HL by <value 1-255>\n"); } static void HL_parse(struct xt_option_call *cb) { struct ip6t_HL_info *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_HL_SET: info->mode = IP6T_HL_SET; break; case O_HL_INC: info->mode = IP6T_HL_INC; break; case O_HL_DEC: info->mode = IP6T_HL_DEC; break; } } static void HL_check(struct xt_fcheck_call *cb) { if (!(cb->xflags & F_ANY)) xtables_error(PARAMETER_PROBLEM, "HL: You must specify an action"); } static void HL_save(const void *ip, const struct xt_entry_target *target) { const struct ip6t_HL_info *info = (struct ip6t_HL_info *) target->data; switch (info->mode) { case IP6T_HL_SET: printf(" --hl-set"); break; case IP6T_HL_DEC: printf(" --hl-dec"); break; case IP6T_HL_INC: printf(" --hl-inc"); break; } printf(" %u", info->hop_limit); } static void HL_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct ip6t_HL_info *info = (struct ip6t_HL_info *) target->data; printf(" HL "); switch (info->mode) { case IP6T_HL_SET: printf("set to"); break; case IP6T_HL_DEC: printf("decrement by"); break; case IP6T_HL_INC: printf("increment by"); break; } printf(" %u", info->hop_limit); } static struct xtables_target hl_tg6_reg = { .name = "HL", .version = XTABLES_VERSION, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct ip6t_HL_info)), .userspacesize = XT_ALIGN(sizeof(struct ip6t_HL_info)), .help = HL_help, .print = HL_print, .save = HL_save, .x6_parse = HL_parse, .x6_fcheck = HL_check, .x6_options = HL_opts, }; void _init(void) { xtables_register_target(&hl_tg6_reg); }
243
./android_firewall/external/iptables/extensions/libxt_limit.c
/* Shared library add-on to iptables to add limit support. * * J├⌐r├┤me de Vivie <[email protected]> * Herv├⌐ Eychenne <[email protected]> */ #define _BSD_SOURCE 1 #define _ISOC99_SOURCE 1 #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <xtables.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter/xt_limit.h> #define XT_LIMIT_AVG "3/hour" #define XT_LIMIT_BURST 5 enum { O_LIMIT = 0, O_BURST, }; static void limit_help(void) { printf( "limit match options:\n" "--limit avg max average match rate: default "XT_LIMIT_AVG"\n" " [Packets per second unless followed by \n" " /sec /minute /hour /day postfixes]\n" "--limit-burst number number to match in a burst, default %u\n", XT_LIMIT_BURST); } static const struct xt_option_entry limit_opts[] = { {.name = "limit", .id = O_LIMIT, .type = XTTYPE_STRING}, {.name = "limit-burst", .id = O_BURST, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(struct xt_rateinfo, burst), .min = 0, .max = 10000}, XTOPT_TABLEEND, }; static int parse_rate(const char *rate, uint32_t *val) { const char *delim; uint32_t r; uint32_t mult = 1; /* Seconds by default. */ delim = strchr(rate, '/'); if (delim) { if (strlen(delim+1) == 0) return 0; if (strncasecmp(delim+1, "second", strlen(delim+1)) == 0) mult = 1; else if (strncasecmp(delim+1, "minute", strlen(delim+1)) == 0) mult = 60; else if (strncasecmp(delim+1, "hour", strlen(delim+1)) == 0) mult = 60*60; else if (strncasecmp(delim+1, "day", strlen(delim+1)) == 0) mult = 24*60*60; else return 0; } r = atoi(rate); if (!r) return 0; *val = XT_LIMIT_SCALE * mult / r; if (*val == 0) /* * The rate maps to infinity. (1/day is the minimum they can * specify, so we are ok at that end). */ xtables_error(PARAMETER_PROBLEM, "Rate too fast \"%s\"\n", rate); return 1; } static void limit_init(struct xt_entry_match *m) { struct xt_rateinfo *r = (struct xt_rateinfo *)m->data; parse_rate(XT_LIMIT_AVG, &r->avg); r->burst = XT_LIMIT_BURST; } /* FIXME: handle overflow: if (r->avg*r->burst/r->burst != r->avg) xtables_error(PARAMETER_PROBLEM, "Sorry: burst too large for that avg rate.\n"); */ static void limit_parse(struct xt_option_call *cb) { struct xt_rateinfo *r = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_LIMIT: if (!parse_rate(cb->arg, &r->avg)) xtables_error(PARAMETER_PROBLEM, "bad rate \"%s\"'", cb->arg); break; } if (cb->invert) xtables_error(PARAMETER_PROBLEM, "limit does not support invert"); } static const struct rates { const char *name; uint32_t mult; } rates[] = { { "day", XT_LIMIT_SCALE*24*60*60 }, { "hour", XT_LIMIT_SCALE*60*60 }, { "min", XT_LIMIT_SCALE*60 }, { "sec", XT_LIMIT_SCALE } }; static void print_rate(uint32_t period) { unsigned int i; if (period == 0) { printf(" %f", INFINITY); return; } for (i = 1; i < ARRAY_SIZE(rates); ++i) if (period > rates[i].mult || rates[i].mult/period < rates[i].mult%period) break; printf(" %u/%s", rates[i-1].mult / period, rates[i-1].name); } static void limit_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_rateinfo *r = (const void *)match->data; printf(" limit: avg"); print_rate(r->avg); printf(" burst %u", r->burst); } static void limit_save(const void *ip, const struct xt_entry_match *match) { const struct xt_rateinfo *r = (const void *)match->data; printf(" --limit"); print_rate(r->avg); if (r->burst != XT_LIMIT_BURST) printf(" --limit-burst %u", r->burst); } static struct xtables_match limit_match = { .family = NFPROTO_UNSPEC, .name = "limit", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_rateinfo)), .userspacesize = offsetof(struct xt_rateinfo, prev), .help = limit_help, .init = limit_init, .x6_parse = limit_parse, .print = limit_print, .save = limit_save, .x6_options = limit_opts, }; void _init(void) { xtables_register_match(&limit_match); }
244
./android_firewall/external/iptables/extensions/libip6t_frag.c
#include <stdio.h> #include <xtables.h> #include <linux/netfilter_ipv6/ip6t_frag.h> enum { O_FRAGID = 0, O_FRAGLEN, O_FRAGRES, O_FRAGFIRST, O_FRAGMORE, O_FRAGLAST, F_FRAGMORE = 1 << O_FRAGMORE, F_FRAGLAST = 1 << O_FRAGLAST, }; static void frag_help(void) { printf( "frag match options:\n" "[!] --fragid id[:id] match the id (range)\n" "[!] --fraglen length total length of this header\n" " --fragres check the reserved field too\n" " --fragfirst matches on the first fragment\n" " [--fragmore|--fraglast] there are more fragments or this\n" " is the last one\n"); } #define s struct ip6t_frag static const struct xt_option_entry frag_opts[] = { {.name = "fragid", .id = O_FRAGID, .type = XTTYPE_UINT32RC, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, ids)}, {.name = "fraglen", .id = O_FRAGLEN, .type = XTTYPE_UINT32, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, hdrlen)}, {.name = "fragres", .id = O_FRAGRES, .type = XTTYPE_NONE}, {.name = "fragfirst", .id = O_FRAGFIRST, .type = XTTYPE_NONE}, {.name = "fragmore", .id = O_FRAGMORE, .type = XTTYPE_NONE, .excl = F_FRAGLAST}, {.name = "fraglast", .id = O_FRAGLAST, .type = XTTYPE_NONE, .excl = F_FRAGMORE}, XTOPT_TABLEEND, }; #undef s static void frag_init(struct xt_entry_match *m) { struct ip6t_frag *fraginfo = (void *)m->data; fraginfo->ids[1] = ~0U; } static void frag_parse(struct xt_option_call *cb) { struct ip6t_frag *fraginfo = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_FRAGID: if (cb->nvals == 1) fraginfo->ids[1] = fraginfo->ids[0]; if (cb->invert) fraginfo->invflags |= IP6T_FRAG_INV_IDS; /* * Note however that IP6T_FRAG_IDS is not tested by anything, * so it is merely here for completeness. */ fraginfo->flags |= IP6T_FRAG_IDS; break; case O_FRAGLEN: /* * As of Linux 3.0, the kernel does not check for * fraglen at all. */ if (cb->invert) fraginfo->invflags |= IP6T_FRAG_INV_LEN; fraginfo->flags |= IP6T_FRAG_LEN; break; case O_FRAGRES: fraginfo->flags |= IP6T_FRAG_RES; break; case O_FRAGFIRST: fraginfo->flags |= IP6T_FRAG_FST; break; case O_FRAGMORE: fraginfo->flags |= IP6T_FRAG_MF; break; case O_FRAGLAST: fraginfo->flags |= IP6T_FRAG_NMF; break; } } static void print_ids(const char *name, uint32_t min, uint32_t max, int invert) { const char *inv = invert ? "!" : ""; if (min != 0 || max != 0xFFFFFFFF || invert) { printf("%s", name); if (min == max) printf(":%s%u", inv, min); else printf("s:%s%u:%u", inv, min, max); } } static void frag_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct ip6t_frag *frag = (struct ip6t_frag *)match->data; printf(" frag "); print_ids("id", frag->ids[0], frag->ids[1], frag->invflags & IP6T_FRAG_INV_IDS); if (frag->flags & IP6T_FRAG_LEN) { printf(" length:%s%u", frag->invflags & IP6T_FRAG_INV_LEN ? "!" : "", frag->hdrlen); } if (frag->flags & IP6T_FRAG_RES) printf(" reserved"); if (frag->flags & IP6T_FRAG_FST) printf(" first"); if (frag->flags & IP6T_FRAG_MF) printf(" more"); if (frag->flags & IP6T_FRAG_NMF) printf(" last"); if (frag->invflags & ~IP6T_FRAG_INV_MASK) printf(" Unknown invflags: 0x%X", frag->invflags & ~IP6T_FRAG_INV_MASK); } static void frag_save(const void *ip, const struct xt_entry_match *match) { const struct ip6t_frag *fraginfo = (struct ip6t_frag *)match->data; if (!(fraginfo->ids[0] == 0 && fraginfo->ids[1] == 0xFFFFFFFF)) { printf("%s --fragid ", (fraginfo->invflags & IP6T_FRAG_INV_IDS) ? " !" : ""); if (fraginfo->ids[0] != fraginfo->ids[1]) printf("%u:%u", fraginfo->ids[0], fraginfo->ids[1]); else printf("%u", fraginfo->ids[0]); } if (fraginfo->flags & IP6T_FRAG_LEN) { printf("%s --fraglen %u", (fraginfo->invflags & IP6T_FRAG_INV_LEN) ? " !" : "", fraginfo->hdrlen); } if (fraginfo->flags & IP6T_FRAG_RES) printf(" --fragres"); if (fraginfo->flags & IP6T_FRAG_FST) printf(" --fragfirst"); if (fraginfo->flags & IP6T_FRAG_MF) printf(" --fragmore"); if (fraginfo->flags & IP6T_FRAG_NMF) printf(" --fraglast"); } static struct xtables_match frag_mt6_reg = { .name = "frag", .version = XTABLES_VERSION, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct ip6t_frag)), .userspacesize = XT_ALIGN(sizeof(struct ip6t_frag)), .help = frag_help, .init = frag_init, .print = frag_print, .save = frag_save, .x6_parse = frag_parse, .x6_options = frag_opts, }; void _init(void) { xtables_register_match(&frag_mt6_reg); }
245
./android_firewall/external/iptables/extensions/libxt_physdev.c
#include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_physdev.h> enum { O_PHYSDEV_IN = 0, O_PHYSDEV_OUT, O_PHYSDEV_IS_IN, O_PHYSDEV_IS_OUT, O_PHYSDEV_IS_BRIDGED, }; static void physdev_help(void) { printf( "physdev match options:\n" " [!] --physdev-in inputname[+] bridge port name ([+] for wildcard)\n" " [!] --physdev-out outputname[+] bridge port name ([+] for wildcard)\n" " [!] --physdev-is-in arrived on a bridge device\n" " [!] --physdev-is-out will leave on a bridge device\n" " [!] --physdev-is-bridged it's a bridged packet\n"); } #define s struct xt_physdev_info static const struct xt_option_entry physdev_opts[] = { {.name = "physdev-in", .id = O_PHYSDEV_IN, .type = XTTYPE_STRING, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, physindev)}, {.name = "physdev-out", .id = O_PHYSDEV_OUT, .type = XTTYPE_STRING, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, physoutdev)}, {.name = "physdev-is-in", .id = O_PHYSDEV_IS_IN, .type = XTTYPE_NONE, .flags = XTOPT_INVERT}, {.name = "physdev-is-out", .id = O_PHYSDEV_IS_OUT, .type = XTTYPE_NONE, .flags = XTOPT_INVERT}, {.name = "physdev-is-bridged", .id = O_PHYSDEV_IS_BRIDGED, .type = XTTYPE_NONE, .flags = XTOPT_INVERT}, XTOPT_TABLEEND, }; #undef s static void physdev_parse(struct xt_option_call *cb) { struct xt_physdev_info *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_PHYSDEV_IN: xtables_parse_interface(cb->arg, info->physindev, (unsigned char *)info->in_mask); if (cb->invert) info->invert |= XT_PHYSDEV_OP_IN; info->bitmask |= XT_PHYSDEV_OP_IN; break; case O_PHYSDEV_OUT: xtables_parse_interface(cb->arg, info->physoutdev, (unsigned char *)info->out_mask); if (cb->invert) info->invert |= XT_PHYSDEV_OP_OUT; info->bitmask |= XT_PHYSDEV_OP_OUT; break; case O_PHYSDEV_IS_IN: info->bitmask |= XT_PHYSDEV_OP_ISIN; if (cb->invert) info->invert |= XT_PHYSDEV_OP_ISIN; break; case O_PHYSDEV_IS_OUT: info->bitmask |= XT_PHYSDEV_OP_ISOUT; if (cb->invert) info->invert |= XT_PHYSDEV_OP_ISOUT; break; case O_PHYSDEV_IS_BRIDGED: if (cb->invert) info->invert |= XT_PHYSDEV_OP_BRIDGED; info->bitmask |= XT_PHYSDEV_OP_BRIDGED; break; } } static void physdev_check(struct xt_fcheck_call *cb) { if (cb->xflags == 0) xtables_error(PARAMETER_PROBLEM, "PHYSDEV: no physdev option specified"); } static void physdev_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_physdev_info *info = (const void *)match->data; printf(" PHYSDEV match"); if (info->bitmask & XT_PHYSDEV_OP_ISIN) printf("%s --physdev-is-in", info->invert & XT_PHYSDEV_OP_ISIN ? " !":""); if (info->bitmask & XT_PHYSDEV_OP_IN) printf("%s --physdev-in %s", (info->invert & XT_PHYSDEV_OP_IN) ? " !":"", info->physindev); if (info->bitmask & XT_PHYSDEV_OP_ISOUT) printf("%s --physdev-is-out", info->invert & XT_PHYSDEV_OP_ISOUT ? " !":""); if (info->bitmask & XT_PHYSDEV_OP_OUT) printf("%s --physdev-out %s", (info->invert & XT_PHYSDEV_OP_OUT) ? " !":"", info->physoutdev); if (info->bitmask & XT_PHYSDEV_OP_BRIDGED) printf("%s --physdev-is-bridged", info->invert & XT_PHYSDEV_OP_BRIDGED ? " !":""); } static void physdev_save(const void *ip, const struct xt_entry_match *match) { const struct xt_physdev_info *info = (const void *)match->data; if (info->bitmask & XT_PHYSDEV_OP_ISIN) printf("%s --physdev-is-in", (info->invert & XT_PHYSDEV_OP_ISIN) ? " !" : ""); if (info->bitmask & XT_PHYSDEV_OP_IN) printf("%s --physdev-in %s", (info->invert & XT_PHYSDEV_OP_IN) ? " !" : "", info->physindev); if (info->bitmask & XT_PHYSDEV_OP_ISOUT) printf("%s --physdev-is-out", (info->invert & XT_PHYSDEV_OP_ISOUT) ? " !" : ""); if (info->bitmask & XT_PHYSDEV_OP_OUT) printf("%s --physdev-out %s", (info->invert & XT_PHYSDEV_OP_OUT) ? " !" : "", info->physoutdev); if (info->bitmask & XT_PHYSDEV_OP_BRIDGED) printf("%s --physdev-is-bridged", (info->invert & XT_PHYSDEV_OP_BRIDGED) ? " !" : ""); } static struct xtables_match physdev_match = { .family = NFPROTO_UNSPEC, .name = "physdev", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_physdev_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_physdev_info)), .help = physdev_help, .print = physdev_print, .save = physdev_save, .x6_parse = physdev_parse, .x6_fcheck = physdev_check, .x6_options = physdev_opts, }; void _init(void) { xtables_register_match(&physdev_match); }
246
./android_firewall/external/iptables/extensions/libxt_CT.c
#include <stdio.h> #include <string.h> #include <xtables.h> #include <linux/netfilter/nf_conntrack_common.h> #include <linux/netfilter/xt_CT.h> static void ct_help(void) { printf( "CT target options:\n" " --notrack Don't track connection\n" " --helper name Use conntrack helper 'name' for connection\n" " --ctevents event[,event...] Generate specified conntrack events for connection\n" " --expevents event[,event...] Generate specified expectation events for connection\n" " --zone ID Assign/Lookup connection in zone ID\n" ); } static void ct_help_v1(void) { printf( "CT target options:\n" " --notrack Don't track connection\n" " --helper name Use conntrack helper 'name' for connection\n" " --timeout name Use timeout policy 'name' for connection\n" " --ctevents event[,event...] Generate specified conntrack events for connection\n" " --expevents event[,event...] Generate specified expectation events for connection\n" " --zone ID Assign/Lookup connection in zone ID\n" ); } enum { O_NOTRACK = 0, O_HELPER, O_TIMEOUT, O_CTEVENTS, O_EXPEVENTS, O_ZONE, }; #define s struct xt_ct_target_info static const struct xt_option_entry ct_opts[] = { {.name = "notrack", .id = O_NOTRACK, .type = XTTYPE_NONE}, {.name = "helper", .id = O_HELPER, .type = XTTYPE_STRING, .flags = XTOPT_PUT, XTOPT_POINTER(s, helper)}, {.name = "ctevents", .id = O_CTEVENTS, .type = XTTYPE_STRING}, {.name = "expevents", .id = O_EXPEVENTS, .type = XTTYPE_STRING}, {.name = "zone", .id = O_ZONE, .type = XTTYPE_UINT16, .flags = XTOPT_PUT, XTOPT_POINTER(s, zone)}, XTOPT_TABLEEND, }; #undef s #define s struct xt_ct_target_info_v1 static const struct xt_option_entry ct_opts_v1[] = { {.name = "notrack", .id = O_NOTRACK, .type = XTTYPE_NONE}, {.name = "helper", .id = O_HELPER, .type = XTTYPE_STRING, .flags = XTOPT_PUT, XTOPT_POINTER(s, helper)}, {.name = "timeout", .id = O_TIMEOUT, .type = XTTYPE_STRING, .flags = XTOPT_PUT, XTOPT_POINTER(s, timeout)}, {.name = "ctevents", .id = O_CTEVENTS, .type = XTTYPE_STRING}, {.name = "expevents", .id = O_EXPEVENTS, .type = XTTYPE_STRING}, {.name = "zone", .id = O_ZONE, .type = XTTYPE_UINT16, .flags = XTOPT_PUT, XTOPT_POINTER(s, zone)}, XTOPT_TABLEEND, }; #undef s struct event_tbl { const char *name; unsigned int event; }; static const struct event_tbl ct_event_tbl[] = { { "new", IPCT_NEW }, { "related", IPCT_RELATED }, { "destroy", IPCT_DESTROY }, { "reply", IPCT_REPLY }, { "assured", IPCT_ASSURED }, { "protoinfo", IPCT_PROTOINFO }, { "helper", IPCT_HELPER }, { "mark", IPCT_MARK }, { "natseqinfo", IPCT_NATSEQADJ }, { "secmark", IPCT_SECMARK }, }; static const struct event_tbl exp_event_tbl[] = { { "new", IPEXP_NEW }, }; static uint32_t ct_parse_events(const struct event_tbl *tbl, unsigned int size, const char *events) { char str[strlen(events) + 1], *e = str, *t; unsigned int mask = 0, i; strcpy(str, events); while ((t = strsep(&e, ","))) { for (i = 0; i < size; i++) { if (strcmp(t, tbl[i].name)) continue; mask |= 1 << tbl[i].event; break; } if (i == size) xtables_error(PARAMETER_PROBLEM, "Unknown event type \"%s\"", t); } return mask; } static void ct_print_events(const char *pfx, const struct event_tbl *tbl, unsigned int size, uint32_t mask) { const char *sep = ""; unsigned int i; printf(" %s ", pfx); for (i = 0; i < size; i++) { if (mask & (1 << tbl[i].event)) { printf("%s%s", sep, tbl[i].name); sep = ","; } } } static void ct_parse(struct xt_option_call *cb) { struct xt_ct_target_info *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_NOTRACK: info->flags |= XT_CT_NOTRACK; break; case O_CTEVENTS: info->ct_events = ct_parse_events(ct_event_tbl, ARRAY_SIZE(ct_event_tbl), cb->arg); break; case O_EXPEVENTS: info->exp_events = ct_parse_events(exp_event_tbl, ARRAY_SIZE(exp_event_tbl), cb->arg); break; } } static void ct_parse_v1(struct xt_option_call *cb) { struct xt_ct_target_info_v1 *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_NOTRACK: info->flags |= XT_CT_NOTRACK; break; case O_CTEVENTS: info->ct_events = ct_parse_events(ct_event_tbl, ARRAY_SIZE(ct_event_tbl), cb->arg); break; case O_EXPEVENTS: info->exp_events = ct_parse_events(exp_event_tbl, ARRAY_SIZE(exp_event_tbl), cb->arg); break; } } static void ct_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_ct_target_info *info = (const struct xt_ct_target_info *)target->data; printf(" CT"); if (info->flags & XT_CT_NOTRACK) printf(" notrack"); if (info->helper[0]) printf(" helper %s", info->helper); if (info->ct_events) ct_print_events("ctevents", ct_event_tbl, ARRAY_SIZE(ct_event_tbl), info->ct_events); if (info->exp_events) ct_print_events("expevents", exp_event_tbl, ARRAY_SIZE(exp_event_tbl), info->exp_events); if (info->zone) printf("zone %u ", info->zone); } static void ct_print_v1(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_ct_target_info_v1 *info = (const struct xt_ct_target_info_v1 *)target->data; printf(" CT"); if (info->flags & XT_CT_NOTRACK) printf(" notrack"); if (info->helper[0]) printf(" helper %s", info->helper); if (info->timeout[0]) printf(" timeout %s", info->timeout); if (info->ct_events) ct_print_events("ctevents", ct_event_tbl, ARRAY_SIZE(ct_event_tbl), info->ct_events); if (info->exp_events) ct_print_events("expevents", exp_event_tbl, ARRAY_SIZE(exp_event_tbl), info->exp_events); if (info->zone) printf("zone %u ", info->zone); } static void ct_save(const void *ip, const struct xt_entry_target *target) { const struct xt_ct_target_info *info = (const struct xt_ct_target_info *)target->data; if (info->flags & XT_CT_NOTRACK) printf(" --notrack"); if (info->helper[0]) printf(" --helper %s", info->helper); if (info->ct_events) ct_print_events("--ctevents", ct_event_tbl, ARRAY_SIZE(ct_event_tbl), info->ct_events); if (info->exp_events) ct_print_events("--expevents", exp_event_tbl, ARRAY_SIZE(exp_event_tbl), info->exp_events); if (info->zone) printf(" --zone %u", info->zone); } static void ct_save_v1(const void *ip, const struct xt_entry_target *target) { const struct xt_ct_target_info_v1 *info = (const struct xt_ct_target_info_v1 *)target->data; if (info->flags & XT_CT_NOTRACK) printf(" --notrack"); if (info->helper[0]) printf(" --helper %s", info->helper); if (info->timeout[0]) printf(" --timeout %s", info->timeout); if (info->ct_events) ct_print_events("--ctevents", ct_event_tbl, ARRAY_SIZE(ct_event_tbl), info->ct_events); if (info->exp_events) ct_print_events("--expevents", exp_event_tbl, ARRAY_SIZE(exp_event_tbl), info->exp_events); if (info->zone) printf(" --zone %u", info->zone); } static void notrack_ct0_tg_init(struct xt_entry_target *target) { struct xt_ct_target_info *info = (void *)target->data; info->flags = XT_CT_NOTRACK; } static void notrack_ct1_tg_init(struct xt_entry_target *target) { struct xt_ct_target_info_v1 *info = (void *)target->data; info->flags = XT_CT_NOTRACK; } static struct xtables_target ct_target_reg[] = { { .family = NFPROTO_UNSPEC, .name = "CT", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_ct_target_info)), .userspacesize = offsetof(struct xt_ct_target_info, ct), .help = ct_help, .print = ct_print, .save = ct_save, .x6_parse = ct_parse, .x6_options = ct_opts, }, { .family = NFPROTO_UNSPEC, .name = "CT", .revision = 1, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_ct_target_info_v1)), .userspacesize = offsetof(struct xt_ct_target_info_v1, ct), .help = ct_help_v1, .print = ct_print_v1, .save = ct_save_v1, .x6_parse = ct_parse_v1, .x6_options = ct_opts_v1, }, { .family = NFPROTO_UNSPEC, .name = "NOTRACK", .real_name = "CT", .revision = 0, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_ct_target_info)), .userspacesize = offsetof(struct xt_ct_target_info, ct), .init = notrack_ct0_tg_init, }, { .family = NFPROTO_UNSPEC, .name = "NOTRACK", .real_name = "CT", .revision = 1, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_ct_target_info_v1)), .userspacesize = offsetof(struct xt_ct_target_info_v1, ct), .init = notrack_ct1_tg_init, }, { .family = NFPROTO_UNSPEC, .name = "NOTRACK", .revision = 0, .version = XTABLES_VERSION, }, }; void _init(void) { xtables_register_targets(ct_target_reg, ARRAY_SIZE(ct_target_reg)); }
247
./android_firewall/external/iptables/extensions/libipt_LOG.c
#include <stdio.h> #include <string.h> #include <syslog.h> #include <xtables.h> #include <linux/netfilter_ipv4/ipt_LOG.h> #define LOG_DEFAULT_LEVEL LOG_WARNING #ifndef IPT_LOG_UID /* Old kernel */ #define IPT_LOG_UID 0x08 /* Log UID owning local socket */ #undef IPT_LOG_MASK #define IPT_LOG_MASK 0x0f #endif enum { O_LOG_LEVEL = 0, O_LOG_PREFIX, O_LOG_TCPSEQ, O_LOG_TCPOPTS, O_LOG_IPOPTS, O_LOG_UID, O_LOG_MAC, }; static void LOG_help(void) { printf( "LOG target options:\n" " --log-level level Level of logging (numeric or see syslog.conf)\n" " --log-prefix prefix Prefix log messages with this prefix.\n\n" " --log-tcp-sequence Log TCP sequence numbers.\n\n" " --log-tcp-options Log TCP options.\n\n" " --log-ip-options Log IP options.\n\n" " --log-uid Log UID owning the local socket.\n\n" " --log-macdecode Decode MAC addresses and protocol.\n\n"); } #define s struct ipt_log_info static const struct xt_option_entry LOG_opts[] = { {.name = "log-level", .id = O_LOG_LEVEL, .type = XTTYPE_SYSLOGLEVEL, .flags = XTOPT_PUT, XTOPT_POINTER(s, level)}, {.name = "log-prefix", .id = O_LOG_PREFIX, .type = XTTYPE_STRING, .flags = XTOPT_PUT, XTOPT_POINTER(s, prefix), .min = 1}, {.name = "log-tcp-sequence", .id = O_LOG_TCPSEQ, .type = XTTYPE_NONE}, {.name = "log-tcp-options", .id = O_LOG_TCPOPTS, .type = XTTYPE_NONE}, {.name = "log-ip-options", .id = O_LOG_IPOPTS, .type = XTTYPE_NONE}, {.name = "log-uid", .id = O_LOG_UID, .type = XTTYPE_NONE}, {.name = "log-macdecode", .id = O_LOG_MAC, .type = XTTYPE_NONE}, XTOPT_TABLEEND, }; #undef s static void LOG_init(struct xt_entry_target *t) { struct ipt_log_info *loginfo = (struct ipt_log_info *)t->data; loginfo->level = LOG_DEFAULT_LEVEL; } struct ipt_log_names { const char *name; unsigned int level; }; static const struct ipt_log_names ipt_log_names[] = { { .name = "alert", .level = LOG_ALERT }, { .name = "crit", .level = LOG_CRIT }, { .name = "debug", .level = LOG_DEBUG }, { .name = "emerg", .level = LOG_EMERG }, { .name = "error", .level = LOG_ERR }, /* DEPRECATED */ { .name = "info", .level = LOG_INFO }, { .name = "notice", .level = LOG_NOTICE }, { .name = "panic", .level = LOG_EMERG }, /* DEPRECATED */ { .name = "warning", .level = LOG_WARNING } }; static void LOG_parse(struct xt_option_call *cb) { struct ipt_log_info *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_LOG_PREFIX: if (strchr(cb->arg, '\n') != NULL) xtables_error(PARAMETER_PROBLEM, "Newlines not allowed in --log-prefix"); break; case O_LOG_TCPSEQ: info->logflags |= IPT_LOG_TCPSEQ; break; case O_LOG_TCPOPTS: info->logflags |= IPT_LOG_TCPOPT; break; case O_LOG_IPOPTS: info->logflags |= IPT_LOG_IPOPT; break; case O_LOG_UID: info->logflags |= IPT_LOG_UID; break; case O_LOG_MAC: info->logflags |= IPT_LOG_MACDECODE; break; } } static void LOG_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct ipt_log_info *loginfo = (const struct ipt_log_info *)target->data; unsigned int i = 0; printf(" LOG"); if (numeric) printf(" flags %u level %u", loginfo->logflags, loginfo->level); else { for (i = 0; i < ARRAY_SIZE(ipt_log_names); ++i) if (loginfo->level == ipt_log_names[i].level) { printf(" level %s", ipt_log_names[i].name); break; } if (i == ARRAY_SIZE(ipt_log_names)) printf(" UNKNOWN level %u", loginfo->level); if (loginfo->logflags & IPT_LOG_TCPSEQ) printf(" tcp-sequence"); if (loginfo->logflags & IPT_LOG_TCPOPT) printf(" tcp-options"); if (loginfo->logflags & IPT_LOG_IPOPT) printf(" ip-options"); if (loginfo->logflags & IPT_LOG_UID) printf(" uid"); if (loginfo->logflags & IPT_LOG_MACDECODE) printf(" macdecode"); if (loginfo->logflags & ~(IPT_LOG_MASK)) printf(" unknown-flags"); } if (strcmp(loginfo->prefix, "") != 0) printf(" prefix \"%s\"", loginfo->prefix); } static void LOG_save(const void *ip, const struct xt_entry_target *target) { const struct ipt_log_info *loginfo = (const struct ipt_log_info *)target->data; if (strcmp(loginfo->prefix, "") != 0) { printf(" --log-prefix"); xtables_save_string(loginfo->prefix); } if (loginfo->level != LOG_DEFAULT_LEVEL) printf(" --log-level %d", loginfo->level); if (loginfo->logflags & IPT_LOG_TCPSEQ) printf(" --log-tcp-sequence"); if (loginfo->logflags & IPT_LOG_TCPOPT) printf(" --log-tcp-options"); if (loginfo->logflags & IPT_LOG_IPOPT) printf(" --log-ip-options"); if (loginfo->logflags & IPT_LOG_UID) printf(" --log-uid"); if (loginfo->logflags & IPT_LOG_MACDECODE) printf(" --log-macdecode"); } static struct xtables_target log_tg_reg = { .name = "LOG", .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct ipt_log_info)), .userspacesize = XT_ALIGN(sizeof(struct ipt_log_info)), .help = LOG_help, .init = LOG_init, .print = LOG_print, .save = LOG_save, .x6_parse = LOG_parse, .x6_options = LOG_opts, }; void _init(void) { xtables_register_target(&log_tg_reg); }
248
./android_firewall/external/iptables/extensions/libxt_length.c
#include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_length.h> enum { O_LENGTH = 0, }; static void length_help(void) { printf( "length match options:\n" "[!] --length length[:length] Match packet length against value or range\n" " of values (inclusive)\n"); } static const struct xt_option_entry length_opts[] = { {.name = "length", .id = O_LENGTH, .type = XTTYPE_UINT16RC, .flags = XTOPT_MAND | XTOPT_INVERT}, XTOPT_TABLEEND, }; static void length_parse(struct xt_option_call *cb) { struct xt_length_info *info = cb->data; xtables_option_parse(cb); info->min = cb->val.u16_range[0]; info->max = cb->val.u16_range[0]; if (cb->nvals >= 2) info->max = cb->val.u16_range[1]; if (cb->invert) info->invert = 1; } static void length_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_length_info *info = (void *)match->data; printf(" length %s", info->invert ? "!" : ""); if (info->min == info->max) printf("%u", info->min); else printf("%u:%u", info->min, info->max); } static void length_save(const void *ip, const struct xt_entry_match *match) { const struct xt_length_info *info = (void *)match->data; printf("%s --length ", info->invert ? " !" : ""); if (info->min == info->max) printf("%u", info->min); else printf("%u:%u", info->min, info->max); } static struct xtables_match length_match = { .family = NFPROTO_UNSPEC, .name = "length", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_length_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_length_info)), .help = length_help, .print = length_print, .save = length_save, .x6_parse = length_parse, .x6_options = length_opts, }; void _init(void) { xtables_register_match(&length_match); }
249
./android_firewall/external/iptables/extensions/libxt_u32.c
/* Shared library add-on to iptables to add u32 matching, * generalized matching on values found at packet offsets * * Detailed doc is in the kernel module source * net/netfilter/xt_u32.c * * (C) 2002 by Don Cohen <[email protected]> * Released under the terms of GNU GPL v2 * * Copyright ┬⌐ CC Computer Consultants GmbH, 2007 * Contact: <[email protected]> */ #include <ctype.h> #include <errno.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_u32.h> enum { O_U32 = 0, }; static const struct xt_option_entry u32_opts[] = { {.name = "u32", .id = O_U32, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_INVERT}, XTOPT_TABLEEND, }; static void u32_help(void) { printf( "u32 match options:\n" "[!] --u32 tests\n" "\t\t""tests := location \"=\" value | tests \"&&\" location \"=\" value\n" "\t\t""value := range | value \",\" range\n" "\t\t""range := number | number \":\" number\n" "\t\t""location := number | location operator number\n" "\t\t""operator := \"&\" | \"<<\" | \">>\" | \"@\"\n"); } static void u32_dump(const struct xt_u32 *data) { const struct xt_u32_test *ct; unsigned int testind, i; printf(" \""); for (testind = 0; testind < data->ntests; ++testind) { ct = &data->tests[testind]; if (testind > 0) printf("&&"); printf("0x%x", ct->location[0].number); for (i = 1; i < ct->nnums; ++i) { switch (ct->location[i].nextop) { case XT_U32_AND: printf("&"); break; case XT_U32_LEFTSH: printf("<<"); break; case XT_U32_RIGHTSH: printf(">>"); break; case XT_U32_AT: printf("@"); break; } printf("0x%x", ct->location[i].number); } printf("="); for (i = 0; i < ct->nvalues; ++i) { if (i > 0) printf(","); if (ct->value[i].min == ct->value[i].max) printf("0x%x", ct->value[i].min); else printf("0x%x:0x%x", ct->value[i].min, ct->value[i].max); } } putchar('\"'); } /* string_to_number() is not quite what we need here ... */ static uint32_t parse_number(const char **s, int pos) { unsigned int number; char *end; if (!xtables_strtoui(*s, &end, &number, 0, UINT32_MAX) || end == *s) xtables_error(PARAMETER_PROBLEM, "u32: at char %d: not a number or out of range", pos); *s = end; return number; } static void u32_parse(struct xt_option_call *cb) { struct xt_u32 *data = cb->data; unsigned int testind = 0, locind = 0, valind = 0; struct xt_u32_test *ct = &data->tests[testind]; /* current test */ const char *arg = cb->arg; /* the argument string */ const char *start = cb->arg; int state = 0; xtables_option_parse(cb); data->invert = cb->invert; /* * states: * 0 = looking for numbers and operations, * 1 = looking for ranges */ while (1) { /* read next operand/number or range */ while (isspace(*arg)) ++arg; if (*arg == '\0') { /* end of argument found */ if (state == 0) xtables_error(PARAMETER_PROBLEM, "u32: abrupt end of input after location specifier"); if (valind == 0) xtables_error(PARAMETER_PROBLEM, "u32: test ended with no value specified"); ct->nnums = locind; ct->nvalues = valind; data->ntests = ++testind; if (testind > XT_U32_MAXSIZE) xtables_error(PARAMETER_PROBLEM, "u32: at char %u: too many \"&&\"s", (unsigned int)(arg - start)); return; } if (state == 0) { /* * reading location: read a number if nothing read yet, * otherwise either op number or = to end location spec */ if (*arg == '=') { if (locind == 0) { xtables_error(PARAMETER_PROBLEM, "u32: at char %u: " "location spec missing", (unsigned int)(arg - start)); } else { ++arg; state = 1; } } else { if (locind != 0) { /* need op before number */ if (*arg == '&') { ct->location[locind].nextop = XT_U32_AND; } else if (*arg == '<') { if (*++arg != '<') xtables_error(PARAMETER_PROBLEM, "u32: at char %u: a second '<' was expected", (unsigned int)(arg - start)); ct->location[locind].nextop = XT_U32_LEFTSH; } else if (*arg == '>') { if (*++arg != '>') xtables_error(PARAMETER_PROBLEM, "u32: at char %u: a second '>' was expected", (unsigned int)(arg - start)); ct->location[locind].nextop = XT_U32_RIGHTSH; } else if (*arg == '@') { ct->location[locind].nextop = XT_U32_AT; } else { xtables_error(PARAMETER_PROBLEM, "u32: at char %u: operator expected", (unsigned int)(arg - start)); } ++arg; } /* now a number; string_to_number skips white space? */ ct->location[locind].number = parse_number(&arg, arg - start); if (++locind > XT_U32_MAXSIZE) xtables_error(PARAMETER_PROBLEM, "u32: at char %u: too many operators", (unsigned int)(arg - start)); } } else { /* * state 1 - reading values: read a range if nothing * read yet, otherwise either ,range or && to end * test spec */ if (*arg == '&') { if (*++arg != '&') xtables_error(PARAMETER_PROBLEM, "u32: at char %u: a second '&' was expected", (unsigned int)(arg - start)); if (valind == 0) { xtables_error(PARAMETER_PROBLEM, "u32: at char %u: value spec missing", (unsigned int)(arg - start)); } else { ct->nnums = locind; ct->nvalues = valind; ct = &data->tests[++testind]; if (testind > XT_U32_MAXSIZE) xtables_error(PARAMETER_PROBLEM, "u32: at char %u: too many \"&&\"s", (unsigned int)(arg - start)); ++arg; state = 0; locind = 0; valind = 0; } } else { /* read value range */ if (valind > 0) { /* need , before number */ if (*arg != ',') xtables_error(PARAMETER_PROBLEM, "u32: at char %u: expected \",\" or \"&&\"", (unsigned int)(arg - start)); ++arg; } ct->value[valind].min = parse_number(&arg, arg - start); while (isspace(*arg)) ++arg; if (*arg == ':') { ++arg; ct->value[valind].max = parse_number(&arg, arg-start); } else { ct->value[valind].max = ct->value[valind].min; } if (++valind > XT_U32_MAXSIZE) xtables_error(PARAMETER_PROBLEM, "u32: at char %u: too many \",\"s", (unsigned int)(arg - start)); } } } } static void u32_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_u32 *data = (const void *)match->data; printf(" u32"); if (data->invert) printf(" !"); u32_dump(data); } static void u32_save(const void *ip, const struct xt_entry_match *match) { const struct xt_u32 *data = (const void *)match->data; if (data->invert) printf(" !"); printf(" --u32"); u32_dump(data); } static struct xtables_match u32_match = { .name = "u32", .family = NFPROTO_UNSPEC, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_u32)), .userspacesize = XT_ALIGN(sizeof(struct xt_u32)), .help = u32_help, .print = u32_print, .save = u32_save, .x6_parse = u32_parse, .x6_options = u32_opts, }; void _init(void) { xtables_register_match(&u32_match); }
250
./android_firewall/external/iptables/extensions/libxt_statistic.c
#include <math.h> #include <stdio.h> #include <string.h> #include <xtables.h> #include <linux/netfilter/xt_statistic.h> enum { O_MODE = 0, O_PROBABILITY, O_EVERY, O_PACKET, F_PROBABILITY = 1 << O_PROBABILITY, F_EVERY = 1 << O_EVERY, F_PACKET = 1 << O_PACKET, }; static void statistic_help(void) { printf( "statistic match options:\n" " --mode mode Match mode (random, nth)\n" " random mode:\n" "[!] --probability p Probability\n" " nth mode:\n" "[!] --every n Match every nth packet\n" " --packet p Initial counter value (0 <= p <= n-1, default 0)\n"); } #define s struct xt_statistic_info static const struct xt_option_entry statistic_opts[] = { {.name = "mode", .id = O_MODE, .type = XTTYPE_STRING, .flags = XTOPT_MAND}, {.name = "probability", .id = O_PROBABILITY, .type = XTTYPE_DOUBLE, .flags = XTOPT_INVERT, .min = 0, .max = 1, .excl = F_EVERY | F_PACKET}, {.name = "every", .id = O_EVERY, .type = XTTYPE_UINT32, .min = 1, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, u.nth.every), .excl = F_PROBABILITY, .also = F_PACKET}, {.name = "packet", .id = O_PACKET, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, u.nth.packet), .excl = F_PROBABILITY, .also = F_EVERY}, XTOPT_TABLEEND, }; #undef s static void statistic_parse(struct xt_option_call *cb) { struct xt_statistic_info *info = cb->data; if (cb->invert) info->flags |= XT_STATISTIC_INVERT; xtables_option_parse(cb); switch (cb->entry->id) { case O_MODE: if (strcmp(cb->arg, "random") == 0) info->mode = XT_STATISTIC_MODE_RANDOM; else if (strcmp(cb->arg, "nth") == 0) info->mode = XT_STATISTIC_MODE_NTH; else xtables_error(PARAMETER_PROBLEM, "Bad mode \"%s\"", cb->arg); break; case O_PROBABILITY: info->u.random.probability = lround(0x80000000 * cb->val.dbl); break; case O_EVERY: --info->u.nth.every; break; } } static void statistic_check(struct xt_fcheck_call *cb) { struct xt_statistic_info *info = cb->data; if (info->mode == XT_STATISTIC_MODE_RANDOM && !(cb->xflags & F_PROBABILITY)) xtables_error(PARAMETER_PROBLEM, "--probability must be specified when using " "random mode"); if (info->mode == XT_STATISTIC_MODE_NTH && !(cb->xflags & (F_EVERY | F_PACKET))) xtables_error(PARAMETER_PROBLEM, "--every and --packet must be specified when " "using nth mode"); /* at this point, info->u.nth.every have been decreased. */ if (info->u.nth.packet > info->u.nth.every) xtables_error(PARAMETER_PROBLEM, "the --packet p must be 0 <= p <= n-1"); info->u.nth.count = info->u.nth.every - info->u.nth.packet; } static void print_match(const struct xt_statistic_info *info, char *prefix) { switch (info->mode) { case XT_STATISTIC_MODE_RANDOM: printf(" %smode random%s %sprobability %.11f", prefix, (info->flags & XT_STATISTIC_INVERT) ? " !" : "", prefix, 1.0 * info->u.random.probability / 0x80000000); break; case XT_STATISTIC_MODE_NTH: printf(" %smode nth%s %severy %u", prefix, (info->flags & XT_STATISTIC_INVERT) ? " !" : "", prefix, info->u.nth.every + 1); if (info->u.nth.packet) printf(" %spacket %u", prefix, info->u.nth.packet); break; } } static void statistic_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_statistic_info *info = (const void *)match->data; printf(" statistic"); print_match(info, ""); } static void statistic_save(const void *ip, const struct xt_entry_match *match) { const struct xt_statistic_info *info = (const void *)match->data; print_match(info, "--"); } static struct xtables_match statistic_match = { .family = NFPROTO_UNSPEC, .name = "statistic", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_statistic_info)), .userspacesize = offsetof(struct xt_statistic_info, u.nth.count), .help = statistic_help, .x6_parse = statistic_parse, .x6_fcheck = statistic_check, .print = statistic_print, .save = statistic_save, .x6_options = statistic_opts, }; void _init(void) { xtables_register_match(&statistic_match); }
251
./android_firewall/external/iptables/extensions/libxt_TCPMSS.c
/* Shared library add-on to iptables to add TCPMSS target support. * * Copyright (c) 2000 Marc Boucher */ #include "config.h" #include <stdio.h> #include <xtables.h> #include <netinet/ip.h> #include <linux/netfilter/xt_TCPMSS.h> enum { O_SET_MSS = 0, O_CLAMP_MSS, }; struct mssinfo { struct xt_entry_target t; struct xt_tcpmss_info mss; }; static void __TCPMSS_help(int hdrsize) { printf( "TCPMSS target mutually-exclusive options:\n" " --set-mss value explicitly set MSS option to specified value\n" " --clamp-mss-to-pmtu automatically clamp MSS value to (path_MTU - %d)\n", hdrsize); } static void TCPMSS_help(void) { __TCPMSS_help(sizeof(struct iphdr)); } static void TCPMSS_help6(void) { __TCPMSS_help(SIZEOF_STRUCT_IP6_HDR); } static const struct xt_option_entry TCPMSS4_opts[] = { {.name = "set-mss", .id = O_SET_MSS, .type = XTTYPE_UINT16, .min = 0, .max = UINT16_MAX - sizeof(struct iphdr), .flags = XTOPT_PUT, XTOPT_POINTER(struct xt_tcpmss_info, mss)}, {.name = "clamp-mss-to-pmtu", .id = O_CLAMP_MSS, .type = XTTYPE_NONE}, XTOPT_TABLEEND, }; static const struct xt_option_entry TCPMSS6_opts[] = { {.name = "set-mss", .id = O_SET_MSS, .type = XTTYPE_UINT16, .min = 0, .max = UINT16_MAX - SIZEOF_STRUCT_IP6_HDR, .flags = XTOPT_PUT, XTOPT_POINTER(struct xt_tcpmss_info, mss)}, {.name = "clamp-mss-to-pmtu", .id = O_CLAMP_MSS, .type = XTTYPE_NONE}, XTOPT_TABLEEND, }; static void TCPMSS_parse(struct xt_option_call *cb) { struct xt_tcpmss_info *mssinfo = cb->data; xtables_option_parse(cb); if (cb->entry->id == O_CLAMP_MSS) mssinfo->mss = XT_TCPMSS_CLAMP_PMTU; } static void TCPMSS_check(struct xt_fcheck_call *cb) { if (cb->xflags == 0) xtables_error(PARAMETER_PROBLEM, "TCPMSS target: At least one parameter is required"); } static void TCPMSS_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_tcpmss_info *mssinfo = (const struct xt_tcpmss_info *)target->data; if(mssinfo->mss == XT_TCPMSS_CLAMP_PMTU) printf(" TCPMSS clamp to PMTU"); else printf(" TCPMSS set %u", mssinfo->mss); } static void TCPMSS_save(const void *ip, const struct xt_entry_target *target) { const struct xt_tcpmss_info *mssinfo = (const struct xt_tcpmss_info *)target->data; if(mssinfo->mss == XT_TCPMSS_CLAMP_PMTU) printf(" --clamp-mss-to-pmtu"); else printf(" --set-mss %u", mssinfo->mss); } static struct xtables_target tcpmss_tg_reg[] = { { .family = NFPROTO_IPV4, .name = "TCPMSS", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_tcpmss_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_tcpmss_info)), .help = TCPMSS_help, .print = TCPMSS_print, .save = TCPMSS_save, .x6_parse = TCPMSS_parse, .x6_fcheck = TCPMSS_check, .x6_options = TCPMSS4_opts, }, { .family = NFPROTO_IPV6, .name = "TCPMSS", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_tcpmss_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_tcpmss_info)), .help = TCPMSS_help6, .print = TCPMSS_print, .save = TCPMSS_save, .x6_parse = TCPMSS_parse, .x6_fcheck = TCPMSS_check, .x6_options = TCPMSS6_opts, }, }; void _init(void) { xtables_register_targets(tcpmss_tg_reg, ARRAY_SIZE(tcpmss_tg_reg)); }
252
./android_firewall/external/iptables/extensions/libxt_TOS.c
/* * Shared library add-on to iptables to add TOS target support * * Copyright ┬⌐ CC Computer Consultants GmbH, 2007 * Contact: Jan Engelhardt <[email protected]> */ #include <getopt.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netinet/in.h> #include <xtables.h> #include <linux/netfilter/xt_DSCP.h> #include "tos_values.c" struct ipt_tos_target_info { uint8_t tos; }; enum { O_SET_TOS = 0, O_AND_TOS, O_OR_TOS, O_XOR_TOS, F_SET_TOS = 1 << O_SET_TOS, F_AND_TOS = 1 << O_AND_TOS, F_OR_TOS = 1 << O_OR_TOS, F_XOR_TOS = 1 << O_XOR_TOS, F_ANY = F_SET_TOS | F_AND_TOS | F_OR_TOS | F_XOR_TOS, }; static const struct xt_option_entry tos_tg_opts_v0[] = { {.name = "set-tos", .id = O_SET_TOS, .type = XTTYPE_TOSMASK, .excl = F_ANY, .max = 0xFF}, XTOPT_TABLEEND, }; static const struct xt_option_entry tos_tg_opts[] = { {.name = "set-tos", .id = O_SET_TOS, .type = XTTYPE_TOSMASK, .excl = F_ANY, .max = 0x3F}, {.name = "and-tos", .id = O_AND_TOS, .type = XTTYPE_UINT8, .excl = F_ANY}, {.name = "or-tos", .id = O_OR_TOS, .type = XTTYPE_UINT8, .excl = F_ANY}, {.name = "xor-tos", .id = O_XOR_TOS, .type = XTTYPE_UINT8, .excl = F_ANY}, XTOPT_TABLEEND, }; static void tos_tg_help_v0(void) { const struct tos_symbol_info *symbol; printf( "TOS target options:\n" " --set-tos value Set Type of Service/Priority field to value\n" " --set-tos symbol Set TOS field (IPv4 only) by symbol\n" " Accepted symbolic names for value are:\n"); for (symbol = tos_symbol_names; symbol->name != NULL; ++symbol) printf(" (0x%02x) %2u %s\n", symbol->value, symbol->value, symbol->name); printf("\n"); } static void tos_tg_help(void) { const struct tos_symbol_info *symbol; printf( "TOS target v%s options:\n" " --set-tos value[/mask] Set Type of Service/Priority field to value\n" " (Zero out bits in mask and XOR value into TOS)\n" " --set-tos symbol Set TOS field (IPv4 only) by symbol\n" " (this zeroes the 4-bit Precedence part!)\n" " Accepted symbolic names for value are:\n", XTABLES_VERSION); for (symbol = tos_symbol_names; symbol->name != NULL; ++symbol) printf(" (0x%02x) %2u %s\n", symbol->value, symbol->value, symbol->name); printf( "\n" " --and-tos bits Binary AND the TOS value with bits\n" " --or-tos bits Binary OR the TOS value with bits\n" " --xor-tos bits Binary XOR the TOS value with bits\n" ); } static void tos_tg_parse_v0(struct xt_option_call *cb) { struct ipt_tos_target_info *info = cb->data; xtables_option_parse(cb); if (cb->val.tos_mask != 0xFF) xtables_error(PARAMETER_PROBLEM, "tos match: Your kernel " "is too old to support anything besides " "/0xFF as a mask."); info->tos = cb->val.tos_value; } static void tos_tg_parse(struct xt_option_call *cb) { struct xt_tos_target_info *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_SET_TOS: info->tos_value = cb->val.tos_value; info->tos_mask = cb->val.tos_mask; break; case O_AND_TOS: info->tos_value = 0; info->tos_mask = ~cb->val.u8; break; case O_OR_TOS: info->tos_value = cb->val.u8; info->tos_mask = cb->val.u8; break; case O_XOR_TOS: info->tos_value = cb->val.u8; info->tos_mask = 0; break; } } static void tos_tg_check(struct xt_fcheck_call *cb) { if (!(cb->xflags & F_ANY)) xtables_error(PARAMETER_PROBLEM, "TOS: An action is required"); } static void tos_tg_print_v0(const void *ip, const struct xt_entry_target *target, int numeric) { const struct ipt_tos_target_info *info = (const void *)target->data; printf(" TOS set "); if (numeric || !tos_try_print_symbolic("", info->tos, 0xFF)) printf("0x%02x", info->tos); } static void tos_tg_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_tos_target_info *info = (const void *)target->data; if (numeric) printf(" TOS set 0x%02x/0x%02x", info->tos_value, info->tos_mask); else if (tos_try_print_symbolic(" TOS set", info->tos_value, info->tos_mask)) /* already printed by call */ return; else if (info->tos_value == 0) printf(" TOS and 0x%02x", (unsigned int)(uint8_t)~info->tos_mask); else if (info->tos_value == info->tos_mask) printf(" TOS or 0x%02x", info->tos_value); else if (info->tos_mask == 0) printf(" TOS xor 0x%02x", info->tos_value); else printf(" TOS set 0x%02x/0x%02x", info->tos_value, info->tos_mask); } static void tos_tg_save_v0(const void *ip, const struct xt_entry_target *target) { const struct ipt_tos_target_info *info = (const void *)target->data; printf(" --set-tos 0x%02x", info->tos); } static void tos_tg_save(const void *ip, const struct xt_entry_target *target) { const struct xt_tos_target_info *info = (const void *)target->data; printf(" --set-tos 0x%02x/0x%02x", info->tos_value, info->tos_mask); } static struct xtables_target tos_tg_reg[] = { { .version = XTABLES_VERSION, .name = "TOS", .revision = 0, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct xt_tos_target_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_tos_target_info)), .help = tos_tg_help_v0, .print = tos_tg_print_v0, .save = tos_tg_save_v0, .x6_parse = tos_tg_parse_v0, .x6_fcheck = tos_tg_check, .x6_options = tos_tg_opts_v0, }, { .version = XTABLES_VERSION, .name = "TOS", .revision = 1, .family = NFPROTO_UNSPEC, .size = XT_ALIGN(sizeof(struct xt_tos_target_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_tos_target_info)), .help = tos_tg_help, .print = tos_tg_print, .save = tos_tg_save, .x6_parse = tos_tg_parse, .x6_fcheck = tos_tg_check, .x6_options = tos_tg_opts, }, }; void _init(void) { xtables_register_targets(tos_tg_reg, ARRAY_SIZE(tos_tg_reg)); }
253
./android_firewall/external/iptables/extensions/libxt_owner.c
/* * libxt_owner - iptables addon for xt_owner * * Copyright ┬⌐ CC Computer Consultants GmbH, 2007 - 2008 * Jan Engelhardt <[email protected]> */ #include <grp.h> #include <pwd.h> #include <stdbool.h> #include <stdio.h> #include <limits.h> #include <xtables.h> #include <linux/netfilter/xt_owner.h> /* match and invert flags */ enum { IPT_OWNER_UID = 0x01, IPT_OWNER_GID = 0x02, IPT_OWNER_PID = 0x04, IPT_OWNER_SID = 0x08, IPT_OWNER_COMM = 0x10, IP6T_OWNER_UID = IPT_OWNER_UID, IP6T_OWNER_GID = IPT_OWNER_GID, IP6T_OWNER_PID = IPT_OWNER_PID, IP6T_OWNER_SID = IPT_OWNER_SID, IP6T_OWNER_COMM = IPT_OWNER_COMM, }; struct ipt_owner_info { uid_t uid; gid_t gid; pid_t pid; pid_t sid; char comm[16]; uint8_t match, invert; /* flags */ }; struct ip6t_owner_info { uid_t uid; gid_t gid; pid_t pid; pid_t sid; char comm[16]; uint8_t match, invert; /* flags */ }; /* * Note: "UINT32_MAX - 1" is used in the code because -1 is a reserved * UID/GID value anyway. */ enum { O_USER = 0, O_GROUP, O_SOCK_EXISTS, O_PROCESS, O_SESSION, O_COMM, }; static void owner_mt_help_v0(void) { printf( "owner match options:\n" "[!] --uid-owner userid Match local UID\n" "[!] --gid-owner groupid Match local GID\n" "[!] --pid-owner processid Match local PID\n" "[!] --sid-owner sessionid Match local SID\n" "[!] --cmd-owner name Match local command name\n" "NOTE: PID, SID and command matching are broken on SMP\n"); } static void owner_mt6_help_v0(void) { printf( "owner match options:\n" "[!] --uid-owner userid Match local UID\n" "[!] --gid-owner groupid Match local GID\n" "[!] --pid-owner processid Match local PID\n" "[!] --sid-owner sessionid Match local SID\n" "NOTE: PID and SID matching are broken on SMP\n"); } static void owner_mt_help(void) { printf( "owner match options:\n" "[!] --uid-owner userid[-userid] Match local UID\n" "[!] --gid-owner groupid[-groupid] Match local GID\n" "[!] --socket-exists Match if socket exists\n"); } #define s struct ipt_owner_info static const struct xt_option_entry owner_mt_opts_v0[] = { {.name = "uid-owner", .id = O_USER, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, {.name = "gid-owner", .id = O_GROUP, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, {.name = "pid-owner", .id = O_PROCESS, .type = XTTYPE_UINT32, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, pid), .max = INT_MAX}, {.name = "sid-owner", .id = O_SESSION, .type = XTTYPE_UINT32, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, sid), .max = INT_MAX}, {.name = "cmd-owner", .id = O_COMM, .type = XTTYPE_STRING, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, comm)}, XTOPT_TABLEEND, }; #undef s #define s struct ip6t_owner_info static const struct xt_option_entry owner_mt6_opts_v0[] = { {.name = "uid-owner", .id = O_USER, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, {.name = "gid-owner", .id = O_GROUP, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, {.name = "pid-owner", .id = O_PROCESS, .type = XTTYPE_UINT32, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, pid), .max = INT_MAX}, {.name = "sid-owner", .id = O_SESSION, .type = XTTYPE_UINT32, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, sid), .max = INT_MAX}, XTOPT_TABLEEND, }; #undef s static const struct xt_option_entry owner_mt_opts[] = { {.name = "uid-owner", .id = O_USER, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, {.name = "gid-owner", .id = O_GROUP, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, {.name = "socket-exists", .id = O_SOCK_EXISTS, .type = XTTYPE_NONE, .flags = XTOPT_INVERT}, XTOPT_TABLEEND, }; static void owner_mt_parse_v0(struct xt_option_call *cb) { struct ipt_owner_info *info = cb->data; struct passwd *pwd; struct group *grp; unsigned int id; xtables_option_parse(cb); switch (cb->entry->id) { case O_USER: if ((pwd = getpwnam(cb->arg)) != NULL) id = pwd->pw_uid; else if (!xtables_strtoui(cb->arg, NULL, &id, 0, UINT32_MAX - 1)) xtables_param_act(XTF_BAD_VALUE, "owner", "--uid-owner", cb->arg); if (cb->invert) info->invert |= IPT_OWNER_UID; info->match |= IPT_OWNER_UID; info->uid = id; break; case O_GROUP: if ((grp = getgrnam(cb->arg)) != NULL) id = grp->gr_gid; else if (!xtables_strtoui(cb->arg, NULL, &id, 0, UINT32_MAX - 1)) xtables_param_act(XTF_BAD_VALUE, "owner", "--gid-owner", cb->arg); if (cb->invert) info->invert |= IPT_OWNER_GID; info->match |= IPT_OWNER_GID; info->gid = id; break; case O_PROCESS: if (cb->invert) info->invert |= IPT_OWNER_PID; info->match |= IPT_OWNER_PID; break; case O_SESSION: if (cb->invert) info->invert |= IPT_OWNER_SID; info->match |= IPT_OWNER_SID; break; case O_COMM: if (cb->invert) info->invert |= IPT_OWNER_COMM; info->match |= IPT_OWNER_COMM; break; } } static void owner_mt6_parse_v0(struct xt_option_call *cb) { struct ip6t_owner_info *info = cb->data; struct passwd *pwd; struct group *grp; unsigned int id; xtables_option_parse(cb); switch (cb->entry->id) { case O_USER: if ((pwd = getpwnam(cb->arg)) != NULL) id = pwd->pw_uid; else if (!xtables_strtoui(cb->arg, NULL, &id, 0, UINT32_MAX - 1)) xtables_param_act(XTF_BAD_VALUE, "owner", "--uid-owner", cb->arg); if (cb->invert) info->invert |= IP6T_OWNER_UID; info->match |= IP6T_OWNER_UID; info->uid = id; break; case O_GROUP: if ((grp = getgrnam(cb->arg)) != NULL) id = grp->gr_gid; else if (!xtables_strtoui(cb->arg, NULL, &id, 0, UINT32_MAX - 1)) xtables_param_act(XTF_BAD_VALUE, "owner", "--gid-owner", cb->arg); if (cb->invert) info->invert |= IP6T_OWNER_GID; info->match |= IP6T_OWNER_GID; info->gid = id; break; case O_PROCESS: if (cb->invert) info->invert |= IP6T_OWNER_PID; info->match |= IP6T_OWNER_PID; break; case O_SESSION: if (cb->invert) info->invert |= IP6T_OWNER_SID; info->match |= IP6T_OWNER_SID; break; } } static void owner_parse_range(const char *s, unsigned int *from, unsigned int *to, const char *opt) { char *end; /* -1 is reversed, so the max is one less than that. */ if (!xtables_strtoui(s, &end, from, 0, UINT32_MAX - 1)) xtables_param_act(XTF_BAD_VALUE, "owner", opt, s); *to = *from; if (*end == '-' || *end == ':') if (!xtables_strtoui(end + 1, &end, to, 0, UINT32_MAX - 1)) xtables_param_act(XTF_BAD_VALUE, "owner", opt, s); if (*end != '\0') xtables_param_act(XTF_BAD_VALUE, "owner", opt, s); } static void owner_mt_parse(struct xt_option_call *cb) { struct xt_owner_match_info *info = cb->data; struct passwd *pwd; struct group *grp; unsigned int from, to; xtables_option_parse(cb); switch (cb->entry->id) { case O_USER: if ((pwd = getpwnam(cb->arg)) != NULL) from = to = pwd->pw_uid; else owner_parse_range(cb->arg, &from, &to, "--uid-owner"); if (cb->invert) info->invert |= XT_OWNER_UID; info->match |= XT_OWNER_UID; info->uid_min = from; info->uid_max = to; break; case O_GROUP: if ((grp = getgrnam(cb->arg)) != NULL) from = to = grp->gr_gid; else owner_parse_range(cb->arg, &from, &to, "--gid-owner"); if (cb->invert) info->invert |= XT_OWNER_GID; info->match |= XT_OWNER_GID; info->gid_min = from; info->gid_max = to; break; case O_SOCK_EXISTS: if (cb->invert) info->invert |= XT_OWNER_SOCKET; info->match |= XT_OWNER_SOCKET; break; } } static void owner_mt_check(struct xt_fcheck_call *cb) { if (cb->xflags == 0) xtables_error(PARAMETER_PROBLEM, "owner: At least one of " "--uid-owner, --gid-owner or --socket-exists " "is required"); } static void owner_mt_print_item_v0(const struct ipt_owner_info *info, const char *label, uint8_t flag, bool numeric) { if (!(info->match & flag)) return; if (info->invert & flag) printf(" !"); printf(" %s", label); switch (info->match & flag) { case IPT_OWNER_UID: if (!numeric) { struct passwd *pwd = getpwuid(info->uid); if (pwd != NULL && pwd->pw_name != NULL) { printf(" %s", pwd->pw_name); break; } } printf(" %u", (unsigned int)info->uid); break; case IPT_OWNER_GID: if (!numeric) { struct group *grp = getgrgid(info->gid); if (grp != NULL && grp->gr_name != NULL) { printf(" %s", grp->gr_name); break; } } printf(" %u", (unsigned int)info->gid); break; case IPT_OWNER_PID: printf(" %u", (unsigned int)info->pid); break; case IPT_OWNER_SID: printf(" %u", (unsigned int)info->sid); break; case IPT_OWNER_COMM: printf(" %.*s", (int)sizeof(info->comm), info->comm); break; } } static void owner_mt6_print_item_v0(const struct ip6t_owner_info *info, const char *label, uint8_t flag, bool numeric) { if (!(info->match & flag)) return; if (info->invert & flag) printf(" !"); printf(" %s", label); switch (info->match & flag) { case IP6T_OWNER_UID: if (!numeric) { struct passwd *pwd = getpwuid(info->uid); if (pwd != NULL && pwd->pw_name != NULL) { printf(" %s", pwd->pw_name); break; } } printf(" %u", (unsigned int)info->uid); break; case IP6T_OWNER_GID: if (!numeric) { struct group *grp = getgrgid(info->gid); if (grp != NULL && grp->gr_name != NULL) { printf(" %s", grp->gr_name); break; } } printf(" %u", (unsigned int)info->gid); break; case IP6T_OWNER_PID: printf(" %u", (unsigned int)info->pid); break; case IP6T_OWNER_SID: printf(" %u", (unsigned int)info->sid); break; } } static void owner_mt_print_item(const struct xt_owner_match_info *info, const char *label, uint8_t flag, bool numeric) { if (!(info->match & flag)) return; if (info->invert & flag) printf(" !"); printf(" %s", label); switch (info->match & flag) { case XT_OWNER_UID: if (info->uid_min != info->uid_max) { printf(" %u-%u", (unsigned int)info->uid_min, (unsigned int)info->uid_max); break; } else if (!numeric) { const struct passwd *pwd = getpwuid(info->uid_min); if (pwd != NULL && pwd->pw_name != NULL) { printf(" %s", pwd->pw_name); break; } } printf(" %u", (unsigned int)info->uid_min); break; case XT_OWNER_GID: if (info->gid_min != info->gid_max) { printf(" %u-%u", (unsigned int)info->gid_min, (unsigned int)info->gid_max); break; } else if (!numeric) { const struct group *grp = getgrgid(info->gid_min); if (grp != NULL && grp->gr_name != NULL) { printf(" %s", grp->gr_name); break; } } printf(" %u", (unsigned int)info->gid_min); break; } } static void owner_mt_print_v0(const void *ip, const struct xt_entry_match *match, int numeric) { const struct ipt_owner_info *info = (void *)match->data; owner_mt_print_item_v0(info, "owner UID match", IPT_OWNER_UID, numeric); owner_mt_print_item_v0(info, "owner GID match", IPT_OWNER_GID, numeric); owner_mt_print_item_v0(info, "owner PID match", IPT_OWNER_PID, numeric); owner_mt_print_item_v0(info, "owner SID match", IPT_OWNER_SID, numeric); owner_mt_print_item_v0(info, "owner CMD match", IPT_OWNER_COMM, numeric); } static void owner_mt6_print_v0(const void *ip, const struct xt_entry_match *match, int numeric) { const struct ip6t_owner_info *info = (void *)match->data; owner_mt6_print_item_v0(info, "owner UID match", IPT_OWNER_UID, numeric); owner_mt6_print_item_v0(info, "owner GID match", IPT_OWNER_GID, numeric); owner_mt6_print_item_v0(info, "owner PID match", IPT_OWNER_PID, numeric); owner_mt6_print_item_v0(info, "owner SID match", IPT_OWNER_SID, numeric); } static void owner_mt_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_owner_match_info *info = (void *)match->data; owner_mt_print_item(info, "owner socket exists", XT_OWNER_SOCKET, numeric); owner_mt_print_item(info, "owner UID match", XT_OWNER_UID, numeric); owner_mt_print_item(info, "owner GID match", XT_OWNER_GID, numeric); } static void owner_mt_save_v0(const void *ip, const struct xt_entry_match *match) { const struct ipt_owner_info *info = (void *)match->data; owner_mt_print_item_v0(info, "--uid-owner", IPT_OWNER_UID, true); owner_mt_print_item_v0(info, "--gid-owner", IPT_OWNER_GID, true); owner_mt_print_item_v0(info, "--pid-owner", IPT_OWNER_PID, true); owner_mt_print_item_v0(info, "--sid-owner", IPT_OWNER_SID, true); owner_mt_print_item_v0(info, "--cmd-owner", IPT_OWNER_COMM, true); } static void owner_mt6_save_v0(const void *ip, const struct xt_entry_match *match) { const struct ip6t_owner_info *info = (void *)match->data; owner_mt6_print_item_v0(info, "--uid-owner", IPT_OWNER_UID, true); owner_mt6_print_item_v0(info, "--gid-owner", IPT_OWNER_GID, true); owner_mt6_print_item_v0(info, "--pid-owner", IPT_OWNER_PID, true); owner_mt6_print_item_v0(info, "--sid-owner", IPT_OWNER_SID, true); } static void owner_mt_save(const void *ip, const struct xt_entry_match *match) { const struct xt_owner_match_info *info = (void *)match->data; owner_mt_print_item(info, "--socket-exists", XT_OWNER_SOCKET, true); owner_mt_print_item(info, "--uid-owner", XT_OWNER_UID, true); owner_mt_print_item(info, "--gid-owner", XT_OWNER_GID, true); } static struct xtables_match owner_mt_reg[] = { { .version = XTABLES_VERSION, .name = "owner", .revision = 0, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct ipt_owner_info)), .userspacesize = XT_ALIGN(sizeof(struct ipt_owner_info)), .help = owner_mt_help_v0, .x6_parse = owner_mt_parse_v0, .x6_fcheck = owner_mt_check, .print = owner_mt_print_v0, .save = owner_mt_save_v0, .x6_options = owner_mt_opts_v0, }, { .version = XTABLES_VERSION, .name = "owner", .revision = 0, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct ip6t_owner_info)), .userspacesize = XT_ALIGN(sizeof(struct ip6t_owner_info)), .help = owner_mt6_help_v0, .x6_parse = owner_mt6_parse_v0, .x6_fcheck = owner_mt_check, .print = owner_mt6_print_v0, .save = owner_mt6_save_v0, .x6_options = owner_mt6_opts_v0, }, { .version = XTABLES_VERSION, .name = "owner", .revision = 1, .family = NFPROTO_UNSPEC, .size = XT_ALIGN(sizeof(struct xt_owner_match_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_owner_match_info)), .help = owner_mt_help, .x6_parse = owner_mt_parse, .x6_fcheck = owner_mt_check, .print = owner_mt_print, .save = owner_mt_save, .x6_options = owner_mt_opts, }, }; void _init(void) { xtables_register_matches(owner_mt_reg, ARRAY_SIZE(owner_mt_reg)); }
254
./android_firewall/external/iptables/extensions/libipt_ULOG.c
/* Shared library add-on to iptables to add ULOG support. * * (C) 2000 by Harald Welte <[email protected]> * * multipart netlink support based on ideas by Sebastian Zander * <[email protected]> * * This software is released under the terms of GNU GPL * * libipt_ULOG.c,v 1.7 2001/01/30 11:55:02 laforge Exp */ #include <stdio.h> #include <string.h> #include <xtables.h> /* For 64bit kernel / 32bit userspace */ #include <linux/netfilter_ipv4/ipt_ULOG.h> enum { O_ULOG_NLGROUP = 0, O_ULOG_PREFIX, O_ULOG_CPRANGE, O_ULOG_QTHR, }; static void ULOG_help(void) { printf("ULOG target options:\n" " --ulog-nlgroup nlgroup NETLINK group used for logging\n" " --ulog-cprange size Bytes of each packet to be passed\n" " --ulog-qthreshold Threshold of in-kernel queue\n" " --ulog-prefix prefix Prefix log messages with this prefix.\n"); } static const struct xt_option_entry ULOG_opts[] = { {.name = "ulog-nlgroup", .id = O_ULOG_NLGROUP, .type = XTTYPE_UINT8, .min = 1, .max = 32}, {.name = "ulog-prefix", .id = O_ULOG_PREFIX, .type = XTTYPE_STRING, .flags = XTOPT_PUT, XTOPT_POINTER(struct ipt_ulog_info, prefix), .min = 1}, {.name = "ulog-cprange", .id = O_ULOG_CPRANGE, .type = XTTYPE_UINT64}, {.name = "ulog-qthreshold", .id = O_ULOG_QTHR, .type = XTTYPE_UINT64, .min = 1, .max = ULOG_MAX_QLEN}, XTOPT_TABLEEND, }; static void ULOG_init(struct xt_entry_target *t) { struct ipt_ulog_info *loginfo = (struct ipt_ulog_info *) t->data; loginfo->nl_group = ULOG_DEFAULT_NLGROUP; loginfo->qthreshold = ULOG_DEFAULT_QTHRESHOLD; } static void ULOG_parse(struct xt_option_call *cb) { struct ipt_ulog_info *loginfo = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_ULOG_NLGROUP: loginfo->nl_group = 1 << (cb->val.u8 - 1); break; case O_ULOG_PREFIX: if (strchr(cb->arg, '\n') != NULL) xtables_error(PARAMETER_PROBLEM, "Newlines not allowed in --ulog-prefix"); break; case O_ULOG_CPRANGE: loginfo->copy_range = cb->val.u64; break; case O_ULOG_QTHR: loginfo->qthreshold = cb->val.u64; break; } } static void ULOG_save(const void *ip, const struct xt_entry_target *target) { const struct ipt_ulog_info *loginfo = (const struct ipt_ulog_info *) target->data; if (strcmp(loginfo->prefix, "") != 0) { fputs(" --ulog-prefix", stdout); xtables_save_string(loginfo->prefix); } if (loginfo->nl_group != ULOG_DEFAULT_NLGROUP) printf(" --ulog-nlgroup %d", ffs(loginfo->nl_group)); if (loginfo->copy_range) printf(" --ulog-cprange %u", (unsigned int)loginfo->copy_range); if (loginfo->qthreshold != ULOG_DEFAULT_QTHRESHOLD) printf(" --ulog-qthreshold %u", (unsigned int)loginfo->qthreshold); } static void ULOG_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct ipt_ulog_info *loginfo = (const struct ipt_ulog_info *) target->data; printf(" ULOG "); printf("copy_range %u nlgroup %d", (unsigned int)loginfo->copy_range, ffs(loginfo->nl_group)); if (strcmp(loginfo->prefix, "") != 0) printf(" prefix \"%s\"", loginfo->prefix); printf(" queue_threshold %u", (unsigned int)loginfo->qthreshold); } static struct xtables_target ulog_tg_reg = { .name = "ULOG", .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct ipt_ulog_info)), .userspacesize = XT_ALIGN(sizeof(struct ipt_ulog_info)), .help = ULOG_help, .init = ULOG_init, .print = ULOG_print, .save = ULOG_save, .x6_parse = ULOG_parse, .x6_options = ULOG_opts, }; void _init(void) { xtables_register_target(&ulog_tg_reg); }
255
./android_firewall/external/iptables/extensions/libipt_NETMAP.c
/* Shared library add-on to iptables to add static NAT support. Author: Svenning Soerensen <[email protected]> */ #include <stdio.h> #include <netdb.h> #include <string.h> #include <stdlib.h> #include <getopt.h> #include <xtables.h> #include <net/netfilter/nf_nat.h> #define MODULENAME "NETMAP" enum { O_TO = 0, }; static const struct xt_option_entry NETMAP_opts[] = { {.name = "to", .id = O_TO, .type = XTTYPE_HOSTMASK, .flags = XTOPT_MAND}, XTOPT_TABLEEND, }; static void NETMAP_help(void) { printf(MODULENAME" target options:\n" " --%s address[/mask]\n" " Network address to map to.\n\n", NETMAP_opts[0].name); } static int netmask2bits(uint32_t netmask) { uint32_t bm; int bits; netmask = ntohl(netmask); for (bits = 0, bm = 0x80000000; netmask & bm; netmask <<= 1) bits++; if (netmask) return -1; /* holes in netmask */ return bits; } static void NETMAP_init(struct xt_entry_target *t) { struct nf_nat_multi_range *mr = (struct nf_nat_multi_range *)t->data; /* Actually, it's 0, but it's ignored at the moment. */ mr->rangesize = 1; } static void NETMAP_parse(struct xt_option_call *cb) { struct nf_nat_multi_range *mr = cb->data; struct nf_nat_range *range = &mr->range[0]; xtables_option_parse(cb); range->flags |= IP_NAT_RANGE_MAP_IPS; range->min_ip = cb->val.haddr.ip & cb->val.hmask.ip; range->max_ip = range->min_ip | ~cb->val.hmask.ip; } static void NETMAP_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct nf_nat_multi_range *mr = (const void *)target->data; const struct nf_nat_range *r = &mr->range[0]; struct in_addr a; int bits; a.s_addr = r->min_ip; printf("%s", xtables_ipaddr_to_numeric(&a)); a.s_addr = ~(r->min_ip ^ r->max_ip); bits = netmask2bits(a.s_addr); if (bits < 0) printf("/%s", xtables_ipaddr_to_numeric(&a)); else printf("/%d", bits); } static void NETMAP_save(const void *ip, const struct xt_entry_target *target) { printf(" --%s ", NETMAP_opts[0].name); NETMAP_print(ip, target, 0); } static struct xtables_target netmap_tg_reg = { .name = MODULENAME, .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct nf_nat_multi_range)), .userspacesize = XT_ALIGN(sizeof(struct nf_nat_multi_range)), .help = NETMAP_help, .init = NETMAP_init, .x6_parse = NETMAP_parse, .print = NETMAP_print, .save = NETMAP_save, .x6_options = NETMAP_opts, }; void _init(void) { xtables_register_target(&netmap_tg_reg); }
256
./android_firewall/external/iptables/extensions/libip6t_eui64.c
/* Shared library add-on to ip6tables to add EUI64 address checking support. */ #include <xtables.h> static struct xtables_match eui64_mt6_reg = { .name = "eui64", .version = XTABLES_VERSION, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(int)), .userspacesize = XT_ALIGN(sizeof(int)), }; void _init(void) { xtables_register_match(&eui64_mt6_reg); }
257
./android_firewall/external/iptables/extensions/libxt_CLASSIFY.c
#include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_CLASSIFY.h> #include <linux/pkt_sched.h> enum { O_SET_CLASS = 0, }; static void CLASSIFY_help(void) { printf( "CLASSIFY target options:\n" "--set-class MAJOR:MINOR Set skb->priority value (always hexadecimal!)\n"); } static const struct xt_option_entry CLASSIFY_opts[] = { {.name = "set-class", .id = O_SET_CLASS, .type = XTTYPE_STRING, .flags = XTOPT_MAND}, XTOPT_TABLEEND, }; static int CLASSIFY_string_to_priority(const char *s, unsigned int *p) { unsigned int i, j; if (sscanf(s, "%x:%x", &i, &j) != 2) return 1; *p = TC_H_MAKE(i<<16, j); return 0; } static void CLASSIFY_parse(struct xt_option_call *cb) { struct xt_classify_target_info *clinfo = cb->data; xtables_option_parse(cb); if (CLASSIFY_string_to_priority(cb->arg, &clinfo->priority)) xtables_error(PARAMETER_PROBLEM, "Bad class value \"%s\"", cb->arg); } static void CLASSIFY_print_class(unsigned int priority, int numeric) { printf(" %x:%x", TC_H_MAJ(priority)>>16, TC_H_MIN(priority)); } static void CLASSIFY_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_classify_target_info *clinfo = (const struct xt_classify_target_info *)target->data; printf(" CLASSIFY set"); CLASSIFY_print_class(clinfo->priority, numeric); } static void CLASSIFY_save(const void *ip, const struct xt_entry_target *target) { const struct xt_classify_target_info *clinfo = (const struct xt_classify_target_info *)target->data; printf(" --set-class %.4x:%.4x", TC_H_MAJ(clinfo->priority)>>16, TC_H_MIN(clinfo->priority)); } static struct xtables_target classify_target = { .family = NFPROTO_UNSPEC, .name = "CLASSIFY", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_classify_target_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_classify_target_info)), .help = CLASSIFY_help, .print = CLASSIFY_print, .save = CLASSIFY_save, .x6_parse = CLASSIFY_parse, .x6_options = CLASSIFY_opts, }; void _init(void) { xtables_register_target(&classify_target); }
258
./android_firewall/external/iptables/extensions/libip6t_REJECT.c
/* Shared library add-on to ip6tables to add customized REJECT support. * * (C) 2000 Jozsef Kadlecsik <[email protected]> * * ported to IPv6 by Harald Welte <[email protected]> * */ #include <stdio.h> #include <string.h> #include <xtables.h> #include <linux/netfilter_ipv6/ip6t_REJECT.h> struct reject_names { const char *name; const char *alias; enum ip6t_reject_with with; const char *desc; }; enum { O_REJECT_WITH = 0, }; static const struct reject_names reject_table[] = { {"icmp6-no-route", "no-route", IP6T_ICMP6_NO_ROUTE, "ICMPv6 no route"}, {"icmp6-adm-prohibited", "adm-prohibited", IP6T_ICMP6_ADM_PROHIBITED, "ICMPv6 administratively prohibited"}, #if 0 {"icmp6-not-neighbor", "not-neighbor"}, IP6T_ICMP6_NOT_NEIGHBOR, "ICMPv6 not a neighbor"}, #endif {"icmp6-addr-unreachable", "addr-unreach", IP6T_ICMP6_ADDR_UNREACH, "ICMPv6 address unreachable"}, {"icmp6-port-unreachable", "port-unreach", IP6T_ICMP6_PORT_UNREACH, "ICMPv6 port unreachable"}, {"tcp-reset", "tcp-reset", IP6T_TCP_RESET, "TCP RST packet"} }; static void print_reject_types(void) { unsigned int i; printf("Valid reject types:\n"); for (i = 0; i < ARRAY_SIZE(reject_table); ++i) { printf(" %-25s\t%s\n", reject_table[i].name, reject_table[i].desc); printf(" %-25s\talias\n", reject_table[i].alias); } printf("\n"); } static void REJECT_help(void) { printf( "REJECT target options:\n" "--reject-with type drop input packet and send back\n" " a reply packet according to type:\n"); print_reject_types(); } static const struct xt_option_entry REJECT_opts[] = { {.name = "reject-with", .id = O_REJECT_WITH, .type = XTTYPE_STRING}, XTOPT_TABLEEND, }; static void REJECT_init(struct xt_entry_target *t) { struct ip6t_reject_info *reject = (struct ip6t_reject_info *)t->data; /* default */ reject->with = IP6T_ICMP6_PORT_UNREACH; } static void REJECT_parse(struct xt_option_call *cb) { struct ip6t_reject_info *reject = cb->data; unsigned int i; xtables_option_parse(cb); for (i = 0; i < ARRAY_SIZE(reject_table); ++i) if (strncasecmp(reject_table[i].name, cb->arg, strlen(cb->arg)) == 0 || strncasecmp(reject_table[i].alias, cb->arg, strlen(cb->arg)) == 0) { reject->with = reject_table[i].with; return; } xtables_error(PARAMETER_PROBLEM, "unknown reject type \"%s\"", cb->arg); } static void REJECT_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct ip6t_reject_info *reject = (const struct ip6t_reject_info *)target->data; unsigned int i; for (i = 0; i < ARRAY_SIZE(reject_table); ++i) if (reject_table[i].with == reject->with) break; printf(" reject-with %s", reject_table[i].name); } static void REJECT_save(const void *ip, const struct xt_entry_target *target) { const struct ip6t_reject_info *reject = (const struct ip6t_reject_info *)target->data; unsigned int i; for (i = 0; i < ARRAY_SIZE(reject_table); ++i) if (reject_table[i].with == reject->with) break; printf(" --reject-with %s", reject_table[i].name); } static struct xtables_target reject_tg6_reg = { .name = "REJECT", .version = XTABLES_VERSION, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct ip6t_reject_info)), .userspacesize = XT_ALIGN(sizeof(struct ip6t_reject_info)), .help = REJECT_help, .init = REJECT_init, .print = REJECT_print, .save = REJECT_save, .x6_parse = REJECT_parse, .x6_options = REJECT_opts, }; void _init(void) { xtables_register_target(&reject_tg6_reg); }
259
./android_firewall/external/iptables/extensions/libxt_LED.c
/* * libxt_LED.c - shared library add-on to iptables to add customized LED * trigger support. * * (C) 2008 Adam Nielsen <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <xtables.h> #include <linux/netfilter/xt_LED.h> enum { O_LED_TRIGGER_ID = 0, O_LED_DELAY, O_LED_ALWAYS_BLINK, }; #define s struct xt_led_info static const struct xt_option_entry LED_opts[] = { {.name = "led-trigger-id", .id = O_LED_TRIGGER_ID, .flags = XTOPT_MAND, .type = XTTYPE_STRING, .min = 0, .max = sizeof(((struct xt_led_info *)NULL)->id) - sizeof("netfilter-")}, {.name = "led-delay", .id = O_LED_DELAY, .type = XTTYPE_STRING}, {.name = "led-always-blink", .id = O_LED_ALWAYS_BLINK, .type = XTTYPE_NONE}, XTOPT_TABLEEND, }; #undef s static void LED_help(void) { printf( "LED target options:\n" "--led-trigger-id name suffix for led trigger name\n" "--led-delay ms leave the LED on for this number of\n" " milliseconds after triggering.\n" "--led-always-blink blink on arriving packets, even if\n" " the LED is already on.\n" ); } static void LED_parse(struct xt_option_call *cb) { struct xt_led_info *led = cb->data; unsigned int delay; xtables_option_parse(cb); switch (cb->entry->id) { case O_LED_TRIGGER_ID: strcpy(led->id, "netfilter-"); strcat(led->id, cb->arg); break; case O_LED_DELAY: if (strncasecmp(cb->arg, "inf", 3) == 0) led->delay = -1; else if (!xtables_strtoui(cb->arg, NULL, &delay, 0, UINT32_MAX)) xtables_error(PARAMETER_PROBLEM, "Delay value must be within range 0..%u", UINT32_MAX); break; case O_LED_ALWAYS_BLINK: led->always_blink = 1; break; } } static void LED_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_led_info *led = (void *)target->data; const char *id = led->id + strlen("netfilter-"); /* trim off prefix */ printf(" led-trigger-id:\""); /* Escape double quotes and backslashes in the ID */ while (*id != '\0') { if (*id == '"' || *id == '\\') printf("\\"); printf("%c", *id++); } printf("\""); if (led->delay == -1) printf(" led-delay:inf"); else printf(" led-delay:%dms", led->delay); if (led->always_blink) printf(" led-always-blink"); } static void LED_save(const void *ip, const struct xt_entry_target *target) { const struct xt_led_info *led = (void *)target->data; const char *id = led->id + strlen("netfilter-"); /* trim off prefix */ printf(" --led-trigger-id \""); /* Escape double quotes and backslashes in the ID */ while (*id != '\0') { if (*id == '"' || *id == '\\') printf("\\"); printf("%c", *id++); } printf("\""); /* Only print the delay if it's not zero (the default) */ if (led->delay > 0) printf(" --led-delay %d", led->delay); else if (led->delay == -1) printf(" --led-delay inf"); /* Only print always_blink if it's not set to the default */ if (led->always_blink) printf(" --led-always-blink"); } static struct xtables_target led_tg_reg = { .version = XTABLES_VERSION, .name = "LED", .family = PF_UNSPEC, .revision = 0, .size = XT_ALIGN(sizeof(struct xt_led_info)), .userspacesize = offsetof(struct xt_led_info, internal_data), .help = LED_help, .print = LED_print, .save = LED_save, .x6_parse = LED_parse, .x6_options = LED_opts, }; void _init(void) { xtables_register_target(&led_tg_reg); }
260
./android_firewall/external/iptables/extensions/libip6t_icmp6.c
#include <stdint.h> #include <stdio.h> #include <string.h> #include <xtables.h> #include <limits.h> /* INT_MAX in ip6_tables.h */ #include <linux/netfilter_ipv6/ip6_tables.h> enum { O_ICMPV6_TYPE = 0, }; struct icmpv6_names { const char *name; uint8_t type; uint8_t code_min, code_max; }; static const struct icmpv6_names icmpv6_codes[] = { { "destination-unreachable", 1, 0, 0xFF }, { "no-route", 1, 0, 0 }, { "communication-prohibited", 1, 1, 1 }, { "address-unreachable", 1, 3, 3 }, { "port-unreachable", 1, 4, 4 }, { "packet-too-big", 2, 0, 0xFF }, { "time-exceeded", 3, 0, 0xFF }, /* Alias */ { "ttl-exceeded", 3, 0, 0xFF }, { "ttl-zero-during-transit", 3, 0, 0 }, { "ttl-zero-during-reassembly", 3, 1, 1 }, { "parameter-problem", 4, 0, 0xFF }, { "bad-header", 4, 0, 0 }, { "unknown-header-type", 4, 1, 1 }, { "unknown-option", 4, 2, 2 }, { "echo-request", 128, 0, 0xFF }, /* Alias */ { "ping", 128, 0, 0xFF }, { "echo-reply", 129, 0, 0xFF }, /* Alias */ { "pong", 129, 0, 0xFF }, { "router-solicitation", 133, 0, 0xFF }, { "router-advertisement", 134, 0, 0xFF }, { "neighbour-solicitation", 135, 0, 0xFF }, /* Alias */ { "neighbor-solicitation", 135, 0, 0xFF }, { "neighbour-advertisement", 136, 0, 0xFF }, /* Alias */ { "neighbor-advertisement", 136, 0, 0xFF }, { "redirect", 137, 0, 0xFF }, }; static void print_icmpv6types(void) { unsigned int i; printf("Valid ICMPv6 Types:"); for (i = 0; i < ARRAY_SIZE(icmpv6_codes); ++i) { if (i && icmpv6_codes[i].type == icmpv6_codes[i-1].type) { if (icmpv6_codes[i].code_min == icmpv6_codes[i-1].code_min && (icmpv6_codes[i].code_max == icmpv6_codes[i-1].code_max)) printf(" (%s)", icmpv6_codes[i].name); else printf("\n %s", icmpv6_codes[i].name); } else printf("\n%s", icmpv6_codes[i].name); } printf("\n"); } static void icmp6_help(void) { printf( "icmpv6 match options:\n" "[!] --icmpv6-type typename match icmpv6 type\n" " (or numeric type or type/code)\n"); print_icmpv6types(); } static const struct xt_option_entry icmp6_opts[] = { {.name = "icmpv6-type", .id = O_ICMPV6_TYPE, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_INVERT}, XTOPT_TABLEEND, }; static void parse_icmpv6(const char *icmpv6type, uint8_t *type, uint8_t code[]) { static const unsigned int limit = ARRAY_SIZE(icmpv6_codes); unsigned int match = limit; unsigned int i; for (i = 0; i < limit; i++) { if (strncasecmp(icmpv6_codes[i].name, icmpv6type, strlen(icmpv6type)) == 0) { if (match != limit) xtables_error(PARAMETER_PROBLEM, "Ambiguous ICMPv6 type `%s':" " `%s' or `%s'?", icmpv6type, icmpv6_codes[match].name, icmpv6_codes[i].name); match = i; } } if (match != limit) { *type = icmpv6_codes[match].type; code[0] = icmpv6_codes[match].code_min; code[1] = icmpv6_codes[match].code_max; } else { char *slash; char buffer[strlen(icmpv6type) + 1]; unsigned int number; strcpy(buffer, icmpv6type); slash = strchr(buffer, '/'); if (slash) *slash = '\0'; if (!xtables_strtoui(buffer, NULL, &number, 0, UINT8_MAX)) xtables_error(PARAMETER_PROBLEM, "Invalid ICMPv6 type `%s'\n", buffer); *type = number; if (slash) { if (!xtables_strtoui(slash+1, NULL, &number, 0, UINT8_MAX)) xtables_error(PARAMETER_PROBLEM, "Invalid ICMPv6 code `%s'\n", slash+1); code[0] = code[1] = number; } else { code[0] = 0; code[1] = 0xFF; } } } static void icmp6_init(struct xt_entry_match *m) { struct ip6t_icmp *icmpv6info = (struct ip6t_icmp *)m->data; icmpv6info->code[1] = 0xFF; } static void icmp6_parse(struct xt_option_call *cb) { struct ip6t_icmp *icmpv6info = cb->data; xtables_option_parse(cb); parse_icmpv6(cb->arg, &icmpv6info->type, icmpv6info->code); if (cb->invert) icmpv6info->invflags |= IP6T_ICMP_INV; } static void print_icmpv6type(uint8_t type, uint8_t code_min, uint8_t code_max, int invert, int numeric) { if (!numeric) { unsigned int i; for (i = 0; i < ARRAY_SIZE(icmpv6_codes); ++i) if (icmpv6_codes[i].type == type && icmpv6_codes[i].code_min == code_min && icmpv6_codes[i].code_max == code_max) break; if (i != ARRAY_SIZE(icmpv6_codes)) { printf(" %s%s", invert ? "!" : "", icmpv6_codes[i].name); return; } } if (invert) printf(" !"); printf("type %u", type); if (code_min == code_max) printf(" code %u", code_min); else if (code_min != 0 || code_max != 0xFF) printf(" codes %u-%u", code_min, code_max); } static void icmp6_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct ip6t_icmp *icmpv6 = (struct ip6t_icmp *)match->data; printf(" ipv6-icmp"); print_icmpv6type(icmpv6->type, icmpv6->code[0], icmpv6->code[1], icmpv6->invflags & IP6T_ICMP_INV, numeric); if (icmpv6->invflags & ~IP6T_ICMP_INV) printf(" Unknown invflags: 0x%X", icmpv6->invflags & ~IP6T_ICMP_INV); } static void icmp6_save(const void *ip, const struct xt_entry_match *match) { const struct ip6t_icmp *icmpv6 = (struct ip6t_icmp *)match->data; if (icmpv6->invflags & IP6T_ICMP_INV) printf(" !"); printf(" --icmpv6-type %u", icmpv6->type); if (icmpv6->code[0] != 0 || icmpv6->code[1] != 0xFF) printf("/%u", icmpv6->code[0]); } static struct xtables_match icmp6_mt6_reg = { .name = "icmp6", .version = XTABLES_VERSION, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct ip6t_icmp)), .userspacesize = XT_ALIGN(sizeof(struct ip6t_icmp)), .help = icmp6_help, .init = icmp6_init, .print = icmp6_print, .save = icmp6_save, .x6_parse = icmp6_parse, .x6_options = icmp6_opts, }; void _init(void) { xtables_register_match(&icmp6_mt6_reg); }
261
./android_firewall/external/iptables/extensions/libxt_sctp.c
/* Shared library add-on to iptables for SCTP matching * * (C) 2003 by Harald Welte <[email protected]> * * This program is distributed under the terms of GNU GPL v2, 1991 * * libipt_ecn.c borrowed heavily from libipt_dscp.c * */ #include <stdbool.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <getopt.h> #include <netdb.h> #include <ctype.h> #include <netinet/in.h> #include <xtables.h> #include <linux/netfilter/xt_sctp.h> #if 0 #define DEBUGP(format, first...) printf(format, ##first) #define static #else #define DEBUGP(format, fist...) #endif static void print_chunk(uint32_t chunknum, int numeric); static void sctp_init(struct xt_entry_match *m) { int i; struct xt_sctp_info *einfo = (struct xt_sctp_info *)m->data; for (i = 0; i < XT_NUM_SCTP_FLAGS; i++) { einfo->flag_info[i].chunktype = -1; } } static void sctp_help(void) { printf( "sctp match options\n" "[!] --source-port port[:port] match source port(s)\n" " --sport ...\n" "[!] --destination-port port[:port] match destination port(s)\n" " --dport ...\n" "[!] --chunk-types (all|any|none) (chunktype[:flags])+ match if all, any or none of\n" " chunktypes are present\n" "chunktypes - DATA INIT INIT_ACK SACK HEARTBEAT HEARTBEAT_ACK ABORT SHUTDOWN SHUTDOWN_ACK ERROR COOKIE_ECHO COOKIE_ACK ECN_ECNE ECN_CWR SHUTDOWN_COMPLETE ASCONF ASCONF_ACK FORWARD_TSN ALL NONE\n"); } static const struct option sctp_opts[] = { {.name = "source-port", .has_arg = true, .val = '1'}, {.name = "sport", .has_arg = true, .val = '1'}, {.name = "destination-port", .has_arg = true, .val = '2'}, {.name = "dport", .has_arg = true, .val = '2'}, {.name = "chunk-types", .has_arg = true, .val = '3'}, XT_GETOPT_TABLEEND, }; static void parse_sctp_ports(const char *portstring, uint16_t *ports) { char *buffer; char *cp; buffer = strdup(portstring); DEBUGP("%s\n", portstring); if ((cp = strchr(buffer, ':')) == NULL) { ports[0] = ports[1] = xtables_parse_port(buffer, "sctp"); } else { *cp = '\0'; cp++; ports[0] = buffer[0] ? xtables_parse_port(buffer, "sctp") : 0; ports[1] = cp[0] ? xtables_parse_port(cp, "sctp") : 0xFFFF; if (ports[0] > ports[1]) xtables_error(PARAMETER_PROBLEM, "invalid portrange (min > max)"); } free(buffer); } struct sctp_chunk_names { const char *name; unsigned int chunk_type; const char *valid_flags; }; /*'ALL' and 'NONE' will be treated specially. */ static const struct sctp_chunk_names sctp_chunk_names[] = { { .name = "DATA", .chunk_type = 0, .valid_flags = "----IUBE"}, { .name = "INIT", .chunk_type = 1, .valid_flags = "--------"}, { .name = "INIT_ACK", .chunk_type = 2, .valid_flags = "--------"}, { .name = "SACK", .chunk_type = 3, .valid_flags = "--------"}, { .name = "HEARTBEAT", .chunk_type = 4, .valid_flags = "--------"}, { .name = "HEARTBEAT_ACK", .chunk_type = 5, .valid_flags = "--------"}, { .name = "ABORT", .chunk_type = 6, .valid_flags = "-------T"}, { .name = "SHUTDOWN", .chunk_type = 7, .valid_flags = "--------"}, { .name = "SHUTDOWN_ACK", .chunk_type = 8, .valid_flags = "--------"}, { .name = "ERROR", .chunk_type = 9, .valid_flags = "--------"}, { .name = "COOKIE_ECHO", .chunk_type = 10, .valid_flags = "--------"}, { .name = "COOKIE_ACK", .chunk_type = 11, .valid_flags = "--------"}, { .name = "ECN_ECNE", .chunk_type = 12, .valid_flags = "--------"}, { .name = "ECN_CWR", .chunk_type = 13, .valid_flags = "--------"}, { .name = "SHUTDOWN_COMPLETE", .chunk_type = 14, .valid_flags = "-------T"}, { .name = "ASCONF", .chunk_type = 193, .valid_flags = "--------"}, { .name = "ASCONF_ACK", .chunk_type = 128, .valid_flags = "--------"}, { .name = "FORWARD_TSN", .chunk_type = 192, .valid_flags = "--------"}, }; static void save_chunk_flag_info(struct xt_sctp_flag_info *flag_info, int *flag_count, int chunktype, int bit, int set) { int i; for (i = 0; i < *flag_count; i++) { if (flag_info[i].chunktype == chunktype) { DEBUGP("Previous match found\n"); flag_info[i].chunktype = chunktype; flag_info[i].flag_mask |= (1 << bit); if (set) { flag_info[i].flag |= (1 << bit); } return; } } if (*flag_count == XT_NUM_SCTP_FLAGS) { xtables_error (PARAMETER_PROBLEM, "Number of chunk types with flags exceeds currently allowed limit." "Increasing this limit involves changing IPT_NUM_SCTP_FLAGS and" "recompiling both the kernel space and user space modules\n"); } flag_info[*flag_count].chunktype = chunktype; flag_info[*flag_count].flag_mask |= (1 << bit); if (set) { flag_info[*flag_count].flag |= (1 << bit); } (*flag_count)++; } static void parse_sctp_chunk(struct xt_sctp_info *einfo, const char *chunks) { char *ptr; char *buffer; unsigned int i, j; int found = 0; char *chunk_flags; buffer = strdup(chunks); DEBUGP("Buffer: %s\n", buffer); SCTP_CHUNKMAP_RESET(einfo->chunkmap); if (!strcasecmp(buffer, "ALL")) { SCTP_CHUNKMAP_SET_ALL(einfo->chunkmap); goto out; } if (!strcasecmp(buffer, "NONE")) { SCTP_CHUNKMAP_RESET(einfo->chunkmap); goto out; } for (ptr = strtok(buffer, ","); ptr; ptr = strtok(NULL, ",")) { found = 0; DEBUGP("Next Chunk type %s\n", ptr); if ((chunk_flags = strchr(ptr, ':')) != NULL) { *chunk_flags++ = 0; } for (i = 0; i < ARRAY_SIZE(sctp_chunk_names); ++i) if (strcasecmp(sctp_chunk_names[i].name, ptr) == 0) { DEBUGP("Chunk num %d\n", sctp_chunk_names[i].chunk_type); SCTP_CHUNKMAP_SET(einfo->chunkmap, sctp_chunk_names[i].chunk_type); found = 1; break; } if (!found) xtables_error(PARAMETER_PROBLEM, "Unknown sctp chunk `%s'", ptr); if (chunk_flags) { DEBUGP("Chunk flags %s\n", chunk_flags); for (j = 0; j < strlen(chunk_flags); j++) { char *p; int bit; if ((p = strchr(sctp_chunk_names[i].valid_flags, toupper(chunk_flags[j]))) != NULL) { bit = p - sctp_chunk_names[i].valid_flags; bit = 7 - bit; save_chunk_flag_info(einfo->flag_info, &(einfo->flag_count), i, bit, isupper(chunk_flags[j])); } else { xtables_error(PARAMETER_PROBLEM, "Invalid flags for chunk type %d\n", i); } } } } out: free(buffer); } static void parse_sctp_chunks(struct xt_sctp_info *einfo, const char *match_type, const char *chunks) { DEBUGP("Match type: %s Chunks: %s\n", match_type, chunks); if (!strcasecmp(match_type, "ANY")) { einfo->chunk_match_type = SCTP_CHUNK_MATCH_ANY; } else if (!strcasecmp(match_type, "ALL")) { einfo->chunk_match_type = SCTP_CHUNK_MATCH_ALL; } else if (!strcasecmp(match_type, "ONLY")) { einfo->chunk_match_type = SCTP_CHUNK_MATCH_ONLY; } else { xtables_error (PARAMETER_PROBLEM, "Match type has to be one of \"ALL\", \"ANY\" or \"ONLY\""); } SCTP_CHUNKMAP_RESET(einfo->chunkmap); parse_sctp_chunk(einfo, chunks); } static int sctp_parse(int c, char **argv, int invert, unsigned int *flags, const void *entry, struct xt_entry_match **match) { struct xt_sctp_info *einfo = (struct xt_sctp_info *)(*match)->data; switch (c) { case '1': if (*flags & XT_SCTP_SRC_PORTS) xtables_error(PARAMETER_PROBLEM, "Only one `--source-port' allowed"); einfo->flags |= XT_SCTP_SRC_PORTS; parse_sctp_ports(optarg, einfo->spts); if (invert) einfo->invflags |= XT_SCTP_SRC_PORTS; *flags |= XT_SCTP_SRC_PORTS; break; case '2': if (*flags & XT_SCTP_DEST_PORTS) xtables_error(PARAMETER_PROBLEM, "Only one `--destination-port' allowed"); einfo->flags |= XT_SCTP_DEST_PORTS; parse_sctp_ports(optarg, einfo->dpts); if (invert) einfo->invflags |= XT_SCTP_DEST_PORTS; *flags |= XT_SCTP_DEST_PORTS; break; case '3': if (*flags & XT_SCTP_CHUNK_TYPES) xtables_error(PARAMETER_PROBLEM, "Only one `--chunk-types' allowed"); if (!argv[optind] || argv[optind][0] == '-' || argv[optind][0] == '!') xtables_error(PARAMETER_PROBLEM, "--chunk-types requires two args"); einfo->flags |= XT_SCTP_CHUNK_TYPES; parse_sctp_chunks(einfo, optarg, argv[optind]); if (invert) einfo->invflags |= XT_SCTP_CHUNK_TYPES; optind++; *flags |= XT_SCTP_CHUNK_TYPES; break; } return 1; } static const char * port_to_service(int port) { const struct servent *service; if ((service = getservbyport(htons(port), "sctp"))) return service->s_name; return NULL; } static void print_port(uint16_t port, int numeric) { const char *service; if (numeric || (service = port_to_service(port)) == NULL) printf("%u", port); else printf("%s", service); } static void print_ports(const char *name, uint16_t min, uint16_t max, int invert, int numeric) { const char *inv = invert ? "!" : ""; if (min != 0 || max != 0xFFFF || invert) { printf(" %s", name); if (min == max) { printf(":%s", inv); print_port(min, numeric); } else { printf("s:%s", inv); print_port(min, numeric); printf(":"); print_port(max, numeric); } } } static void print_chunk_flags(uint32_t chunknum, uint8_t chunk_flags, uint8_t chunk_flags_mask) { int i; DEBUGP("type: %d\tflags: %x\tflag mask: %x\n", chunknum, chunk_flags, chunk_flags_mask); if (chunk_flags_mask) { printf(":"); } for (i = 7; i >= 0; i--) { if (chunk_flags_mask & (1 << i)) { if (chunk_flags & (1 << i)) { printf("%c", sctp_chunk_names[chunknum].valid_flags[7-i]); } else { printf("%c", tolower(sctp_chunk_names[chunknum].valid_flags[7-i])); } } } } static void print_chunk(uint32_t chunknum, int numeric) { if (numeric) { printf("0x%04X", chunknum); } else { int i; for (i = 0; i < ARRAY_SIZE(sctp_chunk_names); ++i) if (sctp_chunk_names[i].chunk_type == chunknum) printf("%s", sctp_chunk_names[chunknum].name); } } static void print_chunks(const struct xt_sctp_info *einfo, int numeric) { uint32_t chunk_match_type = einfo->chunk_match_type; const struct xt_sctp_flag_info *flag_info = einfo->flag_info; int flag_count = einfo->flag_count; int i, j; int flag; switch (chunk_match_type) { case SCTP_CHUNK_MATCH_ANY: printf(" any"); break; case SCTP_CHUNK_MATCH_ALL: printf(" all"); break; case SCTP_CHUNK_MATCH_ONLY: printf(" only"); break; default: printf("Never reach here\n"); break; } if (SCTP_CHUNKMAP_IS_CLEAR(einfo->chunkmap)) { printf(" NONE"); goto out; } if (SCTP_CHUNKMAP_IS_ALL_SET(einfo->chunkmap)) { printf(" ALL"); goto out; } flag = 0; for (i = 0; i < 256; i++) { if (SCTP_CHUNKMAP_IS_SET(einfo->chunkmap, i)) { if (flag) printf(","); else putchar(' '); flag = 1; print_chunk(i, numeric); for (j = 0; j < flag_count; j++) { if (flag_info[j].chunktype == i) { print_chunk_flags(i, flag_info[j].flag, flag_info[j].flag_mask); } } } } out: return; } static void sctp_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_sctp_info *einfo = (const struct xt_sctp_info *)match->data; printf(" sctp"); if (einfo->flags & XT_SCTP_SRC_PORTS) { print_ports("spt", einfo->spts[0], einfo->spts[1], einfo->invflags & XT_SCTP_SRC_PORTS, numeric); } if (einfo->flags & XT_SCTP_DEST_PORTS) { print_ports("dpt", einfo->dpts[0], einfo->dpts[1], einfo->invflags & XT_SCTP_DEST_PORTS, numeric); } if (einfo->flags & XT_SCTP_CHUNK_TYPES) { /* FIXME: print_chunks() is used in save() where the printing of '!' s taken care of, so we need to do that here as well */ if (einfo->invflags & XT_SCTP_CHUNK_TYPES) { printf(" !"); } print_chunks(einfo, numeric); } } static void sctp_save(const void *ip, const struct xt_entry_match *match) { const struct xt_sctp_info *einfo = (const struct xt_sctp_info *)match->data; if (einfo->flags & XT_SCTP_SRC_PORTS) { if (einfo->invflags & XT_SCTP_SRC_PORTS) printf(" !"); if (einfo->spts[0] != einfo->spts[1]) printf(" --sport %u:%u", einfo->spts[0], einfo->spts[1]); else printf(" --sport %u", einfo->spts[0]); } if (einfo->flags & XT_SCTP_DEST_PORTS) { if (einfo->invflags & XT_SCTP_DEST_PORTS) printf(" !"); if (einfo->dpts[0] != einfo->dpts[1]) printf(" --dport %u:%u", einfo->dpts[0], einfo->dpts[1]); else printf(" --dport %u", einfo->dpts[0]); } if (einfo->flags & XT_SCTP_CHUNK_TYPES) { if (einfo->invflags & XT_SCTP_CHUNK_TYPES) printf(" !"); printf(" --chunk-types"); print_chunks(einfo, 0); } } static struct xtables_match sctp_match = { .name = "sctp", .family = NFPROTO_UNSPEC, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_sctp_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_sctp_info)), .help = sctp_help, .init = sctp_init, .parse = sctp_parse, .print = sctp_print, .save = sctp_save, .extra_opts = sctp_opts, }; void _init(void) { xtables_register_match(&sctp_match); }
262
./android_firewall/external/iptables/extensions/libxt_policy.c
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <netdb.h> #include <xtables.h> #include <linux/netfilter/xt_policy.h> enum { O_DIRECTION = 0, O_POLICY, O_STRICT, O_REQID, O_SPI, O_PROTO, O_MODE, O_TUNNELSRC, O_TUNNELDST, O_NEXT, F_STRICT = 1 << O_STRICT, }; static void policy_help(void) { printf( "policy match options:\n" " --dir in|out match policy applied during decapsulation/\n" " policy to be applied during encapsulation\n" " --pol none|ipsec match policy\n" " --strict match entire policy instead of single element\n" " at any position\n" "These options may be used repeatedly, to describe policy elements:\n" "[!] --reqid reqid match reqid\n" "[!] --spi spi match SPI\n" "[!] --proto proto match protocol (ah/esp/ipcomp)\n" "[!] --mode mode match mode (transport/tunnel)\n" "[!] --tunnel-src addr/mask match tunnel source\n" "[!] --tunnel-dst addr/mask match tunnel destination\n" " --next begin next element in policy\n"); } static const struct xt_option_entry policy_opts[] = { {.name = "dir", .id = O_DIRECTION, .type = XTTYPE_STRING}, {.name = "pol", .id = O_POLICY, .type = XTTYPE_STRING}, {.name = "strict", .id = O_STRICT, .type = XTTYPE_NONE}, {.name = "reqid", .id = O_REQID, .type = XTTYPE_UINT32, .flags = XTOPT_MULTI | XTOPT_INVERT}, {.name = "spi", .id = O_SPI, .type = XTTYPE_UINT32, .flags = XTOPT_MULTI | XTOPT_INVERT}, {.name = "tunnel-src", .id = O_TUNNELSRC, .type = XTTYPE_HOSTMASK, .flags = XTOPT_MULTI | XTOPT_INVERT}, {.name = "tunnel-dst", .id = O_TUNNELDST, .type = XTTYPE_HOSTMASK, .flags = XTOPT_MULTI | XTOPT_INVERT}, {.name = "proto", .id = O_PROTO, .type = XTTYPE_PROTOCOL, .flags = XTOPT_MULTI | XTOPT_INVERT}, {.name = "mode", .id = O_MODE, .type = XTTYPE_STRING, .flags = XTOPT_MULTI | XTOPT_INVERT}, {.name = "next", .id = O_NEXT, .type = XTTYPE_NONE, .flags = XTOPT_MULTI, .also = F_STRICT}, XTOPT_TABLEEND, }; static int parse_direction(const char *s) { if (strcmp(s, "in") == 0) return XT_POLICY_MATCH_IN; if (strcmp(s, "out") == 0) return XT_POLICY_MATCH_OUT; xtables_error(PARAMETER_PROBLEM, "policy_match: invalid dir \"%s\"", s); } static int parse_policy(const char *s) { if (strcmp(s, "none") == 0) return XT_POLICY_MATCH_NONE; if (strcmp(s, "ipsec") == 0) return 0; xtables_error(PARAMETER_PROBLEM, "policy match: invalid policy \"%s\"", s); } static int parse_mode(const char *s) { if (strcmp(s, "transport") == 0) return XT_POLICY_MODE_TRANSPORT; if (strcmp(s, "tunnel") == 0) return XT_POLICY_MODE_TUNNEL; xtables_error(PARAMETER_PROBLEM, "policy match: invalid mode \"%s\"", s); } static void policy_parse(struct xt_option_call *cb) { struct xt_policy_info *info = cb->data; struct xt_policy_elem *e = &info->pol[info->len]; xtables_option_parse(cb); switch (cb->entry->id) { case O_DIRECTION: info->flags |= parse_direction(cb->arg); break; case O_POLICY: info->flags |= parse_policy(cb->arg); break; case O_STRICT: info->flags |= XT_POLICY_MATCH_STRICT; break; case O_REQID: if (e->match.reqid) xtables_error(PARAMETER_PROBLEM, "policy match: double --reqid option"); e->match.reqid = 1; e->invert.reqid = cb->invert; e->reqid = cb->val.u32; break; case O_SPI: if (e->match.spi) xtables_error(PARAMETER_PROBLEM, "policy match: double --spi option"); e->match.spi = 1; e->invert.spi = cb->invert; e->spi = cb->val.u32; break; case O_TUNNELSRC: if (e->match.saddr) xtables_error(PARAMETER_PROBLEM, "policy match: double --tunnel-src option"); e->match.saddr = 1; e->invert.saddr = cb->invert; memcpy(&e->saddr, &cb->val.haddr, sizeof(cb->val.haddr)); memcpy(&e->smask, &cb->val.hmask, sizeof(cb->val.hmask)); break; case O_TUNNELDST: if (e->match.daddr) xtables_error(PARAMETER_PROBLEM, "policy match: double --tunnel-dst option"); e->match.daddr = 1; e->invert.daddr = cb->invert; memcpy(&e->daddr, &cb->val.haddr, sizeof(cb->val.haddr)); memcpy(&e->dmask, &cb->val.hmask, sizeof(cb->val.hmask)); break; case O_PROTO: if (e->match.proto) xtables_error(PARAMETER_PROBLEM, "policy match: double --proto option"); e->proto = cb->val.protocol; if (e->proto != IPPROTO_AH && e->proto != IPPROTO_ESP && e->proto != IPPROTO_COMP) xtables_error(PARAMETER_PROBLEM, "policy match: protocol must be ah/esp/ipcomp"); e->match.proto = 1; e->invert.proto = cb->invert; break; case O_MODE: if (e->match.mode) xtables_error(PARAMETER_PROBLEM, "policy match: double --mode option"); e->match.mode = 1; e->invert.mode = cb->invert; e->mode = parse_mode(cb->arg); break; case O_NEXT: if (++info->len == XT_POLICY_MAX_ELEM) xtables_error(PARAMETER_PROBLEM, "policy match: maximum policy depth reached"); break; } } static void policy_check(struct xt_fcheck_call *cb) { struct xt_policy_info *info = cb->data; const struct xt_policy_elem *e; int i; /* * The old "no parameters given" check is carried out * by testing for --dir. */ if (!(info->flags & (XT_POLICY_MATCH_IN | XT_POLICY_MATCH_OUT))) xtables_error(PARAMETER_PROBLEM, "policy match: neither --dir in nor --dir out specified"); if (info->flags & XT_POLICY_MATCH_NONE) { if (info->flags & XT_POLICY_MATCH_STRICT) xtables_error(PARAMETER_PROBLEM, "policy match: policy none but --strict given"); if (info->len != 0) xtables_error(PARAMETER_PROBLEM, "policy match: policy none but policy given"); } else info->len++; /* increase len by 1, no --next after last element */ /* * This is already represented with O_NEXT requiring F_STRICT in the * options table, but will keep this code as a comment for reference. * if (!(info->flags & XT_POLICY_MATCH_STRICT) && info->len > 1) xtables_error(PARAMETER_PROBLEM, "policy match: multiple elements but no --strict"); */ for (i = 0; i < info->len; i++) { e = &info->pol[i]; if (info->flags & XT_POLICY_MATCH_STRICT && !(e->match.reqid || e->match.spi || e->match.saddr || e->match.daddr || e->match.proto || e->match.mode)) xtables_error(PARAMETER_PROBLEM, "policy match: empty policy element %u. " "--strict is in effect, but at least one of " "reqid, spi, tunnel-src, tunnel-dst, proto or " "mode is required.", i); if ((e->match.saddr || e->match.daddr) && ((e->mode == XT_POLICY_MODE_TUNNEL && e->invert.mode) || (e->mode == XT_POLICY_MODE_TRANSPORT && !e->invert.mode))) xtables_error(PARAMETER_PROBLEM, "policy match: --tunnel-src/--tunnel-dst " "is only valid in tunnel mode"); } } static void print_mode(const char *prefix, uint8_t mode, int numeric) { printf(" %smode ", prefix); switch (mode) { case XT_POLICY_MODE_TRANSPORT: printf("transport"); break; case XT_POLICY_MODE_TUNNEL: printf("tunnel"); break; default: printf("???"); break; } } static void print_proto(const char *prefix, uint8_t proto, int numeric) { const struct protoent *p = NULL; printf(" %sproto ", prefix); if (!numeric) p = getprotobynumber(proto); if (p != NULL) printf("%s", p->p_name); else printf("%u", proto); } #define PRINT_INVERT(x) \ do { \ if (x) \ printf(" !"); \ } while(0) static void print_entry(const char *prefix, const struct xt_policy_elem *e, bool numeric, uint8_t family) { if (e->match.reqid) { PRINT_INVERT(e->invert.reqid); printf(" %sreqid %u", prefix, e->reqid); } if (e->match.spi) { PRINT_INVERT(e->invert.spi); printf(" %sspi 0x%x", prefix, e->spi); } if (e->match.proto) { PRINT_INVERT(e->invert.proto); print_proto(prefix, e->proto, numeric); } if (e->match.mode) { PRINT_INVERT(e->invert.mode); print_mode(prefix, e->mode, numeric); } if (e->match.daddr) { PRINT_INVERT(e->invert.daddr); if (family == NFPROTO_IPV6) printf(" %stunnel-dst %s%s", prefix, xtables_ip6addr_to_numeric(&e->daddr.a6), xtables_ip6mask_to_numeric(&e->dmask.a6)); else printf(" %stunnel-dst %s%s", prefix, xtables_ipaddr_to_numeric(&e->daddr.a4), xtables_ipmask_to_numeric(&e->dmask.a4)); } if (e->match.saddr) { PRINT_INVERT(e->invert.saddr); if (family == NFPROTO_IPV6) printf(" %stunnel-src %s%s", prefix, xtables_ip6addr_to_numeric(&e->saddr.a6), xtables_ip6mask_to_numeric(&e->smask.a6)); else printf(" %stunnel-src %s%s", prefix, xtables_ipaddr_to_numeric(&e->saddr.a4), xtables_ipmask_to_numeric(&e->smask.a4)); } } static void print_flags(const char *prefix, const struct xt_policy_info *info) { if (info->flags & XT_POLICY_MATCH_IN) printf(" %sdir in", prefix); else printf(" %sdir out", prefix); if (info->flags & XT_POLICY_MATCH_NONE) printf(" %spol none", prefix); else printf(" %spol ipsec", prefix); if (info->flags & XT_POLICY_MATCH_STRICT) printf(" %sstrict", prefix); } static void policy4_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_policy_info *info = (void *)match->data; unsigned int i; printf(" policy match"); print_flags("", info); for (i = 0; i < info->len; i++) { if (info->len > 1) printf(" [%u]", i); print_entry("", &info->pol[i], numeric, NFPROTO_IPV4); } } static void policy6_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_policy_info *info = (void *)match->data; unsigned int i; printf(" policy match"); print_flags("", info); for (i = 0; i < info->len; i++) { if (info->len > 1) printf(" [%u]", i); print_entry("", &info->pol[i], numeric, NFPROTO_IPV6); } } static void policy4_save(const void *ip, const struct xt_entry_match *match) { const struct xt_policy_info *info = (void *)match->data; unsigned int i; print_flags("--", info); for (i = 0; i < info->len; i++) { print_entry("--", &info->pol[i], false, NFPROTO_IPV4); if (i + 1 < info->len) printf(" --next"); } } static void policy6_save(const void *ip, const struct xt_entry_match *match) { const struct xt_policy_info *info = (void *)match->data; unsigned int i; print_flags("--", info); for (i = 0; i < info->len; i++) { print_entry("--", &info->pol[i], false, NFPROTO_IPV6); if (i + 1 < info->len) printf(" --next"); } } static struct xtables_match policy_mt_reg[] = { { .name = "policy", .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct xt_policy_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_policy_info)), .help = policy_help, .x6_parse = policy_parse, .x6_fcheck = policy_check, .print = policy4_print, .save = policy4_save, .x6_options = policy_opts, }, { .name = "policy", .version = XTABLES_VERSION, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct xt_policy_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_policy_info)), .help = policy_help, .x6_parse = policy_parse, .x6_fcheck = policy_check, .print = policy6_print, .save = policy6_save, .x6_options = policy_opts, }, }; void _init(void) { xtables_register_matches(policy_mt_reg, ARRAY_SIZE(policy_mt_reg)); }
263
./android_firewall/external/iptables/extensions/libxt_NFQUEUE.c
/* Shared library add-on to iptables for NFQ * * (C) 2005 by Harald Welte <[email protected]> * * This program is distributed under the terms of GNU GPL v2, 1991 * */ #include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_NFQUEUE.h> enum { O_QUEUE_NUM = 0, O_QUEUE_BALANCE, O_QUEUE_BYPASS, F_QUEUE_NUM = 1 << O_QUEUE_NUM, F_QUEUE_BALANCE = 1 << O_QUEUE_BALANCE, }; static void NFQUEUE_help(void) { printf( "NFQUEUE target options\n" " --queue-num value Send packet to QUEUE number <value>.\n" " Valid queue numbers are 0-65535\n" ); } static void NFQUEUE_help_v1(void) { NFQUEUE_help(); printf( " --queue-balance first:last Balance flows between queues <value> to <value>.\n"); } static void NFQUEUE_help_v2(void) { NFQUEUE_help_v1(); printf( " --queue-bypass Bypass Queueing if no queue instance exists.\n"); } #define s struct xt_NFQ_info static const struct xt_option_entry NFQUEUE_opts[] = { {.name = "queue-num", .id = O_QUEUE_NUM, .type = XTTYPE_UINT16, .flags = XTOPT_PUT, XTOPT_POINTER(s, queuenum), .excl = F_QUEUE_BALANCE}, {.name = "queue-balance", .id = O_QUEUE_BALANCE, .type = XTTYPE_UINT16RC, .excl = F_QUEUE_NUM}, {.name = "queue-bypass", .id = O_QUEUE_BYPASS, .type = XTTYPE_NONE}, XTOPT_TABLEEND, }; #undef s static void NFQUEUE_parse(struct xt_option_call *cb) { xtables_option_parse(cb); if (cb->entry->id == O_QUEUE_BALANCE) xtables_error(PARAMETER_PROBLEM, "NFQUEUE target: " "--queue-balance not supported (kernel too old?)"); } static void NFQUEUE_parse_v1(struct xt_option_call *cb) { struct xt_NFQ_info_v1 *info = cb->data; const uint16_t *r = cb->val.u16_range; xtables_option_parse(cb); switch (cb->entry->id) { case O_QUEUE_BALANCE: if (cb->nvals != 2) xtables_error(PARAMETER_PROBLEM, "Bad range \"%s\"", cb->arg); if (r[0] >= r[1]) xtables_error(PARAMETER_PROBLEM, "%u should be less than %u", r[0], r[1]); info->queuenum = r[0]; info->queues_total = r[1] - r[0] + 1; break; } } static void NFQUEUE_parse_v2(struct xt_option_call *cb) { struct xt_NFQ_info_v2 *info = cb->data; NFQUEUE_parse_v1(cb); switch (cb->entry->id) { case O_QUEUE_BYPASS: info->bypass = 1; break; } } static void NFQUEUE_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_NFQ_info *tinfo = (const struct xt_NFQ_info *)target->data; printf(" NFQUEUE num %u", tinfo->queuenum); } static void NFQUEUE_print_v1(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_NFQ_info_v1 *tinfo = (const void *)target->data; unsigned int last = tinfo->queues_total; if (last > 1) { last += tinfo->queuenum - 1; printf(" NFQUEUE balance %u:%u", tinfo->queuenum, last); } else { printf(" NFQUEUE num %u", tinfo->queuenum); } } static void NFQUEUE_print_v2(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_NFQ_info_v2 *info = (void *) target->data; NFQUEUE_print_v1(ip, target, numeric); if (info->bypass) printf(" bypass"); } static void NFQUEUE_save(const void *ip, const struct xt_entry_target *target) { const struct xt_NFQ_info *tinfo = (const struct xt_NFQ_info *)target->data; printf(" --queue-num %u", tinfo->queuenum); } static void NFQUEUE_save_v1(const void *ip, const struct xt_entry_target *target) { const struct xt_NFQ_info_v1 *tinfo = (const void *)target->data; unsigned int last = tinfo->queues_total; if (last > 1) { last += tinfo->queuenum - 1; printf(" --queue-balance %u:%u", tinfo->queuenum, last); } else { printf(" --queue-num %u", tinfo->queuenum); } } static void NFQUEUE_save_v2(const void *ip, const struct xt_entry_target *target) { const struct xt_NFQ_info_v2 *info = (void *) target->data; NFQUEUE_save_v1(ip, target); if (info->bypass) printf(" --queue-bypass"); } static void NFQUEUE_init_v1(struct xt_entry_target *t) { struct xt_NFQ_info_v1 *tinfo = (void *)t->data; tinfo->queues_total = 1; } static struct xtables_target nfqueue_targets[] = { { .family = NFPROTO_UNSPEC, .name = "NFQUEUE", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_NFQ_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_NFQ_info)), .help = NFQUEUE_help, .print = NFQUEUE_print, .save = NFQUEUE_save, .x6_parse = NFQUEUE_parse, .x6_options = NFQUEUE_opts },{ .family = NFPROTO_UNSPEC, .revision = 1, .name = "NFQUEUE", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_NFQ_info_v1)), .userspacesize = XT_ALIGN(sizeof(struct xt_NFQ_info_v1)), .help = NFQUEUE_help_v1, .init = NFQUEUE_init_v1, .print = NFQUEUE_print_v1, .save = NFQUEUE_save_v1, .x6_parse = NFQUEUE_parse_v1, .x6_options = NFQUEUE_opts, },{ .family = NFPROTO_UNSPEC, .revision = 2, .name = "NFQUEUE", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_NFQ_info_v2)), .userspacesize = XT_ALIGN(sizeof(struct xt_NFQ_info_v2)), .help = NFQUEUE_help_v2, .init = NFQUEUE_init_v1, .print = NFQUEUE_print_v2, .save = NFQUEUE_save_v2, .x6_parse = NFQUEUE_parse_v2, .x6_options = NFQUEUE_opts, } }; void _init(void) { xtables_register_targets(nfqueue_targets, ARRAY_SIZE(nfqueue_targets)); }
264
./android_firewall/external/iptables/extensions/libxt_helper.c
#include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_helper.h> enum { O_HELPER = 0, }; static void helper_help(void) { printf( "helper match options:\n" "[!] --helper string Match helper identified by string\n"); } static const struct xt_option_entry helper_opts[] = { {.name = "helper", .id = O_HELPER, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(struct xt_helper_info, name)}, XTOPT_TABLEEND, }; static void helper_parse(struct xt_option_call *cb) { struct xt_helper_info *info = cb->data; xtables_option_parse(cb); if (cb->invert) info->invert = 1; } static void helper_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_helper_info *info = (const void *)match->data; printf(" helper match %s\"%s\"", info->invert ? "! " : "", info->name); } static void helper_save(const void *ip, const struct xt_entry_match *match) { const struct xt_helper_info *info = (const void *)match->data; printf("%s --helper", info->invert ? " !" : ""); xtables_save_string(info->name); } static struct xtables_match helper_match = { .family = NFPROTO_UNSPEC, .name = "helper", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_helper_info)), .help = helper_help, .print = helper_print, .save = helper_save, .x6_parse = helper_parse, .x6_options = helper_opts, }; void _init(void) { xtables_register_match(&helper_match); }
265
./android_firewall/external/iptables/extensions/libip6t_dst.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <xtables.h> #include <linux/netfilter_ipv6/ip6t_opts.h> enum { O_DSTLEN = 0, O_DSTOPTS, }; static void dst_help(void) { printf( "dst match options:\n" "[!] --dst-len length total length of this header\n" " --dst-opts TYPE[:LEN][,TYPE[:LEN]...]\n" " Options and its length (list, max: %d)\n", IP6T_OPTS_OPTSNR); } static const struct xt_option_entry dst_opts[] = { {.name = "dst-len", .id = O_DSTLEN, .type = XTTYPE_UINT32, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(struct ip6t_opts, hdrlen)}, {.name = "dst-opts", .id = O_DSTOPTS, .type = XTTYPE_STRING}, XTOPT_TABLEEND, }; static uint32_t parse_opts_num(const char *idstr, const char *typestr) { unsigned long int id; char* ep; id = strtoul(idstr, &ep, 0); if ( idstr == ep ) { xtables_error(PARAMETER_PROBLEM, "dst: no valid digits in %s `%s'", typestr, idstr); } if ( id == ULONG_MAX && errno == ERANGE ) { xtables_error(PARAMETER_PROBLEM, "%s `%s' specified too big: would overflow", typestr, idstr); } if ( *idstr != '\0' && *ep != '\0' ) { xtables_error(PARAMETER_PROBLEM, "dst: error parsing %s `%s'", typestr, idstr); } return id; } static int parse_options(const char *optsstr, uint16_t *opts) { char *buffer, *cp, *next, *range; unsigned int i; buffer = strdup(optsstr); if (!buffer) xtables_error(OTHER_PROBLEM, "strdup failed"); for (cp = buffer, i = 0; cp && i < IP6T_OPTS_OPTSNR; cp = next, i++) { next = strchr(cp, ','); if (next) *next++='\0'; range = strchr(cp, ':'); if (range) { if (i == IP6T_OPTS_OPTSNR-1) xtables_error(PARAMETER_PROBLEM, "too many ports specified"); *range++ = '\0'; } opts[i] = (parse_opts_num(cp, "opt") & 0xFF) << 8; if (range) { if (opts[i] == 0) xtables_error(PARAMETER_PROBLEM, "PAD0 hasn't got length"); opts[i] |= parse_opts_num(range, "length") & 0xFF; } else opts[i] |= (0x00FF); #ifdef DEBUG printf("opts str: %s %s\n", cp, range); printf("opts opt: %04X\n", opts[i]); #endif } if (cp) xtables_error(PARAMETER_PROBLEM, "too many addresses specified"); free(buffer); #ifdef DEBUG printf("addr nr: %d\n", i); #endif return i; } static void dst_parse(struct xt_option_call *cb) { struct ip6t_opts *optinfo = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_DSTLEN: optinfo->flags |= IP6T_OPTS_LEN; break; case O_DSTOPTS: optinfo->optsnr = parse_options(cb->arg, optinfo->opts); optinfo->flags |= IP6T_OPTS_OPTS; break; } } static void print_options(unsigned int optsnr, uint16_t *optsp) { unsigned int i; printf(" "); for(i = 0; i < optsnr; i++) { printf("%d", (optsp[i] & 0xFF00) >> 8); if ((optsp[i] & 0x00FF) != 0x00FF) printf(":%d", (optsp[i] & 0x00FF)); printf("%c", (i != optsnr - 1) ? ',' : ' '); } } static void dst_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct ip6t_opts *optinfo = (struct ip6t_opts *)match->data; printf(" dst"); if (optinfo->flags & IP6T_OPTS_LEN) printf(" length:%s%u", optinfo->invflags & IP6T_OPTS_INV_LEN ? "!" : "", optinfo->hdrlen); if (optinfo->flags & IP6T_OPTS_OPTS) printf(" opts"); print_options(optinfo->optsnr, (uint16_t *)optinfo->opts); if (optinfo->invflags & ~IP6T_OPTS_INV_MASK) printf(" Unknown invflags: 0x%X", optinfo->invflags & ~IP6T_OPTS_INV_MASK); } static void dst_save(const void *ip, const struct xt_entry_match *match) { const struct ip6t_opts *optinfo = (struct ip6t_opts *)match->data; if (optinfo->flags & IP6T_OPTS_LEN) { printf("%s --dst-len %u", (optinfo->invflags & IP6T_OPTS_INV_LEN) ? " !" : "", optinfo->hdrlen); } if (optinfo->flags & IP6T_OPTS_OPTS) printf(" --dst-opts"); print_options(optinfo->optsnr, (uint16_t *)optinfo->opts); } static struct xtables_match dst_mt6_reg = { .name = "dst", .version = XTABLES_VERSION, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct ip6t_opts)), .userspacesize = XT_ALIGN(sizeof(struct ip6t_opts)), .help = dst_help, .print = dst_print, .save = dst_save, .x6_parse = dst_parse, .x6_options = dst_opts, }; void _init(void) { xtables_register_match(&dst_mt6_reg); }
266
./android_firewall/external/iptables/extensions/libxt_RATEEST.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <xtables.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter/xt_RATEEST.h> struct rateest_tg_udata { unsigned int interval; unsigned int ewma_log; }; static void RATEEST_help(void) { printf( "RATEEST target options:\n" " --rateest-name name Rate estimator name\n" " --rateest-interval sec Rate measurement interval in seconds\n" " --rateest-ewmalog value Rate measurement averaging time constant\n"); } enum { O_NAME = 0, O_INTERVAL, O_EWMALOG, }; #define s struct xt_rateest_target_info static const struct xt_option_entry RATEEST_opts[] = { {.name = "rateest-name", .id = O_NAME, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_PUT, XTOPT_POINTER(s, name)}, {.name = "rateest-interval", .id = O_INTERVAL, .type = XTTYPE_STRING, .flags = XTOPT_MAND}, {.name = "rateest-ewmalog", .id = O_EWMALOG, .type = XTTYPE_STRING, .flags = XTOPT_MAND}, XTOPT_TABLEEND, }; #undef s /* Copied from iproute */ #define TIME_UNITS_PER_SEC 1000000 static int RATEEST_get_time(unsigned int *time, const char *str) { double t; char *p; t = strtod(str, &p); if (p == str) return -1; if (*p) { if (strcasecmp(p, "s") == 0 || strcasecmp(p, "sec")==0 || strcasecmp(p, "secs")==0) t *= TIME_UNITS_PER_SEC; else if (strcasecmp(p, "ms") == 0 || strcasecmp(p, "msec")==0 || strcasecmp(p, "msecs") == 0) t *= TIME_UNITS_PER_SEC/1000; else if (strcasecmp(p, "us") == 0 || strcasecmp(p, "usec")==0 || strcasecmp(p, "usecs") == 0) t *= TIME_UNITS_PER_SEC/1000000; else return -1; } *time = t; return 0; } static void RATEEST_print_time(unsigned int time) { double tmp = time; if (tmp >= TIME_UNITS_PER_SEC) printf(" %.1fs", tmp / TIME_UNITS_PER_SEC); else if (tmp >= TIME_UNITS_PER_SEC/1000) printf(" %.1fms", tmp / (TIME_UNITS_PER_SEC / 1000)); else printf(" %uus", time); } static void RATEEST_parse(struct xt_option_call *cb) { struct rateest_tg_udata *udata = cb->udata; xtables_option_parse(cb); switch (cb->entry->id) { case O_INTERVAL: if (RATEEST_get_time(&udata->interval, cb->arg) < 0) xtables_error(PARAMETER_PROBLEM, "RATEEST: bad interval value \"%s\"", cb->arg); break; case O_EWMALOG: if (RATEEST_get_time(&udata->ewma_log, cb->arg) < 0) xtables_error(PARAMETER_PROBLEM, "RATEEST: bad ewmalog value \"%s\"", cb->arg); break; } } static void RATEEST_final_check(struct xt_fcheck_call *cb) { struct xt_rateest_target_info *info = cb->data; struct rateest_tg_udata *udata = cb->udata; for (info->interval = 0; info->interval <= 5; info->interval++) { if (udata->interval <= (1 << info->interval) * (TIME_UNITS_PER_SEC / 4)) break; } if (info->interval > 5) xtables_error(PARAMETER_PROBLEM, "RATEEST: interval value is too large"); info->interval -= 2; for (info->ewma_log = 1; info->ewma_log < 32; info->ewma_log++) { double w = 1.0 - 1.0 / (1 << info->ewma_log); if (udata->interval / (-log(w)) > udata->ewma_log) break; } info->ewma_log--; if (info->ewma_log == 0 || info->ewma_log >= 31) xtables_error(PARAMETER_PROBLEM, "RATEEST: ewmalog value is out of range"); } static void __RATEEST_print(const struct xt_entry_target *target, const char *prefix) { const struct xt_rateest_target_info *info = (const void *)target->data; unsigned int local_interval; unsigned int local_ewma_log; local_interval = (TIME_UNITS_PER_SEC << (info->interval + 2)) / 4; local_ewma_log = local_interval * (1 << (info->ewma_log)); printf(" %sname %s", prefix, info->name); printf(" %sinterval", prefix); RATEEST_print_time(local_interval); printf(" %sewmalog", prefix); RATEEST_print_time(local_ewma_log); } static void RATEEST_print(const void *ip, const struct xt_entry_target *target, int numeric) { __RATEEST_print(target, ""); } static void RATEEST_save(const void *ip, const struct xt_entry_target *target) { __RATEEST_print(target, "--rateest-"); } static struct xtables_target rateest_tg_reg = { .family = NFPROTO_UNSPEC, .name = "RATEEST", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_rateest_target_info)), .userspacesize = offsetof(struct xt_rateest_target_info, est), .help = RATEEST_help, .x6_parse = RATEEST_parse, .x6_fcheck = RATEEST_final_check, .print = RATEEST_print, .save = RATEEST_save, .x6_options = RATEEST_opts, .udata_size = sizeof(struct rateest_tg_udata), }; void _init(void) { xtables_register_target(&rateest_tg_reg); }
267
./android_firewall/external/iptables/extensions/libxt_TPROXY.c
/* * shared library add-on to iptables to add TPROXY target support. * * Copyright (C) 2002-2008 BalaBit IT Ltd. */ #include <stdio.h> #include <limits.h> #include <xtables.h> #include <linux/netfilter/xt_TPROXY.h> #include <arpa/inet.h> enum { P_PORT = 0, P_ADDR, P_MARK, F_PORT = 1 << P_PORT, F_ADDR = 1 << P_ADDR, F_MARK = 1 << P_MARK, }; #define s struct xt_tproxy_target_info static const struct xt_option_entry tproxy_tg0_opts[] = { {.name = "on-port", .id = P_PORT, .type = XTTYPE_PORT, .flags = XTOPT_MAND | XTOPT_NBO | XTOPT_PUT, XTOPT_POINTER(s, lport)}, {.name = "on-ip", .id = P_ADDR, .type = XTTYPE_HOST}, {.name = "tproxy-mark", .id = P_MARK, .type = XTTYPE_MARKMASK32}, XTOPT_TABLEEND, }; #undef s #define s struct xt_tproxy_target_info_v1 static const struct xt_option_entry tproxy_tg1_opts[] = { {.name = "on-port", .id = P_PORT, .type = XTTYPE_PORT, .flags = XTOPT_MAND | XTOPT_NBO | XTOPT_PUT, XTOPT_POINTER(s, lport)}, {.name = "on-ip", .id = P_ADDR, .type = XTTYPE_HOST, .flags = XTOPT_PUT, XTOPT_POINTER(s, laddr)}, {.name = "tproxy-mark", .id = P_MARK, .type = XTTYPE_MARKMASK32}, XTOPT_TABLEEND, }; #undef s static void tproxy_tg_help(void) { printf( "TPROXY target options:\n" " --on-port port Redirect connection to port, or the original port if 0\n" " --on-ip ip Optionally redirect to the given IP\n" " --tproxy-mark value[/mask] Mark packets with the given value/mask\n\n"); } static void tproxy_tg_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_tproxy_target_info *info = (const void *)target->data; printf(" TPROXY redirect %s:%u mark 0x%x/0x%x", xtables_ipaddr_to_numeric((const struct in_addr *)&info->laddr), ntohs(info->lport), (unsigned int)info->mark_value, (unsigned int)info->mark_mask); } static void tproxy_tg_print4(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_tproxy_target_info_v1 *info = (const void *)target->data; printf(" TPROXY redirect %s:%u mark 0x%x/0x%x", xtables_ipaddr_to_numeric(&info->laddr.in), ntohs(info->lport), (unsigned int)info->mark_value, (unsigned int)info->mark_mask); } static void tproxy_tg_print6(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_tproxy_target_info_v1 *info = (const void *)target->data; printf(" TPROXY redirect %s:%u mark 0x%x/0x%x", xtables_ip6addr_to_numeric(&info->laddr.in6), ntohs(info->lport), (unsigned int)info->mark_value, (unsigned int)info->mark_mask); } static void tproxy_tg_save(const void *ip, const struct xt_entry_target *target) { const struct xt_tproxy_target_info *info = (const void *)target->data; printf(" --on-port %u", ntohs(info->lport)); printf(" --on-ip %s", xtables_ipaddr_to_numeric((const struct in_addr *)&info->laddr)); printf(" --tproxy-mark 0x%x/0x%x", (unsigned int)info->mark_value, (unsigned int)info->mark_mask); } static void tproxy_tg_save4(const void *ip, const struct xt_entry_target *target) { const struct xt_tproxy_target_info_v1 *info; info = (const void *)target->data; printf(" --on-port %u", ntohs(info->lport)); printf(" --on-ip %s", xtables_ipaddr_to_numeric(&info->laddr.in)); printf(" --tproxy-mark 0x%x/0x%x", (unsigned int)info->mark_value, (unsigned int)info->mark_mask); } static void tproxy_tg_save6(const void *ip, const struct xt_entry_target *target) { const struct xt_tproxy_target_info_v1 *info; info = (const void *)target->data; printf(" --on-port %u", ntohs(info->lport)); printf(" --on-ip %s", xtables_ip6addr_to_numeric(&info->laddr.in6)); printf(" --tproxy-mark 0x%x/0x%x", (unsigned int)info->mark_value, (unsigned int)info->mark_mask); } static void tproxy_tg0_parse(struct xt_option_call *cb) { struct xt_tproxy_target_info *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case P_MARK: info->mark_value = cb->val.mark; info->mark_mask = cb->val.mask; break; case P_ADDR: info->laddr = cb->val.haddr.ip; break; } } static void tproxy_tg1_parse(struct xt_option_call *cb) { struct xt_tproxy_target_info_v1 *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case P_MARK: info->mark_value = cb->val.mark; info->mark_mask = cb->val.mask; break; } } static struct xtables_target tproxy_tg_reg[] = { { .name = "TPROXY", .revision = 0, .family = NFPROTO_IPV4, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_tproxy_target_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_tproxy_target_info)), .help = tproxy_tg_help, .print = tproxy_tg_print, .save = tproxy_tg_save, .x6_options = tproxy_tg0_opts, .x6_parse = tproxy_tg0_parse, }, { .name = "TPROXY", .revision = 1, .family = NFPROTO_IPV4, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_tproxy_target_info_v1)), .userspacesize = XT_ALIGN(sizeof(struct xt_tproxy_target_info_v1)), .help = tproxy_tg_help, .print = tproxy_tg_print4, .save = tproxy_tg_save4, .x6_options = tproxy_tg1_opts, .x6_parse = tproxy_tg1_parse, }, { .name = "TPROXY", .revision = 1, .family = NFPROTO_IPV6, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_tproxy_target_info_v1)), .userspacesize = XT_ALIGN(sizeof(struct xt_tproxy_target_info_v1)), .help = tproxy_tg_help, .print = tproxy_tg_print6, .save = tproxy_tg_save6, .x6_options = tproxy_tg1_opts, .x6_parse = tproxy_tg1_parse, }, }; void _init(void) { xtables_register_targets(tproxy_tg_reg, ARRAY_SIZE(tproxy_tg_reg)); }
268
./android_firewall/external/iptables/extensions/libxt_quota.c
/* * Shared library add-on to iptables to add quota support * * Sam Johnston <[email protected]> */ #include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_quota.h> enum { O_QUOTA = 0, }; static const struct xt_option_entry quota_opts[] = { {.name = "quota", .id = O_QUOTA, .type = XTTYPE_UINT64, .flags = XTOPT_MAND | XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(struct xt_quota_info, quota)}, XTOPT_TABLEEND, }; static void quota_help(void) { printf("quota match options:\n" "[!] --quota quota quota (bytes)\n"); } static void quota_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_quota_info *q = (const void *)match->data; printf(" quota: %llu bytes", (unsigned long long)q->quota); } static void quota_save(const void *ip, const struct xt_entry_match *match) { const struct xt_quota_info *q = (const void *)match->data; if (q->flags & XT_QUOTA_INVERT) printf("! "); printf(" --quota %llu", (unsigned long long) q->quota); } static void quota_parse(struct xt_option_call *cb) { struct xt_quota_info *info = cb->data; xtables_option_parse(cb); if (cb->invert) info->flags |= XT_QUOTA_INVERT; } static struct xtables_match quota_match = { .family = NFPROTO_UNSPEC, .name = "quota", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof (struct xt_quota_info)), .userspacesize = offsetof(struct xt_quota_info, master), .help = quota_help, .print = quota_print, .save = quota_save, .x6_parse = quota_parse, .x6_options = quota_opts, }; void _init(void) { xtables_register_match(&quota_match); }
269
./android_firewall/external/iptables/extensions/dscp_helper.c
/* * DiffServ classname <-> DiffServ codepoint mapping functions. * * The latest list of the mappings can be found at: * <http://www.iana.org/assignments/dscp-registry> * * This code is released under the GNU GPL v2, 1991 * * Author: Iain Barnes */ #include <stdio.h> #include <string.h> #include <xtables.h> static const struct ds_class { const char *name; unsigned int dscp; } ds_classes[] = { { "CS0", 0x00 }, { "CS1", 0x08 }, { "CS2", 0x10 }, { "CS3", 0x18 }, { "CS4", 0x20 }, { "CS5", 0x28 }, { "CS6", 0x30 }, { "CS7", 0x38 }, { "BE", 0x00 }, { "AF11", 0x0a }, { "AF12", 0x0c }, { "AF13", 0x0e }, { "AF21", 0x12 }, { "AF22", 0x14 }, { "AF23", 0x16 }, { "AF31", 0x1a }, { "AF32", 0x1c }, { "AF33", 0x1e }, { "AF41", 0x22 }, { "AF42", 0x24 }, { "AF43", 0x26 }, { "EF", 0x2e } }; static unsigned int class_to_dscp(const char *name) { unsigned int i; for (i = 0; i < ARRAY_SIZE(ds_classes); i++) { if (!strncasecmp(name, ds_classes[i].name, strlen(ds_classes[i].name))) return ds_classes[i].dscp; } xtables_error(PARAMETER_PROBLEM, "Invalid DSCP value `%s'\n", name); } #if 0 static const char * dscp_to_name(unsigned int dscp) { int i; for (i = 0; i < ARRAY_SIZE(ds_classes); ++i) if (dscp == ds_classes[i].dscp) return ds_classes[i].name; xtables_error(PARAMETER_PROBLEM, "Invalid DSCP value `%d'\n", dscp); } #endif
270
./android_firewall/external/iptables/extensions/libxt_rateest.c
#include <stdbool.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stddef.h> #include <getopt.h> #include <xtables.h> #include <linux/netfilter/xt_rateest.h> static void rateest_help(void) { printf( "rateest match options:\n" " --rateest1 name Rate estimator name\n" " --rateest2 name Rate estimator name\n" " --rateest-delta Compare difference(s) to given rate(s)\n" " --rateest-bps1 [bps] Compare bps\n" " --rateest-pps1 [pps] Compare pps\n" " --rateest-bps2 [bps] Compare bps\n" " --rateest-pps2 [pps] Compare pps\n" " [!] --rateest-lt Match if rate is less than given rate/estimator\n" " [!] --rateest-gt Match if rate is greater than given rate/estimator\n" " [!] --rateest-eq Match if rate is equal to given rate/estimator\n"); } enum rateest_options { OPT_RATEEST1, OPT_RATEEST2, OPT_RATEEST_BPS1, OPT_RATEEST_PPS1, OPT_RATEEST_BPS2, OPT_RATEEST_PPS2, OPT_RATEEST_DELTA, OPT_RATEEST_LT, OPT_RATEEST_GT, OPT_RATEEST_EQ, }; static const struct option rateest_opts[] = { {.name = "rateest1", .has_arg = true, .val = OPT_RATEEST1}, {.name = "rateest", .has_arg = true, .val = OPT_RATEEST1}, /* alias for absolute mode */ {.name = "rateest2", .has_arg = true, .val = OPT_RATEEST2}, {.name = "rateest-bps1", .has_arg = false, .val = OPT_RATEEST_BPS1}, {.name = "rateest-pps1", .has_arg = false, .val = OPT_RATEEST_PPS1}, {.name = "rateest-bps2", .has_arg = false, .val = OPT_RATEEST_BPS2}, {.name = "rateest-pps2", .has_arg = false, .val = OPT_RATEEST_PPS2}, {.name = "rateest-bps", .has_arg = false, .val = OPT_RATEEST_BPS2}, /* alias for absolute mode */ {.name = "rateest-pps", .has_arg = false, .val = OPT_RATEEST_PPS2}, /* alias for absolute mode */ {.name = "rateest-delta", .has_arg = false, .val = OPT_RATEEST_DELTA}, {.name = "rateest-lt", .has_arg = false, .val = OPT_RATEEST_LT}, {.name = "rateest-gt", .has_arg = false, .val = OPT_RATEEST_GT}, {.name = "rateest-eq", .has_arg = false, .val = OPT_RATEEST_EQ}, XT_GETOPT_TABLEEND, }; /* Copied from iproute. See http://physics.nist.gov/cuu/Units/binary.html */ static const struct rate_suffix { const char *name; double scale; } suffixes[] = { { "bit", 1. }, { "Kibit", 1024. }, { "kbit", 1000. }, { "Mibit", 1024.*1024. }, { "mbit", 1000000. }, { "Gibit", 1024.*1024.*1024. }, { "gbit", 1000000000. }, { "Tibit", 1024.*1024.*1024.*1024. }, { "tbit", 1000000000000. }, { "Bps", 8. }, { "KiBps", 8.*1024. }, { "KBps", 8000. }, { "MiBps", 8.*1024*1024. }, { "MBps", 8000000. }, { "GiBps", 8.*1024.*1024.*1024. }, { "GBps", 8000000000. }, { "TiBps", 8.*1024.*1024.*1024.*1024. }, { "TBps", 8000000000000. }, {NULL}, }; static int rateest_get_rate(uint32_t *rate, const char *str) { char *p; double bps = strtod(str, &p); const struct rate_suffix *s; if (p == str) return -1; if (*p == '\0') { *rate = bps / 8.; /* assume bytes/sec */ return 0; } for (s = suffixes; s->name; ++s) { if (strcasecmp(s->name, p) == 0) { *rate = (bps * s->scale) / 8.; return 0; } } return -1; } static int rateest_parse(int c, char **argv, int invert, unsigned int *flags, const void *entry, struct xt_entry_match **match) { struct xt_rateest_match_info *info = (void *)(*match)->data; unsigned int val; switch (c) { case OPT_RATEEST1: if (invert) xtables_error(PARAMETER_PROBLEM, "rateest: rateest can't be inverted"); if (*flags & (1 << c)) xtables_error(PARAMETER_PROBLEM, "rateest: can't specify --rateest1 twice"); *flags |= 1 << c; strncpy(info->name1, optarg, sizeof(info->name1) - 1); break; case OPT_RATEEST2: if (invert) xtables_error(PARAMETER_PROBLEM, "rateest: rateest can't be inverted"); if (*flags & (1 << c)) xtables_error(PARAMETER_PROBLEM, "rateest: can't specify --rateest2 twice"); *flags |= 1 << c; strncpy(info->name2, optarg, sizeof(info->name2) - 1); info->flags |= XT_RATEEST_MATCH_REL; break; case OPT_RATEEST_BPS1: if (invert) xtables_error(PARAMETER_PROBLEM, "rateest: rateest-bps can't be inverted"); if (*flags & (1 << c)) xtables_error(PARAMETER_PROBLEM, "rateest: can't specify --rateest-bps1 twice"); *flags |= 1 << c; info->flags |= XT_RATEEST_MATCH_BPS; /* The rate is optional and only required in absolute mode */ if (!argv[optind] || *argv[optind] == '-' || *argv[optind] == '!') break; if (rateest_get_rate(&info->bps1, argv[optind]) < 0) xtables_error(PARAMETER_PROBLEM, "rateest: could not parse rate `%s'", argv[optind]); optind++; break; case OPT_RATEEST_PPS1: if (invert) xtables_error(PARAMETER_PROBLEM, "rateest: rateest-pps can't be inverted"); if (*flags & (1 << c)) xtables_error(PARAMETER_PROBLEM, "rateest: can't specify --rateest-pps1 twice"); *flags |= 1 << c; info->flags |= XT_RATEEST_MATCH_PPS; /* The rate is optional and only required in absolute mode */ if (!argv[optind] || *argv[optind] == '-' || *argv[optind] == '!') break; if (!xtables_strtoui(argv[optind], NULL, &val, 0, UINT32_MAX)) xtables_error(PARAMETER_PROBLEM, "rateest: could not parse pps `%s'", argv[optind]); info->pps1 = val; optind++; break; case OPT_RATEEST_BPS2: if (invert) xtables_error(PARAMETER_PROBLEM, "rateest: rateest-bps can't be inverted"); if (*flags & (1 << c)) xtables_error(PARAMETER_PROBLEM, "rateest: can't specify --rateest-bps2 twice"); *flags |= 1 << c; info->flags |= XT_RATEEST_MATCH_BPS; /* The rate is optional and only required in absolute mode */ if (!argv[optind] || *argv[optind] == '-' || *argv[optind] == '!') break; if (rateest_get_rate(&info->bps2, argv[optind]) < 0) xtables_error(PARAMETER_PROBLEM, "rateest: could not parse rate `%s'", argv[optind]); optind++; break; case OPT_RATEEST_PPS2: if (invert) xtables_error(PARAMETER_PROBLEM, "rateest: rateest-pps can't be inverted"); if (*flags & (1 << c)) xtables_error(PARAMETER_PROBLEM, "rateest: can't specify --rateest-pps2 twice"); *flags |= 1 << c; info->flags |= XT_RATEEST_MATCH_PPS; /* The rate is optional and only required in absolute mode */ if (!argv[optind] || *argv[optind] == '-' || *argv[optind] == '!') break; if (!xtables_strtoui(argv[optind], NULL, &val, 0, UINT32_MAX)) xtables_error(PARAMETER_PROBLEM, "rateest: could not parse pps `%s'", argv[optind]); info->pps2 = val; optind++; break; case OPT_RATEEST_DELTA: if (invert) xtables_error(PARAMETER_PROBLEM, "rateest: rateest-delta can't be inverted"); if (*flags & (1 << c)) xtables_error(PARAMETER_PROBLEM, "rateest: can't specify --rateest-delta twice"); *flags |= 1 << c; info->flags |= XT_RATEEST_MATCH_DELTA; break; case OPT_RATEEST_EQ: if (*flags & (1 << c)) xtables_error(PARAMETER_PROBLEM, "rateest: can't specify lt/gt/eq twice"); *flags |= 1 << c; info->mode = XT_RATEEST_MATCH_EQ; if (invert) info->flags |= XT_RATEEST_MATCH_INVERT; break; case OPT_RATEEST_LT: if (*flags & (1 << c)) xtables_error(PARAMETER_PROBLEM, "rateest: can't specify lt/gt/eq twice"); *flags |= 1 << c; info->mode = XT_RATEEST_MATCH_LT; if (invert) info->flags |= XT_RATEEST_MATCH_INVERT; break; case OPT_RATEEST_GT: if (*flags & (1 << c)) xtables_error(PARAMETER_PROBLEM, "rateest: can't specify lt/gt/eq twice"); *flags |= 1 << c; info->mode = XT_RATEEST_MATCH_GT; if (invert) info->flags |= XT_RATEEST_MATCH_INVERT; break; } return 1; } static void rateest_final_check(struct xt_fcheck_call *cb) { struct xt_rateest_match_info *info = cb->data; if (info == NULL) xtables_error(PARAMETER_PROBLEM, "rateest match: " "you need to specify some flags"); if (!(info->flags & XT_RATEEST_MATCH_REL)) info->flags |= XT_RATEEST_MATCH_ABS; } static void rateest_print_rate(uint32_t rate, int numeric) { double tmp = (double)rate*8; if (numeric) printf(" %u", rate); else if (tmp >= 1000.0*1000000.0) printf(" %.0fMbit", tmp/1000000.0); else if (tmp >= 1000.0 * 1000.0) printf(" %.0fKbit", tmp/1000.0); else printf(" %.0fbit", tmp); } static void rateest_print_mode(const struct xt_rateest_match_info *info, const char *prefix) { if (info->flags & XT_RATEEST_MATCH_INVERT) printf(" !"); switch (info->mode) { case XT_RATEEST_MATCH_EQ: printf(" %seq", prefix); break; case XT_RATEEST_MATCH_LT: printf(" %slt", prefix); break; case XT_RATEEST_MATCH_GT: printf(" %sgt", prefix); break; default: exit(1); } } static void rateest_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_rateest_match_info *info = (const void *)match->data; printf(" rateest match "); printf("%s", info->name1); if (info->flags & XT_RATEEST_MATCH_DELTA) printf(" delta"); if (info->flags & XT_RATEEST_MATCH_BPS) { printf(" bps"); if (info->flags & XT_RATEEST_MATCH_DELTA) rateest_print_rate(info->bps1, numeric); if (info->flags & XT_RATEEST_MATCH_ABS) { rateest_print_rate(info->bps2, numeric); rateest_print_mode(info, ""); } } if (info->flags & XT_RATEEST_MATCH_PPS) { printf(" pps"); if (info->flags & XT_RATEEST_MATCH_DELTA) printf(" %u", info->pps1); if (info->flags & XT_RATEEST_MATCH_ABS) { rateest_print_mode(info, ""); printf(" %u", info->pps2); } } if (info->flags & XT_RATEEST_MATCH_REL) { rateest_print_mode(info, ""); printf(" %s", info->name2); if (info->flags & XT_RATEEST_MATCH_BPS) { printf(" bps"); if (info->flags & XT_RATEEST_MATCH_DELTA) rateest_print_rate(info->bps2, numeric); } if (info->flags & XT_RATEEST_MATCH_PPS) { printf(" pps"); if (info->flags & XT_RATEEST_MATCH_DELTA) printf(" %u", info->pps2); } } } static void __rateest_save_rate(const struct xt_rateest_match_info *info, const char *name, uint32_t r1, uint32_t r2, int numeric) { if (info->flags & XT_RATEEST_MATCH_DELTA) { printf(" --rateest-%s1", name); rateest_print_rate(r1, numeric); rateest_print_mode(info, "--rateest-"); printf(" --rateest-%s2", name); } else { rateest_print_mode(info, "--rateest-"); printf(" --rateest-%s", name); } if (info->flags & (XT_RATEEST_MATCH_ABS|XT_RATEEST_MATCH_DELTA)) rateest_print_rate(r2, numeric); } static void rateest_save_rates(const struct xt_rateest_match_info *info) { if (info->flags & XT_RATEEST_MATCH_BPS) __rateest_save_rate(info, "bps", info->bps1, info->bps2, 0); if (info->flags & XT_RATEEST_MATCH_PPS) __rateest_save_rate(info, "pps", info->pps1, info->pps2, 1); } static void rateest_save(const void *ip, const struct xt_entry_match *match) { const struct xt_rateest_match_info *info = (const void *)match->data; if (info->flags & XT_RATEEST_MATCH_DELTA) printf(" --rateest-delta"); if (info->flags & XT_RATEEST_MATCH_REL) { printf(" --rateest1 %s", info->name1); rateest_save_rates(info); printf(" --rateest2 %s", info->name2); } else { /* XT_RATEEST_MATCH_ABS */ printf(" --rateest %s", info->name1); rateest_save_rates(info); } } static struct xtables_match rateest_mt_reg = { .family = NFPROTO_UNSPEC, .name = "rateest", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_rateest_match_info)), .userspacesize = XT_ALIGN(offsetof(struct xt_rateest_match_info, est1)), .help = rateest_help, .parse = rateest_parse, .x6_fcheck = rateest_final_check, .print = rateest_print, .save = rateest_save, .extra_opts = rateest_opts, }; void _init(void) { xtables_register_match(&rateest_mt_reg); }
271
./android_firewall/external/iptables/extensions/libipt_DNAT.c
#include <stdio.h> #include <netdb.h> #include <string.h> #include <stdlib.h> #include <xtables.h> #include <iptables.h> /* get_kernel_version */ #include <limits.h> /* INT_MAX in ip_tables.h */ #include <linux/netfilter_ipv4/ip_tables.h> #include <net/netfilter/nf_nat.h> enum { O_TO_DEST = 0, O_RANDOM, O_PERSISTENT, O_X_TO_DEST, /* hidden flag */ F_TO_DEST = 1 << O_TO_DEST, F_RANDOM = 1 << O_RANDOM, F_X_TO_DEST = 1 << O_X_TO_DEST, }; /* Dest NAT data consists of a multi-range, indicating where to map to. */ struct ipt_natinfo { struct xt_entry_target t; struct nf_nat_multi_range mr; }; static void DNAT_help(void) { printf( "DNAT target options:\n" " --to-destination [<ipaddr>[-<ipaddr>]][:port[-port]]\n" " Address to map destination to.\n" "[--random] [--persistent]\n"); } static const struct xt_option_entry DNAT_opts[] = { {.name = "to-destination", .id = O_TO_DEST, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_MULTI}, {.name = "random", .id = O_RANDOM, .type = XTTYPE_NONE}, {.name = "persistent", .id = O_PERSISTENT, .type = XTTYPE_NONE}, XTOPT_TABLEEND, }; static struct ipt_natinfo * append_range(struct ipt_natinfo *info, const struct nf_nat_range *range) { unsigned int size; /* One rangesize already in struct ipt_natinfo */ size = XT_ALIGN(sizeof(*info) + info->mr.rangesize * sizeof(*range)); info = realloc(info, size); if (!info) xtables_error(OTHER_PROBLEM, "Out of memory\n"); info->t.u.target_size = size; info->mr.range[info->mr.rangesize] = *range; info->mr.rangesize++; return info; } /* Ranges expected in network order. */ static struct xt_entry_target * parse_to(const char *orig_arg, int portok, struct ipt_natinfo *info) { struct nf_nat_range range; char *arg, *colon, *dash, *error; const struct in_addr *ip; arg = strdup(orig_arg); if (arg == NULL) xtables_error(RESOURCE_PROBLEM, "strdup"); memset(&range, 0, sizeof(range)); colon = strchr(arg, ':'); if (colon) { int port; if (!portok) xtables_error(PARAMETER_PROBLEM, "Need TCP, UDP, SCTP or DCCP with port specification"); range.flags |= IP_NAT_RANGE_PROTO_SPECIFIED; port = atoi(colon+1); if (port <= 0 || port > 65535) xtables_error(PARAMETER_PROBLEM, "Port `%s' not valid\n", colon+1); error = strchr(colon+1, ':'); if (error) xtables_error(PARAMETER_PROBLEM, "Invalid port:port syntax - use dash\n"); dash = strchr(colon, '-'); if (!dash) { range.min.tcp.port = range.max.tcp.port = htons(port); } else { int maxport; maxport = atoi(dash + 1); if (maxport <= 0 || maxport > 65535) xtables_error(PARAMETER_PROBLEM, "Port `%s' not valid\n", dash+1); if (maxport < port) /* People are stupid. */ xtables_error(PARAMETER_PROBLEM, "Port range `%s' funky\n", colon+1); range.min.tcp.port = htons(port); range.max.tcp.port = htons(maxport); } /* Starts with a colon? No IP info...*/ if (colon == arg) { free(arg); return &(append_range(info, &range)->t); } *colon = '\0'; } range.flags |= IP_NAT_RANGE_MAP_IPS; dash = strchr(arg, '-'); if (colon && dash && dash > colon) dash = NULL; if (dash) *dash = '\0'; ip = xtables_numeric_to_ipaddr(arg); if (!ip) xtables_error(PARAMETER_PROBLEM, "Bad IP address \"%s\"\n", arg); range.min_ip = ip->s_addr; if (dash) { ip = xtables_numeric_to_ipaddr(dash+1); if (!ip) xtables_error(PARAMETER_PROBLEM, "Bad IP address \"%s\"\n", dash+1); range.max_ip = ip->s_addr; } else range.max_ip = range.min_ip; free(arg); return &(append_range(info, &range)->t); } static void DNAT_parse(struct xt_option_call *cb) { const struct ipt_entry *entry = cb->xt_entry; struct ipt_natinfo *info = (void *)(*cb->target); int portok; if (entry->ip.proto == IPPROTO_TCP || entry->ip.proto == IPPROTO_UDP || entry->ip.proto == IPPROTO_SCTP || entry->ip.proto == IPPROTO_DCCP || entry->ip.proto == IPPROTO_ICMP) portok = 1; else portok = 0; xtables_option_parse(cb); switch (cb->entry->id) { case O_TO_DEST: if (cb->xflags & F_X_TO_DEST) { if (!kernel_version) get_kernel_version(); if (kernel_version > LINUX_VERSION(2, 6, 10)) xtables_error(PARAMETER_PROBLEM, "DNAT: Multiple --to-destination not supported"); } *cb->target = parse_to(cb->arg, portok, info); cb->xflags |= F_X_TO_DEST; break; case O_PERSISTENT: info->mr.range[0].flags |= IP_NAT_RANGE_PERSISTENT; break; } } static void DNAT_fcheck(struct xt_fcheck_call *cb) { static const unsigned int f = F_TO_DEST | F_RANDOM; struct nf_nat_multi_range *mr = cb->data; if ((cb->xflags & f) == f) mr->range[0].flags |= IP_NAT_RANGE_PROTO_RANDOM; } static void print_range(const struct nf_nat_range *r) { if (r->flags & IP_NAT_RANGE_MAP_IPS) { struct in_addr a; a.s_addr = r->min_ip; printf("%s", xtables_ipaddr_to_numeric(&a)); if (r->max_ip != r->min_ip) { a.s_addr = r->max_ip; printf("-%s", xtables_ipaddr_to_numeric(&a)); } } if (r->flags & IP_NAT_RANGE_PROTO_SPECIFIED) { printf(":"); printf("%hu", ntohs(r->min.tcp.port)); if (r->max.tcp.port != r->min.tcp.port) printf("-%hu", ntohs(r->max.tcp.port)); } } static void DNAT_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct ipt_natinfo *info = (const void *)target; unsigned int i = 0; printf(" to:"); for (i = 0; i < info->mr.rangesize; i++) { print_range(&info->mr.range[i]); if (info->mr.range[i].flags & IP_NAT_RANGE_PROTO_RANDOM) printf(" random"); if (info->mr.range[i].flags & IP_NAT_RANGE_PERSISTENT) printf(" persistent"); } } static void DNAT_save(const void *ip, const struct xt_entry_target *target) { const struct ipt_natinfo *info = (const void *)target; unsigned int i = 0; for (i = 0; i < info->mr.rangesize; i++) { printf(" --to-destination "); print_range(&info->mr.range[i]); if (info->mr.range[i].flags & IP_NAT_RANGE_PROTO_RANDOM) printf(" --random"); if (info->mr.range[i].flags & IP_NAT_RANGE_PERSISTENT) printf(" --persistent"); } } static struct xtables_target dnat_tg_reg = { .name = "DNAT", .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct nf_nat_multi_range)), .userspacesize = XT_ALIGN(sizeof(struct nf_nat_multi_range)), .help = DNAT_help, .x6_parse = DNAT_parse, .x6_fcheck = DNAT_fcheck, .print = DNAT_print, .save = DNAT_save, .x6_options = DNAT_opts, }; void _init(void) { xtables_register_target(&dnat_tg_reg); }
272
./android_firewall/external/iptables/extensions/libxt_dscp.c
/* Shared library add-on to iptables for DSCP * * (C) 2002 by Harald Welte <[email protected]> * * This program is distributed under the terms of GNU GPL v2, 1991 * * libipt_dscp.c borrowed heavily from libipt_tos.c * * --class support added by Iain Barnes * * For a list of DSCP codepoints see * http://www.iana.org/assignments/dscp-registry * */ #include <stdio.h> #include <string.h> #include <xtables.h> #include <linux/netfilter/xt_dscp.h> /* This is evil, but it's my code - HW*/ #include "dscp_helper.c" enum { O_DSCP = 0, O_DSCP_CLASS, F_DSCP = 1 << O_DSCP, F_DSCP_CLASS = 1 << O_DSCP_CLASS, }; static void dscp_help(void) { printf( "dscp match options\n" "[!] --dscp value Match DSCP codepoint with numerical value\n" " This value can be in decimal (ex: 32)\n" " or in hex (ex: 0x20)\n" "[!] --dscp-class name Match the DiffServ class. This value may\n" " be any of the BE,EF, AFxx or CSx classes\n" "\n" " These two options are mutually exclusive !\n"); } static const struct xt_option_entry dscp_opts[] = { {.name = "dscp", .id = O_DSCP, .excl = F_DSCP_CLASS, .type = XTTYPE_UINT8, .min = 0, .max = XT_DSCP_MAX, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(struct xt_dscp_info, dscp)}, {.name = "dscp-class", .id = O_DSCP_CLASS, .excl = F_DSCP, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, XTOPT_TABLEEND, }; static void dscp_parse(struct xt_option_call *cb) { struct xt_dscp_info *dinfo = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_DSCP: if (cb->invert) dinfo->invert = 1; break; case O_DSCP_CLASS: dinfo->dscp = class_to_dscp(cb->arg); if (cb->invert) dinfo->invert = 1; break; } } static void dscp_check(struct xt_fcheck_call *cb) { if (cb->xflags == 0) xtables_error(PARAMETER_PROBLEM, "DSCP match: Parameter --dscp is required"); } static void dscp_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_dscp_info *dinfo = (const struct xt_dscp_info *)match->data; printf(" DSCP match %s0x%02x", dinfo->invert ? "!" : "", dinfo->dscp); } static void dscp_save(const void *ip, const struct xt_entry_match *match) { const struct xt_dscp_info *dinfo = (const struct xt_dscp_info *)match->data; printf("%s --dscp 0x%02x", dinfo->invert ? " !" : "", dinfo->dscp); } static struct xtables_match dscp_match = { .family = NFPROTO_UNSPEC, .name = "dscp", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_dscp_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_dscp_info)), .help = dscp_help, .print = dscp_print, .save = dscp_save, .x6_parse = dscp_parse, .x6_fcheck = dscp_check, .x6_options = dscp_opts, }; void _init(void) { xtables_register_match(&dscp_match); }
273
./android_firewall/external/iptables/extensions/libxt_udp.c
#include <stdint.h> #include <stdio.h> #include <netdb.h> #include <arpa/inet.h> #include <xtables.h> #include <linux/netfilter/xt_tcpudp.h> enum { O_SOURCE_PORT = 0, O_DEST_PORT, }; static void udp_help(void) { printf( "udp match options:\n" "[!] --source-port port[:port]\n" " --sport ...\n" " match source port(s)\n" "[!] --destination-port port[:port]\n" " --dport ...\n" " match destination port(s)\n"); } #define s struct xt_udp static const struct xt_option_entry udp_opts[] = { {.name = "source-port", .id = O_SOURCE_PORT, .type = XTTYPE_PORTRC, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, spts)}, {.name = "sport", .id = O_SOURCE_PORT, .type = XTTYPE_PORTRC, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, spts)}, {.name = "destination-port", .id = O_DEST_PORT, .type = XTTYPE_PORTRC, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, dpts)}, {.name = "dport", .id = O_DEST_PORT, .type = XTTYPE_PORTRC, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, dpts)}, XTOPT_TABLEEND, }; #undef s static void udp_init(struct xt_entry_match *m) { struct xt_udp *udpinfo = (struct xt_udp *)m->data; udpinfo->spts[1] = udpinfo->dpts[1] = 0xFFFF; } static void udp_parse(struct xt_option_call *cb) { struct xt_udp *udpinfo = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_SOURCE_PORT: if (cb->invert) udpinfo->invflags |= XT_UDP_INV_SRCPT; break; case O_DEST_PORT: if (cb->invert) udpinfo->invflags |= XT_UDP_INV_DSTPT; break; } } static const char * port_to_service(int port) { const struct servent *service; if ((service = getservbyport(htons(port), "udp"))) return service->s_name; return NULL; } static void print_port(uint16_t port, int numeric) { const char *service; if (numeric || (service = port_to_service(port)) == NULL) printf("%u", port); else printf("%s", service); } static void print_ports(const char *name, uint16_t min, uint16_t max, int invert, int numeric) { const char *inv = invert ? "!" : ""; if (min != 0 || max != 0xFFFF || invert) { printf(" %s", name); if (min == max) { printf(":%s", inv); print_port(min, numeric); } else { printf("s:%s", inv); print_port(min, numeric); printf(":"); print_port(max, numeric); } } } static void udp_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_udp *udp = (struct xt_udp *)match->data; printf(" udp"); print_ports("spt", udp->spts[0], udp->spts[1], udp->invflags & XT_UDP_INV_SRCPT, numeric); print_ports("dpt", udp->dpts[0], udp->dpts[1], udp->invflags & XT_UDP_INV_DSTPT, numeric); if (udp->invflags & ~XT_UDP_INV_MASK) printf(" Unknown invflags: 0x%X", udp->invflags & ~XT_UDP_INV_MASK); } static void udp_save(const void *ip, const struct xt_entry_match *match) { const struct xt_udp *udpinfo = (struct xt_udp *)match->data; if (udpinfo->spts[0] != 0 || udpinfo->spts[1] != 0xFFFF) { if (udpinfo->invflags & XT_UDP_INV_SRCPT) printf(" !"); if (udpinfo->spts[0] != udpinfo->spts[1]) printf(" --sport %u:%u", udpinfo->spts[0], udpinfo->spts[1]); else printf(" --sport %u", udpinfo->spts[0]); } if (udpinfo->dpts[0] != 0 || udpinfo->dpts[1] != 0xFFFF) { if (udpinfo->invflags & XT_UDP_INV_DSTPT) printf(" !"); if (udpinfo->dpts[0] != udpinfo->dpts[1]) printf(" --dport %u:%u", udpinfo->dpts[0], udpinfo->dpts[1]); else printf(" --dport %u", udpinfo->dpts[0]); } } static struct xtables_match udp_match = { .family = NFPROTO_UNSPEC, .name = "udp", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_udp)), .userspacesize = XT_ALIGN(sizeof(struct xt_udp)), .help = udp_help, .init = udp_init, .print = udp_print, .save = udp_save, .x6_parse = udp_parse, .x6_options = udp_opts, }; void _init(void) { xtables_register_match(&udp_match); }
274
./android_firewall/external/iptables/extensions/libxt_osf.c
/* * Copyright (c) 2003+ Evgeniy Polyakov <[email protected]> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * xtables interface for OS fingerprint matching module. */ #include <stdio.h> #include <string.h> #include <xtables.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <linux/netfilter/xt_osf.h> enum { O_GENRE = 0, O_TTL, O_LOGLEVEL, }; static void osf_help(void) { printf("OS fingerprint match options:\n" "[!] --genre string Match a OS genre by passive fingerprinting.\n" "--ttl level Use some TTL check extensions to determine OS:\n" " 0 true ip and fingerprint TTL comparison. Works for LAN.\n" " 1 check if ip TTL is less than fingerprint one. Works for global addresses.\n" " 2 do not compare TTL at all. Allows to detect NMAP, but can produce false results.\n" "--log level Log determined genres into dmesg even if they do not match desired one:\n" " 0 log all matched or unknown signatures.\n" " 1 log only first one.\n" " 2 log all known matched signatures.\n" ); } #define s struct xt_osf_info static const struct xt_option_entry osf_opts[] = { {.name = "genre", .id = O_GENRE, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, genre)}, {.name = "ttl", .id = O_TTL, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, ttl), .min = 0, .max = 2}, {.name = "log", .id = O_LOGLEVEL, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, loglevel), .min = 0, .max = 2}, XTOPT_TABLEEND, }; #undef s static void osf_parse(struct xt_option_call *cb) { struct xt_osf_info *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_GENRE: if (cb->invert) info->flags |= XT_OSF_INVERT; info->len = strlen(info->genre); break; case O_TTL: info->flags |= XT_OSF_TTL; break; case O_LOGLEVEL: info->flags |= XT_OSF_LOG; break; } } static void osf_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_osf_info *info = (const struct xt_osf_info*) match->data; printf(" OS fingerprint match %s%s", (info->flags & XT_OSF_INVERT) ? "! " : "", info->genre); } static void osf_save(const void *ip, const struct xt_entry_match *match) { const struct xt_osf_info *info = (const struct xt_osf_info*) match->data; printf(" --genre %s%s", (info->flags & XT_OSF_INVERT) ? "! ": "", info->genre); } static struct xtables_match osf_match = { .name = "osf", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_osf_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_osf_info)), .help = osf_help, .x6_parse = osf_parse, .print = osf_print, .save = osf_save, .x6_options = osf_opts, .family = NFPROTO_IPV4, }; void _init(void) { xtables_register_match(&osf_match); }
275
./android_firewall/external/iptables/extensions/libipt_unclean.c
/* Shared library add-on to iptables for unclean. */ #include <xtables.h> static struct xtables_match unclean_mt_reg = { .name = "unclean", .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(0), .userspacesize = XT_ALIGN(0), }; void _init(void) { xtables_register_match(&unclean_mt_reg); }
276
./android_firewall/external/iptables/extensions/libxt_esp.c
#include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_esp.h> enum { O_ESPSPI = 0, }; static void esp_help(void) { printf( "esp match options:\n" "[!] --espspi spi[:spi]\n" " match spi (range)\n"); } static const struct xt_option_entry esp_opts[] = { {.name = "espspi", .id = O_ESPSPI, .type = XTTYPE_UINT32RC, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(struct xt_esp, spis)}, XTOPT_TABLEEND, }; static void esp_parse(struct xt_option_call *cb) { struct xt_esp *espinfo = cb->data; xtables_option_parse(cb); if (cb->nvals == 1) espinfo->spis[1] = espinfo->spis[0]; if (cb->invert) espinfo->invflags |= XT_ESP_INV_SPI; } static void print_spis(const char *name, uint32_t min, uint32_t max, int invert) { const char *inv = invert ? "!" : ""; if (min != 0 || max != 0xFFFFFFFF || invert) { if (min == max) printf(" %s:%s%u", name, inv, min); else printf(" %ss:%s%u:%u", name, inv, min, max); } } static void esp_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_esp *esp = (struct xt_esp *)match->data; printf(" esp"); print_spis("spi", esp->spis[0], esp->spis[1], esp->invflags & XT_ESP_INV_SPI); if (esp->invflags & ~XT_ESP_INV_MASK) printf(" Unknown invflags: 0x%X", esp->invflags & ~XT_ESP_INV_MASK); } static void esp_save(const void *ip, const struct xt_entry_match *match) { const struct xt_esp *espinfo = (struct xt_esp *)match->data; if (!(espinfo->spis[0] == 0 && espinfo->spis[1] == 0xFFFFFFFF)) { printf("%s --espspi ", (espinfo->invflags & XT_ESP_INV_SPI) ? " !" : ""); if (espinfo->spis[0] != espinfo->spis[1]) printf("%u:%u", espinfo->spis[0], espinfo->spis[1]); else printf("%u", espinfo->spis[0]); } } static struct xtables_match esp_match = { .family = NFPROTO_UNSPEC, .name = "esp", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_esp)), .userspacesize = XT_ALIGN(sizeof(struct xt_esp)), .help = esp_help, .print = esp_print, .save = esp_save, .x6_parse = esp_parse, .x6_options = esp_opts, }; void _init(void) { xtables_register_match(&esp_match); }
277
./android_firewall/external/iptables/extensions/libipt_icmp.c
#include <stdint.h> #include <stdio.h> #include <string.h> #include <xtables.h> #include <limits.h> /* INT_MAX in ip6_tables.h */ #include <linux/netfilter_ipv4/ip_tables.h> /* special hack for icmp-type 'any': * Up to kernel <=2.4.20 the problem was: * '-p icmp ' matches all icmp packets * '-p icmp -m icmp' matches _only_ ICMP type 0 :( * This is now fixed by initializing the field * to icmp type 0xFF * See: https://bugzilla.netfilter.org/cgi-bin/bugzilla/show_bug.cgi?id=37 */ enum { O_ICMP_TYPE = 0, }; struct icmp_names { const char *name; uint8_t type; uint8_t code_min, code_max; }; static const struct icmp_names icmp_codes[] = { { "any", 0xFF, 0, 0xFF }, { "echo-reply", 0, 0, 0xFF }, /* Alias */ { "pong", 0, 0, 0xFF }, { "destination-unreachable", 3, 0, 0xFF }, { "network-unreachable", 3, 0, 0 }, { "host-unreachable", 3, 1, 1 }, { "protocol-unreachable", 3, 2, 2 }, { "port-unreachable", 3, 3, 3 }, { "fragmentation-needed", 3, 4, 4 }, { "source-route-failed", 3, 5, 5 }, { "network-unknown", 3, 6, 6 }, { "host-unknown", 3, 7, 7 }, { "network-prohibited", 3, 9, 9 }, { "host-prohibited", 3, 10, 10 }, { "TOS-network-unreachable", 3, 11, 11 }, { "TOS-host-unreachable", 3, 12, 12 }, { "communication-prohibited", 3, 13, 13 }, { "host-precedence-violation", 3, 14, 14 }, { "precedence-cutoff", 3, 15, 15 }, { "source-quench", 4, 0, 0xFF }, { "redirect", 5, 0, 0xFF }, { "network-redirect", 5, 0, 0 }, { "host-redirect", 5, 1, 1 }, { "TOS-network-redirect", 5, 2, 2 }, { "TOS-host-redirect", 5, 3, 3 }, { "echo-request", 8, 0, 0xFF }, /* Alias */ { "ping", 8, 0, 0xFF }, { "router-advertisement", 9, 0, 0xFF }, { "router-solicitation", 10, 0, 0xFF }, { "time-exceeded", 11, 0, 0xFF }, /* Alias */ { "ttl-exceeded", 11, 0, 0xFF }, { "ttl-zero-during-transit", 11, 0, 0 }, { "ttl-zero-during-reassembly", 11, 1, 1 }, { "parameter-problem", 12, 0, 0xFF }, { "ip-header-bad", 12, 0, 0 }, { "required-option-missing", 12, 1, 1 }, { "timestamp-request", 13, 0, 0xFF }, { "timestamp-reply", 14, 0, 0xFF }, { "address-mask-request", 17, 0, 0xFF }, { "address-mask-reply", 18, 0, 0xFF } }; static void print_icmptypes(void) { unsigned int i; printf("Valid ICMP Types:"); for (i = 0; i < ARRAY_SIZE(icmp_codes); ++i) { if (i && icmp_codes[i].type == icmp_codes[i-1].type) { if (icmp_codes[i].code_min == icmp_codes[i-1].code_min && (icmp_codes[i].code_max == icmp_codes[i-1].code_max)) printf(" (%s)", icmp_codes[i].name); else printf("\n %s", icmp_codes[i].name); } else printf("\n%s", icmp_codes[i].name); } printf("\n"); } static void icmp_help(void) { printf( "icmp match options:\n" "[!] --icmp-type typename match icmp type\n" "[!] --icmp-type type[/code] (or numeric type or type/code)\n"); print_icmptypes(); } static const struct xt_option_entry icmp_opts[] = { {.name = "icmp-type", .id = O_ICMP_TYPE, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_INVERT}, XTOPT_TABLEEND, }; static void parse_icmp(const char *icmptype, uint8_t *type, uint8_t code[]) { static const unsigned int limit = ARRAY_SIZE(icmp_codes); unsigned int match = limit; unsigned int i; for (i = 0; i < limit; i++) { if (strncasecmp(icmp_codes[i].name, icmptype, strlen(icmptype)) == 0) { if (match != limit) xtables_error(PARAMETER_PROBLEM, "Ambiguous ICMP type `%s':" " `%s' or `%s'?", icmptype, icmp_codes[match].name, icmp_codes[i].name); match = i; } } if (match != limit) { *type = icmp_codes[match].type; code[0] = icmp_codes[match].code_min; code[1] = icmp_codes[match].code_max; } else { char *slash; char buffer[strlen(icmptype) + 1]; unsigned int number; strcpy(buffer, icmptype); slash = strchr(buffer, '/'); if (slash) *slash = '\0'; if (!xtables_strtoui(buffer, NULL, &number, 0, UINT8_MAX)) xtables_error(PARAMETER_PROBLEM, "Invalid ICMP type `%s'\n", buffer); *type = number; if (slash) { if (!xtables_strtoui(slash+1, NULL, &number, 0, UINT8_MAX)) xtables_error(PARAMETER_PROBLEM, "Invalid ICMP code `%s'\n", slash+1); code[0] = code[1] = number; } else { code[0] = 0; code[1] = 0xFF; } } } static void icmp_init(struct xt_entry_match *m) { struct ipt_icmp *icmpinfo = (struct ipt_icmp *)m->data; icmpinfo->type = 0xFF; icmpinfo->code[1] = 0xFF; } static void icmp_parse(struct xt_option_call *cb) { struct ipt_icmp *icmpinfo = cb->data; xtables_option_parse(cb); parse_icmp(cb->arg, &icmpinfo->type, icmpinfo->code); if (cb->invert) icmpinfo->invflags |= IPT_ICMP_INV; } static void print_icmptype(uint8_t type, uint8_t code_min, uint8_t code_max, int invert, int numeric) { if (!numeric) { unsigned int i; for (i = 0; i < ARRAY_SIZE(icmp_codes); ++i) if (icmp_codes[i].type == type && icmp_codes[i].code_min == code_min && icmp_codes[i].code_max == code_max) break; if (i != ARRAY_SIZE(icmp_codes)) { printf(" %s%s", invert ? "!" : "", icmp_codes[i].name); return; } } if (invert) printf(" !"); printf("type %u", type); if (code_min == code_max) printf(" code %u", code_min); else if (code_min != 0 || code_max != 0xFF) printf(" codes %u-%u", code_min, code_max); } static void icmp_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct ipt_icmp *icmp = (struct ipt_icmp *)match->data; printf(" icmp"); print_icmptype(icmp->type, icmp->code[0], icmp->code[1], icmp->invflags & IPT_ICMP_INV, numeric); if (icmp->invflags & ~IPT_ICMP_INV) printf(" Unknown invflags: 0x%X", icmp->invflags & ~IPT_ICMP_INV); } static void icmp_save(const void *ip, const struct xt_entry_match *match) { const struct ipt_icmp *icmp = (struct ipt_icmp *)match->data; if (icmp->invflags & IPT_ICMP_INV) printf(" !"); /* special hack for 'any' case */ if (icmp->type == 0xFF) { printf(" --icmp-type any"); } else { printf(" --icmp-type %u", icmp->type); if (icmp->code[0] != 0 || icmp->code[1] != 0xFF) printf("/%u", icmp->code[0]); } } static struct xtables_match icmp_mt_reg = { .name = "icmp", .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct ipt_icmp)), .userspacesize = XT_ALIGN(sizeof(struct ipt_icmp)), .help = icmp_help, .init = icmp_init, .print = icmp_print, .save = icmp_save, .x6_parse = icmp_parse, .x6_options = icmp_opts, }; void _init(void) { xtables_register_match(&icmp_mt_reg); }
278
./android_firewall/external/iptables/extensions/libxt_NFLOG.c
#include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <getopt.h> #include <xtables.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter/xt_NFLOG.h> enum { O_GROUP = 0, O_PREFIX, O_RANGE, O_THRESHOLD, }; #define s struct xt_nflog_info static const struct xt_option_entry NFLOG_opts[] = { {.name = "nflog-group", .id = O_GROUP, .type = XTTYPE_UINT16, .flags = XTOPT_PUT, XTOPT_POINTER(s, group)}, {.name = "nflog-prefix", .id = O_PREFIX, .type = XTTYPE_STRING, .min = 1, .flags = XTOPT_PUT, XTOPT_POINTER(s, prefix)}, {.name = "nflog-range", .id = O_RANGE, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, len)}, {.name = "nflog-threshold", .id = O_THRESHOLD, .type = XTTYPE_UINT16, .flags = XTOPT_PUT, XTOPT_POINTER(s, threshold)}, XTOPT_TABLEEND, }; #undef s static void NFLOG_help(void) { printf("NFLOG target options:\n" " --nflog-group NUM NETLINK group used for logging\n" " --nflog-range NUM Number of byte to copy\n" " --nflog-threshold NUM Message threshold of in-kernel queue\n" " --nflog-prefix STRING Prefix string for log messages\n"); } static void NFLOG_init(struct xt_entry_target *t) { struct xt_nflog_info *info = (struct xt_nflog_info *)t->data; info->threshold = XT_NFLOG_DEFAULT_THRESHOLD; } static void NFLOG_parse(struct xt_option_call *cb) { xtables_option_parse(cb); switch (cb->entry->id) { case O_PREFIX: if (strchr(cb->arg, '\n') != NULL) xtables_error(PARAMETER_PROBLEM, "Newlines not allowed in --log-prefix"); break; } } static void nflog_print(const struct xt_nflog_info *info, char *prefix) { if (info->prefix[0] != '\0') { printf(" %snflog-prefix ", prefix); xtables_save_string(info->prefix); } if (info->group) printf(" %snflog-group %u", prefix, info->group); if (info->len) printf(" %snflog-range %u", prefix, info->len); if (info->threshold != XT_NFLOG_DEFAULT_THRESHOLD) printf(" %snflog-threshold %u", prefix, info->threshold); } static void NFLOG_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_nflog_info *info = (struct xt_nflog_info *)target->data; nflog_print(info, ""); } static void NFLOG_save(const void *ip, const struct xt_entry_target *target) { const struct xt_nflog_info *info = (struct xt_nflog_info *)target->data; nflog_print(info, "--"); } static struct xtables_target nflog_target = { .family = NFPROTO_UNSPEC, .name = "NFLOG", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_nflog_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_nflog_info)), .help = NFLOG_help, .init = NFLOG_init, .x6_parse = NFLOG_parse, .print = NFLOG_print, .save = NFLOG_save, .x6_options = NFLOG_opts, }; void _init(void) { xtables_register_target(&nflog_target); }
279
./android_firewall/external/iptables/extensions/libxt_mark.c
#include <stdbool.h> #include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_mark.h> struct xt_mark_info { unsigned long mark, mask; uint8_t invert; }; enum { O_MARK = 0, }; static void mark_mt_help(void) { printf( "mark match options:\n" "[!] --mark value[/mask] Match nfmark value with optional mask\n"); } static const struct xt_option_entry mark_mt_opts[] = { {.name = "mark", .id = O_MARK, .type = XTTYPE_MARKMASK32, .flags = XTOPT_MAND | XTOPT_INVERT}, XTOPT_TABLEEND, }; static void mark_mt_parse(struct xt_option_call *cb) { struct xt_mark_mtinfo1 *info = cb->data; xtables_option_parse(cb); if (cb->invert) info->invert = true; info->mark = cb->val.mark; info->mask = cb->val.mask; } static void mark_parse(struct xt_option_call *cb) { struct xt_mark_info *markinfo = cb->data; xtables_option_parse(cb); if (cb->invert) markinfo->invert = 1; markinfo->mark = cb->val.mark; markinfo->mask = cb->val.mask; } static void print_mark(unsigned int mark, unsigned int mask) { if (mask != 0xffffffffU) printf(" 0x%x/0x%x", mark, mask); else printf(" 0x%x", mark); } static void mark_mt_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_mark_mtinfo1 *info = (const void *)match->data; printf(" mark match"); if (info->invert) printf(" !"); print_mark(info->mark, info->mask); } static void mark_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_mark_info *info = (const void *)match->data; printf(" MARK match"); if (info->invert) printf(" !"); print_mark(info->mark, info->mask); } static void mark_mt_save(const void *ip, const struct xt_entry_match *match) { const struct xt_mark_mtinfo1 *info = (const void *)match->data; if (info->invert) printf(" !"); printf(" --mark"); print_mark(info->mark, info->mask); } static void mark_save(const void *ip, const struct xt_entry_match *match) { const struct xt_mark_info *info = (const void *)match->data; if (info->invert) printf(" !"); printf(" --mark"); print_mark(info->mark, info->mask); } static struct xtables_match mark_mt_reg[] = { { .family = NFPROTO_UNSPEC, .name = "mark", .revision = 0, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_mark_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_mark_info)), .help = mark_mt_help, .print = mark_print, .save = mark_save, .x6_parse = mark_parse, .x6_options = mark_mt_opts, }, { .version = XTABLES_VERSION, .name = "mark", .revision = 1, .family = NFPROTO_UNSPEC, .size = XT_ALIGN(sizeof(struct xt_mark_mtinfo1)), .userspacesize = XT_ALIGN(sizeof(struct xt_mark_mtinfo1)), .help = mark_mt_help, .print = mark_mt_print, .save = mark_mt_save, .x6_parse = mark_mt_parse, .x6_options = mark_mt_opts, }, }; void _init(void) { xtables_register_matches(mark_mt_reg, ARRAY_SIZE(mark_mt_reg)); }
280
./android_firewall/external/iptables/extensions/libipt_REDIRECT.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <xtables.h> #include <limits.h> /* INT_MAX in ip_tables.h */ #include <linux/netfilter_ipv4/ip_tables.h> #include <net/netfilter/nf_nat.h> enum { O_TO_PORTS = 0, O_RANDOM, F_TO_PORTS = 1 << O_TO_PORTS, F_RANDOM = 1 << O_RANDOM, }; static void REDIRECT_help(void) { printf( "REDIRECT target options:\n" " --to-ports <port>[-<port>]\n" " Port (range) to map to.\n" " [--random]\n"); } static const struct xt_option_entry REDIRECT_opts[] = { {.name = "to-ports", .id = O_TO_PORTS, .type = XTTYPE_STRING}, {.name = "random", .id = O_RANDOM, .type = XTTYPE_NONE}, XTOPT_TABLEEND, }; static void REDIRECT_init(struct xt_entry_target *t) { struct nf_nat_multi_range *mr = (struct nf_nat_multi_range *)t->data; /* Actually, it's 0, but it's ignored at the moment. */ mr->rangesize = 1; } /* Parses ports */ static void parse_ports(const char *arg, struct nf_nat_multi_range *mr) { char *end = ""; unsigned int port, maxport; mr->range[0].flags |= IP_NAT_RANGE_PROTO_SPECIFIED; if (!xtables_strtoui(arg, &end, &port, 0, UINT16_MAX) && (port = xtables_service_to_port(arg, NULL)) == (unsigned)-1) xtables_param_act(XTF_BAD_VALUE, "REDIRECT", "--to-ports", arg); switch (*end) { case '\0': mr->range[0].min.tcp.port = mr->range[0].max.tcp.port = htons(port); return; case '-': if (!xtables_strtoui(end + 1, NULL, &maxport, 0, UINT16_MAX) && (maxport = xtables_service_to_port(end + 1, NULL)) == (unsigned)-1) break; if (maxport < port) break; mr->range[0].min.tcp.port = htons(port); mr->range[0].max.tcp.port = htons(maxport); return; default: break; } xtables_param_act(XTF_BAD_VALUE, "REDIRECT", "--to-ports", arg); } static void REDIRECT_parse(struct xt_option_call *cb) { const struct ipt_entry *entry = cb->xt_entry; struct nf_nat_multi_range *mr = (void *)(*cb->target)->data; int portok; if (entry->ip.proto == IPPROTO_TCP || entry->ip.proto == IPPROTO_UDP || entry->ip.proto == IPPROTO_SCTP || entry->ip.proto == IPPROTO_DCCP || entry->ip.proto == IPPROTO_ICMP) portok = 1; else portok = 0; xtables_option_parse(cb); switch (cb->entry->id) { case O_TO_PORTS: if (!portok) xtables_error(PARAMETER_PROBLEM, "Need TCP, UDP, SCTP or DCCP with port specification"); parse_ports(cb->arg, mr); if (cb->xflags & F_RANDOM) mr->range[0].flags |= IP_NAT_RANGE_PROTO_RANDOM; break; case O_RANDOM: if (cb->xflags & F_TO_PORTS) mr->range[0].flags |= IP_NAT_RANGE_PROTO_RANDOM; break; } } static void REDIRECT_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct nf_nat_multi_range *mr = (const void *)target->data; const struct nf_nat_range *r = &mr->range[0]; if (r->flags & IP_NAT_RANGE_PROTO_SPECIFIED) { printf(" redir ports "); printf("%hu", ntohs(r->min.tcp.port)); if (r->max.tcp.port != r->min.tcp.port) printf("-%hu", ntohs(r->max.tcp.port)); if (mr->range[0].flags & IP_NAT_RANGE_PROTO_RANDOM) printf(" random"); } } static void REDIRECT_save(const void *ip, const struct xt_entry_target *target) { const struct nf_nat_multi_range *mr = (const void *)target->data; const struct nf_nat_range *r = &mr->range[0]; if (r->flags & IP_NAT_RANGE_PROTO_SPECIFIED) { printf(" --to-ports "); printf("%hu", ntohs(r->min.tcp.port)); if (r->max.tcp.port != r->min.tcp.port) printf("-%hu", ntohs(r->max.tcp.port)); if (mr->range[0].flags & IP_NAT_RANGE_PROTO_RANDOM) printf(" --random"); } } static struct xtables_target redirect_tg_reg = { .name = "REDIRECT", .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct nf_nat_multi_range)), .userspacesize = XT_ALIGN(sizeof(struct nf_nat_multi_range)), .help = REDIRECT_help, .init = REDIRECT_init, .x6_parse = REDIRECT_parse, .print = REDIRECT_print, .save = REDIRECT_save, .x6_options = REDIRECT_opts, }; void _init(void) { xtables_register_target(&redirect_tg_reg); }
281
./android_firewall/external/iptables/extensions/libxt_DSCP.c
/* Shared library add-on to iptables for DSCP * * (C) 2000- 2002 by Matthew G. Marsh <[email protected]>, * Harald Welte <[email protected]> * * This program is distributed under the terms of GNU GPL v2, 1991 * * libipt_DSCP.c borrowed heavily from libipt_TOS.c * * --set-class added by Iain Barnes */ #include <stdio.h> #include <string.h> #include <xtables.h> #include <linux/netfilter/xt_DSCP.h> /* This is evil, but it's my code - HW*/ #include "dscp_helper.c" enum { O_SET_DSCP = 0, O_SET_DSCP_CLASS, F_SET_DSCP = 1 << O_SET_DSCP, F_SET_DSCP_CLASS = 1 << O_SET_DSCP_CLASS, }; static void DSCP_help(void) { printf( "DSCP target options\n" " --set-dscp value Set DSCP field in packet header to value\n" " This value can be in decimal (ex: 32)\n" " or in hex (ex: 0x20)\n" " --set-dscp-class class Set the DSCP field in packet header to the\n" " value represented by the DiffServ class value.\n" " This class may be EF,BE or any of the CSxx\n" " or AFxx classes.\n" "\n" " These two options are mutually exclusive !\n" ); } static const struct xt_option_entry DSCP_opts[] = { {.name = "set-dscp", .id = O_SET_DSCP, .excl = F_SET_DSCP_CLASS, .type = XTTYPE_UINT8, .min = 0, .max = XT_DSCP_MAX, .flags = XTOPT_PUT, XTOPT_POINTER(struct xt_DSCP_info, dscp)}, {.name = "set-dscp-class", .id = O_SET_DSCP_CLASS, .excl = F_SET_DSCP, .type = XTTYPE_STRING}, XTOPT_TABLEEND, }; static void DSCP_parse(struct xt_option_call *cb) { struct xt_DSCP_info *dinfo = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_SET_DSCP_CLASS: dinfo->dscp = class_to_dscp(cb->arg); break; } } static void DSCP_check(struct xt_fcheck_call *cb) { if (cb->xflags == 0) xtables_error(PARAMETER_PROBLEM, "DSCP target: Parameter --set-dscp is required"); } static void print_dscp(uint8_t dscp, int numeric) { printf(" 0x%02x", dscp); } static void DSCP_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_DSCP_info *dinfo = (const struct xt_DSCP_info *)target->data; printf(" DSCP set"); print_dscp(dinfo->dscp, numeric); } static void DSCP_save(const void *ip, const struct xt_entry_target *target) { const struct xt_DSCP_info *dinfo = (const struct xt_DSCP_info *)target->data; printf(" --set-dscp 0x%02x", dinfo->dscp); } static struct xtables_target dscp_target = { .family = NFPROTO_UNSPEC, .name = "DSCP", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_DSCP_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_DSCP_info)), .help = DSCP_help, .print = DSCP_print, .save = DSCP_save, .x6_parse = DSCP_parse, .x6_fcheck = DSCP_check, .x6_options = DSCP_opts, }; void _init(void) { xtables_register_target(&dscp_target); }
282
./android_firewall/external/iptables/extensions/libxt_dccp.c
/* Shared library add-on to iptables for DCCP matching * * (C) 2005 by Harald Welte <[email protected]> * * This program is distributed under the terms of GNU GPL v2, 1991 * */ #include <stdint.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <netdb.h> #include <arpa/inet.h> #include <xtables.h> #include <linux/dccp.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter/xt_dccp.h> #if 0 #define DEBUGP(format, first...) printf(format, ##first) #define static #else #define DEBUGP(format, fist...) #endif enum { O_SOURCE_PORT = 0, O_DEST_PORT, O_DCCP_TYPES, O_DCCP_OPTION, }; static void dccp_help(void) { printf( "dccp match options\n" "[!] --source-port port[:port] match source port(s)\n" " --sport ...\n" "[!] --destination-port port[:port] match destination port(s)\n" " --dport ...\n" "[!] --dccp-types type[,...] match when packet is one of the given types\n" "[!] --dccp-option option match if option (by number!) is set\n" ); } #define s struct xt_dccp_info static const struct xt_option_entry dccp_opts[] = { {.name = "source-port", .id = O_SOURCE_PORT, .type = XTTYPE_PORTRC, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, spts)}, {.name = "sport", .id = O_SOURCE_PORT, .type = XTTYPE_PORTRC, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, spts)}, {.name = "destination-port", .id = O_DEST_PORT, .type = XTTYPE_PORTRC, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, dpts)}, {.name = "dport", .id = O_DEST_PORT, .type = XTTYPE_PORTRC, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, dpts)}, {.name = "dccp-types", .id = O_DCCP_TYPES, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, {.name = "dccp-option", .id = O_DCCP_OPTION, .type = XTTYPE_UINT8, .min = 1, .max = UINT8_MAX, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, option)}, XTOPT_TABLEEND, }; #undef s static const char *const dccp_pkt_types[] = { [DCCP_PKT_REQUEST] = "REQUEST", [DCCP_PKT_RESPONSE] = "RESPONSE", [DCCP_PKT_DATA] = "DATA", [DCCP_PKT_ACK] = "ACK", [DCCP_PKT_DATAACK] = "DATAACK", [DCCP_PKT_CLOSEREQ] = "CLOSEREQ", [DCCP_PKT_CLOSE] = "CLOSE", [DCCP_PKT_RESET] = "RESET", [DCCP_PKT_SYNC] = "SYNC", [DCCP_PKT_SYNCACK] = "SYNCACK", [DCCP_PKT_INVALID] = "INVALID", }; static uint16_t parse_dccp_types(const char *typestring) { uint16_t typemask = 0; char *ptr, *buffer; buffer = strdup(typestring); for (ptr = strtok(buffer, ","); ptr; ptr = strtok(NULL, ",")) { unsigned int i; for (i = 0; i < ARRAY_SIZE(dccp_pkt_types); ++i) if (!strcasecmp(dccp_pkt_types[i], ptr)) { typemask |= (1 << i); break; } if (i == ARRAY_SIZE(dccp_pkt_types)) xtables_error(PARAMETER_PROBLEM, "Unknown DCCP type `%s'", ptr); } free(buffer); return typemask; } static void dccp_parse(struct xt_option_call *cb) { struct xt_dccp_info *einfo = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_SOURCE_PORT: einfo->flags |= XT_DCCP_SRC_PORTS; if (cb->invert) einfo->invflags |= XT_DCCP_SRC_PORTS; break; case O_DEST_PORT: einfo->flags |= XT_DCCP_DEST_PORTS; if (cb->invert) einfo->invflags |= XT_DCCP_DEST_PORTS; break; case O_DCCP_TYPES: einfo->flags |= XT_DCCP_TYPE; einfo->typemask = parse_dccp_types(cb->arg); if (cb->invert) einfo->invflags |= XT_DCCP_TYPE; break; case O_DCCP_OPTION: einfo->flags |= XT_DCCP_OPTION; if (cb->invert) einfo->invflags |= XT_DCCP_OPTION; break; } } static const char * port_to_service(int port) { const struct servent *service; if ((service = getservbyport(htons(port), "dccp"))) return service->s_name; return NULL; } static void print_port(uint16_t port, int numeric) { const char *service; if (numeric || (service = port_to_service(port)) == NULL) printf("%u", port); else printf("%s", service); } static void print_ports(const char *name, uint16_t min, uint16_t max, int invert, int numeric) { const char *inv = invert ? "!" : ""; if (min != 0 || max != 0xFFFF || invert) { printf(" %s", name); if (min == max) { printf(":%s", inv); print_port(min, numeric); } else { printf("s:%s", inv); print_port(min, numeric); printf(":"); print_port(max, numeric); } } } static void print_types(uint16_t types, int inverted, int numeric) { int have_type = 0; if (inverted) printf(" !"); printf(" "); while (types) { unsigned int i; for (i = 0; !(types & (1 << i)); i++); if (have_type) printf(","); else have_type = 1; if (numeric) printf("%u", i); else printf("%s", dccp_pkt_types[i]); types &= ~(1 << i); } } static void print_option(uint8_t option, int invert, int numeric) { if (option || invert) printf(" option=%s%u", invert ? "!" : "", option); } static void dccp_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_dccp_info *einfo = (const struct xt_dccp_info *)match->data; printf(" dccp"); if (einfo->flags & XT_DCCP_SRC_PORTS) { print_ports("spt", einfo->spts[0], einfo->spts[1], einfo->invflags & XT_DCCP_SRC_PORTS, numeric); } if (einfo->flags & XT_DCCP_DEST_PORTS) { print_ports("dpt", einfo->dpts[0], einfo->dpts[1], einfo->invflags & XT_DCCP_DEST_PORTS, numeric); } if (einfo->flags & XT_DCCP_TYPE) { print_types(einfo->typemask, einfo->invflags & XT_DCCP_TYPE, numeric); } if (einfo->flags & XT_DCCP_OPTION) { print_option(einfo->option, einfo->invflags & XT_DCCP_OPTION, numeric); } } static void dccp_save(const void *ip, const struct xt_entry_match *match) { const struct xt_dccp_info *einfo = (const struct xt_dccp_info *)match->data; if (einfo->flags & XT_DCCP_SRC_PORTS) { if (einfo->invflags & XT_DCCP_SRC_PORTS) printf(" !"); if (einfo->spts[0] != einfo->spts[1]) printf(" --sport %u:%u", einfo->spts[0], einfo->spts[1]); else printf(" --sport %u", einfo->spts[0]); } if (einfo->flags & XT_DCCP_DEST_PORTS) { if (einfo->invflags & XT_DCCP_DEST_PORTS) printf(" !"); if (einfo->dpts[0] != einfo->dpts[1]) printf(" --dport %u:%u", einfo->dpts[0], einfo->dpts[1]); else printf(" --dport %u", einfo->dpts[0]); } if (einfo->flags & XT_DCCP_TYPE) { printf("%s --dccp-types", einfo->invflags & XT_DCCP_TYPE ? " !" : ""); print_types(einfo->typemask, false, 0); } if (einfo->flags & XT_DCCP_OPTION) { printf("%s --dccp-option %u", einfo->invflags & XT_DCCP_OPTION ? " !" : "", einfo->option); } } static struct xtables_match dccp_match = { .name = "dccp", .family = NFPROTO_UNSPEC, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_dccp_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_dccp_info)), .help = dccp_help, .print = dccp_print, .save = dccp_save, .x6_parse = dccp_parse, .x6_options = dccp_opts, }; void _init(void) { xtables_register_match(&dccp_match); }
283
./android_firewall/external/iptables/extensions/libxt_standard.c
/* Shared library add-on to iptables for standard target support. */ #include <stdio.h> #include <xtables.h> static void standard_help(void) { printf( "standard match options:\n" "(If target is DROP, ACCEPT, RETURN or nothing)\n"); } static struct xtables_target standard_target = { .family = NFPROTO_UNSPEC, .name = "standard", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(int)), .userspacesize = XT_ALIGN(sizeof(int)), .help = standard_help, }; void _init(void) { xtables_register_target(&standard_target); }
284
./android_firewall/external/iptables/extensions/libip6t_hbh.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <xtables.h> #include <linux/netfilter_ipv6/ip6t_opts.h> #define DEBUG 0 enum { O_HBH_LEN = 0, O_HBH_OPTS, }; static void hbh_help(void) { printf( "hbh match options:\n" "[!] --hbh-len length total length of this header\n" " --hbh-opts TYPE[:LEN][,TYPE[:LEN]...] \n" " Options and its length (list, max: %d)\n", IP6T_OPTS_OPTSNR); } static const struct xt_option_entry hbh_opts[] = { {.name = "hbh-len", .id = O_HBH_LEN, .type = XTTYPE_UINT32, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(struct ip6t_opts, hdrlen)}, {.name = "hbh-opts", .id = O_HBH_OPTS, .type = XTTYPE_STRING}, XTOPT_TABLEEND, }; static uint32_t parse_opts_num(const char *idstr, const char *typestr) { unsigned long int id; char* ep; id = strtoul(idstr,&ep,0) ; if ( idstr == ep ) { xtables_error(PARAMETER_PROBLEM, "hbh: no valid digits in %s `%s'", typestr, idstr); } if ( id == ULONG_MAX && errno == ERANGE ) { xtables_error(PARAMETER_PROBLEM, "%s `%s' specified too big: would overflow", typestr, idstr); } if ( *idstr != '\0' && *ep != '\0' ) { xtables_error(PARAMETER_PROBLEM, "hbh: error parsing %s `%s'", typestr, idstr); } return id; } static int parse_options(const char *optsstr, uint16_t *opts) { char *buffer, *cp, *next, *range; unsigned int i; buffer = strdup(optsstr); if (!buffer) xtables_error(OTHER_PROBLEM, "strdup failed"); for (cp=buffer, i=0; cp && i<IP6T_OPTS_OPTSNR; cp=next,i++) { next=strchr(cp, ','); if (next) *next++='\0'; range = strchr(cp, ':'); if (range) { if (i == IP6T_OPTS_OPTSNR-1) xtables_error(PARAMETER_PROBLEM, "too many ports specified"); *range++ = '\0'; } opts[i] = (parse_opts_num(cp, "opt") & 0xFF) << 8; if (range) { if (opts[i] == 0) xtables_error(PARAMETER_PROBLEM, "PAD0 has not got length"); opts[i] |= parse_opts_num(range, "length") & 0xFF; } else { opts[i] |= (0x00FF); } #if DEBUG printf("opts str: %s %s\n", cp, range); printf("opts opt: %04X\n", opts[i]); #endif } if (cp) xtables_error(PARAMETER_PROBLEM, "too many addresses specified"); free(buffer); #if DEBUG printf("addr nr: %d\n", i); #endif return i; } static void hbh_parse(struct xt_option_call *cb) { struct ip6t_opts *optinfo = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_HBH_LEN: if (cb->invert) optinfo->invflags |= IP6T_OPTS_INV_LEN; optinfo->flags |= IP6T_OPTS_LEN; break; case O_HBH_OPTS: optinfo->optsnr = parse_options(cb->arg, optinfo->opts); optinfo->flags |= IP6T_OPTS_OPTS; break; } } static void print_options(unsigned int optsnr, uint16_t *optsp) { unsigned int i; for(i=0; i<optsnr; i++){ printf("%c", (i==0)?' ':','); printf("%d", (optsp[i] & 0xFF00)>>8); if ((optsp[i] & 0x00FF) != 0x00FF){ printf(":%d", (optsp[i] & 0x00FF)); } } } static void hbh_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct ip6t_opts *optinfo = (struct ip6t_opts *)match->data; printf(" hbh"); if (optinfo->flags & IP6T_OPTS_LEN) { printf(" length"); printf(":%s", optinfo->invflags & IP6T_OPTS_INV_LEN ? "!" : ""); printf("%u", optinfo->hdrlen); } if (optinfo->flags & IP6T_OPTS_OPTS) printf(" opts"); print_options(optinfo->optsnr, (uint16_t *)optinfo->opts); if (optinfo->invflags & ~IP6T_OPTS_INV_MASK) printf(" Unknown invflags: 0x%X", optinfo->invflags & ~IP6T_OPTS_INV_MASK); } static void hbh_save(const void *ip, const struct xt_entry_match *match) { const struct ip6t_opts *optinfo = (struct ip6t_opts *)match->data; if (optinfo->flags & IP6T_OPTS_LEN) { printf("%s --hbh-len %u", (optinfo->invflags & IP6T_OPTS_INV_LEN) ? " !" : "", optinfo->hdrlen); } if (optinfo->flags & IP6T_OPTS_OPTS) printf(" --hbh-opts"); print_options(optinfo->optsnr, (uint16_t *)optinfo->opts); } static struct xtables_match hbh_mt6_reg = { .name = "hbh", .version = XTABLES_VERSION, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct ip6t_opts)), .userspacesize = XT_ALIGN(sizeof(struct ip6t_opts)), .help = hbh_help, .print = hbh_print, .save = hbh_save, .x6_parse = hbh_parse, .x6_options = hbh_opts, }; void _init(void) { xtables_register_match(&hbh_mt6_reg); }
285
./android_firewall/external/iptables/extensions/libxt_recent.c
#include <stdbool.h> #include <stdio.h> #include <string.h> #include <xtables.h> #include <linux/netfilter/xt_recent.h> enum { O_SET = 0, O_RCHECK, O_UPDATE, O_REMOVE, O_SECONDS, O_REAP, O_HITCOUNT, O_RTTL, O_NAME, O_RSOURCE, O_RDEST, O_MASK, F_SET = 1 << O_SET, F_RCHECK = 1 << O_RCHECK, F_UPDATE = 1 << O_UPDATE, F_REMOVE = 1 << O_REMOVE, F_SECONDS = 1 << O_SECONDS, F_ANY_OP = F_SET | F_RCHECK | F_UPDATE | F_REMOVE, }; #define s struct xt_recent_mtinfo static const struct xt_option_entry recent_opts_v0[] = { {.name = "set", .id = O_SET, .type = XTTYPE_NONE, .excl = F_ANY_OP, .flags = XTOPT_INVERT}, {.name = "rcheck", .id = O_RCHECK, .type = XTTYPE_NONE, .excl = F_ANY_OP, .flags = XTOPT_INVERT}, {.name = "update", .id = O_UPDATE, .type = XTTYPE_NONE, .excl = F_ANY_OP, .flags = XTOPT_INVERT}, {.name = "remove", .id = O_REMOVE, .type = XTTYPE_NONE, .excl = F_ANY_OP, .flags = XTOPT_INVERT}, {.name = "seconds", .id = O_SECONDS, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, seconds), .min = 1}, {.name = "reap", .id = O_REAP, .type = XTTYPE_NONE, .also = F_SECONDS }, {.name = "hitcount", .id = O_HITCOUNT, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, hit_count)}, {.name = "rttl", .id = O_RTTL, .type = XTTYPE_NONE, .excl = F_SET | F_REMOVE}, {.name = "name", .id = O_NAME, .type = XTTYPE_STRING, .flags = XTOPT_PUT, XTOPT_POINTER(s, name)}, {.name = "rsource", .id = O_RSOURCE, .type = XTTYPE_NONE}, {.name = "rdest", .id = O_RDEST, .type = XTTYPE_NONE}, XTOPT_TABLEEND, }; #undef s #define s struct xt_recent_mtinfo_v1 static const struct xt_option_entry recent_opts_v1[] = { {.name = "set", .id = O_SET, .type = XTTYPE_NONE, .excl = F_ANY_OP, .flags = XTOPT_INVERT}, {.name = "rcheck", .id = O_RCHECK, .type = XTTYPE_NONE, .excl = F_ANY_OP, .flags = XTOPT_INVERT}, {.name = "update", .id = O_UPDATE, .type = XTTYPE_NONE, .excl = F_ANY_OP, .flags = XTOPT_INVERT}, {.name = "remove", .id = O_REMOVE, .type = XTTYPE_NONE, .excl = F_ANY_OP, .flags = XTOPT_INVERT}, {.name = "seconds", .id = O_SECONDS, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, seconds)}, {.name = "hitcount", .id = O_HITCOUNT, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, hit_count)}, {.name = "rttl", .id = O_RTTL, .type = XTTYPE_NONE, .excl = F_SET | F_REMOVE}, {.name = "name", .id = O_NAME, .type = XTTYPE_STRING, .flags = XTOPT_PUT, XTOPT_POINTER(s, name)}, {.name = "rsource", .id = O_RSOURCE, .type = XTTYPE_NONE}, {.name = "rdest", .id = O_RDEST, .type = XTTYPE_NONE}, {.name = "mask", .id = O_MASK, .type = XTTYPE_HOST, .flags = XTOPT_PUT, XTOPT_POINTER(s, mask)}, XTOPT_TABLEEND, }; #undef s static void recent_help(void) { printf( "recent match options:\n" "[!] --set Add source address to list, always matches.\n" "[!] --rcheck Match if source address in list.\n" "[!] --update Match if source address in list, also update last-seen time.\n" "[!] --remove Match if source address in list, also removes that address from list.\n" " --seconds seconds For check and update commands above.\n" " Specifies that the match will only occur if source address last seen within\n" " the last 'seconds' seconds.\n" " --reap Purge entries older then 'seconds'.\n" " Can only be used in conjunction with the seconds option.\n" " --hitcount hits For check and update commands above.\n" " Specifies that the match will only occur if source address seen hits times.\n" " May be used in conjunction with the seconds option.\n" " --rttl For check and update commands above.\n" " Specifies that the match will only occur if the source address and the TTL\n" " match between this packet and the one which was set.\n" " Useful if you have problems with people spoofing their source address in order\n" " to DoS you via this module.\n" " --name name Name of the recent list to be used. DEFAULT used if none given.\n" " --rsource Match/Save the source address of each packet in the recent list table (default).\n" " --rdest Match/Save the destination address of each packet in the recent list table.\n" " --mask netmask Netmask that will be applied to this recent list.\n" "xt_recent by: Stephen Frost <[email protected]>. http://snowman.net/projects/ipt_recent/\n"); } enum { XT_RECENT_REV_0 = 0, XT_RECENT_REV_1, }; static void recent_init(struct xt_entry_match *match, unsigned int rev) { struct xt_recent_mtinfo *info = (struct xt_recent_mtinfo *)match->data; struct xt_recent_mtinfo_v1 *info_v1 = (struct xt_recent_mtinfo_v1 *)match->data; strncpy(info->name,"DEFAULT", XT_RECENT_NAME_LEN); /* even though XT_RECENT_NAME_LEN is currently defined as 200, * better be safe, than sorry */ info->name[XT_RECENT_NAME_LEN-1] = '\0'; info->side = XT_RECENT_SOURCE; if (rev == XT_RECENT_REV_1) memset(&info_v1->mask, 0xFF, sizeof(info_v1->mask)); } static void recent_parse(struct xt_option_call *cb) { struct xt_recent_mtinfo *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_SET: info->check_set |= XT_RECENT_SET; if (cb->invert) info->invert = true; break; case O_RCHECK: info->check_set |= XT_RECENT_CHECK; if (cb->invert) info->invert = true; break; case O_UPDATE: info->check_set |= XT_RECENT_UPDATE; if (cb->invert) info->invert = true; break; case O_REMOVE: info->check_set |= XT_RECENT_REMOVE; if (cb->invert) info->invert = true; break; case O_RTTL: info->check_set |= XT_RECENT_TTL; break; case O_RSOURCE: info->side = XT_RECENT_SOURCE; break; case O_RDEST: info->side = XT_RECENT_DEST; break; case O_REAP: info->check_set |= XT_RECENT_REAP; break; } } static void recent_check(struct xt_fcheck_call *cb) { if (!(cb->xflags & F_ANY_OP)) xtables_error(PARAMETER_PROBLEM, "recent: you must specify one of `--set', `--rcheck' " "`--update' or `--remove'"); } static void recent_print(const void *ip, const struct xt_entry_match *match, unsigned int family) { const struct xt_recent_mtinfo_v1 *info = (const void *)match->data; if (info->invert) printf(" !"); printf(" recent:"); if (info->check_set & XT_RECENT_SET) printf(" SET"); if (info->check_set & XT_RECENT_CHECK) printf(" CHECK"); if (info->check_set & XT_RECENT_UPDATE) printf(" UPDATE"); if (info->check_set & XT_RECENT_REMOVE) printf(" REMOVE"); if(info->seconds) printf(" seconds: %d", info->seconds); if (info->check_set & XT_RECENT_REAP) printf(" reap"); if(info->hit_count) printf(" hit_count: %d", info->hit_count); if (info->check_set & XT_RECENT_TTL) printf(" TTL-Match"); if(info->name) printf(" name: %s", info->name); if (info->side == XT_RECENT_SOURCE) printf(" side: source"); if (info->side == XT_RECENT_DEST) printf(" side: dest"); switch(family) { case NFPROTO_IPV4: printf(" mask: %s", xtables_ipaddr_to_numeric(&info->mask.in)); break; case NFPROTO_IPV6: printf(" mask: %s", xtables_ip6addr_to_numeric(&info->mask.in6)); break; } } static void recent_save(const void *ip, const struct xt_entry_match *match, unsigned int family) { const struct xt_recent_mtinfo_v1 *info = (const void *)match->data; if (info->invert) printf(" !"); if (info->check_set & XT_RECENT_SET) printf(" --set"); if (info->check_set & XT_RECENT_CHECK) printf(" --rcheck"); if (info->check_set & XT_RECENT_UPDATE) printf(" --update"); if (info->check_set & XT_RECENT_REMOVE) printf(" --remove"); if(info->seconds) printf(" --seconds %d", info->seconds); if (info->check_set & XT_RECENT_REAP) printf(" --reap"); if(info->hit_count) printf(" --hitcount %d", info->hit_count); if (info->check_set & XT_RECENT_TTL) printf(" --rttl"); if(info->name) printf(" --name %s",info->name); switch(family) { case NFPROTO_IPV4: printf(" --mask %s", xtables_ipaddr_to_numeric(&info->mask.in)); break; case NFPROTO_IPV6: printf(" --mask %s", xtables_ip6addr_to_numeric(&info->mask.in6)); break; } if (info->side == XT_RECENT_SOURCE) printf(" --rsource"); if (info->side == XT_RECENT_DEST) printf(" --rdest"); } static void recent_init_v0(struct xt_entry_match *match) { recent_init(match, XT_RECENT_REV_0); } static void recent_init_v1(struct xt_entry_match *match) { recent_init(match, XT_RECENT_REV_1); } static void recent_save_v0(const void *ip, const struct xt_entry_match *match) { recent_save(ip, match, NFPROTO_UNSPEC); } static void recent_save_v4(const void *ip, const struct xt_entry_match *match) { recent_save(ip, match, NFPROTO_IPV4); } static void recent_save_v6(const void *ip, const struct xt_entry_match *match) { recent_save(ip, match, NFPROTO_IPV6); } static void recent_print_v0(const void *ip, const struct xt_entry_match *match, int numeric) { recent_print(ip, match, NFPROTO_UNSPEC); } static void recent_print_v4(const void *ip, const struct xt_entry_match *match, int numeric) { recent_print(ip, match, NFPROTO_IPV4); } static void recent_print_v6(const void *ip, const struct xt_entry_match *match, int numeric) { recent_print(ip, match, NFPROTO_IPV6); } static struct xtables_match recent_mt_reg[] = { { .name = "recent", .version = XTABLES_VERSION, .revision = 0, .family = NFPROTO_UNSPEC, .size = XT_ALIGN(sizeof(struct xt_recent_mtinfo)), .userspacesize = XT_ALIGN(sizeof(struct xt_recent_mtinfo)), .help = recent_help, .init = recent_init_v0, .x6_parse = recent_parse, .x6_fcheck = recent_check, .print = recent_print_v0, .save = recent_save_v0, .x6_options = recent_opts_v0, }, { .name = "recent", .version = XTABLES_VERSION, .revision = 1, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct xt_recent_mtinfo_v1)), .userspacesize = XT_ALIGN(sizeof(struct xt_recent_mtinfo_v1)), .help = recent_help, .init = recent_init_v1, .x6_parse = recent_parse, .x6_fcheck = recent_check, .print = recent_print_v4, .save = recent_save_v4, .x6_options = recent_opts_v1, }, { .name = "recent", .version = XTABLES_VERSION, .revision = 1, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct xt_recent_mtinfo_v1)), .userspacesize = XT_ALIGN(sizeof(struct xt_recent_mtinfo_v1)), .help = recent_help, .init = recent_init_v1, .x6_parse = recent_parse, .x6_fcheck = recent_check, .print = recent_print_v6, .save = recent_save_v6, .x6_options = recent_opts_v1, }, }; void _init(void) { xtables_register_matches(recent_mt_reg, ARRAY_SIZE(recent_mt_reg)); }
286
./android_firewall/external/iptables/extensions/libip6t_LOG.c
#include <stdio.h> #include <string.h> #include <syslog.h> #include <xtables.h> #include <linux/netfilter_ipv6/ip6t_LOG.h> #ifndef IP6T_LOG_UID /* Old kernel */ #define IP6T_LOG_UID 0x08 #undef IP6T_LOG_MASK #define IP6T_LOG_MASK 0x0f #endif #define LOG_DEFAULT_LEVEL LOG_WARNING enum { O_LOG_LEVEL = 0, O_LOG_PREFIX, O_LOG_TCPSEQ, O_LOG_TCPOPTS, O_LOG_IPOPTS, O_LOG_UID, O_LOG_MAC, }; static void LOG_help(void) { printf( "LOG target options:\n" " --log-level level Level of logging (numeric or see syslog.conf)\n" " --log-prefix prefix Prefix log messages with this prefix.\n" " --log-tcp-sequence Log TCP sequence numbers.\n" " --log-tcp-options Log TCP options.\n" " --log-ip-options Log IP options.\n" " --log-uid Log UID owning the local socket.\n" " --log-macdecode Decode MAC addresses and protocol.\n"); } #define s struct ip6t_log_info static const struct xt_option_entry LOG_opts[] = { {.name = "log-level", .id = O_LOG_LEVEL, .type = XTTYPE_SYSLOGLEVEL, .flags = XTOPT_PUT, XTOPT_POINTER(s, level)}, {.name = "log-prefix", .id = O_LOG_PREFIX, .type = XTTYPE_STRING, .flags = XTOPT_PUT, XTOPT_POINTER(s, prefix), .min = 1}, {.name = "log-tcp-sequence", .id = O_LOG_TCPSEQ, .type = XTTYPE_NONE}, {.name = "log-tcp-options", .id = O_LOG_TCPOPTS, .type = XTTYPE_NONE}, {.name = "log-ip-options", .id = O_LOG_IPOPTS, .type = XTTYPE_NONE}, {.name = "log-uid", .id = O_LOG_UID, .type = XTTYPE_NONE}, {.name = "log-macdecode", .id = O_LOG_MAC, .type = XTTYPE_NONE}, XTOPT_TABLEEND, }; #undef s static void LOG_init(struct xt_entry_target *t) { struct ip6t_log_info *loginfo = (struct ip6t_log_info *)t->data; loginfo->level = LOG_DEFAULT_LEVEL; } struct ip6t_log_names { const char *name; unsigned int level; }; static const struct ip6t_log_names ip6t_log_names[] = { { .name = "alert", .level = LOG_ALERT }, { .name = "crit", .level = LOG_CRIT }, { .name = "debug", .level = LOG_DEBUG }, { .name = "emerg", .level = LOG_EMERG }, { .name = "error", .level = LOG_ERR }, /* DEPRECATED */ { .name = "info", .level = LOG_INFO }, { .name = "notice", .level = LOG_NOTICE }, { .name = "panic", .level = LOG_EMERG }, /* DEPRECATED */ { .name = "warning", .level = LOG_WARNING } }; static void LOG_parse(struct xt_option_call *cb) { struct ip6t_log_info *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_LOG_PREFIX: if (strchr(cb->arg, '\n') != NULL) xtables_error(PARAMETER_PROBLEM, "Newlines not allowed in --log-prefix"); break; case O_LOG_TCPSEQ: info->logflags |= IP6T_LOG_TCPSEQ; break; case O_LOG_TCPOPTS: info->logflags |= IP6T_LOG_TCPOPT; break; case O_LOG_IPOPTS: info->logflags |= IP6T_LOG_IPOPT; break; case O_LOG_UID: info->logflags |= IP6T_LOG_UID; break; case O_LOG_MAC: info->logflags |= IP6T_LOG_MACDECODE; break; } } static void LOG_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct ip6t_log_info *loginfo = (const struct ip6t_log_info *)target->data; unsigned int i = 0; printf(" LOG"); if (numeric) printf(" flags %u level %u", loginfo->logflags, loginfo->level); else { for (i = 0; i < ARRAY_SIZE(ip6t_log_names); ++i) if (loginfo->level == ip6t_log_names[i].level) { printf(" level %s", ip6t_log_names[i].name); break; } if (i == ARRAY_SIZE(ip6t_log_names)) printf(" UNKNOWN level %u", loginfo->level); if (loginfo->logflags & IP6T_LOG_TCPSEQ) printf(" tcp-sequence"); if (loginfo->logflags & IP6T_LOG_TCPOPT) printf(" tcp-options"); if (loginfo->logflags & IP6T_LOG_IPOPT) printf(" ip-options"); if (loginfo->logflags & IP6T_LOG_UID) printf(" uid"); if (loginfo->logflags & IP6T_LOG_MACDECODE) printf(" macdecode"); if (loginfo->logflags & ~(IP6T_LOG_MASK)) printf(" unknown-flags"); } if (strcmp(loginfo->prefix, "") != 0) printf(" prefix \"%s\"", loginfo->prefix); } static void LOG_save(const void *ip, const struct xt_entry_target *target) { const struct ip6t_log_info *loginfo = (const struct ip6t_log_info *)target->data; if (strcmp(loginfo->prefix, "") != 0) printf(" --log-prefix \"%s\"", loginfo->prefix); if (loginfo->level != LOG_DEFAULT_LEVEL) printf(" --log-level %d", loginfo->level); if (loginfo->logflags & IP6T_LOG_TCPSEQ) printf(" --log-tcp-sequence"); if (loginfo->logflags & IP6T_LOG_TCPOPT) printf(" --log-tcp-options"); if (loginfo->logflags & IP6T_LOG_IPOPT) printf(" --log-ip-options"); if (loginfo->logflags & IP6T_LOG_UID) printf(" --log-uid"); if (loginfo->logflags & IP6T_LOG_MACDECODE) printf(" --log-macdecode"); } static struct xtables_target log_tg6_reg = { .name = "LOG", .version = XTABLES_VERSION, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct ip6t_log_info)), .userspacesize = XT_ALIGN(sizeof(struct ip6t_log_info)), .help = LOG_help, .init = LOG_init, .print = LOG_print, .save = LOG_save, .x6_parse = LOG_parse, .x6_options = LOG_opts, }; void _init(void) { xtables_register_target(&log_tg6_reg); }
287
./android_firewall/external/iptables/extensions/libip6t_hl.c
/* * IPv6 Hop Limit matching module * Maciej Soltysiak <[email protected]> * Based on HW's ttl match * This program is released under the terms of GNU GPL * Cleanups by Stephane Ouellette <[email protected]> */ #include <stdio.h> #include <xtables.h> #include <linux/netfilter_ipv6/ip6t_hl.h> enum { O_HL_EQ = 0, O_HL_LT, O_HL_GT, F_HL_EQ = 1 << O_HL_EQ, F_HL_LT = 1 << O_HL_LT, F_HL_GT = 1 << O_HL_GT, F_ANY = F_HL_EQ | F_HL_LT | F_HL_GT, }; static void hl_help(void) { printf( "hl match options:\n" "[!] --hl-eq value Match hop limit value\n" " --hl-lt value Match HL < value\n" " --hl-gt value Match HL > value\n"); } static void hl_parse(struct xt_option_call *cb) { struct ip6t_hl_info *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_HL_EQ: info->mode = cb->invert ? IP6T_HL_NE : IP6T_HL_EQ; break; case O_HL_LT: info->mode = IP6T_HL_LT; break; case O_HL_GT: info->mode = IP6T_HL_GT; break; } } static void hl_check(struct xt_fcheck_call *cb) { if (!(cb->xflags & F_ANY)) xtables_error(PARAMETER_PROBLEM, "HL match: You must specify one of " "`--hl-eq', `--hl-lt', `--hl-gt'"); } static void hl_print(const void *ip, const struct xt_entry_match *match, int numeric) { static const char *const op[] = { [IP6T_HL_EQ] = "==", [IP6T_HL_NE] = "!=", [IP6T_HL_LT] = "<", [IP6T_HL_GT] = ">" }; const struct ip6t_hl_info *info = (struct ip6t_hl_info *) match->data; printf(" HL match HL %s %u", op[info->mode], info->hop_limit); } static void hl_save(const void *ip, const struct xt_entry_match *match) { static const char *const op[] = { [IP6T_HL_EQ] = "--hl-eq", [IP6T_HL_NE] = "! --hl-eq", [IP6T_HL_LT] = "--hl-lt", [IP6T_HL_GT] = "--hl-gt" }; const struct ip6t_hl_info *info = (struct ip6t_hl_info *) match->data; printf(" %s %u", op[info->mode], info->hop_limit); } #define s struct ip6t_hl_info static const struct xt_option_entry hl_opts[] = { {.name = "hl-lt", .id = O_HL_LT, .excl = F_ANY, .type = XTTYPE_UINT8, .flags = XTOPT_PUT, XTOPT_POINTER(s, hop_limit)}, {.name = "hl-gt", .id = O_HL_GT, .excl = F_ANY, .type = XTTYPE_UINT8, .flags = XTOPT_PUT, XTOPT_POINTER(s, hop_limit)}, {.name = "hl-eq", .id = O_HL_EQ, .excl = F_ANY, .type = XTTYPE_UINT8, .flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, hop_limit)}, {.name = "hl", .id = O_HL_EQ, .excl = F_ANY, .type = XTTYPE_UINT8, .flags = XTOPT_PUT, XTOPT_POINTER(s, hop_limit)}, XTOPT_TABLEEND, }; #undef s static struct xtables_match hl_mt6_reg = { .name = "hl", .version = XTABLES_VERSION, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct ip6t_hl_info)), .userspacesize = XT_ALIGN(sizeof(struct ip6t_hl_info)), .help = hl_help, .print = hl_print, .save = hl_save, .x6_parse = hl_parse, .x6_fcheck = hl_check, .x6_options = hl_opts, }; void _init(void) { xtables_register_match(&hl_mt6_reg); }
288
./android_firewall/external/iptables/extensions/libip6t_mh.c
/* Shared library add-on to ip6tables to add mobility header support. */ /* * Copyright (C)2006 USAGI/WIDE Project * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Author: * Masahide NAKAMURA @USAGI <[email protected]> * * Based on libip6t_{icmpv6,udp}.c */ #include <stdint.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <xtables.h> #include <linux/netfilter_ipv6/ip6t_mh.h> enum { O_MH_TYPE = 0, }; struct mh_name { const char *name; uint8_t type; }; static const struct mh_name mh_names[] = { { "binding-refresh-request", 0, }, /* Alias */ { "brr", 0, }, { "home-test-init", 1, }, /* Alias */ { "hoti", 1, }, { "careof-test-init", 2, }, /* Alias */ { "coti", 2, }, { "home-test", 3, }, /* Alias */ { "hot", 3, }, { "careof-test", 4, }, /* Alias */ { "cot", 4, }, { "binding-update", 5, }, /* Alias */ { "bu", 5, }, { "binding-acknowledgement", 6, }, /* Alias */ { "ba", 6, }, { "binding-error", 7, }, /* Alias */ { "be", 7, }, }; static void print_types_all(void) { unsigned int i; printf("Valid MH types:"); for (i = 0; i < ARRAY_SIZE(mh_names); ++i) { if (i && mh_names[i].type == mh_names[i-1].type) printf(" (%s)", mh_names[i].name); else printf("\n%s", mh_names[i].name); } printf("\n"); } static void mh_help(void) { printf( "mh match options:\n" "[!] --mh-type type[:type] match mh type\n"); print_types_all(); } static void mh_init(struct xt_entry_match *m) { struct ip6t_mh *mhinfo = (struct ip6t_mh *)m->data; mhinfo->types[1] = 0xFF; } static unsigned int name_to_type(const char *name) { int namelen = strlen(name); static const unsigned int limit = ARRAY_SIZE(mh_names); unsigned int match = limit; unsigned int i; for (i = 0; i < limit; i++) { if (strncasecmp(mh_names[i].name, name, namelen) == 0) { int len = strlen(mh_names[i].name); if (match == limit || len == namelen) match = i; } } if (match != limit) { return mh_names[match].type; } else { unsigned int number; if (!xtables_strtoui(name, NULL, &number, 0, UINT8_MAX)) xtables_error(PARAMETER_PROBLEM, "Invalid MH type `%s'\n", name); return number; } } static void parse_mh_types(const char *mhtype, uint8_t *types) { char *buffer; char *cp; buffer = strdup(mhtype); if ((cp = strchr(buffer, ':')) == NULL) types[0] = types[1] = name_to_type(buffer); else { *cp = '\0'; cp++; types[0] = buffer[0] ? name_to_type(buffer) : 0; types[1] = cp[0] ? name_to_type(cp) : 0xFF; if (types[0] > types[1]) xtables_error(PARAMETER_PROBLEM, "Invalid MH type range (min > max)"); } free(buffer); } static void mh_parse(struct xt_option_call *cb) { struct ip6t_mh *mhinfo = cb->data; xtables_option_parse(cb); parse_mh_types(cb->arg, mhinfo->types); if (cb->invert) mhinfo->invflags |= IP6T_MH_INV_TYPE; } static const char *type_to_name(uint8_t type) { unsigned int i; for (i = 0; i < ARRAY_SIZE(mh_names); ++i) if (mh_names[i].type == type) return mh_names[i].name; return NULL; } static void print_type(uint8_t type, int numeric) { const char *name; if (numeric || !(name = type_to_name(type))) printf("%u", type); else printf("%s", name); } static void print_types(uint8_t min, uint8_t max, int invert, int numeric) { const char *inv = invert ? "!" : ""; if (min != 0 || max != 0xFF || invert) { printf(" "); if (min == max) { printf("%s", inv); print_type(min, numeric); } else { printf("%s", inv); print_type(min, numeric); printf(":"); print_type(max, numeric); } } } static void mh_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct ip6t_mh *mhinfo = (struct ip6t_mh *)match->data; printf(" mh"); print_types(mhinfo->types[0], mhinfo->types[1], mhinfo->invflags & IP6T_MH_INV_TYPE, numeric); if (mhinfo->invflags & ~IP6T_MH_INV_MASK) printf(" Unknown invflags: 0x%X", mhinfo->invflags & ~IP6T_MH_INV_MASK); } static void mh_save(const void *ip, const struct xt_entry_match *match) { const struct ip6t_mh *mhinfo = (struct ip6t_mh *)match->data; if (mhinfo->types[0] == 0 && mhinfo->types[1] == 0xFF) return; if (mhinfo->invflags & IP6T_MH_INV_TYPE) printf(" !"); if (mhinfo->types[0] != mhinfo->types[1]) printf(" --mh-type %u:%u", mhinfo->types[0], mhinfo->types[1]); else printf(" --mh-type %u", mhinfo->types[0]); } static const struct xt_option_entry mh_opts[] = { {.name = "mh-type", .id = O_MH_TYPE, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, XTOPT_TABLEEND, }; static struct xtables_match mh_mt6_reg = { .name = "mh", .version = XTABLES_VERSION, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct ip6t_mh)), .userspacesize = XT_ALIGN(sizeof(struct ip6t_mh)), .help = mh_help, .init = mh_init, .x6_parse = mh_parse, .print = mh_print, .save = mh_save, .x6_options = mh_opts, }; void _init(void) { xtables_register_match(&mh_mt6_reg); }
289
./android_firewall/external/iptables/extensions/libxt_MARK.c
#include <stdbool.h> #include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_MARK.h> /* Version 0 */ struct xt_mark_target_info { unsigned long mark; }; /* Version 1 */ enum { XT_MARK_SET=0, XT_MARK_AND, XT_MARK_OR, }; struct xt_mark_target_info_v1 { unsigned long mark; uint8_t mode; }; enum { O_SET_MARK = 0, O_AND_MARK, O_OR_MARK, O_XOR_MARK, O_SET_XMARK, F_SET_MARK = 1 << O_SET_MARK, F_AND_MARK = 1 << O_AND_MARK, F_OR_MARK = 1 << O_OR_MARK, F_XOR_MARK = 1 << O_XOR_MARK, F_SET_XMARK = 1 << O_SET_XMARK, F_ANY = F_SET_MARK | F_AND_MARK | F_OR_MARK | F_XOR_MARK | F_SET_XMARK, }; static void MARK_help(void) { printf( "MARK target options:\n" " --set-mark value Set nfmark value\n" " --and-mark value Binary AND the nfmark with value\n" " --or-mark value Binary OR the nfmark with value\n"); } static const struct xt_option_entry MARK_opts[] = { {.name = "set-mark", .id = O_SET_MARK, .type = XTTYPE_UINT32, .excl = F_ANY}, {.name = "and-mark", .id = O_AND_MARK, .type = XTTYPE_UINT32, .excl = F_ANY}, {.name = "or-mark", .id = O_OR_MARK, .type = XTTYPE_UINT32, .excl = F_ANY}, XTOPT_TABLEEND, }; static const struct xt_option_entry mark_tg_opts[] = { {.name = "set-xmark", .id = O_SET_XMARK, .type = XTTYPE_MARKMASK32, .excl = F_ANY}, {.name = "set-mark", .id = O_SET_MARK, .type = XTTYPE_MARKMASK32, .excl = F_ANY}, {.name = "and-mark", .id = O_AND_MARK, .type = XTTYPE_UINT32, .excl = F_ANY}, {.name = "or-mark", .id = O_OR_MARK, .type = XTTYPE_UINT32, .excl = F_ANY}, {.name = "xor-mark", .id = O_XOR_MARK, .type = XTTYPE_UINT32, .excl = F_ANY}, XTOPT_TABLEEND, }; static void mark_tg_help(void) { printf( "MARK target options:\n" " --set-xmark value[/mask] Clear bits in mask and XOR value into nfmark\n" " --set-mark value[/mask] Clear bits in mask and OR value into nfmark\n" " --and-mark bits Binary AND the nfmark with bits\n" " --or-mark bits Binary OR the nfmark with bits\n" " --xor-mask bits Binary XOR the nfmark with bits\n" "\n"); } static void MARK_parse_v0(struct xt_option_call *cb) { struct xt_mark_target_info *markinfo = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_SET_MARK: markinfo->mark = cb->val.mark; break; default: xtables_error(PARAMETER_PROBLEM, "MARK target: kernel too old for --%s", cb->entry->name); } } static void MARK_check(struct xt_fcheck_call *cb) { if (cb->xflags == 0) xtables_error(PARAMETER_PROBLEM, "MARK target: Parameter --set/and/or-mark" " is required"); } static void MARK_parse_v1(struct xt_option_call *cb) { struct xt_mark_target_info_v1 *markinfo = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_SET_MARK: markinfo->mode = XT_MARK_SET; break; case O_AND_MARK: markinfo->mode = XT_MARK_AND; break; case O_OR_MARK: markinfo->mode = XT_MARK_OR; break; } markinfo->mark = cb->val.u32; } static void mark_tg_parse(struct xt_option_call *cb) { struct xt_mark_tginfo2 *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_SET_XMARK: info->mark = cb->val.mark; info->mask = cb->val.mask; break; case O_SET_MARK: info->mark = cb->val.mark; info->mask = cb->val.mark | cb->val.mask; break; case O_AND_MARK: info->mark = 0; info->mask = ~cb->val.u32; break; case O_OR_MARK: info->mark = info->mask = cb->val.u32; break; case O_XOR_MARK: info->mark = cb->val.u32; info->mask = 0; break; } } static void mark_tg_check(struct xt_fcheck_call *cb) { if (cb->xflags == 0) xtables_error(PARAMETER_PROBLEM, "MARK: One of the --set-xmark, " "--{and,or,xor,set}-mark options is required"); } static void print_mark(unsigned long mark) { printf(" 0x%lx", mark); } static void MARK_print_v0(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_mark_target_info *markinfo = (const struct xt_mark_target_info *)target->data; printf(" MARK set"); print_mark(markinfo->mark); } static void MARK_save_v0(const void *ip, const struct xt_entry_target *target) { const struct xt_mark_target_info *markinfo = (const struct xt_mark_target_info *)target->data; printf(" --set-mark"); print_mark(markinfo->mark); } static void MARK_print_v1(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_mark_target_info_v1 *markinfo = (const struct xt_mark_target_info_v1 *)target->data; switch (markinfo->mode) { case XT_MARK_SET: printf(" MARK set"); break; case XT_MARK_AND: printf(" MARK and"); break; case XT_MARK_OR: printf(" MARK or"); break; } print_mark(markinfo->mark); } static void mark_tg_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_mark_tginfo2 *info = (const void *)target->data; if (info->mark == 0) printf(" MARK and 0x%x", (unsigned int)(uint32_t)~info->mask); else if (info->mark == info->mask) printf(" MARK or 0x%x", info->mark); else if (info->mask == 0) printf(" MARK xor 0x%x", info->mark); else if (info->mask == 0xffffffffU) printf(" MARK set 0x%x", info->mark); else printf(" MARK xset 0x%x/0x%x", info->mark, info->mask); } static void MARK_save_v1(const void *ip, const struct xt_entry_target *target) { const struct xt_mark_target_info_v1 *markinfo = (const struct xt_mark_target_info_v1 *)target->data; switch (markinfo->mode) { case XT_MARK_SET: printf(" --set-mark"); break; case XT_MARK_AND: printf(" --and-mark"); break; case XT_MARK_OR: printf(" --or-mark"); break; } print_mark(markinfo->mark); } static void mark_tg_save(const void *ip, const struct xt_entry_target *target) { const struct xt_mark_tginfo2 *info = (const void *)target->data; printf(" --set-xmark 0x%x/0x%x", info->mark, info->mask); } static struct xtables_target mark_tg_reg[] = { { .family = NFPROTO_UNSPEC, .name = "MARK", .version = XTABLES_VERSION, .revision = 0, .size = XT_ALIGN(sizeof(struct xt_mark_target_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_mark_target_info)), .help = MARK_help, .print = MARK_print_v0, .save = MARK_save_v0, .x6_parse = MARK_parse_v0, .x6_fcheck = MARK_check, .x6_options = MARK_opts, }, { .family = NFPROTO_IPV4, .name = "MARK", .version = XTABLES_VERSION, .revision = 1, .size = XT_ALIGN(sizeof(struct xt_mark_target_info_v1)), .userspacesize = XT_ALIGN(sizeof(struct xt_mark_target_info_v1)), .help = MARK_help, .print = MARK_print_v1, .save = MARK_save_v1, .x6_parse = MARK_parse_v1, .x6_fcheck = MARK_check, .x6_options = MARK_opts, }, { .version = XTABLES_VERSION, .name = "MARK", .revision = 2, .family = NFPROTO_UNSPEC, .size = XT_ALIGN(sizeof(struct xt_mark_tginfo2)), .userspacesize = XT_ALIGN(sizeof(struct xt_mark_tginfo2)), .help = mark_tg_help, .print = mark_tg_print, .save = mark_tg_save, .x6_parse = mark_tg_parse, .x6_fcheck = mark_tg_check, .x6_options = mark_tg_opts, }, }; void _init(void) { xtables_register_targets(mark_tg_reg, ARRAY_SIZE(mark_tg_reg)); }
290
./android_firewall/external/iptables/extensions/libipt_CLUSTERIP.c
/* Shared library add-on to iptables to add CLUSTERIP target support. * (C) 2003 by Harald Welte <[email protected]> * * Development of this code was funded by SuSE AG, http://www.suse.com/ */ #include <stdbool.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <getopt.h> #include <stddef.h> #if defined(__GLIBC__) && __GLIBC__ == 2 #include <net/ethernet.h> #else #include <linux/if_ether.h> #endif #include <xtables.h> #include <linux/netfilter_ipv4/ipt_CLUSTERIP.h> enum { O_NEW = 0, O_HASHMODE, O_CLUSTERMAC, O_TOTAL_NODES, O_LOCAL_NODE, O_HASH_INIT, F_NEW = 1 << O_NEW, F_HASHMODE = 1 << O_HASHMODE, F_CLUSTERMAC = 1 << O_CLUSTERMAC, F_TOTAL_NODES = 1 << O_TOTAL_NODES, F_LOCAL_NODE = 1 << O_LOCAL_NODE, F_FULL = F_NEW | F_HASHMODE | F_CLUSTERMAC | F_TOTAL_NODES | F_LOCAL_NODE, }; static void CLUSTERIP_help(void) { printf( "CLUSTERIP target options:\n" " --new Create a new ClusterIP\n" " --hashmode <mode> Specify hashing mode\n" " sourceip\n" " sourceip-sourceport\n" " sourceip-sourceport-destport\n" " --clustermac <mac> Set clusterIP MAC address\n" " --total-nodes <num> Set number of total nodes in cluster\n" " --local-node <num> Set the local node number\n" " --hash-init <num> Set init value of the Jenkins hash\n"); } #define s struct ipt_clusterip_tgt_info static const struct xt_option_entry CLUSTERIP_opts[] = { {.name = "new", .id = O_NEW, .type = XTTYPE_NONE}, {.name = "hashmode", .id = O_HASHMODE, .type = XTTYPE_STRING, .also = O_NEW}, {.name = "clustermac", .id = O_CLUSTERMAC, .type = XTTYPE_ETHERMAC, .also = O_NEW, .flags = XTOPT_PUT, XTOPT_POINTER(s, clustermac)}, {.name = "total-nodes", .id = O_TOTAL_NODES, .type = XTTYPE_UINT16, .flags = XTOPT_PUT, XTOPT_POINTER(s, num_total_nodes), .also = O_NEW, .max = CLUSTERIP_MAX_NODES}, {.name = "local-node", .id = O_LOCAL_NODE, .type = XTTYPE_UINT16, .flags = XTOPT_PUT, XTOPT_POINTER(s, local_nodes[0]), .also = O_NEW, .max = CLUSTERIP_MAX_NODES}, {.name = "hash-init", .id = O_HASH_INIT, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, hash_initval), .also = O_NEW, .max = UINT_MAX}, XTOPT_TABLEEND, }; #undef s static void CLUSTERIP_parse(struct xt_option_call *cb) { struct ipt_clusterip_tgt_info *cipinfo = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_NEW: cipinfo->flags |= CLUSTERIP_FLAG_NEW; break; case O_HASHMODE: if (strcmp(cb->arg, "sourceip") == 0) cipinfo->hash_mode = CLUSTERIP_HASHMODE_SIP; else if (strcmp(cb->arg, "sourceip-sourceport") == 0) cipinfo->hash_mode = CLUSTERIP_HASHMODE_SIP_SPT; else if (strcmp(cb->arg, "sourceip-sourceport-destport") == 0) cipinfo->hash_mode = CLUSTERIP_HASHMODE_SIP_SPT_DPT; else xtables_error(PARAMETER_PROBLEM, "Unknown hashmode \"%s\"\n", cb->arg); break; case O_CLUSTERMAC: if (!(cipinfo->clustermac[0] & 0x01)) xtables_error(PARAMETER_PROBLEM, "MAC has to be a multicast ethernet address\n"); break; case O_LOCAL_NODE: cipinfo->num_local_nodes = 1; break; } } static void CLUSTERIP_check(struct xt_fcheck_call *cb) { if (cb->xflags == 0) return; if ((cb->xflags & F_FULL) == F_FULL) return; xtables_error(PARAMETER_PROBLEM, "CLUSTERIP target: Invalid parameter combination\n"); } static const char *hashmode2str(enum clusterip_hashmode mode) { const char *retstr; switch (mode) { case CLUSTERIP_HASHMODE_SIP: retstr = "sourceip"; break; case CLUSTERIP_HASHMODE_SIP_SPT: retstr = "sourceip-sourceport"; break; case CLUSTERIP_HASHMODE_SIP_SPT_DPT: retstr = "sourceip-sourceport-destport"; break; default: retstr = "unknown-error"; break; } return retstr; } static const char *mac2str(const uint8_t mac[ETH_ALEN]) { static char buf[ETH_ALEN*3]; sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); return buf; } static void CLUSTERIP_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct ipt_clusterip_tgt_info *cipinfo = (const struct ipt_clusterip_tgt_info *)target->data; if (!(cipinfo->flags & CLUSTERIP_FLAG_NEW)) { printf(" CLUSTERIP"); return; } printf(" CLUSTERIP hashmode=%s clustermac=%s total_nodes=%u local_node=%u hash_init=%u", hashmode2str(cipinfo->hash_mode), mac2str(cipinfo->clustermac), cipinfo->num_total_nodes, cipinfo->local_nodes[0], cipinfo->hash_initval); } static void CLUSTERIP_save(const void *ip, const struct xt_entry_target *target) { const struct ipt_clusterip_tgt_info *cipinfo = (const struct ipt_clusterip_tgt_info *)target->data; /* if this is not a new entry, we don't need to save target * parameters */ if (!(cipinfo->flags & CLUSTERIP_FLAG_NEW)) return; printf(" --new --hashmode %s --clustermac %s --total-nodes %d --local-node %d --hash-init %u", hashmode2str(cipinfo->hash_mode), mac2str(cipinfo->clustermac), cipinfo->num_total_nodes, cipinfo->local_nodes[0], cipinfo->hash_initval); } static struct xtables_target clusterip_tg_reg = { .name = "CLUSTERIP", .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct ipt_clusterip_tgt_info)), .userspacesize = offsetof(struct ipt_clusterip_tgt_info, config), .help = CLUSTERIP_help, .x6_parse = CLUSTERIP_parse, .x6_fcheck = CLUSTERIP_check, .print = CLUSTERIP_print, .save = CLUSTERIP_save, .x6_options = CLUSTERIP_opts, }; void _init(void) { xtables_register_target(&clusterip_tg_reg); }
291
./android_firewall/external/iptables/extensions/libxt_pkttype.c
/* * Shared library add-on to iptables to match * packets by their type (BROADCAST, UNICAST, MULTICAST). * * Michal Ludvig <[email protected]> */ #include <stdio.h> #include <string.h> #include <xtables.h> #include <linux/if_packet.h> #include <linux/netfilter/xt_pkttype.h> enum { O_PKTTYPE = 0, }; struct pkttypes { const char *name; unsigned char pkttype; unsigned char printhelp; const char *help; }; static const struct pkttypes supported_types[] = { {"unicast", PACKET_HOST, 1, "to us"}, {"broadcast", PACKET_BROADCAST, 1, "to all"}, {"multicast", PACKET_MULTICAST, 1, "to group"}, /* {"otherhost", PACKET_OTHERHOST, 1, "to someone else"}, {"outgoing", PACKET_OUTGOING, 1, "outgoing of any type"}, */ /* aliases */ {"bcast", PACKET_BROADCAST, 0, NULL}, {"mcast", PACKET_MULTICAST, 0, NULL}, {"host", PACKET_HOST, 0, NULL} }; static void print_types(void) { unsigned int i; printf("Valid packet types:\n"); for (i = 0; i < ARRAY_SIZE(supported_types); ++i) if(supported_types[i].printhelp == 1) printf("\t%-14s\t\t%s\n", supported_types[i].name, supported_types[i].help); printf("\n"); } static void pkttype_help(void) { printf( "pkttype match options:\n" "[!] --pkt-type packettype match packet type\n"); print_types(); } static const struct xt_option_entry pkttype_opts[] = { {.name = "pkt-type", .id = O_PKTTYPE, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_INVERT}, XTOPT_TABLEEND, }; static void parse_pkttype(const char *pkttype, struct xt_pkttype_info *info) { unsigned int i; for (i = 0; i < ARRAY_SIZE(supported_types); ++i) if(strcasecmp(pkttype, supported_types[i].name)==0) { info->pkttype=supported_types[i].pkttype; return; } xtables_error(PARAMETER_PROBLEM, "Bad packet type '%s'", pkttype); } static void pkttype_parse(struct xt_option_call *cb) { struct xt_pkttype_info *info = cb->data; xtables_option_parse(cb); parse_pkttype(cb->arg, info); if (cb->invert) info->invert = 1; } static void print_pkttype(const struct xt_pkttype_info *info) { unsigned int i; for (i = 0; i < ARRAY_SIZE(supported_types); ++i) if(supported_types[i].pkttype==info->pkttype) { printf("%s", supported_types[i].name); return; } printf("%d", info->pkttype); /* in case we didn't find an entry in named-packtes */ } static void pkttype_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_pkttype_info *info = (const void *)match->data; printf(" PKTTYPE %s= ", info->invert ? "!" : ""); print_pkttype(info); } static void pkttype_save(const void *ip, const struct xt_entry_match *match) { const struct xt_pkttype_info *info = (const void *)match->data; printf("%s --pkt-type ", info->invert ? " !" : ""); print_pkttype(info); } static struct xtables_match pkttype_match = { .family = NFPROTO_UNSPEC, .name = "pkttype", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_pkttype_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_pkttype_info)), .help = pkttype_help, .print = pkttype_print, .save = pkttype_save, .x6_parse = pkttype_parse, .x6_options = pkttype_opts, }; void _init(void) { xtables_register_match(&pkttype_match); }
292
./android_firewall/external/iptables/extensions/libxt_IDLETIMER.c
/* * Shared library add-on for iptables to add IDLETIMER support. * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Luciano Coelho <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_IDLETIMER.h> enum { O_TIMEOUT = 0, O_LABEL, }; #define s struct idletimer_tg_info static const struct xt_option_entry idletimer_tg_opts[] = { {.name = "timeout", .id = O_TIMEOUT, .type = XTTYPE_UINT32, .flags = XTOPT_MAND | XTOPT_PUT, XTOPT_POINTER(s, timeout)}, {.name = "label", .id = O_LABEL, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_PUT, XTOPT_POINTER(s, label)}, XTOPT_TABLEEND, }; #undef s static void idletimer_tg_help(void) { printf( "IDLETIMER target options:\n" " --timeout time Timeout until the notification is sent (in seconds)\n" " --label string Unique rule identifier\n" "\n"); } static void idletimer_tg_print(const void *ip, const struct xt_entry_target *target, int numeric) { struct idletimer_tg_info *info = (struct idletimer_tg_info *) target->data; printf(" timeout:%u", info->timeout); printf(" label:%s", info->label); } static void idletimer_tg_save(const void *ip, const struct xt_entry_target *target) { struct idletimer_tg_info *info = (struct idletimer_tg_info *) target->data; printf(" --timeout %u", info->timeout); printf(" --label %s", info->label); } static struct xtables_target idletimer_tg_reg = { .family = NFPROTO_UNSPEC, .name = "IDLETIMER", .version = XTABLES_VERSION, .revision = 0, .size = XT_ALIGN(sizeof(struct idletimer_tg_info)), .userspacesize = offsetof(struct idletimer_tg_info, timer), .help = idletimer_tg_help, .x6_parse = xtables_option_parse, .print = idletimer_tg_print, .save = idletimer_tg_save, .x6_options = idletimer_tg_opts, }; void _init(void) { xtables_register_target(&idletimer_tg_reg); }
293
./android_firewall/external/iptables/extensions/libxt_TEE.c
/* * "TEE" target extension for iptables * Copyright © Sebastian Claßen <sebastian.classen [at] freenet.ag>, 2007 * Jan Engelhardt <jengelh [at] medozas de>, 2007 - 2010 * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License; either * version 2 of the License, or any later version, as published by the * Free Software Foundation. */ #include <sys/socket.h> #include <getopt.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <net/if.h> #include <netinet/in.h> #include <xtables.h> #include <linux/netfilter.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter/xt_TEE.h> enum { O_GATEWAY = 0, O_OIF, }; #define s struct xt_tee_tginfo static const struct xt_option_entry tee_tg_opts[] = { {.name = "gateway", .id = O_GATEWAY, .type = XTTYPE_HOST, .flags = XTOPT_MAND | XTOPT_PUT, XTOPT_POINTER(s, gw)}, {.name = "oif", .id = O_OIF, .type = XTTYPE_STRING, .flags = XTOPT_PUT, XTOPT_POINTER(s, oif)}, XTOPT_TABLEEND, }; #undef s static void tee_tg_help(void) { printf( "TEE target options:\n" " --gateway IPADDR Route packet via the gateway given by address\n" " --oif NAME Include oif in route calculation\n" "\n"); } static void tee_tg_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_tee_tginfo *info = (const void *)target->data; if (numeric) printf(" TEE gw:%s", xtables_ipaddr_to_numeric(&info->gw.in)); else printf(" TEE gw:%s", xtables_ipaddr_to_anyname(&info->gw.in)); if (*info->oif != '\0') printf(" oif=%s", info->oif); } static void tee_tg6_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct xt_tee_tginfo *info = (const void *)target->data; if (numeric) printf(" TEE gw:%s", xtables_ip6addr_to_numeric(&info->gw.in6)); else printf(" TEE gw:%s", xtables_ip6addr_to_anyname(&info->gw.in6)); if (*info->oif != '\0') printf(" oif=%s", info->oif); } static void tee_tg_save(const void *ip, const struct xt_entry_target *target) { const struct xt_tee_tginfo *info = (const void *)target->data; printf(" --gateway %s", xtables_ipaddr_to_numeric(&info->gw.in)); if (*info->oif != '\0') printf(" --oif %s", info->oif); } static void tee_tg6_save(const void *ip, const struct xt_entry_target *target) { const struct xt_tee_tginfo *info = (const void *)target->data; printf(" --gateway %s", xtables_ip6addr_to_numeric(&info->gw.in6)); if (*info->oif != '\0') printf(" --oif %s", info->oif); } static struct xtables_target tee_tg_reg[] = { { .name = "TEE", .version = XTABLES_VERSION, .revision = 1, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct xt_tee_tginfo)), .userspacesize = XT_ALIGN(sizeof(struct xt_tee_tginfo)), .help = tee_tg_help, .print = tee_tg_print, .save = tee_tg_save, .x6_parse = xtables_option_parse, .x6_options = tee_tg_opts, }, { .name = "TEE", .version = XTABLES_VERSION, .revision = 1, .family = NFPROTO_IPV6, .size = XT_ALIGN(sizeof(struct xt_tee_tginfo)), .userspacesize = XT_ALIGN(sizeof(struct xt_tee_tginfo)), .help = tee_tg_help, .print = tee_tg6_print, .save = tee_tg6_save, .x6_parse = xtables_option_parse, .x6_options = tee_tg_opts, }, }; void _init(void) { xtables_register_targets(tee_tg_reg, ARRAY_SIZE(tee_tg_reg)); }
294
./android_firewall/external/iptables/extensions/libipt_SNAT.c
#include <stdio.h> #include <netdb.h> #include <string.h> #include <stdlib.h> #include <xtables.h> #include <iptables.h> #include <limits.h> /* INT_MAX in ip_tables.h */ #include <linux/netfilter_ipv4/ip_tables.h> #include <net/netfilter/nf_nat.h> enum { O_TO_SRC = 0, O_RANDOM, O_PERSISTENT, O_X_TO_SRC, F_TO_SRC = 1 << O_TO_SRC, F_RANDOM = 1 << O_RANDOM, F_X_TO_SRC = 1 << O_X_TO_SRC, }; /* Source NAT data consists of a multi-range, indicating where to map to. */ struct ipt_natinfo { struct xt_entry_target t; struct nf_nat_multi_range mr; }; static void SNAT_help(void) { printf( "SNAT target options:\n" " --to-source [<ipaddr>[-<ipaddr>]][:port[-port]]\n" " Address to map source to.\n" "[--random] [--persistent]\n"); } static const struct xt_option_entry SNAT_opts[] = { {.name = "to-source", .id = O_TO_SRC, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_MULTI}, {.name = "random", .id = O_RANDOM, .type = XTTYPE_NONE}, {.name = "persistent", .id = O_PERSISTENT, .type = XTTYPE_NONE}, XTOPT_TABLEEND, }; static struct ipt_natinfo * append_range(struct ipt_natinfo *info, const struct nf_nat_range *range) { unsigned int size; /* One rangesize already in struct ipt_natinfo */ size = XT_ALIGN(sizeof(*info) + info->mr.rangesize * sizeof(*range)); info = realloc(info, size); if (!info) xtables_error(OTHER_PROBLEM, "Out of memory\n"); info->t.u.target_size = size; info->mr.range[info->mr.rangesize] = *range; info->mr.rangesize++; return info; } /* Ranges expected in network order. */ static struct xt_entry_target * parse_to(const char *orig_arg, int portok, struct ipt_natinfo *info) { struct nf_nat_range range; char *arg, *colon, *dash, *error; const struct in_addr *ip; arg = strdup(orig_arg); if (arg == NULL) xtables_error(RESOURCE_PROBLEM, "strdup"); memset(&range, 0, sizeof(range)); colon = strchr(arg, ':'); if (colon) { int port; if (!portok) xtables_error(PARAMETER_PROBLEM, "Need TCP, UDP, SCTP or DCCP with port specification"); range.flags |= IP_NAT_RANGE_PROTO_SPECIFIED; port = atoi(colon+1); if (port <= 0 || port > 65535) xtables_error(PARAMETER_PROBLEM, "Port `%s' not valid\n", colon+1); error = strchr(colon+1, ':'); if (error) xtables_error(PARAMETER_PROBLEM, "Invalid port:port syntax - use dash\n"); dash = strchr(colon, '-'); if (!dash) { range.min.tcp.port = range.max.tcp.port = htons(port); } else { int maxport; maxport = atoi(dash + 1); if (maxport <= 0 || maxport > 65535) xtables_error(PARAMETER_PROBLEM, "Port `%s' not valid\n", dash+1); if (maxport < port) /* People are stupid. */ xtables_error(PARAMETER_PROBLEM, "Port range `%s' funky\n", colon+1); range.min.tcp.port = htons(port); range.max.tcp.port = htons(maxport); } /* Starts with a colon? No IP info...*/ if (colon == arg) { free(arg); return &(append_range(info, &range)->t); } *colon = '\0'; } range.flags |= IP_NAT_RANGE_MAP_IPS; dash = strchr(arg, '-'); if (colon && dash && dash > colon) dash = NULL; if (dash) *dash = '\0'; ip = xtables_numeric_to_ipaddr(arg); if (!ip) xtables_error(PARAMETER_PROBLEM, "Bad IP address \"%s\"\n", arg); range.min_ip = ip->s_addr; if (dash) { ip = xtables_numeric_to_ipaddr(dash+1); if (!ip) xtables_error(PARAMETER_PROBLEM, "Bad IP address \"%s\"\n", dash+1); range.max_ip = ip->s_addr; } else range.max_ip = range.min_ip; free(arg); return &(append_range(info, &range)->t); } static void SNAT_parse(struct xt_option_call *cb) { const struct ipt_entry *entry = cb->xt_entry; struct ipt_natinfo *info = (void *)(*cb->target); int portok; if (entry->ip.proto == IPPROTO_TCP || entry->ip.proto == IPPROTO_UDP || entry->ip.proto == IPPROTO_SCTP || entry->ip.proto == IPPROTO_DCCP || entry->ip.proto == IPPROTO_ICMP) portok = 1; else portok = 0; xtables_option_parse(cb); switch (cb->entry->id) { case O_TO_SRC: if (cb->xflags & F_X_TO_SRC) { if (!kernel_version) get_kernel_version(); if (kernel_version > LINUX_VERSION(2, 6, 10)) xtables_error(PARAMETER_PROBLEM, "SNAT: Multiple --to-source not supported"); } *cb->target = parse_to(cb->arg, portok, info); cb->xflags |= F_X_TO_SRC; break; case O_PERSISTENT: info->mr.range[0].flags |= IP_NAT_RANGE_PERSISTENT; break; } } static void SNAT_fcheck(struct xt_fcheck_call *cb) { static const unsigned int f = F_TO_SRC | F_RANDOM; struct nf_nat_multi_range *mr = cb->data; if ((cb->xflags & f) == f) mr->range[0].flags |= IP_NAT_RANGE_PROTO_RANDOM; } static void print_range(const struct nf_nat_range *r) { if (r->flags & IP_NAT_RANGE_MAP_IPS) { struct in_addr a; a.s_addr = r->min_ip; printf("%s", xtables_ipaddr_to_numeric(&a)); if (r->max_ip != r->min_ip) { a.s_addr = r->max_ip; printf("-%s", xtables_ipaddr_to_numeric(&a)); } } if (r->flags & IP_NAT_RANGE_PROTO_SPECIFIED) { printf(":"); printf("%hu", ntohs(r->min.tcp.port)); if (r->max.tcp.port != r->min.tcp.port) printf("-%hu", ntohs(r->max.tcp.port)); } } static void SNAT_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct ipt_natinfo *info = (const void *)target; unsigned int i = 0; printf(" to:"); for (i = 0; i < info->mr.rangesize; i++) { print_range(&info->mr.range[i]); if (info->mr.range[i].flags & IP_NAT_RANGE_PROTO_RANDOM) printf(" random"); if (info->mr.range[i].flags & IP_NAT_RANGE_PERSISTENT) printf(" persistent"); } } static void SNAT_save(const void *ip, const struct xt_entry_target *target) { const struct ipt_natinfo *info = (const void *)target; unsigned int i = 0; for (i = 0; i < info->mr.rangesize; i++) { printf(" --to-source "); print_range(&info->mr.range[i]); if (info->mr.range[i].flags & IP_NAT_RANGE_PROTO_RANDOM) printf(" --random"); if (info->mr.range[i].flags & IP_NAT_RANGE_PERSISTENT) printf(" --persistent"); } } static struct xtables_target snat_tg_reg = { .name = "SNAT", .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct nf_nat_multi_range)), .userspacesize = XT_ALIGN(sizeof(struct nf_nat_multi_range)), .help = SNAT_help, .x6_parse = SNAT_parse, .x6_fcheck = SNAT_fcheck, .print = SNAT_print, .save = SNAT_save, .x6_options = SNAT_opts, }; void _init(void) { xtables_register_target(&snat_tg_reg); }
295
./android_firewall/external/iptables/extensions/libxt_time.c
/* * libxt_time - iptables part for xt_time * Copyright ┬⌐ CC Computer Consultants GmbH, 2007 * Contact: <[email protected]> * * libxt_time.c is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 or 3 of the License. * * Based on libipt_time.c. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <linux/types.h> #include <linux/netfilter/xt_time.h> #include <xtables.h> enum { O_DATE_START = 0, O_DATE_STOP, O_TIME_START, O_TIME_STOP, O_MONTHDAYS, O_WEEKDAYS, O_LOCAL_TZ, O_UTC, O_KERNEL_TZ, F_LOCAL_TZ = 1 << O_LOCAL_TZ, F_UTC = 1 << O_UTC, F_KERNEL_TZ = 1 << O_KERNEL_TZ, }; static const char *const week_days[] = { NULL, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", }; static const struct xt_option_entry time_opts[] = { {.name = "datestart", .id = O_DATE_START, .type = XTTYPE_STRING}, {.name = "datestop", .id = O_DATE_STOP, .type = XTTYPE_STRING}, {.name = "timestart", .id = O_TIME_START, .type = XTTYPE_STRING}, {.name = "timestop", .id = O_TIME_STOP, .type = XTTYPE_STRING}, {.name = "weekdays", .id = O_WEEKDAYS, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, {.name = "monthdays", .id = O_MONTHDAYS, .type = XTTYPE_STRING, .flags = XTOPT_INVERT}, {.name = "localtz", .id = O_LOCAL_TZ, .type = XTTYPE_NONE, .excl = F_UTC}, {.name = "utc", .id = O_UTC, .type = XTTYPE_NONE, .excl = F_LOCAL_TZ | F_KERNEL_TZ}, {.name = "kerneltz", .id = O_KERNEL_TZ, .type = XTTYPE_NONE, .excl = F_UTC}, XTOPT_TABLEEND, }; static void time_help(void) { printf( "time match options:\n" " --datestart time Start and stop time, to be given in ISO 8601\n" " --datestop time (YYYY[-MM[-DD[Thh[:mm[:ss]]]]])\n" " --timestart time Start and stop daytime (hh:mm[:ss])\n" " --timestop time (between 00:00:00 and 23:59:59)\n" "[!] --monthdays value List of days on which to match, separated by comma\n" " (Possible days: 1 to 31; defaults to all)\n" "[!] --weekdays value List of weekdays on which to match, sep. by comma\n" " (Possible days: Mon,Tue,Wed,Thu,Fri,Sat,Sun or 1 to 7\n" " Defaults to all weekdays.)\n" " --kerneltz Work with the kernel timezone instead of UTC\n"); } static void time_init(struct xt_entry_match *m) { struct xt_time_info *info = (void *)m->data; /* By default, we match on every day, every daytime */ info->monthdays_match = XT_TIME_ALL_MONTHDAYS; info->weekdays_match = XT_TIME_ALL_WEEKDAYS; info->daytime_start = XT_TIME_MIN_DAYTIME; info->daytime_stop = XT_TIME_MAX_DAYTIME; /* ...and have no date-begin or date-end boundary */ info->date_start = 0; info->date_stop = INT_MAX; } static time_t time_parse_date(const char *s, bool end) { unsigned int month = 1, day = 1, hour = 0, minute = 0, second = 0; unsigned int year = end ? 2038 : 1970; const char *os = s; struct tm tm; time_t ret; char *e; year = strtoul(s, &e, 10); if ((*e != '-' && *e != '\0') || year < 1970 || year > 2038) goto out; if (*e == '\0') goto eval; s = e + 1; month = strtoul(s, &e, 10); if ((*e != '-' && *e != '\0') || month > 12) goto out; if (*e == '\0') goto eval; s = e + 1; day = strtoul(s, &e, 10); if ((*e != 'T' && *e != '\0') || day > 31) goto out; if (*e == '\0') goto eval; s = e + 1; hour = strtoul(s, &e, 10); if ((*e != ':' && *e != '\0') || hour > 23) goto out; if (*e == '\0') goto eval; s = e + 1; minute = strtoul(s, &e, 10); if ((*e != ':' && *e != '\0') || minute > 59) goto out; if (*e == '\0') goto eval; s = e + 1; second = strtoul(s, &e, 10); if (*e != '\0' || second > 59) goto out; eval: tm.tm_year = year - 1900; tm.tm_mon = month - 1; tm.tm_mday = day; tm.tm_hour = hour; tm.tm_min = minute; tm.tm_sec = second; tm.tm_isdst = 0; /* * Offsetting, if any, is done by xt_time.ko, * so we have to disable it here in userspace. */ setenv("TZ", "UTC", true); tzset(); ret = mktime(&tm); if (ret >= 0) return ret; perror("mktime"); xtables_error(OTHER_PROBLEM, "mktime returned an error"); out: xtables_error(PARAMETER_PROBLEM, "Invalid date \"%s\" specified. Should " "be YYYY[-MM[-DD[Thh[:mm[:ss]]]]]", os); return -1; } static unsigned int time_parse_minutes(const char *s) { unsigned int hour, minute, second = 0; char *e; hour = strtoul(s, &e, 10); if (*e != ':' || hour > 23) goto out; s = e + 1; minute = strtoul(s, &e, 10); if ((*e != ':' && *e != '\0') || minute > 59) goto out; if (*e == '\0') goto eval; s = e + 1; second = strtoul(s, &e, 10); if (*e != '\0' || second > 59) goto out; eval: return 60 * 60 * hour + 60 * minute + second; out: xtables_error(PARAMETER_PROBLEM, "invalid time \"%s\" specified, " "should be hh:mm[:ss] format and within the boundaries", s); return -1; } static const char *my_strseg(char *buf, unsigned int buflen, const char **arg, char delim) { const char *sep; if (*arg == NULL || **arg == '\0') return NULL; sep = strchr(*arg, delim); if (sep == NULL) { snprintf(buf, buflen, "%s", *arg); *arg = NULL; return buf; } snprintf(buf, buflen, "%.*s", (unsigned int)(sep - *arg), *arg); *arg = sep + 1; return buf; } static uint32_t time_parse_monthdays(const char *arg) { char day[3], *err = NULL; uint32_t ret = 0; unsigned int i; while (my_strseg(day, sizeof(day), &arg, ',') != NULL) { i = strtoul(day, &err, 0); if ((*err != ',' && *err != '\0') || i > 31) xtables_error(PARAMETER_PROBLEM, "%s is not a valid day for --monthdays", day); ret |= 1 << i; } return ret; } static unsigned int time_parse_weekdays(const char *arg) { char day[4], *err = NULL; unsigned int i, ret = 0; bool valid; while (my_strseg(day, sizeof(day), &arg, ',') != NULL) { i = strtoul(day, &err, 0); if (*err == '\0') { if (i == 0) xtables_error(PARAMETER_PROBLEM, "No, the week does NOT begin with Sunday."); ret |= 1 << i; continue; } valid = false; for (i = 1; i < ARRAY_SIZE(week_days); ++i) if (strncmp(day, week_days[i], 2) == 0) { ret |= 1 << i; valid = true; } if (!valid) xtables_error(PARAMETER_PROBLEM, "%s is not a valid day specifier", day); } return ret; } static void time_parse(struct xt_option_call *cb) { struct xt_time_info *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_DATE_START: info->date_start = time_parse_date(cb->arg, false); break; case O_DATE_STOP: info->date_stop = time_parse_date(cb->arg, true); break; case O_TIME_START: info->daytime_start = time_parse_minutes(cb->arg); break; case O_TIME_STOP: info->daytime_stop = time_parse_minutes(cb->arg); break; case O_LOCAL_TZ: fprintf(stderr, "WARNING: --localtz is being replaced by " "--kerneltz, since \"local\" is ambiguous. Note the " "kernel timezone has caveats - " "see manpage for details.\n"); /* fallthrough */ case O_KERNEL_TZ: info->flags |= XT_TIME_LOCAL_TZ; break; case O_MONTHDAYS: info->monthdays_match = time_parse_monthdays(cb->arg); if (cb->invert) info->monthdays_match ^= XT_TIME_ALL_MONTHDAYS; break; case O_WEEKDAYS: info->weekdays_match = time_parse_weekdays(cb->arg); if (cb->invert) info->weekdays_match ^= XT_TIME_ALL_WEEKDAYS; break; } } static void time_print_date(time_t date, const char *command) { struct tm *t; /* If it is the default value, do not print it. */ if (date == 0 || date == LONG_MAX) return; t = gmtime(&date); if (command != NULL) /* * Need a contiguous string (no whitespaces), hence using * the ISO 8601 "T" variant. */ printf(" %s %04u-%02u-%02uT%02u:%02u:%02u", command, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); else printf(" %04u-%02u-%02u %02u:%02u:%02u", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); } static void time_print_monthdays(uint32_t mask, bool human_readable) { unsigned int i, nbdays = 0; printf(" "); for (i = 1; i <= 31; ++i) if (mask & (1 << i)) { if (nbdays++ > 0) printf(","); printf("%u", i); if (human_readable) switch (i % 10) { case 1: printf("st"); break; case 2: printf("nd"); break; case 3: printf("rd"); break; default: printf("th"); break; } } } static void time_print_weekdays(unsigned int mask) { unsigned int i, nbdays = 0; printf(" "); for (i = 1; i <= 7; ++i) if (mask & (1 << i)) { if (nbdays > 0) printf(",%s", week_days[i]); else printf("%s", week_days[i]); ++nbdays; } } static inline void divide_time(unsigned int fulltime, unsigned int *hours, unsigned int *minutes, unsigned int *seconds) { *seconds = fulltime % 60; fulltime /= 60; *minutes = fulltime % 60; *hours = fulltime / 60; } static void time_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_time_info *info = (const void *)match->data; unsigned int h, m, s; printf(" TIME"); if (info->daytime_start != XT_TIME_MIN_DAYTIME || info->daytime_stop != XT_TIME_MAX_DAYTIME) { divide_time(info->daytime_start, &h, &m, &s); printf(" from %02u:%02u:%02u", h, m, s); divide_time(info->daytime_stop, &h, &m, &s); printf(" to %02u:%02u:%02u", h, m, s); } if (info->weekdays_match != XT_TIME_ALL_WEEKDAYS) { printf(" on"); time_print_weekdays(info->weekdays_match); } if (info->monthdays_match != XT_TIME_ALL_MONTHDAYS) { printf(" on"); time_print_monthdays(info->monthdays_match, true); } if (info->date_start != 0) { printf(" starting from"); time_print_date(info->date_start, NULL); } if (info->date_stop != INT_MAX) { printf(" until date"); time_print_date(info->date_stop, NULL); } if (!(info->flags & XT_TIME_LOCAL_TZ)) printf(" UTC"); } static void time_save(const void *ip, const struct xt_entry_match *match) { const struct xt_time_info *info = (const void *)match->data; unsigned int h, m, s; if (info->daytime_start != XT_TIME_MIN_DAYTIME || info->daytime_stop != XT_TIME_MAX_DAYTIME) { divide_time(info->daytime_start, &h, &m, &s); printf(" --timestart %02u:%02u:%02u", h, m, s); divide_time(info->daytime_stop, &h, &m, &s); printf(" --timestop %02u:%02u:%02u", h, m, s); } if (info->monthdays_match != XT_TIME_ALL_MONTHDAYS) { printf(" --monthdays"); time_print_monthdays(info->monthdays_match, false); } if (info->weekdays_match != XT_TIME_ALL_WEEKDAYS) { printf(" --weekdays"); time_print_weekdays(info->weekdays_match); } time_print_date(info->date_start, "--datestart"); time_print_date(info->date_stop, "--datestop"); if (info->flags & XT_TIME_LOCAL_TZ) printf(" --kerneltz"); } static struct xtables_match time_match = { .name = "time", .family = NFPROTO_UNSPEC, .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_time_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_time_info)), .help = time_help, .init = time_init, .print = time_print, .save = time_save, .x6_parse = time_parse, .x6_options = time_opts, }; void _init(void) { xtables_register_match(&time_match); }
296
./android_firewall/external/iptables/extensions/libipt_TTL.c
/* Shared library add-on to iptables for the TTL target * (C) 2000 by Harald Welte <[email protected]> * * This program is distributed under the terms of GNU GPL */ #include <stdio.h> #include <xtables.h> #include <linux/netfilter_ipv4/ipt_TTL.h> enum { O_TTL_SET = 0, O_TTL_INC, O_TTL_DEC, F_TTL_SET = 1 << O_TTL_SET, F_TTL_INC = 1 << O_TTL_INC, F_TTL_DEC = 1 << O_TTL_DEC, F_ANY = F_TTL_SET | F_TTL_INC | F_TTL_DEC, }; #define s struct ipt_TTL_info static const struct xt_option_entry TTL_opts[] = { {.name = "ttl-set", .type = XTTYPE_UINT8, .id = O_TTL_SET, .excl = F_ANY, .flags = XTOPT_PUT, XTOPT_POINTER(s, ttl)}, {.name = "ttl-dec", .type = XTTYPE_UINT8, .id = O_TTL_DEC, .excl = F_ANY, .flags = XTOPT_PUT, XTOPT_POINTER(s, ttl), .min = 1}, {.name = "ttl-inc", .type = XTTYPE_UINT8, .id = O_TTL_INC, .excl = F_ANY, .flags = XTOPT_PUT, XTOPT_POINTER(s, ttl), .min = 1}, XTOPT_TABLEEND, }; #undef s static void TTL_help(void) { printf( "TTL target options\n" " --ttl-set value Set TTL to <value 0-255>\n" " --ttl-dec value Decrement TTL by <value 1-255>\n" " --ttl-inc value Increment TTL by <value 1-255>\n"); } static void TTL_parse(struct xt_option_call *cb) { struct ipt_TTL_info *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_TTL_SET: info->mode = IPT_TTL_SET; break; case O_TTL_DEC: info->mode = IPT_TTL_DEC; break; case O_TTL_INC: info->mode = IPT_TTL_INC; break; } } static void TTL_check(struct xt_fcheck_call *cb) { if (!(cb->xflags & F_ANY)) xtables_error(PARAMETER_PROBLEM, "TTL: You must specify an action"); } static void TTL_save(const void *ip, const struct xt_entry_target *target) { const struct ipt_TTL_info *info = (struct ipt_TTL_info *) target->data; switch (info->mode) { case IPT_TTL_SET: printf(" --ttl-set"); break; case IPT_TTL_DEC: printf(" --ttl-dec"); break; case IPT_TTL_INC: printf(" --ttl-inc"); break; } printf(" %u", info->ttl); } static void TTL_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct ipt_TTL_info *info = (struct ipt_TTL_info *) target->data; printf(" TTL "); switch (info->mode) { case IPT_TTL_SET: printf("set to"); break; case IPT_TTL_DEC: printf("decrement by"); break; case IPT_TTL_INC: printf("increment by"); break; } printf(" %u", info->ttl); } static struct xtables_target ttl_tg_reg = { .name = "TTL", .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct ipt_TTL_info)), .userspacesize = XT_ALIGN(sizeof(struct ipt_TTL_info)), .help = TTL_help, .print = TTL_print, .save = TTL_save, .x6_parse = TTL_parse, .x6_fcheck = TTL_check, .x6_options = TTL_opts, }; void _init(void) { xtables_register_target(&ttl_tg_reg); }
297
./android_firewall/external/iptables/extensions/libipt_MASQUERADE.c
#include <stdio.h> #include <netdb.h> #include <string.h> #include <stdlib.h> #include <getopt.h> #include <xtables.h> #include <limits.h> /* INT_MAX in ip_tables.h */ #include <linux/netfilter_ipv4/ip_tables.h> #include <net/netfilter/nf_nat.h> enum { O_TO_PORTS = 0, O_RANDOM, }; static void MASQUERADE_help(void) { printf( "MASQUERADE target options:\n" " --to-ports <port>[-<port>]\n" " Port (range) to map to.\n" " --random\n" " Randomize source port.\n"); } static const struct xt_option_entry MASQUERADE_opts[] = { {.name = "to-ports", .id = O_TO_PORTS, .type = XTTYPE_STRING}, {.name = "random", .id = O_RANDOM, .type = XTTYPE_NONE}, XTOPT_TABLEEND, }; static void MASQUERADE_init(struct xt_entry_target *t) { struct nf_nat_multi_range *mr = (struct nf_nat_multi_range *)t->data; /* Actually, it's 0, but it's ignored at the moment. */ mr->rangesize = 1; } /* Parses ports */ static void parse_ports(const char *arg, struct nf_nat_multi_range *mr) { char *end; unsigned int port, maxport; mr->range[0].flags |= IP_NAT_RANGE_PROTO_SPECIFIED; if (!xtables_strtoui(arg, &end, &port, 0, UINT16_MAX)) xtables_param_act(XTF_BAD_VALUE, "MASQUERADE", "--to-ports", arg); switch (*end) { case '\0': mr->range[0].min.tcp.port = mr->range[0].max.tcp.port = htons(port); return; case '-': if (!xtables_strtoui(end + 1, NULL, &maxport, 0, UINT16_MAX)) break; if (maxport < port) break; mr->range[0].min.tcp.port = htons(port); mr->range[0].max.tcp.port = htons(maxport); return; default: break; } xtables_param_act(XTF_BAD_VALUE, "MASQUERADE", "--to-ports", arg); } static void MASQUERADE_parse(struct xt_option_call *cb) { const struct ipt_entry *entry = cb->xt_entry; int portok; struct nf_nat_multi_range *mr = cb->data; if (entry->ip.proto == IPPROTO_TCP || entry->ip.proto == IPPROTO_UDP || entry->ip.proto == IPPROTO_SCTP || entry->ip.proto == IPPROTO_DCCP || entry->ip.proto == IPPROTO_ICMP) portok = 1; else portok = 0; xtables_option_parse(cb); switch (cb->entry->id) { case O_TO_PORTS: if (!portok) xtables_error(PARAMETER_PROBLEM, "Need TCP, UDP, SCTP or DCCP with port specification"); parse_ports(cb->arg, mr); break; case O_RANDOM: mr->range[0].flags |= IP_NAT_RANGE_PROTO_RANDOM; break; } } static void MASQUERADE_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct nf_nat_multi_range *mr = (const void *)target->data; const struct nf_nat_range *r = &mr->range[0]; if (r->flags & IP_NAT_RANGE_PROTO_SPECIFIED) { printf(" masq ports: "); printf("%hu", ntohs(r->min.tcp.port)); if (r->max.tcp.port != r->min.tcp.port) printf("-%hu", ntohs(r->max.tcp.port)); } if (r->flags & IP_NAT_RANGE_PROTO_RANDOM) printf(" random"); } static void MASQUERADE_save(const void *ip, const struct xt_entry_target *target) { const struct nf_nat_multi_range *mr = (const void *)target->data; const struct nf_nat_range *r = &mr->range[0]; if (r->flags & IP_NAT_RANGE_PROTO_SPECIFIED) { printf(" --to-ports %hu", ntohs(r->min.tcp.port)); if (r->max.tcp.port != r->min.tcp.port) printf("-%hu", ntohs(r->max.tcp.port)); } if (r->flags & IP_NAT_RANGE_PROTO_RANDOM) printf(" --random"); } static struct xtables_target masquerade_tg_reg = { .name = "MASQUERADE", .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct nf_nat_multi_range)), .userspacesize = XT_ALIGN(sizeof(struct nf_nat_multi_range)), .help = MASQUERADE_help, .init = MASQUERADE_init, .x6_parse = MASQUERADE_parse, .print = MASQUERADE_print, .save = MASQUERADE_save, .x6_options = MASQUERADE_opts, }; void _init(void) { xtables_register_target(&masquerade_tg_reg); }
298
./android_firewall/external/iptables/extensions/libxt_set.c
/* Copyright (C) 2000-2002 Joakim Axelsson <[email protected]> * Patrick Schaaf <[email protected]> * Martin Josefsson <[email protected]> * Copyright (C) 2003-2010 Jozsef Kadlecsik <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ /* Shared library add-on to iptables to add IP set matching. */ #include <stdbool.h> #include <stdio.h> #include <netdb.h> #include <string.h> #include <stdlib.h> #include <getopt.h> #include <ctype.h> #include <errno.h> #include <xtables.h> #include <linux/netfilter/xt_set.h> #include "libxt_set.h" /* Revision 0 */ static void set_help_v0(void) { printf("set match options:\n" " [!] --match-set name flags\n" " 'name' is the set name from to match,\n" " 'flags' are the comma separated list of\n" " 'src' and 'dst' specifications.\n"); } static const struct option set_opts_v0[] = { {.name = "match-set", .has_arg = true, .val = '1'}, {.name = "set", .has_arg = true, .val = '2'}, XT_GETOPT_TABLEEND, }; static void set_check_v0(unsigned int flags) { if (!flags) xtables_error(PARAMETER_PROBLEM, "You must specify `--match-set' with proper arguments"); } static int set_parse_v0(int c, char **argv, int invert, unsigned int *flags, const void *entry, struct xt_entry_match **match) { struct xt_set_info_match_v0 *myinfo = (struct xt_set_info_match_v0 *) (*match)->data; struct xt_set_info_v0 *info = &myinfo->match_set; switch (c) { case '2': fprintf(stderr, "--set option deprecated, please use --match-set\n"); case '1': /* --match-set <set> <flag>[,<flag> */ if (info->u.flags[0]) xtables_error(PARAMETER_PROBLEM, "--match-set can be specified only once"); if (invert) info->u.flags[0] |= IPSET_MATCH_INV; if (!argv[optind] || argv[optind][0] == '-' || argv[optind][0] == '!') xtables_error(PARAMETER_PROBLEM, "--match-set requires two args."); if (strlen(optarg) > IPSET_MAXNAMELEN - 1) xtables_error(PARAMETER_PROBLEM, "setname `%s' too long, max %d characters.", optarg, IPSET_MAXNAMELEN - 1); get_set_byname(optarg, (struct xt_set_info *)info); parse_dirs_v0(argv[optind], info); DEBUGP("parse: set index %u\n", info->index); optind++; *flags = 1; break; } return 1; } static void print_match_v0(const char *prefix, const struct xt_set_info_v0 *info) { int i; char setname[IPSET_MAXNAMELEN]; get_set_byid(setname, info->index); printf("%s %s %s", (info->u.flags[0] & IPSET_MATCH_INV) ? " !" : "", prefix, setname); for (i = 0; i < IPSET_DIM_MAX; i++) { if (!info->u.flags[i]) break; printf("%s%s", i == 0 ? " " : ",", info->u.flags[i] & IPSET_SRC ? "src" : "dst"); } } /* Prints out the matchinfo. */ static void set_print_v0(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_set_info_match_v0 *info = (const void *)match->data; print_match_v0("match-set", &info->match_set); } static void set_save_v0(const void *ip, const struct xt_entry_match *match) { const struct xt_set_info_match_v0 *info = (const void *)match->data; print_match_v0("--match-set", &info->match_set); } /* Revision 1 */ static int set_parse_v1(int c, char **argv, int invert, unsigned int *flags, const void *entry, struct xt_entry_match **match) { struct xt_set_info_match_v1 *myinfo = (struct xt_set_info_match_v1 *) (*match)->data; struct xt_set_info *info = &myinfo->match_set; switch (c) { case '2': fprintf(stderr, "--set option deprecated, please use --match-set\n"); case '1': /* --match-set <set> <flag>[,<flag> */ if (info->dim) xtables_error(PARAMETER_PROBLEM, "--match-set can be specified only once"); if (invert) info->flags |= IPSET_INV_MATCH; if (!argv[optind] || argv[optind][0] == '-' || argv[optind][0] == '!') xtables_error(PARAMETER_PROBLEM, "--match-set requires two args."); if (strlen(optarg) > IPSET_MAXNAMELEN - 1) xtables_error(PARAMETER_PROBLEM, "setname `%s' too long, max %d characters.", optarg, IPSET_MAXNAMELEN - 1); get_set_byname(optarg, info); parse_dirs(argv[optind], info); DEBUGP("parse: set index %u\n", info->index); optind++; *flags = 1; break; } return 1; } static void print_match(const char *prefix, const struct xt_set_info *info) { int i; char setname[IPSET_MAXNAMELEN]; get_set_byid(setname, info->index); printf("%s %s %s", (info->flags & IPSET_INV_MATCH) ? " !" : "", prefix, setname); for (i = 1; i <= info->dim; i++) { printf("%s%s", i == 1 ? " " : ",", info->flags & (1 << i) ? "src" : "dst"); } } /* Prints out the matchinfo. */ static void set_print_v1(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_set_info_match_v1 *info = (const void *)match->data; print_match("match-set", &info->match_set); } static void set_save_v1(const void *ip, const struct xt_entry_match *match) { const struct xt_set_info_match_v1 *info = (const void *)match->data; print_match("--match-set", &info->match_set); } /* Revision 2 */ static void set_help_v2(void) { printf("set match options:\n" " [!] --match-set name flags [--return-nomatch]\n" " 'name' is the set name from to match,\n" " 'flags' are the comma separated list of\n" " 'src' and 'dst' specifications.\n"); } static const struct option set_opts_v2[] = { {.name = "match-set", .has_arg = true, .val = '1'}, {.name = "set", .has_arg = true, .val = '2'}, {.name = "return-nomatch", .has_arg = false, .val = '3'}, XT_GETOPT_TABLEEND, }; static int set_parse_v2(int c, char **argv, int invert, unsigned int *flags, const void *entry, struct xt_entry_match **match) { struct xt_set_info_match_v1 *myinfo = (struct xt_set_info_match_v1 *) (*match)->data; struct xt_set_info *info = &myinfo->match_set; switch (c) { case '3': info->flags |= IPSET_RETURN_NOMATCH; break; case '2': fprintf(stderr, "--set option deprecated, please use --match-set\n"); case '1': /* --match-set <set> <flag>[,<flag> */ if (info->dim) xtables_error(PARAMETER_PROBLEM, "--match-set can be specified only once"); if (invert) info->flags |= IPSET_INV_MATCH; if (!argv[optind] || argv[optind][0] == '-' || argv[optind][0] == '!') xtables_error(PARAMETER_PROBLEM, "--match-set requires two args."); if (strlen(optarg) > IPSET_MAXNAMELEN - 1) xtables_error(PARAMETER_PROBLEM, "setname `%s' too long, max %d characters.", optarg, IPSET_MAXNAMELEN - 1); get_set_byname(optarg, info); parse_dirs(argv[optind], info); DEBUGP("parse: set index %u\n", info->index); optind++; *flags = 1; break; } return 1; } /* Prints out the matchinfo. */ static void set_print_v2(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_set_info_match_v1 *info = (const void *)match->data; print_match("match-set", &info->match_set); if (info->match_set.flags & IPSET_RETURN_NOMATCH) printf(" return-nomatch"); } static void set_save_v2(const void *ip, const struct xt_entry_match *match) { const struct xt_set_info_match_v1 *info = (const void *)match->data; print_match("--match-set", &info->match_set); if (info->match_set.flags & IPSET_RETURN_NOMATCH) printf(" --return-nomatch"); } static struct xtables_match set_mt_reg[] = { { .name = "set", .revision = 0, .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct xt_set_info_match_v0)), .userspacesize = XT_ALIGN(sizeof(struct xt_set_info_match_v0)), .help = set_help_v0, .parse = set_parse_v0, .final_check = set_check_v0, .print = set_print_v0, .save = set_save_v0, .extra_opts = set_opts_v0, }, { .name = "set", .revision = 1, .version = XTABLES_VERSION, .family = NFPROTO_UNSPEC, .size = XT_ALIGN(sizeof(struct xt_set_info_match_v1)), .userspacesize = XT_ALIGN(sizeof(struct xt_set_info_match_v1)), .help = set_help_v0, .parse = set_parse_v1, .final_check = set_check_v0, .print = set_print_v1, .save = set_save_v1, .extra_opts = set_opts_v0, }, { .name = "set", .revision = 2, .version = XTABLES_VERSION, .family = NFPROTO_UNSPEC, .size = XT_ALIGN(sizeof(struct xt_set_info_match_v1)), .userspacesize = XT_ALIGN(sizeof(struct xt_set_info_match_v1)), .help = set_help_v2, .parse = set_parse_v2, .final_check = set_check_v0, .print = set_print_v2, .save = set_save_v2, .extra_opts = set_opts_v2, }, }; void _init(void) { xtables_register_matches(set_mt_reg, ARRAY_SIZE(set_mt_reg)); }
299
./android_firewall/external/iptables/extensions/libxt_comment.c
/* Shared library add-on to iptables to add comment match support. * * ChangeLog * 2003-05-13: Brad Fisher <[email protected]> * Initial comment match * 2004-05-12: Brad Fisher <[email protected]> * Port to patch-o-matic-ng */ #include <stdio.h> #include <xtables.h> #include <linux/netfilter/xt_comment.h> enum { O_COMMENT = 0, }; static void comment_help(void) { printf( "comment match options:\n" "--comment COMMENT Attach a comment to a rule\n"); } static const struct xt_option_entry comment_opts[] = { {.name = "comment", .id = O_COMMENT, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_PUT, XTOPT_POINTER(struct xt_comment_info, comment)}, XTOPT_TABLEEND, }; static void comment_print(const void *ip, const struct xt_entry_match *match, int numeric) { struct xt_comment_info *commentinfo = (void *)match->data; commentinfo->comment[XT_MAX_COMMENT_LEN-1] = '\0'; printf(" /* %s */", commentinfo->comment); } /* Saves the union ipt_matchinfo in parsable form to stdout. */ static void comment_save(const void *ip, const struct xt_entry_match *match) { struct xt_comment_info *commentinfo = (void *)match->data; commentinfo->comment[XT_MAX_COMMENT_LEN-1] = '\0'; printf(" --comment"); xtables_save_string(commentinfo->comment); } static struct xtables_match comment_match = { .family = NFPROTO_UNSPEC, .name = "comment", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_comment_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_comment_info)), .help = comment_help, .print = comment_print, .save = comment_save, .x6_parse = xtables_option_parse, .x6_options = comment_opts, }; void _init(void) { xtables_register_match(&comment_match); }
300
./android_firewall/external/iptables/extensions/libipt_REJECT.c
/* Shared library add-on to iptables to add customized REJECT support. * * (C) 2000 Jozsef Kadlecsik <[email protected]> */ #include <stdio.h> #include <string.h> #include <xtables.h> #include <linux/netfilter_ipv4/ipt_REJECT.h> #include <linux/version.h> /* If we are compiling against a kernel that does not support * IPT_ICMP_ADMIN_PROHIBITED, we are emulating it. * The result will be a plain DROP of the packet instead of * reject. -- Maciej Soltysiak <[email protected]> */ #ifndef IPT_ICMP_ADMIN_PROHIBITED #define IPT_ICMP_ADMIN_PROHIBITED IPT_TCP_RESET + 1 #endif struct reject_names { const char *name; const char *alias; enum ipt_reject_with with; const char *desc; }; enum { O_REJECT_WITH = 0, }; static const struct reject_names reject_table[] = { {"icmp-net-unreachable", "net-unreach", IPT_ICMP_NET_UNREACHABLE, "ICMP network unreachable"}, {"icmp-host-unreachable", "host-unreach", IPT_ICMP_HOST_UNREACHABLE, "ICMP host unreachable"}, {"icmp-proto-unreachable", "proto-unreach", IPT_ICMP_PROT_UNREACHABLE, "ICMP protocol unreachable"}, {"icmp-port-unreachable", "port-unreach", IPT_ICMP_PORT_UNREACHABLE, "ICMP port unreachable (default)"}, #if 0 {"echo-reply", "echoreply", IPT_ICMP_ECHOREPLY, "for ICMP echo only: faked ICMP echo reply"}, #endif {"icmp-net-prohibited", "net-prohib", IPT_ICMP_NET_PROHIBITED, "ICMP network prohibited"}, {"icmp-host-prohibited", "host-prohib", IPT_ICMP_HOST_PROHIBITED, "ICMP host prohibited"}, {"tcp-reset", "tcp-rst", IPT_TCP_RESET, "TCP RST packet"}, {"icmp-admin-prohibited", "admin-prohib", IPT_ICMP_ADMIN_PROHIBITED, "ICMP administratively prohibited (*)"} }; static void print_reject_types(void) { unsigned int i; printf("Valid reject types:\n"); for (i = 0; i < ARRAY_SIZE(reject_table); ++i) { printf(" %-25s\t%s\n", reject_table[i].name, reject_table[i].desc); printf(" %-25s\talias\n", reject_table[i].alias); } printf("\n"); } static void REJECT_help(void) { printf( "REJECT target options:\n" "--reject-with type drop input packet and send back\n" " a reply packet according to type:\n"); print_reject_types(); printf("(*) See man page or read the INCOMPATIBILITES file for compatibility issues.\n"); } static const struct xt_option_entry REJECT_opts[] = { {.name = "reject-with", .id = O_REJECT_WITH, .type = XTTYPE_STRING}, XTOPT_TABLEEND, }; static void REJECT_init(struct xt_entry_target *t) { struct ipt_reject_info *reject = (struct ipt_reject_info *)t->data; /* default */ reject->with = IPT_ICMP_PORT_UNREACHABLE; } static void REJECT_parse(struct xt_option_call *cb) { struct ipt_reject_info *reject = cb->data; unsigned int i; xtables_option_parse(cb); for (i = 0; i < ARRAY_SIZE(reject_table); ++i) if (strncasecmp(reject_table[i].name, cb->arg, strlen(cb->arg)) == 0 || strncasecmp(reject_table[i].alias, cb->arg, strlen(cb->arg)) == 0) { reject->with = reject_table[i].with; return; } /* This due to be dropped late in 2.4 pre-release cycle --RR */ if (strncasecmp("echo-reply", cb->arg, strlen(cb->arg)) == 0 || strncasecmp("echoreply", cb->arg, strlen(cb->arg)) == 0) fprintf(stderr, "--reject-with echo-reply no longer" " supported\n"); xtables_error(PARAMETER_PROBLEM, "unknown reject type \"%s\"", cb->arg); } static void REJECT_print(const void *ip, const struct xt_entry_target *target, int numeric) { const struct ipt_reject_info *reject = (const struct ipt_reject_info *)target->data; unsigned int i; for (i = 0; i < ARRAY_SIZE(reject_table); ++i) if (reject_table[i].with == reject->with) break; printf(" reject-with %s", reject_table[i].name); } static void REJECT_save(const void *ip, const struct xt_entry_target *target) { const struct ipt_reject_info *reject = (const struct ipt_reject_info *)target->data; unsigned int i; for (i = 0; i < ARRAY_SIZE(reject_table); ++i) if (reject_table[i].with == reject->with) break; printf(" --reject-with %s", reject_table[i].name); } static struct xtables_target reject_tg_reg = { .name = "REJECT", .version = XTABLES_VERSION, .family = NFPROTO_IPV4, .size = XT_ALIGN(sizeof(struct ipt_reject_info)), .userspacesize = XT_ALIGN(sizeof(struct ipt_reject_info)), .help = REJECT_help, .init = REJECT_init, .print = REJECT_print, .save = REJECT_save, .x6_parse = REJECT_parse, .x6_options = REJECT_opts, }; void _init(void) { xtables_register_target(&reject_tg_reg); }