big svn cleanup
[anytun.git] / src / openvpn / misc.c
blobe190b7baca4675324a47a9d5dabd6477a5a1e518
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.
8 * Copyright (C) 2002-2005 OpenVPN Solutions LLC <info@openvpn.net>
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.
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.
19 * You should have received a copy of the GNU General Public License
20 * along with this program (see the file COPYING included with this
21 * distribution); if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #ifdef WIN32
26 #include "config-win32.h"
27 #else
28 #include "config.h"
29 #endif
31 #include "syshead.h"
33 #include "buffer.h"
34 #include "misc.h"
35 #include "tun.h"
36 #include "error.h"
37 #include "thread.h"
38 #include "otime.h"
39 #include "plugin.h"
40 #include "options.h"
41 #include "manage.h"
43 #include "memdbg.h"
45 /* Redefine the top level directory of the filesystem
46 to restrict access to files for security */
47 void
48 do_chroot (const char *path)
50 if (path)
52 #ifdef HAVE_CHROOT
53 const char *top = "/";
54 if (chroot (path))
55 msg (M_ERR, "chroot to '%s' failed", path);
56 if (openvpn_chdir (top))
57 msg (M_ERR, "cd to '%s' failed", top);
58 msg (M_INFO, "chroot to '%s' and cd to '%s' succeeded", path, top);
59 #else
60 msg (M_FATAL, "Sorry but I can't chroot to '%s' because this operating system doesn't appear to support the chroot() system call", path);
61 #endif
65 /* Get/Set UID of process */
67 bool
68 get_user (const char *username, struct user_state *state)
70 bool ret = false;
71 CLEAR (*state);
72 if (username)
74 #if defined(HAVE_GETPWNAM) && defined(HAVE_SETUID)
75 state->pw = getpwnam (username);
76 if (!state->pw)
77 msg (M_ERR, "failed to find UID for user %s", username);
78 state->username = username;
79 ret = true;
80 #else
81 msg (M_FATAL, "Sorry but I can't setuid to '%s' because this operating system doesn't appear to support the getpwname() or setuid() system calls", username);
82 #endif
84 return ret;
87 void
88 set_user (const struct user_state *state)
90 #if defined(HAVE_GETPWNAM) && defined(HAVE_SETUID)
91 if (state->username && state->pw)
93 if (setuid (state->pw->pw_uid))
94 msg (M_ERR, "setuid('%s') failed", state->username);
95 msg (M_INFO, "UID set to %s", state->username);
97 #endif
100 /* Get/Set GID of process */
102 bool
103 get_group (const char *groupname, struct group_state *state)
105 bool ret = false;
106 CLEAR (*state);
107 if (groupname)
109 #if defined(HAVE_GETGRNAM) && defined(HAVE_SETGID)
110 state->gr = getgrnam (groupname);
111 if (!state->gr)
112 msg (M_ERR, "failed to find GID for group %s", groupname);
113 state->groupname = groupname;
114 ret = true;
115 #else
116 msg (M_FATAL, "Sorry but I can't setgid to '%s' because this operating system doesn't appear to support the getgrnam() or setgid() system calls", groupname);
117 #endif
119 return ret;
122 void
123 set_group (const struct group_state *state)
125 #if defined(HAVE_GETGRNAM) && defined(HAVE_SETGID)
126 if (state->groupname && state->gr)
128 if (setgid (state->gr->gr_gid))
129 msg (M_ERR, "setgid('%s') failed", state->groupname);
130 msg (M_INFO, "GID set to %s", state->groupname);
131 #ifdef HAVE_SETGROUPS
133 gid_t gr_list[1];
134 gr_list[0] = state->gr->gr_gid;
135 if (setgroups (1, gr_list))
136 msg (M_ERR, "setgroups('%s') failed", state->groupname);
138 #endif
140 #endif
143 /* Change process priority */
144 void
145 set_nice (int niceval)
147 if (niceval)
149 #ifdef HAVE_NICE
150 errno = 0;
151 nice (niceval);
152 if (errno != 0)
153 msg (M_WARN | M_ERRNO, "WARNING: nice %d failed", niceval);
154 else
155 msg (M_INFO, "nice %d succeeded", niceval);
156 #else
157 msg (M_WARN, "WARNING: nice %d failed (function not implemented)", niceval);
158 #endif
163 * Pass tunnel endpoint and MTU parms to a user-supplied script.
164 * Used to execute the up/down script/plugins.
166 void
167 run_up_down (const char *command,
168 const struct plugin_list *plugins,
169 int plugin_type,
170 const char *arg,
171 int tun_mtu,
172 int link_mtu,
173 const char *ifconfig_local,
174 const char* ifconfig_remote,
175 const char *context,
176 const char *signal_text,
177 const char *script_type,
178 struct env_set *es)
180 struct gc_arena gc = gc_new ();
182 if (signal_text)
183 setenv_str (es, "signal", signal_text);
184 setenv_str (es, "script_context", context);
185 setenv_int (es, "tun_mtu", tun_mtu);
186 setenv_int (es, "link_mtu", link_mtu);
187 setenv_str (es, "dev", arg);
189 if (!ifconfig_local)
190 ifconfig_local = "";
191 if (!ifconfig_remote)
192 ifconfig_remote = "";
193 if (!context)
194 context = "";
196 if (plugin_defined (plugins, plugin_type))
198 struct buffer cmd = alloc_buf_gc (256, &gc);
200 ASSERT (arg);
202 buf_printf (&cmd,
203 "%s %d %d %s %s %s",
204 arg,
205 tun_mtu, link_mtu,
206 ifconfig_local, ifconfig_remote,
207 context);
209 if (plugin_call (plugins, plugin_type, BSTR (&cmd), es))
210 msg (M_FATAL, "ERROR: up/down plugin call failed");
213 if (command)
215 struct buffer cmd = alloc_buf_gc (256, &gc);
217 ASSERT (arg);
219 setenv_str (es, "script_type", script_type);
221 buf_printf (&cmd,
222 "%s %s %d %d %s %s %s",
223 command,
224 arg,
225 tun_mtu, link_mtu,
226 ifconfig_local, ifconfig_remote,
227 context);
228 msg (M_INFO, "%s", BSTR (&cmd));
229 system_check (BSTR (&cmd), es, S_SCRIPT|S_FATAL, "script failed");
232 gc_free (&gc);
235 /* Get the file we will later write our process ID to */
236 void
237 get_pid_file (const char* filename, struct pid_state *state)
239 CLEAR (*state);
240 if (filename)
242 state->fp = fopen (filename, "w");
243 if (!state->fp)
244 msg (M_ERR, "Open error on pid file %s", filename);
245 state->filename = filename;
249 /* Write our PID to a file */
250 void
251 write_pid (const struct pid_state *state)
253 if (state->filename && state->fp)
255 unsigned int pid = openvpn_getpid ();
256 fprintf(state->fp, "%u\n", pid);
257 if (fclose (state->fp))
258 msg (M_ERR, "Close error on pid file %s", state->filename);
262 /* Get current PID */
263 unsigned int
264 openvpn_getpid ()
266 #ifdef WIN32
267 return (unsigned int) GetCurrentProcessId ();
268 #else
269 #ifdef HAVE_GETPID
270 return (unsigned int) getpid ();
271 #else
272 return 0;
273 #endif
274 #endif
277 /* Disable paging */
278 void
279 do_mlockall(bool print_msg)
281 #ifdef HAVE_MLOCKALL
282 if (mlockall (MCL_CURRENT | MCL_FUTURE))
283 msg (M_WARN | M_ERRNO, "WARNING: mlockall call failed");
284 else if (print_msg)
285 msg (M_INFO, "mlockall call succeeded");
286 #else
287 msg (M_WARN, "WARNING: mlockall call failed (function not implemented)");
288 #endif
291 #ifndef HAVE_DAEMON
294 daemon(int nochdir, int noclose)
296 #if defined(HAVE_FORK) && defined(HAVE_SETSID)
297 switch (fork())
299 case -1:
300 return (-1);
301 case 0:
302 break;
303 default:
304 openvpn_exit (OPENVPN_EXIT_STATUS_GOOD); /* exit point */
307 if (setsid() == -1)
308 return (-1);
310 if (!nochdir)
311 openvpn_chdir ("/");
313 if (!noclose)
314 set_std_files_to_null (false);
315 #else
316 msg (M_FATAL, "Sorry but I can't become a daemon because this operating system doesn't appear to support either the daemon() or fork() system calls");
317 #endif
318 return (0);
321 #endif
324 * Set standard file descriptors to /dev/null
326 void
327 set_std_files_to_null (bool stdin_only)
329 #if defined(HAVE_DUP) && defined(HAVE_DUP2)
330 int fd;
331 if ((fd = open ("/dev/null", O_RDWR, 0)) != -1)
333 dup2 (fd, 0);
334 if (!stdin_only)
336 dup2 (fd, 1);
337 dup2 (fd, 2);
339 if (fd > 2)
340 close (fd);
342 #endif
346 * Wrapper for chdir library function
349 openvpn_chdir (const char* dir)
351 #ifdef HAVE_CHDIR
352 return chdir (dir);
353 #else
354 return -1;
355 #endif
359 * dup inetd/xinetd socket descriptor and save
362 int inetd_socket_descriptor = SOCKET_UNDEFINED; /* GLOBAL */
364 void
365 save_inetd_socket_descriptor (void)
367 inetd_socket_descriptor = INETD_SOCKET_DESCRIPTOR;
368 #if defined(HAVE_DUP) && defined(HAVE_DUP2)
369 /* use handle passed by inetd/xinetd */
370 if ((inetd_socket_descriptor = dup (INETD_SOCKET_DESCRIPTOR)) < 0)
371 msg (M_ERR, "INETD_SOCKET_DESCRIPTOR dup(%d) failed", INETD_SOCKET_DESCRIPTOR);
372 set_std_files_to_null (true);
373 #endif
377 * Wrapper around the system() call.
380 openvpn_system (const char *command, const struct env_set *es, unsigned int flags)
382 #ifdef HAVE_SYSTEM
383 int ret;
386 * We need to bracket this code by mutex because system() doesn't
387 * accept an environment list, so we have to use the process-wide
388 * list which is shared between all threads.
390 mutex_lock_static (L_SYSTEM);
391 perf_push (PERF_SCRIPT);
394 * add env_set to environment.
396 if (flags & S_SCRIPT)
397 env_set_add_to_environment (es);
400 /* debugging */
401 dmsg (D_SCRIPT, "SYSTEM[%u] '%s'", flags, command);
402 if (flags & S_SCRIPT)
403 env_set_print (D_SCRIPT, es);
406 * execute the command
408 ret = system (command);
410 /* debugging */
411 dmsg (D_SCRIPT, "SYSTEM return=%u", ret);
414 * remove env_set from environment
416 if (flags & S_SCRIPT)
417 env_set_remove_from_environment (es);
419 perf_pop ();
420 mutex_unlock_static (L_SYSTEM);
421 return ret;
423 #else
424 msg (M_FATAL, "Sorry but I can't execute the shell command '%s' because this operating system doesn't appear to support the system() call", command);
425 return -1; /* NOTREACHED */
426 #endif
430 * Warn if a given file is group/others accessible.
432 void
433 warn_if_group_others_accessible (const char* filename)
435 #ifdef HAVE_STAT
436 struct stat st;
437 if (stat (filename, &st))
439 msg (M_WARN | M_ERRNO, "WARNING: cannot stat file '%s'", filename);
441 else
443 if (st.st_mode & (S_IRWXG|S_IRWXO))
444 msg (M_WARN, "WARNING: file '%s' is group or others accessible", filename);
446 #endif
450 * convert system() return into a success/failure value
452 bool
453 system_ok (int stat)
455 #ifdef WIN32
456 return stat == 0;
457 #else
458 return stat != -1 && WIFEXITED (stat) && WEXITSTATUS (stat) == 0;
459 #endif
463 * did system() call execute the given command?
465 bool
466 system_executed (int stat)
468 #ifdef WIN32
469 return stat != -1;
470 #else
471 return stat != -1 && WEXITSTATUS (stat) != 127;
472 #endif
476 * Print an error message based on the status code returned by system().
478 const char *
479 system_error_message (int stat, struct gc_arena *gc)
481 struct buffer out = alloc_buf_gc (256, gc);
482 #ifdef WIN32
483 if (stat == -1)
484 buf_printf (&out, "shell command did not execute -- ");
485 buf_printf (&out, "system() returned error code %d", stat);
486 #else
487 if (stat == -1)
488 buf_printf (&out, "shell command fork failed");
489 else if (!WIFEXITED (stat))
490 buf_printf (&out, "shell command did not exit normally");
491 else
493 const int cmd_ret = WEXITSTATUS (stat);
494 if (!cmd_ret)
495 buf_printf (&out, "shell command exited normally");
496 else if (cmd_ret == 127)
497 buf_printf (&out, "could not execute shell command");
498 else
499 buf_printf (&out, "shell command exited with error status: %d", cmd_ret);
501 #endif
502 return (const char *)out.data;
506 * Run system(), exiting on error.
508 bool
509 system_check (const char *command, const struct env_set *es, unsigned int flags, const char *error_message)
511 struct gc_arena gc = gc_new ();
512 const int stat = openvpn_system (command, es, flags);
513 int ret = false;
515 if (system_ok (stat))
516 ret = true;
517 else
519 if (error_message)
520 msg (((flags & S_FATAL) ? M_FATAL : M_WARN), "%s: %s",
521 error_message,
522 system_error_message (stat, &gc));
524 gc_free (&gc);
525 return ret;
529 * Initialize random number seed. random() is only used
530 * when "weak" random numbers are acceptable.
531 * OpenSSL routines are always used when cryptographically
532 * strong random numbers are required.
535 void
536 init_random_seed(void)
538 #ifdef HAVE_GETTIMEOFDAY
539 struct timeval tv;
541 if (!gettimeofday (&tv, NULL))
543 const unsigned int seed = (unsigned int) tv.tv_sec ^ tv.tv_usec;
544 srandom (seed);
546 #else /* HAVE_GETTIMEOFDAY */
547 const time_t current = time (NULL);
548 srandom ((unsigned int)current);
549 #endif /* HAVE_GETTIMEOFDAY */
552 /* thread-safe strerror */
554 const char *
555 strerror_ts (int errnum, struct gc_arena *gc)
557 #ifdef HAVE_STRERROR
558 struct buffer out = alloc_buf_gc (256, gc);
560 mutex_lock_static (L_STRERR);
561 buf_printf (&out, "%s", openvpn_strerror (errnum, gc));
562 mutex_unlock_static (L_STRERR);
563 return BSTR (&out);
564 #else
565 return "[error string unavailable]";
566 #endif
570 * Set environmental variable (int or string).
572 * On Posix, we use putenv for portability,
573 * and put up with its painful semantics
574 * that require all the support code below.
577 /* General-purpose environmental variable set functions */
579 static char *
580 construct_name_value (const char *name, const char *value, struct gc_arena *gc)
582 struct buffer out;
584 ASSERT (name);
585 if (!value)
586 value = "";
587 out = alloc_buf_gc (strlen (name) + strlen (value) + 2, gc);
588 buf_printf (&out, "%s=%s", name, value);
589 return BSTR (&out);
592 bool
593 deconstruct_name_value (const char *str, const char **name, const char **value, struct gc_arena *gc)
595 char *cp;
597 ASSERT (str);
598 ASSERT (name && value);
600 *name = cp = string_alloc (str, gc);
601 *value = NULL;
603 while ((*cp))
605 if (*cp == '=' && !*value)
607 *cp = 0;
608 *value = cp + 1;
610 ++cp;
612 return *name && *value;
615 static bool
616 env_string_equal (const char *s1, const char *s2)
618 int c1, c2;
619 ASSERT (s1);
620 ASSERT (s2);
622 while (true)
624 c1 = *s1++;
625 c2 = *s2++;
626 if (c1 == '=')
627 c1 = 0;
628 if (c2 == '=')
629 c2 = 0;
630 if (!c1 && !c2)
631 return true;
632 if (c1 != c2)
633 break;
635 return false;
638 static bool
639 remove_env_item (const char *str, const bool do_free, struct env_item **list)
641 struct env_item *current, *prev;
643 ASSERT (str);
644 ASSERT (list);
646 for (current = *list, prev = NULL; current != NULL; current = current->next)
648 if (env_string_equal (current->string, str))
650 if (prev)
651 prev->next = current->next;
652 else
653 *list = current->next;
654 if (do_free)
656 memset (current->string, 0, strlen (current->string));
657 free (current->string);
658 free (current);
660 return true;
662 prev = current;
664 return false;
667 static void
668 add_env_item (char *str, const bool do_alloc, struct env_item **list, struct gc_arena *gc)
670 struct env_item *item;
672 ASSERT (str);
673 ASSERT (list);
675 ALLOC_OBJ_GC (item, struct env_item, gc);
676 item->string = do_alloc ? string_alloc (str, gc): str;
677 item->next = *list;
678 *list = item;
681 /* struct env_set functions */
683 static bool
684 env_set_del_nolock (struct env_set *es, const char *str)
686 return remove_env_item (str, false, &es->list);
689 static void
690 env_set_add_nolock (struct env_set *es, const char *str)
692 remove_env_item (str, false, &es->list);
693 add_env_item ((char *)str, true, &es->list, es->gc);
696 struct env_set *
697 env_set_create (struct gc_arena *gc)
699 struct env_set *es;
700 ASSERT (gc);
701 mutex_lock_static (L_ENV_SET);
702 ALLOC_OBJ_CLEAR_GC (es, struct env_set, gc);
703 es->list = NULL;
704 es->gc = gc;
705 mutex_unlock_static (L_ENV_SET);
706 return es;
709 bool
710 env_set_del (struct env_set *es, const char *str)
712 bool ret;
713 ASSERT (es);
714 ASSERT (str);
715 mutex_lock_static (L_ENV_SET);
716 ret = env_set_del_nolock (es, str);
717 mutex_unlock_static (L_ENV_SET);
718 return ret;
721 void
722 env_set_add (struct env_set *es, const char *str)
724 ASSERT (es);
725 ASSERT (str);
726 mutex_lock_static (L_ENV_SET);
727 env_set_add_nolock (es, str);
728 mutex_unlock_static (L_ENV_SET);
731 void
732 env_set_print (int msglevel, const struct env_set *es)
734 if (check_debug_level (msglevel))
736 const struct env_item *e;
737 int i;
739 if (es)
741 mutex_lock_static (L_ENV_SET);
742 e = es->list;
743 i = 0;
745 while (e)
747 msg (msglevel, "ENV [%d] '%s'", i, e->string);
748 ++i;
749 e = e->next;
751 mutex_unlock_static (L_ENV_SET);
756 void
757 env_set_inherit (struct env_set *es, const struct env_set *src)
759 const struct env_item *e;
761 ASSERT (es);
763 if (src)
765 mutex_lock_static (L_ENV_SET);
766 e = src->list;
767 while (e)
769 env_set_add_nolock (es, e->string);
770 e = e->next;
772 mutex_unlock_static (L_ENV_SET);
776 void
777 env_set_add_to_environment (const struct env_set *es)
779 if (es)
781 struct gc_arena gc = gc_new ();
782 const struct env_item *e;
784 mutex_lock_static (L_ENV_SET);
785 e = es->list;
787 while (e)
789 const char *name;
790 const char *value;
792 if (deconstruct_name_value (e->string, &name, &value, &gc))
793 setenv_str (NULL, name, value);
795 e = e->next;
797 mutex_unlock_static (L_ENV_SET);
798 gc_free (&gc);
802 void
803 env_set_remove_from_environment (const struct env_set *es)
805 if (es)
807 struct gc_arena gc = gc_new ();
808 const struct env_item *e;
810 mutex_lock_static (L_ENV_SET);
811 e = es->list;
813 while (e)
815 const char *name;
816 const char *value;
818 if (deconstruct_name_value (e->string, &name, &value, &gc))
819 setenv_del (NULL, name);
821 e = e->next;
823 mutex_unlock_static (L_ENV_SET);
824 gc_free (&gc);
828 #ifdef HAVE_PUTENV
830 /* companion functions to putenv */
832 static struct env_item *global_env = NULL; /* GLOBAL */
834 static void
835 manage_env (char *str)
837 remove_env_item (str, true, &global_env);
838 add_env_item (str, false, &global_env, NULL);
841 #endif
843 /* add/modify/delete environmental strings */
845 void
846 setenv_counter (struct env_set *es, const char *name, counter_type value)
848 char buf[64];
849 openvpn_snprintf (buf, sizeof(buf), counter_format, value);
850 setenv_str (es, name, buf);
853 void
854 setenv_int (struct env_set *es, const char *name, int value)
856 char buf[64];
857 openvpn_snprintf (buf, sizeof(buf), "%d", value);
858 setenv_str (es, name, buf);
861 void
862 setenv_str (struct env_set *es, const char *name, const char *value)
864 setenv_str_ex (es, name, value, CC_NAME, 0, 0, CC_PRINT, 0, 0);
867 void
868 setenv_del (struct env_set *es, const char *name)
870 ASSERT (name);
871 setenv_str (es, name, NULL);
874 void
875 setenv_str_ex (struct env_set *es,
876 const char *name,
877 const char *value,
878 const unsigned int name_include,
879 const unsigned int name_exclude,
880 const char name_replace,
881 const unsigned int value_include,
882 const unsigned int value_exclude,
883 const char value_replace)
885 struct gc_arena gc = gc_new ();
886 const char *name_tmp;
887 const char *val_tmp = NULL;
889 ASSERT (name && strlen (name) > 1);
891 name_tmp = string_mod_const (name, name_include, name_exclude, name_replace, &gc);
893 if (value)
894 val_tmp = string_mod_const (value, value_include, value_exclude, value_replace, &gc);
896 if (es)
898 if (val_tmp)
900 const char *str = construct_name_value (name_tmp, val_tmp, &gc);
901 env_set_add (es, str);
903 else
904 env_set_del (es, name_tmp);
906 else
908 #if defined(WIN32)
910 /*msg (M_INFO, "SetEnvironmentVariable '%s' '%s'", name_tmp, val_tmp ? val_tmp : "NULL");*/
911 if (!SetEnvironmentVariable (name_tmp, val_tmp))
912 msg (M_WARN | M_ERRNO, "SetEnvironmentVariable failed, name='%s', value='%s'",
913 name_tmp,
914 val_tmp ? val_tmp : "NULL");
916 #elif defined(HAVE_PUTENV)
918 char *str = construct_name_value (name_tmp, val_tmp, NULL);
919 int status;
921 mutex_lock_static (L_PUTENV);
922 status = putenv (str);
923 /*msg (M_INFO, "PUTENV '%s'", str);*/
924 if (!status)
925 manage_env (str);
926 mutex_unlock_static (L_PUTENV);
927 if (status)
928 msg (M_WARN | M_ERRNO, "putenv('%s') failed", str);
930 #endif
933 gc_free (&gc);
937 * taken from busybox networking/ifupdown.c
939 unsigned int
940 count_bits(unsigned int a)
942 unsigned int result;
943 result = (a & 0x55) + ((a >> 1) & 0x55);
944 result = (result & 0x33) + ((result >> 2) & 0x33);
945 return((result & 0x0F) + ((result >> 4) & 0x0F));
949 count_netmask_bits(const char *dotted_quad)
951 unsigned int result, a, b, c, d;
952 /* Found a netmask... Check if it is dotted quad */
953 if (sscanf(dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
954 return -1;
955 result = count_bits(a);
956 result += count_bits(b);
957 result += count_bits(c);
958 result += count_bits(d);
959 return ((int)result);
963 * Go to sleep for n milliseconds.
965 void
966 sleep_milliseconds (unsigned int n)
968 #ifdef WIN32
969 Sleep (n);
970 #else
971 struct timeval tv;
972 tv.tv_sec = n / 1000;
973 tv.tv_usec = (n % 1000) * 1000;
974 select (0, NULL, NULL, NULL, &tv);
975 #endif
979 * Go to sleep indefinitely.
981 void
982 sleep_until_signal (void)
984 #ifdef WIN32
985 ASSERT (0);
986 #else
987 select (0, NULL, NULL, NULL, NULL);
988 #endif
991 /* return true if filename can be opened for read */
992 bool
993 test_file (const char *filename)
995 bool ret = false;
996 if (filename)
998 FILE *fp = fopen (filename, "r");
999 if (fp)
1001 fclose (fp);
1002 ret = true;
1006 dmsg (D_TEST_FILE, "TEST FILE '%s' [%d]",
1007 filename ? filename : "UNDEF",
1008 ret);
1010 return ret;
1013 /* create a temporary filename in directory */
1014 const char *
1015 create_temp_filename (const char *directory, struct gc_arena *gc)
1017 static unsigned int counter;
1018 struct buffer fname = alloc_buf_gc (256, gc);
1020 mutex_lock_static (L_CREATE_TEMP);
1021 ++counter;
1022 mutex_unlock_static (L_CREATE_TEMP);
1024 buf_printf (&fname, PACKAGE "_%u_%u.tmp",
1025 openvpn_getpid (),
1026 counter);
1028 return gen_path (directory, BSTR (&fname), gc);
1032 * Put a directory and filename together.
1034 const char *
1035 gen_path (const char *directory, const char *filename, struct gc_arena *gc)
1037 const char *safe_filename = string_mod_const (filename, CC_ALNUM|CC_UNDERBAR|CC_DASH|CC_DOT|CC_AT, 0, '_', gc);
1039 if (safe_filename
1040 && strcmp (safe_filename, ".")
1041 && strcmp (safe_filename, ".."))
1043 struct buffer out = alloc_buf_gc (256, gc);
1044 char dirsep[2];
1046 dirsep[0] = OS_SPECIFIC_DIRSEP;
1047 dirsep[1] = '\0';
1049 if (directory)
1050 buf_printf (&out, "%s%s", directory, dirsep);
1051 buf_printf (&out, "%s", safe_filename);
1053 return BSTR (&out);
1055 else
1056 return NULL;
1059 /* delete a file, return true if succeeded */
1060 bool
1061 delete_file (const char *filename)
1063 #if defined(WIN32)
1064 return (DeleteFile (filename) != 0);
1065 #elif defined(HAVE_UNLINK)
1066 return (unlink (filename) == 0);
1067 #else
1068 return false;
1069 #endif
1073 * Return the next largest power of 2
1074 * or u if u is a power of 2.
1076 unsigned int
1077 adjust_power_of_2 (unsigned int u)
1079 unsigned int ret = 1;
1081 while (ret < u)
1083 ret <<= 1;
1084 ASSERT (ret > 0);
1087 return ret;
1090 #ifdef HAVE_GETPASS
1092 static FILE *
1093 open_tty (const bool write)
1095 FILE *ret;
1096 ret = fopen ("/dev/tty", write ? "w" : "r");
1097 if (!ret)
1098 ret = write ? stderr : stdin;
1099 return ret;
1102 static void
1103 close_tty (FILE *fp)
1105 if (fp != stderr && fp != stdin)
1106 fclose (fp);
1109 #endif
1112 * Get input from console
1114 bool
1115 get_console_input (const char *prompt, const bool echo, char *input, const int capacity)
1117 bool ret = false;
1118 ASSERT (prompt);
1119 ASSERT (input);
1120 ASSERT (capacity > 0);
1121 input[0] = '\0';
1123 #if defined(WIN32)
1124 return get_console_input_win32 (prompt, echo, input, capacity);
1125 #elif defined(HAVE_GETPASS)
1126 if (echo)
1128 FILE *fp;
1130 fp = open_tty (true);
1131 fprintf (fp, "%s", prompt);
1132 fflush (fp);
1133 close_tty (fp);
1135 fp = open_tty (false);
1136 if (fgets (input, capacity, fp) != NULL)
1138 chomp (input);
1139 ret = true;
1141 close_tty (fp);
1143 else
1145 char *gp = getpass (prompt);
1146 if (gp)
1148 strncpynt (input, gp, capacity);
1149 memset (gp, 0, strlen (gp));
1150 ret = true;
1153 #else
1154 msg (M_FATAL, "Sorry, but I can't get console input on this OS");
1155 #endif
1156 return ret;
1160 * Get and store a username/password
1163 void
1164 get_user_pass (struct user_pass *up,
1165 const char *auth_file,
1166 const bool password_only,
1167 const char *prefix,
1168 const unsigned int flags)
1170 struct gc_arena gc = gc_new ();
1172 if (!up->defined)
1174 const bool from_stdin = (!auth_file || !strcmp (auth_file, "stdin"));
1176 #ifdef ENABLE_MANAGEMENT
1178 * Get username/password from standard input?
1180 if (management
1181 && ((auth_file && streq (auth_file, "management")) || (from_stdin && (flags & GET_USER_PASS_MANAGEMENT)))
1182 && management_query_user_pass_enabled (management))
1184 if (!management_query_user_pass (management, up, prefix, password_only))
1185 msg (M_FATAL, "ERROR: could not read %s username/password from management interface", prefix);
1187 else
1188 #endif
1190 * Get username/password from standard input?
1192 if (from_stdin)
1194 struct buffer user_prompt = alloc_buf_gc (128, &gc);
1195 struct buffer pass_prompt = alloc_buf_gc (128, &gc);
1197 buf_printf (&user_prompt, "Enter %s Username:", prefix);
1198 buf_printf (&pass_prompt, "Enter %s Password:", prefix);
1200 if (!password_only)
1202 if (!get_console_input (BSTR (&user_prompt), true, up->username, USER_PASS_LEN))
1203 msg (M_FATAL, "ERROR: could not read %s username from stdin", prefix);
1204 if (strlen (up->username) == 0)
1205 msg (M_FATAL, "ERROR: %s username is empty", prefix);
1208 if (!get_console_input (BSTR (&pass_prompt), false, up->password, USER_PASS_LEN))
1209 msg (M_FATAL, "ERROR: could not not read %s password from stdin", prefix);
1211 else
1214 * Get username/password from a file.
1216 FILE *fp;
1218 #ifndef ENABLE_PASSWORD_SAVE
1220 * Unless ENABLE_PASSWORD_SAVE is defined, don't allow sensitive passwords
1221 * to be read from a file.
1223 if (flags & GET_USER_PASS_SENSITIVE)
1224 msg (M_FATAL, "Sorry, '%s' password cannot be read from a file", prefix);
1225 #endif
1227 warn_if_group_others_accessible (auth_file);
1229 fp = fopen (auth_file, "r");
1230 if (!fp)
1231 msg (M_ERR, "Error opening '%s' auth file: %s", prefix, auth_file);
1233 if (password_only)
1235 if (fgets (up->password, USER_PASS_LEN, fp) == NULL)
1236 msg (M_FATAL, "Error reading password from %s authfile: %s",
1237 prefix,
1238 auth_file);
1240 else
1242 if (fgets (up->username, USER_PASS_LEN, fp) == NULL
1243 || fgets (up->password, USER_PASS_LEN, fp) == NULL)
1244 msg (M_FATAL, "Error reading username and password (must be on two consecutive lines) from %s authfile: %s",
1245 prefix,
1246 auth_file);
1249 fclose (fp);
1251 chomp (up->username);
1252 chomp (up->password);
1254 if (!password_only && strlen (up->username) == 0)
1255 msg (M_FATAL, "ERROR: username from %s authfile '%s' is empty", prefix, auth_file);
1258 string_mod (up->username, CC_PRINT, CC_CRLF, 0);
1259 string_mod (up->password, CC_PRINT, CC_CRLF, 0);
1261 up->defined = true;
1264 #if 0
1265 msg (M_INFO, "GET_USER_PASS %s u='%s' p='%s'", prefix, up->username, up->password);
1266 #endif
1268 gc_free (&gc);
1271 void
1272 purge_user_pass (struct user_pass *up, const bool force)
1274 const bool nocache = up->nocache;
1275 if (nocache || force)
1277 CLEAR (*up);
1278 up->nocache = nocache;
1283 * Process string received by untrusted peer before
1284 * printing to console or log file.
1286 * Assumes that string has been null terminated.
1288 const char *
1289 safe_print (const char *str, struct gc_arena *gc)
1291 return string_mod_const (str, CC_PRINT, CC_CRLF, '.', gc);
1294 /* Make arrays of strings */
1296 const char **
1297 make_env_array (const struct env_set *es, struct gc_arena *gc)
1299 char **ret = NULL;
1300 struct env_item *e = NULL;
1301 int i = 0, n = 0;
1303 /* figure length of es */
1304 if (es)
1306 for (e = es->list; e != NULL; e = e->next)
1307 ++n;
1310 /* alloc return array */
1311 ALLOC_ARRAY_CLEAR_GC (ret, char *, n+1, gc);
1313 /* fill return array */
1314 if (es)
1316 e = es->list;
1317 for (i = 0; i < n; ++i)
1319 ASSERT (e);
1320 ret[i] = e->string;
1321 e = e->next;
1325 ret[i] = NULL;
1326 return (const char **)ret;
1329 const char **
1330 make_arg_array (const char *first, const char *parms, struct gc_arena *gc)
1332 char **ret = NULL;
1333 int base = 0;
1334 const int max_parms = MAX_PARMS + 2;
1335 int n = 0;
1337 /* alloc return array */
1338 ALLOC_ARRAY_CLEAR_GC (ret, char *, max_parms, gc);
1340 /* process first parameter, if provided */
1341 if (first)
1343 ret[base++] = string_alloc (first, gc);
1346 if (parms)
1348 n = parse_line (parms, &ret[base], max_parms - base - 1, "make_arg_array", 0, M_WARN, gc);
1349 ASSERT (n >= 0 && n + base + 1 <= max_parms);
1351 ret[base + n] = NULL;
1353 return (const char **)ret;
1356 void
1357 openvpn_sleep (const int n)
1359 #ifdef ENABLE_MANAGEMENT
1360 if (management)
1362 management_event_loop_n_seconds (management, n);
1363 return;
1365 #endif
1366 sleep (n);