aboutsummaryrefslogtreecommitdiff
path: root/src/arm/arm_api.c
blob: afc32fc3a5bbe0d0602bce05bc23fb88ccaf563d (plain) (blame)
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
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
/*
     This file is part of GNUnet.
     Copyright (C) 2009, 2010, 2012, 2013, 2016, 2019 GNUnet e.V.

     GNUnet is free software: you can redistribute it and/or modify it
     under the terms of the GNU Affero General Public License as published
     by the Free Software Foundation, either version 3 of the License,
     or (at your option) any later version.

     GNUnet 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
     Affero General Public License for more details.

     You should have received a copy of the GNU Affero General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.

     SPDX-License-Identifier: AGPL3.0-or-later
 */

/**
 * @file arm/arm_api.c
 * @brief API for accessing the ARM service
 * @author Christian Grothoff
 * @author LRN
 */
#include "platform.h"
#include "gnunet_util_lib.h"
#include "gnunet_arm_service.h"
#include "gnunet_protocols.h"
#include "arm.h"

#define LOG(kind, ...) GNUNET_log_from (kind, "arm-api", __VA_ARGS__)


/**
 * Entry in a doubly-linked list of operations awaiting for replies
 * (in-order) from the ARM service.
 */
struct GNUNET_ARM_Operation
{
  /**
   * This is a doubly-linked list.
   */
  struct GNUNET_ARM_Operation *next;

  /**
   * This is a doubly-linked list.
   */
  struct GNUNET_ARM_Operation *prev;

  /**
   * ARM handle.
   */
  struct GNUNET_ARM_Handle *h;

  /**
   * Callback for service state change requests.
   */
  GNUNET_ARM_ResultCallback result_cont;

  /**
   * Callback for service list requests.
   */
  GNUNET_ARM_ServiceListCallback list_cont;

  /**
   * Closure for @e result_cont or @e list_cont.
   */
  void *cont_cls;

  /**
   * Task for async completion.
   */
  struct GNUNET_SCHEDULER_Task *async;

  /**
   * Unique ID for the request.
   */
  uint64_t id;

  /**
   * Result of this operation for #notify_starting().
   */
  enum GNUNET_ARM_Result starting_ret;

  /**
   * File descriptor to close on operation stop, if not NULL.
   */
  struct GNUNET_DISK_FileHandle *rfd;

  /**
   * Is this an operation to stop the ARM service?
   */
  int is_arm_stop;
};


/**
 * Handle for interacting with ARM.
 */
struct GNUNET_ARM_Handle
{
  /**
   * Our connection to the ARM service.
   */
  struct GNUNET_MQ_Handle *mq;

  /**
   * The configuration that we are using.
   */
  const struct GNUNET_CONFIGURATION_Handle *cfg;

  /**
   * Head of doubly-linked list of pending operations.
   */
  struct GNUNET_ARM_Operation *operation_pending_head;

  /**
   * Tail of doubly-linked list of pending operations.
   */
  struct GNUNET_ARM_Operation *operation_pending_tail;

  /**
   * Callback to invoke on connection/disconnection.
   */
  GNUNET_ARM_ConnectionStatusCallback conn_status;

  /**
   * Closure for @e conn_status.
   */
  void *conn_status_cls;

  /**
   * ARM operation where the goal is to wait for ARM shutdown to
   * complete.  This operation is special in that it waits for an
   * error on the @e mq.  So we complete it by calling the
   * continuation in the #mq_error_handler().  Note that the operation
   * is no longer in the @e operation_pending_head DLL once it is
   * referenced from this field.
   */
  struct GNUNET_ARM_Operation *thm;

  /**
   * ID of the reconnect task (if any).
   */
  struct GNUNET_SCHEDULER_Task *reconnect_task;

  /**
   * Current delay we use for re-trying to connect to core.
   */
  struct GNUNET_TIME_Relative retry_backoff;

  /**
   * Counter for request identifiers.  They are used to match replies
   * from ARM to operations in the @e operation_pending_head DLL.
   */
  uint64_t request_id_counter;

  /**
   * Have we detected that ARM is up?
   */
  int currently_up;
};


