Welcome to mirror list, hosted at ThFree Co, Russian Federation.

cygserver.cc « cygwin « winsup - cygwin.com/git/newlib-cygwin.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0c0740379bf40d88986bad4daad79f2e8151ec53 (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
/* cygserver.cc

   Copyright 2001, 2002 Red Hat Inc.

   Written by Egor Duda <deo@logos-m.ru>

This file is part of Cygwin.

This software is a copyrighted work licensed under the terms of the
Cygwin license.  Please consult the file "CYGWIN_LICENSE" for
details. */

#include "woutsup.h"

#include <sys/types.h>

#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <getopt.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "cygerrno.h"
#include "cygwin_version.h"

#include "cygwin/cygserver.h"
#include "cygwin/cygserver_process.h"
#include "cygwin/cygserver_transport.h"

// Version string.
static const char version[] = "$Revision$";

/*
 * Support function for the XXX_printf () macros in "woutsup.h".
 * Copied verbatim from "strace.cc".
 */
static int
getfunc (char *in_dst, const char *func)
{
  const char *p;
  const char *pe;
  char *dst = in_dst;
  for (p = func; (pe = strchr (p, '(')); p = pe + 1)
    if (isalnum ((int)pe[-1]) || pe[-1] == '_')
      break;
    else if (isspace ((int)pe[-1]))
      {
	pe--;
	break;
      }
  if (!pe)
    pe = strchr (func, '\0');
  for (p = pe; p > func; p--)
    if (p != pe && *p == ' ')
      {
	p++;
	break;
      }
  if (*p == '*')
    p++;
  while (p < pe)
    *dst++ = *p++;

  *dst++ = ':';
  *dst++ = ' ';
  *dst = '\0';

  return dst - in_dst;
}

/*
 * Support function for the XXX_printf () macros in "woutsup.h".
 */
extern "C" void
__cygserver__printf (const char *const function, const char *const fmt, ...)
{
  const DWORD lasterror = GetLastError ();
  const int lasterrno = errno;

  va_list ap;

  char *const buf = (char *) alloca (BUFSIZ);

  assert (buf);

  int len = 0;

  if (function)
    len += getfunc (buf, function);

  va_start (ap, fmt);
  len += vsnprintf (buf + len, BUFSIZ - len, fmt, ap);
  va_end (ap);

  len += snprintf (buf + len, BUFSIZ - len, "\n");

  const int actual = (len > BUFSIZ ? BUFSIZ : len);

  write (2, buf, actual);

  errno = lasterrno;
  SetLastError (lasterror);

  return;
}

#ifdef DEBUGGING

int __stdcall
__set_errno (const char *func, int ln, int val)
{
  debug_printf ("%s:%d val %d", func, ln, val);
  return _impure_ptr->_errno = val;
}

#endif /* DEBUGGING */

GENERIC_MAPPING access_mapping;

static BOOL
setup_privileges ()
{
  BOOL rc, ret_val;
  HANDLE hToken = NULL;
  TOKEN_PRIVILEGES sPrivileges;

  rc = OpenProcessToken (GetCurrentProcess () , TOKEN_ALL_ACCESS , &hToken) ;
  if (!rc)
    {
      system_printf ("error opening process token (%lu)", GetLastError ());
      ret_val = FALSE;
      goto out;
    }
  rc = LookupPrivilegeValue (NULL, SE_DEBUG_NAME, &sPrivileges.Privileges[0].Luid);
  if (!rc)
    {
      system_printf ("error getting privilege luid (%lu)", GetLastError ());
      ret_val = FALSE;
      goto out;
    }
  sPrivileges.PrivilegeCount = 1 ;
  sPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED ;
  rc = AdjustTokenPrivileges (hToken, FALSE, &sPrivileges, 0, NULL, NULL) ;
  if (!rc)
    {
      system_printf ("error adjusting privilege level. (%lu)",
		     GetLastError ());
      ret_val = FALSE;
      goto out;
    }

  access_mapping.GenericRead = FILE_READ_DATA;
  access_mapping.GenericWrite = FILE_WRITE_DATA;
  access_mapping.GenericExecute = 0;
  access_mapping.GenericAll = FILE_READ_DATA | FILE_WRITE_DATA;

  ret_val = TRUE;

out:
  CloseHandle (hToken);
  return ret_val;
}

int
check_and_dup_handle (HANDLE from_process, HANDLE to_process,
		      HANDLE from_process_token,
		      DWORD access,
		      HANDLE from_handle,
		      HANDLE *to_handle_ptr, BOOL bInheritHandle = FALSE)
{
  HANDLE local_handle = NULL;
  int ret_val = EACCES;

  if (from_process != GetCurrentProcess ())
    {
      if (!DuplicateHandle (from_process, from_handle,
			    GetCurrentProcess (), &local_handle,
			    0, bInheritHandle,
			    DUPLICATE_SAME_ACCESS))
	{
	  system_printf ("error getting handle(%u) to server (%lu)",
			 (unsigned int)from_handle, GetLastError ());
	  goto out;
	}
    } else
      local_handle = from_handle;

  if (!wincap.has_security ())
    assert (!from_process_token);
  else
    {
      char sd_buf [1024];
      PSECURITY_DESCRIPTOR sd = (PSECURITY_DESCRIPTOR) &sd_buf;
      DWORD bytes_needed;
      PRIVILEGE_SET ps;
      DWORD ps_len = sizeof (ps);
      BOOL status;

      if (!GetKernelObjectSecurity (local_handle,
				    (OWNER_SECURITY_INFORMATION
				     | GROUP_SECURITY_INFORMATION
				     | DACL_SECURITY_INFORMATION),
				    sd, sizeof (sd_buf), &bytes_needed))
	{
	  system_printf ("error getting handle SD (%lu)", GetLastError ());
	  goto out;
	}

      MapGenericMask (&access, &access_mapping);

      if (!AccessCheck (sd, from_process_token, access, &access_mapping,
			&ps, &ps_len, &access, &status))
	{
	  system_printf ("error checking access rights (%lu)",
			 GetLastError ());
	  goto out;
	}

      if (!status)
	{
	  system_printf ("access to object denied");
	  goto out;
	}
    }

  if (!DuplicateHandle (from_process, from_handle,
			to_process, to_handle_ptr,
			access, bInheritHandle, 0))
    {
      system_printf ("error getting handle to client (%lu)", GetLastError ());
      goto out;
    }

  // verbose: debug_printf ("Duplicated %p to %p", from_handle, *to_handle_ptr);

  ret_val = 0;

 out:
  if (local_handle && from_process != GetCurrentProcess ())
    CloseHandle (local_handle);

  return (ret_val);
}

/*
 * client_request_attach_tty::serve ()
 */

void
client_request_attach_tty::serve (transport_layer_base *const conn,
				  process_cache *)
{
  assert (conn);

  assert (!error_code ());

  if (!wincap.has_security ())
    {
      syscall_printf ("operation only supported on systems with security");
      error_code (EINVAL);
      msglen (0);
      return;
    }

  if (msglen () != sizeof (req))
    {
      syscall_printf ("bad request body length: expecting %lu bytes, got %lu",
		      sizeof (req), msglen ());
      error_code (EINVAL);
      msglen (0);
      return;
    }

  msglen (0);			// Until we fill in some fields.

  // verbose: debug_printf ("pid %ld:(%p,%p) -> pid %ld",
  //			    req.master_pid, req.from_master, req.to_master,
  //			    req.pid);

  // verbose: debug_printf ("opening process %ld", req.master_pid);

  const HANDLE from_process_handle =
    OpenProcess (PROCESS_DUP_HANDLE, FALSE, req.master_pid);

  if (!from_process_handle)
    {
      system_printf ("error opening `from' process, error = %lu",
		     GetLastError ());
      error_code (EACCES);
      return;
    }

  // verbose: debug_printf ("opening process %ld", req.pid);

  const HANDLE to_process_handle =
    OpenProcess (PROCESS_DUP_HANDLE, FALSE, req.pid);

  if (!to_process_handle)
    {
      system_printf ("error opening `to' process, error = %lu",
		     GetLastError ());
      CloseHandle (from_process_handle);
      error_code (EACCES);
      return;
    }

  // verbose: debug_printf ("Impersonating client");
  conn->impersonate_client ();

  HANDLE token_handle = NULL;

  // verbose: debug_printf ("about to open thread token");
  const DWORD rc = OpenThreadToken (GetCurrentThread (),
				    TOKEN_QUERY,
				    TRUE,
				    &token_handle);

  // verbose: debug_printf ("opened thread token, rc=%lu", rc);
  conn->revert_to_self ();

  if (!rc)
    {
      system_printf ("error opening thread token, error = %lu",
		     GetLastError ());
      CloseHandle (from_process_handle);
      CloseHandle (to_process_handle);
      error_code (EACCES);
      return;
    }

  // From this point on, a reply body is returned to the client.

  const HANDLE from_master = req.from_master;
  const HANDLE to_master = req.to_master;

  req.from_master = NULL;
  req.to_master = NULL;

  msglen (sizeof (req));

  if (from_master)
    if (check_and_dup_handle (from_process_handle, to_process_handle,
			      token_handle,
			      GENERIC_READ,
			      from_master,
			      &req.from_master, TRUE) != 0)
      {
	system_printf ("error duplicating from_master handle, error = %lu",
		       GetLastError ());
	error_code (EACCES);
      }

  if (to_master)
    if (check_and_dup_handle (from_process_handle, to_process_handle,
			      token_handle,
			      GENERIC_WRITE,
			      to_master,
			      &req.to_master, TRUE) != 0)
      {
	system_printf ("error duplicating to_master handle, error = %lu",
		       GetLastError ());
	error_code (EACCES);
      }

  CloseHandle (from_process_handle);
  CloseHandle (to_process_handle);
  CloseHandle (token_handle);

  debug_printf ("%lu(%lu, %lu) -> %lu(%lu,%lu)",
		req.master_pid, from_master, to_master,
		req.pid, req.from_master, req.to_master);

  return;
}

void
client_request_get_version::serve (transport_layer_base *, process_cache *)
{
  assert (!error_code ());

  if (msglen ())
    syscall_printf ("unexpected request body ignored: %lu bytes", msglen ());

  msglen (sizeof (version));

  version.major = CYGWIN_SERVER_VERSION_MAJOR;
  version.api   = CYGWIN_SERVER_VERSION_API;
  version.minor = CYGWIN_SERVER_VERSION_MINOR;
  version.patch = CYGWIN_SERVER_VERSION_PATCH;
}

class server_request : public queue_request
{
public:
  server_request (transport_layer_base *const conn, process_cache *const cache)
    : _conn (conn), _cache (cache)
  {}

  virtual ~server_request ()
  {
    safe_delete (_conn);
  }

  virtual void process ()
  {
    client_request::handle_request (_conn, _cache);
  }

private:
  transport_layer_base *const _conn;
  process_cache *const _cache;
};

class server_submission_loop : public queue_submission_loop
{
public:
  server_submission_loop (threaded_queue *const queue,
			  transport_layer_base *const transport,
			  process_cache *const cache)
    : queue_submission_loop (queue, false),
      _transport (transport),
      _cache (cache)
  {
    assert (_transport);
    assert (_cache);
  }

private:
  transport_layer_base *const _transport;
  process_cache *const _cache;

  virtual void request_loop ();
};

/* FIXME: this is a little ugly.  What we really want is to wait on
 * two objects: one for the pipe/socket, and one for being told to
 * shutdown.  Otherwise this will stay a problem (we won't actually
 * shutdown until the request _AFTER_ the shutdown request.  And
 * sending ourselves a request is ugly
 */
void
server_submission_loop::request_loop ()
{
  /* I'd like the accepting thread's priority to be above any "normal"
   * thread in the system to avoid overflowing the listen queue (for
   * sockets; similar issues exist for named pipes); but, for example,
   * a normal priority thread in a foregrounded process is boosted to
   * THREAD_PRIORITY_HIGHEST (AFAICT).  Thus try to set the current
   * thread's priority to a level one above that.  This fails on
   * win9x/ME so assume any failure in that call is due to that and
   * simply call again at one priority level lower.
   */
  if (!SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_HIGHEST + 1))
    if (!SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_HIGHEST))
      debug_printf ("failed to raise accept thread priority, error = %lu",
		    GetLastError ());

  while (_running)
    {
      bool recoverable = false;
      transport_layer_base *const conn = _transport->accept (&recoverable);
      if (!conn && !recoverable)
	{
	  system_printf ("fatal error on IPC transport: closing down");
	  return;
	}
      // EINTR probably implies a shutdown request; so back off for a
      // moment to let the main thread take control, otherwise the
      // server spins here receiving EINTR repeatedly since the signal
      // handler in the main thread doesn't get a chance to be called.
      if (!conn && errno == EINTR)
	{
	  if (!SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_NORMAL))
	    debug_printf ("failed to reset thread priority, error = %lu",
			  GetLastError ());

	  Sleep (0);
	  if (!SetThreadPriority (GetCurrentThread (),
				  THREAD_PRIORITY_HIGHEST + 1))
	    if (!SetThreadPriority (GetCurrentThread (),
				    THREAD_PRIORITY_HIGHEST))
	      debug_printf ("failed to raise thread priority, error = %lu",
			    GetLastError ());
	}
      if (conn)
	_queue->add (safe_new (server_request, conn, _cache));
    }
}

