summaryrefslogtreecommitdiff
path: root/stc/stcd.c
blob: 28ad6a6a981d7a24cecc7373cbc5c4493a065bcf (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
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
 *
 * Copyright (C) 2007-2010 David Zeuthen <zeuthen@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the licence, or (at your option) any later version.
 *
 * 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 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * Author: David Zeuthen <zeuthen@gmail.com>
 */

#include "config.h"

#include <syslog.h>

#include "stc.h"
#include "gposixsignal.h"

/* ---------------------------------------------------------------------------------------------------- */

typedef enum
{
  LOG_LEVEL_ERROR,
  LOG_LEVEL_WARNING,
  LOG_LEVEL_INFO,
  LOG_LEVEL_DEBUG
} LogLevel;

static void
print_timestamp (void)
{
  GTimeVal now;
  time_t now_time;
  struct tm *now_tm;
  gchar time_buf[128];

  g_get_current_time (&now);
  now_time = (time_t) now.tv_sec;
  now_tm = localtime (&now_time);
  strftime (time_buf, sizeof time_buf, "%H:%M:%S", now_tm);

  g_print ("%s.%03d",
           time_buf, (gint) now.tv_usec / 1000);
}

static void
log_message (LogLevel     log_level,
             const gchar *format,
             ...)
{
  gchar *s;
  va_list var_args;
  const gchar *level_str;
  static gboolean syslog_initialized = FALSE;
  int syslog_pri;

  if (!syslog_initialized)
    {
      openlog ("stcd",
               LOG_CONS | LOG_PID,
               LOG_DAEMON);
      syslog_initialized = TRUE;
    }

  va_start (var_args, format);
  s = g_strdup_vprintf (format, var_args);
  va_end (var_args);

  switch (log_level)
    {
    case LOG_LEVEL_ERROR:
      level_str = "[ERROR]: ";
      syslog_pri = LOG_ERR;
      break;
    case LOG_LEVEL_WARNING:
      level_str = "[WARNING]: ";
      syslog_pri = LOG_WARNING;
      break;
    case LOG_LEVEL_INFO:
      level_str = "[INFO]: ";
      syslog_pri = LOG_INFO;
      break;
    case LOG_LEVEL_DEBUG:
      level_str = "[DEBUG]: ";
      syslog_pri = LOG_DEBUG;
      break;
    }
  g_assert (level_str != NULL);

  print_timestamp ();
  g_print (" [%d]: %s%s\n", (gint) getpid (), level_str, s);
  syslog (syslog_pri, "%s", s);
  g_free (s);
}

static const gchar *
enum_to_str (GType gtype, gint value)
{
  GEnumClass *klass;
  GEnumValue *enum_value;
  const gchar *ret;

  ret = "<Unregistered enum type>";
  klass = g_type_class_ref (gtype);
  if (klass == NULL)
    goto out;

  ret = "<Invalid enum value>";
  enum_value = g_enum_get_value (klass, value);
  if (enum_value == NULL)
    goto out;

  ret = enum_value->value_nick;

 out:
  if (klass != NULL)
    g_type_class_unref (klass);
  return ret;
}

/* ---------------------------------------------------------------------------------------------------- */

#define _STC_TYPE_DAEMON         (_stc_daemon_get_type ())
#define _STC_DAEMON(o)           (G_TYPE_CHECK_INSTANCE_CAST ((o), _STC_TYPE_DAEMON, _StcDaemon))
#define _STC_IS_DAEMON(o)        (G_TYPE_CHECK_INSTANCE_TYPE ((o), _STC_TYPE_DAEMON))

struct __StcDaemon;
typedef struct __StcDaemon _StcDaemon;

struct __StcDaemonClass;
typedef struct __StcDaemonClass _StcDaemonClass;

struct __StcDaemon
{
  GObject parent_instance;

  StcMonitor *monitor;

  GHashTable *pending_item_ids;
};

struct __StcDaemonClass
{
  GObjectClass parent_class;

  void (*pending_items_changed) (_StcDaemon *daemon);
};

GType        _stc_daemon_get_type (void) G_GNUC_CONST;
_StcDaemon  *_stc_daemon_new      (void);

static void maybe_act_on_item (_StcDaemon  *daemon,
                               StcItem     *item);

static void error_handler (StcMonitor   *monitor,
                           const gchar  *filename,
                           gint          line_no,
                           GError       *error,
                           gpointer      user_data);

static void on_item_added (StcMonitor  *monitor,
                           StcItem     *item,
                           gpointer     user_data);

static void on_item_removed (StcMonitor  *monitor,
                             StcItem     *item,
                             gpointer     user_data);

static void on_item_changed (StcMonitor  *monitor,
                             StcItem     *item,
                             gpointer     user_data);

static StcOperation * get_operation (_StcDaemon *daemon);

enum
{
  PENDING_ITEMS_CHANGED_SIGNAL,
  LAST_SIGNAL
};

static guint signals[LAST_SIGNAL] = { 0 };

G_DEFINE_TYPE (_StcDaemon, _stc_daemon, G_TYPE_OBJECT);

static void
_stc_daemon_finalize (GObject *object)
{
  _StcDaemon *daemon = _STC_DAEMON (object);

  g_hash_table_unref (daemon->pending_item_ids);
  g_object_unref (daemon->monitor);

  if (G_OBJECT_CLASS (_stc_daemon_parent_class)->finalize != NULL)
    G_OBJECT_CLASS (_stc_daemon_parent_class)->finalize (object);
}

static void
_stc_daemon_init (_StcDaemon *daemon)
{
  GList *items;
  GList *l;

  daemon->pending_item_ids = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);

  daemon->monitor = stc_monitor_new (error_handler, NULL);
  g_signal_connect (daemon->monitor,
                    "item-added",
                    G_CALLBACK (on_item_added),
                    daemon);
  g_signal_connect (daemon->monitor,
                    "item-removed",
                    G_CALLBACK (on_item_removed),
                    daemon);
  g_signal_connect (daemon->monitor,
                    "item-changed",
                    G_CALLBACK (on_item_changed),
                    daemon);

  /* coldplug */
  log_message (LOG_LEVEL_DEBUG, "coldplugging items");
  items = stc_monitor_get_items (daemon->monitor);
  for (l = items; l != NULL; l = l->next)
    {
      StcItem *item = STC_ITEM (l->data);
      maybe_act_on_item (daemon, item);
    }
  g_list_foreach (items, (GFunc) g_object_unref, NULL);
  g_list_free (items);
  log_message (LOG_LEVEL_DEBUG, "done coldplugging items");
}

