summaryrefslogtreecommitdiffstats
path: root/win32.c
blob: e6d7b483c97a132e4edb959264efb6b3e81d9478 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
/*
 *  OpenVPN -- An application to securely tunnel IP networks
 *             over a single UDP port, with support for SSL/TLS-based
 *             session authentication and key exchange,
 *             packet encryption, packet authentication, and
 *             packet compression.
 *
 *  Copyright (C) 2002-2008 Telethra, Inc. <sales@openvpn.net>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2
 *  as published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program (see the file COPYING included with this
 *  distribution); if not, write to the Free Software Foundation, Inc.,
 *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * Win32-specific OpenVPN code, targetted at the mingw
 * development environment.
 */
#include "syshead.h"

#ifdef WIN32

#include "buffer.h"
#include "error.h"
#include "mtu.h"
#include "sig.h"
#include "win32.h"
#include "misc.h"

#include "memdbg.h"

/*
 * Windows internal socket API state (opaque).
 */
static struct WSAData wsa_state; /* GLOBAL */

/*
 * Should we call win32_pause() on program exit?
 */
static bool pause_exit_enabled = false; /* GLOBAL */

/*
 * win32_signal is used to get input from the keyboard
 * if we are running in a console, or get input from an
 * event object if we are running as a service.
 */

struct win32_signal win32_signal; /* GLOBAL */

/*
 * Save our old window title so we can restore
 * it on exit.
 */
struct window_title window_title; /* GLOBAL*/

/*
 * Special global semaphore used to protect network
 * shell commands from simultaneous instantiation.
 */

struct semaphore netcmd_semaphore; /* GLOBAL */

/*
 * Windows system pathname such as c:\windows
 */
static char *win_sys_path = NULL; /* GLOBAL */

void
init_win32 (void)
{
  if (WSAStartup(0x0101, &wsa_state))
    {
      msg (M_ERR, "WSAStartup failed");
    }
  window_title_clear (&window_title);
  win32_signal_clear (&win32_signal);
  netcmd_semaphore_init ();
}

void
uninit_win32 (void)
{
  netcmd_semaphore_close ();
  if (pause_exit_enabled)
    {
      if (win32_signal.mode == WSO_MODE_UNDEF)
	{
	  struct win32_signal w;
	  win32_signal_open (&w, WSO_FORCE_CONSOLE, NULL, false);
	  win32_pause (&w);
	  win32_signal_close (&w);
	}
      else
	win32_pause (&win32_signal);
    }
  window_title_restore (&window_title);
  win32_signal_close (&win32_signal);
  WSACleanup ();
  free (win_sys_path);
}

void
set_pause_exit_win32 (void)
{
  pause_exit_enabled = true;
}

bool
init_security_attributes_allow_all (struct security_attributes *obj)
{
  CLEAR (*obj);

  obj->sa.nLength = sizeof (SECURITY_ATTRIBUTES);
  obj->sa.lpSecurityDescriptor = &obj->sd;
  obj->sa.bInheritHandle = FALSE;
  if (!InitializeSecurityDescriptor (&obj->sd, SECURITY_DESCRIPTOR_REVISION))
    return false;
  if (!SetSecurityDescriptorDacl (&obj->sd, TRUE, NULL, FALSE))
    return false;
  return true;
}

void
overlapped_io_init (struct overlapped_io *o,
		    const struct frame *frame,
		    BOOL event_state,
		    bool tuntap_buffer) /* if true: tuntap buffer, if false: socket buffer */
{
  CLEAR (*o);

  /* manual reset event, initially set according to event_state */
  o->overlapped.hEvent = CreateEvent (NULL, TRUE, event_state, NULL);
  if (o->overlapped.hEvent == NULL)
    msg (M_ERR, "Error: overlapped_io_init: CreateEvent failed");

  /* allocate buffer for overlapped I/O */
  alloc_buf_sock_tun (&o->buf_init, frame, tuntap_buffer, 0);
}