/**
 * Connect to arm.
 *
 * @param h arm handle
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
 */
static int
reconnect_arm (struct GNUNET_ARM_Handle *h);


/**
 * Task scheduled to try to re-connect to arm.
 *
 * @param cls the `struct GNUNET_ARM_Handle`
 */
static void
reconnect_arm_task (void *cls)
{
  struct GNUNET_ARM_Handle *h = cls;

  h->reconnect_task = NULL;
  reconnect_arm (h);
}


/**
 * Close down any existing connection to the ARM service and
 * try re-establishing it later.
 *
 * @param h our handle
 */
static void
reconnect_arm_later (struct GNUNET_ARM_Handle *h)
{
  struct GNUNET_ARM_Operation *op;

  if (NULL != h->mq)
  {
    GNUNET_MQ_destroy (h->mq);
    h->mq = NULL;
  }
  h->currently_up = GNUNET_NO;
  GNUNET_assert (NULL == h->reconnect_task);
  h->reconnect_task =
    GNUNET_SCHEDULER_add_delayed (h->retry_backoff,
                                  &reconnect_arm_task,
                                  h);
  while (NULL != (op = h->operation_pending_head))
  {
    if (NULL != op->result_cont)
      op->result_cont (op->cont_cls,
                       GNUNET_ARM_REQUEST_DISCONNECTED,
                       0);
    if (NULL != op->list_cont)
      op->list_cont (op->cont_cls,
                     GNUNET_ARM_REQUEST_DISCONNECTED,
                     0,
                     NULL);
    GNUNET_ARM_operation_cancel (op);
  }
  GNUNET_assert (NULL == h->operation_pending_head);
  h->retry_backoff = GNUNET_TIME_STD_BACKOFF (h->retry_backoff);
  if (NULL != h->conn_status)
    h->conn_status (h->conn_status_cls,
                    GNUNET_NO);
}


/**
 * Find a control message by its unique ID.
 *
 * @param h ARM handle
 * @param id unique message ID to use for the lookup
 * @return NULL if not found
 */
static struct GNUNET_ARM_Operation *
find_op_by_id (struct GNUNET_ARM_Handle *h,
               uint64_t id)
{
  for (struct GNUNET_ARM_Operation *result = h->operation_pending_head;
       NULL != result;
       result = result->next)
    if (id == result->id)
      return result;
  return NULL;
}


/**
 * Handler for ARM replies.
 *
 * @param cls our `struct GNUNET_ARM_Handle`
 * @param res the message received from the arm service
 */
static void
handle_arm_result (void *cls,
                   const struct GNUNET_ARM_ResultMessage *res)
{
  struct GNUNET_ARM_Handle *h = cls;
  struct GNUNET_ARM_Operation *op;
  uint64_t id;
  enum GNUNET_ARM_Result result;
  GNUNET_ARM_ResultCallback result_cont;
  void *result_cont_cls;

  id = GNUNET_ntohll (res->arm_msg.request_id);
  op = find_op_by_id (h,
                      id);
  if (NULL == op)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Message with unknown id %llu\n",
         (unsigned long long) id);
    return;
  }

  result = (enum GNUNET_ARM_Result) ntohl (res->result);
  if ( (GNUNET_YES == op->is_arm_stop) &&
       (GNUNET_ARM_RESULT_STOPPING == result) )
  {
    /* special case: if we are stopping 'gnunet-service-arm', we do not just
       wait for the result message, but also wait for the service to close
       the connection (and then we have to close our client handle as well);
       this is done by installing a different receive handler, waiting for
       the connection to go down */if (NULL != h->thm)
    {
      GNUNET_break (0);
      op->result_cont (h->thm->cont_cls,
                       GNUNET_ARM_REQUEST_SENT_OK,
                       GNUNET_ARM_RESULT_IS_NOT_KNOWN);
      GNUNET_free (h->thm);
    }
    GNUNET_CONTAINER_DLL_remove (h->operation_pending_head,
                                 h->operation_pending_tail,
                                 op);
    h->thm = op;
    return;
  }
  result_cont = op->result_cont;
  result_cont_cls = op->cont_cls;
  GNUNET_ARM_operation_cancel (op);
  if (NULL != result_cont)
    result_cont (result_cont_cls,
                 GNUNET_ARM_REQUEST_SENT_OK,
                 result);
}