static void
_stc_daemon_class_init (_StcDaemonClass *klass)
{
  GObjectClass *gobject_class;

  gobject_class = G_OBJECT_CLASS (klass);
  gobject_class->finalize = _stc_daemon_finalize;

  signals[PENDING_ITEMS_CHANGED_SIGNAL] = g_signal_new ("pending-items-changed",
                                                        G_TYPE_FROM_CLASS (klass),
                                                        G_SIGNAL_RUN_LAST,
                                                        G_STRUCT_OFFSET (_StcDaemonClass, pending_items_changed),
                                                        NULL,
                                                        NULL,
                                                        g_cclosure_marshal_VOID__VOID,
                                                        G_TYPE_NONE,
                                                        0);
}

_StcDaemon *
_stc_daemon_new (void)
{
  return _STC_DAEMON (g_object_new (_STC_TYPE_DAEMON, NULL));
}

/* Returns TRUE exactly if @item (or one of its dependencies) currently have a pending operation */
static gboolean
_stc_daemon_has_pending (_StcDaemon   *daemon,
                         StcItem      *item)
{
  gboolean ret;
  const gchar *const *deps;
  guint n;

  ret = TRUE;

  if (g_hash_table_lookup (daemon->pending_item_ids, stc_item_get_id (item)) != NULL)
    goto out;

  deps = stc_item_get_dependencies (item);
  for (n = 0; deps != NULL && deps[n] != NULL; n++)
    {
      StcItem *dep;
      dep = stc_monitor_get_item_by_id (daemon->monitor, deps[n]);
      if (dep != NULL)
        {
          if (_stc_daemon_has_pending (daemon, dep))
            {
              g_object_unref (dep);
              goto out;
            }
          g_object_unref (dep);
        }
    }

  ret = FALSE;

 out:
  return ret;
}

