attr-sql: Handle concurrent insertion of identities
[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 <utils/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 if (family == AF_INET6)
499 { /* update address family if necessary */
500 addr = host_create_from_string("%any6", 0);
501 if (db->execute(db, NULL,
502 "UPDATE pools SET start = ?, end = ? WHERE id = ?",
503 DB_BLOB, addr->get_address(addr),
504 DB_BLOB, addr->get_address(addr), DB_UINT, pool_id) <= 0)
505 {
506 addr->destroy(addr);
507 fprintf(stderr, "updating pool address family failed.\n");
508 exit(EXIT_FAILURE);
509 }
510 addr->destroy(addr);
511 }
512
513 commit_transaction();
514
515 printf("%d addresses done.\n", count);
516 }
517
518 /**
519 * ipsec pool --del - delete a pool
520 */
521 static void del(char *name)
522 {
523 enumerator_t *query;
524 u_int id;
525 bool found = FALSE;
526
527 query = db->query(db, "SELECT id FROM pools WHERE name = ?",
528 DB_TEXT, name, DB_UINT);
529 if (!query)
530 {
531 fprintf(stderr, "deleting pool failed.\n");
532 exit(EXIT_FAILURE);
533 }
534 while (query->enumerate(query, &id))
535 {
536 found = TRUE;
537 if (db->execute(db, NULL,
538 "DELETE FROM leases WHERE address IN ("
539 " SELECT id FROM addresses WHERE pool = ?)", DB_UINT, id) < 0 ||
540 db->execute(db, NULL,
541 "DELETE FROM addresses WHERE pool = ?", DB_UINT, id) < 0 ||
542 db->execute(db, NULL,
543 "DELETE FROM pools WHERE id = ?", DB_UINT, id) < 0)
544 {
545 fprintf(stderr, "deleting pool failed.\n");
546 query->destroy(query);
547 exit(EXIT_FAILURE);
548 }
549 }
550 query->destroy(query);
551 if (!found)
552 {
553 fprintf(stderr, "pool '%s' not found.\n", name);
554 exit(EXIT_FAILURE);
555 }
556 }
557
558 /**
559 * ipsec pool --resize - resize a pool
560 */
561 static void resize(char *name, host_t *end)
562 {
563 enumerator_t *query;
564 chunk_t old_addr, new_addr, cur_addr;
565 u_int id, count;
566 host_t *old_end;
567
568 new_addr = end->get_address(end);
569
570 query = db->query(db, "SELECT id, end FROM pools WHERE name = ?",
571 DB_TEXT, name, DB_UINT, DB_BLOB);
572 if (!query || !query->enumerate(query, &id, &old_addr))
573 {
574 DESTROY_IF(query);
575 fprintf(stderr, "resizing pool failed.\n");
576 exit(EXIT_FAILURE);
577 }
578 if (old_addr.len != new_addr.len ||
579 memcmp(new_addr.ptr, old_addr.ptr, old_addr.len) < 0)
580 {
581 fprintf(stderr, "shrinking of pools not supported.\n");
582 query->destroy(query);
583 exit(EXIT_FAILURE);
584 }
585 cur_addr = chunk_clonea(old_addr);
586 count = get_pool_size(old_addr, new_addr) - 1;
587 query->destroy(query);
588
589 /* Check whether pool is resizable */
590 old_end = host_create_from_chunk(AF_UNSPEC, old_addr, 0);
591 if (old_end && old_end->is_anyaddr(old_end))
592 {
593 fprintf(stderr, "pool is not resizable.\n");
594 old_end->destroy(old_end);
595 exit(EXIT_FAILURE);
596 }
597 DESTROY_IF(old_end);
598
599 if (db->execute(db, NULL,
600 "UPDATE pools SET end = ? WHERE name = ?",
601 DB_BLOB, new_addr, DB_TEXT, name) <= 0)
602 {
603 fprintf(stderr, "pool '%s' not found.\n", name);
604 exit(EXIT_FAILURE);
605 }
606
607 printf("allocating %d new addresses... ", count);
608 fflush(stdout);
609 /* run population in a transaction for sqlite */
610 begin_transaction();
611 while (count-- > 0)
612 {
613 chunk_increment(cur_addr);
614 db->execute(db, NULL,
615 "INSERT INTO addresses (pool, address, identity, acquired, released) "
616 "VALUES (?, ?, ?, ?, ?)",
617 DB_UINT, id, DB_BLOB, cur_addr, DB_UINT, 0, DB_UINT, 0, DB_UINT, 1);
618 }
619 commit_transaction();
620 printf("done.\n");
621
622 }
623
624 /**
625 * create the lease query using the filter string
626 */
627 static enumerator_t *create_lease_query(char *filter)
628 {
629 enumerator_t *query;
630 identification_t *id = NULL;
631 host_t *addr = NULL;
632 u_int tstamp = 0;
633 bool online = FALSE, valid = FALSE, expired = FALSE;
634 char *value, *pos, *pool = NULL;
635 enum {
636 FIL_POOL = 0,
637 FIL_ID,
638 FIL_ADDR,
639 FIL_TSTAMP,
640 FIL_STATE,
641 };
642 char *const token[] = {
643 [FIL_POOL] = "pool",
644 [FIL_ID] = "id",
645 [FIL_ADDR] = "addr",
646 [FIL_TSTAMP] = "tstamp",
647 [FIL_STATE] = "status",
648 NULL
649 };
650
651 /* if the filter string contains a distinguished name as a ID, we replace
652 * ", " by "/ " in order to not confuse the getsubopt parser */
653 pos = filter;
654 while ((pos = strchr(pos, ',')))
655 {
656 if (pos[1] == ' ')
657 {
658 pos[0] = '/';
659 }
660 pos++;
661 }
662
663 while (filter && *filter != '\0')
664 {
665 switch (getsubopt(&filter, token, &value))
666 {
667 case FIL_POOL:
668 if (value)
669 {
670 pool = value;
671 }
672 break;
673 case FIL_ID:
674 if (value)
675 {
676 id = identification_create_from_string(value);
677 }
678 break;
679 case FIL_ADDR:
680 if (value)
681 {
682 addr = host_create_from_string(value, 0);
683 }
684 if (!addr)
685 {
686 fprintf(stderr, "invalid 'addr' in filter string.\n");
687 exit(EXIT_FAILURE);
688 }
689 break;
690 case FIL_TSTAMP:
691 if (value)
692 {
693 tstamp = atoi(value);
694 }
695 if (tstamp == 0)
696 {
697 online = TRUE;
698 }
699 break;
700 case FIL_STATE:
701 if (value)
702 {
703 if (streq(value, "online"))
704 {
705 online = TRUE;
706 }
707 else if (streq(value, "valid"))
708 {
709 valid = TRUE;
710 }
711 else if (streq(value, "expired"))
712 {
713 expired = TRUE;
714 }
715 else
716 {
717 fprintf(stderr, "invalid 'state' in filter string.\n");
718 exit(EXIT_FAILURE);
719 }
720 }
721 break;
722 default:
723 fprintf(stderr, "invalid filter string.\n");
724 exit(EXIT_FAILURE);
725 break;
726 }
727 }
728 query = db->query(db,
729 "SELECT name, addresses.address, identities.type, "
730 "identities.data, leases.acquired, leases.released, timeout "
731 "FROM leases JOIN addresses ON leases.address = addresses.id "
732 "JOIN pools ON addresses.pool = pools.id "
733 "JOIN identities ON leases.identity = identities.id "
734 "WHERE (? OR name = ?) "
735 "AND (? OR (identities.type = ? AND identities.data = ?)) "
736 "AND (? OR addresses.address = ?) "
737 "AND (? OR (? >= leases.acquired AND (? <= leases.released))) "
738 "AND (? OR leases.released > ? - timeout) "
739 "AND (? OR leases.released < ? - timeout) "
740 "AND ? "
741 "UNION "
742 "SELECT name, address, identities.type, identities.data, "
743 "acquired, released, timeout FROM addresses "
744 "JOIN pools ON addresses.pool = pools.id "
745 "JOIN identities ON addresses.identity = identities.id "
746 "WHERE ? AND released = 0 "
747 "AND (? OR name = ?) "
748 "AND (? OR (identities.type = ? AND identities.data = ?)) "
749 "AND (? OR address = ?)",
750 DB_INT, pool == NULL, DB_TEXT, pool,
751 DB_INT, id == NULL,
752 DB_INT, id ? id->get_type(id) : 0,
753 DB_BLOB, id ? id->get_encoding(id) : chunk_empty,
754 DB_INT, addr == NULL,
755 DB_BLOB, addr ? addr->get_address(addr) : chunk_empty,
756 DB_INT, tstamp == 0, DB_UINT, tstamp, DB_UINT, tstamp,
757 DB_INT, !valid, DB_INT, time(NULL),
758 DB_INT, !expired, DB_INT, time(NULL),
759 DB_INT, !online,
760 /* union */
761 DB_INT, !(valid || expired),
762 DB_INT, pool == NULL, DB_TEXT, pool,
763 DB_INT, id == NULL,
764 DB_INT, id ? id->get_type(id) : 0,
765 DB_BLOB, id ? id->get_encoding(id) : chunk_empty,
766 DB_INT, addr == NULL,
767 DB_BLOB, addr ? addr->get_address(addr) : chunk_empty,
768 /* res */
769 DB_TEXT, DB_BLOB, DB_INT, DB_BLOB, DB_UINT, DB_UINT, DB_UINT);
770 /* id and addr leak but we can't destroy them until query is destroyed. */
771 return query;
772 }
773
774 /**
775 * ipsec pool --leases - show lease information of a pool
776 */
777 static void leases(char *filter, bool utc)
778 {
779 enumerator_t *query;
780 chunk_t address_chunk, identity_chunk;
781 int identity_type;
782 char *name;
783 u_int db_acquired, db_released, db_timeout;
784 time_t acquired, released, timeout;
785 host_t *address;
786 identification_t *identity;
787 bool found = FALSE;
788
789 query = create_lease_query(filter);
790 if (!query)
791 {
792 fprintf(stderr, "querying leases failed.\n");
793 exit(EXIT_FAILURE);
794 }
795 while (query->enumerate(query, &name, &address_chunk, &identity_type,
796 &identity_chunk, &db_acquired, &db_released, &db_timeout))
797 {
798 if (!found)
799 {
800 int len = utc ? 25 : 21;
801
802 found = TRUE;
803 printf("%-8s %-15s %-7s %-*s %-*s %s\n",
804 "name", "address", "status", len, "start", len, "end", "identity");
805 }
806 address = host_create_from_chunk(AF_UNSPEC, address_chunk, 0);
807 identity = identification_create_from_encoding(identity_type, identity_chunk);
808
809 /* u_int is not always equal to time_t */
810 acquired = (time_t)db_acquired;
811 released = (time_t)db_released;
812 timeout = (time_t)db_timeout;
813
814 printf("%-8s %-15H ", name, address);
815 if (released == 0)
816 {
817 printf("%-7s ", "online");
818 }
819 else if (timeout == 0)
820 {
821 printf("%-7s ", "static");
822 }
823 else if (released >= time(NULL) - timeout)
824 {
825 printf("%-7s ", "valid");
826 }
827 else
828 {
829 printf("%-7s ", "expired");
830 }
831
832 printf(" %T ", &acquired, utc);
833 if (released)
834 {
835 printf("%T ", &released, utc);
836 }
837 else
838 {
839 printf(" ");
840 if (utc)
841 {
842 printf(" ");
843 }
844 }
845 printf("%Y\n", identity);
846 DESTROY_IF(address);
847 identity->destroy(identity);
848 }
849 query->destroy(query);
850 if (!found)
851 {
852 fprintf(stderr, "no matching leases found.\n");
853 exit(EXIT_FAILURE);
854 }
855 }
856
857 /**
858 * ipsec pool --purge - delete expired leases
859 */
860 static void purge(char *name)
861 {
862 int purged = 0;
863
864 purged = db->execute(db, NULL,
865 "DELETE FROM leases WHERE address IN ("
866 " SELECT id FROM addresses WHERE pool IN ("
867 " SELECT id FROM pools WHERE name = ?))",
868 DB_TEXT, name);
869 if (purged < 0)
870 {
871 fprintf(stderr, "purging pool '%s' failed.\n", name);
872 exit(EXIT_FAILURE);
873 }
874 fprintf(stderr, "purged %d leases in pool '%s'.\n", purged, name);
875 }
876
877 #define ARGV_SIZE 32
878
879 static void argv_add(char **argv, int argc, char *value)
880 {
881 if (argc >= ARGV_SIZE)
882 {
883 fprintf(stderr, "too many arguments: %s\n", value);
884 exit(EXIT_FAILURE);
885 }
886 argv[argc] = value;
887 }
888
889 /**
890 * ipsec pool --batch - read commands from a file
891 */
892 static void batch(char *argv0, char *name)
893 {
894 char command[512];
895
896 FILE *file = strncmp(name, "-", 1) == 0 ? stdin : fopen(name, "r");
897 if (file == NULL)
898 {
899 fprintf(stderr, "opening '%s' failed: %s\n", name, strerror(errno));
900 exit(EXIT_FAILURE);
901 }
902
903 begin_transaction();
904 while (fgets(command, sizeof(command), file))
905 {
906 char *argv[ARGV_SIZE], *start;
907 int i, argc = 0;
908 size_t cmd_len = strlen(command);
909
910 /* ignore empty lines */
911 if (cmd_len == 1 && *(command + cmd_len - 1) == '\n')
912 {
913 continue;
914 }
915
916 /* parse command into argv */
917 start = command;
918 argv_add(argv, argc++, argv0);
919 for (i = 0; i < cmd_len; ++i)
920 {
921 if (command[i] == ' ' || command[i] == '\n')
922 {
923 if (command + i == start)
924 {
925 /* ignore leading whitespace */
926 ++start;
927 continue;
928 }
929 command[i] = '\0';
930 argv_add(argv, argc++, start);
931 start = command + i + 1;
932 }
933 }
934 if (strlen(start) > 0)
935 {
936 argv_add(argv, argc++, start);
937 }
938 argv_add(argv, argc, NULL);
939
940 do_args(argc, argv);
941 }
942 commit_transaction();
943
944 if (file != stdin)
945 {
946 fclose(file);
947 }
948 }
949
950 /**
951 * atexit handler to close db on shutdown
952 */
953 static void cleanup(void)
954 {
955 db->destroy(db);
956 DESTROY_IF(start);
957 DESTROY_IF(end);
958 }
959
960 static void do_args(int argc, char *argv[])
961 {
962 char *name = "", *value = "", *filter = "";
963 char *pool = NULL, *identity = NULL, *addresses = NULL;
964 value_type_t value_type = VALUE_NONE;
965 int timeout = 0;
966 bool utc = FALSE, hexout = FALSE;
967
968 enum {
969 OP_UNDEF,
970 OP_USAGE,
971 OP_STATUS,
972 OP_STATUS_ATTR,
973 OP_ADD,
974 OP_ADD_ATTR,
975 OP_DEL,
976 OP_DEL_ATTR,
977 OP_SHOW_ATTR,
978 OP_RESIZE,
979 OP_LEASES,
980 OP_PURGE,
981 OP_BATCH
982 } operation = OP_UNDEF;
983
984 /* reinit getopt state */
985 optind = 0;
986
987 while (TRUE)
988 {
989 int c;
990
991 struct option long_opts[] = {
992 { "help", no_argument, NULL, 'h' },
993
994 { "utc", no_argument, NULL, 'u' },
995 { "status", no_argument, NULL, 'w' },
996 { "add", required_argument, NULL, 'a' },
997 { "replace", required_argument, NULL, 'c' },
998 { "del", required_argument, NULL, 'd' },
999 { "resize", required_argument, NULL, 'r' },
1000 { "leases", no_argument, NULL, 'l' },
1001 { "purge", required_argument, NULL, 'p' },
1002 { "statusattr", no_argument, NULL, '1' },
1003 { "addattr", required_argument, NULL, '2' },
1004 { "delattr", required_argument, NULL, '3' },
1005 { "showattr", no_argument, NULL, '4' },
1006 { "batch", required_argument, NULL, 'b' },
1007
1008 { "start", required_argument, NULL, 's' },
1009 { "end", required_argument, NULL, 'e' },
1010 { "addresses", required_argument, NULL, 'y' },
1011 { "timeout", required_argument, NULL, 't' },
1012 { "filter", required_argument, NULL, 'f' },
1013 { "addr", required_argument, NULL, 'v' },
1014 { "mask", required_argument, NULL, 'v' },
1015 { "server", required_argument, NULL, 'v' },
1016 { "subnet", required_argument, NULL, 'n' },
1017 { "string", required_argument, NULL, 'g' },
1018 { "hex", required_argument, NULL, 'x' },
1019 { "hexout", no_argument, NULL, '5' },
1020 { "pool", required_argument, NULL, '6' },
1021 { "identity", required_argument, NULL, '7' },
1022 { 0,0,0,0 }
1023 };
1024
1025 c = getopt_long(argc, argv, "", long_opts, NULL);
1026 switch (c)
1027 {
1028 case EOF:
1029 break;
1030 case 'h':
1031 operation = OP_USAGE;
1032 break;
1033 case 'w':
1034 operation = OP_STATUS;
1035 break;
1036 case '1':
1037 operation = OP_STATUS_ATTR;
1038 break;
1039 case 'u':
1040 utc = TRUE;
1041 continue;
1042 case 'c':
1043 replace_pool = TRUE;
1044 /* fallthrough */
1045 case 'a':
1046 name = optarg;
1047 operation = is_attribute(name) ? OP_ADD_ATTR : OP_ADD;
1048 if (replace_pool && operation == OP_ADD_ATTR)
1049 {
1050 fprintf(stderr, "invalid pool name: "
1051 "reserved for '%s' attribute.\n", optarg);
1052 usage();
1053 exit(EXIT_FAILURE);
1054 }
1055 continue;
1056 case '2':
1057 name = optarg;
1058 operation = OP_ADD_ATTR;
1059 continue;
1060 case 'd':
1061 name = optarg;
1062 operation = is_attribute(name) ? OP_DEL_ATTR : OP_DEL;
1063 continue;
1064 case '3':
1065 name = optarg;
1066 operation = OP_DEL_ATTR;
1067 continue;
1068 case '4':
1069 operation = OP_SHOW_ATTR;
1070 continue;
1071 case 'r':
1072 name = optarg;
1073 operation = OP_RESIZE;
1074 continue;
1075 case 'l':
1076 operation = OP_LEASES;
1077 continue;
1078 case 'p':
1079 name = optarg;
1080 operation = OP_PURGE;
1081 continue;
1082 case 'b':
1083 name = optarg;
1084 if (operation == OP_BATCH)
1085 {
1086 fprintf(stderr, "--batch commands can not be nested\n");
1087 exit(EXIT_FAILURE);
1088 }
1089 operation = OP_BATCH;
1090 continue;
1091 case 's':
1092 DESTROY_IF(start);
1093 start = host_create_from_string(optarg, 0);
1094 if (start == NULL)
1095 {
1096 fprintf(stderr, "invalid start address: '%s'.\n", optarg);
1097 usage();
1098 exit(EXIT_FAILURE);
1099 }
1100 continue;
1101 case 'e':
1102 DESTROY_IF(end);
1103 end = host_create_from_string(optarg, 0);
1104 if (end == NULL)
1105 {
1106 fprintf(stderr, "invalid end address: '%s'.\n", optarg);
1107 usage();
1108 exit(EXIT_FAILURE);
1109 }
1110 continue;
1111 case 't':
1112 timeout = atoi(optarg);
1113 if (timeout == 0 && strcmp(optarg, "0") != 0)
1114 {
1115 fprintf(stderr, "invalid timeout '%s'.\n", optarg);
1116 usage();
1117 exit(EXIT_FAILURE);
1118 }
1119 continue;
1120 case 'f':
1121 filter = optarg;
1122 continue;
1123 case 'y':
1124 addresses = optarg;
1125 continue;
1126 case 'g':
1127 value_type = VALUE_STRING;
1128 value = optarg;
1129 continue;
1130 case 'n':
1131 value_type = VALUE_SUBNET;
1132 value = optarg;
1133 continue;
1134 case 'v':
1135 value_type = VALUE_ADDR;
1136 value = optarg;
1137 continue;
1138 case 'x':
1139 value_type = VALUE_HEX;
1140 value = optarg;
1141 continue;
1142 case '5':
1143 hexout = TRUE;
1144 continue;
1145 case '6':
1146 pool = optarg;
1147 continue;
1148 case '7':
1149 identity = optarg;
1150 continue;
1151 default:
1152 usage();
1153 exit(EXIT_FAILURE);
1154 break;
1155 }
1156 break;
1157 }
1158
1159 switch (operation)
1160 {
1161 case OP_USAGE:
1162 usage();
1163 break;
1164 case OP_STATUS:
1165 status();
1166 break;
1167 case OP_STATUS_ATTR:
1168 status_attr(hexout);
1169 break;
1170 case OP_ADD:
1171 if (addresses != NULL)
1172 {
1173 add_addresses(name, addresses, timeout);
1174 }
1175 else if (start != NULL && end != NULL)
1176 {
1177 add(name, start, end, timeout);
1178 }
1179 else
1180 {
1181 fprintf(stderr, "missing arguments.\n");
1182 usage();
1183 exit(EXIT_FAILURE);
1184 }
1185 break;
1186 case OP_ADD_ATTR:
1187 if (value_type == VALUE_NONE)
1188 {
1189 fprintf(stderr, "missing arguments.\n");
1190 usage();
1191 exit(EXIT_FAILURE);
1192 }
1193 if (identity && !pool)
1194 {
1195 fprintf(stderr, "--identity option can't be used without --pool.\n");
1196 usage();
1197 exit(EXIT_FAILURE);
1198 }
1199 add_attr(name, pool, identity, value, value_type);
1200 break;
1201 case OP_DEL:
1202 del(name);
1203 break;
1204 case OP_DEL_ATTR:
1205 if (identity && !pool)
1206 {
1207 fprintf(stderr, "--identity option can't be used without --pool.\n");
1208 usage();
1209 exit(EXIT_FAILURE);
1210 }
1211 del_attr(name, pool, identity, value, value_type);
1212 break;
1213 case OP_SHOW_ATTR:
1214 show_attr();
1215 break;
1216 case OP_RESIZE:
1217 if (end == NULL)
1218 {
1219 fprintf(stderr, "missing arguments.\n");
1220 usage();
1221 exit(EXIT_FAILURE);
1222 }
1223 resize(name, end);
1224 break;
1225 case OP_LEASES:
1226 leases(filter, utc);
1227 break;
1228 case OP_PURGE:
1229 purge(name);
1230 break;
1231 case OP_BATCH:
1232 if (name == NULL)
1233 {
1234 fprintf(stderr, "missing arguments.\n");
1235 usage();
1236 exit(EXIT_FAILURE);
1237 }
1238 batch(argv[0], name);
1239 break;
1240 default:
1241 usage();
1242 exit(EXIT_FAILURE);
1243 }
1244 }
1245
1246 int main(int argc, char *argv[])
1247 {
1248 char *uri;
1249
1250 atexit(library_deinit);
1251
1252 /* initialize library */
1253 if (!library_init(NULL))
1254 {
1255 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
1256 }
1257 if (lib->integrity &&
1258 !lib->integrity->check_file(lib->integrity, "pool", argv[0]))
1259 {
1260 fprintf(stderr, "integrity check of pool failed\n");
1261 exit(SS_RC_DAEMON_INTEGRITY);
1262 }
1263 if (!lib->plugins->load(lib->plugins,
1264 lib->settings->get_str(lib->settings, "pool.load", PLUGINS)))
1265 {
1266 exit(SS_RC_INITIALIZATION_FAILED);
1267 }
1268
1269 uri = lib->settings->get_str(lib->settings, "libhydra.plugins.attr-sql.database", NULL);
1270 if (!uri)
1271 {
1272 fprintf(stderr, "database URI libhydra.plugins.attr-sql.database not set.\n");
1273 exit(SS_RC_INITIALIZATION_FAILED);
1274 }
1275 db = lib->db->create(lib->db, uri);
1276 if (!db)
1277 {
1278 fprintf(stderr, "opening database failed.\n");
1279 exit(SS_RC_INITIALIZATION_FAILED);
1280 }
1281 atexit(cleanup);
1282
1283 do_args(argc, argv);
1284
1285 exit(EXIT_SUCCESS);
1286 }
1287