]> git.ipfire.org Git - thirdparty/openvpn.git/blob - src/openvpn/manage.c
Replace custom min macro and use more C99 style in man_remote_entry_get
[thirdparty/openvpn.git] / src / openvpn / manage.c
1 /*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
7 *
8 * Copyright (C) 2002-2022 OpenVPN Inc <sales@openvpn.net>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 */
23
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #elif defined(_MSC_VER)
27 #include "config-msvc.h"
28 #endif
29
30 #include "syshead.h"
31
32 #ifdef ENABLE_MANAGEMENT
33
34 #include "error.h"
35 #include "fdmisc.h"
36 #include "options.h"
37 #include "sig.h"
38 #include "event.h"
39 #include "otime.h"
40 #include "integer.h"
41 #include "misc.h"
42 #include "ssl.h"
43 #include "common.h"
44 #include "manage.h"
45 #include "openvpn.h"
46 #include "dco.h"
47
48 #include "memdbg.h"
49
50 #ifdef ENABLE_PKCS11
51 #include "pkcs11.h"
52 #endif
53
54 #define MANAGEMENT_ECHO_PULL_INFO 0
55
56 #if MANAGEMENT_ECHO_PULL_INFO
57 #define MANAGEMENT_ECHO_FLAGS LOG_PRINT_INTVAL
58 #else
59 #define MANAGEMENT_ECHO_FLAGS 0
60 #endif
61
62 /* tag for blank username/password */
63 static const char blank_up[] = "[[BLANK]]";
64
65 struct management *management; /* GLOBAL */
66
67 /* static forward declarations */
68 static void man_output_standalone(struct management *man, volatile int *signal_received);
69
70 static void man_reset_client_socket(struct management *man, const bool exiting);
71
72 static void
73 man_help(void)
74 {
75 msg(M_CLIENT, "Management Interface for %s", title_string);
76 msg(M_CLIENT, "Commands:");
77 msg(M_CLIENT, "auth-retry t : Auth failure retry mode (none,interact,nointeract).");
78 msg(M_CLIENT, "bytecount n : Show bytes in/out, update every n secs (0=off).");
79 msg(M_CLIENT, "echo [on|off] [N|all] : Like log, but only show messages in echo buffer.");
80 msg(M_CLIENT, "cr-response response : Send a challenge response answer via CR_RESPONSE to server");
81 msg(M_CLIENT, "exit|quit : Close management session.");
82 msg(M_CLIENT, "forget-passwords : Forget passwords entered so far.");
83 msg(M_CLIENT, "help : Print this message.");
84 msg(M_CLIENT, "hold [on|off|release] : Set/show hold flag to on/off state, or");
85 msg(M_CLIENT, " release current hold and start tunnel.");
86 msg(M_CLIENT, "kill cn : Kill the client instance(s) having common name cn.");
87 msg(M_CLIENT, "kill IP:port : Kill the client instance connecting from IP:port.");
88 msg(M_CLIENT, "load-stats : Show global server load stats.");
89 msg(M_CLIENT, "log [on|off] [N|all] : Turn on/off realtime log display");
90 msg(M_CLIENT, " + show last N lines or 'all' for entire history.");
91 msg(M_CLIENT, "mute [n] : Set log mute level to n, or show level if n is absent.");
92 msg(M_CLIENT, "needok type action : Enter confirmation for NEED-OK request of 'type',");
93 msg(M_CLIENT, " where action = 'ok' or 'cancel'.");
94 msg(M_CLIENT, "needstr type action : Enter confirmation for NEED-STR request of 'type',");
95 msg(M_CLIENT, " where action is reply string.");
96 msg(M_CLIENT, "net : (Windows only) Show network info and routing table.");
97 msg(M_CLIENT, "password type p : Enter password p for a queried OpenVPN password.");
98 msg(M_CLIENT, "remote type [host port] : Override remote directive, type=ACCEPT|MOD|SKIP.");
99 msg(M_CLIENT, "remote-entry-count : Get number of available remote entries.");
100 msg(M_CLIENT, "remote-entry-get i|all [j]: Get remote entry at index = i to to j-1 or all.");
101 msg(M_CLIENT, "proxy type [host port flags] : Enter dynamic proxy server info.");
102 msg(M_CLIENT, "pid : Show process ID of the current OpenVPN process.");
103 #ifdef ENABLE_PKCS11
104 msg(M_CLIENT, "pkcs11-id-count : Get number of available PKCS#11 identities.");
105 msg(M_CLIENT, "pkcs11-id-get index : Get PKCS#11 identity at index.");
106 #endif
107 msg(M_CLIENT, "client-auth CID KID : Authenticate client-id/key-id CID/KID (MULTILINE)");
108 msg(M_CLIENT, "client-auth-nt CID KID : Authenticate client-id/key-id CID/KID");
109 msg(M_CLIENT, "client-deny CID KID R [CR] : Deny auth client-id/key-id CID/KID with log reason");
110 msg(M_CLIENT, " text R and optional client reason text CR");
111 msg(M_CLIENT, "client-pending-auth CID MSG timeout : Instruct OpenVPN to send AUTH_PENDING and INFO_PRE msg");
112 msg(M_CLIENT, " to the client and wait for a final client-auth/client-deny");
113 msg(M_CLIENT, "client-kill CID [M] : Kill client instance CID with message M (def=RESTART)");
114 msg(M_CLIENT, "env-filter [level] : Set env-var filter level");
115 msg(M_CLIENT, "rsa-sig : Enter a signature in response to >RSA_SIGN challenge");
116 msg(M_CLIENT, " Enter signature base64 on subsequent lines followed by END");
117 msg(M_CLIENT, "pk-sig : Enter a signature in response to >PK_SIGN challenge");
118 msg(M_CLIENT, " Enter signature base64 on subsequent lines followed by END");
119 msg(M_CLIENT, "certificate : Enter a client certificate in response to >NEED-CERT challenge");
120 msg(M_CLIENT, " Enter certificate base64 on subsequent lines followed by END");
121 msg(M_CLIENT, "signal s : Send signal s to daemon,");
122 msg(M_CLIENT, " s = SIGHUP|SIGTERM|SIGUSR1|SIGUSR2.");
123 msg(M_CLIENT, "state [on|off] [N|all] : Like log, but show state history.");
124 msg(M_CLIENT, "status [n] : Show current daemon status info using format #n.");
125 msg(M_CLIENT, "test n : Produce n lines of output for testing/debugging.");
126 msg(M_CLIENT, "username type u : Enter username u for a queried OpenVPN username.");
127 msg(M_CLIENT, "verb [n] : Set log verbosity level to n, or show if n is absent.");
128 msg(M_CLIENT, "version [n] : Set client's version to n or show current version of daemon.");
129 msg(M_CLIENT, "END");
130 }
131
132 static const char *
133 man_state_name(const int state)
134 {
135 switch (state)
136 {
137 case OPENVPN_STATE_INITIAL:
138 return "INITIAL";
139
140 case OPENVPN_STATE_CONNECTING:
141 return "CONNECTING";
142
143 case OPENVPN_STATE_WAIT:
144 return "WAIT";
145
146 case OPENVPN_STATE_AUTH:
147 return "AUTH";
148
149 case OPENVPN_STATE_GET_CONFIG:
150 return "GET_CONFIG";
151
152 case OPENVPN_STATE_ASSIGN_IP:
153 return "ASSIGN_IP";
154
155 case OPENVPN_STATE_ADD_ROUTES:
156 return "ADD_ROUTES";
157
158 case OPENVPN_STATE_CONNECTED:
159 return "CONNECTED";
160
161 case OPENVPN_STATE_RECONNECTING:
162 return "RECONNECTING";
163
164 case OPENVPN_STATE_EXITING:
165 return "EXITING";
166
167 case OPENVPN_STATE_RESOLVE:
168 return "RESOLVE";
169
170 case OPENVPN_STATE_TCP_CONNECT:
171 return "TCP_CONNECT";
172
173 case OPENVPN_STATE_AUTH_PENDING:
174 return "AUTH_PENDING";
175
176 default:
177 return "?";
178 }
179 }
180
181 static void
182 man_welcome(struct management *man)
183 {
184 msg(M_CLIENT, ">INFO:OpenVPN Management Interface Version %d -- type 'help' for more info",
185 MANAGEMENT_VERSION);
186 if (man->persist.special_state_msg)
187 {
188 msg(M_CLIENT, "%s", man->persist.special_state_msg);
189 }
190 }
191
192 static inline bool
193 man_password_needed(struct management *man)
194 {
195 return man->settings.up.defined && !man->connection.password_verified;
196 }
197
198 static void
199 man_check_password(struct management *man, const char *line)
200 {
201 if (man_password_needed(man))
202 {
203 /* This comparison is not fixed time but since strlen(time) is based on
204 * the attacker choice, it should not give any indication of the real
205 * password length, use + 1 to include the NUL byte that terminates the
206 * string*/
207 size_t compare_len = min_uint(strlen(line) + 1, sizeof(man->settings.up.password));
208 if (memcmp_constant_time(line, man->settings.up.password, compare_len) == 0)
209 {
210 man->connection.password_verified = true;
211 msg(M_CLIENT, "SUCCESS: password is correct");
212 man_welcome(man);
213 }
214 else
215 {
216 man->connection.password_verified = false;
217 msg(M_CLIENT, "ERROR: bad password");
218 if (++man->connection.password_tries >= MANAGEMENT_N_PASSWORD_RETRIES)
219 {
220 msg(M_WARN, "MAN: client connection rejected after %d failed password attempts",
221 MANAGEMENT_N_PASSWORD_RETRIES);
222 man->connection.halt = true;
223 }
224 }
225 }
226 }
227
228 static void
229 man_update_io_state(struct management *man)
230 {
231 if (socket_defined(man->connection.sd_cli))
232 {
233 if (buffer_list_defined(man->connection.out))
234 {
235 man->connection.state = MS_CC_WAIT_WRITE;
236 }
237 else
238 {
239 man->connection.state = MS_CC_WAIT_READ;
240 }
241 }
242 }
243
244 static void
245 man_output_list_push_finalize(struct management *man)
246 {
247 if (management_connected(man))
248 {
249 man_update_io_state(man);
250 if (!man->persist.standalone_disabled)
251 {
252 volatile int signal_received = 0;
253 man_output_standalone(man, &signal_received);
254 }
255 }
256 }
257
258 static void
259 man_output_list_push_str(struct management *man, const char *str)
260 {
261 if (management_connected(man) && str)
262 {
263 buffer_list_push(man->connection.out, str);
264 }
265 }
266
267 static void
268 man_output_list_push(struct management *man, const char *str)
269 {
270 man_output_list_push_str(man, str);
271 man_output_list_push_finalize(man);
272 }
273
274 static void
275 man_prompt(struct management *man)
276 {
277 if (man_password_needed(man))
278 {
279 man_output_list_push(man, "ENTER PASSWORD:");
280 }
281 #if 0 /* should we use prompt? */
282 else
283 {
284 man_output_list_push(man, ">");
285 }
286 #endif
287 }
288
289 static void
290 man_delete_unix_socket(struct management *man)
291 {
292 #if UNIX_SOCK_SUPPORT
293 if ((man->settings.flags & (MF_UNIX_SOCK|MF_CONNECT_AS_CLIENT)) == MF_UNIX_SOCK)
294 {
295 socket_delete_unix(&man->settings.local_unix);
296 }
297 #endif
298 }
299
300 static void
301 man_close_socket(struct management *man, const socket_descriptor_t sd)
302 {
303 #ifndef _WIN32
304 /*
305 * Windows doesn't need this because the ne32 event is permanently
306 * enabled at struct management scope.
307 */
308 if (man->persist.callback.delete_event)
309 {
310 (*man->persist.callback.delete_event)(man->persist.callback.arg, sd);
311 }
312 #endif
313 openvpn_close_socket(sd);
314 }
315
316 static void
317 virtual_output_callback_func(void *arg, const unsigned int flags, const char *str)
318 {
319 struct management *man = (struct management *) arg;
320 static int recursive_level = 0; /* GLOBAL */
321
322 #define AF_DID_PUSH (1<<0)
323 #define AF_DID_RESET (1<<1)
324 if (recursive_level < 5) /* limit recursion */
325 {
326 struct gc_arena gc = gc_new();
327 struct log_entry e;
328 const char *out = NULL;
329 unsigned int action_flags = 0;
330
331 ++recursive_level;
332
333 CLEAR(e);
334 update_time();
335 e.timestamp = now;
336 e.u.msg_flags = flags;
337 e.string = str;
338
339 if (flags & M_FATAL)
340 {
341 man->persist.standalone_disabled = false;
342 }
343
344 if (flags != M_CLIENT)
345 {
346 log_history_add(man->persist.log, &e);
347 }
348
349 if (!man_password_needed(man))
350 {
351 if (flags == M_CLIENT)
352 {
353 out = log_entry_print(&e, LOG_PRINT_CRLF, &gc);
354 }
355 else if (man->connection.log_realtime)
356 {
357 out = log_entry_print(&e, LOG_PRINT_INT_DATE
358 | LOG_PRINT_MSG_FLAGS
359 | LOG_PRINT_LOG_PREFIX
360 | LOG_PRINT_CRLF, &gc);
361 }
362 if (out)
363 {
364 man_output_list_push_str(man, out);
365 action_flags |= AF_DID_PUSH;
366 }
367 if (flags & M_FATAL)
368 {
369 out = log_entry_print(&e, LOG_FATAL_NOTIFY|LOG_PRINT_CRLF, &gc);
370 if (out)
371 {
372 man_output_list_push_str(man, out);
373 action_flags |= (AF_DID_PUSH|AF_DID_RESET);
374 }
375 }
376 }
377
378 gc_free(&gc);
379
380 if (action_flags & AF_DID_PUSH)
381 {
382 man_output_list_push_finalize(man);
383 }
384 if (action_flags & AF_DID_RESET)
385 {
386 man_reset_client_socket(man, true);
387 }
388
389 --recursive_level;
390 }
391 else
392 {
393 /* cannot use msg here */
394 printf("virtual_output: message to management interface "
395 "dropped due to recursion: <%s>\n", str);
396 }
397 }
398
399 /*
400 * Given a signal, return the signal with possible remapping applied,
401 * or -1 if the signal should be ignored.
402 */
403 static int
404 man_mod_signal(const struct management *man, const int signum)
405 {
406 const unsigned int flags = man->settings.mansig;
407 int s = signum;
408 if (s == SIGUSR1)
409 {
410 if (flags & MANSIG_MAP_USR1_TO_HUP)
411 {
412 s = SIGHUP;
413 }
414 if (flags & MANSIG_MAP_USR1_TO_TERM)
415 {
416 s = SIGTERM;
417 }
418 }
419 if (flags & MANSIG_IGNORE_USR1_HUP)
420 {
421 if (s == SIGHUP || s == SIGUSR1)
422 {
423 s = -1;
424 }
425 }
426 return s;
427 }
428
429 static void
430 man_signal(struct management *man, const char *name)
431 {
432 const int sig = parse_signal(name);
433 if (sig >= 0)
434 {
435 const int sig_mod = man_mod_signal(man, sig);
436 if (sig_mod >= 0)
437 {
438 throw_signal(sig_mod);
439 msg(M_CLIENT, "SUCCESS: signal %s thrown", signal_name(sig_mod, true));
440 }
441 else
442 {
443 msg(M_CLIENT, "ERROR: signal '%s' is currently ignored", name);
444 if (man->persist.special_state_msg)
445 {
446 msg(M_CLIENT, "%s", man->persist.special_state_msg);
447 }
448 }
449 }
450 else
451 {
452 msg(M_CLIENT, "ERROR: signal '%s' is not a known signal type", name);
453 }
454 }
455
456 static void
457 man_command_unsupported(const char *command_name)
458 {
459 msg(M_CLIENT, "ERROR: The '%s' command is not supported by the current daemon mode", command_name);
460 }
461
462 static void
463 man_status(struct management *man, const int version, struct status_output *so)
464 {
465 if (man->persist.callback.status)
466 {
467 (*man->persist.callback.status)(man->persist.callback.arg, version, so);
468 }
469 else
470 {
471 man_command_unsupported("status");
472 }
473 }
474
475 static void
476 man_bytecount(struct management *man, const int update_seconds)
477 {
478 if (update_seconds > 0)
479 {
480 man->connection.bytecount_update_seconds = update_seconds;
481 event_timeout_init(&man->connection.bytecount_update_interval,
482 man->connection.bytecount_update_seconds,
483 now);
484 }
485 else
486 {
487 man->connection.bytecount_update_seconds = 0;
488 event_timeout_clear(&man->connection.bytecount_update_interval);
489 }
490 msg(M_CLIENT, "SUCCESS: bytecount interval changed");
491 }
492
493 static void
494 man_bytecount_output_client(struct management *man,
495 counter_type dco_read_bytes,
496 counter_type dco_write_bytes)
497 {
498 char in[32];
499 char out[32];
500
501 /* do in a roundabout way to work around possible mingw or mingw-glibc bug */
502 openvpn_snprintf(in, sizeof(in), counter_format, man->persist.bytes_in + dco_read_bytes);
503 openvpn_snprintf(out, sizeof(out), counter_format, man->persist.bytes_out + dco_write_bytes);
504 msg(M_CLIENT, ">BYTECOUNT:%s,%s", in, out);
505 }
506
507 void
508 man_bytecount_output_server(const counter_type *bytes_in_total,
509 const counter_type *bytes_out_total,
510 struct man_def_auth_context *mdac)
511 {
512 char in[32];
513 char out[32];
514 /* do in a roundabout way to work around possible mingw or mingw-glibc bug */
515 openvpn_snprintf(in, sizeof(in), counter_format, *bytes_in_total);
516 openvpn_snprintf(out, sizeof(out), counter_format, *bytes_out_total);
517 msg(M_CLIENT, ">BYTECOUNT_CLI:%lu,%s,%s", mdac->cid, in, out);
518 mdac->bytecount_last_update = now;
519 }
520
521 static void
522 man_kill(struct management *man, const char *victim)
523 {
524 struct gc_arena gc = gc_new();
525
526 if (man->persist.callback.kill_by_cn && man->persist.callback.kill_by_addr)
527 {
528 struct buffer buf;
529 char p1[128];
530 char p2[128];
531 int n_killed;
532
533 buf_set_read(&buf, (uint8_t *) victim, strlen(victim) + 1);
534 buf_parse(&buf, ':', p1, sizeof(p1));
535 buf_parse(&buf, ':', p2, sizeof(p2));
536
537 if (strlen(p1) && strlen(p2))
538 {
539 /* IP:port specified */
540 bool status;
541 const in_addr_t addr = getaddr(GETADDR_HOST_ORDER|GETADDR_MSG_VIRT_OUT, p1, 0, &status, NULL);
542 if (status)
543 {
544 const int port = atoi(p2);
545 if (port > 0 && port < 65536)
546 {
547 n_killed = (*man->persist.callback.kill_by_addr)(man->persist.callback.arg, addr, port);
548 if (n_killed > 0)
549 {
550 msg(M_CLIENT, "SUCCESS: %d client(s) at address %s:%d killed",
551 n_killed,
552 print_in_addr_t(addr, 0, &gc),
553 port);
554 }
555 else
556 {
557 msg(M_CLIENT, "ERROR: client at address %s:%d not found",
558 print_in_addr_t(addr, 0, &gc),
559 port);
560 }
561 }
562 else
563 {
564 msg(M_CLIENT, "ERROR: port number is out of range: %s", p2);
565 }
566 }
567 else
568 {
569 msg(M_CLIENT, "ERROR: error parsing IP address: %s", p1);
570 }
571 }
572 else if (strlen(p1))
573 {
574 /* common name specified */
575 n_killed = (*man->persist.callback.kill_by_cn)(man->persist.callback.arg, p1);
576 if (n_killed > 0)
577 {
578 msg(M_CLIENT, "SUCCESS: common name '%s' found, %d client(s) killed", p1, n_killed);
579 }
580 else
581 {
582 msg(M_CLIENT, "ERROR: common name '%s' not found", p1);
583 }
584 }
585 else
586 {
587 msg(M_CLIENT, "ERROR: kill parse");
588 }
589 }
590 else
591 {
592 man_command_unsupported("kill");
593 }
594
595 gc_free(&gc);
596 }
597
598 /*
599 * General-purpose history command handler
600 * for the log and echo commands.
601 */
602 static void
603 man_history(struct management *man,
604 const char *parm,
605 const char *type,
606 struct log_history *log,
607 bool *realtime,
608 const unsigned int lep_flags)
609 {
610 struct gc_arena gc = gc_new();
611 int n = 0;
612
613 if (streq(parm, "on"))
614 {
615 *realtime = true;
616 msg(M_CLIENT, "SUCCESS: real-time %s notification set to ON", type);
617 }
618 else if (streq(parm, "off"))
619 {
620 *realtime = false;
621 msg(M_CLIENT, "SUCCESS: real-time %s notification set to OFF", type);
622 }
623 else if (streq(parm, "all") || (n = atoi(parm)) > 0)
624 {
625 const int size = log_history_size(log);
626 const int start = (n ? n : size) - 1;
627 int i;
628
629 for (i = start; i >= 0; --i)
630 {
631 const struct log_entry *e = log_history_ref(log, i);
632 if (e)
633 {
634 const char *out = log_entry_print(e, lep_flags, &gc);
635 virtual_output_callback_func(man, M_CLIENT, out);
636 }
637 }
638 msg(M_CLIENT, "END");
639 }
640 else
641 {
642 msg(M_CLIENT, "ERROR: %s parameter must be 'on' or 'off' or some number n or 'all'", type);
643 }
644
645 gc_free(&gc);
646 }
647
648 static void
649 man_log(struct management *man, const char *parm)
650 {
651 man_history(man,
652 parm,
653 "log",
654 man->persist.log,
655 &man->connection.log_realtime,
656 LOG_PRINT_INT_DATE|LOG_PRINT_MSG_FLAGS);
657 }
658
659 static void
660 man_echo(struct management *man, const char *parm)
661 {
662 man_history(man,
663 parm,
664 "echo",
665 man->persist.echo,
666 &man->connection.echo_realtime,
667 LOG_PRINT_INT_DATE|MANAGEMENT_ECHO_FLAGS);
668 }
669
670 static void
671 man_state(struct management *man, const char *parm)
672 {
673 man_history(man,
674 parm,
675 "state",
676 man->persist.state,
677 &man->connection.state_realtime,
678 LOG_PRINT_INT_DATE|LOG_PRINT_STATE
679 |LOG_PRINT_LOCAL_IP|LOG_PRINT_REMOTE_IP);
680 }
681
682 static void
683 man_up_finalize(struct management *man)
684 {
685 switch (man->connection.up_query_mode)
686 {
687 case UP_QUERY_USER_PASS:
688 if (!strlen(man->connection.up_query.username))
689 {
690 break;
691 }
692
693 /* fall through */
694 case UP_QUERY_PASS:
695 case UP_QUERY_NEED_OK:
696 case UP_QUERY_NEED_STR:
697 if (strlen(man->connection.up_query.password))
698 {
699 man->connection.up_query.defined = true;
700 }
701 break;
702
703 case UP_QUERY_DISABLED:
704 man->connection.up_query.defined = false;
705 break;
706
707 default:
708 ASSERT(0);
709 }
710 }
711
712 static void
713 man_query_user_pass(struct management *man,
714 const char *type,
715 const char *string,
716 const bool needed,
717 const char *prompt,
718 char *dest,
719 int len)
720 {
721 if (needed)
722 {
723 ASSERT(man->connection.up_query_type);
724 if (streq(man->connection.up_query_type, type))
725 {
726 strncpynt(dest, string, len);
727 man_up_finalize(man);
728 msg(M_CLIENT, "SUCCESS: '%s' %s entered, but not yet verified",
729 type,
730 prompt);
731 }
732 else
733 {
734 msg(M_CLIENT, "ERROR: %s of type '%s' entered, but we need one of type '%s'",
735 prompt,
736 type,
737 man->connection.up_query_type);
738 }
739 }
740 else
741 {
742 msg(M_CLIENT, "ERROR: no %s is currently needed at this time", prompt);
743 }
744 }
745
746 static void
747 man_query_username(struct management *man, const char *type, const char *string)
748 {
749 const bool needed = ((man->connection.up_query_mode == UP_QUERY_USER_PASS
750 ) && man->connection.up_query_type);
751 man_query_user_pass(man, type, string, needed, "username", man->connection.up_query.username, USER_PASS_LEN);
752 }
753
754 static void
755 man_query_password(struct management *man, const char *type, const char *string)
756 {
757 const bool needed = ((man->connection.up_query_mode == UP_QUERY_PASS
758 || man->connection.up_query_mode == UP_QUERY_USER_PASS
759 ) && man->connection.up_query_type);
760 if (!string[0]) /* allow blank passwords to be passed through using the blank_up tag */
761 {
762 string = blank_up;
763 }
764 man_query_user_pass(man, type, string, needed, "password", man->connection.up_query.password, USER_PASS_LEN);
765 }
766
767 static void
768 man_query_need_ok(struct management *man, const char *type, const char *action)
769 {
770 const bool needed = ((man->connection.up_query_mode == UP_QUERY_NEED_OK) && man->connection.up_query_type);
771 man_query_user_pass(man, type, action, needed, "needok-confirmation", man->connection.up_query.password, USER_PASS_LEN);
772 }
773
774 static void
775 man_query_need_str(struct management *man, const char *type, const char *action)
776 {
777 const bool needed = ((man->connection.up_query_mode == UP_QUERY_NEED_STR) && man->connection.up_query_type);
778 man_query_user_pass(man, type, action, needed, "needstr-string", man->connection.up_query.password, USER_PASS_LEN);
779 }
780
781 static void
782 man_forget_passwords(struct management *man)
783 {
784 ssl_purge_auth(false);
785 (void)ssl_clean_auth_token();
786 msg(M_CLIENT, "SUCCESS: Passwords were forgotten");
787 }
788
789 static void
790 man_net(struct management *man)
791 {
792 if (man->persist.callback.show_net)
793 {
794 (*man->persist.callback.show_net)(man->persist.callback.arg, M_CLIENT);
795 }
796 else
797 {
798 man_command_unsupported("net");
799 }
800 }
801
802 static void
803 man_send_cc_message(struct management *man, const char *message, const char *parameters)
804 {
805 if (man->persist.callback.send_cc_message)
806 {
807 const bool status = (*man->persist.callback.send_cc_message)
808 (man->persist.callback.arg, message, parameters);
809 if (status)
810 {
811 msg(M_CLIENT, "SUCCESS: command succeeded");
812 }
813 else
814 {
815 msg(M_CLIENT, "ERROR: command failed");
816 }
817 }
818 else
819 {
820 man_command_unsupported("cr-repsonse");
821 }
822 }
823 #ifdef ENABLE_PKCS11
824
825 static void
826 man_pkcs11_id_count(struct management *man)
827 {
828 msg(M_CLIENT, ">PKCS11ID-COUNT:%d", pkcs11_management_id_count());
829 }
830
831 static void
832 man_pkcs11_id_get(struct management *man, const int index)
833 {
834 char *id = NULL;
835 char *base64 = NULL;
836
837 if (pkcs11_management_id_get(index, &id, &base64))
838 {
839 msg(M_CLIENT, ">PKCS11ID-ENTRY:'%d', ID:'%s', BLOB:'%s'", index, id, base64);
840 }
841 else
842 {
843 msg(M_CLIENT, ">PKCS11ID-ENTRY:'%d'", index);
844 }
845
846 free(id);
847 free(base64);
848 }
849
850 #endif /* ifdef ENABLE_PKCS11 */
851
852 static void
853 man_remote_entry_count(struct management *man)
854 {
855 unsigned count = 0;
856 if (man->persist.callback.remote_entry_count)
857 {
858 count = (*man->persist.callback.remote_entry_count)(man->persist.callback.arg);
859 msg(M_CLIENT, "%u", count);
860 msg(M_CLIENT, "END");
861 }
862 else
863 {
864 man_command_unsupported("remote-entry-count");
865 }
866 }
867
868 static void
869 man_remote_entry_get(struct management *man, const char *p1, const char *p2)
870 {
871 ASSERT(p1);
872
873 if (man->persist.callback.remote_entry_get
874 && man->persist.callback.remote_entry_count)
875 {
876 unsigned int count = (*man->persist.callback.remote_entry_count)(man->persist.callback.arg);
877
878 unsigned int from = (unsigned int) atoi(p1);
879 unsigned int to = p2 ? (unsigned int) atoi(p2) : from + 1;
880
881 if (!strcmp(p1, "all"))
882 {
883 from = 0;
884 to = count;
885 }
886
887 for (unsigned int i = from; i < min_uint(to, count); i++)
888 {
889 char *remote = NULL;
890 bool res = (*man->persist.callback.remote_entry_get)(man->persist.callback.arg, i, &remote);
891 if (res && remote)
892 {
893 msg(M_CLIENT, "%u,%s", i, remote);
894 }
895 free(remote);
896 }
897 msg(M_CLIENT, "END");
898 }
899 else
900 {
901 man_command_unsupported("remote-entry-get");
902 }
903 }
904
905 static void
906 man_hold(struct management *man, const char *cmd)
907 {
908 if (cmd)
909 {
910 if (streq(cmd, "on"))
911 {
912 man->settings.flags |= MF_HOLD;
913 msg(M_CLIENT, "SUCCESS: hold flag set to ON");
914 }
915 else if (streq(cmd, "off"))
916 {
917 man->settings.flags &= ~MF_HOLD;
918 msg(M_CLIENT, "SUCCESS: hold flag set to OFF");
919 }
920 else if (streq(cmd, "release"))
921 {
922 man->persist.hold_release = true;
923 msg(M_CLIENT, "SUCCESS: hold release succeeded");
924 }
925 else
926 {
927 msg(M_CLIENT, "ERROR: bad hold command parameter");
928 }
929 }
930 else
931 {
932 msg(M_CLIENT, "SUCCESS: hold=%d", BOOL_CAST(man->settings.flags & MF_HOLD));
933 }
934 }
935
936 #define IER_RESET 0
937 #define IER_NEW 1
938
939 static void
940 in_extra_reset(struct man_connection *mc, const int mode)
941 {
942 if (mc)
943 {
944 if (mode != IER_NEW)
945 {
946 mc->in_extra_cmd = IEC_UNDEF;
947 mc->in_extra_cid = 0;
948 mc->in_extra_kid = 0;
949 }
950 if (mc->in_extra)
951 {
952 buffer_list_free(mc->in_extra);
953 mc->in_extra = NULL;
954 }
955 if (mode == IER_NEW)
956 {
957 mc->in_extra = buffer_list_new();
958 }
959 }
960 }
961
962 static void
963 in_extra_dispatch(struct management *man)
964 {
965 switch (man->connection.in_extra_cmd)
966 {
967 case IEC_CLIENT_AUTH:
968 if (man->persist.callback.client_auth)
969 {
970 const bool status = (*man->persist.callback.client_auth)
971 (man->persist.callback.arg,
972 man->connection.in_extra_cid,
973 man->connection.in_extra_kid,
974 true,
975 NULL,
976 NULL,
977 man->connection.in_extra);
978 man->connection.in_extra = NULL;
979 if (status)
980 {
981 msg(M_CLIENT, "SUCCESS: client-auth command succeeded");
982 }
983 else
984 {
985 msg(M_CLIENT, "ERROR: client-auth command failed");
986 }
987 }
988 else
989 {
990 man_command_unsupported("client-auth");
991 }
992 break;
993
994 case IEC_PK_SIGN:
995 man->connection.ext_key_state = EKS_READY;
996 buffer_list_free(man->connection.ext_key_input);
997 man->connection.ext_key_input = man->connection.in_extra;
998 man->connection.in_extra = NULL;
999 return;
1000
1001 case IEC_CERTIFICATE:
1002 man->connection.ext_cert_state = EKS_READY;
1003 buffer_list_free(man->connection.ext_cert_input);
1004 man->connection.ext_cert_input = man->connection.in_extra;
1005 man->connection.in_extra = NULL;
1006 return;
1007 }
1008 in_extra_reset(&man->connection, IER_RESET);
1009 }
1010
1011 static bool
1012 parse_cid(const char *str, unsigned long *cid)
1013 {
1014 if (sscanf(str, "%lu", cid) == 1)
1015 {
1016 return true;
1017 }
1018 else
1019 {
1020 msg(M_CLIENT, "ERROR: cannot parse CID");
1021 return false;
1022 }
1023 }
1024
1025 static bool
1026 parse_uint(const char *str, const char *what, unsigned int *uint)
1027 {
1028 if (sscanf(str, "%u", uint) == 1)
1029 {
1030 return true;
1031 }
1032 else
1033 {
1034 msg(M_CLIENT, "ERROR: cannot parse %s", what);
1035 return false;
1036 }
1037 }
1038
1039 /**
1040 * Will send a notification to the client that succesful authentication
1041 * will require an additional step (web based SSO/2-factor auth/etc)
1042 *
1043 * @param man The management interface struct
1044 * @param cid_str The CID in string form
1045 * @param extra The string to be send to the client containing
1046 * the information of the additional steps
1047 */
1048 static void
1049 man_client_pending_auth(struct management *man, const char *cid_str,
1050 const char *extra, const char *timeout_str)
1051 {
1052 unsigned long cid = 0;
1053 unsigned int timeout = 0;
1054 if (parse_cid(cid_str, &cid)
1055 && parse_uint(timeout_str, "TIMEOUT", &timeout))
1056 {
1057 if (man->persist.callback.client_pending_auth)
1058 {
1059 bool ret = (*man->persist.callback.client_pending_auth)
1060 (man->persist.callback.arg, cid, extra, timeout);
1061
1062 if (ret)
1063 {
1064 msg(M_CLIENT, "SUCCESS: client-pending-auth command succeeded");
1065 }
1066 else
1067 {
1068 msg(M_CLIENT, "ERROR: client-pending-auth command failed."
1069 " Extra parameter might be too long");
1070 }
1071 }
1072 else
1073 {
1074 man_command_unsupported("client-pending-auth");
1075 }
1076 }
1077 }
1078
1079 static void
1080 man_client_auth(struct management *man, const char *cid_str, const char *kid_str, const bool extra)
1081 {
1082 struct man_connection *mc = &man->connection;
1083 mc->in_extra_cid = 0;
1084 mc->in_extra_kid = 0;
1085 if (parse_cid(cid_str, &mc->in_extra_cid)
1086 && parse_uint(kid_str, "KID", &mc->in_extra_kid))
1087 {
1088 mc->in_extra_cmd = IEC_CLIENT_AUTH;
1089 in_extra_reset(mc, IER_NEW);
1090 if (!extra)
1091 {
1092 in_extra_dispatch(man);
1093 }
1094 }
1095 }
1096
1097 static void
1098 man_client_deny(struct management *man, const char *cid_str, const char *kid_str, const char *reason, const char *client_reason)
1099 {
1100 unsigned long cid = 0;
1101 unsigned int kid = 0;
1102 if (parse_cid(cid_str, &cid) && parse_uint(kid_str, "KID", &kid))
1103 {
1104 if (man->persist.callback.client_auth)
1105 {
1106 const bool status = (*man->persist.callback.client_auth)
1107 (man->persist.callback.arg,
1108 cid,
1109 kid,
1110 false,
1111 reason,
1112 client_reason,
1113 NULL);
1114 if (status)
1115 {
1116 msg(M_CLIENT, "SUCCESS: client-deny command succeeded");
1117 }
1118 else
1119 {
1120 msg(M_CLIENT, "ERROR: client-deny command failed");
1121 }
1122 }
1123 else
1124 {
1125 man_command_unsupported("client-deny");
1126 }
1127 }
1128 }
1129
1130 static void
1131 man_client_kill(struct management *man, const char *cid_str, const char *kill_msg)
1132 {
1133 unsigned long cid = 0;
1134 if (parse_cid(cid_str, &cid))
1135 {
1136 if (man->persist.callback.kill_by_cid)
1137 {
1138 const bool status = (*man->persist.callback.kill_by_cid)(man->persist.callback.arg, cid, kill_msg);
1139 if (status)
1140 {
1141 msg(M_CLIENT, "SUCCESS: client-kill command succeeded");
1142 }
1143 else
1144 {
1145 msg(M_CLIENT, "ERROR: client-kill command failed");
1146 }
1147 }
1148 else
1149 {
1150 man_command_unsupported("client-kill");
1151 }
1152 }
1153 }
1154
1155 static void
1156 man_client_n_clients(struct management *man)
1157 {
1158 if (man->persist.callback.n_clients)
1159 {
1160 const int nclients = (*man->persist.callback.n_clients)(man->persist.callback.arg);
1161 msg(M_CLIENT, "SUCCESS: nclients=%d", nclients);
1162 }
1163 else
1164 {
1165 man_command_unsupported("nclients");
1166 }
1167 }
1168
1169 static void
1170 man_env_filter(struct management *man, const int level)
1171 {
1172 man->connection.env_filter_level = level;
1173 msg(M_CLIENT, "SUCCESS: env_filter_level=%d", level);
1174 }
1175
1176
1177 static void
1178 man_pk_sig(struct management *man, const char *cmd_name)
1179 {
1180 struct man_connection *mc = &man->connection;
1181 if (mc->ext_key_state == EKS_SOLICIT)
1182 {
1183 mc->ext_key_state = EKS_INPUT;
1184 mc->in_extra_cmd = IEC_PK_SIGN;
1185 in_extra_reset(mc, IER_NEW);
1186 }
1187 else
1188 {
1189 msg(M_CLIENT, "ERROR: The %s command is not currently available", cmd_name);
1190 }
1191 }
1192
1193 static void
1194 man_certificate(struct management *man)
1195 {
1196 struct man_connection *mc = &man->connection;
1197 if (mc->ext_cert_state == EKS_SOLICIT)
1198 {
1199 mc->ext_cert_state = EKS_INPUT;
1200 mc->in_extra_cmd = IEC_CERTIFICATE;
1201 in_extra_reset(mc, IER_NEW);
1202 }
1203 else
1204 {
1205 msg(M_CLIENT, "ERROR: The certificate command is not currently available");
1206 }
1207 }
1208
1209 static void
1210 man_load_stats(struct management *man)
1211 {
1212 extern counter_type link_read_bytes_global;
1213 extern counter_type link_write_bytes_global;
1214 int nclients = 0;
1215
1216 if (man->persist.callback.n_clients)
1217 {
1218 nclients = (*man->persist.callback.n_clients)(man->persist.callback.arg);
1219 }
1220 msg(M_CLIENT, "SUCCESS: nclients=%d,bytesin=" counter_format ",bytesout=" counter_format,
1221 nclients,
1222 link_read_bytes_global,
1223 link_write_bytes_global);
1224 }
1225
1226 #define MN_AT_LEAST (1<<0)
1227 /**
1228 * Checks if the correct number of arguments to a management command are present
1229 * and otherwise prints an error and returns false.
1230 *
1231 * @param p pointer to the parameter array
1232 * @param n number of arguments required
1233 * @param flags if MN_AT_LEAST require at least n parameters and not exactly n
1234 * @return Return whether p has n (or at least n) parameters
1235 */
1236 static bool
1237 man_need(struct management *man, const char **p, const int n, unsigned int flags)
1238 {
1239 int i;
1240 ASSERT(p[0]);
1241 for (i = 1; i <= n; ++i)
1242 {
1243 if (!p[i])
1244 {
1245 msg(M_CLIENT, "ERROR: the '%s' command requires %s%d parameter%s",
1246 p[0],
1247 (flags & MN_AT_LEAST) ? "at least " : "",
1248 n,
1249 n > 1 ? "s" : "");
1250 return false;
1251 }
1252 }
1253 return true;
1254 }
1255
1256 static void
1257 man_proxy(struct management *man, const char **p)
1258 {
1259 if (man->persist.callback.proxy_cmd)
1260 {
1261 const bool status = (*man->persist.callback.proxy_cmd)(man->persist.callback.arg, p);
1262 if (status)
1263 {
1264 msg(M_CLIENT, "SUCCESS: proxy command succeeded");
1265 }
1266 else
1267 {
1268 msg(M_CLIENT, "ERROR: proxy command failed");
1269 }
1270 }
1271 else
1272 {
1273 man_command_unsupported("proxy");
1274 }
1275 }
1276
1277 static void
1278 man_remote(struct management *man, const char **p)
1279 {
1280 if (man->persist.callback.remote_cmd)
1281 {
1282 const bool status = (*man->persist.callback.remote_cmd)(man->persist.callback.arg, p);
1283 if (status)
1284 {
1285 msg(M_CLIENT, "SUCCESS: remote command succeeded");
1286 }
1287 else
1288 {
1289 msg(M_CLIENT, "ERROR: remote command failed");
1290 }
1291 }
1292 else
1293 {
1294 man_command_unsupported("remote");
1295 }
1296 }
1297
1298 #ifdef TARGET_ANDROID
1299 static void
1300 man_network_change(struct management *man, bool samenetwork)
1301 {
1302 /* Called to signal the OpenVPN that the network configuration has changed and
1303 * the client should either float or reconnect.
1304 *
1305 * The code is currently only used by ics-openvpn
1306 */
1307 if (man->persist.callback.network_change)
1308 {
1309 int fd = (*man->persist.callback.network_change)
1310 (man->persist.callback.arg, samenetwork);
1311 man->connection.fdtosend = fd;
1312 msg(M_CLIENT, "PROTECTFD: fd '%d' sent to be protected", fd);
1313 if (fd == -2)
1314 {
1315 man_signal(man, "SIGUSR1");
1316 }
1317 }
1318 }
1319 #endif
1320
1321 static void
1322 set_client_version(struct management *man, const char *version)
1323 {
1324 if (version)
1325 {
1326 man->connection.client_version = atoi(version);
1327 }
1328 }
1329
1330 static void
1331 man_dispatch_command(struct management *man, struct status_output *so, const char **p, const int nparms)
1332 {
1333 struct gc_arena gc = gc_new();
1334
1335 ASSERT(p[0]);
1336 if (streq(p[0], "exit") || streq(p[0], "quit"))
1337 {
1338 man->connection.halt = true;
1339 goto done;
1340 }
1341 else if (streq(p[0], "help"))
1342 {
1343 man_help();
1344 }
1345 else if (streq(p[0], "version") && p[1])
1346 {
1347 set_client_version(man, p[1]);
1348 }
1349 else if (streq(p[0], "version"))
1350 {
1351 msg(M_CLIENT, "OpenVPN Version: %s", title_string);
1352 msg(M_CLIENT, "Management Version: %d", MANAGEMENT_VERSION);
1353 msg(M_CLIENT, "END");
1354 }
1355 else if (streq(p[0], "pid"))
1356 {
1357 msg(M_CLIENT, "SUCCESS: pid=%d", platform_getpid());
1358 }
1359 else if (streq(p[0], "nclients"))
1360 {
1361 man_client_n_clients(man);
1362 }
1363 else if (streq(p[0], "env-filter"))
1364 {
1365 int level = 0;
1366 if (p[1])
1367 {
1368 level = atoi(p[1]);
1369 }
1370 man_env_filter(man, level);
1371 }
1372 else if (streq(p[0], "signal"))
1373 {
1374 if (man_need(man, p, 1, 0))
1375 {
1376 man_signal(man, p[1]);
1377 }
1378 }
1379 #ifdef TARGET_ANDROID
1380 else if (streq(p[0], "network-change"))
1381 {
1382 bool samenetwork = false;
1383 if (p[1] && streq(p[1], "samenetwork"))
1384 {
1385 samenetwork = true;
1386 }
1387
1388 man_network_change(man, samenetwork);
1389 }
1390 #endif
1391 else if (streq(p[0], "load-stats"))
1392 {
1393 man_load_stats(man);
1394 }
1395 else if (streq(p[0], "status"))
1396 {
1397 int version = 0;
1398 if (p[1])
1399 {
1400 version = atoi(p[1]);
1401 }
1402 man_status(man, version, so);
1403 }
1404 else if (streq(p[0], "kill"))
1405 {
1406 if (man_need(man, p, 1, 0))
1407 {
1408 man_kill(man, p[1]);
1409 }
1410 }
1411 else if (streq(p[0], "verb"))
1412 {
1413 if (p[1])
1414 {
1415 const int level = atoi(p[1]);
1416 if (set_debug_level(level, 0))
1417 {
1418 msg(M_CLIENT, "SUCCESS: verb level changed");
1419 }
1420 else
1421 {
1422 msg(M_CLIENT, "ERROR: verb level is out of range");
1423 }
1424 }
1425 else
1426 {
1427 msg(M_CLIENT, "SUCCESS: verb=%d", get_debug_level());
1428 }
1429 }
1430 else if (streq(p[0], "mute"))
1431 {
1432 if (p[1])
1433 {
1434 const int level = atoi(p[1]);
1435 if (set_mute_cutoff(level))
1436 {
1437 msg(M_CLIENT, "SUCCESS: mute level changed");
1438 }
1439 else
1440 {
1441 msg(M_CLIENT, "ERROR: mute level is out of range");
1442 }
1443 }
1444 else
1445 {
1446 msg(M_CLIENT, "SUCCESS: mute=%d", get_mute_cutoff());
1447 }
1448 }
1449 else if (streq(p[0], "auth-retry"))
1450 {
1451 if (p[1])
1452 {
1453 if (auth_retry_set(M_CLIENT, p[1]))
1454 {
1455 msg(M_CLIENT, "SUCCESS: auth-retry parameter changed");
1456 }
1457 else
1458 {
1459 msg(M_CLIENT, "ERROR: bad auth-retry parameter");
1460 }
1461 }
1462 else
1463 {
1464 msg(M_CLIENT, "SUCCESS: auth-retry=%s", auth_retry_print());
1465 }
1466 }
1467 else if (streq(p[0], "state"))
1468 {
1469 if (!p[1])
1470 {
1471 man_state(man, "1");
1472 }
1473 else
1474 {
1475 if (p[1])
1476 {
1477 man_state(man, p[1]);
1478 }
1479 if (p[2])
1480 {
1481 man_state(man, p[2]);
1482 }
1483 }
1484 }
1485 else if (streq(p[0], "log"))
1486 {
1487 if (man_need(man, p, 1, MN_AT_LEAST))
1488 {
1489 if (p[1])
1490 {
1491 man_log(man, p[1]);
1492 }
1493 if (p[2])
1494 {
1495 man_log(man, p[2]);
1496 }
1497 }
1498 }
1499 else if (streq(p[0], "echo"))
1500 {
1501 if (man_need(man, p, 1, MN_AT_LEAST))
1502 {
1503 if (p[1])
1504 {
1505 man_echo(man, p[1]);
1506 }
1507 if (p[2])
1508 {
1509 man_echo(man, p[2]);
1510 }
1511 }
1512 }
1513 else if (streq(p[0], "username"))
1514 {
1515 if (man_need(man, p, 2, 0))
1516 {
1517 man_query_username(man, p[1], p[2]);
1518 }
1519 }
1520 else if (streq(p[0], "password"))
1521 {
1522 if (man_need(man, p, 2, 0))
1523 {
1524 man_query_password(man, p[1], p[2]);
1525 }
1526 }
1527 else if (streq(p[0], "forget-passwords"))
1528 {
1529 man_forget_passwords(man);
1530 }
1531 else if (streq(p[0], "needok"))
1532 {
1533 if (man_need(man, p, 2, 0))
1534 {
1535 man_query_need_ok(man, p[1], p[2]);
1536 }
1537 }
1538 else if (streq(p[0], "needstr"))
1539 {
1540 if (man_need(man, p, 2, 0))
1541 {
1542 man_query_need_str(man, p[1], p[2]);
1543 }
1544 }
1545 else if (streq(p[0], "cr-response"))
1546 {
1547 if (man_need(man, p, 1, 0))
1548 {
1549 man_send_cc_message(man, "CR_RESPONSE", p[1]);
1550 }
1551 }
1552 else if (streq(p[0], "net"))
1553 {
1554 man_net(man);
1555 }
1556 else if (streq(p[0], "hold"))
1557 {
1558 man_hold(man, p[1]);
1559 }
1560 else if (streq(p[0], "bytecount"))
1561 {
1562 if (man_need(man, p, 1, 0))
1563 {
1564 man_bytecount(man, atoi(p[1]));
1565 }
1566 }
1567 else if (streq(p[0], "client-kill"))
1568 {
1569 if (man_need(man, p, 1, MN_AT_LEAST))
1570 {
1571 man_client_kill(man, p[1], p[2]);
1572 }
1573 }
1574 else if (streq(p[0], "client-deny"))
1575 {
1576 if (man_need(man, p, 3, MN_AT_LEAST))
1577 {
1578 man_client_deny(man, p[1], p[2], p[3], p[4]);
1579 }
1580 }
1581 else if (streq(p[0], "client-auth-nt"))
1582 {
1583 if (man_need(man, p, 2, 0))
1584 {
1585 man_client_auth(man, p[1], p[2], false);
1586 }
1587 }
1588 else if (streq(p[0], "client-auth"))
1589 {
1590 if (man_need(man, p, 2, 0))
1591 {
1592 man_client_auth(man, p[1], p[2], true);
1593 }
1594 }
1595 else if (streq(p[0], "client-pending-auth"))
1596 {
1597 if (man_need(man, p, 3, 0))
1598 {
1599 man_client_pending_auth(man, p[1], p[2], p[3]);
1600 }
1601 }
1602 else if (streq(p[0], "rsa-sig"))
1603 {
1604 man_pk_sig(man, "rsa-sig");
1605 }
1606 else if (streq(p[0], "pk-sig"))
1607 {
1608 man_pk_sig(man, "pk-sig");
1609 }
1610 else if (streq(p[0], "certificate"))
1611 {
1612 man_certificate(man);
1613 }
1614 #ifdef ENABLE_PKCS11
1615 else if (streq(p[0], "pkcs11-id-count"))
1616 {
1617 man_pkcs11_id_count(man);
1618 }
1619 else if (streq(p[0], "pkcs11-id-get"))
1620 {
1621 if (man_need(man, p, 1, 0))
1622 {
1623 man_pkcs11_id_get(man, atoi(p[1]));
1624 }
1625 }
1626 #endif
1627 else if (streq(p[0], "remote-entry-count"))
1628 {
1629 man_remote_entry_count(man);
1630 }
1631 else if (streq(p[0], "remote-entry-get"))
1632 {
1633 if (man_need(man, p, 1, MN_AT_LEAST))
1634 {
1635 man_remote_entry_get(man, p[1], p[2]);
1636 }
1637 }
1638 else if (streq(p[0], "proxy"))
1639 {
1640 if (man_need(man, p, 1, MN_AT_LEAST))
1641 {
1642 man_proxy(man, p);
1643 }
1644 }
1645 else if (streq(p[0], "remote"))
1646 {
1647 if (man_need(man, p, 1, MN_AT_LEAST))
1648 {
1649 man_remote(man, p);
1650 }
1651 }
1652 #if 1
1653 else if (streq(p[0], "test"))
1654 {
1655 if (man_need(man, p, 1, 0))
1656 {
1657 int i;
1658 const int n = atoi(p[1]);
1659 for (i = 0; i < n; ++i)
1660 {
1661 msg(M_CLIENT, "[%d] The purpose of this command is to generate large amounts of output.", i);
1662 }
1663 }
1664 }
1665 #endif
1666 else
1667 {
1668 msg(M_CLIENT, "ERROR: unknown command, enter 'help' for more options");
1669 }
1670
1671 done:
1672 gc_free(&gc);
1673 }
1674
1675 #ifdef _WIN32
1676
1677 static void
1678 man_start_ne32(struct management *man)
1679 {
1680 switch (man->connection.state)
1681 {
1682 case MS_LISTEN:
1683 net_event_win32_start(&man->connection.ne32, FD_ACCEPT, man->connection.sd_top);
1684 break;
1685
1686 case MS_CC_WAIT_READ:
1687 case MS_CC_WAIT_WRITE:
1688 net_event_win32_start(&man->connection.ne32, FD_READ|FD_WRITE|FD_CLOSE, man->connection.sd_cli);
1689 break;
1690
1691 default:
1692 ASSERT(0);
1693 }
1694 }
1695
1696 static void
1697 man_stop_ne32(struct management *man)
1698 {
1699 net_event_win32_stop(&man->connection.ne32);
1700 }
1701
1702 #endif /* ifdef _WIN32 */
1703
1704 static void
1705 man_connection_settings_reset(struct management *man)
1706 {
1707 man->connection.state_realtime = false;
1708 man->connection.log_realtime = false;
1709 man->connection.echo_realtime = false;
1710 man->connection.bytecount_update_seconds = 0;
1711 man->connection.password_verified = false;
1712 man->connection.password_tries = 0;
1713 man->connection.halt = false;
1714 man->connection.state = MS_CC_WAIT_WRITE;
1715 }
1716
1717 static void
1718 man_new_connection_post(struct management *man, const char *description)
1719 {
1720 struct gc_arena gc = gc_new();
1721
1722 set_nonblock(man->connection.sd_cli);
1723
1724 man_connection_settings_reset(man);
1725
1726 #ifdef _WIN32
1727 man_start_ne32(man);
1728 #endif
1729
1730 #if UNIX_SOCK_SUPPORT
1731 if (man->settings.flags & MF_UNIX_SOCK)
1732 {
1733 msg(D_MANAGEMENT, "MANAGEMENT: %s %s",
1734 description,
1735 sockaddr_unix_name(&man->settings.local_unix, "NULL"));
1736 }
1737 else
1738 #endif
1739 if (man->settings.flags & MF_CONNECT_AS_CLIENT)
1740 {
1741 msg(D_MANAGEMENT, "MANAGEMENT: %s %s",
1742 description,
1743 print_sockaddr(man->settings.local->ai_addr, &gc));
1744 }
1745 else
1746 {
1747 struct sockaddr_storage addr;
1748 socklen_t addrlen = sizeof(addr);
1749 if (!getpeername(man->connection.sd_cli, (struct sockaddr *) &addr,
1750 &addrlen))
1751 {
1752 msg(D_MANAGEMENT, "MANAGEMENT: %s %s", description,
1753 print_sockaddr((struct sockaddr *) &addr, &gc));
1754 }
1755 else
1756 {
1757 msg(D_MANAGEMENT, "MANAGEMENT: %s %s", description, "unknown");
1758 }
1759 }
1760
1761 buffer_list_reset(man->connection.out);
1762
1763 if (!man_password_needed(man))
1764 {
1765 man_welcome(man);
1766 }
1767 man_prompt(man);
1768 man_update_io_state(man);
1769
1770 gc_free(&gc);
1771 }
1772
1773 #if UNIX_SOCK_SUPPORT
1774 static bool
1775 man_verify_unix_peer_uid_gid(struct management *man, const socket_descriptor_t sd)
1776 {
1777 if (socket_defined(sd) && (man->settings.client_uid != -1 || man->settings.client_gid != -1))
1778 {
1779 static const char err_prefix[] = "MANAGEMENT: unix domain socket client connection rejected --";
1780 int uid, gid;
1781 if (unix_socket_get_peer_uid_gid(man->connection.sd_cli, &uid, &gid))
1782 {
1783 if (man->settings.client_uid != -1 && man->settings.client_uid != uid)
1784 {
1785 msg(D_MANAGEMENT, "%s UID of socket peer (%d) doesn't match required value (%d) as given by --management-client-user",
1786 err_prefix, uid, man->settings.client_uid);
1787 return false;
1788 }
1789 if (man->settings.client_gid != -1 && man->settings.client_gid != gid)
1790 {
1791 msg(D_MANAGEMENT, "%s GID of socket peer (%d) doesn't match required value (%d) as given by --management-client-group",
1792 err_prefix, gid, man->settings.client_gid);
1793 return false;
1794 }
1795 }
1796 else
1797 {
1798 msg(D_MANAGEMENT, "%s cannot get UID/GID of socket peer", err_prefix);
1799 return false;
1800 }
1801 }
1802 return true;
1803 }
1804 #endif /* if UNIX_SOCK_SUPPORT */
1805
1806 static void
1807 man_accept(struct management *man)
1808 {
1809 struct link_socket_actual act;
1810 CLEAR(act);
1811
1812 /*
1813 * Accept the TCP or Unix domain socket client.
1814 */
1815 #if UNIX_SOCK_SUPPORT
1816 if (man->settings.flags & MF_UNIX_SOCK)
1817 {
1818 struct sockaddr_un remote;
1819 man->connection.sd_cli = socket_accept_unix(man->connection.sd_top, &remote);
1820 if (!man_verify_unix_peer_uid_gid(man, man->connection.sd_cli))
1821 {
1822 sd_close(&man->connection.sd_cli);
1823 }
1824 }
1825 else
1826 #endif
1827 man->connection.sd_cli = socket_do_accept(man->connection.sd_top, &act, false);
1828
1829 if (socket_defined(man->connection.sd_cli))
1830 {
1831 man->connection.remote = act.dest;
1832
1833 if (socket_defined(man->connection.sd_top))
1834 {
1835 #ifdef _WIN32
1836 man_stop_ne32(man);
1837 #endif
1838 }
1839
1840 man_new_connection_post(man, "Client connected from");
1841 }
1842 }
1843
1844 static void
1845 man_listen(struct management *man)
1846 {
1847 struct gc_arena gc = gc_new();
1848
1849 /*
1850 * Initialize state
1851 */
1852 man->connection.state = MS_LISTEN;
1853 man->connection.sd_cli = SOCKET_UNDEFINED;
1854
1855 /*
1856 * Initialize listening socket
1857 */
1858 if (man->connection.sd_top == SOCKET_UNDEFINED)
1859 {
1860 #if UNIX_SOCK_SUPPORT
1861 if (man->settings.flags & MF_UNIX_SOCK)
1862 {
1863 man_delete_unix_socket(man);
1864 man->connection.sd_top = create_socket_unix();
1865 socket_bind_unix(man->connection.sd_top, &man->settings.local_unix, "MANAGEMENT");
1866 }
1867 else
1868 #endif
1869 {
1870 man->connection.sd_top = create_socket_tcp(man->settings.local);
1871 socket_bind(man->connection.sd_top, man->settings.local,
1872 man->settings.local->ai_family, "MANAGEMENT", false);
1873 }
1874
1875 /*
1876 * Listen for connection
1877 */
1878 if (listen(man->connection.sd_top, 1))
1879 {
1880 msg(M_ERR, "MANAGEMENT: listen() failed");
1881 }
1882
1883 /*
1884 * Set misc socket properties
1885 */
1886 set_nonblock(man->connection.sd_top);
1887
1888 #if UNIX_SOCK_SUPPORT
1889 if (man->settings.flags & MF_UNIX_SOCK)
1890 {
1891 msg(D_MANAGEMENT, "MANAGEMENT: unix domain socket listening on %s",
1892 sockaddr_unix_name(&man->settings.local_unix, "NULL"));
1893 }
1894 else
1895 #endif
1896 {
1897 const struct sockaddr *man_addr = man->settings.local->ai_addr;
1898 struct sockaddr_storage addr;
1899 socklen_t addrlen = sizeof(addr);
1900 if (!getsockname(man->connection.sd_top, (struct sockaddr *) &addr, &addrlen))
1901 {
1902 man_addr = (struct sockaddr *) &addr;
1903 }
1904 else
1905 {
1906 msg(M_WARN|M_ERRNO,
1907 "Failed to get the management socket address");
1908 }
1909 msg(D_MANAGEMENT, "MANAGEMENT: TCP Socket listening on %s",
1910 print_sockaddr(man_addr, &gc));
1911 }
1912 }
1913
1914 #ifdef _WIN32
1915 man_start_ne32(man);
1916 #endif
1917
1918 gc_free(&gc);
1919 }
1920
1921 static void
1922 man_connect(struct management *man)
1923 {
1924 struct gc_arena gc = gc_new();
1925 int status;
1926 int signal_received = 0;
1927
1928 /*
1929 * Initialize state
1930 */
1931 man->connection.state = MS_INITIAL;
1932 man->connection.sd_top = SOCKET_UNDEFINED;
1933
1934 #if UNIX_SOCK_SUPPORT
1935 if (man->settings.flags & MF_UNIX_SOCK)
1936 {
1937 man->connection.sd_cli = create_socket_unix();
1938 status = socket_connect_unix(man->connection.sd_cli, &man->settings.local_unix);
1939 if (!status && !man_verify_unix_peer_uid_gid(man, man->connection.sd_cli))
1940 {
1941 #ifdef EPERM
1942 status = EPERM;
1943 #else
1944 status = 1;
1945 #endif
1946 sd_close(&man->connection.sd_cli);
1947 }
1948 }
1949 else
1950 #endif
1951 {
1952 man->connection.sd_cli = create_socket_tcp(man->settings.local);
1953 status = openvpn_connect(man->connection.sd_cli,
1954 man->settings.local->ai_addr,
1955 5,
1956 &signal_received);
1957 }
1958
1959 if (signal_received)
1960 {
1961 throw_signal(signal_received);
1962 goto done;
1963 }
1964
1965 if (status)
1966 {
1967 #if UNIX_SOCK_SUPPORT
1968 if (man->settings.flags & MF_UNIX_SOCK)
1969 {
1970 msg(D_LINK_ERRORS | M_ERRNO,
1971 "MANAGEMENT: connect to unix socket %s failed",
1972 sockaddr_unix_name(&man->settings.local_unix, "NULL"));
1973 }
1974 else
1975 #endif
1976 msg(D_LINK_ERRORS | M_ERRNO,
1977 "MANAGEMENT: connect to %s failed",
1978 print_sockaddr(man->settings.local->ai_addr, &gc));
1979 throw_signal_soft(SIGTERM, "management-connect-failed");
1980 goto done;
1981 }
1982
1983 man_new_connection_post(man, "Connected to management server at");
1984
1985 done:
1986 gc_free(&gc);
1987 }
1988
1989 static void
1990 man_reset_client_socket(struct management *man, const bool exiting)
1991 {
1992 if (socket_defined(man->connection.sd_cli))
1993 {
1994 #ifdef _WIN32
1995 man_stop_ne32(man);
1996 #endif
1997 man_close_socket(man, man->connection.sd_cli);
1998 man->connection.sd_cli = SOCKET_UNDEFINED;
1999 man->connection.state = MS_INITIAL;
2000 command_line_reset(man->connection.in);
2001 buffer_list_reset(man->connection.out);
2002 in_extra_reset(&man->connection, IER_RESET);
2003 msg(D_MANAGEMENT, "MANAGEMENT: Client disconnected");
2004 }
2005 if (!exiting)
2006 {
2007 if (man->settings.flags & MF_FORGET_DISCONNECT)
2008 {
2009 ssl_purge_auth(false);
2010 (void)ssl_clean_auth_token();
2011 }
2012
2013 if (man->settings.flags & MF_SIGNAL)
2014 {
2015 int mysig = man_mod_signal(man, SIGUSR1);
2016 if (mysig >= 0)
2017 {
2018 msg(D_MANAGEMENT, "MANAGEMENT: Triggering management signal");
2019 throw_signal_soft(mysig, "management-disconnect");
2020 }
2021 }
2022
2023 if (man->settings.flags & MF_CONNECT_AS_CLIENT)
2024 {
2025 msg(D_MANAGEMENT, "MANAGEMENT: Triggering management exit");
2026 throw_signal_soft(SIGTERM, "management-exit");
2027 }
2028 else
2029 {
2030 man_listen(man);
2031 }
2032 }
2033 }
2034
2035 static void
2036 man_process_command(struct management *man, const char *line)
2037 {
2038 struct gc_arena gc = gc_new();
2039 struct status_output *so;
2040 int nparms;
2041 char *parms[MAX_PARMS+1];
2042
2043 CLEAR(parms);
2044 so = status_open(NULL, 0, -1, &man->persist.vout, 0);
2045 in_extra_reset(&man->connection, IER_RESET);
2046
2047 if (man_password_needed(man))
2048 {
2049 man_check_password(man, line);
2050 }
2051 else
2052 {
2053 nparms = parse_line(line, parms, MAX_PARMS, "TCP", 0, M_CLIENT, &gc);
2054 if (parms[0] && streq(parms[0], "password"))
2055 {
2056 msg(D_MANAGEMENT_DEBUG, "MANAGEMENT: CMD 'password [...]'");
2057 }
2058 else if (!streq(line, "load-stats"))
2059 {
2060 msg(D_MANAGEMENT_DEBUG, "MANAGEMENT: CMD '%s'", line);
2061 }
2062
2063 #if 0
2064 /* DEBUGGING -- print args */
2065 {
2066 int i;
2067 for (i = 0; i < nparms; ++i)
2068 {
2069 msg(M_INFO, "[%d] '%s'", i, parms[i]);
2070 }
2071 }
2072 #endif
2073
2074 if (nparms > 0)
2075 {
2076 man_dispatch_command(man, so, (const char **)parms, nparms);
2077 }
2078 }
2079
2080 CLEAR(parms);
2081 status_close(so);
2082 gc_free(&gc);
2083 }
2084
2085 static bool
2086 man_io_error(struct management *man, const char *prefix)
2087 {
2088 bool crt_error = false;
2089 int err = openvpn_errno_maybe_crt(&crt_error);
2090
2091 if (!ignore_sys_error(err, crt_error))
2092 {
2093 struct gc_arena gc = gc_new();
2094 msg(D_MANAGEMENT, "MANAGEMENT: TCP %s error: %s", prefix,
2095 strerror(err));
2096 gc_free(&gc);
2097 return true;
2098 }
2099 else
2100 {
2101 return false;
2102 }
2103 }
2104
2105 #ifdef TARGET_ANDROID
2106 static ssize_t
2107 man_send_with_fd(int fd, void *ptr, size_t nbytes, int flags, int sendfd)
2108 {
2109 struct msghdr msg = { 0 };
2110 struct iovec iov[1];
2111
2112 union {
2113 struct cmsghdr cm;
2114 char control[CMSG_SPACE(sizeof(int))];
2115 } control_un;
2116 struct cmsghdr *cmptr;
2117
2118 msg.msg_control = control_un.control;
2119 msg.msg_controllen = sizeof(control_un.control);
2120
2121 cmptr = CMSG_FIRSTHDR(&msg);
2122 cmptr->cmsg_len = CMSG_LEN(sizeof(int));
2123 cmptr->cmsg_level = SOL_SOCKET;
2124 cmptr->cmsg_type = SCM_RIGHTS;
2125 *((int *) CMSG_DATA(cmptr)) = sendfd;
2126
2127 msg.msg_name = NULL;
2128 msg.msg_namelen = 0;
2129
2130 iov[0].iov_base = ptr;
2131 iov[0].iov_len = nbytes;
2132 msg.msg_iov = iov;
2133 msg.msg_iovlen = 1;
2134
2135 return (sendmsg(fd, &msg, flags));
2136 }
2137
2138 static ssize_t
2139 man_recv_with_fd(int fd, void *ptr, size_t nbytes, int flags, int *recvfd)
2140 {
2141 struct msghdr msghdr = { 0 };
2142 struct iovec iov[1];
2143 ssize_t n;
2144
2145 union {
2146 struct cmsghdr cm;
2147 char control[CMSG_SPACE(sizeof(int))];
2148 } control_un;
2149 struct cmsghdr *cmptr;
2150
2151 msghdr.msg_control = control_un.control;
2152 msghdr.msg_controllen = sizeof(control_un.control);
2153
2154 msghdr.msg_name = NULL;
2155 msghdr.msg_namelen = 0;
2156
2157 iov[0].iov_base = ptr;
2158 iov[0].iov_len = nbytes;
2159 msghdr.msg_iov = iov;
2160 msghdr.msg_iovlen = 1;
2161
2162 if ( (n = recvmsg(fd, &msghdr, flags)) <= 0)
2163 {
2164 return (n);
2165 }
2166
2167 if ( (cmptr = CMSG_FIRSTHDR(&msghdr)) != NULL
2168 && cmptr->cmsg_len == CMSG_LEN(sizeof(int)))
2169 {
2170 if (cmptr->cmsg_level != SOL_SOCKET)
2171 {
2172 msg(M_ERR, "control level != SOL_SOCKET");
2173 }
2174 if (cmptr->cmsg_type != SCM_RIGHTS)
2175 {
2176 msg(M_ERR, "control type != SCM_RIGHTS");
2177 }
2178 *recvfd = *((int *) CMSG_DATA(cmptr));
2179 }
2180 else
2181 {
2182 *recvfd = -1; /* descriptor was not passed */
2183
2184 }
2185 return (n);
2186 }
2187
2188 /*
2189 * The android control method will instruct the GUI part of openvpn to do
2190 * the route/ifconfig/open tun command. See doc/android.txt for details.
2191 */
2192 bool
2193 management_android_control(struct management *man, const char *command, const char *msg)
2194 {
2195 struct user_pass up;
2196 CLEAR(up);
2197 strncpy(up.username, msg, sizeof(up.username)-1);
2198
2199 management_query_user_pass(management, &up, command, GET_USER_PASS_NEED_OK, (void *) 0);
2200 return strcmp("ok", up.password)==0;
2201 }
2202
2203 /*
2204 * In Android 4.4 it is not possible to open a new tun device and then close the
2205 * old tun device without breaking the whole VPNService stack until the device
2206 * is rebooted. This management method ask the UI what method should be taken to
2207 * ensure the optimal solution for the situation
2208 */
2209 int
2210 managment_android_persisttun_action(struct management *man)
2211 {
2212 struct user_pass up;
2213 CLEAR(up);
2214 strcpy(up.username, "tunmethod");
2215 management_query_user_pass(management, &up, "PERSIST_TUN_ACTION",
2216 GET_USER_PASS_NEED_OK, (void *) 0);
2217 if (!strcmp("NOACTION", up.password))
2218 {
2219 return ANDROID_KEEP_OLD_TUN;
2220 }
2221 else if (!strcmp("OPEN_BEFORE_CLOSE", up.password))
2222 {
2223 return ANDROID_OPEN_BEFORE_CLOSE;
2224 }
2225 else
2226 {
2227 msg(M_ERR, "Got unrecognised '%s' from management for PERSIST_TUN_ACTION query", up.password);
2228 }
2229
2230 ASSERT(0);
2231 return ANDROID_OPEN_BEFORE_CLOSE;
2232 }
2233
2234
2235 #endif /* ifdef TARGET_ANDROID */
2236
2237 static int
2238 man_read(struct management *man)
2239 {
2240 /*
2241 * read command line from socket
2242 */
2243 unsigned char buf[256];
2244 int len = 0;
2245
2246 #ifdef TARGET_ANDROID
2247 int fd;
2248 len = man_recv_with_fd(man->connection.sd_cli, buf, sizeof(buf), MSG_NOSIGNAL, &fd);
2249 if (fd >= 0)
2250 {
2251 man->connection.lastfdreceived = fd;
2252 }
2253 #else /* ifdef TARGET_ANDROID */
2254 len = recv(man->connection.sd_cli, buf, sizeof(buf), MSG_NOSIGNAL);
2255 #endif
2256
2257 if (len == 0)
2258 {
2259 man_reset_client_socket(man, false);
2260 }
2261 else if (len > 0)
2262 {
2263 bool processed_command = false;
2264
2265 ASSERT(len <= (int) sizeof(buf));
2266 command_line_add(man->connection.in, buf, len);
2267
2268 /*
2269 * Reset output object
2270 */
2271 buffer_list_reset(man->connection.out);
2272
2273 /*
2274 * process command line if complete
2275 */
2276 {
2277 const char *line;
2278 while ((line = command_line_get(man->connection.in)))
2279 {
2280 if (man->connection.in_extra)
2281 {
2282 if (!strcmp(line, "END"))
2283 {
2284 in_extra_dispatch(man);
2285 }
2286 else
2287 {
2288 buffer_list_push(man->connection.in_extra, line);
2289 }
2290 }
2291 else
2292 {
2293 man_process_command(man, (char *) line);
2294 }
2295 if (man->connection.halt)
2296 {
2297 break;
2298 }
2299 command_line_next(man->connection.in);
2300 processed_command = true;
2301 }
2302 }
2303
2304 /*
2305 * Reset output state to MS_CC_WAIT_(READ|WRITE)
2306 */
2307 if (man->connection.halt)
2308 {
2309 man_reset_client_socket(man, false);
2310 len = 0;
2311 }
2312 else
2313 {
2314 if (processed_command)
2315 {
2316 man_prompt(man);
2317 }
2318 man_update_io_state(man);
2319 }
2320 }
2321 else /* len < 0 */
2322 {
2323 if (man_io_error(man, "recv"))
2324 {
2325 man_reset_client_socket(man, false);
2326 }
2327 }
2328 return len;
2329 }
2330
2331 static int
2332 man_write(struct management *man)
2333 {
2334 const int size_hint = 1024;
2335 int sent = 0;
2336 const struct buffer *buf;
2337
2338 buffer_list_aggregate(man->connection.out, size_hint);
2339 buf = buffer_list_peek(man->connection.out);
2340 if (buf && BLEN(buf))
2341 {
2342 const int len = min_int(size_hint, BLEN(buf));
2343 #ifdef TARGET_ANDROID
2344 if (man->connection.fdtosend > 0)
2345 {
2346 sent = man_send_with_fd(man->connection.sd_cli, BPTR(buf), len, MSG_NOSIGNAL, man->connection.fdtosend);
2347 man->connection.fdtosend = -1;
2348 }
2349 else
2350 #endif
2351 sent = send(man->connection.sd_cli, BPTR(buf), len, MSG_NOSIGNAL);
2352 if (sent >= 0)
2353 {
2354 buffer_list_advance(man->connection.out, sent);
2355 }
2356 else if (sent < 0)
2357 {
2358 if (man_io_error(man, "send"))
2359 {
2360 man_reset_client_socket(man, false);
2361 }
2362 }
2363 }
2364
2365 /*
2366 * Reset output state to MS_CC_WAIT_(READ|WRITE)
2367 */
2368 man_update_io_state(man);
2369
2370 return sent;
2371 }
2372
2373 static void
2374 man_connection_clear(struct man_connection *mc)
2375 {
2376 CLEAR(*mc);
2377
2378 /* set initial state */
2379 mc->state = MS_INITIAL;
2380
2381 /* clear socket descriptors */
2382 mc->sd_top = SOCKET_UNDEFINED;
2383 mc->sd_cli = SOCKET_UNDEFINED;
2384 }
2385
2386 static void
2387 man_persist_init(struct management *man,
2388 const int log_history_cache,
2389 const int echo_buffer_size,
2390 const int state_buffer_size)
2391 {
2392 struct man_persist *mp = &man->persist;
2393 if (!mp->defined)
2394 {
2395 CLEAR(*mp);
2396
2397 /* initialize log history store */
2398 mp->log = log_history_init(log_history_cache);
2399
2400 /*
2401 * Initialize virtual output object, so that functions
2402 * which write to a virtual_output object can be redirected
2403 * here to the management object.
2404 */
2405 mp->vout.func = virtual_output_callback_func;
2406 mp->vout.arg = man;
2407 mp->vout.flags_default = M_CLIENT;
2408 msg_set_virtual_output(&mp->vout);
2409
2410 /*
2411 * Initialize --echo list
2412 */
2413 man->persist.echo = log_history_init(echo_buffer_size);
2414
2415 /*
2416 * Initialize --state list
2417 */
2418 man->persist.state = log_history_init(state_buffer_size);
2419
2420 mp->defined = true;
2421 }
2422 }
2423
2424 static void
2425 man_persist_close(struct man_persist *mp)
2426 {
2427 if (mp->log)
2428 {
2429 msg_set_virtual_output(NULL);
2430 log_history_close(mp->log);
2431 }
2432
2433 if (mp->echo)
2434 {
2435 log_history_close(mp->echo);
2436 }
2437
2438 if (mp->state)
2439 {
2440 log_history_close(mp->state);
2441 }
2442
2443 CLEAR(*mp);
2444 }
2445
2446 static void
2447 man_settings_init(struct man_settings *ms,
2448 const char *addr,
2449 const char *port,
2450 const char *pass_file,
2451 const char *client_user,
2452 const char *client_group,
2453 const int log_history_cache,
2454 const int echo_buffer_size,
2455 const int state_buffer_size,
2456 const int remap_sigusr1,
2457 const unsigned int flags)
2458 {
2459 if (!ms->defined)
2460 {
2461 CLEAR(*ms);
2462
2463 ms->flags = flags;
2464 ms->client_uid = -1;
2465 ms->client_gid = -1;
2466
2467 /*
2468 * Get username/password
2469 */
2470 if (pass_file)
2471 {
2472 get_user_pass(&ms->up, pass_file, "Management", GET_USER_PASS_PASSWORD_ONLY);
2473 }
2474
2475 /*
2476 * lookup client UID/GID if specified
2477 */
2478 if (client_user)
2479 {
2480 struct platform_state_user s;
2481 platform_user_get(client_user, &s);
2482 ms->client_uid = platform_state_user_uid(&s);
2483 msg(D_MANAGEMENT, "MANAGEMENT: client_uid=%d", ms->client_uid);
2484 ASSERT(ms->client_uid >= 0);
2485 }
2486 if (client_group)
2487 {
2488 struct platform_state_group s;
2489 platform_group_get(client_group, &s);
2490 ms->client_gid = platform_state_group_gid(&s);
2491 msg(D_MANAGEMENT, "MANAGEMENT: client_gid=%d", ms->client_gid);
2492 ASSERT(ms->client_gid >= 0);
2493 }
2494
2495 #if UNIX_SOCK_SUPPORT
2496 if (ms->flags & MF_UNIX_SOCK)
2497 {
2498 sockaddr_unix_init(&ms->local_unix, addr);
2499 }
2500 else
2501 #endif
2502 {
2503
2504 /*
2505 * Run management over tunnel, or
2506 * separate channel?
2507 */
2508 if (streq(addr, "tunnel") && !(flags & MF_CONNECT_AS_CLIENT))
2509 {
2510 ms->management_over_tunnel = true;
2511 }
2512 else
2513 {
2514 int status;
2515 int resolve_flags = GETADDR_RESOLVE|GETADDR_WARN_ON_SIGNAL|GETADDR_FATAL;
2516
2517 if (!(flags & MF_CONNECT_AS_CLIENT))
2518 {
2519 resolve_flags |= GETADDR_PASSIVE;
2520 }
2521
2522 status = openvpn_getaddrinfo(resolve_flags, addr, port, 0,
2523 NULL, AF_UNSPEC, &ms->local);
2524 ASSERT(status==0);
2525 }
2526 }
2527
2528 /*
2529 * Log history and echo buffer may need to be resized
2530 */
2531 ms->log_history_cache = log_history_cache;
2532 ms->echo_buffer_size = echo_buffer_size;
2533 ms->state_buffer_size = state_buffer_size;
2534
2535 /*
2536 * Set remap sigusr1 flags
2537 */
2538 if (remap_sigusr1 == SIGHUP)
2539 {
2540 ms->mansig |= MANSIG_MAP_USR1_TO_HUP;
2541 }
2542 else if (remap_sigusr1 == SIGTERM)
2543 {
2544 ms->mansig |= MANSIG_MAP_USR1_TO_TERM;
2545 }
2546
2547 ms->defined = true;
2548 }
2549 }
2550
2551 static void
2552 man_settings_close(struct man_settings *ms)
2553 {
2554 if (ms->local)
2555 {
2556 freeaddrinfo(ms->local);
2557 }
2558 CLEAR(*ms);
2559 }
2560
2561
2562 static void
2563 man_connection_init(struct management *man)
2564 {
2565 if (man->connection.state == MS_INITIAL)
2566 {
2567 #ifdef _WIN32
2568 /*
2569 * This object is a sort of TCP/IP helper
2570 * for Windows.
2571 */
2572 net_event_win32_init(&man->connection.ne32);
2573 #endif
2574
2575 /*
2576 * Allocate helper objects for command line input and
2577 * command output from/to the socket.
2578 */
2579 man->connection.in = command_line_new(1024);
2580 man->connection.out = buffer_list_new();
2581
2582 /*
2583 * Initialize event set for standalone usage, when we are
2584 * running outside of the primary event loop.
2585 */
2586 {
2587 int maxevents = 1;
2588 man->connection.es = event_set_init(&maxevents, EVENT_METHOD_FAST);
2589 }
2590
2591 man->connection.client_version = 1; /* default version */
2592
2593 /*
2594 * Listen/connect socket
2595 */
2596 if (man->settings.flags & MF_CONNECT_AS_CLIENT)
2597 {
2598 man_connect(man);
2599 }
2600 else
2601 {
2602 man_listen(man);
2603 }
2604 }
2605 }
2606
2607 static void
2608 man_connection_close(struct management *man)
2609 {
2610 struct man_connection *mc = &man->connection;
2611
2612 event_free(mc->es);
2613 #ifdef _WIN32
2614 net_event_win32_close(&mc->ne32);
2615 #endif
2616 if (socket_defined(mc->sd_top))
2617 {
2618 man_close_socket(man, mc->sd_top);
2619 man_delete_unix_socket(man);
2620 }
2621 if (socket_defined(mc->sd_cli))
2622 {
2623 man_close_socket(man, mc->sd_cli);
2624 }
2625
2626 command_line_free(mc->in);
2627 buffer_list_free(mc->out);
2628
2629 event_timeout_clear(&mc->bytecount_update_interval);
2630
2631 in_extra_reset(&man->connection, IER_RESET);
2632 buffer_list_free(mc->ext_key_input);
2633 man_connection_clear(mc);
2634 }
2635
2636 struct management *
2637 management_init(void)
2638 {
2639 struct management *man;
2640 ALLOC_OBJ_CLEAR(man, struct management);
2641
2642 man_persist_init(man,
2643 MANAGEMENT_LOG_HISTORY_INITIAL_SIZE,
2644 MANAGEMENT_ECHO_BUFFER_SIZE,
2645 MANAGEMENT_STATE_BUFFER_SIZE);
2646
2647 man_connection_clear(&man->connection);
2648
2649 return man;
2650 }
2651
2652 bool
2653 management_open(struct management *man,
2654 const char *addr,
2655 const char *port,
2656 const char *pass_file,
2657 const char *client_user,
2658 const char *client_group,
2659 const int log_history_cache,
2660 const int echo_buffer_size,
2661 const int state_buffer_size,
2662 const int remap_sigusr1,
2663 const unsigned int flags)
2664 {
2665 bool ret = false;
2666
2667 /*
2668 * Save the settings only if they have not
2669 * been saved before.
2670 */
2671 man_settings_init(&man->settings,
2672 addr,
2673 port,
2674 pass_file,
2675 client_user,
2676 client_group,
2677 log_history_cache,
2678 echo_buffer_size,
2679 state_buffer_size,
2680 remap_sigusr1,
2681 flags);
2682
2683 /*
2684 * The log is initially sized to MANAGEMENT_LOG_HISTORY_INITIAL_SIZE,
2685 * but may be changed here. Ditto for echo and state buffers.
2686 */
2687 log_history_resize(man->persist.log, man->settings.log_history_cache);
2688 log_history_resize(man->persist.echo, man->settings.echo_buffer_size);
2689 log_history_resize(man->persist.state, man->settings.state_buffer_size);
2690
2691 /*
2692 * If connection object is uninitialized and we are not doing
2693 * over-the-tunnel management, then open (listening) connection.
2694 */
2695 if (man->connection.state == MS_INITIAL)
2696 {
2697 if (!man->settings.management_over_tunnel)
2698 {
2699 man_connection_init(man);
2700 ret = true;
2701 }
2702 }
2703
2704 return ret;
2705 }
2706
2707 void
2708 management_close(struct management *man)
2709 {
2710 man_output_list_push_finalize(man); /* flush output queue */
2711 man_connection_close(man);
2712 man_settings_close(&man->settings);
2713 man_persist_close(&man->persist);
2714 free(man);
2715 }
2716
2717 void
2718 management_set_callback(struct management *man,
2719 const struct management_callback *cb)
2720 {
2721 man->persist.standalone_disabled = true;
2722 man->persist.callback = *cb;
2723 }
2724
2725 void
2726 management_clear_callback(struct management *man)
2727 {
2728 man->persist.standalone_disabled = false;
2729 man->persist.hold_release = false;
2730 CLEAR(man->persist.callback);
2731 man_output_list_push_finalize(man); /* flush output queue */
2732 }
2733
2734 void
2735 management_set_state(struct management *man,
2736 const int state,
2737 const char *detail,
2738 const in_addr_t *tun_local_ip,
2739 const struct in6_addr *tun_local_ip6,
2740 const struct openvpn_sockaddr *local,
2741 const struct openvpn_sockaddr *remote)
2742 {
2743 if (man->persist.state && (!(man->settings.flags & MF_SERVER) || state < OPENVPN_STATE_CLIENT_BASE))
2744 {
2745 struct gc_arena gc = gc_new();
2746 struct log_entry e;
2747 const char *out = NULL;
2748
2749 update_time();
2750 CLEAR(e);
2751 e.timestamp = now;
2752 e.u.state = state;
2753 e.string = detail;
2754 if (tun_local_ip)
2755 {
2756 e.local_ip = *tun_local_ip;
2757 }
2758 if (tun_local_ip6)
2759 {
2760 e.local_ip6 = *tun_local_ip6;
2761 }
2762 if (local)
2763 {
2764 e.local_sock = *local;
2765 }
2766 if (remote)
2767 {
2768 e.remote_sock = *remote;
2769 }
2770
2771 log_history_add(man->persist.state, &e);
2772
2773 if (man->connection.state_realtime)
2774 {
2775 out = log_entry_print(&e, LOG_PRINT_STATE_PREFIX
2776 | LOG_PRINT_INT_DATE
2777 | LOG_PRINT_STATE
2778 | LOG_PRINT_LOCAL_IP
2779 | LOG_PRINT_REMOTE_IP
2780 | LOG_PRINT_CRLF
2781 | LOG_ECHO_TO_LOG, &gc);
2782 }
2783
2784 if (out)
2785 {
2786 man_output_list_push(man, out);
2787 }
2788
2789 gc_free(&gc);
2790 }
2791 }
2792
2793 static bool
2794 env_filter_match(const char *env_str, const int env_filter_level)
2795 {
2796 static const char *env_names[] = {
2797 "username=",
2798 "password=",
2799 "X509_0_CN=",
2800 "tls_serial_",
2801 "untrusted_ip=",
2802 "ifconfig_local=",
2803 "ifconfig_netmask=",
2804 "daemon_start_time=",
2805 "daemon_pid=",
2806 "dev=",
2807 "ifconfig_pool_remote_ip=",
2808 "ifconfig_pool_netmask=",
2809 "time_duration=",
2810 "bytes_sent=",
2811 "bytes_received=",
2812 "session_id=",
2813 "session_state="
2814 };
2815
2816 if (env_filter_level == 0)
2817 {
2818 return true;
2819 }
2820 else if (env_filter_level <= 1 && !strncmp(env_str, "X509_", 5))
2821 {
2822 return true;
2823 }
2824 else if (env_filter_level <= 2)
2825 {
2826 size_t i;
2827 for (i = 0; i < SIZE(env_names); ++i)
2828 {
2829 const char *en = env_names[i];
2830 const size_t len = strlen(en);
2831 if (!strncmp(env_str, en, len))
2832 {
2833 return true;
2834 }
2835 }
2836 return false;
2837 }
2838 return false;
2839 }
2840
2841 static void
2842 man_output_env(const struct env_set *es, const bool tail, const int env_filter_level, const char *prefix)
2843 {
2844 if (es)
2845 {
2846 struct env_item *e;
2847 for (e = es->list; e != NULL; e = e->next)
2848 {
2849 if (e->string && (!env_filter_level || env_filter_match(e->string, env_filter_level)))
2850 {
2851 msg(M_CLIENT, ">%s:ENV,%s", prefix, e->string);
2852 }
2853 }
2854 }
2855 if (tail)
2856 {
2857 msg(M_CLIENT, ">%s:ENV,END", prefix);
2858 }
2859 }
2860
2861 static void
2862 man_output_extra_env(struct management *man, const char *prefix)
2863 {
2864 struct gc_arena gc = gc_new();
2865 struct env_set *es = env_set_create(&gc);
2866 if (man->persist.callback.n_clients)
2867 {
2868 const int nclients = (*man->persist.callback.n_clients)(man->persist.callback.arg);
2869 setenv_int(es, "n_clients", nclients);
2870 }
2871 man_output_env(es, false, man->connection.env_filter_level, prefix);
2872 gc_free(&gc);
2873 }
2874
2875 void
2876 management_up_down(struct management *man, const char *updown, const struct env_set *es)
2877 {
2878 if (man->settings.flags & MF_UP_DOWN)
2879 {
2880 msg(M_CLIENT, ">UPDOWN:%s", updown);
2881 man_output_env(es, true, 0, "UPDOWN");
2882 }
2883 }
2884
2885 void
2886 management_notify(struct management *man, const char *severity, const char *type, const char *text)
2887 {
2888 msg(M_CLIENT, ">NOTIFY:%s,%s,%s", severity, type, text);
2889 }
2890
2891 void
2892 management_notify_generic(struct management *man, const char *str)
2893 {
2894 msg(M_CLIENT, "%s", str);
2895 }
2896
2897 static void
2898 man_output_peer_info_env(struct management *man, const struct man_def_auth_context *mdac)
2899 {
2900 char line[256];
2901 if (man->persist.callback.get_peer_info)
2902 {
2903 const char *peer_info = (*man->persist.callback.get_peer_info)(man->persist.callback.arg, mdac->cid);
2904 if (peer_info)
2905 {
2906 struct buffer buf;
2907 buf_set_read(&buf, (const uint8_t *) peer_info, strlen(peer_info));
2908 while (buf_parse(&buf, '\n', line, sizeof(line)))
2909 {
2910 chomp(line);
2911 if (validate_peer_info_line(line))
2912 {
2913 msg(M_CLIENT, ">CLIENT:ENV,%s", line);
2914 }
2915 else
2916 {
2917 msg(D_MANAGEMENT, "validation failed on peer_info line received from client");
2918 }
2919 }
2920 }
2921 }
2922 }
2923
2924 void
2925 management_notify_client_needing_auth(struct management *management,
2926 const unsigned int mda_key_id,
2927 struct man_def_auth_context *mdac,
2928 const struct env_set *es)
2929 {
2930 if (!(mdac->flags & DAF_CONNECTION_CLOSED))
2931 {
2932 const char *mode = "CONNECT";
2933 if (mdac->flags & DAF_CONNECTION_ESTABLISHED)
2934 {
2935 mode = "REAUTH";
2936 }
2937 msg(M_CLIENT, ">CLIENT:%s,%lu,%u", mode, mdac->cid, mda_key_id);
2938 man_output_extra_env(management, "CLIENT");
2939 if (management->connection.env_filter_level>0)
2940 {
2941 man_output_peer_info_env(management, mdac);
2942 }
2943 man_output_env(es, true, management->connection.env_filter_level, "CLIENT");
2944 mdac->flags |= DAF_INITIAL_AUTH;
2945 }
2946 }
2947
2948 void
2949 management_notify_client_cr_response(unsigned mda_key_id,
2950 const struct man_def_auth_context *mdac,
2951 const struct env_set *es,
2952 const char *response)
2953 {
2954 struct gc_arena gc;
2955 if (management)
2956 {
2957 gc = gc_new();
2958
2959 msg(M_CLIENT, ">CLIENT:CR_RESPONSE,%lu,%u,%s",
2960 mdac->cid, mda_key_id, response);
2961 man_output_extra_env(management, "CLIENT");
2962 if (management->connection.env_filter_level > 0)
2963 {
2964 man_output_peer_info_env(management, mdac);
2965 }
2966 man_output_env(es, true, management->connection.env_filter_level, "CLIENT");
2967 gc_free(&gc);
2968 }
2969 }
2970
2971 void
2972 management_connection_established(struct management *management,
2973 struct man_def_auth_context *mdac,
2974 const struct env_set *es)
2975 {
2976 mdac->flags |= DAF_CONNECTION_ESTABLISHED;
2977 msg(M_CLIENT, ">CLIENT:ESTABLISHED,%lu", mdac->cid);
2978 man_output_extra_env(management, "CLIENT");
2979 man_output_env(es, true, management->connection.env_filter_level, "CLIENT");
2980 }
2981
2982 void
2983 management_notify_client_close(struct management *management,
2984 struct man_def_auth_context *mdac,
2985 const struct env_set *es)
2986 {
2987 if ((mdac->flags & DAF_INITIAL_AUTH) && !(mdac->flags & DAF_CONNECTION_CLOSED))
2988 {
2989 msg(M_CLIENT, ">CLIENT:DISCONNECT,%lu", mdac->cid);
2990 man_output_env(es, true, management->connection.env_filter_level, "CLIENT");
2991 mdac->flags |= DAF_CONNECTION_CLOSED;
2992 }
2993 }
2994
2995 void
2996 management_learn_addr(struct management *management,
2997 struct man_def_auth_context *mdac,
2998 const struct mroute_addr *addr,
2999 const bool primary)
3000 {
3001 struct gc_arena gc = gc_new();
3002 if ((mdac->flags & DAF_INITIAL_AUTH) && !(mdac->flags & DAF_CONNECTION_CLOSED))
3003 {
3004 msg(M_CLIENT, ">CLIENT:ADDRESS,%lu,%s,%d",
3005 mdac->cid,
3006 mroute_addr_print_ex(addr, MAPF_SUBNET, &gc),
3007 BOOL_CAST(primary));
3008 }
3009 gc_free(&gc);
3010 }
3011
3012 void
3013 management_echo(struct management *man, const char *string, const bool pull)
3014 {
3015 if (man->persist.echo)
3016 {
3017 struct gc_arena gc = gc_new();
3018 struct log_entry e;
3019 const char *out = NULL;
3020
3021 update_time();
3022 CLEAR(e);
3023 e.timestamp = now;
3024 e.string = string;
3025 e.u.intval = BOOL_CAST(pull);
3026
3027 log_history_add(man->persist.echo, &e);
3028
3029 if (man->connection.echo_realtime)
3030 {
3031 out = log_entry_print(&e, LOG_PRINT_INT_DATE|LOG_PRINT_ECHO_PREFIX|LOG_PRINT_CRLF|MANAGEMENT_ECHO_FLAGS, &gc);
3032 }
3033
3034 if (out)
3035 {
3036 man_output_list_push(man, out);
3037 }
3038
3039 gc_free(&gc);
3040 }
3041 }
3042
3043 void
3044 management_post_tunnel_open(struct management *man, const in_addr_t tun_local_ip)
3045 {
3046 /*
3047 * If we are running management over the tunnel,
3048 * this is the place to initialize the connection.
3049 */
3050 if (man->settings.management_over_tunnel
3051 && man->connection.state == MS_INITIAL)
3052 {
3053 /* listen on our local TUN/TAP IP address */
3054 struct in_addr ia;
3055 int ret;
3056
3057 ia.s_addr = htonl(tun_local_ip);
3058 ret = openvpn_getaddrinfo(GETADDR_PASSIVE, inet_ntoa(ia), NULL, 0, NULL,
3059 AF_INET, &man->settings.local);
3060 ASSERT(ret==0);
3061 man_connection_init(man);
3062 }
3063
3064 }
3065
3066 void
3067 management_pre_tunnel_close(struct management *man)
3068 {
3069 if (man->settings.management_over_tunnel)
3070 {
3071 man_connection_close(man);
3072 }
3073 }
3074
3075 void
3076 management_auth_failure(struct management *man, const char *type, const char *reason)
3077 {
3078 if (reason)
3079 {
3080 msg(M_CLIENT, ">PASSWORD:Verification Failed: '%s' ['%s']", type, reason);
3081 }
3082 else
3083 {
3084 msg(M_CLIENT, ">PASSWORD:Verification Failed: '%s'", type);
3085 }
3086 }
3087
3088 void
3089 management_auth_token(struct management *man, const char *token)
3090 {
3091 msg(M_CLIENT, ">PASSWORD:Auth-Token:%s", token);
3092 }
3093
3094 static inline bool
3095 man_persist_state(unsigned int *persistent, const int n)
3096 {
3097 if (persistent)
3098 {
3099 if (*persistent == (unsigned int)n)
3100 {
3101 return false;
3102 }
3103 *persistent = n;
3104 }
3105 return true;
3106 }
3107
3108 #ifdef _WIN32
3109
3110 void
3111 management_socket_set(struct management *man,
3112 struct event_set *es,
3113 void *arg,
3114 unsigned int *persistent)
3115 {
3116 if (man->connection.state != MS_INITIAL)
3117 {
3118 event_t ev = net_event_win32_get_event(&man->connection.ne32);
3119 net_event_win32_reset_write(&man->connection.ne32);
3120
3121 switch (man->connection.state)
3122 {
3123 case MS_LISTEN:
3124 if (man_persist_state(persistent, 1))
3125 {
3126 event_ctl(es, ev, EVENT_READ, arg);
3127 }
3128 break;
3129
3130 case MS_CC_WAIT_READ:
3131 if (man_persist_state(persistent, 2))
3132 {
3133 event_ctl(es, ev, EVENT_READ, arg);
3134 }
3135 break;
3136
3137 case MS_CC_WAIT_WRITE:
3138 if (man_persist_state(persistent, 3))
3139 {
3140 event_ctl(es, ev, EVENT_READ|EVENT_WRITE, arg);
3141 }
3142 break;
3143
3144 default:
3145 ASSERT(0);
3146 }
3147 }
3148 }
3149
3150 void
3151 management_io(struct management *man)
3152 {
3153 if (man->connection.state != MS_INITIAL)
3154 {
3155 long net_events;
3156 net_event_win32_reset(&man->connection.ne32);
3157 net_events = net_event_win32_get_event_mask(&man->connection.ne32);
3158
3159 if (net_events & FD_CLOSE)
3160 {
3161 man_reset_client_socket(man, false);
3162 }
3163 else
3164 {
3165 if (man->connection.state == MS_LISTEN)
3166 {
3167 if (net_events & FD_ACCEPT)
3168 {
3169 man_accept(man);
3170 net_event_win32_clear_selected_events(&man->connection.ne32, FD_ACCEPT);
3171 }
3172 }
3173 else if (man->connection.state == MS_CC_WAIT_READ || man->connection.state == MS_CC_WAIT_WRITE)
3174 {
3175 if (net_events & FD_READ)
3176 {
3177 while (man_read(man) > 0)
3178 {
3179 }
3180 net_event_win32_clear_selected_events(&man->connection.ne32, FD_READ);
3181 }
3182
3183 if (net_events & FD_WRITE)
3184 {
3185 int status;
3186 status = man_write(man);
3187 if (status < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
3188 {
3189 net_event_win32_clear_selected_events(&man->connection.ne32, FD_WRITE);
3190 }
3191 }
3192 }
3193 }
3194 }
3195 }
3196
3197 #else /* ifdef _WIN32 */
3198
3199 void
3200 management_socket_set(struct management *man,
3201 struct event_set *es,
3202 void *arg,
3203 unsigned int *persistent)
3204 {
3205 switch (man->connection.state)
3206 {
3207 case MS_LISTEN:
3208 if (man_persist_state(persistent, 1))
3209 {
3210 event_ctl(es, man->connection.sd_top, EVENT_READ, arg);
3211 }
3212 break;
3213
3214 case MS_CC_WAIT_READ:
3215 if (man_persist_state(persistent, 2))
3216 {
3217 event_ctl(es, man->connection.sd_cli, EVENT_READ, arg);
3218 }
3219 break;
3220
3221 case MS_CC_WAIT_WRITE:
3222 if (man_persist_state(persistent, 3))
3223 {
3224 event_ctl(es, man->connection.sd_cli, EVENT_WRITE, arg);
3225 }
3226 break;
3227
3228 case MS_INITIAL:
3229 break;
3230
3231 default:
3232 ASSERT(0);
3233 }
3234 }
3235
3236 void
3237 management_io(struct management *man)
3238 {
3239 switch (man->connection.state)
3240 {
3241 case MS_LISTEN:
3242 man_accept(man);
3243 break;
3244
3245 case MS_CC_WAIT_READ:
3246 man_read(man);
3247 break;
3248
3249 case MS_CC_WAIT_WRITE:
3250 man_write(man);
3251 break;
3252
3253 case MS_INITIAL:
3254 break;
3255
3256 default:
3257 ASSERT(0);
3258 }
3259 }
3260
3261 #endif /* ifdef _WIN32 */
3262
3263 static inline bool
3264 man_standalone_ok(const struct management *man)
3265 {
3266 return !man->settings.management_over_tunnel && man->connection.state != MS_INITIAL;
3267 }
3268
3269 static bool
3270 man_check_for_signals(volatile int *signal_received)
3271 {
3272 if (signal_received)
3273 {
3274 get_signal(signal_received);
3275 if (*signal_received)
3276 {
3277 return true;
3278 }
3279 }
3280 return false;
3281 }
3282
3283 /*
3284 * Wait for socket I/O when outside primary event loop
3285 */
3286 static int
3287 man_block(struct management *man, volatile int *signal_received, const time_t expire)
3288 {
3289 struct timeval tv;
3290 struct event_set_return esr;
3291 int status = -1;
3292
3293 if (man_standalone_ok(man))
3294 {
3295 /* expire time can be already overdue, for this case init zero
3296 * timeout to avoid waiting first time and exit loop early with
3297 * either obtained event or timeout.
3298 */
3299 tv.tv_usec = 0;
3300 tv.tv_sec = 0;
3301
3302 while (true)
3303 {
3304 event_reset(man->connection.es);
3305 management_socket_set(man, man->connection.es, NULL, NULL);
3306 if (man_check_for_signals(signal_received))
3307 {
3308 status = -1;
3309 break;
3310 }
3311 status = event_wait(man->connection.es, &tv, &esr, 1);
3312 update_time();
3313 if (man_check_for_signals(signal_received))
3314 {
3315 status = -1;
3316 break;
3317 }
3318
3319 if (status > 0)
3320 {
3321 break;
3322 }
3323 else if (expire && now >= expire)
3324 {
3325 /* set SIGINT signal if expiration time exceeded */
3326 status = 0;
3327 if (signal_received)
3328 {
3329 *signal_received = SIGINT;
3330 }
3331 break;
3332 }
3333
3334 /* wait one second more */
3335 tv.tv_sec = 1;
3336 tv.tv_usec = 0;
3337 }
3338 }
3339 return status;
3340 }
3341
3342 /*
3343 * Perform management socket output outside primary event loop
3344 */
3345 static void
3346 man_output_standalone(struct management *man, volatile int *signal_received)
3347 {
3348 if (man_standalone_ok(man))
3349 {
3350 while (man->connection.state == MS_CC_WAIT_WRITE)
3351 {
3352 management_io(man);
3353 if (man->connection.state == MS_CC_WAIT_WRITE)
3354 {
3355 man_block(man, signal_received, 0);
3356 }
3357 if (signal_received && *signal_received)
3358 {
3359 break;
3360 }
3361 }
3362 }
3363 }
3364
3365 /*
3366 * Process management event loop outside primary event loop
3367 */
3368 static int
3369 man_standalone_event_loop(struct management *man, volatile int *signal_received, const time_t expire)
3370 {
3371 int status = -1;
3372 if (man_standalone_ok(man))
3373 {
3374 status = man_block(man, signal_received, expire);
3375 if (status > 0)
3376 {
3377 management_io(man);
3378 }
3379 }
3380 return status;
3381 }
3382
3383 #define MWCC_PASSWORD_WAIT (1<<0)
3384 #define MWCC_HOLD_WAIT (1<<1)
3385 #define MWCC_OTHER_WAIT (1<<2)
3386
3387 /*
3388 * Block until client connects
3389 */
3390 static void
3391 man_wait_for_client_connection(struct management *man,
3392 volatile int *signal_received,
3393 const time_t expire,
3394 unsigned int flags)
3395 {
3396 ASSERT(man_standalone_ok(man));
3397 if (man->connection.state == MS_LISTEN)
3398 {
3399 if (flags & MWCC_PASSWORD_WAIT)
3400 {
3401 msg(D_MANAGEMENT, "Need password(s) from management interface, waiting...");
3402 }
3403 if (flags & MWCC_HOLD_WAIT)
3404 {
3405 msg(D_MANAGEMENT, "Need hold release from management interface, waiting...");
3406 }
3407 if (flags & MWCC_OTHER_WAIT)
3408 {
3409 msg(D_MANAGEMENT, "Need information from management interface, waiting...");
3410 }
3411 do
3412 {
3413 man_standalone_event_loop(man, signal_received, expire);
3414 if (signal_received && *signal_received)
3415 {
3416 break;
3417 }
3418 } while (man->connection.state == MS_LISTEN || man_password_needed(man));
3419 }
3420 }
3421
3422 /*
3423 * Process the management event loop for sec seconds
3424 */
3425 void
3426 management_event_loop_n_seconds(struct management *man, int sec)
3427 {
3428 if (man_standalone_ok(man))
3429 {
3430 volatile int signal_received = 0;
3431 const bool standalone_disabled_save = man->persist.standalone_disabled;
3432 time_t expire = 0;
3433
3434 man->persist.standalone_disabled = false; /* This is so M_CLIENT messages will be correctly passed through msg() */
3435
3436 /* set expire time */
3437 update_time();
3438 if (sec >= 0)
3439 {
3440 expire = now + sec;
3441 }
3442
3443 /* if no client connection, wait for one */
3444 man_wait_for_client_connection(man, &signal_received, expire, 0);
3445 if (signal_received)
3446 {
3447 return;
3448 }
3449
3450 /* run command processing event loop */
3451 do
3452 {
3453 man_standalone_event_loop(man, &signal_received, expire);
3454 if (!signal_received)
3455 {
3456 man_check_for_signals(&signal_received);
3457 }
3458 if (signal_received)
3459 {
3460 return;
3461 }
3462 update_time();
3463 } while (expire && expire > now);
3464
3465 /* revert state */
3466 man->persist.standalone_disabled = standalone_disabled_save;
3467 }
3468 else if (sec > 0)
3469 {
3470 sleep(sec);
3471 }
3472 }
3473
3474 /*
3475 * Get a username/password from management channel in standalone mode.
3476 */
3477 bool
3478 management_query_user_pass(struct management *man,
3479 struct user_pass *up,
3480 const char *type,
3481 const unsigned int flags,
3482 const char *static_challenge)
3483 {
3484 struct gc_arena gc = gc_new();
3485 bool ret = false;
3486
3487 if (man_standalone_ok(man))
3488 {
3489 volatile int signal_received = 0;
3490 const bool standalone_disabled_save = man->persist.standalone_disabled;
3491 struct buffer alert_msg = alloc_buf_gc(128, &gc);
3492 const char *alert_type = NULL;
3493 const char *prefix = NULL;
3494 unsigned int up_query_mode = 0;
3495 const char *sc = NULL;
3496 ret = true;
3497 man->persist.standalone_disabled = false; /* This is so M_CLIENT messages will be correctly passed through msg() */
3498 man->persist.special_state_msg = NULL;
3499
3500 CLEAR(man->connection.up_query);
3501
3502 if (flags & GET_USER_PASS_NEED_OK)
3503 {
3504 up_query_mode = UP_QUERY_NEED_OK;
3505 prefix = "NEED-OK";
3506 alert_type = "confirmation";
3507 }
3508 else if (flags & GET_USER_PASS_NEED_STR)
3509 {
3510 up_query_mode = UP_QUERY_NEED_STR;
3511 prefix = "NEED-STR";
3512 alert_type = "string";
3513 }
3514 else if (flags & GET_USER_PASS_PASSWORD_ONLY)
3515 {
3516 up_query_mode = UP_QUERY_PASS;
3517 prefix = "PASSWORD";
3518 alert_type = "password";
3519 }
3520 else
3521 {
3522 up_query_mode = UP_QUERY_USER_PASS;
3523 prefix = "PASSWORD";
3524 alert_type = "username/password";
3525 if (static_challenge)
3526 {
3527 sc = static_challenge;
3528 }
3529 }
3530 buf_printf(&alert_msg, ">%s:Need '%s' %s",
3531 prefix,
3532 type,
3533 alert_type);
3534
3535 if (flags & (GET_USER_PASS_NEED_OK | GET_USER_PASS_NEED_STR))
3536 {
3537 buf_printf(&alert_msg, " MSG:%s", up->username);
3538 }
3539
3540 if (sc)
3541 {
3542 buf_printf(&alert_msg, " SC:%d,%s",
3543 BOOL_CAST(flags & GET_USER_PASS_STATIC_CHALLENGE_ECHO),
3544 sc);
3545 }
3546
3547 man_wait_for_client_connection(man, &signal_received, 0, MWCC_PASSWORD_WAIT);
3548 if (signal_received)
3549 {
3550 ret = false;
3551 }
3552
3553 if (ret)
3554 {
3555 man->persist.special_state_msg = BSTR(&alert_msg);
3556 msg(M_CLIENT, "%s", man->persist.special_state_msg);
3557
3558 /* tell command line parser which info we need */
3559 man->connection.up_query_mode = up_query_mode;
3560 man->connection.up_query_type = type;
3561
3562 /* run command processing event loop until we get our username/password/response */
3563 do
3564 {
3565 man_standalone_event_loop(man, &signal_received, 0);
3566 if (!signal_received)
3567 {
3568 man_check_for_signals(&signal_received);
3569 }
3570 if (signal_received)
3571 {
3572 ret = false;
3573 break;
3574 }
3575 } while (!man->connection.up_query.defined);
3576 }
3577
3578 /* revert state */
3579 man->connection.up_query_mode = UP_QUERY_DISABLED;
3580 man->connection.up_query_type = NULL;
3581 man->persist.standalone_disabled = standalone_disabled_save;
3582 man->persist.special_state_msg = NULL;
3583
3584 /* pass through blank passwords */
3585 if (!strcmp(man->connection.up_query.password, blank_up))
3586 {
3587 CLEAR(man->connection.up_query.password);
3588 }
3589
3590 /*
3591 * Transfer u/p to return object, zero any record
3592 * we hold in the management object.
3593 */
3594 if (ret)
3595 {
3596 /* preserve caller's settings */
3597 man->connection.up_query.nocache = up->nocache;
3598 *up = man->connection.up_query;
3599 }
3600 secure_memzero(&man->connection.up_query, sizeof(man->connection.up_query));
3601 }
3602
3603 gc_free(&gc);
3604 return ret;
3605 }
3606
3607 static int
3608 management_query_multiline(struct management *man,
3609 const char *b64_data, const char *prompt, const char *cmd, int *state, struct buffer_list **input)
3610 {
3611 struct gc_arena gc = gc_new();
3612 int ret = 0;
3613 volatile int signal_received = 0;
3614 struct buffer alert_msg = clear_buf();
3615 const bool standalone_disabled_save = man->persist.standalone_disabled;
3616 struct man_connection *mc = &man->connection;
3617
3618 if (man_standalone_ok(man))
3619 {
3620 man->persist.standalone_disabled = false; /* This is so M_CLIENT messages will be correctly passed through msg() */
3621 man->persist.special_state_msg = NULL;
3622
3623 *state = EKS_SOLICIT;
3624
3625 if (b64_data)
3626 {
3627 alert_msg = alloc_buf_gc(strlen(b64_data)+strlen(prompt)+3, &gc);
3628 buf_printf(&alert_msg, ">%s:%s", prompt, b64_data);
3629 }
3630 else
3631 {
3632 alert_msg = alloc_buf_gc(strlen(prompt)+3, &gc);
3633 buf_printf(&alert_msg, ">%s", prompt);
3634 }
3635
3636 man_wait_for_client_connection(man, &signal_received, 0, MWCC_OTHER_WAIT);
3637
3638 if (signal_received)
3639 {
3640 goto done;
3641 }
3642
3643 man->persist.special_state_msg = BSTR(&alert_msg);
3644 msg(M_CLIENT, "%s", man->persist.special_state_msg);
3645
3646 /* run command processing event loop until we get our signature */
3647 do
3648 {
3649 man_standalone_event_loop(man, &signal_received, 0);
3650 if (!signal_received)
3651 {
3652 man_check_for_signals(&signal_received);
3653 }
3654 if (signal_received)
3655 {
3656 goto done;
3657 }
3658 } while (*state != EKS_READY);
3659
3660 ret = 1;
3661 }
3662
3663 done:
3664 if (*state == EKS_READY && ret)
3665 {
3666 msg(M_CLIENT, "SUCCESS: %s command succeeded", cmd);
3667 }
3668 else if (*state == EKS_INPUT || *state == EKS_READY)
3669 {
3670 msg(M_CLIENT, "ERROR: %s command failed", cmd);
3671 }
3672
3673 /* revert state */
3674 man->persist.standalone_disabled = standalone_disabled_save;
3675 man->persist.special_state_msg = NULL;
3676 in_extra_reset(mc, IER_RESET);
3677 *state = EKS_UNDEF;
3678
3679 gc_free(&gc);
3680 return ret;
3681 }
3682
3683 static char *
3684 /* returns allocated base64 signature */
3685 management_query_multiline_flatten_newline(struct management *man,
3686 const char *b64_data, const char *prompt, const char *cmd, int *state, struct buffer_list **input)
3687 {
3688 int ok;
3689 char *result = NULL;
3690 struct buffer *buf;
3691
3692 ok = management_query_multiline(man, b64_data, prompt, cmd, state, input);
3693 if (ok && buffer_list_defined(*input))
3694 {
3695 buffer_list_aggregate_separator(*input, 10000, "\n");
3696 buf = buffer_list_peek(*input);
3697 if (buf && BLEN(buf) > 0)
3698 {
3699 result = (char *) malloc(BLEN(buf)+1);
3700 check_malloc_return(result);
3701 memcpy(result, buf->data, BLEN(buf));
3702 result[BLEN(buf)] = '\0';
3703 }
3704 }
3705
3706 buffer_list_free(*input);
3707 *input = NULL;
3708
3709 return result;
3710 }
3711
3712 static char *
3713 /* returns allocated base64 signature */
3714 management_query_multiline_flatten(struct management *man,
3715 const char *b64_data, const char *prompt, const char *cmd, int *state, struct buffer_list **input)
3716 {
3717 int ok;
3718 char *result = NULL;
3719 struct buffer *buf;
3720
3721 ok = management_query_multiline(man, b64_data, prompt, cmd, state, input);
3722 if (ok && buffer_list_defined(*input))
3723 {
3724 buffer_list_aggregate(*input, 2048);
3725 buf = buffer_list_peek(*input);
3726 if (buf && BLEN(buf) > 0)
3727 {
3728 result = (char *) malloc(BLEN(buf)+1);
3729 check_malloc_return(result);
3730 memcpy(result, buf->data, BLEN(buf));
3731 result[BLEN(buf)] = '\0';
3732 }
3733 }
3734
3735 buffer_list_free(*input);
3736 *input = NULL;
3737
3738 return result;
3739 }
3740
3741 char *
3742 /* returns allocated base64 signature */
3743 management_query_pk_sig(struct management *man, const char *b64_data,
3744 const char *algorithm)
3745 {
3746 const char *prompt = "PK_SIGN";
3747 const char *desc = "pk-sign";
3748 struct buffer buf_data = alloc_buf(strlen(b64_data) + strlen(algorithm) + 20);
3749
3750 if (man->connection.client_version <= 1)
3751 {
3752 prompt = "RSA_SIGN";
3753 desc = "rsa-sign";
3754 }
3755
3756 buf_write(&buf_data, b64_data, (int) strlen(b64_data));
3757 if (man->connection.client_version > 2)
3758 {
3759 buf_write(&buf_data, ",", (int) strlen(","));
3760 buf_write(&buf_data, algorithm, (int) strlen(algorithm));
3761 }
3762 char *ret = management_query_multiline_flatten(man,
3763 (char *)buf_bptr(&buf_data), prompt, desc,
3764 &man->connection.ext_key_state, &man->connection.ext_key_input);
3765 free_buf(&buf_data);
3766 return ret;
3767 }
3768
3769 char *
3770 management_query_cert(struct management *man, const char *cert_name)
3771 {
3772 const char prompt_1[] = "NEED-CERTIFICATE:";
3773 struct buffer buf_prompt = alloc_buf(strlen(cert_name) + 20);
3774 buf_write(&buf_prompt, prompt_1, strlen(prompt_1));
3775 buf_write(&buf_prompt, cert_name, strlen(cert_name)+1); /* +1 for \0 */
3776
3777 char *result;
3778 result = management_query_multiline_flatten_newline(management,
3779 NULL, (char *)buf_bptr(&buf_prompt), "certificate",
3780 &man->connection.ext_cert_state, &man->connection.ext_cert_input);
3781 free_buf(&buf_prompt);
3782 return result;
3783 }
3784
3785 /*
3786 * Return true if management_hold() would block
3787 */
3788 bool
3789 management_would_hold(struct management *man)
3790 {
3791 return (man->settings.flags & MF_HOLD) && !man->persist.hold_release && man_standalone_ok(man);
3792 }
3793
3794 /*
3795 * Return true if (from the management interface's perspective) OpenVPN should
3796 * daemonize.
3797 */
3798 bool
3799 management_should_daemonize(struct management *man)
3800 {
3801 return management_would_hold(man) || (man->settings.flags & MF_QUERY_PASSWORDS);
3802 }
3803
3804 /*
3805 * If the hold flag is enabled, hibernate until a management client releases the hold.
3806 * Return true if the caller should not sleep for an additional time interval.
3807 */
3808 bool
3809 management_hold(struct management *man, int holdtime)
3810 {
3811 if (management_would_hold(man))
3812 {
3813 volatile int signal_received = 0;
3814 const bool standalone_disabled_save = man->persist.standalone_disabled;
3815 struct gc_arena gc = gc_new();
3816
3817 man->persist.standalone_disabled = false; /* This is so M_CLIENT messages will be correctly passed through msg() */
3818 man->persist.special_state_msg = NULL;
3819 man->settings.mansig |= MANSIG_IGNORE_USR1_HUP;
3820
3821 man_wait_for_client_connection(man, &signal_received, 0, MWCC_HOLD_WAIT);
3822
3823 if (!signal_received)
3824 {
3825 struct buffer out = alloc_buf_gc(128, &gc);
3826 buf_printf(&out, ">HOLD:Waiting for hold release:%d", holdtime);
3827 man->persist.special_state_msg = BSTR(&out);
3828 msg(M_CLIENT, "%s", man->persist.special_state_msg);
3829
3830 /* run command processing event loop until we get our username/password */
3831 do
3832 {
3833 man_standalone_event_loop(man, &signal_received, 0);
3834 if (!signal_received)
3835 {
3836 man_check_for_signals(&signal_received);
3837 }
3838 if (signal_received)
3839 {
3840 break;
3841 }
3842 } while (!man->persist.hold_release);
3843 }
3844
3845 /* revert state */
3846 man->persist.standalone_disabled = standalone_disabled_save;
3847 man->persist.special_state_msg = NULL;
3848 man->settings.mansig &= ~MANSIG_IGNORE_USR1_HUP;
3849
3850 gc_free(&gc);
3851 return true;
3852 }
3853 return false;
3854 }
3855
3856 /*
3857 * struct command_line
3858 */
3859
3860 struct command_line *
3861 command_line_new(const int buf_len)
3862 {
3863 struct command_line *cl;
3864 ALLOC_OBJ_CLEAR(cl, struct command_line);
3865 cl->buf = alloc_buf(buf_len);
3866 cl->residual = alloc_buf(buf_len);
3867 return cl;
3868 }
3869
3870 void
3871 command_line_reset(struct command_line *cl)
3872 {
3873 buf_clear(&cl->buf);
3874 buf_clear(&cl->residual);
3875 }
3876
3877 void
3878 command_line_free(struct command_line *cl)
3879 {
3880 if (!cl)
3881 {
3882 return;
3883 }
3884 command_line_reset(cl);
3885 free_buf(&cl->buf);
3886 free_buf(&cl->residual);
3887 free(cl);
3888 }
3889
3890 void
3891 command_line_add(struct command_line *cl, const unsigned char *buf, const int len)
3892 {
3893 int i;
3894 for (i = 0; i < len; ++i)
3895 {
3896 if (buf[i] && char_class(buf[i], (CC_PRINT|CC_NEWLINE)))
3897 {
3898 if (!buf_write_u8(&cl->buf, buf[i]))
3899 {
3900 buf_clear(&cl->buf);
3901 }
3902 }
3903 }
3904 }
3905
3906 const char *
3907 command_line_get(struct command_line *cl)
3908 {
3909 int i;
3910 const char *ret = NULL;
3911
3912 i = buf_substring_len(&cl->buf, '\n');
3913 if (i >= 0)
3914 {
3915 buf_copy_excess(&cl->residual, &cl->buf, i);
3916 buf_chomp(&cl->buf);
3917 ret = BSTR(&cl->buf);
3918 }
3919 return ret;
3920 }
3921
3922 void
3923 command_line_next(struct command_line *cl)
3924 {
3925 buf_clear(&cl->buf);
3926 buf_copy(&cl->buf, &cl->residual);
3927 buf_clear(&cl->residual);
3928 }
3929
3930 /*
3931 * struct log_entry
3932 */
3933
3934 const char *
3935 log_entry_print(const struct log_entry *e, unsigned int flags, struct gc_arena *gc)
3936 {
3937 struct buffer out = alloc_buf_gc(ERR_BUF_SIZE, gc);
3938 if (flags & LOG_FATAL_NOTIFY)
3939 {
3940 buf_printf(&out, ">FATAL:");
3941 }
3942 if (flags & LOG_PRINT_LOG_PREFIX)
3943 {
3944 buf_printf(&out, ">LOG:");
3945 }
3946 if (flags & LOG_PRINT_ECHO_PREFIX)
3947 {
3948 buf_printf(&out, ">ECHO:");
3949 }
3950 if (flags & LOG_PRINT_STATE_PREFIX)
3951 {
3952 buf_printf(&out, ">STATE:");
3953 }
3954 if (flags & LOG_PRINT_INT_DATE)
3955 {
3956 buf_printf(&out, "%u,", (unsigned int)e->timestamp);
3957 }
3958 if (flags & LOG_PRINT_MSG_FLAGS)
3959 {
3960 buf_printf(&out, "%s,", msg_flags_string(e->u.msg_flags, gc));
3961 }
3962 if (flags & LOG_PRINT_STATE)
3963 {
3964 buf_printf(&out, "%s,", man_state_name(e->u.state));
3965 }
3966 if (flags & LOG_PRINT_INTVAL)
3967 {
3968 buf_printf(&out, "%d,", e->u.intval);
3969 }
3970 if (e->string)
3971 {
3972 buf_printf(&out, "%s", e->string);
3973 }
3974 if (flags & LOG_PRINT_LOCAL_IP)
3975 {
3976 buf_printf(&out, ",%s", print_in_addr_t(e->local_ip, IA_EMPTY_IF_UNDEF, gc));
3977 }
3978 if (flags & LOG_PRINT_REMOTE_IP)
3979 {
3980 buf_printf(&out, ",%s", (!addr_defined(&e->remote_sock) ? "," :
3981 print_sockaddr_ex(&e->remote_sock.addr.sa, ",", PS_DONT_SHOW_FAMILY|PS_SHOW_PORT, gc)));
3982 buf_printf(&out, ",%s", (!addr_defined(&e->local_sock) ? "," :
3983 print_sockaddr_ex(&e->local_sock.addr.sa, ",", PS_DONT_SHOW_FAMILY|PS_SHOW_PORT, gc)));
3984 }
3985 if (flags & LOG_PRINT_LOCAL_IP && !IN6_IS_ADDR_UNSPECIFIED(&e->local_ip6))
3986 {
3987 buf_printf(&out, ",%s", print_in6_addr(e->local_ip6, IA_EMPTY_IF_UNDEF, gc));
3988 }
3989 if (flags & LOG_ECHO_TO_LOG)
3990 {
3991 msg(D_MANAGEMENT, "MANAGEMENT: %s", BSTR(&out));
3992 }
3993 if (flags & LOG_PRINT_CRLF)
3994 {
3995 buf_printf(&out, "\r\n");
3996 }
3997 return BSTR(&out);
3998 }
3999
4000 static void
4001 log_entry_free_contents(struct log_entry *e)
4002 {
4003 /* Cast away constness of const char* */
4004 free((char *)e->string);
4005 CLEAR(*e);
4006 }
4007
4008 /*
4009 * struct log_history
4010 */
4011
4012 static inline int
4013 log_index(const struct log_history *h, int i)
4014 {
4015 return modulo_add(h->base, i, h->capacity);
4016 }
4017
4018 static void
4019 log_history_obj_init(struct log_history *h, int capacity)
4020 {
4021 CLEAR(*h);
4022 h->capacity = capacity;
4023 ALLOC_ARRAY_CLEAR(h->array, struct log_entry, capacity);
4024 }
4025
4026 struct log_history *
4027 log_history_init(const int capacity)
4028 {
4029 struct log_history *h;
4030 ASSERT(capacity > 0);
4031 ALLOC_OBJ(h, struct log_history);
4032 log_history_obj_init(h, capacity);
4033 return h;
4034 }
4035
4036 static void
4037 log_history_free_contents(struct log_history *h)
4038 {
4039 int i;
4040 for (i = 0; i < h->size; ++i)
4041 {
4042 log_entry_free_contents(&h->array[log_index(h, i)]);
4043 }
4044 free(h->array);
4045 }
4046
4047 void
4048 log_history_close(struct log_history *h)
4049 {
4050 log_history_free_contents(h);
4051 free(h);
4052 }
4053
4054 void
4055 log_history_add(struct log_history *h, const struct log_entry *le)
4056 {
4057 struct log_entry *e;
4058 ASSERT(h->size >= 0 && h->size <= h->capacity);
4059 if (h->size == h->capacity)
4060 {
4061 e = &h->array[h->base];
4062 log_entry_free_contents(e);
4063 h->base = log_index(h, 1);
4064 }
4065 else
4066 {
4067 e = &h->array[log_index(h, h->size)];
4068 ++h->size;
4069 }
4070
4071 *e = *le;
4072 e->string = string_alloc(le->string, NULL);
4073 }
4074
4075 void
4076 log_history_resize(struct log_history *h, const int capacity)
4077 {
4078 if (capacity != h->capacity)
4079 {
4080 struct log_history newlog;
4081 int i;
4082
4083 ASSERT(capacity > 0);
4084 log_history_obj_init(&newlog, capacity);
4085
4086 for (i = 0; i < h->size; ++i)
4087 {
4088 log_history_add(&newlog, &h->array[log_index(h, i)]);
4089 }
4090
4091 log_history_free_contents(h);
4092 *h = newlog;
4093 }
4094 }
4095
4096 const struct log_entry *
4097 log_history_ref(const struct log_history *h, const int index)
4098 {
4099 if (index >= 0 && index < h->size)
4100 {
4101 return &h->array[log_index(h, (h->size - 1) - index)];
4102 }
4103 else
4104 {
4105 return NULL;
4106 }
4107 }
4108
4109 void
4110 management_sleep(const int n)
4111 {
4112 if (n < 0)
4113 {
4114 return;
4115 }
4116 else if (management)
4117 {
4118 management_event_loop_n_seconds(management, n);
4119 }
4120 else if (n > 0)
4121 {
4122 sleep(n);
4123 }
4124 }
4125
4126 void
4127 management_check_bytecount(struct context *c, struct management *man, struct timeval *timeval)
4128 {
4129 if (event_timeout_trigger(&man->connection.bytecount_update_interval,
4130 timeval, ETT_DEFAULT))
4131 {
4132 counter_type dco_read_bytes = 0;
4133 counter_type dco_write_bytes = 0;
4134
4135 if (dco_enabled(&c->options) && (dco_get_peer_stats(c) == 0))
4136 {
4137 dco_read_bytes = c->c2.dco_read_bytes;
4138 dco_write_bytes = c->c2.dco_write_bytes;
4139 }
4140
4141 if (!(man->persist.callback.flags & MCF_SERVER))
4142 {
4143 man_bytecount_output_client(man, dco_read_bytes, dco_write_bytes);
4144 }
4145 }
4146 }
4147
4148 /* DCO resets stats on reconnect. Since client expects stats
4149 * to be preserved across reconnects, we need to save DCO
4150 * stats before tearing the tunnel down.
4151 */
4152 void
4153 man_persist_client_stats(struct management *man, struct context *c)
4154 {
4155 if (dco_enabled(&c->options) && (dco_get_peer_stats(c) == 0))
4156 {
4157 management_bytes_client(man, c->c2.dco_read_bytes, c->c2.dco_write_bytes);
4158 }
4159 }
4160
4161 #else /* ifdef ENABLE_MANAGEMENT */
4162
4163 void
4164 management_sleep(const int n)
4165 {
4166 if (n > 0)
4167 {
4168 sleep(n);
4169 }
4170 }
4171
4172 #endif /* ENABLE_MANAGEMENT */