const several ptr args
[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_CONNECTION_HASH_MAX_VACATED_RATIO 0.25      /* rebalance hash after this ratio of vacated slots is exceeded */ 
59 #define TCP_CONNECTION_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  * Copy a connection
101  *
102  * Returns 0 on success, -1 otherwise
103  * ----------------------------------*/
104 int copy_tcp_connection( 
105         tcp_connection_t *                      /* p_dest_connection */,
106         const tcp_connection_t *                /* p_source_connection */
107         );
108
109 /* ------------------------------------------------------------------------
110  * A tcp connection node/list
111  *
112  * Connections within each monitor are stored in a double-linked list.
113  * ------------------------------------------------------------------------ */
114 typedef struct _tcp_connection_node_t {
115         tcp_connection_t connection;
116         struct _tcp_connection_node_t * p_prev;
117         struct _tcp_connection_node_t * p_next;
118 } tcp_connection_node_t;
119
120 typedef struct _tcp_connection_list_t {
121         tcp_connection_node_t * p_head;
122         tcp_connection_node_t * p_tail;
123 } tcp_connection_list_t;
124
125 /* --------------
126  * A port monitor 
127  * -------------- */
128 typedef struct _tcp_port_monitor_t {
129         in_port_t port_range_begin;
130         in_port_t port_range_end;               /* begin = end to monitor a single port */
131         tcp_connection_list_t connection_list;  /* list of connections for this monitor */
132         hash_table_t hash;                      /* hash table contains pointers into monitor's connection list */
133         tcp_connection_t **p_peek;              /* array of connection pointers for O(1) peeking by index */ 
134 } tcp_port_monitor_t;
135
136 /* -----------------------------------------------------------------------------
137  * Open-addressed hash implementation requires that we supply two hash functions
138  * and a match function to compare two hash elements for identity.
139  * ----------------------------------------------------------------------------- */
140
141 /* --------------------------------------------------
142  * Functions to hash the connections within a monitor
143  * --------------------------------------------------*/
144
145 /* First connection hash function */
146 int connection_hash_function_1( const void * /* p_data */ );
147
148 /* Second connection hash function */
149 int connection_hash_function_2( const void * /* p_data */ );
150
151 /* Connection match function returns non-zero if hash elements are identical. */
152 int connection_match_function( const void * /* p_data1 */, const void * /* p_data2 */ );
153
154 /* --------------------------------------------------
155  * Functions to hash the monitors within a collection
156  * --------------------------------------------------*/
157
158 /* First monitor hash function */
159 int monitor_hash_function_1( const void * /* p_data */ );
160
161 /* Second monitor hash function */
162 int monitor_hash_function_2( const void * /* p_data */ );
163
164 /* Monitor match function returns non-zero if hash elements are identical. */
165 int monitor_match_function( const void * /* p_data1 */, const void * /* p_data2 */ );
166
167 /* ------------------------
168  * A port monitor node/list 
169  * ------------------------ */
170 typedef struct _tcp_port_monitor_node_t {
171         tcp_port_monitor_t * p_monitor;
172         struct _tcp_port_monitor_node_t *p_next;
173 } tcp_port_monitor_node_t;
174
175 typedef struct __tcp_port_monitor_list_t {
176         tcp_port_monitor_node_t * p_head;
177         tcp_port_monitor_node_t * p_tail;
178 } tcp_port_monitor_list_t;
179
180 /* ---------------------------------------
181  * A port monitor utility function typedef
182  * ---------------------------------------*/ 
183 typedef void (*tcp_port_monitor_function_ptr_t)( tcp_port_monitor_t * /* p_monitor */, void * /* p_void */ );
184
185 /* ---------------------------------------------------------------------------
186  * Port monitor utility functions implementing tcp_port_monitor_function_ptr_t
187  * ---------------------------------------------------------------------------*/
188 void destroy_tcp_port_monitor(
189         tcp_port_monitor_t *                    /* p_monitor */,
190         void *                                  /* p_void (use NULL for this function) */
191         );
192
193 void age_tcp_port_monitor(
194         tcp_port_monitor_t *                    /* p_monitor */,
195         void *                                  /* p_void (use NULL for this function) */
196         );
197
198 void maintain_tcp_port_monitor_hash(
199         tcp_port_monitor_t *                    /* p_monitor */,
200         void *                                  /* p_void (use NULL for this function) */
201         );
202
203 void rebuild_tcp_port_monitor_peek_table(
204         tcp_port_monitor_t *                    /* p_monitor */,
205         void *                                  /* p_void (use NULL for this function) */
206         );
207
208 void show_connection_to_tcp_port_monitor(
209         tcp_port_monitor_t *                    /* p_monitor */,
210         void *                                  /* p_connection (client should cast) */
211         );
212
213 /* -----------------------------
214  * A tcp port monitor collection
215  * -----------------------------*/
216 typedef struct _tcp_port_monitor_collection_t {
217         tcp_port_monitor_list_t monitor_list;   /* list of monitors for this collection */
218         hash_table_t hash;                      /* hash table contains pointers into collection's monitor list */
219 } tcp_port_monitor_collection_t;
220
221 /* ---------------------------------------------------------------------------------------
222  * Apply a tcp_port_monitor_function_ptr_t function to each port monitor in the collection. 
223  * ---------------------------------------------------------------------------------------*/
224 void for_each_tcp_port_monitor_in_collection(
225         tcp_port_monitor_collection_t *         /* p_collection */,
226         tcp_port_monitor_function_ptr_t         /* p_function */,
227         void *                                  /* p_function_args (for user arguments) */
228         );
229
230 /* ----------------------------------------------------------------------------------------
231  * Calculate an efficient hash size based on the desired number of elements and load factor.
232  * ---------------------------------------------------------------------------------------- */
233 int calc_efficient_hash_size(
234         int                                     /* min_elements, the minimum number of elements to store */,
235         int                                     /* max_hash_size, the maximum permissible hash size */,
236         double                                  /* max_load_factor, the fractional load we wish not to exceed, e.g. 0.5 */
237         );
238
239 /* ----------------------------------------------------------------------
240  * CLIENT INTERFACE 
241  *
242  * Clients should call only those functions below this line.
243  * ---------------------------------------------------------------------- */
244
245 /* struct to hold monitor creation arguments */
246 typedef struct _tcp_port_monitor_args_t {
247         int     min_port_monitor_connections;   /* monitor must support tracking at least this many connections */
248 } tcp_port_monitor_args_t;
249
250
251 /* struct to hold collection creation arguments */
252 typedef struct _tcp_port_monitor_collection_args_t {
253         int     min_port_monitors;              /* collection must support creation of at least this many monitors */
254 } tcp_port_monitor_collection_args_t; 
255
256 /* ----------------------------------
257  * Client operations on port monitors
258  * ---------------------------------- */
259
260 /* Clients should first try to "find_tcp_port_monitor" before creating one
261    so that there are no redundant monitors. */
262 tcp_port_monitor_t * create_tcp_port_monitor(
263         in_port_t                               /* port_range_begin */, 
264         in_port_t                               /* port_range_end */,
265         tcp_port_monitor_args_t *               /* p_creation_args, NULL ok for library defaults */
266         );
267
268 /* Clients use this function to get connection data from the indicated port monitor.
269    The requested monitor value is copied into a client-supplied char buffer. 
270    Returns 0 on success, -1 otherwise. */
271 int peek_tcp_port_monitor(
272         const tcp_port_monitor_t *              /* p_monitor */,
273         int                                     /* item, ( item of interest, from tcp_port_monitor_peekables enum ) */,
274         int                                     /* connection_index, ( 0 to number of connections in monitor - 1 )*/,
275         char *                                  /* p_buffer, buffer to receive requested value */,
276         size_t                                  /* buffer_size, size of p_buffer */
277         );
278
279 /* --------------------------------
280  * Client operations on collections
281  * -------------------------------- */
282
283 /* Create a monitor collection.  Do this one first. */
284 tcp_port_monitor_collection_t * create_tcp_port_monitor_collection(
285         tcp_port_monitor_collection_args_t *    /* p_creation_args, NULL ok for library defaults */
286         );
287
288 /* Destroy the monitor collection (and everything it contains).  Do this one last. */
289 void destroy_tcp_port_monitor_collection( 
290         tcp_port_monitor_collection_t *         /* p_collection */ 
291         );
292
293 /* Updates the tcp statitics for all monitors within a collection */
294 void update_tcp_port_monitor_collection(
295         tcp_port_monitor_collection_t *         /* p_collection */
296         );
297
298 /* After clients create a monitor, use this to add it to the collection. 
299    Returns 0 on success, -1 otherwise. */
300 int insert_tcp_port_monitor_into_collection( 
301         tcp_port_monitor_collection_t *         /* p_collection */, 
302         tcp_port_monitor_t *                    /* p_monitor */ 
303         );
304
305 /* Clients need a way to find monitors */
306 tcp_port_monitor_t * find_tcp_port_monitor( 
307         const tcp_port_monitor_collection_t *   /* p_collection */, 
308         in_port_t                               /* port_range_begin */, 
309         in_port_t                               /* port_range_end */ 
310         );
311
312 #endif