File: evd-daemon.c

package info (click to toggle)
event-dance 0.1.20-2
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 5,068 kB
  • sloc: ansic: 25,946; sh: 11,340; makefile: 418; xml: 249; python: 27
file content (409 lines) | stat: -rw-r--r-- 9,487 bytes parent folder | download
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
/*
 * evd-daemon.c
 *
 * EventDance, Peer-to-peer IPC library <http://eventdance.org>
 *
 * Copyright (C) 2011, Igalia S.L.
 *
 * Authors:
 *   Eduardo Lima Mitev <elima@igalia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 3, or (at your option) any later version as published by
 * the Free Software Foundation.
 *
 * This library 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
 * Lesser General Public License at http://www.gnu.org/licenses/lgpl-3.0.txt
 * for more details.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <pwd.h>

#include <glib/gprintf.h>
#include <gio/gio.h>

#include "evd-daemon.h"

#include "evd-utils.h"
#include "evd-error.h"

G_DEFINE_TYPE (EvdDaemon, evd_daemon, G_TYPE_OBJECT)

#define EVD_DAEMON_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), \
                                     EVD_TYPE_DAEMON, \
                                     EvdDaemonPrivate))

/* private data */
struct _EvdDaemonPrivate
{
  GMainLoop *main_loop;

  gboolean daemonize;
  gboolean daemonized;

  gint exit_code;

  gchar *pid_file;
};

static EvdDaemon *evd_daemon_default = NULL;

static void     evd_daemon_class_init         (EvdDaemonClass *class);
static void     evd_daemon_init               (EvdDaemon *self);

static void     evd_daemon_finalize           (GObject *obj);

static void
evd_daemon_class_init (EvdDaemonClass *class)
{
  GObjectClass *obj_class = G_OBJECT_CLASS (class);

  obj_class->finalize = evd_daemon_finalize;

  g_type_class_add_private (obj_class, sizeof (EvdDaemonPrivate));
}

static void
evd_daemon_init (EvdDaemon *self)
{
  EvdDaemonPrivate *priv;

  priv = EVD_DAEMON_GET_PRIVATE (self);
  self->priv = priv;

  priv->main_loop = g_main_loop_new (g_main_context_get_thread_default (),
                                     FALSE);

  priv->daemonize = FALSE;
  priv->daemonized = FALSE;

  priv->exit_code = 0;

  priv->pid_file = NULL;
}

static void
evd_daemon_finalize (GObject *obj)
{
  EvdDaemon *self = EVD_DAEMON (obj);

  g_main_loop_unref (self->priv->main_loop);

  g_free (self->priv->pid_file);

  G_OBJECT_CLASS (evd_daemon_parent_class)->finalize (obj);

  if (evd_daemon_default == self)
    evd_daemon_default = NULL;
}

static void
evd_daemon_on_user_interrupt (gint sig)
{
  signal (SIGINT, NULL);
  signal (SIGTERM, NULL);

  if (evd_daemon_default != NULL)
    evd_daemon_quit (evd_daemon_default, -sig);
}

/* public methods */

/**
 * evd_daemon_get_default: (constructor):
 * @argc: (allow-none):
 * @argv: (allow-none):
 *
 * Returns: (transfer full):
 **/
EvdDaemon *
evd_daemon_get_default (gint *argc, gchar **argv[])
{
  if (evd_daemon_default == NULL)
    evd_daemon_default = evd_daemon_new (argc, argv);
  else
    g_object_ref (evd_daemon_default);

  return evd_daemon_default;
}

/**
 * evd_daemon_new: (constructor):
 * @argv: (allow-none):
 *
 * Returns: (transfer full):
 **/
EvdDaemon *
evd_daemon_new (gint *argc, gchar **argv[])
{
  EvdDaemon *self;
  gboolean daemonize = FALSE;
  GOptionContext *context;

  const GOptionEntry entries[] =
    {
      { "daemonize", 'D', 0, G_OPTION_ARG_NONE, &daemonize, NULL, NULL },
      { NULL }
    };

  context = g_option_context_new (NULL);
  g_option_context_add_main_entries (context, entries, NULL);
  g_option_context_set_help_enabled (context, FALSE);
  g_option_context_set_ignore_unknown_options (context, TRUE);
  g_option_context_parse (context, argc, argv, NULL); /* lets ignore any parsing error */
  g_option_context_free (context);

  self = g_object_new (EVD_TYPE_DAEMON, NULL);

  self->priv->daemonize = daemonize;

  if (evd_daemon_default == NULL)
    evd_daemon_default = self;

  return self;
}

GMainLoop *
evd_daemon_get_main_loop (EvdDaemon *self)
{
  g_return_val_if_fail (EVD_IS_DAEMON (self), NULL);

  return self->priv->main_loop;
}