/**
 * Read from a string pool.
 *
 * @param pool_start start of the string pool
 * @param pool_size size of the string pool
 * @param str_index index into the string pool
 * @returns an index into the string pool, or
 *          NULL if the index is out of bounds
 */
static const char *
pool_get (const char *pool_start,
          size_t pool_size,
          size_t str_index)
{
  const char *str_start;
  const char *end;

  if (str_index >= pool_size)
    return NULL;
  str_start = pool_start + str_index;
  end = memchr (str_start, 0, pool_size - str_index);
  if (NULL == end)
    return NULL;
  return str_start;
}


/**
 * Check that list result message is well-formed.
 *
 * @param cls our `struct GNUNET_ARM_Handle`
 * @param lres the message received from the arm service
 * @return #GNUNET_OK if message is well-formed
 */
static int
check_arm_list_result (void *cls,
                       const struct GNUNET_ARM_ListResultMessage *lres)
{
  uint16_t rcount = ntohs (lres->count);
  uint16_t msize = ntohs (lres->arm_msg.header.size) - sizeof(*lres);
  struct GNUNET_ARM_ServiceInfoMessage *ssm;
  size_t pool_size;
  char *pool_start;

  (void) cls;
  if ((rcount * sizeof (struct GNUNET_ARM_ServiceInfoMessage) > msize))
  {
    GNUNET_break_op (0);
    return GNUNET_NO;
  }
  ssm = (struct GNUNET_ARM_ServiceInfoMessage *) &lres[1];
  pool_start = (char *) (ssm + rcount);
  pool_size = msize - (rcount * sizeof (struct GNUNET_ARM_ServiceInfoMessage));
  for (unsigned int i = 0; i < rcount; i++)
  {
    uint16_t name_index = ntohs (ssm->name_index);
    uint16_t binary_index = ntohs (ssm->binary_index);
    if (NULL == pool_get (pool_start,
                          pool_size,
                          name_index))
    {
      GNUNET_break_op (0);
      return GNUNET_NO;
    }
    if (NULL == pool_get (pool_start,
                          pool_size,
                          binary_index))
    {
      GNUNET_break_op (0);
      return GNUNET_NO;
    }
    ssm++;
  }
  return GNUNET_OK;
}


/**
 * Handler for ARM list replies.
 *
 * @param cls our `struct GNUNET_ARM_Handle`
 * @param lres the message received from the arm service
 */
static void
handle_arm_list_result (void *cls,
                        const struct GNUNET_ARM_ListResultMessage *lres)
{
  struct GNUNET_ARM_Handle *h = cls;
  uint16_t rcount = ntohs (lres->count);
  uint16_t msize = ntohs (lres->arm_msg.header.size) - sizeof(*lres);
  struct GNUNET_ARM_ServiceInfo list[rcount];
  struct GNUNET_ARM_ServiceInfoMessage *ssm;
  struct GNUNET_ARM_Operation *op;
  uint64_t id;
  size_t pool_size;
  char *pool_start;

  id = GNUNET_ntohll (lres->arm_msg.request_id);
  op = find_op_by_id (h, id);
  if (NULL == op)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Message with unknown id %llu\n",
         (unsigned long long) id);
    return;
  }

  GNUNET_assert ((rcount * sizeof (struct GNUNET_ARM_ServiceInfoMessage) <=
                  msize));

  ssm = (struct GNUNET_ARM_ServiceInfoMessage *) &lres[1];
  pool_start = (char *) (ssm + rcount);
  pool_size = msize - (rcount * sizeof (struct GNUNET_ARM_ServiceInfoMessage));

  for (unsigned int i = 0; i < rcount; i++)
  {
    uint16_t name_index = ntohs (ssm->name_index);
    uint16_t binary_index = ntohs (ssm->binary_index);
    const char *name;
    const char *binary;

    name = pool_get (pool_start, pool_size, name_index);
    binary = pool_get (pool_start, pool_size, binary_index);
    GNUNET_assert (NULL != name);
    GNUNET_assert (NULL != binary);
    list[i] = (struct GNUNET_ARM_ServiceInfo) {
      .name = name,
      .binary = binary,
      .status = ntohl (ssm->status),
      .last_started_at = GNUNET_TIME_absolute_ntoh (ssm->last_started_at),
      .restart_at = GNUNET_TIME_absolute_ntoh (ssm->restart_at),
      .last_exit_status = ntohs (ssm->last_exit_status),
    };
    ssm++;
  }
  if (NULL != op->list_cont)
    op->list_cont (op->cont_cls,
                   GNUNET_ARM_REQUEST_SENT_OK,
                   rcount,
                   list);
  GNUNET_ARM_operation_cancel (op);
}


