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