void
overlapped_io_close (struct overlapped_io *o)
{
  if (o->overlapped.hEvent)
    {
      if (!CloseHandle (o->overlapped.hEvent))
	msg (M_WARN | M_ERRNO, "Warning: CloseHandle failed on overlapped I/O event object");
    }
  free_buf (&o->buf_init);
}

char *
overlapped_io_state_ascii (const struct overlapped_io *o)
{
  switch (o->iostate)
    {
    case IOSTATE_INITIAL:
      return "0";
    case IOSTATE_QUEUED:
      return "Q";
    case IOSTATE_IMMEDIATE_RETURN:
      return "1";
    }
  return "?";
}

/*
 * Event-based notification of network events
 */

void
init_net_event_win32 (struct rw_handle *event, long network_events, socket_descriptor_t sd, unsigned int flags)
{
  /* manual reset events, initially set to unsignaled */

  /* initialize write event */
  if (!(flags & NE32_PERSIST_EVENT) || !event->write)
    {
      if (flags & NE32_WRITE_EVENT)
	{
	  event->write = CreateEvent (NULL, TRUE, FALSE, NULL);
	  if (event->write == NULL)
	    msg (M_ERR, "Error: init_net_event_win32: CreateEvent (write) failed");
	}
      else
	event->write = NULL;
    }

  /* initialize read event */
  if (!(flags & NE32_PERSIST_EVENT) || !event->read)
    {
      event->read = CreateEvent (NULL, TRUE, FALSE, NULL);
      if (event->read == NULL)
	msg (M_ERR, "Error: init_net_event_win32: CreateEvent (read) failed");
    }
  
  /* setup network events to change read event state */
  if (WSAEventSelect (sd, event->read, network_events) != 0)
    msg (M_FATAL | M_ERRNO_SOCK, "Error: init_net_event_win32: WSAEventSelect call failed");
}

long
reset_net_event_win32 (struct rw_handle *event, socket_descriptor_t sd)
{
  WSANETWORKEVENTS wne;  
  if (WSAEnumNetworkEvents (sd, event->read, &wne) != 0)
    {
      msg (M_FATAL | M_ERRNO_SOCK, "Error: reset_net_event_win32: WSAEnumNetworkEvents call failed");
      return 0; /* NOTREACHED */
    }
  else
    return wne.lNetworkEvents;
}

void
close_net_event_win32 (struct rw_handle *event, socket_descriptor_t sd, unsigned int flags)
{
  if (event->read)
    {
      if (socket_defined (sd))
	{
	  if (WSAEventSelect (sd, event->read, 0) != 0)
	    msg (M_WARN | M_ERRNO_SOCK, "Warning: close_net_event_win32: WSAEventSelect call failed");
	}
      if (!ResetEvent (event->read))
	msg (M_WARN | M_ERRNO, "Warning: ResetEvent (read) failed in close_net_event_win32");
      if (!(flags & NE32_PERSIST_EVENT))
	{
	  if (!CloseHandle (event->read))
	    msg (M_WARN | M_ERRNO, "Warning: CloseHandle (read) failed in close_net_event_win32");
	  event->read = NULL;
	}
    }

  if (event->write)
    {
      if (!ResetEvent (event->write))
	msg (M_WARN | M_ERRNO, "Warning: ResetEvent (write) failed in close_net_event_win32");
      if (!(flags & NE32_PERSIST_EVENT))
	{
	  if (!CloseHandle (event->write))
	    msg (M_WARN | M_ERRNO, "Warning: CloseHandle (write) failed in close_net_event_win32");
	  event->write = NULL;
	}
    }
}

/*
 * struct net_event_win32
 */

void
net_event_win32_init (struct net_event_win32 *ne)
{
  CLEAR (*ne);
  ne->sd = SOCKET_UNDEFINED;
}

void
net_event_win32_start (struct net_event_win32 *ne, long network_events, socket_descriptor_t sd)
{
  ASSERT (!socket_defined (ne->sd));
  ne->sd = sd;
  ne->event_mask = 0;
  init_net_event_win32 (&ne->handle, network_events, sd, NE32_PERSIST_EVENT|NE32_WRITE_EVENT);
}