/**
 * Receive confirmation from test, ARM service is up.
 *
 * @param cls closure with the `struct GNUNET_ARM_Handle`
 * @param msg message received
 */
static void
handle_confirm (void *cls,
                const struct GNUNET_MessageHeader *msg)
{
  struct GNUNET_ARM_Handle *h = cls;

  (void) msg;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Got confirmation from ARM that we are up!\n");
  if (GNUNET_NO == h->currently_up)
  {
    h->currently_up = GNUNET_YES;
    if (NULL != h->conn_status)
      h->conn_status (h->conn_status_cls, GNUNET_YES);
  }
}


/**
 * Generic error handler, called with the appropriate error code and
 * the same closure specified at the creation of the message queue.
 * Not every message queue implementation supports an error handler.
 *
 * @param cls closure with the `struct GNUNET_ARM_Handle *`
 * @param error error code
 */
static void
mq_error_handler (void *cls,
                  enum GNUNET_MQ_Error error)
{
  struct GNUNET_ARM_Handle *h = cls;
  struct GNUNET_ARM_Operation *op;

  (void) error;
  h->currently_up = GNUNET_NO;
  if (NULL != (op = h->thm))
  {
    h->thm = NULL;
    op->result_cont (op->cont_cls,
                     GNUNET_ARM_REQUEST_SENT_OK,
                     GNUNET_ARM_RESULT_STOPPED);
    GNUNET_free (op);
  }
  reconnect_arm_later (h);
}


/**
 * Connect to arm.
 *
 * @param h arm handle
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
 */
static int
reconnect_arm (struct GNUNET_ARM_Handle *h)
{
  struct GNUNET_MQ_MessageHandler handlers[] = {
    GNUNET_MQ_hd_fixed_size (arm_result,
                             GNUNET_MESSAGE_TYPE_ARM_RESULT,
                             struct GNUNET_ARM_ResultMessage,
                             h),
    GNUNET_MQ_hd_var_size (arm_list_result,
                           GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT,
                           struct GNUNET_ARM_ListResultMessage,
                           h),
    GNUNET_MQ_hd_fixed_size (confirm,
                             GNUNET_MESSAGE_TYPE_ARM_TEST,
                             struct GNUNET_MessageHeader,
                             h),
    GNUNET_MQ_handler_end ()
  };
  struct GNUNET_MessageHeader *test;
  struct GNUNET_MQ_Envelope *env;

  if (NULL != h->mq)
    return GNUNET_OK;
  GNUNET_assert (GNUNET_NO == h->currently_up);
  h->mq = GNUNET_CLIENT_connect (h->cfg,
                                 "arm",
                                 handlers,
                                 &mq_error_handler,
                                 h);
  if (NULL == h->mq)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "GNUNET_CLIENT_connect returned NULL\n");
    if (NULL != h->conn_status)
      h->conn_status (h->conn_status_cls,
                      GNUNET_SYSERR);
    return GNUNET_SYSERR;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Sending TEST message to ARM\n");
  env = GNUNET_MQ_msg (test,
                       GNUNET_MESSAGE_TYPE_ARM_TEST);
  GNUNET_MQ_send (h->mq, env);
  return GNUNET_OK;
}


