ported some hard-to-merge cherries back to trunk :-/
[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 * calculate the size of a pool using start and end address chunk
40 */
41 static u_int get_pool_size(chunk_t start, chunk_t end)
42 {
43 u_int *start_ptr, *end_ptr;
44
45 if (start.len < sizeof(u_int) || end.len < sizeof(u_int))
46 {
47 return 0;
48 }
49 start_ptr = (u_int*)(start.ptr + start.len - sizeof(u_int));
50 end_ptr = (u_int*)(end.ptr + end.len - sizeof(u_int));
51 return ntohl(*end_ptr) - ntohl(*start_ptr) + 1;
52 }
53
54 /**
55 * print usage info
56 */
57 static void usage(void)
58 {
59 printf("\
60 Usage:\n\
61 ipsec pool --status|--add|--del|--resize|--purge [options]\n\
62 \n\
63 ipsec pool --status\n\
64 Show a list of installed pools with statistics.\n\
65 \n\
66 ipsec pool --add <name> --start <start> --end <end> [--timeout <timeout>]\n\
67 Add a new pool to the database.\n\
68 name: Name of the pool, as used in ipsec.conf rightsourceip=%%name\n\
69 start: Start address of the pool\n\
70 end: End address of the pool\n\
71 timeout: Lease time in hours, 0 for static leases\n\
72 \n\
73 ipsec pool --del <name>\n\
74 Delete a pool from the database.\n\
75 name: Name of the pool to delete\n\
76 \n\
77 ipsec pool --resize <name> --end <end>\n\
78 Grow or shrink an existing pool.\n\
79 name: Name of the pool to resize\n\
80 end: New end address for the pool\n\
81 \n\
82 ipsec pool --leases [--filter <filter>] [--utc]\n\
83 Show lease information using filters:\n\
84 filter: Filter string containing comma separated key=value filters,\n\
85 e.g. id=alice@strongswan.org,addr=1.1.1.1\n\
86 pool: name of the pool\n\
87 id: assigned identity of the lease\n\
88 addr: lease IP address\n\
89 tstamp: UNIX timestamp when lease was valid, as integer\n\
90 status: status of the lease: online|valid|expired\n\
91 utc: Show times in UTC instead of local time\n\
92 \n\
93 ipsec pool --purge <name>\n\
94 Delete lease history of a pool:\n\
95 name: Name of the pool to purge\n\
96 \n");
97 exit(0);
98 }
99
100 /**
101 * ipsec pool --status - show pool overview
102 */
103 static void status(void)
104 {
105 enumerator_t *pool, *lease;
106 bool found = FALSE;
107
108 pool = db->query(db, "SELECT id, name, start, end, timeout FROM pools",
109 DB_INT, DB_TEXT, DB_BLOB, DB_BLOB, DB_UINT);
110 if (pool)
111 {
112 char *name;
113 chunk_t start_chunk, end_chunk;
114 host_t *start, *end;
115 u_int id, timeout, online = 0, used = 0, size = 0;
116
117 while (pool->enumerate(pool, &id, &name,
118 &start_chunk, &end_chunk, &timeout))
119 {
120 if (!found)
121 {
122 printf("%8s %15s %15s %8s %6s %11s %11s\n", "name", "start",
123 "end", "timeout", "size", "online", "usage");
124 found = TRUE;
125 }
126
127 start = host_create_from_chunk(AF_UNSPEC, start_chunk, 0);
128 end = host_create_from_chunk(AF_UNSPEC, end_chunk, 0);
129 size = get_pool_size(start_chunk, end_chunk);
130 printf("%8s %15H %15H ", name, start, end);
131 if (timeout)
132 {
133 printf("%7dh ", timeout/3600);
134 }
135 else
136 {
137 printf("%8s ", "static");
138 }
139 printf("%6d ", size);
140 /* get number of online hosts */
141 lease = db->query(db, "SELECT COUNT(*) FROM addresses "
142 "WHERE pool = ? AND released = 0",
143 DB_UINT, id, DB_INT);
144 if (lease)
145 {
146 lease->enumerate(lease, &online);
147 lease->destroy(lease);
148 }
149 printf("%5d (%2d%%) ", online, online*100/size);
150 /* get number of online or valid lieases */
151 lease = db->query(db, "SELECT COUNT(*) FROM addresses "
152 "WHERE addresses.pool = ? "
153 "AND ((? AND acquired != 0) "
154 " OR released = 0 OR released > ?) ",
155 DB_UINT, id, DB_UINT, !timeout,
156 DB_UINT, time(NULL) - timeout, DB_UINT);
157 if (lease)
158 {
159 lease->enumerate(lease, &used);
160 lease->destroy(lease);
161 }
162 printf("%5d (%2d%%) ", used, used*100/size);
163
164 printf("\n");
165 DESTROY_IF(start);
166 DESTROY_IF(end);
167 }
168 pool->destroy(pool);
169 }
170 if (!found)
171 {
172 printf("no pools found.\n");
173 }
174 exit(0);
175 }
176
177 /**
178 * increment a chunk, as it would reprensent a network order integer
179 */
180 static void increment_chunk(chunk_t chunk)
181 {
182 int i;
183
184 for (i = chunk.len - 1; i >= 0; i--)
185 {
186 if (++chunk.ptr[i] != 0)
187 {
188 return;
189 }
190 }
191 }
192
193 /**
194 * ipsec pool --add - add a new pool
195 */
196 static void add(char *name, host_t *start, host_t *end, int timeout)
197 {
198 chunk_t start_addr, end_addr, cur_addr;
199 u_int id, count;
200
201 start_addr = start->get_address(start);
202 end_addr = end->get_address(end);
203 cur_addr = chunk_clonea(start_addr);
204 count = get_pool_size(start_addr, end_addr);
205
206 if (start_addr.len != end_addr.len ||
207 memcmp(start_addr.ptr, end_addr.ptr, start_addr.len) > 0)
208 {
209 fprintf(stderr, "invalid start/end pair specified.\n");
210 exit(-1);
211 }
212 if (db->execute(db, &id,
213 "INSERT INTO pools (name, start, end, timeout) "
214 "VALUES (?, ?, ?, ?)",
215 DB_TEXT, name, DB_BLOB, start_addr,
216 DB_BLOB, end_addr, DB_INT, timeout*3600) != 1)
217 {
218 fprintf(stderr, "creating pool failed.\n");
219 exit(-1);
220 }
221 printf("allocating %d addresses... ", count);
222 fflush(stdout);
223 if (db->get_driver(db) == DB_SQLITE)
224 { /* run population in a transaction for sqlite */
225 db->execute(db, NULL, "BEGIN TRANSACTION");
226 }
227 while (TRUE)
228 {
229 db->execute(db, NULL,
230 "INSERT INTO addresses (pool, address, identity, acquired, released) "
231 "VALUES (?, ?, ?, ?, ?)",
232 DB_UINT, id, DB_BLOB, cur_addr, DB_UINT, 0, DB_UINT, 0, DB_UINT, 1);
233 if (chunk_equals(cur_addr, end_addr))
234 {
235 break;
236 }
237 increment_chunk(cur_addr);
238 }
239 if (db->get_driver(db) == DB_SQLITE)
240 {
241 db->execute(db, NULL, "END TRANSACTION");
242 }
243 printf("done.\n", count);
244
245 exit(0);
246 }
247
248 /**
249 * ipsec pool --del - delete a pool
250 */
251 static void del(char *name)
252 {
253 enumerator_t *query;
254 u_int id;
255 bool found = FALSE;
256
257 query = db->query(db, "SELECT id FROM pools WHERE name = ?",
258 DB_TEXT, name, DB_UINT);
259 if (!query)
260 {
261 fprintf(stderr, "deleting pool failed.\n");
262 exit(-1);
263 }
264 while (query->enumerate(query, &id))
265 {
266 found = TRUE;
267 if (db->execute(db, NULL,
268 "DELETE FROM leases WHERE address IN ("
269 " SELECT id FROM addresses WHERE pool = ?)", DB_UINT, id) < 0 ||
270 db->execute(db, NULL,
271 "DELETE FROM addresses WHERE pool = ?", DB_UINT, id) < 0 ||
272 db->execute(db, NULL,
273 "DELETE FROM pools WHERE id = ?", DB_UINT, id) < 0)
274 {
275 fprintf(stderr, "deleting pool failed.\n");
276 query->destroy(query);
277 exit(-1);
278 }
279 }
280 query->destroy(query);
281 if (!found)
282 {
283 fprintf(stderr, "pool '%s' not found.\n", name);
284 exit(-1);
285 }
286 exit(0);
287 }
288
289 /**
290 * ipsec pool --resize - resize a pool
291 */
292 static void resize(char *name, host_t *end)
293 {
294 enumerator_t *query;
295 chunk_t old_addr, new_addr, cur_addr;
296 u_int id, count;
297
298 new_addr = end->get_address(end);
299
300 query = db->query(db, "SELECT id, end FROM pools WHERE name = ?",
301 DB_TEXT, name, DB_UINT, DB_BLOB);
302 if (!query || !query->enumerate(query, &id, &old_addr))
303 {
304 DESTROY_IF(query);
305 fprintf(stderr, "resizing pool failed.\n");
306 exit(-1);
307 }
308 if (old_addr.len != new_addr.len ||
309 memcmp(new_addr.ptr, old_addr.ptr, old_addr.len) < 0)
310 {
311 fprintf(stderr, "shrinking of pools not supported.\n");
312 query->destroy(query);
313 exit(-1);
314 }
315 cur_addr = chunk_clonea(old_addr);
316 count = get_pool_size(old_addr, new_addr) - 1;
317 query->destroy(query);
318
319 if (db->execute(db, NULL,
320 "UPDATE pools SET end = ? WHERE name = ?",
321 DB_BLOB, new_addr, DB_TEXT, name) <= 0)
322 {
323 fprintf(stderr, "pool '%s' not found.\n", name);
324 exit(-1);
325 }
326
327 printf("allocating %d new addresses... ", count);
328 fflush(stdout);
329 if (db->get_driver(db) == DB_SQLITE)
330 { /* run population in a transaction for sqlite */
331 db->execute(db, NULL, "BEGIN TRANSACTION");
332 }
333 while (count-- > 0)
334 {
335 increment_chunk(cur_addr);
336 db->execute(db, NULL,
337 "INSERT INTO addresses (pool, address, identity, acquired, released) "
338 "VALUES (?, ?, ?, ?, ?)",
339 DB_UINT, id, DB_BLOB, cur_addr, DB_UINT, 0, DB_UINT, 0, DB_UINT, 1);
340 }
341 if (db->get_driver(db) == DB_SQLITE)
342 {
343 db->execute(db, NULL, "END TRANSACTION");
344 }
345 printf("done.\n", count);
346
347 exit(0);
348 }
349
350 /**
351 * create the lease query using the filter string
352 */
353 static enumerator_t *create_lease_query(char *filter)
354 {
355 enumerator_t *query;
356 identification_t *id = NULL;
357 host_t *addr = NULL;
358 u_int tstamp = 0;
359 bool online = FALSE, valid = FALSE, expired = FALSE;
360 char *value, *pos, *pool = NULL;
361 enum {
362 FIL_POOL = 0,
363 FIL_ID,
364 FIL_ADDR,
365 FIL_TSTAMP,
366 FIL_STATE,
367 };
368 char *const token[] = {
369 [FIL_POOL] = "pool",
370 [FIL_ID] = "id",
371 [FIL_ADDR] = "addr",
372 [FIL_TSTAMP] = "tstamp",
373 [FIL_STATE] = "status",
374 NULL
375 };
376
377 /* if the filter string contains a distinguished name as a ID, we replace
378 * ", " by "/ " in order to not confuse the getsubopt parser */
379 pos = filter;
380 while ((pos = strchr(pos, ',')))
381 {
382 if (pos[1] == ' ')
383 {
384 pos[0] = '/';
385 }
386 pos++;
387 }
388
389 while (filter && *filter != '\0')
390 {
391 switch (getsubopt(&filter, token, &value))
392 {
393 case FIL_POOL:
394 if (value)
395 {
396 pool = value;
397 }
398 break;
399 case FIL_ID:
400 if (value)
401 {
402 id = identification_create_from_string(value);
403 }
404 if (!id)
405 {
406 fprintf(stderr, "invalid 'id' in filter string.\n");
407 exit(-1);
408 }
409 break;
410 case FIL_ADDR:
411 if (value)
412 {
413 addr = host_create_from_string(value, 0);
414 }
415 if (!addr)
416 {
417 fprintf(stderr, "invalid 'addr' in filter string.\n");
418 exit(-1);
419 }
420 break;
421 case FIL_TSTAMP:
422 if (value)
423 {
424 tstamp = atoi(value);
425 }
426 if (tstamp == 0)
427 {
428 online = TRUE;
429 }
430 break;
431 case FIL_STATE:
432 if (value)
433 {
434 if (streq(value, "online"))
435 {
436 online = TRUE;
437 }
438 else if (streq(value, "valid"))
439 {
440 valid = TRUE;
441 }
442 else if (streq(value, "expired"))
443 {
444 expired = TRUE;
445 }
446 else
447 {
448 fprintf(stderr, "invalid 'state' in filter string.\n");
449 exit(-1);
450 }
451 }
452 break;
453 default:
454 fprintf(stderr, "invalid filter string.\n");
455 exit(-1);
456 break;
457 }
458 }
459 query = db->query(db,
460 "SELECT name, addresses.address, identities.type, "
461 "identities.data, leases.acquired, leases.released, timeout "
462 "FROM leases JOIN addresses ON leases.address = addresses.id "
463 "JOIN pools ON addresses.pool = pools.id "
464 "JOIN identities ON leases.identity = identities.id "
465 "WHERE (? OR name = ?) "
466 "AND (? OR (identities.type = ? AND identities.data = ?)) "
467 "AND (? OR addresses.address = ?) "
468 "AND (? OR (? >= leases.acquired AND (? <= leases.released))) "
469 "AND (? OR leases.released > ? - timeout) "
470 "AND (? OR leases.released < ? - timeout) "
471 "AND ? "
472 "UNION "
473 "SELECT name, address, identities.type, identities.data, "
474 "acquired, released, timeout FROM addresses "
475 "JOIN pools ON addresses.pool = pools.id "
476 "JOIN identities ON addresses.identity = identities.id "
477 "WHERE ? AND released = 0 "
478 "AND (? OR name = ?) "
479 "AND (? OR (identities.type = ? AND identities.data = ?)) "
480 "AND (? OR address = ?)",
481 DB_INT, pool == NULL, DB_TEXT, pool,
482 DB_INT, id == NULL,
483 DB_INT, id ? id->get_type(id) : 0,
484 DB_BLOB, id ? id->get_encoding(id) : chunk_empty,
485 DB_INT, addr == NULL,
486 DB_BLOB, addr ? addr->get_address(addr) : chunk_empty,
487 DB_INT, tstamp == 0, DB_UINT, tstamp, DB_UINT, tstamp,
488 DB_INT, !valid, DB_INT, time(NULL),
489 DB_INT, !expired, DB_INT, time(NULL),
490 DB_INT, !online,
491 /* union */
492 DB_INT, !(valid || expired),
493 DB_INT, pool == NULL, DB_TEXT, pool,
494 DB_INT, id == NULL,
495 DB_INT, id ? id->get_type(id) : 0,
496 DB_BLOB, id ? id->get_encoding(id) : chunk_empty,
497 DB_INT, addr == NULL,
498 DB_BLOB, addr ? addr->get_address(addr) : chunk_empty,
499 /* res */
500 DB_TEXT, DB_BLOB, DB_INT, DB_BLOB, DB_UINT, DB_UINT, DB_UINT);
501 /* id and addr leak but we can't destroy them until query is destroyed. */
502 return query;
503 }
504
505 /**
506 * ipsec pool --leases - show lease information of a pool
507 */
508 static void leases(char *filter, bool utc)
509 {
510 enumerator_t *query;
511 chunk_t address_chunk, identity_chunk;
512 int identity_type;
513 char *name;
514 u_int acquired, released, timeout;
515 host_t *address;
516 identification_t *identity;
517 bool found = FALSE;
518
519 query = create_lease_query(filter);
520 if (!query)
521 {
522 fprintf(stderr, "querying leases failed.\n");
523 exit(-1);
524 }
525 while (query->enumerate(query, &name, &address_chunk, &identity_type,
526 &identity_chunk, &acquired, &released, &timeout))
527 {
528 if (!found)
529 {
530 int len = utc ? 25 : 21;
531
532 found = TRUE;
533 printf("%-8s %-15s %-7s %-*s %-*s %s\n",
534 "name", "address", "status", len, "start", len, "end", "identity");
535 }
536 address = host_create_from_chunk(AF_UNSPEC, address_chunk, 0);
537 identity = identification_create_from_encoding(identity_type, identity_chunk);
538
539 printf("%-8s %-15H ", name, address);
540 if (released == 0)
541 {
542 printf("%-7s ", "online");
543 }
544 else if (timeout == 0)
545 {
546 printf("%-7s ", "static");
547 }
548 else if (released >= time(NULL) - timeout)
549 {
550 printf("%-7s ", "valid");
551 }
552 else
553 {
554 printf("%-7s ", "expired");
555 }
556
557 printf(" %#T ", &acquired, utc);
558 if (released)
559 {
560 printf("%#T ", &released, utc);
561 }
562 else
563 {
564 printf(" ");
565 if (utc)
566 {
567 printf(" ");
568 }
569 }
570 printf("%D\n", identity);
571 DESTROY_IF(address);
572 identity->destroy(identity);
573 }
574 query->destroy(query);
575 if (!found)
576 {
577 fprintf(stderr, "no matching leases found.\n");
578 exit(-1);
579 }
580 exit(0);
581 }
582
583 /**
584 * ipsec pool --purge - delete expired leases
585 */
586 static void purge(char *name)
587 {
588 int purged = 0;
589
590 purged = db->execute(db, NULL,
591 "DELETE FROM leases WHERE address IN ("
592 " SELECT id FROM addresses WHERE pool IN ("
593 " SELECT id FROM pools WHERE name = ?))",
594 DB_TEXT, name);
595 if (purged < 0)
596 {
597 fprintf(stderr, "purging pool '%s' failed.\n", name);
598 exit(-1);
599 }
600 fprintf(stderr, "purged %d leases in pool '%s'.\n", purged, name);
601 exit(0);
602 }
603
604 /**
605 * atexit handler to close db on shutdown
606 */
607 static void cleanup(void)
608 {
609 db->destroy(db);
610 DESTROY_IF(start);
611 DESTROY_IF(end);
612 }
613
614 /**
615 * Logging hook for library logs, using stderr output
616 */
617 static void dbg_stderr(int level, char *fmt, ...)
618 {
619 va_list args;
620
621 if (level <= 1)
622 {
623 va_start(args, fmt);
624 vfprintf(stderr, fmt, args);
625 fprintf(stderr, "\n");
626 va_end(args);
627 }
628 }
629
630 int main(int argc, char *argv[])
631 {
632 char *uri, *name = "", *filter = "";
633 int timeout = 0;
634 bool utc = FALSE;
635 enum {
636 OP_USAGE,
637 OP_STATUS,
638 OP_ADD,
639 OP_DEL,
640 OP_RESIZE,
641 OP_LEASES,
642 OP_PURGE,
643 } operation = OP_USAGE;
644
645 dbg = dbg_stderr;
646 library_init(STRONGSWAN_CONF);
647 atexit(library_deinit);
648 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR,
649 lib->settings->get_str(lib->settings, "pool.load", PLUGINS));
650
651 uri = lib->settings->get_str(lib->settings, "charon.plugins.sql.database", NULL);
652 if (!uri)
653 {
654 fprintf(stderr, "database URI charon.plugins.sql.database not set.\n");
655 exit(-1);
656 }
657 db = lib->db->create(lib->db, uri);
658 if (!db)
659 {
660 fprintf(stderr, "opening database failed.\n");
661 exit(-1);
662 }
663 atexit(cleanup);
664
665 while (TRUE)
666 {
667 int c;
668
669 struct option long_opts[] = {
670 { "help", no_argument, NULL, 'h' },
671
672 { "utc", no_argument, NULL, 'u' },
673 { "status", no_argument, NULL, 'w' },
674 { "add", required_argument, NULL, 'a' },
675 { "del", required_argument, NULL, 'd' },
676 { "resize", required_argument, NULL, 'r' },
677 { "leases", no_argument, NULL, 'l' },
678 { "purge", required_argument, NULL, 'p' },
679
680 { "start", required_argument, NULL, 's' },
681 { "end", required_argument, NULL, 'e' },
682 { "timeout", required_argument, NULL, 't' },
683 { "filter", required_argument, NULL, 'f' },
684 { 0,0,0,0 }
685 };
686
687 c = getopt_long(argc, argv, "", long_opts, NULL);
688 switch (c)
689 {
690 case EOF:
691 break;
692 case 'h':
693 break;
694 case 'w':
695 operation = OP_STATUS;
696 break;
697 case 'u':
698 utc = TRUE;
699 continue;
700 case 'a':
701 operation = OP_ADD;
702 name = optarg;
703 continue;
704 case 'd':
705 operation = OP_DEL;
706 name = optarg;
707 continue;
708 case 'r':
709 operation = OP_RESIZE;
710 name = optarg;
711 continue;
712 case 'l':
713 operation = OP_LEASES;
714 continue;
715 case 'p':
716 operation = OP_PURGE;
717 name = optarg;
718 continue;
719 case 's':
720 start = host_create_from_string(optarg, 0);
721 if (start == NULL)
722 {
723 fprintf(stderr, "invalid start address: '%s'.\n", optarg);
724 operation = OP_USAGE;
725 break;
726 }
727 continue;
728 case 'e':
729 end = host_create_from_string(optarg, 0);
730 if (end == NULL)
731 {
732 fprintf(stderr, "invalid end address: '%s'.\n", optarg);
733 operation = OP_USAGE;
734 break;
735 }
736 continue;
737 case 't':
738 timeout = atoi(optarg);
739 if (timeout == 0 && strcmp(optarg, "0") != 0)
740 {
741 fprintf(stderr, "invalid timeout '%s'.\n", optarg);
742 operation = OP_USAGE;
743 break;
744 }
745 continue;
746 case 'f':
747 filter = optarg;
748 continue;
749 default:
750 operation = OP_USAGE;
751 break;
752 }
753 break;
754 }
755
756 switch (operation)
757 {
758 case OP_USAGE:
759 usage();
760 break;
761 case OP_STATUS:
762 status();
763 break;
764 case OP_ADD:
765 if (start == NULL || end == NULL)
766 {
767 fprintf(stderr, "missing arguments.\n");
768 usage();
769 }
770 add(name, start, end, timeout);
771 break;
772 case OP_DEL:
773 del(name);
774 break;
775 case OP_RESIZE:
776 if (end == NULL)
777 {
778 fprintf(stderr, "missing arguments.\n");
779 usage();
780 }
781 resize(name, end);
782 break;
783 case OP_LEASES:
784 leases(filter, utc);
785 break;
786 case OP_PURGE:
787 purge(name);
788 break;
789 }
790 exit(0);
791 }
792