aboutsummaryrefslogtreecommitdiffstats
path: root/server/opserver.c
blob: d51141f8dfb42c08924da89e6f0af1c07d14bd04 (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
/*
 * OProfile User Interface
 *
 * Copyright (C) 2007 Nokia Corporation. All rights reserved.
 *
 * Author: Robert Bradford <rob@openedhand.com>
 *
 * 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; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <config.h>
#include <stdlib.h>
#include <glib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <wait.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>

#include "util.h"
#include "command.h"
#include "response.h"

#if WITH_AVAHI
#include "mdns.h"
#endif

/* Represents whether we are profiling or not */
static gboolean profiling = FALSE;

/* Represents whether we've been configured */
static gboolean configured = FALSE;

/* For the GOption parsing */
static gint port = 4224;
static gboolean verbose = FALSE;

static GOptionEntry entries[] = 
{
  { "port", 'p', 0, G_OPTION_ARG_INT, &port, 
    "Listen on <port> for connections. Default: 4224.", "<port>"},
  { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Enable verbose output",
    NULL},
  { NULL }
};

/* Setup the socket to listen on */
static int
server_setup_socket (int port)
{
  struct sockaddr_in addr;
  int server_fd = 0;

  addr.sin_family = AF_INET;
  addr.sin_port = htons(port);
  addr.sin_addr.s_addr = INADDR_ANY;

  server_fd = socket (AF_INET,SOCK_STREAM, 0);

  if (server_fd < 0)
    {
      const gchar *error = g_strerror (errno);
      g_error ("Could not open server socket: %s", error);
    }

  if (bind (server_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
      const gchar *error = g_strerror (errno);
      g_error ("Could not bind the server socket: %s", error);
    }

  if (listen (server_fd,1) < 0)
    {
      const gchar *error = g_strerror (errno);
      g_error ("Could not listen on the socket: %s", error);
    }

  return server_fd;
}

/* Setup the local domain socket to listen on */
static int
server_setup_socket_local ()
{
  struct sockaddr_un addr;
  int addr_len;
  int server_fd = 0;

  /* Remove any existing socket */
  unlink (OPROFILEUI_LOCAL_SOCKET);

  memset ((char *) &addr, 0, sizeof(addr));
  addr.sun_family = AF_UNIX;
  strcpy (addr.sun_path, OPROFILEUI_LOCAL_SOCKET);
  addr_len = strlen(addr.sun_path) + sizeof(addr.sun_family);

  server_fd = socket (AF_UNIX, SOCK_STREAM, 0);

  if (server_fd < 0)
    {
      const gchar *error = g_strerror (errno);
      g_error ("Could not open server domain socket: %s", error);
    }

  if (bind (server_fd, (struct sockaddr *)&addr, addr_len) < 0)
    {
      const gchar *error = g_strerror (errno);
      g_error ("Could not bind the server domain socket: %s", error);
    }

  if (listen (server_fd, 1) < 0)
    {
      const gchar *error = g_strerror (errno);
      g_error ("Could not listen on the socket: %s", error);
    }

  chmod (OPROFILEUI_LOCAL_SOCKET, 0777);

  return server_fd;
}


/* 
 * For a given opcode create a new response and allocate the appropriate
 * amount of memory for it.
 */
static OpuiResponse *
server_response_new (char opcode, size_t length, void *payload)
{
  OpuiResponse *buf;

  buf = g_malloc0 (sizeof (OpuiResponse) + length);

  buf->opcode = opcode;
  buf->length = length;

  if (length > 0)
    {
      assert (payload != NULL);
      memcpy(&(buf->payload[0]), payload, length);
    }

  return buf;
}

/* Generate the response for commands that don't need the output of stdout */
static OpuiResponse *
server_do_command_wrapper (gchar **args)
{
  gchar *stdout = NULL;
  gchar *stderr = NULL;
  gint exit_status;
  GError *err = NULL;
  gboolean success;

  OpuiResponse *reply;

  success = g_spawn_sync (
      NULL, /* working directory, inherit because NULL */
      args, /* argv[0] is program to run */

      NULL, /* environment, inherit because NULL */
      G_SPAWN_SEARCH_PATH, /* search for executable, no need for full path */
      NULL, /* child setup func */
      NULL, /* user_data for child setup func */
      &stdout,
      &stderr,
      &exit_status,
      &err);

  if (success)
    {
      /* This is the UNIX exit code */
      int exit_code = WEXITSTATUS (exit_status);
      if (WIFEXITED (exit_status) && exit_code==0)
        {
          /* Create a positive reply */
          reply = server_response_new (RESPONSE_OP_OK, 0, NULL);
        } else {
          gchar *err_string = g_strdup_printf (
              "Error whilst spawning: opcontrol exited with error code: %d",
              exit_code);

          /* Create an error reply. NB: strlen (...) + 1 to include \0 */
          reply = server_response_new (RESPONSE_OP_ERROR, 
              strlen (err_string) + 1, err_string);

          g_warning ("Error whilst spawning: %s", err_string);
          g_free(err_string);
        }
    } else {
      gchar *err_string = NULL;

      if (err)
        {
          err_string = g_strdup_printf ("Error whilst spawning: %s",
              err->message);
        } else {
          err_string = "Error whilst spawning";
        }

      /* Create an error response */
      reply = server_response_new (RESPONSE_OP_ERROR, strlen (err_string) + 1,
          err_string);

      if (err)
        {
          g_free(err_string);
          g_clear_error (&err);
        }

    }

  g_debug ("%s", stderr);
  g_free (stdout);
  g_free (stderr);
  return reply;
}

static void
server_handle_command_start (OpuiCommand *buf, int active_fd)
{
  OpuiResponse *reply;
  const gchar *args[] = {"opcontrol", "--start", NULL};

  if (verbose)
    g_debug ("Command received: START");

  /* Use the generic wrapper for this command */
  reply = server_do_command_wrapper ((gchar **)args);

  /* Send out the reply */
  util_resp_write_in_full (active_fd, reply);

  /* Update internal state */
  if (reply->opcode == RESPONSE_OP_OK)
    profiling = TRUE;

  g_free (reply);
}

static void
server_handle_command_config (OpuiCommand *buf, int active_fd)
{
  OpuiResponse *reply;
  gchar **args;
  const gchar *default_args[] = {"opcontrol", "--start-daemon",
    "--separate=lib","-c 6", "--no-vmlinux", NULL};

  /* Examine the payload */
  gchar *str = (gchar *)buf->payload;
  g_strstrip (str);

  if (verbose)
    g_debug ("Command received: CONFIG: %s", str);

  /* Test to see if any arguments are supplied. Otherwise use defaults */
  if (buf->length == 0 || strlen (str) == 0)
    {
      args = (gchar **)default_args;
    } else {
      /* The arguments are supplied as a string */
      gchar **parts = g_strsplit (str, " ", 0);

      int i = 0;

      /* 
       * Allocate enough space to hold the content of parts plus 2 more cells
       * to add to the front. We must add one more on here since g_strv_length
       * does not count the final NULL.
       */
      args = g_malloc0 ((g_strv_length (parts) + 3) * sizeof (gchar *));

      /* Allocate these onto the heap to make freeing easier later */
      args[0] = g_strdup ("opcontrol");
      args[1] = g_strdup ("--start-daemon");

      /* Copy the pointers to the arguments from parts into args */
      for (i=2; i < g_strv_length (parts) + 3; i++)
        {
          args[i] = parts[i-2];
        }

      /* This only frees the array itself. */
      g_free (parts);
    }

  /* Use the generic wrapper for this command */
  reply = server_do_command_wrapper (args);

  /* Send out the reply */
  util_resp_write_in_full (active_fd, reply);

  /* Update internal state */
  if (reply->opcode == RESPONSE_OP_OK)
    configured = TRUE;

  g_free (reply);

  if (args != (gchar **)default_args)
    {
      /* 
       * We had custom arguments so we should free the array of pointers we
       * used. This frees all the strings and the array itself.
       */
      g_strfreev (args);
    }
}

static void
server_handle_command_stop (OpuiCommand *buf, int active_fd)
{
  OpuiResponse *reply;
  const gchar *args[] = {"opcontrol","--stop",NULL};

  if (verbose)
    g_debug ("Command received: STOP");

  /* Use the generic wrapper for this command */
  reply = server_do_command_wrapper ((gchar **)args);

  /* Send out the reply */
  util_resp_write_in_full (active_fd, reply);

  /* Update internal state */
  if (reply->opcode == RESPONSE_OP_OK)
    profiling = FALSE;

  g_free (reply);
}

static void
server_handle_command_status (OpuiCommand *buf, int active_fd)
{
  OpuiResponse *reply;
  OpuiResponseStatus status;

  if (verbose)
    g_debug ("Command received: STATUS");

  status.proto_version = OPROFILEUI_PROTO_VERSION;
  status.profiling = profiling;
  status.configured = configured;

  reply = server_response_new (RESPONSE_OP_STATUS, sizeof(status), &status);

  /* Send out the reply */
  util_resp_write_in_full (active_fd, reply);

  g_free (reply);
}

static void
server_handle_command_reset (OpuiCommand *buf, int active_fd)
{
  OpuiResponse *reply;
  const gchar *args[] = {"opcontrol","--reset",NULL};

  if (verbose)
    g_debug ("Command received: RESET");

  /* Use the generic wrapper for this command */
  reply = server_do_command_wrapper ((gchar **)args);

  /* Send out the reply */
  util_resp_write_in_full (active_fd, reply);

  /* Update internal state */
  if (reply->opcode == RESPONSE_OP_OK)
    profiling = FALSE;

  g_free (reply);
}

/*
 * Like server_handle_command_wrapper except that the stdout is included as
 * the payload in the response.
 */
static void
server_handle_command_archive (OpuiCommand *buf, int active_fd)
{
  gchar *stdout = NULL;
  gchar *stderr = NULL;
  gint exit_status;
  GError *err = NULL;
  gboolean success;

  const gchar *args[] = {"oparchive", "--list-files", NULL};
  OpuiResponse *reply;

  success = g_spawn_sync (
      NULL, /* working directory, inherit because NULL */
      (gchar **)args, /* argv[0] is program to run */

      NULL, /* environment, inherit because NULL */
      G_SPAWN_SEARCH_PATH, /* search for executable, no need for full path */
      NULL, /* child setup func */
      NULL, /* user_data for child setup func */
      &stdout,
      &stderr,
      &exit_status,
      &err);

  if (success)
    {

      /* This is the UNIX exit code */
      int exit_code = WEXITSTATUS (exit_status);
      if (WIFEXITED (exit_status) && exit_code==0)
        {
          /* Create a positive reply, and include the stdout as the payload */
          reply = server_response_new (RESPONSE_OP_ARCHIVE, strlen (stdout) + 1,
              stdout);

        } else {
          gchar *err_string;

          if (strstr (stderr,"No sample file found") != NULL)
            {
              err_string = g_strdup_printf ("No sample data available to download.");
            } else {
              err_string = g_strdup_printf ("oparchive reported error code: %d", exit_code);
            }

          /* Create an error response */
          reply = server_response_new (RESPONSE_OP_ERROR,
              strlen (err_string) + 1, err_string);

          g_free(err_string);
        }
    } else {
      gchar *err_string = NULL;

      if (err)
        {
          err_string = g_strdup_printf ("Error whilst spawning: %s",
              err->message);
        } else {
          err_string = "Error whilst spawning";
        }

      /* Create an error response */
      reply = server_response_new (RESPONSE_OP_ERROR, strlen (err_string) + 1,
          err_string);

      if (err)
        {
          g_free(err_string);
          g_clear_error (&err);
        }
    }

  g_debug ("%s", stderr);

  g_free (stdout);
  g_free (stderr);

  /* Send the reply */
  util_resp_write_in_full (active_fd, reply);

  g_free (reply);
}


/* 
 * Open the file pointed to by buf and return an open file descriptor
 * and stat information. Return an error response for invalid paths.
 */
static int
server_parse_open_file (OpuiCommand *buf, int active_fd, 
			struct stat *stat_details)
{
  int fd;
  gchar *path = NULL;
  OpuiResponse *reply;

  /* Prepare the path to fetch */
  path = (gchar *)buf->payload;
  g_strstrip (path);

  /* Check path is valid */
  if (buf->length == 0 || strlen (path) == 0)
    {
      g_warning ("ERROR: Filename absent for GET command");
      return -1;
    }

  fd = open (path, O_RDONLY);

  if (fd < 0)
    {
      /* Something went wrong when trying to open the file */
      const gchar *err_string = g_strerror (errno);

      /* Generate an error response */
      reply = server_response_new (RESPONSE_OP_ERROR, strlen (err_string) + 1,
          (gchar *)err_string);

      /* Send the error response */
      util_resp_write_in_full (active_fd, reply);

      g_free (reply);
      return fd;
    }

  fstat (fd, stat_details);

  return fd;
}


static void
server_handle_command_get (OpuiCommand *buf, int active_fd)
{
  int fd;
  off_t size;
  struct stat stat_details;
  OpuiResponse *reply;

  if (verbose)
    g_debug ("Command recieved: GET: %s", buf->payload);

  fd = server_parse_open_file (buf, active_fd, &stat_details);
  if (fd < 0)
    return;

  /* Get the size of the file */
  size = stat_details.st_size;

  /* 
   * Create a response. We have to do it manually since we want to set the
   * length but not allocate any memory because we are going to sendfile ()
   * later.
   */
  reply = g_malloc0 (sizeof (OpuiResponse));

  reply->opcode = RESPONSE_OP_FILE;
  reply->length = size;

  /* Send the response (header) */
  util_resp_header_write_in_full (active_fd, reply);

  /* Use sendfile to stream the file to the client */
  util_sendfile_in_full (active_fd, fd, size);

  close (fd);

  g_free (reply);
}

static void
server_handle_command_filestat (OpuiCommand *buf, int active_fd)
{
  struct stat stat_details;
  OpuiResponseFileStat filestat;
  OpuiResponse *reply;
  int fd;

  if (verbose)
    g_debug ("Command recieved: FILESTAT: %s", buf->payload);

  fd = server_parse_open_file (buf, active_fd, &stat_details);

  if (fd < 0)
    return;

  close (fd);

  filestat.mtime_h = (uint32_t)((uint64_t)stat_details.st_mtime >> 32);
  filestat.mtime_l = (uint32_t)stat_details.st_mtime;
  filestat.size_h = (uint32_t)((uint64_t)stat_details.st_size >> 32);
  filestat.size_l = (uint32_t)stat_details.st_size;
  filestat.mode_h = (uint32_t)((uint64_t)stat_details.st_mode >> 32);
  filestat.mode_l = (uint32_t)stat_details.st_mode;

  reply = server_response_new (RESPONSE_OP_FILESTAT, sizeof(filestat), &filestat);

  util_resp_write_in_full (active_fd, reply);

  g_free (reply);
}

static void
server_handle_command_unknown (OpuiCommand *buf, int active_fd)
{
  if (verbose)
    g_debug ("UNKNOWN");
}


/* Demultiplex the command to figure out what to do */
static void
server_handle_command (OpuiCommand *buf, int active_fd)
{
  switch (buf->opcode)
  {
    case COMMAND_OP_START:
      server_handle_command_start (buf, active_fd);
      break;
    case COMMAND_OP_STOP:
      server_handle_command_stop (buf, active_fd);
      break;
    case COMMAND_OP_ARCHIVE:
      server_handle_command_archive (buf, active_fd);
      break;
    case COMMAND_OP_GET:
      server_handle_command_get (buf, active_fd);
      break;
    case COMMAND_OP_STATUS:
      server_handle_command_status (buf, active_fd);
      break;
    case COMMAND_OP_RESET:
      server_handle_command_reset (buf, active_fd);
      break;
    case COMMAND_OP_FILESTAT:
      server_handle_command_filestat (buf, active_fd);
      break;
    case COMMAND_OP_CONFIG:
      server_handle_command_config (buf, active_fd);
      break;
    default:
      server_handle_command_unknown (buf, active_fd);
  }
}

static gboolean
server_handle_connection (GIOChannel *source, GIOCondition condition, gpointer user_data)
{
  int active_fd;
  int res;
  OpuiCommand *buf;

  if (condition & G_IO_ERR) {
    g_warning ("%s", g_strerror (errno));
    return FALSE;
  }

  active_fd = accept (g_io_channel_unix_get_fd (source), NULL, 0);
  do
    {
      /* Allocate just enough for the header of the command */
      buf = g_malloc0 (sizeof (OpuiCommand));

      /* Read in the header of the command */
      res = util_cmd_header_read_in_full (active_fd, buf);

      if (res > 0)
        {
          /* 
           * Provided that was successful check if there is a payload to read
           * in.
           */

          if (buf->length > 64 * 1024)
            {
              g_error ("Bad buffer length requested by client for command.");
            }

          if (buf->length > 0)
            {
              /* Increase the size of the buffer if necessary */
              buf = g_realloc (buf, sizeof (OpuiCommand) + buf->length);

              /* Read in the payload */
              res = util_read_in_full (active_fd, (gchar *)&(buf->payload[0]),
                  buf->length);
            }

          /* If we have a complete response */
          if (res >= 0)
            {
              server_handle_command (buf, active_fd);
            }
        }

      g_free (buf);
    }
  while (res > 0);

  if (res < 0)
    {
      g_warning ("Error whilst reading on socket: %s", g_strerror (errno));
    }

  return TRUE;
}

int
main (int argc, char **argv)
{
  GError *error = NULL;
  GOptionContext *context;
  GMainLoop *loop;
  GIOChannel *channel, *local_channel;

  context = g_option_context_new ("- OProfile control server");
  g_option_context_add_main_entries (context, entries, NULL);
  if (!g_option_context_parse (context, &argc, &argv, &error)) {
    if (error)
    {
      /* Should catch G_OPTION_ERROR_UNKNOWN_OPTION and display the help */
      g_error ("Cannot parse arguments: %s", error->message);
      g_clear_error (&error);
    }
  }
  g_option_context_free (context);

  /* Check for root */
  if (geteuid() != 0)
    {
      printf ("The server needs to be run with root privileges\n");
      return 1;
    }

  loop = g_main_loop_new (NULL, TRUE);

  /* Add internet socket */
  channel = g_io_channel_unix_new (server_setup_socket (port));
  g_io_channel_set_close_on_unref (channel, TRUE);
  g_io_add_watch (channel, G_IO_IN|G_IO_ERR, server_handle_connection, NULL);

  /* Add domain socket */
  local_channel = g_io_channel_unix_new (server_setup_socket_local ());
  g_io_channel_set_close_on_unref (local_channel, TRUE);
  g_io_add_watch (local_channel, G_IO_IN|G_IO_ERR, server_handle_connection, NULL);

#if WITH_AVAHI
  mdns_publish (port);
#endif
  g_io_channel_unref (channel);
  g_io_channel_unref (local_channel);

  if (verbose)
    g_debug ("Starting OProfile Server " VERSION);

  g_main_loop_run (loop);

  g_main_loop_unref (loop);

  /* local_channel cleanup */
  unlink(OPROFILEUI_LOCAL_SOCKET);

  return 0;
}