/**
 * Set up a context for communicating with ARM, then
 * start connecting to the ARM service using that context.
 *
 * @param cfg configuration to use (needed to contact ARM;
 *        the ARM service may internally use a different
 *        configuration to determine how to start the service).
 * @param conn_status will be called when connecting/disconnecting
 * @param conn_status_cls closure for @a conn_status
 * @return context to use for further ARM operations, NULL on error.
 */
struct GNUNET_ARM_Handle *
GNUNET_ARM_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
                    GNUNET_ARM_ConnectionStatusCallback conn_status,
                    void *conn_status_cls)
{
  struct GNUNET_ARM_Handle *h;

  h = GNUNET_new (struct GNUNET_ARM_Handle);
  h->cfg = cfg;
  h->conn_status = conn_status;
  h->conn_status_cls = conn_status_cls;
  if (GNUNET_OK != reconnect_arm (h))
  {
    GNUNET_free (h);
    return NULL;
  }
  return h;
}


/**
 * Disconnect from the ARM service (if connected) and destroy the context.
 *
 * @param h the handle that was being used
 */
void
GNUNET_ARM_disconnect (struct GNUNET_ARM_Handle *h)
{
  struct GNUNET_ARM_Operation *op;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from ARM service\n");
  while (NULL != (op = h->operation_pending_head))
  {
    GNUNET_CONTAINER_DLL_remove (h->operation_pending_head,
                                 h->operation_pending_tail,
                                 op);
    if (NULL != op->result_cont)
      op->result_cont (op->cont_cls,
                       GNUNET_ARM_REQUEST_DISCONNECTED,
                       0);
    if (NULL != op->list_cont)
      op->list_cont (op->cont_cls,
                     GNUNET_ARM_REQUEST_DISCONNECTED,
                     0,
                     NULL);
    if (NULL != op->async)
    {
      GNUNET_SCHEDULER_cancel (op->async);
      op->async = NULL;
    }
    GNUNET_free (op);
  }
  if (NULL != h->mq)
  {
    GNUNET_MQ_destroy (h->mq);
    h->mq = NULL;
  }
  if (NULL != h->reconnect_task)
  {
    GNUNET_SCHEDULER_cancel (h->reconnect_task);
    h->reconnect_task = NULL;
  }
  GNUNET_free (h);
}


/**
 * A client specifically requested starting of ARM itself.
 * Starts the ARM service.
 *
 * @param h the handle with configuration details
 * @param std_inheritance inheritance of std streams
 * @param sigfd socket to pass to ARM for signalling
 * @return operation status code
 */
static enum GNUNET_ARM_Result
start_arm_service (struct GNUNET_ARM_Handle *h,
                   enum GNUNET_OS_InheritStdioFlags std_inheritance,
                   struct GNUNET_DISK_FileHandle *sigfd)
{
  struct GNUNET_OS_Process *proc;
  char *cbinary;
  char *binary;
  char *quotedbinary;
  char *config;
  char *loprefix;
  char *lopostfix;
  int ld[2];
  int *lsocks;