static void
_stc_daemon_set_pending (_StcDaemon   *daemon,
                         StcItem      *item)
{
  g_assert (! _stc_daemon_has_pending (daemon, item));
  g_hash_table_insert (daemon->pending_item_ids, g_strdup (stc_item_get_id (item)), item);
  g_signal_emit (daemon, signals[PENDING_ITEMS_CHANGED_SIGNAL], 0);
}

static void
_stc_daemon_clear_pending (_StcDaemon   *daemon,
                           StcItem      *item)
{
  g_assert (_stc_daemon_has_pending (daemon, item));
  g_assert (g_hash_table_remove (daemon->pending_item_ids, g_strdup (stc_item_get_id (item))));
  g_signal_emit (daemon, signals[PENDING_ITEMS_CHANGED_SIGNAL], 0);
}

/* ---------------------------------------------------------------------------------------------------- */

static void
start_cb (GObject       *source_object,
          GAsyncResult  *res,
          gpointer       user_data)
{
  _StcDaemon *daemon = _STC_DAEMON (user_data);
  StcItem *item = STC_ITEM (source_object);
  GError *error;

  error = NULL;
  if (!stc_item_start_finish (item,
                              res,
                              &error))
    {
      log_message (LOG_LEVEL_ERROR,
                   "Auto-starting item %s (%s) failed: %s (%s, %d)",
                   stc_item_get_id (item),
                   enum_to_str (STC_TYPE_ITEM_TYPE, stc_item_get_item_type (item)),
                   error->message,
                   g_quark_to_string (error->domain),
                   error->code);
      g_error_free (error);
    }

  _stc_daemon_clear_pending (daemon, item);

  g_object_unref (daemon);
}

typedef struct
{
  _StcDaemon *daemon;
  StcItem *item;
  gulong signal_handler_id;
} SerializedStartData;

static void
serialized_start_data_free (SerializedStartData *data)
{
  g_signal_handler_disconnect (data->daemon, data->signal_handler_id);
  g_object_unref (data->daemon);
  g_object_unref (data->item);
  g_free (data);
}

static gboolean _stc_daemon_start_serialized_or_queue (_StcDaemon  *daemon,
                                                       StcItem     *item,
                                                       gboolean     queue);

static void
start_serialized_pending_items_changed_cb (_StcDaemon  *daemon,
                                           gpointer     user_data)
{
  SerializedStartData *data = user_data;

  if (_stc_daemon_start_serialized_or_queue (data->daemon, data->item, FALSE))
    {
      serialized_start_data_free (data);
    }
}

static gboolean
_stc_daemon_start_serialized_or_queue (_StcDaemon  *daemon,
                                       StcItem     *item,
                                       gboolean     queue)
{
  gboolean ret;

  ret = FALSE;

  if (!_stc_daemon_has_pending (daemon, item))
    {
      StcOperation *operation;

      _stc_daemon_set_pending (daemon, item);

      if (!queue)
        {
          log_message (LOG_LEVEL_DEBUG,
                       "Resuming starting queued item %s (%s)",
                       stc_item_get_id (item),
                       enum_to_str (STC_TYPE_ITEM_TYPE, stc_item_get_item_type (item)));
        }
      log_message (LOG_LEVEL_INFO,
                   "Auto-starting item %s (%s)",
                   stc_item_get_id (item),
                   enum_to_str (STC_TYPE_ITEM_TYPE, stc_item_get_item_type (item)));
      operation = get_operation (daemon);
      stc_item_start (item,
                      operation,
                      NULL,  /* GCancellable* */
                      start_cb,
                      g_object_ref (daemon));
      g_object_unref (operation);
      ret = TRUE;
    }
  else
    {
      if (queue)
        {
          SerializedStartData *data;
          data = g_new0 (SerializedStartData, 1);
          data->daemon = g_object_ref (daemon);
          data->item = g_object_ref (item);
          data->signal_handler_id = g_signal_connect (daemon,
                                                      "pending-items-changed",
                                                      G_CALLBACK (start_serialized_pending_items_changed_cb),
                                                      data);
          log_message (LOG_LEVEL_DEBUG,
                       "Queued auto-start of item %s (%s) since one of its "
                       "dependencies is currently being started",
                       stc_item_get_id (item),
                       enum_to_str (STC_TYPE_ITEM_TYPE, stc_item_get_item_type (item)));
        }
    }
  return ret;
}

static void
_stc_daemon_start_serialized (_StcDaemon  *daemon,
                              StcItem     *item)
{
  _stc_daemon_start_serialized_or_queue (daemon, item, TRUE);
}

