Moved host_t and host_resolver_t to a new networking subfolder
[strongswan.git] / src / libhydra / plugins / attr_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
16 #define _GNU_SOURCE
17 #include <getopt.h>
18 #include <unistd.h>
19 #include <stdio.h>
20 #include <time.h>
21 #include <string.h>
22 #include <errno.h>
23
24 #include <debug.h>
25 #include <library.h>
26 #include <networking/host.h>
27 #include <utils/identification.h>
28 #include <attributes/attributes.h>
29
30 #include "pool_attributes.h"
31 #include "pool_usage.h"
32
33 /**
34 * global database handle
35 */
36 database_t *db;
37
38 /**
39 * --start/--end addresses of various subcommands
40 */
41 host_t *start = NULL, *end = NULL;
42
43 /**
44 * whether --add should --replace an existing pool
45 */
46 bool replace_pool = FALSE;
47
48 /**
49 * forward declarations
50 */
51 static void del(char *name);
52 static void do_args(int argc, char *argv[]);
53
54 /**
55 * nesting counter for database transaction functions
56 */
57 int nested_transaction = 0;
58
59 /**
60 * start a database transaction
61 */
62 static void begin_transaction()
63 {
64 if (db->get_driver(db) == DB_SQLITE)
65 {
66 if (!nested_transaction)
67 {
68 db->execute(db, NULL, "BEGIN EXCLUSIVE TRANSACTION");
69 }
70 ++nested_transaction;
71 }
72 }
73
74 /**
75 * commit a database transaction
76 */
77 static void commit_transaction()
78 {
79 if (db->get_driver(db) == DB_SQLITE)
80 {
81 --nested_transaction;
82 if (!nested_transaction)
83 {
84 db->execute(db, NULL, "END TRANSACTION");
85 }
86 }
87 }
88
89 /**
90 * Create or replace a pool by name
91 */
92 static u_int create_pool(char *name, chunk_t start, chunk_t end, int timeout)
93 {
94 enumerator_t *e;
95 int pool;
96
97 e = db->query(db, "SELECT id FROM pools WHERE name = ?",
98 DB_TEXT, name, DB_UINT);
99 if (e && e->enumerate(e, &pool))
100 {
101 if (replace_pool == FALSE)
102 {
103 fprintf(stderr, "pool '%s' exists.\n", name);
104 e->destroy(e);
105 exit(EXIT_FAILURE);
106 }
107 del(name);
108 }
109 DESTROY_IF(e);
110 if (db->execute(db, &pool,
111 "INSERT INTO pools (name, start, end, timeout) VALUES (?, ?, ?, ?)",
112 DB_TEXT, name, DB_BLOB, start, DB_BLOB, end,
113 DB_INT, timeout*3600) != 1)
114 {
115 fprintf(stderr, "creating pool failed.\n");
116 exit(EXIT_FAILURE);
117 }
118
119 return pool;
120 }
121
122 /**
123 * instead of a pool handle a DNS or NBNS attribute
124 */
125 static bool is_attribute(char *name)
126 {
127 return strcaseeq(name, "dns") || strcaseeq(name, "nbns") ||
128 strcaseeq(name, "wins");
129 }
130
131 /**
132 * calculate the size of a pool using start and end address chunk
133 */
134 static u_int get_pool_size(chunk_t start, chunk_t end)
135 {
136 u_int *start_ptr, *end_ptr;
137
138 if (start.len < sizeof(u_int) || end.len < sizeof(u_int))
139 {
140 return 0;
141 }
142 start_ptr = (u_int*)(start.ptr + start.len - sizeof(u_int));
143 end_ptr = (u_int*)(end.ptr + end.len - sizeof(u_int));
144 return ntohl(*end_ptr) - ntohl(*start_ptr) + 1;
145 }
146
147 /**
148 * ipsec pool --status - show pool overview
149 */
150 static void status(void)
151 {
152 enumerator_t *ns, *pool, *lease;
153 host_t *server;
154 chunk_t value;
155 bool found = FALSE;
156
157 /* enumerate IPv4 DNS servers */
158 ns = db->query(db, "SELECT value FROM attributes WHERE type = ?",
159 DB_INT, INTERNAL_IP4_DNS, DB_BLOB);
160 if (ns)
161 {
162 while (ns->enumerate(ns, &value))
163 {
164 if (!found)
165 {
166 printf("dns servers:");
167 found = TRUE;
168 }
169 server = host_create_from_chunk(AF_INET, value, 0);
170 if (server)
171 {
172 printf(" %H", server);
173 server->destroy(server);
174 }
175 }
176 ns->destroy(ns);
177 }
178
179 /* enumerate IPv6 DNS servers */
180 ns = db->query(db, "SELECT value FROM attributes WHERE type = ?",
181 DB_INT, INTERNAL_IP6_DNS, DB_BLOB);
182 if (ns)
183 {
184 while (ns->enumerate(ns, &value))
185 {
186 if (!found)
187 {
188 printf("dns servers:");
189 found = TRUE;
190 }
191 server = host_create_from_chunk(AF_INET6, value, 0);
192 if (server)
193 {
194 printf(" %H", server);
195 server->destroy(server);
196 }
197 }
198 ns->destroy(ns);
199 }
200 if (found)
201 {
202 printf("\n");
203 }
204 else
205 {
206 printf("no dns servers found.\n");
207 }
208 found = FALSE;
209
210 /* enumerate IPv4 NBNS servers */
211 ns = db->query(db, "SELECT value FROM attributes WHERE type = ?",
212 DB_INT, INTERNAL_IP4_NBNS, DB_BLOB);
213 if (ns)
214 {
215 while (ns->enumerate(ns, &value))
216 {
217 if (!found)
218 {
219 printf("nbns servers:");
220 found = TRUE;
221 }
222 server = host_create_from_chunk(AF_INET, value, 0);
223 if (server)
224 {
225 printf(" %H", server);
226 server->destroy(server);
227 }
228 }
229 ns->destroy(ns);
230 }
231
232 /* enumerate IPv6 NBNS servers */
233 ns = db->query(db, "SELECT value FROM attributes WHERE type = ?",
234 DB_INT, INTERNAL_IP6_NBNS, DB_BLOB);
235 if (ns)
236 {
237 while (ns->enumerate(ns, &value))
238 {
239 if (!found)
240 {
241 printf("nbns servers:");
242 found = TRUE;
243 }
244 server = host_create_from_chunk(AF_INET6, value, 0);
245 if (server)
246 {
247 printf(" %H", server);
248 server->destroy(server);
249 }
250 }
251 ns->destroy(ns);
252 }
253 if (found)
254 {
255 printf("\n");
256 }
257 else
258 {
259 printf("no nbns servers found.\n");
260 }
261 found = FALSE;
262
263 pool = db->query(db, "SELECT id, name, start, end, timeout FROM pools",
264 DB_INT, DB_TEXT, DB_BLOB, DB_BLOB, DB_UINT);
265 if (pool)
266 {
267 char *name;
268 chunk_t start_chunk, end_chunk;
269 host_t *start, *end;
270 u_int id, timeout, online = 0, used = 0, size = 0;
271
272 while (pool->enumerate(pool, &id, &name,
273 &start_chunk, &end_chunk, &timeout))
274 {
275 if (!found)
276 {
277 printf("%8s %15s %15s %8s %6s %11s %11s\n", "name", "start",
278 "end", "timeout", "size", "online", "usage");
279 found = TRUE;
280 }
281
282 start = host_create_from_chunk(AF_UNSPEC, start_chunk, 0);
283 end = host_create_from_chunk(AF_UNSPEC, end_chunk, 0);
284 if (start->is_anyaddr(start) && end->is_anyaddr(end))
285 {
286 printf("%8s %15s %15s ", name, "n/a", "n/a");
287 }
288 else
289 {
290 printf("%8s %15H %15H ", name, start, end);
291 }
292 if (timeout)
293 {
294 printf("%7dh ", timeout/3600);
295 }
296 else
297 {
298 printf("%8s ", "static");
299 }
300 /* get total number of hosts in the pool */
301 lease = db->query(db, "SELECT COUNT(*) FROM addresses "
302 "WHERE pool = ?", DB_UINT, id, DB_INT);
303 if (lease)
304 {
305 lease->enumerate(lease, &size);
306 lease->destroy(lease);
307 }
308 if (!size)
309 { /* empty pool */
310 printf("%6d %11s %11s ", 0, "n/a", "n/a");
311 goto next_pool;
312 }
313 printf("%6d ", size);
314 /* get number of online hosts */
315 lease = db->query(db, "SELECT COUNT(*) FROM addresses "
316 "WHERE pool = ? AND released = 0",
317 DB_UINT, id, DB_INT);
318 if (lease)
319 {
320 lease->enumerate(lease, &online);
321 lease->destroy(lease);
322 }
323 printf("%5d (%2d%%) ", online, online*100/size);
324 /* get number of online or valid leases */
325 lease = db->query(db, "SELECT COUNT(*) FROM addresses "
326 "WHERE addresses.pool = ? "
327 "AND ((? AND acquired != 0) "
328 " OR released = 0 OR released > ?) ",
329 DB_UINT, id, DB_UINT, !timeout,
330 DB_UINT, time(NULL) - timeout, DB_UINT);
331 if (lease)
332 {
333 lease->enumerate(lease, &used);
334 lease->destroy(lease);
335 }
336 printf("%5d (%2d%%) ", used, used*100/size);
337
338 next_pool:
339 printf("\n");
340 DESTROY_IF(start);
341 DESTROY_IF(end);
342 }
343 pool->destroy(pool);
344 }
345 if (!found)
346 {
347 printf("no pools found.\n");
348 }
349 }
350
351 /**
352 * ipsec pool --add - add a new pool
353 */
354 static void add(char *name, host_t *start, host_t *end, int timeout)
355 {
356 chunk_t start_addr, end_addr, cur_addr;
357 u_int id, count;
358
359 start_addr = start->get_address(start);
360 end_addr = end->get_address(end);
361 cur_addr = chunk_clonea(start_addr);
362 count = get_pool_size(start_addr, end_addr);
363
364 if (start_addr.len != end_addr.len ||
365 memcmp(start_addr.ptr, end_addr.ptr, start_addr.len) > 0)
366 {
367 fprintf(stderr, "invalid start/end pair specified.\n");
368 exit(EXIT_FAILURE);
369 }
370 id = create_pool(name, start_addr, end_addr, timeout);
371 printf("allocating %d addresses... ", count);
372 fflush(stdout);
373 /* run population in a transaction for sqlite */
374 begin_transaction();
375 while (TRUE)
376 {
377 db->execute(db, NULL,
378 "INSERT INTO addresses (pool, address, identity, acquired, released) "
379 "VALUES (?, ?, ?, ?, ?)",
380 DB_UINT, id, DB_BLOB, cur_addr, DB_UINT, 0, DB_UINT, 0, DB_UINT, 1);
381 if (chunk_equals(cur_addr, end_addr))
382 {
383 break;
384 }
385 chunk_increment(cur_addr);
386 }
387 commit_transaction();
388 printf("done.\n");
389 }
390
391 static bool add_address(u_int pool_id, char *address_str, int *family)
392 {
393 host_t *address;
394 int user_id = 0;
395
396 char *pos_eq = strchr(address_str, '=');
397 if (pos_eq != NULL)
398 {
399 identification_t *id = identification_create_from_string(pos_eq + 1);
400 user_id = get_identity(id);
401 id->destroy(id);
402
403 if (user_id == 0)
404 {
405 return FALSE;
406 }
407 *pos_eq = '\0';
408 }
409
410 address = host_create_from_string(address_str, 0);
411 if (address == NULL)
412 {
413 fprintf(stderr, "invalid address '%s'.\n", address_str);
414 return FALSE;
415 }
416 if (family && *family != AF_UNSPEC &&
417 *family != address->get_family(address))
418 {
419 fprintf(stderr, "invalid address family '%s'.\n", address_str);
420 address->destroy(address);
421 return FALSE;
422 }
423
424 if (db->execute(db, NULL,
425 "INSERT INTO addresses "
426 "(pool, address, identity, acquired, released) "
427 "VALUES (?, ?, ?, ?, ?)",
428 DB_UINT, pool_id, DB_BLOB, address->get_address(address),
429 DB_UINT, user_id, DB_UINT, 0, DB_UINT, 1) != 1)
430 {
431 fprintf(stderr, "inserting address '%s' failed.\n", address_str);
432 address->destroy(address);
433 return FALSE;
434 }
435 if (family)
436 {
437 *family = address->get_family(address);
438 }
439 address->destroy(address);
440
441 return TRUE;
442 }
443
444 static void add_addresses(char *pool, char *path, int timeout)
445 {
446 u_int pool_id, count = 0;
447 int family = AF_UNSPEC;
448 char address_str[512];
449 host_t *addr;
450 FILE *file;
451
452 /* run population in a transaction for sqlite */
453 begin_transaction();
454
455 addr = host_create_from_string("%any", 0);
456 pool_id = create_pool(pool, addr->get_address(addr),
457 addr->get_address(addr), timeout);
458 addr->destroy(addr);
459
460 file = (strcmp(path, "-") == 0 ? stdin : fopen(path, "r"));
461 if (file == NULL)
462 {
463 fprintf(stderr, "opening '%s' failed: %s\n", path, strerror(errno));
464 exit(-1);
465 }
466
467 printf("starting allocation... ");
468 fflush(stdout);
469
470 while (fgets(address_str, sizeof(address_str), file))
471 {
472 size_t addr_len = strlen(address_str);
473 char *last_chr = address_str + addr_len - 1;
474 if (*last_chr == '\n')
475 {
476 if (addr_len == 1)
477 { /* end of input */
478 break;
479 }
480 *last_chr = '\0';
481 }
482 if (add_address(pool_id, address_str, &family) == FALSE)
483 {
484 if (file != stdin)
485 {
486 fclose(file);
487 }
488 exit(EXIT_FAILURE);
489 }
490 ++count;
491 }
492
493 if (file != stdin)
494 {
495 fclose(file);
496 }
497
498 commit_transaction();
499
500 printf("%d addresses done.\n", count);
501 }
502
503 /**
504 * ipsec pool --del - delete a pool
505 */
506 static void del(char *name)
507 {
508 enumerator_t *query;
509 u_int id;
510 bool found = FALSE;
511
512 query = db->query(db, "SELECT id FROM pools WHERE name = ?",
513 DB_TEXT, name, DB_UINT);
514 if (!query)
515 {
516 fprintf(stderr, "deleting pool failed.\n");
517 exit(EXIT_FAILURE);
518 }
519 while (query->enumerate(query, &id))
520 {
521 found = TRUE;
522 if (db->execute(db, NULL,
523 "DELETE FROM leases WHERE address IN ("
524 " SELECT id FROM addresses WHERE pool = ?)", DB_UINT, id) < 0 ||
525 db->execute(db, NULL,
526 "DELETE FROM addresses WHERE pool = ?", DB_UINT, id) < 0 ||
527 db->execute(db, NULL,
528 "DELETE FROM pools WHERE id = ?", DB_UINT, id) < 0)
529 {
530 fprintf(stderr, "deleting pool failed.\n");
531 query->destroy(query);
532 exit(EXIT_FAILURE);
533 }
534 }
535 query->destroy(query);
536 if (!found)
537 {
538 fprintf(stderr, "pool '%s' not found.\n", name);
539 exit(EXIT_FAILURE);
540 }
541 }
542
543 /**
544 * ipsec pool --resize - resize a pool
545 */
546 static void resize(char *name, host_t *end)
547 {
548 enumerator_t *query;
549 chunk_t old_addr, new_addr, cur_addr;
550 u_int id, count;
551 host_t *old_end;
552
553 new_addr = end->get_address(end);
554
555 query = db->query(db, "SELECT id, end FROM pools WHERE name = ?",
556 DB_TEXT, name, DB_UINT, DB_BLOB);
557 if (!query || !query->enumerate(query, &id, &old_addr))
558 {
559 DESTROY_IF(query);
560 fprintf(stderr, "resizing pool failed.\n");
561 exit(EXIT_FAILURE);
562 }
563 if (old_addr.len != new_addr.len ||
564 memcmp(new_addr.ptr, old_addr.ptr, old_addr.len) < 0)
565 {
566 fprintf(stderr, "shrinking of pools not supported.\n");
567 query->destroy(query);
568 exit(EXIT_FAILURE);
569 }
570 cur_addr = chunk_clonea(old_addr);
571 count = get_pool_size(old_addr, new_addr) - 1;
572 query->destroy(query);
573
574 /* Check whether pool is resizable */
575 old_end = host_create_from_chunk(AF_UNSPEC, old_addr, 0);
576 if (old_end && old_end->is_anyaddr(old_end))
577 {
578 fprintf(stderr, "pool is not resizable.\n");
579 old_end->destroy(old_end);
580 exit(EXIT_FAILURE);
581 }
582 DESTROY_IF(old_end);
583
584 if (db->execute(db, NULL,
585 "UPDATE pools SET end = ? WHERE name = ?",
586 DB_BLOB, new_addr, DB_TEXT, name) <= 0)
587 {
588 fprintf(stderr, "pool '%s' not found.\n", name);
589 exit(EXIT_FAILURE);
590 }
591
592 printf("allocating %d new addresses... ", count);
593 fflush(stdout);
594 /* run population in a transaction for sqlite */
595 begin_transaction();
596 while (count-- > 0)
597 {
598 chunk_increment(cur_addr);
599 db->execute(db, NULL,
600 "INSERT INTO addresses (pool, address, identity, acquired, released) "
601 "VALUES (?, ?, ?, ?, ?)",
602 DB_UINT, id, DB_BLOB, cur_addr, DB_UINT, 0, DB_UINT, 0, DB_UINT, 1);
603 }
604 commit_transaction();
605 printf("done.\n");
606
607 }
608
609 /**
610 * create the lease query using the filter string
611 */
612 static enumerator_t *create_lease_query(char *filter)
613 {
614 enumerator_t *query;
615 identification_t *id = NULL;
616 host_t *addr = NULL;
617 u_int tstamp = 0;
618 bool online = FALSE, valid = FALSE, expired = FALSE;
619 char *value, *pos, *pool = NULL;
620 enum {
621 FIL_POOL = 0,
622 FIL_ID,
623 FIL_ADDR,
624 FIL_TSTAMP,
625 FIL_STATE,
626 };
627 char *const token[] = {
628 [FIL_POOL] = "pool",
629 [FIL_ID] = "id",
630 [FIL_ADDR] = "addr",
631 [FIL_TSTAMP] = "tstamp",
632 [FIL_STATE] = "status",
633 NULL
634 };
635
636 /* if the filter string contains a distinguished name as a ID, we replace
637 * ", " by "/ " in order to not confuse the getsubopt parser */
638 pos = filter;
639 while ((pos = strchr(pos, ',')))
640 {
641 if (pos[1] == ' ')
642 {
643 pos[0] = '/';
644 }
645 pos++;
646 }
647
648 while (filter && *filter != '\0')
649 {
650 switch (getsubopt(&filter, token, &value))
651 {
652 case FIL_POOL:
653 if (value)
654 {
655 pool = value;
656 }
657 break;
658 case FIL_ID:
659 if (value)
660 {
661 id = identification_create_from_string(value);
662 }
663 break;
664 case FIL_ADDR:
665 if (value)
666 {
667 addr = host_create_from_string(value, 0);
668 }
669 if (!addr)
670 {
671 fprintf(stderr, "invalid 'addr' in filter string.\n");
672 exit(EXIT_FAILURE);
673 }
674 break;
675 case FIL_TSTAMP:
676 if (value)
677 {
678 tstamp = atoi(value);
679 }
680 if (tstamp == 0)
681 {
682 online = TRUE;
683 }
684 break;
685 case FIL_STATE:
686 if (value)
687 {
688 if (streq(value, "online"))
689 {
690 online = TRUE;
691 }
692 else if (streq(value, "valid"))
693 {
694 valid = TRUE;
695 }
696 else if (streq(value, "expired"))
697 {
698 expired = TRUE;
699 }
700 else
701 {
702 fprintf(stderr, "invalid 'state' in filter string.\n");
703 exit(EXIT_FAILURE);
704 }
705 }
706 break;
707 default:
708 fprintf(stderr, "invalid filter string.\n");
709 exit(EXIT_FAILURE);
710 break;
711 }
712 }
713 query = db->query(db,
714 "SELECT name, addresses.address, identities.type, "
715 "identities.data, leases.acquired, leases.released, timeout "
716 "FROM leases JOIN addresses ON leases.address = addresses.id "
717 "JOIN pools ON addresses.pool = pools.id "
718 "JOIN identities ON leases.identity = identities.id "
719 "WHERE (? OR name = ?) "
720 "AND (? OR (identities.type = ? AND identities.data = ?)) "
721 "AND (? OR addresses.address = ?) "
722 "AND (? OR (? >= leases.acquired AND (? <= leases.released))) "
723 "AND (? OR leases.released > ? - timeout) "
724 "AND (? OR leases.released < ? - timeout) "
725 "AND ? "
726 "UNION "
727 "SELECT name, address, identities.type, identities.data, "
728 "acquired, released, timeout FROM addresses "
729 "JOIN pools ON addresses.pool = pools.id "
730 "JOIN identities ON addresses.identity = identities.id "
731 "WHERE ? AND released = 0 "
732 "AND (? OR name = ?) "
733 "AND (? OR (identities.type = ? AND identities.data = ?)) "
734 "AND (? OR address = ?)",
735 DB_INT, pool == NULL, DB_TEXT, pool,
736 DB_INT, id == NULL,
737 DB_INT, id ? id->get_type(id) : 0,
738 DB_BLOB, id ? id->get_encoding(id) : chunk_empty,
739 DB_INT, addr == NULL,
740 DB_BLOB, addr ? addr->get_address(addr) : chunk_empty,
741 DB_INT, tstamp == 0, DB_UINT, tstamp, DB_UINT, tstamp,
742 DB_INT, !valid, DB_INT, time(NULL),
743 DB_INT, !expired, DB_INT, time(NULL),
744 DB_INT, !online,
745 /* union */
746 DB_INT, !(valid || expired),
747 DB_INT, pool == NULL, DB_TEXT, pool,
748 DB_INT, id == NULL,
749 DB_INT, id ? id->get_type(id) : 0,
750 DB_BLOB, id ? id->get_encoding(id) : chunk_empty,
751 DB_INT, addr == NULL,
752 DB_BLOB, addr ? addr->get_address(addr) : chunk_empty,
753 /* res */
754 DB_TEXT, DB_BLOB, DB_INT, DB_BLOB, DB_UINT, DB_UINT, DB_UINT);
755 /* id and addr leak but we can't destroy them until query is destroyed. */
756 return query;
757 }
758
759 /**
760 * ipsec pool --leases - show lease information of a pool
761 */
762 static void leases(char *filter, bool utc)
763 {
764 enumerator_t *query;
765 chunk_t address_chunk, identity_chunk;
766 int identity_type;
767 char *name;
768 u_int db_acquired, db_released, db_timeout;
769 time_t acquired, released, timeout;
770 host_t *address;
771 identification_t *identity;
772 bool found = FALSE;
773
774 query = create_lease_query(filter);
775 if (!query)
776 {
777 fprintf(stderr, "querying leases failed.\n");
778 exit(EXIT_FAILURE);
779 }
780 while (query->enumerate(query, &name, &address_chunk, &identity_type,
781 &identity_chunk, &db_acquired, &db_released, &db_timeout))
782 {
783 if (!found)
784 {
785 int len = utc ? 25 : 21;
786
787 found = TRUE;
788 printf("%-8s %-15s %-7s %-*s %-*s %s\n",
789 "name", "address", "status", len, "start", len, "end", "identity");
790 }
791 address = host_create_from_chunk(AF_UNSPEC, address_chunk, 0);
792 identity = identification_create_from_encoding(identity_type, identity_chunk);
793
794 /* u_int is not always equal to time_t */
795 acquired = (time_t)db_acquired;
796 released = (time_t)db_released;
797 timeout = (time_t)db_timeout;
798
799 printf("%-8s %-15H ", name, address);
800 if (released == 0)
801 {
802 printf("%-7s ", "online");
803 }
804 else if (timeout == 0)
805 {
806 printf("%-7s ", "static");
807 }
808 else if (released >= time(NULL) - timeout)
809 {
810 printf("%-7s ", "valid");
811 }
812 else
813 {
814 printf("%-7s ", "expired");
815 }
816
817 printf(" %T ", &acquired, utc);
818 if (released)
819 {
820 printf("%T ", &released, utc);
821 }
822 else
823 {
824 printf(" ");
825 if (utc)
826 {
827 printf(" ");
828 }
829 }
830 printf("%Y\n", identity);
831 DESTROY_IF(address);
832 identity->destroy(identity);
833 }
834 query->destroy(query);
835 if (!found)
836 {
837 fprintf(stderr, "no matching leases found.\n");
838 exit(EXIT_FAILURE);
839 }
840 }
841
842 /**
843 * ipsec pool --purge - delete expired leases
844 */
845 static void purge(char *name)
846 {
847 int purged = 0;
848
849 purged = db->execute(db, NULL,
850 "DELETE FROM leases WHERE address IN ("
851 " SELECT id FROM addresses WHERE pool IN ("
852 " SELECT id FROM pools WHERE name = ?))",
853 DB_TEXT, name);
854 if (purged < 0)
855 {
856 fprintf(stderr, "purging pool '%s' failed.\n", name);
857 exit(EXIT_FAILURE);
858 }
859 fprintf(stderr, "purged %d leases in pool '%s'.\n", purged, name);
860 }
861
862 #define ARGV_SIZE 32
863
864 static void argv_add(char **argv, int argc, char *value)
865 {
866 if (argc >= ARGV_SIZE)
867 {
868 fprintf(stderr, "too many arguments: %s\n", value);
869 exit(EXIT_FAILURE);
870 }
871 argv[argc] = value;
872 }
873
874 /**
875 * ipsec pool --batch - read commands from a file
876 */
877 static void batch(char *argv0, char *name)
878 {
879 char command[512];
880
881 FILE *file = strncmp(name, "-", 1) == 0 ? stdin : fopen(name, "r");
882 if (file == NULL)
883 {
884 fprintf(stderr, "opening '%s' failed: %s\n", name, strerror(errno));
885 exit(EXIT_FAILURE);
886 }
887
888 begin_transaction();
889 while (fgets(command, sizeof(command), file))
890 {
891 char *argv[ARGV_SIZE], *start;
892 int i, argc = 0;
893 size_t cmd_len = strlen(command);
894
895 /* ignore empty lines */
896 if (cmd_len == 1 && *(command + cmd_len - 1) == '\n')
897 {
898 continue;
899 }
900
901 /* parse command into argv */
902 start = command;
903 argv_add(argv, argc++, argv0);
904 for (i = 0; i < cmd_len; ++i)
905 {
906 if (command[i] == ' ' || command[i] == '\n')
907 {
908 if (command + i == start)
909 {
910 /* ignore leading whitespace */
911 ++start;
912 continue;
913 }
914 command[i] = '\0';
915 argv_add(argv, argc++, start);
916 start = command + i + 1;
917 }
918 }
919 if (strlen(start) > 0)
920 {
921 argv_add(argv, argc++, start);
922 }
923 argv_add(argv, argc, NULL);
924
925 do_args(argc, argv);
926 }
927 commit_transaction();
928
929 if (file != stdin)
930 {
931 fclose(file);
932 }
933 }
934
935 /**
936 * atexit handler to close db on shutdown
937 */
938 static void cleanup(void)
939 {
940 db->destroy(db);
941 DESTROY_IF(start);
942 DESTROY_IF(end);
943 }
944
945 static void do_args(int argc, char *argv[])
946 {
947 char *name = "", *value = "", *filter = "";
948 char *pool = NULL, *identity = NULL, *addresses = NULL;
949 value_type_t value_type = VALUE_NONE;
950 int timeout = 0;
951 bool utc = FALSE, hexout = FALSE;
952
953 enum {
954 OP_UNDEF,
955 OP_USAGE,
956 OP_STATUS,
957 OP_STATUS_ATTR,
958 OP_ADD,
959 OP_ADD_ATTR,
960 OP_DEL,
961 OP_DEL_ATTR,
962 OP_SHOW_ATTR,
963 OP_RESIZE,
964 OP_LEASES,
965 OP_PURGE,
966 OP_BATCH
967 } operation = OP_UNDEF;
968
969 /* reinit getopt state */
970 optind = 0;
971
972 while (TRUE)
973 {
974 int c;
975
976 struct option long_opts[] = {
977 { "help", no_argument, NULL, 'h' },
978
979 { "utc", no_argument, NULL, 'u' },
980 { "status", no_argument, NULL, 'w' },
981 { "add", required_argument, NULL, 'a' },
982 { "replace", required_argument, NULL, 'c' },
983 { "del", required_argument, NULL, 'd' },
984 { "resize", required_argument, NULL, 'r' },
985 { "leases", no_argument, NULL, 'l' },
986 { "purge", required_argument, NULL, 'p' },
987 { "statusattr", no_argument, NULL, '1' },
988 { "addattr", required_argument, NULL, '2' },
989 { "delattr", required_argument, NULL, '3' },
990 { "showattr", no_argument, NULL, '4' },
991 { "batch", required_argument, NULL, 'b' },
992
993 { "start", required_argument, NULL, 's' },
994 { "end", required_argument, NULL, 'e' },
995 { "addresses", required_argument, NULL, 'y' },
996 { "timeout", required_argument, NULL, 't' },
997 { "filter", required_argument, NULL, 'f' },
998 { "addr", required_argument, NULL, 'v' },
999 { "mask", required_argument, NULL, 'v' },
1000 { "server", required_argument, NULL, 'v' },
1001 { "subnet", required_argument, NULL, 'n' },
1002 { "string", required_argument, NULL, 'g' },
1003 { "hex", required_argument, NULL, 'x' },
1004 { "hexout", no_argument, NULL, '5' },
1005 { "pool", required_argument, NULL, '6' },
1006 { "identity", required_argument, NULL, '7' },
1007 { 0,0,0,0 }
1008 };
1009
1010 c = getopt_long(argc, argv, "", long_opts, NULL);
1011 switch (c)
1012 {
1013 case EOF:
1014 break;
1015 case 'h':
1016 operation = OP_USAGE;
1017 break;
1018 case 'w':
1019 operation = OP_STATUS;
1020 break;
1021 case '1':
1022 operation = OP_STATUS_ATTR;
1023 break;
1024 case 'u':
1025 utc = TRUE;
1026 continue;
1027 case 'c':
1028 replace_pool = TRUE;
1029 /* fallthrough */
1030 case 'a':
1031 name = optarg;
1032 operation = is_attribute(name) ? OP_ADD_ATTR : OP_ADD;
1033 if (replace_pool && operation == OP_ADD_ATTR)
1034 {
1035 fprintf(stderr, "invalid pool name: "
1036 "reserved for '%s' attribute.\n", optarg);
1037 usage();
1038 exit(EXIT_FAILURE);
1039 }
1040 continue;
1041 case '2':
1042 name = optarg;
1043 operation = OP_ADD_ATTR;
1044 continue;
1045 case 'd':
1046 name = optarg;
1047 operation = is_attribute(name) ? OP_DEL_ATTR : OP_DEL;
1048 continue;
1049 case '3':
1050 name = optarg;
1051 operation = OP_DEL_ATTR;
1052 continue;
1053 case '4':
1054 operation = OP_SHOW_ATTR;
1055 continue;
1056 case 'r':
1057 name = optarg;
1058 operation = OP_RESIZE;
1059 continue;
1060 case 'l':
1061 operation = OP_LEASES;
1062 continue;
1063 case 'p':
1064 name = optarg;
1065 operation = OP_PURGE;
1066 continue;
1067 case 'b':
1068 name = optarg;
1069 if (operation == OP_BATCH)
1070 {
1071 fprintf(stderr, "--batch commands can not be nested\n");
1072 exit(EXIT_FAILURE);
1073 }
1074 operation = OP_BATCH;
1075 continue;
1076 case 's':
1077 DESTROY_IF(start);
1078 start = host_create_from_string(optarg, 0);
1079 if (start == NULL)
1080 {
1081 fprintf(stderr, "invalid start address: '%s'.\n", optarg);
1082 usage();
1083 exit(EXIT_FAILURE);
1084 }
1085 continue;
1086 case 'e':
1087 DESTROY_IF(end);
1088 end = host_create_from_string(optarg, 0);
1089 if (end == NULL)
1090 {
1091 fprintf(stderr, "invalid end address: '%s'.\n", optarg);
1092 usage();
1093 exit(EXIT_FAILURE);
1094 }
1095 continue;
1096 case 't':
1097 timeout = atoi(optarg);
1098 if (timeout == 0 && strcmp(optarg, "0") != 0)
1099 {
1100 fprintf(stderr, "invalid timeout '%s'.\n", optarg);
1101 usage();
1102 exit(EXIT_FAILURE);
1103 }
1104 continue;
1105 case 'f':
1106 filter = optarg;
1107 continue;
1108 case 'y':
1109 addresses = optarg;
1110 continue;
1111 case 'g':
1112 value_type = VALUE_STRING;
1113 value = optarg;
1114 continue;
1115 case 'n':
1116 value_type = VALUE_SUBNET;
1117 value = optarg;
1118 continue;
1119 case 'v':
1120 value_type = VALUE_ADDR;
1121 value = optarg;
1122 continue;
1123 case 'x':
1124 value_type = VALUE_HEX;
1125 value = optarg;
1126 continue;
1127 case '5':
1128 hexout = TRUE;
1129 continue;
1130 case '6':
1131 pool = optarg;
1132 continue;
1133 case '7':
1134 identity = optarg;
1135 continue;
1136 default:
1137 usage();
1138 exit(EXIT_FAILURE);
1139 break;
1140 }
1141 break;
1142 }
1143
1144 switch (operation)
1145 {
1146 case OP_USAGE:
1147 usage();
1148 break;
1149 case OP_STATUS:
1150 status();
1151 break;
1152 case OP_STATUS_ATTR:
1153 status_attr(hexout);
1154 break;
1155 case OP_ADD:
1156 if (addresses != NULL)
1157 {
1158 add_addresses(name, addresses, timeout);
1159 }
1160 else if (start != NULL && end != NULL)
1161 {
1162 add(name, start, end, timeout);
1163 }
1164 else
1165 {
1166 fprintf(stderr, "missing arguments.\n");
1167 usage();
1168 exit(EXIT_FAILURE);
1169 }
1170 break;
1171 case OP_ADD_ATTR:
1172 if (value_type == VALUE_NONE)
1173 {
1174 fprintf(stderr, "missing arguments.\n");
1175 usage();
1176 exit(EXIT_FAILURE);
1177 }
1178 if (identity && !pool)
1179 {
1180 fprintf(stderr, "--identity option can't be used without --pool.\n");
1181 usage();
1182 exit(EXIT_FAILURE);
1183 }
1184 add_attr(name, pool, identity, value, value_type);
1185 break;
1186 case OP_DEL:
1187 del(name);
1188 break;
1189 case OP_DEL_ATTR:
1190 if (identity && !pool)
1191 {
1192 fprintf(stderr, "--identity option can't be used without --pool.\n");
1193 usage();
1194 exit(EXIT_FAILURE);
1195 }
1196 del_attr(name, pool, identity, value, value_type);
1197 break;
1198 case OP_SHOW_ATTR:
1199 show_attr();
1200 break;
1201 case OP_RESIZE:
1202 if (end == NULL)
1203 {
1204 fprintf(stderr, "missing arguments.\n");
1205 usage();
1206 exit(EXIT_FAILURE);
1207 }
1208 resize(name, end);
1209 break;
1210 case OP_LEASES:
1211 leases(filter, utc);
1212 break;
1213 case OP_PURGE:
1214 purge(name);
1215 break;
1216 case OP_BATCH:
1217 if (name == NULL)
1218 {
1219 fprintf(stderr, "missing arguments.\n");
1220 usage();
1221 exit(EXIT_FAILURE);
1222 }
1223 batch(argv[0], name);
1224 break;
1225 default:
1226 usage();
1227 exit(EXIT_FAILURE);
1228 }
1229 }
1230
1231 int main(int argc, char *argv[])
1232 {
1233 char *uri;
1234
1235 atexit(library_deinit);
1236
1237 /* initialize library */
1238 if (!library_init(NULL))
1239 {
1240 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
1241 }
1242 if (lib->integrity &&
1243 !lib->integrity->check_file(lib->integrity, "pool", argv[0]))
1244 {
1245 fprintf(stderr, "integrity check of pool failed\n");
1246 exit(SS_RC_DAEMON_INTEGRITY);
1247 }
1248 if (!lib->plugins->load(lib->plugins, NULL,
1249 lib->settings->get_str(lib->settings, "pool.load", PLUGINS)))
1250 {
1251 exit(SS_RC_INITIALIZATION_FAILED);
1252 }
1253
1254 uri = lib->settings->get_str(lib->settings, "libhydra.plugins.attr-sql.database", NULL);
1255 if (!uri)
1256 {
1257 fprintf(stderr, "database URI libhydra.plugins.attr-sql.database not set.\n");
1258 exit(SS_RC_INITIALIZATION_FAILED);
1259 }
1260 db = lib->db->create(lib->db, uri);
1261 if (!db)
1262 {
1263 fprintf(stderr, "opening database failed.\n");
1264 exit(SS_RC_INITIALIZATION_FAILED);
1265 }
1266 atexit(cleanup);
1267
1268 do_args(argc, argv);
1269
1270 exit(EXIT_SUCCESS);
1271 }
1272