client_request_shutdown::client_request_shutdown ()
  : client_request (CYGSERVER_REQUEST_SHUTDOWN)
{
  // verbose: syscall_printf ("created");
}

void
client_request_shutdown::serve (transport_layer_base *, process_cache *)
{
  assert (!error_code ());

  if (msglen ())
    syscall_printf ("unexpected request body ignored: %lu bytes", msglen ());

  /* FIXME: link upwards, and then this becomes a trivial method call to
   * only shutdown _this queue_
   */

  kill (getpid (), SIGINT);

  msglen (0);
}

static sig_atomic_t shutdown_server = false;

static void
handle_signal (const int signum)
{
  /* any signal makes us die :} */

  shutdown_server = true;
}

/*
 * print_usage ()
 */

static void
print_usage (const char *const pgm)
{
  printf ("Usage: %s [OPTIONS]\n", pgm);
  printf ("  -c, --cleanup-threads   number of cleanup threads to use\n");
  printf ("  -h, --help              output usage information and exit\n");
  printf ("  -r, --request-threads   number of request threads to use\n");
  printf ("  -s, --shutdown          shutdown the daemon\n");
  printf ("  -v, --version           output version information and exit\n");
}

/*
 * print_version ()
 */

static void
print_version (const char *const pgm)
{
  char *vn = NULL;

  const char *const colon = strchr (version, ':');

  if (!colon)
    {
      vn = strdup ("?");
    }
  else
    {
      vn = strdup (colon + 2);	// Skip ": "

      char *const spc = strchr (vn, ' ');

      if (spc)
	*spc = '\0';
    }

  char buf[200];
  snprintf (buf, sizeof (buf), "%d.%d.%d(%d.%d/%d/%d)-(%d.%d.%d.%d) %s",
	    cygwin_version.dll_major / 1000,
	    cygwin_version.dll_major % 1000,
	    cygwin_version.dll_minor,
	    cygwin_version.api_major,
	    cygwin_version.api_minor,
	    cygwin_version.shared_data,
	    CYGWIN_SERVER_VERSION_MAJOR,
	    CYGWIN_SERVER_VERSION_API,
	    CYGWIN_SERVER_VERSION_MINOR,
	    CYGWIN_SERVER_VERSION_PATCH,
	    cygwin_version.mount_registry,
	    cygwin_version.dll_build_date);

  printf ("%s (cygwin) %s\n", pgm, vn);
  printf ("API version %s\n", buf);
  printf ("Copyright 2001, 2002 Red Hat, Inc.\n");
  printf ("Compiled on %s\n", __DATE__);

  free (vn);
}