gint
evd_daemon_run (EvdDaemon *self, GError **error)
{
  g_return_val_if_fail (EVD_IS_DAEMON (self), -1);
  g_return_val_if_fail (! g_main_loop_is_running (self->priv->main_loop), -1);

  /* daemonize */
  if (! self->priv->daemonized && self->priv->daemonize)
    {
      if (! evd_daemon_daemonize (self, error))
        return -1;
    }

  /* write PID file */
  if (self->priv->pid_file != NULL)
    {
      const gint BUF_SIZE = 20;
      gint pid;
      gchar buf[BUF_SIZE];

      pid = getpid ();
      g_snprintf (buf, BUF_SIZE - 1, "%d\n", pid);
      buf[BUF_SIZE - 1] = '\0';

      if (! g_file_set_contents (self->priv->pid_file, buf, -1, error))
        return -1;

      /* force PID-file permissions to 00644 */
      if (chmod (self->priv->pid_file,
                 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
        {
          gchar *err_st;

          err_st = strerror (errno);
          g_set_error (error,
                       G_IO_ERROR,
                       g_io_error_from_errno (errno),
                       "Failed to set permissions on PID file: %s",
                       err_st);
          g_free (err_st);

          return -1;
        }
    }

  /* hook SIGINT and SIGTERM if this is the default daemon */
  if (self == evd_daemon_default)
    {
      signal (SIGINT, evd_daemon_on_user_interrupt);
      signal (SIGTERM, evd_daemon_on_user_interrupt);
    }

  /* finally, run the main loop */
  g_main_loop_run (self->priv->main_loop);

  return self->priv->exit_code;
}

void
evd_daemon_quit (EvdDaemon *self, gint exit_code)
{
  g_return_if_fail (EVD_IS_DAEMON (self));

  g_main_loop_quit (self->priv->main_loop);
}

gboolean
evd_daemon_daemonize (EvdDaemon *self, GError **error)
{
  pid_t pid, sid;
  gchar *err_st;

  errno = 0;

  /* already a daemon */
  if (self->priv->daemonized || getppid () == 1)
    return TRUE;

  /* Fork off the parent process */
  pid = fork ();
  if (pid < 0)
    goto error;

  /* If we got a good PID, then we can exit the parent process. */
  if (pid > 0)
    exit (0);

  /* At this point we are executing as the child process */

  /* Change the file mode mask */
  umask (0);

  /* Create a new SID for the child process */
  sid = setsid ();
  if (sid < 0)
    goto error;

  /* Change the current working directory.  This prevents the current
     directory from being locked; hence not being able to remove it. */
  if ((chdir ("/")) < 0)
    goto error;

  /* Redirect standard files to /dev/null */
  if (freopen ("/dev/null", "r", stdin) == NULL ||
      freopen ("/dev/null", "w", stdout) == NULL ||
      freopen ("/dev/null", "w", stderr) == NULL)
    {
      goto error;
    }

  self->priv->daemonized = TRUE;

  return TRUE;

 error:
  err_st = strerror (errno);
  g_set_error (error,
               G_IO_ERROR,
               g_io_error_from_errno (errno),
               "Failed to daemonize process: %s",
               err_st);
  g_free (err_st);

  return FALSE;
}

/**
 * evd_daemon_set_timeout:
 * @function: (scope notified):
 *
 * Returns:
 **/
guint
evd_daemon_set_timeout (EvdDaemon   *self,
                        guint        timeout,
                        GSourceFunc  function,
                        gpointer     user_data)
{
  g_return_val_if_fail (EVD_IS_DAEMON (self), 0);

  return evd_timeout_add (g_main_loop_get_context (self->priv->main_loop),
                          timeout,
                          G_PRIORITY_DEFAULT,
                          function,
                          user_data);
}

gboolean
evd_daemon_set_user_id (EvdDaemon  *self,
                        gint        user_id,
                        GError    **error)
{
  g_return_val_if_fail (EVD_IS_DAEMON (self), FALSE);

  errno = 0;
  if (setuid (user_id) != 0)
    {
      g_set_error (error,
                   EVD_ERRNO_ERROR,
                   errno,
                   "%s",
                   strerror (errno));
      return FALSE;
    }

  return TRUE;
}

gboolean
evd_daemon_set_user (EvdDaemon    *self,
                     const gchar  *username,
                     GError      **error)
{
  struct passwd *buf;

  g_return_val_if_fail (EVD_IS_DAEMON (self), FALSE);
  g_return_val_if_fail (username != NULL, FALSE);

  errno = 0;
  buf = getpwnam (username);
  if (buf == NULL)
    {
      if (errno != 0)
        g_set_error (error,
                     EVD_ERRNO_ERROR,
                     errno,
                     "%s",
                     strerror (errno));
      else
        g_set_error (error,
                     G_IO_ERROR,
                     G_IO_ERROR_NOT_FOUND,
                     "User %s not found",
                     username);

      return FALSE;
    }

  return evd_daemon_set_user_id (self, buf->pw_uid, error);
}

void
evd_daemon_set_pid_file (EvdDaemon *self, const gchar *pid_file)
{
  g_return_if_fail (EVD_IS_DAEMON (self));

  if (g_main_loop_is_running (self->priv->main_loop))
    {
      g_warning ("Ignoring PID file change because daemon is already running");
      return;
    }

  g_free (self->priv->pid_file);
  self->priv->pid_file = NULL;

  if (pid_file != NULL)
    self->priv->pid_file = g_strdup (pid_file);
}

const gchar *
evd_daemon_get_pid_file (EvdDaemon *self)
{
  g_return_val_if_fail (EVD_IS_DAEMON (self), NULL);

  return self->priv->pid_file;
}