  if (NULL == sigfd)
  {
    lsocks = NULL;
  }
  else
  {
    ld[0] = sigfd->fd;
    ld[1] = -1;
    lsocks = ld;
  }
  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (h->cfg,
                                                          "arm",
                                                          "PREFIX",
                                                          &loprefix))
    loprefix = GNUNET_strdup ("");
  else
    loprefix = GNUNET_CONFIGURATION_expand_dollar (h->cfg, loprefix);
  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (h->cfg,
                                                          "arm",
                                                          "OPTIONS",
                                                          &lopostfix))
    lopostfix = GNUNET_strdup ("");
  else
    lopostfix = GNUNET_CONFIGURATION_expand_dollar (h->cfg,
                                                    lopostfix);
  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_string (h->cfg,
                                             "arm",
                                             "BINARY",
                                             &cbinary))
  {
    GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING,
                               "arm",
                               "BINARY");
    GNUNET_free (loprefix);
    GNUNET_free (lopostfix);
    return GNUNET_ARM_RESULT_IS_NOT_KNOWN;
  }
  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (h->cfg,
                                                            "arm",
                                                            "CONFIG",
                                                            &config))
    config = NULL;
  binary = GNUNET_OS_get_libexec_binary_path (cbinary);
  GNUNET_asprintf (&quotedbinary,
                   "\"%s\"",
                   binary);
  GNUNET_free (cbinary);
  if ( (GNUNET_YES ==
        GNUNET_CONFIGURATION_have_value (h->cfg,
                                         "TESTING",
                                         "WEAKRANDOM")) &&
       (GNUNET_YES ==
        GNUNET_CONFIGURATION_get_value_yesno (h->cfg,
                                              "TESTING",
                                              "WEAKRANDOM")) &&
       (GNUNET_NO ==
        GNUNET_CONFIGURATION_have_value (h->cfg,
                                         "TESTING",
                                         "HOSTFILE")) )
  {
    /* Means we are ONLY running locally */
    /* we're clearly running a test, don't daemonize */
    if (NULL == config)
      proc = GNUNET_OS_start_process_s (std_inheritance,
                                        lsocks,
                                        loprefix,
                                        quotedbinary,
                                        /* no daemonization! */
                                        lopostfix,
                                        NULL);
    else
      proc = GNUNET_OS_start_process_s (std_inheritance,
                                        lsocks,
                                        loprefix,
                                        quotedbinary,
                                        "-c",
                                        config,
                                        /* no daemonization! */
                                        lopostfix,
                                        NULL);
  }
  else
  {
    if (NULL == config)
      proc = GNUNET_OS_start_process_s (std_inheritance,
                                        lsocks,
                                        loprefix,
                                        quotedbinary,
                                        "-d",  /* do daemonize */
                                        lopostfix,
                                        NULL);
    else
      proc = GNUNET_OS_start_process_s (std_inheritance,
                                        lsocks,
                                        loprefix,
                                        quotedbinary,
                                        "-c",
                                        config,
                                        "-d",  /* do daemonize */
                                        lopostfix,
                                        NULL);
  }
  GNUNET_free (binary);
  GNUNET_free (quotedbinary);
  if (NULL != config)
    GNUNET_free (config);
  GNUNET_free (loprefix);
  GNUNET_free (lopostfix);
  if (NULL == proc)
    return GNUNET_ARM_RESULT_START_FAILED;
  GNUNET_OS_process_destroy (proc);
  return GNUNET_ARM_RESULT_STARTING;
}


/**
 * Abort an operation.  Only prevents the callback from being
 * called, the operation may still complete.
 *
 * @param op operation to cancel
 */
void
GNUNET_ARM_operation_cancel (struct GNUNET_ARM_Operation *op)
{
  struct GNUNET_ARM_Handle *h = op->h;

  if (NULL != op->async)
  {
    GNUNET_SCHEDULER_cancel (op->async);
    op->async = NULL;
  }
  if (NULL != op->rfd)
  {
    GNUNET_DISK_file_close (op->rfd);
    op->rfd = NULL;
  }
  if (h->thm == op)
  {
    op->result_cont = NULL;
    return;
  }
  GNUNET_CONTAINER_DLL_remove (h->operation_pending_head,
                               h->operation_pending_tail,
                               op);
  GNUNET_free (op);
}


/**
 * Start or stop a service.
 *
 * @param h handle to ARM
 * @param service_name name of the service
 * @param cb callback to invoke when service is ready
 * @param cb_cls closure for @a cb
 * @param type type of the request
 * @return handle to queue, NULL on error
 */
static struct GNUNET_ARM_Operation *
change_service (struct GNUNET_ARM_Handle *h,
                const char *service_name,
                GNUNET_ARM_ResultCallback cb,
                void *cb_cls,
                uint16_t type)
{
  struct GNUNET_ARM_Operation *op;
  size_t slen;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_ARM_Message *msg;

  slen = strlen (service_name) + 1;
  if (slen + sizeof(struct GNUNET_ARM_Message) >= GNUNET_MAX_MESSAGE_SIZE)
  {
    GNUNET_break (0);
    return NULL;
  }
  if (0 == h->request_id_counter)
    h->request_id_counter++;
  op = GNUNET_new (struct GNUNET_ARM_Operation);
  op->h = h;
  op->result_cont = cb;
  op->cont_cls = cb_cls;
  op->id = h->request_id_counter++;
  GNUNET_CONTAINER_DLL_insert_tail (h->operation_pending_head,
                                    h->operation_pending_tail,
                                    op);
  env = GNUNET_MQ_msg_extra (msg, slen, type);
  msg->reserved = htonl (0);
  msg->request_id = GNUNET_htonll (op->id);
  GNUNET_memcpy (&msg[1], service_name, slen);
  GNUNET_MQ_send (h->mq, env);
  return op;
}


