smaller tcp_connection_t
[monky] / src / libtcp-portmon.h
1 /* -------------------------------------------------------------------------
2  * libtcp-portmon.h:  tcp port monitoring library.               
3  *
4  * Copyright (C) 2005  Philip Kovacs kovacsp3@comcast.net
5  *
6  * $Id$
7  * 
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  * --------------------------------------------------------------------------- */
22
23 #ifndef LIBTCP_PORTMON_H
24 #define LIBTCP_PORTMON_H
25
26 #include <math.h>
27 #include <netdb.h>
28 #include <netinet/in.h>
29 #include <netinet/tcp.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <sys/socket.h>
34 #include <arpa/inet.h>
35 #include "hash.h"
36
37 /* ------------------------------------------------------------------------------------------------
38  * Each port monitor contains a connection hash whose contents changes dynamically as the monitor 
39  * is presented with connections on each update cycle.   This implementation maintains the health
40  * of this hash by enforcing several rules.  First, the hash cannot contain more items than the
41  * TCP_CONNECTION_HASH_MAX_LOAD_RATIO permits.  For example, a 512 element hash with a max load of 
42  * 0.5 cannot contain more than 256 connections.  Additional connections are ignored by the monitor.
43  * The load factor of 0.5 is low enough to keep the hash running at near O(1) performanace at all 
44  * times.  As elements are removed from the hash, the hash slots are tagged vacated, as required 
45  * by open address hashing.  The vacated tags are essential as they enable the hash to find elements
46  * for which there were collisions during insert (requiring additional probing for an open slot).
47  * The problem with vacated slots (even though they are reused) is that, as they increase in number,
48  * esp. past about 1/4 of all slots, the average number of probes the hash has to perform increases
49  * from O(1) on average to O(n) worst case. To keep the hash healthy, we simply rebuild it when the
50  * percentage of vacated slots gets too high (above TCP_CONNECTION_HASH_MAX_VACATED_RATIO).  
51  * Rebuilding the hash takes O(n) on the number of elements, but it well worth it as it keeps the
52  * hash running at an average access time of O(1).
53  * ------------------------------------------------------------------------------------------------*/
54
55 #define TCP_CONNECTION_HASH_SIZE_DEFAULT 512            /* connection hash size default -- must be a power of two */
56 #define TCP_CONNECTION_HASH_SIZE_MAX 65536              /* connection hash size maximum -- must be a power of two */
57 #define TCP_CONNECTION_HASH_MAX_LOAD_RATIO 0.5          /* disallow inserts after this load ratio is exceeded */
58 #define TCP_CONNECIION_HASH_MAX_VACATED_RATIO 0.25      /* rebalance hash after this ratio of vacated slots is exceeded */ 
59 #define TCP_CONNECIION_STARTING_AGE 1                   /* connection deleted if unseen again after this # of refreshes */
60
61 /* ----------------------------------------------------------------------------------------
62  * The tcp port monitor collection also contains a hash to track the monitors it contains.
63  * This hash, unlike the connection hash describes above, is not very dynamic.  Clients of
64  * this library typically create a fixed number of monitors and let them run until program 
65  * termination.  For this reason, I haven't included any hash rebuilding code as is done
66  * above.  You may store up to TCP_MONITOR_HASH_SIZE_MAX monitors in this hash, but you
67  * should remember that keeping the load low (e.g. 0.5) keeps the monitor lookups at O(1).  
68  * ----------------------------------------------------------------------------------------*/
69
70 #define TCP_MONITOR_HASH_SIZE_DEFAULT 32                /* monitor hash size default -- must be a power of two */
71 #define TCP_MONITOR_HASH_SIZE_MAX 512                   /* monitor hash size maximum -- must be a power of two */
72 #define TCP_MONITOR_HASH_MAX_LOAD_RATIO 0.5             /* disallow new monitors after this load ratio is exceeded */
73
74 /* -------------------------------------------------------------------
75  * IMPLEMENTATION INTERFACE
76  *
77  * Implementation-specific interface begins here.  Clients should not 
78  * manipulate these structures directly, nor call the defined helper 
79  * functions.  Use the "Client interface" functions defined at bottom.
80  * ------------------------------------------------------------------- */
81
82 /* The inventory of peekable items within the port monitor. */
83 enum tcp_port_monitor_peekables { COUNT=0, REMOTEIP, REMOTEHOST, REMOTEPORT, LOCALIP, LOCALHOST, LOCALPORT, LOCALSERVICE };
84
85 /* ------------------------------------------------------------------------
86  * A single tcp connection 
87  *
88  * The age variable provides the mechanism for removing connections if they
89  * are not seen again in subsequent update cycles.
90  * ------------------------------------------------------------------------ */
91 typedef struct _tcp_connection_t {
92         in_addr_t local_addr;
93         in_port_t local_port;
94         in_addr_t remote_addr;
95         in_port_t remote_port;
96         int age;
97 } tcp_connection_t;
98
99 /* ------------------------------------------------------------------------
100  * A tcp connection node/list
101  *
102  * Connections within each monitor are stored in a double-linked list.
103  * ------------------------------------------------------------------------ */
104 typedef struct _tcp_connection_node_t {
105         tcp_connection_t connection;
106         struct _tcp_connection_node_t * p_prev;
107         struct _tcp_connection_node_t * p_next;
108 } tcp_connection_node_t;
109
110 typedef struct _tcp_connection_list_t {
111         tcp_connection_node_t * p_head;
112         tcp_connection_node_t * p_tail;
113 } tcp_connection_list_t;
114
115 /* --------------
116  * A port monitor 
117  * -------------- */
118 typedef struct _tcp_port_monitor_t {
119         in_port_t port_range_begin;
120         in_port_t port_range_end;               /* begin = end to monitor a single port */
121         tcp_connection_list_t connection_list;  /* list of connections for this monitor */
122         hash_table_t hash;                      /* hash table contains pointers into monitor's connection list */
123         tcp_connection_t **p_peek;              /* array of connection pointers for O(1) peeking by index */ 
124 } tcp_port_monitor_t;
125
126 /* -----------------------------------------------------------------------------
127  * Open-addressed hash implementation requires that we supply two hash functions
128  * and a match function to compare two hash elements for identity.
129  * ----------------------------------------------------------------------------- */
130
131 /* --------------------------------------------------
132  * Functions to hash the connections within a monitor
133  * --------------------------------------------------*/
134
135 /* First connection hash function */
136 int connection_hash_function_1( const void * /* p_data */ );
137
138 /* Second connection hash function */
139 int connection_hash_function_2( const void * /* p_data */ );
140
141 /* Connection match function returns non-zero if hash elements are identical. */
142 int connection_match_function( const void * /* p_data1 */, const void * /* p_data2 */ );
143
144 /* --------------------------------------------------
145  * Functions to hash the monitors within a collection
146  * --------------------------------------------------*/
147
148 /* First monitor hash function */
149 int monitor_hash_function_1( const void * /* p_data */ );
150
151 /* Second monitor hash function */
152 int monitor_hash_function_2( const void * /* p_data */ );
153
154 /* Monitor match function returns non-zero if hash elements are identical. */
155 int monitor_match_function( const void * /* p_data1 */, const void * /* p_data2 */ );
156
157 /* ------------------------
158  * A port monitor node/list 
159  * ------------------------ */
160 typedef struct _tcp_port_monitor_node_t {
161         tcp_port_monitor_t * p_monitor;
162         struct _tcp_port_monitor_node_t *p_next;
163 } tcp_port_monitor_node_t;
164
165 typedef struct __tcp_port_monitor_list_t {
166         tcp_port_monitor_node_t * p_head;
167         tcp_port_monitor_node_t * p_tail;
168 } tcp_port_monitor_list_t;
169
170 /* ---------------------------------------
171  * A port monitor utility function typedef
172  * ---------------------------------------*/ 
173 typedef void (*tcp_port_monitor_function_ptr_t)( tcp_port_monitor_t * /* p_monitor */, void * /* p_void */ );
174
175 /* ---------------------------------------------------------------------------
176  * Port monitor utility functions implementing tcp_port_monitor_function_ptr_t
177  * ---------------------------------------------------------------------------*/
178 void destroy_tcp_port_monitor(
179         tcp_port_monitor_t *                    /* p_monitor */,
180         void *                                  /* p_void (use NULL for this function) */
181         );
182
183 void age_tcp_port_monitor(
184         tcp_port_monitor_t *                    /* p_monitor */,
185         void *                                  /* p_void (use NULL for this function) */
186         );
187
188 void maintain_tcp_port_monitor_hash(
189         tcp_port_monitor_t *                    /* p_monitor */,
190         void *                                  /* p_void (use NULL for this function) */
191         );
192
193 void rebuild_tcp_port_monitor_peek_table(
194         tcp_port_monitor_t *                    /* p_monitor */,
195         void *                                  /* p_void (use NULL for this function) */
196         );
197
198 void show_connection_to_tcp_port_monitor(
199         tcp_port_monitor_t *                    /* p_monitor */,
200         void *                                  /* p_connection (client should cast) */
201         );
202
203 /* -----------------------------
204  * A tcp port monitor collection
205  * -----------------------------*/
206 typedef struct _tcp_port_monitor_collection_t {
207         tcp_port_monitor_list_t monitor_list;   /* list of monitors for this collection */
208         hash_table_t hash;                      /* hash table contains pointers into collection's monitor list */
209 } tcp_port_monitor_collection_t;
210
211 /* ---------------------------------------------------------------------------------------
212  * Apply a tcp_port_monitor_function_ptr_t function to each port monitor in the collection. 
213  * ---------------------------------------------------------------------------------------*/
214 void for_each_tcp_port_monitor_in_collection(
215         tcp_port_monitor_collection_t *         /* p_collection */,
216         tcp_port_monitor_function_ptr_t         /* p_function */,
217         void *                                  /* p_function_args (for user arguments) */
218         );
219
220 /* ----------------------------------------------------------------------------------------
221  * Calculate an efficient hash size based on the desired number of elements and load factor.
222  * ---------------------------------------------------------------------------------------- */
223 int calc_efficient_hash_size(
224         int                                     /* min_elements, the minimum number of elements to store */,
225         int                                     /* max_hash_size, the maximum permissible hash size */,
226         double                                  /* max_load_factor, the fractional load we wish not to exceed, e.g. 0.5 */
227         );
228
229 /* ----------------------------------------------------------------------
230  * CLIENT INTERFACE 
231  *
232  * Clients should call only those functions below this line.
233  * ---------------------------------------------------------------------- */
234
235 /* struct to hold monitor creation arguments */
236 typedef struct _tcp_port_monitor_args_t {
237         int     min_port_monitor_connections;   /* monitor must support tracking at least this many connections */
238 } tcp_port_monitor_args_t;
239
240
241 /* struct to hold collection creation arguments */
242 typedef struct _tcp_port_monitor_collection_args_t {
243         int     min_port_monitors;              /* collection must support creation of at least this many monitors */
244 } tcp_port_monitor_collection_args_t; 
245
246 /* ----------------------------------
247  * Client operations on port monitors
248  * ---------------------------------- */
249
250 /* Clients should first try to "find_tcp_port_monitor" before creating one
251    so that there are no redundant monitors. */
252 tcp_port_monitor_t * create_tcp_port_monitor(
253         in_port_t                               /* port_range_begin */, 
254         in_port_t                               /* port_range_end */,
255         tcp_port_monitor_args_t *               /* p_creation_args, NULL ok for library defaults */
256         );
257
258 /* Clients use this function to get connection data from the indicated port monitor.
259    The requested monitor value is copied into a client-supplied char buffer. 
260    Returns 0 on success, -1 otherwise. */
261 int peek_tcp_port_monitor(
262         tcp_port_monitor_t *                    /* p_monitor */,
263         int                                     /* item, ( item of interest, from tcp_port_monitor_peekables enum ) */,
264         int                                     /* connection_index, ( 0 to number of connections in monitor - 1 )*/,
265         char *                                  /* p_buffer, buffer to receive requested value */,
266         size_t                                  /* buffer_size, size of p_buffer */
267         );
268
269 /* --------------------------------
270  * Client operations on collections
271  * -------------------------------- */
272
273 /* Create a monitor collection.  Do this one first. */
274 tcp_port_monitor_collection_t * create_tcp_port_monitor_collection(
275         tcp_port_monitor_collection_args_t *    /* p_creation_args, NULL ok for library defaults */
276         );
277
278 /* Destroy the monitor collection (and everything it contains).  Do this one last. */
279 void destroy_tcp_port_monitor_collection( 
280         tcp_port_monitor_collection_t *         /* p_collection */ 
281         );
282
283 /* Updates the tcp statitics for all monitors within a collection */
284 void update_tcp_port_monitor_collection(
285         tcp_port_monitor_collection_t *         /* p_collection */
286         );
287
288 /* After clients create a monitor, use this to add it to the collection. 
289    Returns 0 on success, -1 otherwise. */
290 int insert_tcp_port_monitor_into_collection( 
291         tcp_port_monitor_collection_t *         /* p_collection */, 
292         tcp_port_monitor_t *                    /* p_monitor */ 
293         );
294
295 /* Clients need a way to find monitors */
296 tcp_port_monitor_t * find_tcp_port_monitor( 
297         tcp_port_monitor_collection_t *         /* p_collection */, 
298         in_port_t                               /* port_range_begin */, 
299         in_port_t                               /* port_range_end */ 
300         );
301
302 #endif