/* ---------------------------------------------------------------------------------------------------- */

static void
error_handler (StcMonitor   *monitor,
               const gchar  *filename,
               gint          line_no,
               GError       *error,
               gpointer      user_data)
{
  GString *str;
  str = g_string_new (NULL);
  if (filename != NULL)
    {
      if (line_no >= 0)
        g_string_append_printf (str, "%s:%d: ", filename, line_no);
      else
        g_string_append_printf (str, "%s: ", filename);
    }
  g_string_append_printf (str, "%s", error->message);
  g_string_append_printf (str, " (%s, %d)", g_quark_to_string (error->domain), error->code);
  log_message (LOG_LEVEL_WARNING, "Error while parsing %s", str->str);
  g_string_free (str, TRUE);
}

/* ---------------------------------------------------------------------------------------------------- */

static void
on_started (StcOperation *operation,
            StcItem      *item,
            gpointer      user_data)
{
  gchar *extra;
  GString *str;

  extra = NULL;
  switch (stc_item_get_item_type (item))
    {
    case STC_ITEM_TYPE_FILESYSTEM:
      {
        const gchar *const *slave_devices = stc_item_get_slave_devices (item);
        extra = g_strdup_printf ("%s is mounted at %s",
                                 slave_devices != NULL ? slave_devices[0] : "(unknown)",
                                 stc_item_get_resulting_mount_path (item));
      }
      break;

    case STC_ITEM_TYPE_LUKS:
      {
        const gchar *const *slave_devices = stc_item_get_slave_devices (item);
        extra = g_strdup_printf ("%s is unlocked as %s",
                                 slave_devices != NULL ? slave_devices[0] : "(unknown)",
                                 stc_item_get_resulting_device (item));
      }
      break;

    case STC_ITEM_TYPE_RAID:
      {
        const gchar *const *slave_devices = stc_item_get_slave_devices (item);
        GString *str;
        guint n;
        str = g_string_new (NULL);
        g_string_append_printf (str,
                                "%s with components ",
                                stc_item_get_resulting_device (item));
        for (n = 0; slave_devices != NULL && slave_devices[n] != NULL; n++)
          {
            if (n > 0)
              g_string_append (str, ", ");
            g_string_append (str, slave_devices[n]);
          }
        extra = g_string_free (str, FALSE);
      }
      break;

    default:
      break;
    }

  str = g_string_new (NULL);
  g_string_append_printf (str,
                          "Item %s (%s) has been started",
                          stc_item_get_id (item),
                          enum_to_str (STC_TYPE_ITEM_TYPE, stc_item_get_item_type (item)));
  if (extra != NULL)
    g_string_append_printf (str, " (%s)", extra);
  log_message (LOG_LEVEL_INFO, str->str);
  g_string_free (str, TRUE);
  g_free (extra);
}

static void
on_stopped (StcOperation *operation,
            StcItem      *item,
            gpointer      user_data)
{
  gchar *extra;
  GString *str;

  extra = NULL;
  switch (stc_item_get_item_type (item))
    {
    case STC_ITEM_TYPE_FILESYSTEM:
      {
        const gchar *const *slave_devices = stc_item_get_slave_devices (item);
        if (slave_devices != NULL && slave_devices[0] != NULL)
          extra = g_strdup_printf ("%s unmounted", slave_devices[0]);
      }
      break;

    case STC_ITEM_TYPE_LUKS:
      {
        const gchar *const *slave_devices = stc_item_get_slave_devices (item);
        if (slave_devices != NULL && slave_devices[0] != NULL)
          extra = g_strdup_printf ("%s locked", slave_devices[0]);
      }
      break;

    case STC_ITEM_TYPE_RAID:
      {
        const gchar *const *slave_devices = stc_item_get_slave_devices (item);
        if (slave_devices != NULL && slave_devices[0] != NULL)
          {
            GString *str;
            guint n;

            str = g_string_new (NULL);
            g_string_append (str, "components ");
            for (n = 0; slave_devices != NULL && slave_devices[n] != NULL; n++)
              {
                if (n > 0)
                  g_string_append (str, ", ");
                g_string_append (str, slave_devices[n]);
              }
            extra = g_string_free (str, FALSE);
          }
      }
      break;

    default:
      break;
    }

  str = g_string_new (NULL);
  g_string_append_printf (str,
                          "Item %s (%s) has been stopped",
                          stc_item_get_id (item),
                          enum_to_str (STC_TYPE_ITEM_TYPE, stc_item_get_item_type (item)));
  if (extra != NULL)
    g_string_append_printf (str, " (%s)", extra);
  log_message (LOG_LEVEL_INFO, str->str);
  g_string_free (str, TRUE);
  g_free (extra);
}