/**
 * Task run to notify application that ARM is already up.
 *
 * @param cls the operation that asked ARM to be started
 */
static void
notify_running (void *cls)
{
  struct GNUNET_ARM_Operation *op = cls;
  struct GNUNET_ARM_Handle *h = op->h;

  op->async = NULL;
  GNUNET_CONTAINER_DLL_remove (h->operation_pending_head,
                               h->operation_pending_tail,
                               op);
  if (NULL != op->result_cont)
    op->result_cont (op->cont_cls,
                     GNUNET_ARM_REQUEST_SENT_OK,
                     GNUNET_ARM_RESULT_IS_STARTED_ALREADY);
  if ( (GNUNET_YES == h->currently_up) &&
       (NULL != h->conn_status) )
    h->conn_status (h->conn_status_cls,
                    GNUNET_YES);
  GNUNET_free (op);
}


/**
 * Task run to notify application that ARM is being started.
 *
 * @param cls the operation that asked ARM to be started
 */
static void
notify_starting (void *cls)
{
  struct GNUNET_ARM_Operation *op = cls;
  struct GNUNET_ARM_Handle *h = op->h;

  op->async = NULL;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Notifying client that we started the ARM service\n");
  GNUNET_CONTAINER_DLL_remove (h->operation_pending_head,
                               h->operation_pending_tail,
                               op);
  if (NULL != op->result_cont)
    op->result_cont (op->cont_cls,
                     GNUNET_ARM_REQUEST_SENT_OK,
                     op->starting_ret);
  GNUNET_free (op);
}


/**
 * Request for a service to be started.
 *
 * @param h handle to ARM
 * @param service_name name of the service
 * @param std_inheritance inheritance of std streams
 * @param cont callback to invoke after request is sent or not sent
 * @param cont_cls closure for @a cont
 * @return handle for the operation, NULL on error
 */
