cosmetics in size field of ipsec pool --status command
[strongswan.git] / src / charon / plugins / sql / pool.c
1 /*
2 * Copyright (C) 2008 Martin Willi
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 *
15 * $Id$
16 */
17
18 #define _GNU_SOURCE
19 #include <getopt.h>
20 #include <unistd.h>
21 #include <stdio.h>
22 #include <time.h>
23
24 #include <debug.h>
25 #include <library.h>
26 #include <utils/host.h>
27
28 /**
29 * global database handle
30 */
31 database_t *db;
32
33 /**
34 * --start/--end addresses of various subcommands
35 */
36 host_t *start = NULL, *end = NULL;
37
38 /**
39 * create a host from a blob
40 */
41 static host_t *host_create_from_blob(chunk_t blob)
42 {
43 return host_create_from_chunk(blob.len == 4 ? AF_INET : AF_INET6, blob, 0);
44 }
45
46 /**
47 * calculate the size of a pool using start and end address chunk
48 */
49 static u_int get_pool_size(chunk_t start, chunk_t end)
50 {
51 u_int *start_ptr, *end_ptr;
52
53 if (start.len < sizeof(u_int) || end.len < sizeof(u_int))
54 {
55 return 0;
56 }
57 start_ptr = (u_int*)(start.ptr + start.len - sizeof(u_int));
58 end_ptr = (u_int*)(end.ptr + end.len - sizeof(u_int));
59 return ntohl(*end_ptr) - ntohl(*start_ptr) + 1;
60 }
61
62 /**
63 * print usage info
64 */
65 static void usage(void)
66 {
67 printf("\
68 Usage:\n\
69 ipsec pool --status|--add|--del|--resize|--purge [options]\n\
70 \n\
71 ipsec pool --status\n\
72 Show a list of installed pools with statistics.\n\
73 \n\
74 ipsec pool --add <name> --start <start> --end <end> [--timeout <timeout>]\n\
75 Add a new pool to the database.\n\
76 name: Name of the pool, as used in ipsec.conf rightsourceip=%%name\n\
77 start: Start address of the pool\n\
78 end: End address of the pool\n\
79 timeout: Lease time in hours, 0 for static leases\n\
80 \n\
81 ipsec pool --del <name>\n\
82 Delete a pool from the database.\n\
83 name: Name of the pool to delete\n\
84 \n\
85 ipsec pool --resize <name> --end <end>\n\
86 Grow or shrink an existing pool.\n\
87 name: Name of the pool to resize\n\
88 end: New end address for the pool\n\
89 \n\
90 ipsec pool --leases <name> [--filter <filter>] [--utc]\n\
91 Show lease information using filters:\n\
92 name: Name of the pool to show leases from\n\
93 filter: Filter string - unimplemented\n\
94 utc: Show times in UTC instead of local time\n\
95 \n\
96 ipsec pool --purge <name>\n\
97 Delete expired leases of a pool:\n\
98 name: Name of the pool to purge\n\
99 \n");
100 exit(0);
101 }
102
103 /**
104 * ipsec pool --status - show pool overview
105 */
106 static void status(void)
107 {
108 enumerator_t *pool, *lease;
109 bool found = FALSE;
110
111 pool = db->query(db, "SELECT id, name, start, end, timeout FROM pools",
112 DB_INT, DB_TEXT, DB_BLOB, DB_BLOB, DB_UINT);
113 if (pool)
114 {
115 char *name;
116 chunk_t start_chunk, end_chunk;
117 host_t *start, *end;
118 u_int id, timeout, online = 0, used = 0, size = 0;
119
120 while (pool->enumerate(pool, &id, &name,
121 &start_chunk, &end_chunk, &timeout))
122 {
123 if (!found)
124 {
125 printf("%8s %15s %15s %8s %6s %11s %11s\n",
126 "name", "start", "end", "timeout", "size", "online", "leases");
127 found = TRUE;
128 }
129
130 start = host_create_from_blob(start_chunk);
131 end = host_create_from_blob(end_chunk);
132 size = get_pool_size(start_chunk, end_chunk);
133 printf("%8s %15H %15H ", name, start, end);
134 if (timeout)
135 {
136 printf("%7dh ", timeout/3600);
137 }
138 else
139 {
140 printf("%8s ", "static");
141 }
142 printf("%6d ", size);
143 /* get number of online hosts */
144 lease = db->query(db, "SELECT COUNT(*) FROM leases "
145 "WHERE pool = ? AND released IS NULL",
146 DB_UINT, id, DB_INT);
147 if (lease)
148 {
149 lease->enumerate(lease, &online);
150 lease->destroy(lease);
151 }
152 printf("%5d (%2d%%) ", online, online*100/size);
153 /* get number of online or valid lieases */
154 lease = db->query(db, "SELECT COUNT(*) FROM leases JOIN pools "
155 "ON leases.pool = pools.id "
156 "WHERE pools.id = ? "
157 "AND (released IS NULL OR released > ? - timeout) ",
158 DB_UINT, id, DB_UINT, time(NULL), DB_UINT);
159 if (lease)
160 {
161 lease->enumerate(lease, &used);
162 lease->destroy(lease);
163 }
164 printf("%5d (%2d%%) ", used, used*100/size);
165
166 printf("\n");
167 DESTROY_IF(start);
168 DESTROY_IF(end);
169 }
170 pool->destroy(pool);
171 }
172 if (!found)
173 {
174 printf("no pools found.\n");
175 }
176 exit(0);
177 }
178
179 /**
180 * ipsec pool --add - add a new pool
181 */
182 static void add(char *name, host_t *start, host_t *end, int timeout)
183 {
184 chunk_t start_addr, end_addr;
185
186 start_addr = start->get_address(start);
187 end_addr = end->get_address(end);
188
189 if (start_addr.len != end_addr.len ||
190 memcmp(start_addr.ptr, end_addr.ptr, start_addr.len) > 0)
191 {
192 fprintf(stderr, "invalid start/end pair specified.\n");
193 exit(-1);
194 }
195 if (db->execute(db, NULL,
196 "INSERT INTO pools (name, start, end, next, timeout) "
197 "VALUES (?, ?, ?, ?, ?)",
198 DB_TEXT, name, DB_BLOB, start_addr,
199 DB_BLOB, end_addr, DB_BLOB, start_addr,
200 DB_INT, timeout*3600) != 1)
201 {
202 fprintf(stderr, "creating pool failed.\n");
203 exit(-1);
204 }
205 exit(0);
206 }
207
208 /**
209 * ipsec pool --del - delete a pool
210 */
211 static void del(char *name)
212 {
213 enumerator_t *query;
214 u_int id;
215 bool found = FALSE;
216
217 query = db->query(db, "SELECT id FROM pools WHERE name = ?",
218 DB_TEXT, name, DB_UINT);
219 if (!query)
220 {
221 fprintf(stderr, "deleting pool failed.\n");
222 exit(-1);
223 }
224 while (query->enumerate(query, &id))
225 {
226 found = TRUE;
227 if (db->execute(db, NULL,
228 "DELETE FROM pools WHERE id = ?", DB_UINT, id) != 1 ||
229 db->execute(db, NULL,
230 "DELETE FROM leases WHERE pool = ?", DB_UINT, id) < 0)
231 {
232 fprintf(stderr, "deleting pool failed.\n");
233 query->destroy(query);
234 exit(-1);
235 }
236 }
237 query->destroy(query);
238 if (!found)
239 {
240 fprintf(stderr, "pool '%s' not found.\n", name);
241 exit(-1);
242 }
243 exit(0);
244 }
245
246 /**
247 * ipsec pool --resize - resize a pool
248 */
249 static void resize(char *name, host_t *end)
250 {
251 enumerator_t *query;
252 chunk_t next_addr, end_addr;
253
254 end_addr = end->get_address(end);
255
256 query = db->query(db, "SELECT next FROM pools WHERE name = ?",
257 DB_TEXT, name, DB_BLOB);
258 if (!query || !query->enumerate(query, &next_addr))
259 {
260 DESTROY_IF(query);
261 fprintf(stderr, "resizing pool failed.\n");
262 exit(-1);
263 }
264 if (next_addr.len != end_addr.len ||
265 memcmp(end_addr.ptr, next_addr.ptr, end_addr.len) < 0)
266 {
267 end = host_create_from_blob(next_addr);
268 fprintf(stderr, "pool addresses up to %H in use, resizing failed.\n", end);
269 end->destroy(end);
270 query->destroy(query);
271 exit(-1);
272 }
273 query->destroy(query);
274
275 if (db->execute(db, NULL,
276 "UPDATE pools SET end = ? WHERE name = ?",
277 DB_BLOB, end_addr, DB_TEXT, name) <= 0)
278 {
279 fprintf(stderr, "pool '%s' not found.\n", name);
280 exit(-1);
281 }
282 exit(0);
283 }
284
285 /**
286 * ipsec pool --leases - show lease information of a pool
287 */
288 static void leases(char *name, char *filter, bool utc)
289 {
290 enumerator_t *query;
291 chunk_t address_chunk, identity_chunk;
292 int identity_type;
293 u_int acquired, released, timeout;
294 host_t *address;
295 identification_t *identity;
296 bool found = FALSE;
297
298 query = db->query(db, "SELECT name, address, identities.type, "
299 "identities.data, acquired, released, timeout "
300 "FROM leases JOIN pools ON leases.pool = pools.id "
301 "JOIN identities ON leases.identity = identities.id ",
302 DB_TEXT, DB_BLOB, DB_INT,
303 DB_BLOB, DB_UINT, DB_UINT, DB_UINT);
304 if (!query)
305 {
306 fprintf(stderr, "querying leases failed.\n");
307 exit(-1);
308 }
309 while (query->enumerate(query, &name, &address_chunk, &identity_type,
310 &identity_chunk, &acquired, &released, &timeout))
311 {
312 if (!found)
313 {
314 int len = utc ? 25 : 21;
315
316 found = TRUE;
317 printf("%-8s %15s %-33s %-*s %-*s %-7s\n",
318 "name", "address", "identity", len, "start", len, "end", "status");
319 }
320 address = host_create_from_blob(address_chunk);
321 identity = identification_create_from_encoding(identity_type, identity_chunk);
322
323 printf("%-8s %15H %-32D %#T ", name, address, identity, &acquired, utc);
324 if (released)
325 {
326 printf("%#T ", &released, utc);
327 }
328 else
329 {
330 printf(" ");
331 }
332 if (released == 0)
333 {
334 printf("%-7s\n", "online");
335 }
336 else if (timeout == 0)
337 {
338 printf("%-7s\n", "static");
339 }
340 else if (released >= time(NULL) - timeout)
341 {
342 printf("%-7s\n", "valid");
343 }
344 else
345 {
346 printf("%-7s\n", "expired");
347 }
348 DESTROY_IF(address);
349 identity->destroy(identity);
350 }
351 query->destroy(query);
352 if (!found)
353 {
354 fprintf(stderr, "no matching leases found.\n");
355 exit(-1);
356 }
357 exit(0);
358 }
359
360 /**
361 * ipsec pool --purge - delete expired leases
362 */
363 static void purge(char *name)
364 {
365 enumerator_t *query;
366 u_int id, timeout, purged = 0;
367
368 query = db->query(db, "SELECT id, timeout FROM pools WHERE name = ?",
369 DB_TEXT, name, DB_UINT, DB_UINT);
370 if (!query)
371 {
372 fprintf(stderr, "purging pool failed.\n");
373 exit(-1);
374 }
375 /* we have to keep one lease if we purge. It wouldn't be reallocateable
376 * as we move on the "next" address for speedy allocation */
377 if (query->enumerate(query, &id, &timeout))
378 {
379 timeout = time(NULL) - timeout;
380 purged = db->execute(db, NULL,
381 "DELETE FROM leases WHERE pool = ? "
382 "AND released IS NOT NULL AND released < ? AND id NOT IN ("
383 " SELECT id FROM leases "
384 " WHERE released IS NOT NULL and released < ? "
385 " GROUP BY address)",
386 DB_UINT, id, DB_UINT, timeout, DB_UINT, timeout);
387 }
388 query->destroy(query);
389 fprintf(stderr, "purged %d leases in pool '%s'.\n", purged, name);
390 exit(0);
391 }
392
393 /**
394 * atexit handler to close db on shutdown
395 */
396 static void cleanup(void)
397 {
398 db->destroy(db);
399 DESTROY_IF(start);
400 DESTROY_IF(end);
401 }
402
403 /**
404 * Logging hook for library logs, using stderr output
405 */
406 static void dbg_stderr(int level, char *fmt, ...)
407 {
408 va_list args;
409
410 if (level <= 1)
411 {
412 va_start(args, fmt);
413 vfprintf(stderr, fmt, args);
414 fprintf(stderr, "\n");
415 va_end(args);
416 }
417 }
418
419 int main(int argc, char *argv[])
420 {
421 char *uri, *name = "", *filter = "";
422 int timeout = 0;
423 bool utc = FALSE;
424 enum {
425 OP_USAGE,
426 OP_STATUS,
427 OP_ADD,
428 OP_DEL,
429 OP_RESIZE,
430 OP_LEASES,
431 OP_PURGE,
432 } operation = OP_USAGE;
433
434 dbg = dbg_stderr;
435 library_init(STRONGSWAN_CONF);
436 atexit(library_deinit);
437 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR,
438 lib->settings->get_str(lib->settings, "pool.load", PLUGINS));
439
440 uri = lib->settings->get_str(lib->settings, "charon.plugins.sql.database", NULL);
441 if (!uri)
442 {
443 fprintf(stderr, "database URI charon.plugins.sql.database not set.\n");
444 exit(-1);
445 }
446 db = lib->db->create(lib->db, uri);
447 if (!db)
448 {
449 fprintf(stderr, "opening database failed.\n");
450 exit(-1);
451 }
452 atexit(cleanup);
453
454 while (TRUE)
455 {
456 int c;
457
458 struct option long_opts[] = {
459 { "help", no_argument, NULL, 'h' },
460
461 { "utc", no_argument, NULL, 'u' },
462 { "status", no_argument, NULL, 'w' },
463 { "add", required_argument, NULL, 'a' },
464 { "del", required_argument, NULL, 'd' },
465 { "resize", required_argument, NULL, 'r' },
466 { "leases", optional_argument, NULL, 'l' },
467 { "purge", required_argument, NULL, 'p' },
468
469 { "start", required_argument, NULL, 's' },
470 { "end", required_argument, NULL, 'e' },
471 { "timeout", required_argument, NULL, 't' },
472 { "filter", required_argument, NULL, 'f' },
473 { 0,0,0,0 }
474 };
475
476 c = getopt_long(argc, argv, "", long_opts, NULL);
477 switch (c)
478 {
479 case EOF:
480 break;
481 case 'h':
482 break;
483 case 'u':
484 utc = TRUE;
485 break;
486 case 'w':
487 operation = OP_STATUS;
488 break;
489 case 'a':
490 operation = OP_ADD;
491 name = optarg;
492 continue;
493 case 'd':
494 operation = OP_DEL;
495 name = optarg;
496 continue;
497 case 'r':
498 operation = OP_RESIZE;
499 name = optarg;
500 continue;
501 case 'l':
502 operation = OP_LEASES;
503 name = optarg;
504 continue;
505 case 'p':
506 operation = OP_PURGE;
507 name = optarg;
508 continue;
509 case 's':
510 start = host_create_from_string(optarg, 0);
511 if (start == NULL)
512 {
513 fprintf(stderr, "invalid start address: '%s'.\n", optarg);
514 operation = OP_USAGE;
515 break;
516 }
517 continue;
518 case 'e':
519 end = host_create_from_string(optarg, 0);
520 if (end == NULL)
521 {
522 fprintf(stderr, "invalid end address: '%s'.\n", optarg);
523 operation = OP_USAGE;
524 break;
525 }
526 continue;
527 case 't':
528 timeout = atoi(optarg);
529 if (timeout == 0 && strcmp(optarg, "0") != 0)
530 {
531 fprintf(stderr, "invalid timeout '%s'.\n", optarg);
532 operation = OP_USAGE;
533 break;
534 }
535 continue;
536 case 'f':
537 filter = optarg;
538 continue;
539 default:
540 operation = OP_USAGE;
541 break;
542 }
543 break;
544 }
545
546 switch (operation)
547 {
548 case OP_USAGE:
549 usage();
550 break;
551 case OP_STATUS:
552 status();
553 break;
554 case OP_ADD:
555 if (start == NULL || end == NULL)
556 {
557 fprintf(stderr, "missing arguments.\n");
558 usage();
559 }
560 add(name, start, end, timeout);
561 break;
562 case OP_DEL:
563 del(name);
564 break;
565 case OP_RESIZE:
566 if (end == NULL)
567 {
568 fprintf(stderr, "missing arguments.\n");
569 usage();
570 }
571 resize(name, end);
572 break;
573 case OP_LEASES:
574 leases(name, filter, utc);
575 break;
576 case OP_PURGE:
577 purge(name);
578 break;
579 }
580 exit(0);
581 }
582