void
net_event_win32_reset_write (struct net_event_win32 *ne)
{
  BOOL status;
  if (ne->event_mask & FD_WRITE)
    status = SetEvent (ne->handle.write);
  else
    status = ResetEvent (ne->handle.write);
  if (!status)
    msg (M_WARN | M_ERRNO, "Warning: SetEvent/ResetEvent failed in net_event_win32_reset_write");
}

void
net_event_win32_reset (struct net_event_win32 *ne)
{
  ne->event_mask |= reset_net_event_win32 (&ne->handle, ne->sd);
}

void
net_event_win32_stop (struct net_event_win32 *ne)
{
  if (net_event_win32_defined (ne))
    close_net_event_win32 (&ne->handle, ne->sd, NE32_PERSIST_EVENT);
  ne->sd = SOCKET_UNDEFINED;
  ne->event_mask = 0;
}

void
net_event_win32_close (struct net_event_win32 *ne)
{
  if (net_event_win32_defined (ne))
    close_net_event_win32 (&ne->handle, ne->sd, 0);
  net_event_win32_init (ne);
}

/*
 * Simulate *nix signals on Windows.
 *
 * Two modes:
 * (1) Console mode -- map keyboard function keys to signals
 * (2) Service mode -- map Windows event object to SIGTERM
 */

void
win32_signal_clear (struct win32_signal *ws)
{
  CLEAR (*ws);
}

void
win32_signal_open (struct win32_signal *ws,
		   int force,
		   const char *exit_event_name,
		   bool exit_event_initial_state)
{
  CLEAR (*ws);

  ws->mode = WSO_MODE_UNDEF;
  ws->in.read = INVALID_HANDLE_VALUE;
  ws->in.write = INVALID_HANDLE_VALUE;
  ws->console_mode_save = 0;
  ws->console_mode_save_defined = false;

  if (force == WSO_NOFORCE || force == WSO_FORCE_CONSOLE)
    {
      /*
       * Try to open console.
       */
      ws->in.read = GetStdHandle (STD_INPUT_HANDLE);
      if (ws->in.read != INVALID_HANDLE_VALUE)
	{
	  if (GetConsoleMode (ws->in.read, &ws->console_mode_save))
	    {
	      /* running on a console */
	      const DWORD new_console_mode = ws->console_mode_save
		& ~(ENABLE_WINDOW_INPUT
		    | ENABLE_PROCESSED_INPUT
		    | ENABLE_LINE_INPUT
		    | ENABLE_ECHO_INPUT 
		    | ENABLE_MOUSE_INPUT);

	      if (new_console_mode != ws->console_mode_save)
		{
		  if (!SetConsoleMode (ws->in.read, new_console_mode))
		    msg (M_ERR, "Error: win32_signal_open: SetConsoleMode failed");
		  ws->console_mode_save_defined = true;
		}
	      ws->mode = WSO_MODE_CONSOLE;
	    }
	  else
	    ws->in.read = INVALID_HANDLE_VALUE; /* probably running as a service */
	}
    }

  /*
   * If console open failed, assume we are running
   * as a service.
   */
  if ((force == WSO_NOFORCE || force == WSO_FORCE_SERVICE)
      && !HANDLE_DEFINED (ws->in.read) && exit_event_name)
    {
      struct security_attributes sa;

      if (!init_security_attributes_allow_all (&sa))
	msg (M_ERR, "Error: win32_signal_open: init SA failed");

      ws->in.read = CreateEvent (&sa.sa,
				 TRUE,
				 exit_event_initial_state ? TRUE : FALSE,
				 exit_event_name);
      if (ws->in.read == NULL)
	{
	  msg (M_WARN|M_ERRNO, "NOTE: CreateEvent '%s' failed", exit_event_name);
	}
      else
	{
	  if (WaitForSingleObject (ws->in.read, 0) != WAIT_TIMEOUT)
	    msg (M_FATAL, "ERROR: Exit Event ('%s') is signaled", exit_event_name);
	  else
	    ws->mode = WSO_MODE_SERVICE;
	}
    }
}