struct GNUNET_ARM_Operation *
GNUNET_ARM_request_service_start (struct GNUNET_ARM_Handle *h,
                                  const char *service_name,
                                  enum GNUNET_OS_InheritStdioFlags
                                  std_inheritance,
                                  GNUNET_ARM_ResultCallback cont,
                                  void *cont_cls)
{
  struct GNUNET_ARM_Operation *op;
  enum GNUNET_ARM_Result ret;
  struct GNUNET_DISK_PipeHandle *sig;
  struct GNUNET_DISK_FileHandle *wsig;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Starting service `%s'\n",
       service_name);
  if (0 != strcasecmp ("arm",
                       service_name))
    return change_service (h,
                           service_name,
                           cont,
                           cont_cls,
                           GNUNET_MESSAGE_TYPE_ARM_START);

  /* Possible cases:
   * 1) We're connected to ARM already. Invoke the callback immediately.
   * 2) We're not connected to ARM.
   *    Cancel any reconnection attempts temporarily, then perform
   *    a service test.
   */
  if (GNUNET_YES == h->currently_up)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "ARM is already running\n");
    op = GNUNET_new (struct GNUNET_ARM_Operation);
    op->h = h;
    op->result_cont = cont;
    op->cont_cls = cont_cls;
    GNUNET_CONTAINER_DLL_insert_tail (h->operation_pending_head,
                                      h->operation_pending_tail,
                                      op);
    op->async = GNUNET_SCHEDULER_add_now (&notify_running, op);
    return op;
  }
  /* This is an inherently uncertain choice, as it is of course
     theoretically possible that ARM is up and we just did not
     yet complete the MQ handshake.  However, given that users
     are unlikely to hammer 'gnunet-arm -s' on a busy system,
     the above check should catch 99.99% of the cases where ARM
     is already running. */
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Starting ARM service\n");
  if (NULL == (sig = GNUNET_DISK_pipe (GNUNET_DISK_PF_NONE)))
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                         "pipe");
  } else {
    wsig = GNUNET_DISK_pipe_detach_end (sig,
                                      GNUNET_DISK_PIPE_END_WRITE);
    ret = start_arm_service (h,
                             std_inheritance,
                             wsig);
    GNUNET_DISK_file_close (wsig);
    if (GNUNET_ARM_RESULT_STARTING == ret)
      reconnect_arm (h);
  }
  op = GNUNET_new (struct GNUNET_ARM_Operation);
  op->h = h;
  op->result_cont = cont;
  op->cont_cls = cont_cls;
  GNUNET_CONTAINER_DLL_insert_tail (h->operation_pending_head,
                                    h->operation_pending_tail,
                                    op);
  op->starting_ret = ret;
  if (NULL != sig)
  {
    op->rfd = GNUNET_DISK_pipe_detach_end (sig,
                                           GNUNET_DISK_PIPE_END_READ);
    /* Wait at most a minute for gnunet-service-arm to be up, as beyond
       that something clearly just went wrong */
    op->async = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_MINUTES,
                                                op->rfd,
                                                &notify_starting,
                                                op);
    GNUNET_DISK_pipe_close (sig);
  }
  else
  {
    op->async = GNUNET_SCHEDULER_add_now (&notify_starting,
                                          op);
  }
  return op;
}


/**
 * Request a service to be stopped.  Stopping arm itself will not
 * invalidate its handle, and ARM API will try to restore connection
 * to the ARM service, even if ARM connection was lost because you
 * asked for ARM to be stopped.  Call
 * #GNUNET_ARM_disconnect() to free the handle and prevent
 * further connection attempts.
 *
 * @param h handle to ARM
 * @param service_name name of the service
 * @param cont callback to invoke after request is sent or is not sent
 * @param cont_cls closure for @a cont
 * @return handle for the operation, NULL on error
 */
struct GNUNET_ARM_Operation *
GNUNET_ARM_request_service_stop (struct GNUNET_ARM_Handle *h,
                                 const char *service_name,
                                 GNUNET_ARM_ResultCallback cont,
                                 void *cont_cls)
{
  struct GNUNET_ARM_Operation *op;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Stopping service `%s'\n",
       service_name);
  op = change_service (h,
                       service_name,
                       cont,
                       cont_cls,
                       GNUNET_MESSAGE_TYPE_ARM_STOP);
  if (NULL == op)
    return NULL;
  /* If the service is ARM, set a flag as we will use MQ errors
     to detect that the process is really gone. */
  if (0 == strcasecmp (service_name,
                       "arm"))
    op->is_arm_stop = GNUNET_YES;
  return op;
}


/**
 * Request a list of running services.
 *
 * @param h handle to ARM
 * @param cont callback to invoke after request is sent or is not sent
 * @param cont_cls closure for @a cont
 * @return handle for the operation, NULL on error
 */
struct GNUNET_ARM_Operation *
GNUNET_ARM_request_service_list (struct GNUNET_ARM_Handle *h,
                                 GNUNET_ARM_ServiceListCallback cont,
                                 void *cont_cls)
{
  struct GNUNET_ARM_Operation *op;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_ARM_Message *msg;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Requesting LIST from ARM service\n");
  if (0 == h->request_id_counter)
    h->request_id_counter++;
  op = GNUNET_new (struct GNUNET_ARM_Operation);
  op->h = h;
  op->list_cont = cont;
  op->cont_cls = cont_cls;
  op->id = h->request_id_counter++;
  GNUNET_CONTAINER_DLL_insert_tail (h->operation_pending_head,
                                    h->operation_pending_tail,
                                    op);
  env = GNUNET_MQ_msg (msg,
                       GNUNET_MESSAGE_TYPE_ARM_LIST);
  msg->reserved = htonl (0);
  msg->request_id = GNUNET_htonll (op->id);
  GNUNET_MQ_send (h->mq, env);
  return op;
}


/* end of arm_api.c */