static StcOperation *
get_operation (_StcDaemon *daemon)
{
  StcOperation *operation;
  operation = stc_operation_new ();
  /* TODO: maybe connect to these signals are forward requests to
   *       e.g. plymouth when booting.. need to figure out how to best
   *       do that...
   *
   * g_signal_connect (operation,
   *                  "may-start-degraded",
   *                  G_CALLBACK (on_may_start_degraded),
   *                  NULL);
   * g_signal_connect (operation,
   *                  "request-passphrase",
   *                  G_CALLBACK (on_request_passphrase),
   *                  NULL);
   */
  g_signal_connect (operation,
                    "started",
                    G_CALLBACK (on_started),
                    NULL);
  g_signal_connect (operation,
                    "stopped",
                    G_CALLBACK (on_stopped),
                    NULL);
  return operation;
}

/* ---------------------------------------------------------------------------------------------------- */

static void
maybe_autostart_item (_StcDaemon *daemon,
                      StcItem    *item)
{
  gint64 age_of_slaves;
  gboolean autostart;

  /* First check if we can start the item... */
  if (stc_item_get_state (item) != STC_ITEM_STATE_CAN_START)
    goto out;

  /* Just because the item is startable it doesn't mean that we
   * SHOULD be starting it... because if we blindly did this then
   * we would easily run into loops where we'd be starting devices
   * RIGHT AFTER the user
   *
   *  - has stopped the item via stc(8)
   *
   *  - unmounted a filesystem via umount(8)
   *
   *  - created a filesystem on the device
   *
   *  - partitioned a disk
   *
   *   (Btw, desktop automounters have struggled with problems like
   *    this for ages so it's not like it's something new.)
   *
   * The algorithm we use here is simple: if all slaves have been
   * added within the last give seconds then go ahead and autostart
   * the item. Otherwise don't...
   */
  autostart = FALSE;
  age_of_slaves = stc_item_get_slave_devices_age (item);
  log_message (LOG_LEVEL_DEBUG,
               "age_of_slaves for %s is %d msec (only autostarting if less than 5 seconds)",
               stc_item_get_id (item), age_of_slaves);
  if (age_of_slaves >= 0 && age_of_slaves < 5 * 1000)
    autostart = TRUE;

  if (!autostart)
    goto out;

  /* If we are not careful we could end up starting the same item more
   * than once. For example, consider the following setup
   *
   *  [Luks sekrit_Luks]
   *  UUID=5b2aeadf-7f10-4df9-92f2-0bc13123d6e5
   *  LuksPassphrase=xyz123
   *  Auto=true
   *
   *  [Filesystem sekrit]
   *  Label=sekrit
   *  FilesystemMountPath=/media/sekrit
   *  Depends=sekrit_Luks
   *  Auto=true
   *
   * With this we'd end up starting both sekrit and sekrit_Luks
   * since both items will be in the CAN_START state at the same
   * time. Since sekrit depends on sekrit_Luks we end up up
   * starting sekrit_Luks twice.
   *
   * The way we work around this is by post-poning the start()
   * operation on an item until all start() ops for its dependencies
   * have completed.
   *
   * An easier (but less optimal) solution would be to just serialize
   * all start() ops without worrying about dependencies (essentially
   * use stc_item_start_sync())... we don't do this since we wouldn't
   * be able to start unrelated items in parallel (also, we don't want
   * to block the main thread).
   */
  _stc_daemon_start_serialized (daemon, item);

 out:
  ;
}

/* ---------------------------------------------------------------------------------------------------- */

