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