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