/*
 * main ()
 */

int
main (const int argc, char *argv[])
{
  const struct option longopts[] = {
    {"cleanup-threads", required_argument, NULL, 'c'},
    {"help", no_argument, NULL, 'h'},
    {"request-threads", required_argument, NULL, 'r'},
    {"shutdown", no_argument, NULL, 's'},
    {"version", no_argument, NULL, 'v'},
    {0, no_argument, NULL, 0}
  };

  const char opts[] = "c:hr:sv";

  int cleanup_threads = 2;
  int request_threads = 10;
  bool shutdown = false;

  const char *pgm = NULL;

  if (!(pgm = strrchr (*argv, '\\')) && !(pgm = strrchr (*argv, '/')))
    pgm = *argv;
  else
    pgm++;

  wincap.init ();
  if (wincap.has_security ())
    setup_privileges ();

  int opt;

  while ((opt = getopt_long (argc, argv, opts, longopts, NULL)) != EOF)
    switch (opt)
      {
      case 'c':
	cleanup_threads = atoi (optarg);
	if (cleanup_threads <= 0)
	  {
	    fprintf (stderr,
		     "%s: number of cleanup threads must be positive\n",
		     pgm);
	    exit (1);
	  }
	break;

      case 'h':
	print_usage (pgm);
	return 0;

      case 'r':
	request_threads = atoi (optarg);
	if (request_threads <= 0)
	  {
	    fprintf (stderr,
		     "%s: number of request threads must be positive\n",
		     pgm);
	    exit (1);
	  }
	break;

      case 's':
	shutdown = true;
	break;

      case 'v':
	print_version (pgm);
	return 0;

      case '?':
	fprintf (stderr, "Try `%s --help' for more information.\n", pgm);
	exit (1);
      }

  if (optind != argc)
    {
      fprintf (stderr, "%s: too many arguments\n", pgm);
      exit (1);
    }

  if (shutdown)
    {
      /* Setting `cygserver_running' stops the request code making a
       * version request, which is not much to the point.
       */
      cygserver_running = CYGSERVER_OK;

      client_request_shutdown req;

      if (req.make_request () == -1 || req.error_code ())
	{
	  fprintf (stderr, "%s: shutdown request failed: %s\n",
		   pgm, strerror (req.error_code ()));
	  exit (1);
	}

      // FIXME: It would be nice to wait here for the daemon to exit.

      return 0;
    }

#define SIGHANDLE(SIG)							\
  do									\
    {									\
      struct sigaction act;						\
									\
      act.sa_handler = &handle_signal;					\
      act.sa_mask = 0;							\
      act.sa_flags = 0;							\
									\
      if (sigaction (SIG, &act, NULL) == -1)				\
	{								\
	  system_printf ("failed to install handler for " #SIG ": %s",	\
			 strerror (errno));				\
	  exit (1);							\
	}								\
    } while (false)

  SIGHANDLE (SIGHUP);
  SIGHANDLE (SIGINT);
  SIGHANDLE (SIGTERM);

  print_version (pgm);
  setbuf (stdout, NULL);
  printf ("daemon starting up");

  threaded_queue request_queue (request_threads);
  printf (".");

  transport_layer_base *const transport = create_server_transport ();
  assert (transport);
  printf (".");

  process_cache cache (cleanup_threads);
  printf (".");

  server_submission_loop submission_loop (&request_queue, transport, &cache);
  printf (".");

  request_queue.add_submission_loop (&submission_loop);
  printf (".");

  if (transport->listen () == -1)
    {
      exit (1);
    }
  printf (".");

  cache.start ();
  printf (".");

  request_queue.start ();
  printf (".");

  printf ("complete\n");

  /* TODO: wait on multiple objects - the thread handle for each
   * request loop + all the process handles. This should be done by
   * querying the request_queue and the process cache for all their
   * handles, and then waiting for (say) 30 seconds.  after that we
   * recreate the list of handles to wait on, and wait again.  the
   * point of all this abstraction is that we can trivially server
   * both sockets and pipes simply by making a new transport, and then
   * calling request_queue.process_requests (transport2);
   */
  /* WaitForMultipleObjects abort && request_queue && process_queue && signal
     -- if signal event then retrigger it
  */
  while (!shutdown_server && request_queue.running () && cache.running ())
    pause ();

  printf ("\nShutdown request received - new requests will be denied\n");
  request_queue.stop ();
  printf ("All pending requests processed\n");
  safe_delete (transport);
  printf ("No longer accepting requests - cygwin will operate in daemonless mode\n");
  cache.stop ();
  printf ("All outstanding process-cache activities completed\n");
  printf ("daemon shutdown\n");

  return 0;
}