727a11a2794d9d424e80faca844ca08e80fae002
[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 256 element hash with a max load of 
42  * 0.5 cannot contain more than 128 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 65535              /* 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 load governors or hash rebuilding
66  * steps as is done above.  You may store up to TCP_MONITOR_HASH_SIZE monitors in this hash,
67  * but you _should_ remember that keeping the load low (e.g. max of 0.5) keeps the monitor
68  * lookups at O(1).  
69  * ----------------------------------------------------------------------------------------*/
70
71 #define TCP_MONITOR_HASH_SIZE_DEFAULT 32                /* monitor hash size default -- must be a power of two */
72 #define TCP_MONITOR_HASH_SIZE_MAX 512                   /* monitor hash size maximum -- must be a power of two */
73 #define TCP_MONITOR_HASH_MAX_LOAD_RATIO 0.5             /* disallow new monitors after this load ratio is exceeded */
74
75 /* -------------------------------------------------------------------
76  * IMPLEMENTATION INTERFACE
77  *
78  * Implementation-specific interface begins here.  Clients should not 
79  * manipulate these structures directly, nor call the defined helper 
80  * functions.  Use the "Client interface" functions defined at bottom.
81  * ------------------------------------------------------------------- */
82
83 /* The inventory of peekable items within the port monitor. */
84 enum tcp_port_monitor_peekables { COUNT=0, REMOTEIP, REMOTEHOST, REMOTEPORT, LOCALIP, LOCALHOST, LOCALPORT, LOCALSERVICE };
85
86 /* ------------------------------------------------------------------------
87  * A single tcp connection 
88  *
89  * The age variable provides the mechanism for removing connections if they
90  * are not seen again in subsequent update cycles.
91  * ------------------------------------------------------------------------ */
92 typedef struct _tcp_connection_t {
93         in_addr_t local_addr;
94         in_port_t local_port;
95         in_addr_t remote_addr;
96         in_port_t remote_port;
97         unsigned int uid;
98         unsigned int inode;
99         int age;
100 } tcp_connection_t;
101
102 /* ------------------------------------------------------------------------
103  * A tcp connection node/list
104  *
105  * Connections within each monitor are stored in a double-linked list.
106  * ------------------------------------------------------------------------ */
107 typedef struct _tcp_connection_node_t {
108         tcp_connection_t connection;
109         struct _tcp_connection_node_t * p_prev;
110         struct _tcp_connection_node_t * p_next;
111 } tcp_connection_node_t;
112
113 typedef struct _tcp_connection_list_t {
114         tcp_connection_node_t * p_head;
115         tcp_connection_node_t * p_tail;
116 } tcp_connection_list_t;
117
118 /* --------------
119  * A port monitor 
120  * -------------- */
121 typedef struct _tcp_port_monitor_t {
122         in_port_t port_range_begin;
123         in_port_t port_range_end;               /* begin = end to monitor a single port */
124         tcp_connection_list_t connection_list;  /* list of connections for this monitor */
125         hash_table_t hash;                      /* hash table contains pointers into monitor's connection list */
126         tcp_connection_t **p_peek;              /* array of connection pointers for O(1) peeking by index */ 
127 } tcp_port_monitor_t;
128
129 /* -----------------------------------------------------------------------------
130  * Open-addressed hash implementation requires that we supply two hash functions
131  * and a match function to compare two hash elements for identity.
132  * ----------------------------------------------------------------------------- */
133
134 /* --------------------------------------------------
135  * Functions to hash the connections within a monitor
136  * --------------------------------------------------*/
137
138 /* First connection hash function */
139 int connection_hash_function_1( const void * /* p_data */ );
140
141 /* Second connection hash function */
142 int connection_hash_function_2( const void * /* p_data */ );
143
144 /* Connection match function returns non-zero if hash elements are identical. */
145 int connection_match_function( const void * /* p_data1 */, const void * /* p_data2 */ );
146
147 /* --------------------------------------------------
148  * Functions to hash the monitors within a collection
149  * --------------------------------------------------*/
150
151 /* First monitor hash function */
152 int monitor_hash_function_1( const void * /* p_data */ );
153
154 /* Second monitor hash function */
155 int monitor_hash_function_2( const void * /* p_data */ );
156
157 /* Monitor match function returns non-zero if hash elements are identical. */
158 int monitor_match_function( const void * /* p_data1 */, const void * /* p_data2 */ );
159
160 /* ------------------------
161  * A port monitor node/list 
162  * ------------------------ */
163 typedef struct _tcp_port_monitor_node_t {
164         tcp_port_monitor_t * p_monitor;
165         struct _tcp_port_monitor_node_t *p_next;
166 } tcp_port_monitor_node_t;
167
168 typedef struct __tcp_port_monitor_list_t {
169         tcp_port_monitor_node_t * p_head;
170         tcp_port_monitor_node_t * p_tail;
171 } tcp_port_monitor_list_t;
172
173 /* ---------------------------------------
174  * A port monitor utility function typedef
175  * ---------------------------------------*/ 
176 typedef void (*tcp_port_monitor_function_ptr_t)( tcp_port_monitor_t * /* p_monitor */, void * /* p_void */ );
177
178 /* ---------------------------------------------------------------------------
179  * Port monitor utility functions implementing tcp_port_monitor_function_ptr_t
180  * ---------------------------------------------------------------------------*/
181 void destroy_tcp_port_monitor(
182         tcp_port_monitor_t *                    /* p_monitor */,
183         void *                                  /* p_void (use NULL for this function) */
184         );
185
186 void age_tcp_port_monitor(
187         tcp_port_monitor_t *                    /* p_monitor */,
188         void *                                  /* p_void (use NULL for this function) */
189         );
190
191 void maintain_tcp_port_monitor_hash(
192         tcp_port_monitor_t *                    /* p_monitor */,
193         void *                                  /* p_void (use NULL for this function) */
194         );
195
196 void rebuild_tcp_port_monitor_peek_table(
197         tcp_port_monitor_t *                    /* p_monitor */,
198         void *                                  /* p_void (use NULL for this function) */
199         );
200
201 void show_connection_to_tcp_port_monitor(
202         tcp_port_monitor_t *                    /* p_monitor */,
203         void *                                  /* p_connection (client should cast) */
204         );
205
206 /* -----------------------------
207  * A tcp port monitor collection
208  * -----------------------------*/
209 typedef struct _tcp_port_monitor_collection_t {
210         tcp_port_monitor_list_t monitor_list;   /* list of monitors for this collection */
211         hash_table_t hash;                      /* hash table contains pointers into collection's monitor list */
212 } tcp_port_monitor_collection_t;
213
214 /* ---------------------------------------------------------------------------------------
215  * Apply a tcp_port_monitor_function_ptr_t function to each port monitor in the collection. 
216  * ---------------------------------------------------------------------------------------*/
217 void for_each_tcp_port_monitor_in_collection(
218         tcp_port_monitor_collection_t *         /* p_collection */,
219         tcp_port_monitor_function_ptr_t         /* p_function */,
220         void *                                  /* p_function_args (for user arguments) */
221         );
222
223 /* ----------------------------------------------------------------------------------------
224  * Calculate an efficient hash size based on the desired number of elements and load factor.
225  * ---------------------------------------------------------------------------------------- */
226 int calc_efficient_hash_size(
227         int                                     /* min_elements, the minimum number of elements to store */,
228         int                                     /* max_hash_size, the maximum permissible hash size */,
229         double                                  /* max_load_factor, the fractional load we wish not to exceed, e.g. 0.5 */
230         );
231
232 /* ----------------------------------------------------------------------
233  * CLIENT INTERFACE 
234  *
235  * Clients should call only those functions below this line.
236  * ---------------------------------------------------------------------- */
237
238 /* struct to hold monitor creation arguments */
239 typedef struct _tcp_port_monitor_args_t {
240         int     min_port_monitor_connections;   /* monitor must support tracking at least this many connections */
241 } tcp_port_monitor_args_t;
242
243
244 /* struct to hold collection creation arguments */
245 typedef struct _tcp_port_monitor_collection_args_t {
246         int     min_port_monitors;              /* collection must support creation of at least this many monitors */
247 } tcp_port_monitor_collection_args_t; 
248
249 /* ----------------------------------
250  * Client operations on port monitors
251  * ---------------------------------- */
252
253 /* Clients should first try to "find_tcp_port_monitor" before creating one
254    so that there are no redundant monitors. */
255 tcp_port_monitor_t * create_tcp_port_monitor(
256         in_port_t                               /* port_range_begin */, 
257         in_port_t                               /* port_range_end */,
258         tcp_port_monitor_args_t *               /* p_creation_args, NULL ok for library defaults */
259         );
260
261 /* Clients use this function to get connection data from the indicated port monitor.
262    The requested monitor value is copied into a client-supplied char buffer. 
263    Returns 0 on success, -1 otherwise. */
264 int peek_tcp_port_monitor(
265         tcp_port_monitor_t *                    /* p_monitor */,
266         int                                     /* item, ( item of interest, from tcp_port_monitor_peekables enum ) */,
267         int                                     /* connection_index, ( 0 to number of connections in monitor - 1 )*/,
268         char *                                  /* p_buffer, buffer to receive requested value */,
269         size_t                                  /* buffer_size, size of p_buffer */
270         );
271
272 /* --------------------------------
273  * Client operations on collections
274  * -------------------------------- */
275
276 /* Create a monitor collection.  Do this one first. */
277 tcp_port_monitor_collection_t * create_tcp_port_monitor_collection(
278         tcp_port_monitor_collection_args_t *    /* p_creation_args, NULL ok for library defaults */
279         );
280
281 /* Destroy the monitor collection (and everything it contains).  Do this one last. */
282 void destroy_tcp_port_monitor_collection( 
283         tcp_port_monitor_collection_t *         /* p_collection */ 
284         );
285
286 /* Updates the tcp statitics for all monitors within a collection */
287 void update_tcp_port_monitor_collection(
288         tcp_port_monitor_collection_t *         /* p_collection */
289         );
290
291 /* After clients create a monitor, use this to add it to the collection. 
292    Returns 0 on success, -1 otherwise. */
293 int insert_tcp_port_monitor_into_collection( 
294         tcp_port_monitor_collection_t *         /* p_collection */, 
295         tcp_port_monitor_t *                    /* p_monitor */ 
296         );
297
298 /* Clients need a way to find monitors */
299 tcp_port_monitor_t * find_tcp_port_monitor( 
300         tcp_port_monitor_collection_t *         /* p_collection */, 
301         in_port_t                               /* port_range_begin */, 
302         in_port_t                               /* port_range_end */ 
303         );
304
305 #endif