static void
stop_cb (GObject       *source_object,
         GAsyncResult  *res,
         gpointer       user_data)
{
  StcItem *item = STC_ITEM (source_object);
  GError *error;

  error = NULL;
  if (!stc_item_stop_finish (item,
                             res,
                             &error))
    {
      log_message (LOG_LEVEL_ERROR,
                   "Cleaning up defunct item %s (%s) failed: %s (%s, %d)",
                   stc_item_get_id (item),
                   enum_to_str (STC_TYPE_ITEM_TYPE, stc_item_get_item_type (item)),
                   error->message,
                   g_quark_to_string (error->domain),
                   error->code);
      g_error_free (error);
    }
}

static void
maybe_autocleanup_item (_StcDaemon *daemon,
                        StcItem    *item)
{
  StcOperation *operation;

  operation = NULL;

  /* First check if the item needs cleanup at all... */
  if (stc_item_get_state (item) != STC_ITEM_STATE_DEFUNCT)
    goto out;

  log_message (LOG_LEVEL_INFO,
               "Stopping defunct item %s (%s)",
               stc_item_get_id (item),
               enum_to_str (STC_TYPE_ITEM_TYPE, stc_item_get_item_type (item)));

  /* TODO: need to serialize stop requests for the same reasons we
   * seralize start requests - see maybe_autostart_items() for
   * details and why
   */
  operation = get_operation (daemon);
  stc_item_stop (item,
                 operation,
                 NULL,  /* GCancellable* */
                 stop_cb,
                 NULL); /* user_data */

 out:
  if (operation != NULL)
    g_object_unref (operation);
}

/* ---------------------------------------------------------------------------------------------------- */

/* Called whenever an item has been added, removed or changed - and on coldplug */
static void
maybe_act_on_item (_StcDaemon *daemon,
                   StcItem    *item)
{
  /* Only act on the item if Auto=true is set */
  if (!stc_item_get_auto (item))
    goto out;

  log_message (LOG_LEVEL_DEBUG,
               "maybe_act_on_item() for id %s (type=%s, state=%s)",
               stc_item_get_id (item),
               enum_to_str (STC_TYPE_ITEM_TYPE, stc_item_get_item_type (item)),
               enum_to_str (STC_TYPE_ITEM_STATE, stc_item_get_state (item)));

  maybe_autostart_item (daemon, item);
  maybe_autocleanup_item (daemon, item);

 out:
  ;
}

/* ---------------------------------------------------------------------------------------------------- */

static void
on_item_added (StcMonitor  *monitor,
               StcItem     *item,
               gpointer     user_data)
{
  _StcDaemon *daemon = _STC_DAEMON (user_data);

  log_message (LOG_LEVEL_DEBUG, "Item %s added", stc_item_get_id (item));
  maybe_act_on_item (daemon, item);
}

static void
on_item_removed (StcMonitor  *monitor,
                 StcItem     *item,
                 gpointer     user_data)
{
  _StcDaemon *daemon = _STC_DAEMON (user_data);

  log_message (LOG_LEVEL_DEBUG, "Item %s removed", stc_item_get_id (item));
  maybe_act_on_item (daemon, item);
}

static void
on_item_changed (StcMonitor  *monitor,
                 StcItem     *item,
                 gpointer     user_data)
{
  _StcDaemon *daemon = _STC_DAEMON (user_data);

  log_message (LOG_LEVEL_DEBUG, "Item %s changed", stc_item_get_id (item));
  maybe_act_on_item (daemon, item);
}

/* ---------------------------------------------------------------------------------------------------- */

static gboolean
on_sigint (gpointer user_data)
{
  GMainLoop *loop = user_data;
  g_print ("Handling SIGINT\n");
  g_main_loop_quit (loop);
  return FALSE;
}

int
main (int argc, char *argv[])
{
  GMainLoop *loop;
  _StcDaemon *daemon;
  guint sigint_id;

  g_type_init ();

  log_message (LOG_LEVEL_INFO, "stcd " PACKAGE_VERSION " starting up");


  log_message (LOG_LEVEL_DEBUG, "running event loop");

  loop = g_main_loop_new (NULL, FALSE);
  daemon = _stc_daemon_new ();

  sigint_id = _g_posix_signal_watch_add (SIGINT,
                                         G_PRIORITY_DEFAULT,
                                         on_sigint,
                                         loop,
                                         NULL);

  g_main_loop_run (loop);

  g_print ("Shutting down\n");

  if (sigint_id > 0)
    g_source_remove (sigint_id);
  g_object_unref (daemon);
  g_main_loop_unref (loop);

  return 0;
}