static bool
keyboard_input_available (struct win32_signal *ws)
{
  ASSERT (ws->mode == WSO_MODE_CONSOLE);
  if (HANDLE_DEFINED (ws->in.read))
    {
      DWORD n;
      if (GetNumberOfConsoleInputEvents (ws->in.read, &n))
	return n > 0;
    }
  return false;
}

static unsigned int
keyboard_ir_to_key (INPUT_RECORD *ir)
{
  if (ir->Event.KeyEvent.uChar.AsciiChar == 0)
    return ir->Event.KeyEvent.wVirtualScanCode;

  if ((ir->Event.KeyEvent.dwControlKeyState
       & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
      && (ir->Event.KeyEvent.wVirtualKeyCode != 18))
    return ir->Event.KeyEvent.wVirtualScanCode * 256;

  return ir->Event.KeyEvent.uChar.AsciiChar;
}

static unsigned int
win32_keyboard_get (struct win32_signal *ws)
{
  ASSERT (ws->mode == WSO_MODE_CONSOLE);
  if (HANDLE_DEFINED (ws->in.read))
    {
      INPUT_RECORD ir;
      do {
	DWORD n;
	if (!keyboard_input_available (ws))
	  return 0;
	if (!ReadConsoleInput (ws->in.read, &ir, 1, &n))
	  return 0;
      } while (ir.EventType != KEY_EVENT || ir.Event.KeyEvent.bKeyDown != TRUE);

      return keyboard_ir_to_key (&ir);
    }
  else
    return 0;
}

void
win32_signal_close (struct win32_signal *ws)
{
  if (ws->mode == WSO_MODE_SERVICE && HANDLE_DEFINED (ws->in.read))
    CloseHandle (ws->in.read);
  if (ws->console_mode_save_defined)
    {
      if (!SetConsoleMode (ws->in.read, ws->console_mode_save))
	msg (M_ERR, "Error: win32_signal_close: SetConsoleMode failed");
    }
  CLEAR (*ws);
}

/*
 * Return true if interrupt occurs in service mode.
 */
static bool
win32_service_interrupt (struct win32_signal *ws)
{
  if (ws->mode == WSO_MODE_SERVICE)
    {
      if (HANDLE_DEFINED (ws->in.read)
	  && WaitForSingleObject (ws->in.read, 0) == WAIT_OBJECT_0)
	return true;
    }
  return false;
}

int
win32_signal_get (struct win32_signal *ws)
{
  int ret = 0;
  if (siginfo_static.signal_received)
    {
      ret = siginfo_static.signal_received;
    }
  else
    {
      if (ws->mode == WSO_MODE_SERVICE)
	{
	  if (win32_service_interrupt (ws))
	    ret = SIGTERM;
	}
      else if (ws->mode == WSO_MODE_CONSOLE)
	{
	  switch (win32_keyboard_get (ws))
	    {
	    case 0x3B: /* F1 -> USR1 */
	      ret = SIGUSR1;
	      break;
	    case 0x3C: /* F2 -> USR2 */
	      ret = SIGUSR2;
	      break;
	    case 0x3D: /* F3 -> HUP */
	      ret = SIGHUP;
	      break;
	    case 0x3E: /* F4 -> TERM */
	      ret = SIGTERM;
	      break;
	    }
	}
      if (ret)
	{
	  siginfo_static.signal_received = ret;
	  siginfo_static.hard = true;
	}
    }
  return ret;
}

void
win32_pause (struct win32_signal *ws)
{
  if (ws->mode == WSO_MODE_CONSOLE && HANDLE_DEFINED (ws->in.read))
    {
      int status;
      msg (M_INFO|M_NOPREFIX, "Press any key to continue...");
      do {
	status = WaitForSingleObject (ws->in.read, INFINITE);
      } while (!win32_keyboard_get (ws));
    }
}

/* window functions */

void
window_title_clear (struct window_title *wt)
{
  CLEAR (*wt);
}

void
window_title_save (struct window_title *wt)
{
  if (!wt->saved)
    {
      if (!GetConsoleTitle (wt->old_window_title, sizeof (wt->old_window_title)))
	{
	  wt->old_window_title[0] = 0;
	  wt->saved = false;
	}
      else
	wt->saved = true;
    }
}

void
window_title_restore (const struct window_title *wt)
{
  if (wt->saved)
    SetConsoleTitle (wt->old_window_title);
}

void
window_title_generate (const char *title)
{
  struct gc_arena gc = gc_new ();
  struct buffer out = alloc_buf_gc (256, &gc);
  if (!title)
    title = "";
  buf_printf (&out, "[%s] " PACKAGE_NAME " " VERSION " F4:EXIT F1:USR1 F2:USR2 F3:HUP", title);
  SetConsoleTitle (BSTR (&out));
  gc_free (&gc);
}

/* semaphore functions */

void
semaphore_clear (struct semaphore *s)
{
  CLEAR (*s);
}

void
semaphore_open (struct semaphore *s, const char *name)
{
  struct security_attributes sa;

  s->locked = false;
  s->name = name;
  s->hand = NULL;

  if (init_security_attributes_allow_all (&sa))
    s->hand = CreateSemaphore(&sa.sa, 1, 1, name);

  if (s->hand == NULL)
    msg (M_WARN|M_ERRNO, "WARNING: Cannot create Win32 semaphore '%s'", name);
  else
    dmsg (D_SEMAPHORE, "Created Win32 semaphore '%s'", s->name);
}

bool
semaphore_lock (struct semaphore *s, int timeout_milliseconds)
{
  bool ret = true;

  if (s->hand)
    {
      DWORD status;
      ASSERT (!s->locked);

      dmsg (D_SEMAPHORE_LOW, "Attempting to lock Win32 semaphore '%s' prior to net shell command (timeout = %d sec)",
	   s->name,
	   timeout_milliseconds / 1000);
      status = WaitForSingleObject (s->hand, timeout_milliseconds);
      if (status == WAIT_FAILED)
	msg (M_ERR, "Wait failed on Win32 semaphore '%s'", s->name);
      ret = (status == WAIT_TIMEOUT) ? false : true;
      if (ret)
	{
	  dmsg (D_SEMAPHORE, "Locked Win32 semaphore '%s'", s->name);
	  s->locked = true;
	}
      else
	{
	  dmsg (D_SEMAPHORE, "Wait on Win32 semaphore '%s' timed out after %d milliseconds",
	       s->name,
	       timeout_milliseconds);
	}
    }
  return ret;
}

void
semaphore_release (struct semaphore *s)
{
  if (s->hand)
    {
      ASSERT (s->locked);
      dmsg (D_SEMAPHORE, "Releasing Win32 semaphore '%s'", s->name);
      if (!ReleaseSemaphore(s->hand, 1, NULL))
	msg (M_WARN | M_ERRNO, "ReleaseSemaphore failed on Win32 semaphore '%s'",
	     s->name);
      s->locked = false;
    }
}

void
semaphore_close (struct semaphore *s)
{
  if (s->hand)
    {
      if (s->locked)
	semaphore_release (s);
      dmsg (D_SEMAPHORE, "Closing Win32 semaphore '%s'", s->name);
      CloseHandle (s->hand);
      s->hand = NULL;
    }
}

/*
 * Special global semaphore used to protect network
 * shell commands from simultaneous instantiation.
 */

void
netcmd_semaphore_init (void)
{
  semaphore_open (&netcmd_semaphore, PACKAGE "_netcmd");
}

void
netcmd_semaphore_close (void)
{
  semaphore_close (&netcmd_semaphore);
}

void
netcmd_semaphore_lock (void)
{
  const int timeout_seconds = 600;
  if (!semaphore_lock (&netcmd_semaphore, timeout_seconds * 1000))
    msg (M_FATAL, "Cannot lock net command semaphore"); 
}

void
netcmd_semaphore_release (void)
{
  semaphore_release (&netcmd_semaphore);
}

/*
 * Get input from console.
 *
 * Return false on input error, or if service
 * exit event is signaled.
 */

bool
get_console_input_win32 (const char *prompt, const bool echo, char *input, const int capacity)
{
  HANDLE in = INVALID_HANDLE_VALUE;
  HANDLE err = INVALID_HANDLE_VALUE;
  DWORD len = 0;

  ASSERT (prompt);
  ASSERT (input);
  ASSERT (capacity > 0);

  input[0] = '\0';

  in = GetStdHandle (STD_INPUT_HANDLE);
  err = get_orig_stderr ();

  if (in != INVALID_HANDLE_VALUE
      && err != INVALID_HANDLE_VALUE
      && !win32_service_interrupt (&win32_signal)
      && WriteFile (err, prompt, strlen (prompt), &len, NULL))
    {
      bool is_console = (GetFileType (in) == FILE_TYPE_CHAR);
      DWORD flags_save = 0;
      int status = 0;

      if (is_console)
	{
	  if (GetConsoleMode (in, &flags_save))
	    {
	      DWORD flags = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
	      if (echo)
		flags |= ENABLE_ECHO_INPUT;
	      SetConsoleMode (in, flags);
	    }
	  else
	    is_console = 0;
	}

      status = ReadFile (in, input, capacity, &len, NULL);

      string_null_terminate (input, (int)len, capacity);
      chomp (input);

      if (!echo)
	WriteFile (err, "\r\n", 2, &len, NULL);
      if (is_console)
	SetConsoleMode (in, flags_save);
      if (status && !win32_service_interrupt (&win32_signal))
	return true;
    }

  return false;
}

/* get password from console */

char *
getpass (const char *prompt)
{
  static char line[256];
  if (get_console_input_win32 (prompt, false, line, sizeof (line)))
    return line;
  else
    return NULL;
}

/*
 * Return true if filename is safe to be used on Windows,
 * by avoiding the following reserved names:
 *
 * CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9,
 * LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9, and CLOCK$
 *
 * See: http://msdn.microsoft.com/en-us/library/aa365247.aspx
 *  and http://msdn.microsoft.com/en-us/library/86k9f82k(VS.80).aspx
 */

static bool
cmp_prefix (const char *str, const bool n, const char *pre)
{
  size_t i = 0;

  if (!str)
    return false;

  while (true)
    {
      const int c1 = pre[i];
      int c2 = str[i];
      ++i;
      if (c1 == '\0')
	{
	  if (n)
	    {
	      if (isdigit (c2))
		c2 = str[i];
	      else
		return false;
	    }
	  return c2 == '\0' || c2 == '.';
	}
      else if (c2 == '\0')
	return false;
      if (c1 != tolower(c2))
	return false;
    }
}

bool
win_safe_filename (const char *fn)
{
  if (cmp_prefix (fn, false, "con"))
    return false;
  if (cmp_prefix (fn, false, "prn"))
    return false;
  if (cmp_prefix (fn, false, "aux"))
    return false;
  if (cmp_prefix (fn, false, "nul"))
    return false;
  if (cmp_prefix (fn, true, "com"))
    return false;
  if (cmp_prefix (fn, true, "lpt"))
    return false;
  if (cmp_prefix (fn, false, "clock$"))
    return false;
  return true;
}

/*
 * Service functions for openvpn_execve
 */

static char *
env_block (const struct env_set *es)
{
  if (es)
    {
      struct env_item *e;
      char *ret;
      char *p;
      size_t nchars = 1;
      
      for (e = es->list; e != NULL; e = e->next)
	nchars += strlen (e->string) + 1;

      ret = (char *) malloc (nchars);
      check_malloc_return (ret);

      p = ret;
      for (e = es->list; e != NULL; e = e->next)
	{
	  if (env_allowed (e->string))
	    {
	      strcpy (p, e->string);
	      p += strlen (e->string) + 1;
	    }
	}
      *p = '\0';
      return ret;
    }
  else
    return NULL;
}

static char *
cmd_line (const struct argv *a)
{
  size_t nchars = 1;
  size_t maxlen = 0;
  size_t i;
  struct buffer buf;
  char *work = NULL;

  if (!a)
    return NULL;

  for (i = 0; i < a->argc; ++i)
    {
      const char *arg = a->argv[i];
      const size_t len = strlen (arg);
      nchars += len + 3;
      if (len > maxlen)
	maxlen = len;
    }

  work = (char *) malloc (maxlen + 1);
  check_malloc_return (work);
  buf = alloc_buf (nchars);

  for (i = 0; i < a->argc; ++i)
    {
      const char *arg = a->argv[i];
      strcpy (work, arg);
      string_mod (work, CC_PRINT, CC_DOUBLE_QUOTE|CC_CRLF, '_');
      if (i)
	buf_printf (&buf, " ");
      if (string_class (work, CC_ANY, CC_SPACE))
	buf_printf (&buf, "%s", work);
      else
	buf_printf (&buf, "\"%s\"", work);
    }

  free (work);
  return BSTR(&buf);
}

/*
 * Attempt to simulate fork/execve on Windows
 */
int
openvpn_execve (const struct argv *a, const struct env_set *es, const unsigned int flags)
{
  int ret = -1;
  if (a && a->argv[0])
    {
      if (openvpn_execve_allowed (flags))
	{
	  STARTUPINFO start_info;
	  PROCESS_INFORMATION proc_info;

	  char *env = env_block (es);
	  char *cl = cmd_line (a);
	  char *cmd = a->argv[0];

	  CLEAR (start_info);
	  CLEAR (proc_info);

	  /* fill in STARTUPINFO struct */
	  GetStartupInfo(&start_info);
	  start_info.cb = sizeof(start_info);
	  start_info.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
	  start_info.wShowWindow = SW_HIDE;
	  start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
	  start_info.hStdOutput = start_info.hStdError = GetStdHandle(STD_OUTPUT_HANDLE);

	  if (CreateProcess (cmd, cl, NULL, NULL, FALSE, 0, env, NULL, &start_info, &proc_info))
	    {
	      DWORD exit_status = 0;
	      CloseHandle (proc_info.hThread);
	      WaitForSingleObject (proc_info.hProcess, INFINITE);
	      if (GetExitCodeProcess (proc_info.hProcess, &exit_status))
		ret = (int)exit_status;
	      else
		msg (M_WARN|M_ERRNO, "openvpn_execve: GetExitCodeProcess %s failed", cmd);
	      CloseHandle (proc_info.hProcess);
	    }
	  else
	    {
	      msg (M_WARN|M_ERRNO, "openvpn_execve: CreateProcess %s failed", cmd);
	    }
	  free (cl);
	  free (env);
	}
      else
	{
	  msg (M_WARN, "openvpn_execve: external program may not be called due to setting of --script-security level");
	}
    }
  else
    {
      msg (M_WARN, "openvpn_execve: called with empty argv");
    }
  return ret;
}

char *
get_win_sys_path (void)
{
  ASSERT (win_sys_path);
  return win_sys_path;
}

void
set_win_sys_path (const char *newpath, struct env_set *es)
{
  free (win_sys_path);
  win_sys_path = string_alloc (newpath, NULL);
  setenv_str (es, SYS_PATH_ENV_VAR_NAME, win_sys_path); /* route.exe needs this */
}

void
set_win_sys_path_via_env (struct env_set *es)
{
  char buf[256];
  DWORD status = GetEnvironmentVariable (SYS_PATH_ENV_VAR_NAME, buf, sizeof(buf));
  if (!status)
    msg (M_ERR, "Cannot find environmental variable %s", SYS_PATH_ENV_VAR_NAME);
  if (status > sizeof (buf) - 1)
    msg (M_FATAL, "String overflow attempting to read environmental variable %s", SYS_PATH_ENV_VAR_NAME);
  set_win_sys_path (buf, es);
}

void
env_set_add_win32 (struct env_set *es)
{
  set_win_sys_path (DEFAULT_WIN_SYS_PATH, es);
}

#endif