use c99
[oweals/gnunet.git] / src / arm / arm_api.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2010, 2012, 2013 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file arm/arm_api.c
23  * @brief API for accessing the ARM service
24  * @author Christian Grothoff
25  * @author LRN
26  */
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_arm_service.h"
30 #include "gnunet_protocols.h"
31 #include "arm.h"
32
33 #define LOG(kind,...) GNUNET_log_from (kind, "arm-api",__VA_ARGS__)
34
35 /**
36  * Handle for interacting with ARM.
37  */
38 struct GNUNET_ARM_Handle
39 {
40   /**
41    * Our control connection to the ARM service.
42    */
43   struct GNUNET_CLIENT_Connection *client;
44
45   /**
46    * The configuration that we are using.
47    */
48   struct GNUNET_CONFIGURATION_Handle *cfg;
49
50   /**
51    * Handle for our current transmission request.
52    */
53   struct GNUNET_CLIENT_TransmitHandle *cth;
54
55   /**
56    * Head of doubly-linked list of pending requests.
57    */
58   struct ARMControlMessage *control_pending_head;
59
60   /**
61    * Tail of doubly-linked list of pending requests.
62    */
63   struct ARMControlMessage *control_pending_tail;
64
65   /**
66    * Head of doubly-linked list of sent requests.
67    */
68   struct ARMControlMessage *control_sent_head;
69
70   /**
71    * Tail of doubly-linked list of sent requests.
72    */
73   struct ARMControlMessage *control_sent_tail;
74
75   /**
76    * Callback to invoke on connection/disconnection.
77    */
78   GNUNET_ARM_ConnectionStatusCallback conn_status;
79
80   /**
81    * Closure for conn_status.
82    */
83   void *conn_status_cls;
84
85   /**
86    * ARM control message for the 'arm_termination_handler'
87    * with the continuation to call once the ARM shutdown is done.
88    */
89   struct ARMControlMessage *thm;
90
91   /**
92    * ID of the reconnect task (if any).
93    */
94   struct GNUNET_SCHEDULER_Task *reconnect_task;
95
96   /**
97    * Current delay we use for re-trying to connect to core.
98    */
99   struct GNUNET_TIME_Relative retry_backoff;
100
101   /**
102    * Counter for request identifiers
103    */
104   uint64_t request_id_counter;
105
106   /**
107    * Are we currently disconnected and hence unable to send?
108    */
109   unsigned char currently_down;
110
111   /**
112    * #GNUNET_YES if we're running a service test.
113    */
114   unsigned char service_test_is_active;
115 };
116
117
118 /**
119  * Entry in a doubly-linked list of control messages to be transmitted
120  * to the arm service.
121  *
122  * The actual message is allocated at the end of this struct.
123  */
124 struct ARMControlMessage
125 {
126   /**
127    * This is a doubly-linked list.
128    */
129   struct ARMControlMessage *next;
130
131   /**
132    * This is a doubly-linked list.
133    */
134   struct ARMControlMessage *prev;
135
136   /**
137    * ARM handle.
138    */
139   struct GNUNET_ARM_Handle *h;
140
141   /**
142    * Message to send.
143    */
144   struct GNUNET_ARM_Message *msg;
145
146   /**
147    * Callback for service state change requests.
148    */
149   GNUNET_ARM_ResultCallback result_cont;
150
151   /**
152    * Callback for service list requests.
153    */
154   GNUNET_ARM_ServiceListCallback list_cont;
155
156   /**
157    * Closure for @e result_cont' or @e list_cont'.
158    */
159   void *cont_cls;
160
161   /**
162    * Timeout for the operation.
163    */
164   struct GNUNET_TIME_Absolute timeout;
165
166   /**
167    * Task to run when request times out.
168    */
169   struct GNUNET_SCHEDULER_Task * timeout_task_id;
170
171   /**
172    * Flags for passing std descriptors to ARM (when starting ARM).
173    */
174   enum GNUNET_OS_InheritStdioFlags std_inheritance;
175
176   /**
177    * Type of the request expressed as a message type (start, stop or list).
178    */
179   uint16_t type;
180 };
181
182
183 /**
184  * Connect to arm.
185  *
186  * @param h arm handle
187  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
188  */
189 static int
190 reconnect_arm (struct GNUNET_ARM_Handle *h);
191
192
193 /**
194  * Check the list of pending requests, send the next
195  * one to the arm.
196  *
197  * @param h arm handle
198  * @param ignore_currently_down transmit message even if not initialized?
199  */
200 static void
201 trigger_next_request (struct GNUNET_ARM_Handle *h, int ignore_currently_down);
202
203
204 /**
205  * Task scheduled to try to re-connect to arm.
206  *
207  * @param cls the 'struct GNUNET_ARM_Handle'
208  */
209 static void
210 reconnect_arm_task (void *cls)
211 {
212   struct GNUNET_ARM_Handle *h = cls;
213
214   h->reconnect_task = NULL;
215   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connecting to ARM service after delay\n");
216   reconnect_arm (h);
217 }
218
219
220 /**
221  * Close down any existing connection to the ARM service and
222  * try re-establishing it later.
223  *
224  * @param h our handle
225  */
226 static void
227 reconnect_arm_later (struct GNUNET_ARM_Handle *h)
228 {
229   if (GNUNET_NO != h->currently_down)
230     return;
231   if (NULL != h->cth)
232   {
233     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
234     h->cth = NULL;
235   }
236   if (NULL != h->client)
237   {
238     GNUNET_CLIENT_disconnect (h->client);
239     h->client = NULL;
240   }
241   h->currently_down = GNUNET_YES;
242   GNUNET_assert (NULL == h->reconnect_task);
243   h->reconnect_task =
244       GNUNET_SCHEDULER_add_delayed (h->retry_backoff,
245                                     &reconnect_arm_task,
246                                     h);
247   /* Don't clear pending messages on disconnection, deliver them later
248   clear_pending_messages (h, GNUNET_ARM_REQUEST_DISCONNECTED);
249   GNUNET_assert (NULL == h->control_pending_head);
250   */
251   h->retry_backoff = GNUNET_TIME_STD_BACKOFF (h->retry_backoff);
252   if (NULL != h->conn_status)
253     h->conn_status (h->conn_status_cls, GNUNET_NO);
254 }
255
256
257 /**
258  * Find a control message by its unique ID.
259  *
260  * @param h ARM handle
261  * @param id unique message ID to use for the lookup
262  * @return NULL if not found
263  */
264 static struct ARMControlMessage *
265 find_cm_by_id (struct GNUNET_ARM_Handle *h, uint64_t id)
266 {
267   struct ARMControlMessage *result;
268   for (result = h->control_sent_head; result; result = result->next)
269     if (id == result->msg->request_id)
270       return result;
271   return NULL;
272 }
273
274
275 /**
276  * Handler for ARM 'termination' reply (failure to receive).
277  *
278  * @param cls our "struct GNUNET_ARM_Handle"
279  * @param msg expected to be NULL
280  */
281 static void
282 arm_termination_handler (void *cls, const struct GNUNET_MessageHeader *msg)
283 {
284   struct GNUNET_ARM_Handle *h = cls;
285   struct ARMControlMessage *cm;
286
287   if (NULL != msg)
288   {
289     GNUNET_break (0);
290     GNUNET_CLIENT_receive (h->client, &arm_termination_handler, h,
291                            GNUNET_TIME_UNIT_FOREVER_REL);
292     return;
293   }
294   cm = h->thm;
295   h->thm = NULL;
296   h->currently_down = GNUNET_YES;
297   GNUNET_CLIENT_disconnect (h->client);
298   h->client = NULL;
299   if (NULL != cm->result_cont)
300     cm->result_cont (cm->cont_cls,
301                      GNUNET_ARM_REQUEST_SENT_OK,
302                      (const char *) &cm->msg[1],
303                      GNUNET_ARM_RESULT_STOPPED);
304   GNUNET_free (cm->msg);
305   GNUNET_free (cm);
306 }
307
308
309 /**
310  * Handler for ARM replies.
311  *
312  * @param cls our `struct GNUNET_ARM_Handle`
313  * @param msg the message received from the arm service
314  */
315 static void
316 client_notify_handler (void *cls,
317                        const struct GNUNET_MessageHeader *msg)
318 {
319   struct GNUNET_ARM_Handle *h = cls;
320   const struct GNUNET_ARM_Message *arm_msg;
321   const struct GNUNET_ARM_ResultMessage *res;
322   const struct GNUNET_ARM_ListResultMessage *lres;
323   struct ARMControlMessage *cm;
324   const char **list;
325   const char *pos;
326   uint64_t id;
327   enum GNUNET_ARM_Result result;
328   uint16_t size_check;
329   uint16_t rcount;
330   uint16_t msize;
331   unsigned char fail;
332
333   list = NULL;
334   rcount = 0;
335   if (NULL == msg)
336   {
337     LOG (GNUNET_ERROR_TYPE_INFO,
338          _("Client was disconnected from arm service, trying to reconnect.\n"));
339     reconnect_arm_later (h);
340     return;
341   }
342   msize = ntohs (msg->size);
343   LOG (GNUNET_ERROR_TYPE_DEBUG,
344        "Processing message of type %u and size %u from arm service\n",
345        ntohs (msg->type), msize);
346   if (msize < sizeof (struct GNUNET_ARM_Message))
347   {
348     GNUNET_break (0);
349     reconnect_arm_later (h);
350     return;
351   }
352   arm_msg = (const struct GNUNET_ARM_Message *) msg;
353   GNUNET_break (0 == ntohl (arm_msg->reserved));
354   id = GNUNET_ntohll (arm_msg->request_id);
355   cm = find_cm_by_id (h, id);
356   if (NULL == cm)
357   {
358     LOG (GNUNET_ERROR_TYPE_DEBUG,
359          "Message with unknown id %llu\n",
360          id);
361     return;
362   }
363   fail = GNUNET_NO;
364   switch (ntohs (msg->type))
365   {
366   case GNUNET_MESSAGE_TYPE_ARM_RESULT:
367     if (msize < sizeof (struct GNUNET_ARM_ResultMessage))
368     {
369       GNUNET_assert (0);
370       fail = GNUNET_YES;
371     }
372     break;
373   case GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT:
374     if (msize < sizeof (struct GNUNET_ARM_ListResultMessage))
375     {
376       GNUNET_break (0);
377       fail = GNUNET_YES;
378       break;
379     }
380     size_check = 0;
381     lres = (const struct GNUNET_ARM_ListResultMessage *) msg;
382     rcount = ntohs (lres->count);
383     {
384       unsigned int i;
385
386       list = GNUNET_malloc (sizeof (const char *) * rcount);
387       pos = (const char *)&lres[1];
388       for (i = 0; i < rcount; i++)
389       {
390         const char *end = memchr (pos, 0, msize - size_check);
391         if (NULL == end)
392         {
393           GNUNET_break (0);
394           fail = GNUNET_YES;
395           break;
396         }
397         list[i] = pos;
398         size_check += (end - pos) + 1;
399         pos = end + 1;
400       }
401       if (GNUNET_YES == fail)
402       {
403         GNUNET_free (list);
404         list = NULL;
405       }
406     }
407     break;
408   default:
409     fail = GNUNET_YES;
410     break;
411   }
412   GNUNET_assert (NULL != cm->timeout_task_id);
413   GNUNET_SCHEDULER_cancel (cm->timeout_task_id);
414   GNUNET_CONTAINER_DLL_remove (h->control_sent_head,
415                                h->control_sent_tail, cm);
416   if (GNUNET_YES == fail)
417   {
418     reconnect_arm_later (h);
419     GNUNET_free (cm->msg);
420     GNUNET_free (cm);
421     return;
422   }
423   if ( (GNUNET_MESSAGE_TYPE_ARM_RESULT == ntohs (msg->type)) &&
424        (0 == strcasecmp ((const char *) &cm->msg[1],
425                          "arm")) &&
426        (NULL != (res = (const struct GNUNET_ARM_ResultMessage *) msg)) &&
427        (GNUNET_ARM_RESULT_STOPPING == ntohl (res->result)) )
428   {
429     /* special case: if we are stopping 'gnunet-service-arm', we do not just
430        wait for the result message, but also wait for the service to close
431        the connection (and then we have to close our client handle as well);
432        this is done by installing a different receive handler, waiting for
433        the connection to go down */
434     if (NULL != h->thm)
435     {
436       GNUNET_break (0);
437       cm->result_cont (h->thm->cont_cls,
438                        GNUNET_ARM_REQUEST_SENT_OK,
439                        (const char *) &h->thm->msg[1],
440                        GNUNET_ARM_RESULT_IS_NOT_KNOWN);
441       GNUNET_free (h->thm->msg);
442       GNUNET_free (h->thm);
443     }
444     h->thm = cm;
445     GNUNET_CLIENT_receive (h->client, &arm_termination_handler, h,
446                            GNUNET_TIME_UNIT_FOREVER_REL);
447     return;
448   }
449   GNUNET_CLIENT_receive (h->client, &client_notify_handler, h,
450                          GNUNET_TIME_UNIT_FOREVER_REL);
451   switch (ntohs (msg->type))
452   {
453   case GNUNET_MESSAGE_TYPE_ARM_RESULT:
454     res = (const struct GNUNET_ARM_ResultMessage *) msg;
455     LOG (GNUNET_ERROR_TYPE_DEBUG,
456          "Received response from ARM for service `%s': %u\n",
457          (const char *) &cm->msg[1], ntohs (msg->type));
458     result = (enum GNUNET_ARM_Result) ntohl (res->result);
459     if (NULL != cm->result_cont)
460       cm->result_cont (cm->cont_cls, GNUNET_ARM_REQUEST_SENT_OK,
461                        (const char *) &cm->msg[1], result);
462     break;
463   case GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT:
464     if (NULL != cm->list_cont)
465         cm->list_cont (cm->cont_cls, GNUNET_ARM_REQUEST_SENT_OK, rcount,
466                        list);
467     GNUNET_free_non_null (list);
468     break;
469   }
470   GNUNET_free (cm->msg);
471   GNUNET_free (cm);
472 }
473
474
475 /**
476  * Transmit the next message to the arm service.
477  *
478  * @param cls closure with the `struct GNUNET_ARM_Handle`
479  * @param size number of bytes available in @a buf
480  * @param buf where the callee should write the message
481  * @return number of bytes written to @a buf
482  */
483 static size_t
484 transmit_arm_message (void *cls, size_t size, void *buf)
485 {
486   struct GNUNET_ARM_Handle *h = cls;
487   struct ARMControlMessage *cm;
488   struct GNUNET_ARM_Message *arm_msg;
489   uint64_t request_id;
490   int notify_connection;
491   uint16_t msize;
492
493   notify_connection = GNUNET_NO;
494   LOG (GNUNET_ERROR_TYPE_DEBUG,
495        "transmit_arm_message is running with %p buffer of size %lu. ARM is known to be %s\n",
496        buf, size, h->currently_down ? "unconnected" : "connected");
497   GNUNET_assert (NULL == h->reconnect_task);
498   h->cth = NULL;
499   if ((GNUNET_YES == h->currently_down) && (NULL != buf))
500   {
501     h->currently_down = GNUNET_NO;
502     notify_connection = GNUNET_YES;
503     h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
504     GNUNET_CLIENT_receive (h->client, &client_notify_handler, h,
505                            GNUNET_TIME_UNIT_FOREVER_REL);
506   }
507   if (NULL == buf)
508   {
509     LOG (GNUNET_ERROR_TYPE_DEBUG,
510          "Transmission failed, initiating reconnect\n");
511     reconnect_arm_later (h);
512     return 0;
513   }
514   if (NULL == (cm = h->control_pending_head))
515   {
516     LOG (GNUNET_ERROR_TYPE_DEBUG,
517          "Queue is empty, not sending anything\n");
518     msize = 0;
519     goto end;
520   }
521   GNUNET_assert (NULL != cm->msg);
522   msize = ntohs (cm->msg->header.size);
523   if (size < msize)
524   {
525     LOG (GNUNET_ERROR_TYPE_DEBUG,
526         "Request is too big (%u < %u), not sending it\n", size, msize);
527     trigger_next_request (h, GNUNET_NO);
528     msize = 0;
529     goto end;
530   }
531   arm_msg = cm->msg;
532   if (0 == h->request_id_counter)
533     h->request_id_counter++;
534   request_id = h->request_id_counter++;
535   LOG (GNUNET_ERROR_TYPE_DEBUG,
536        "Transmitting control message with %u bytes of type %u to arm with id %llu\n",
537        (unsigned int) msize, (unsigned int) ntohs (cm->msg->header.type), request_id);
538   arm_msg->reserved = htonl (0);
539   arm_msg->request_id = GNUNET_htonll (request_id);
540   memcpy (buf, cm->msg, msize);
541   /* Otherwise we won't be able to find it later! */
542   arm_msg->request_id = request_id;
543   GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
544                                h->control_pending_tail, cm);
545   GNUNET_CONTAINER_DLL_insert_tail (h->control_sent_head,
546                                     h->control_sent_tail, cm);
547   /* Don't free msg, keep it around (kind of wasteful, but then we don't
548    * really have many messages to handle, and it'll be freed when it times
549    * out anyway.
550    */
551   trigger_next_request (h, GNUNET_NO);
552
553  end:
554   if ((GNUNET_YES == notify_connection) && (NULL != h->conn_status))
555     h->conn_status (h->conn_status_cls, GNUNET_YES);
556   return msize;
557 }
558
559
560 /**
561  * Check the list of pending requests, send the next
562  * one to the arm.
563  *
564  * @param h arm handle
565  * @param ignore_currently_down transmit message even if not initialized?
566  */
567 static void
568 trigger_next_request (struct GNUNET_ARM_Handle *h, int ignore_currently_down)
569 {
570   uint16_t msize;
571
572   msize = sizeof (struct GNUNET_MessageHeader);
573   if ((GNUNET_YES == h->currently_down) && (ignore_currently_down == GNUNET_NO))
574   {
575     LOG (GNUNET_ERROR_TYPE_DEBUG,
576          "ARM connection down, not processing queue\n");
577     return;
578   }
579   if (NULL != h->cth)
580   {
581     LOG (GNUNET_ERROR_TYPE_DEBUG, "Request pending, not processing queue\n");
582     return;
583   }
584   if (NULL != h->control_pending_head)
585     msize =
586         ntohs (h->control_pending_head->msg->header.size);
587   else if (GNUNET_NO == ignore_currently_down)
588   {
589     LOG (GNUNET_ERROR_TYPE_DEBUG,
590          "Request queue empty, not processing queue\n");
591     return;                     /* no pending message */
592   }
593   h->cth =
594       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
595                                            GNUNET_TIME_UNIT_FOREVER_REL,
596                                            GNUNET_NO, &transmit_arm_message, h);
597 }
598
599
600 /**
601  * Connect to arm.
602  *
603  * @param h arm handle
604  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
605  */
606 static int
607 reconnect_arm (struct GNUNET_ARM_Handle *h)
608 {
609   GNUNET_assert (NULL == h->client);
610   GNUNET_assert (GNUNET_YES == h->currently_down);
611   h->client = GNUNET_CLIENT_connect ("arm", h->cfg);
612   if (NULL == h->client)
613   {
614     LOG (GNUNET_ERROR_TYPE_DEBUG,
615            "arm_api, GNUNET_CLIENT_connect returned NULL\n");
616     if (NULL != h->conn_status)
617       h->conn_status (h->conn_status_cls, GNUNET_SYSERR);
618     return GNUNET_SYSERR;
619   }
620   LOG (GNUNET_ERROR_TYPE_DEBUG,
621          "arm_api, GNUNET_CLIENT_connect returned non-NULL\n");
622   trigger_next_request (h, GNUNET_YES);
623   return GNUNET_OK;
624 }
625
626
627 /**
628  * Set up a context for communicating with ARM, then
629  * start connecting to the ARM service using that context.
630  *
631  * @param cfg configuration to use (needed to contact ARM;
632  *        the ARM service may internally use a different
633  *        configuration to determine how to start the service).
634  * @param conn_status will be called when connecting/disconnecting
635  * @param cls closure for conn_status
636  * @return context to use for further ARM operations, NULL on error.
637  */
638 struct GNUNET_ARM_Handle *
639 GNUNET_ARM_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
640                     GNUNET_ARM_ConnectionStatusCallback conn_status,
641                     void *cls)
642 {
643   struct GNUNET_ARM_Handle *h;
644
645   h = GNUNET_new (struct GNUNET_ARM_Handle);
646   h->cfg = GNUNET_CONFIGURATION_dup (cfg);
647   h->currently_down = GNUNET_YES;
648   h->reconnect_task = NULL;
649   h->conn_status = conn_status;
650   h->conn_status_cls = cls;
651   if (GNUNET_OK != reconnect_arm (h))
652   {
653     GNUNET_free (h);
654     return NULL;
655   }
656   return h;
657 }
658
659
660 /**
661  * Disconnect from the ARM service (if connected) and destroy the context.
662  *
663  * @param h the handle that was being used
664  */
665 void
666 GNUNET_ARM_disconnect_and_free (struct GNUNET_ARM_Handle *h)
667 {
668   struct ARMControlMessage *cm;
669
670   LOG (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from ARM service\n");
671   if (NULL != h->cth)
672   {
673     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
674     h->cth = NULL;
675   }
676   while ((NULL != (cm = h->control_pending_head))
677          || (NULL != (cm = h->control_sent_head)) )
678   {
679     if (NULL != h->control_pending_head)
680       GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
681                                    h->control_pending_tail, cm);
682     else
683       GNUNET_CONTAINER_DLL_remove (h->control_sent_head,
684                                    h->control_sent_tail, cm);
685     GNUNET_assert (NULL != cm->timeout_task_id);
686     GNUNET_SCHEDULER_cancel (cm->timeout_task_id);
687     if (NULL != cm->result_cont)
688       cm->result_cont (cm->cont_cls, GNUNET_ARM_REQUEST_DISCONNECTED,
689                        NULL, 0);
690     /* FIXME: What about list callback? */
691     GNUNET_free_non_null (cm->msg);
692     GNUNET_free (cm);
693   }
694   if (NULL != h->client)
695   {
696     GNUNET_CLIENT_disconnect (h->client);
697     h->client = NULL;
698   }
699   if (NULL != h->reconnect_task)
700   {
701     GNUNET_SCHEDULER_cancel (h->reconnect_task);
702     h->reconnect_task = NULL;
703   }
704   if (GNUNET_NO == h->service_test_is_active)
705   {
706     GNUNET_CONFIGURATION_destroy (h->cfg);
707     GNUNET_free (h);
708   }
709 }
710
711
712 /**
713  * Message timed out. Remove it from the queue.
714  *
715  * @param cls the message (struct ARMControlMessage *)
716  */
717 static void
718 control_message_timeout (void *cls)
719 {
720   struct ARMControlMessage *cm = cls;
721   struct GNUNET_ARM_Message *arm_msg;
722
723   LOG (GNUNET_ERROR_TYPE_DEBUG,
724        "Control message timed out\n");
725   arm_msg = cm->msg;
726   if ((NULL == arm_msg) || (0 == arm_msg->request_id))
727   {
728     GNUNET_CONTAINER_DLL_remove (cm->h->control_pending_head,
729                                  cm->h->control_pending_tail, cm);
730   }
731   else
732   {
733     GNUNET_CONTAINER_DLL_remove (cm->h->control_sent_head,
734                                  cm->h->control_sent_tail, cm);
735   }
736   if (NULL != cm->result_cont)
737     cm->result_cont (cm->cont_cls, GNUNET_ARM_REQUEST_TIMEOUT, NULL, 0);
738   else if (NULL != cm->list_cont)
739     cm->list_cont (cm->cont_cls, GNUNET_ARM_REQUEST_TIMEOUT, 0, NULL);
740   GNUNET_free_non_null (cm->msg);
741   GNUNET_free (cm);
742 }
743
744
745 /**
746  * A client specifically requested starting of ARM itself.
747  * This function is called with information about whether
748  * or not ARM is running; if it is, report success.  If
749  * it is not, start the ARM process.
750  *
751  * @param cls the context for the request that we will report on (struct ARMControlMessage *)
752  * @param result #GNUNET_YES if ARM is running
753  */
754 static void
755 arm_service_report (void *cls,
756                     int result)
757 {
758   struct ARMControlMessage *cm = cls;
759   struct GNUNET_ARM_Handle *h;
760   struct GNUNET_OS_Process *proc;
761   unsigned char test_is_active;
762   char *cbinary;
763   char *binary;
764   char *quotedbinary;
765   char *config;
766   char *loprefix;
767   char *lopostfix;
768
769   test_is_active = cm->h->service_test_is_active;
770   if ((GNUNET_YES == test_is_active) &&
771       (GNUNET_YES == result))
772   {
773     LOG (GNUNET_ERROR_TYPE_DEBUG,
774          "Looks like `%s' is already running.\n",
775          "gnunet-service-arm");
776     /* arm is running! */
777     if (cm->result_cont)
778       cm->result_cont (cm->cont_cls,
779                        GNUNET_ARM_REQUEST_SENT_OK, "arm",
780                        GNUNET_ARM_RESULT_IS_STARTED_ALREADY);
781   }
782   if (GNUNET_NO == test_is_active)
783   {
784     /* User disconnected & destroyed ARM handle in the middle of
785      * the service test, so we kept the handle around until now.
786      */
787     GNUNET_CONFIGURATION_destroy (cm->h->cfg);
788     GNUNET_free (cm->h);
789   }
790   if ((GNUNET_YES == result) ||
791       (GNUNET_NO == test_is_active))
792   {
793     GNUNET_free (cm);
794     return;
795   }
796   cm->h->service_test_is_active = GNUNET_NO;
797   LOG (GNUNET_ERROR_TYPE_DEBUG,
798        "Looks like `%s' is not running, will start it.\n",
799        "gnunet-service-arm");
800   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (
801       cm->h->cfg, "arm", "PREFIX", &loprefix))
802     loprefix = GNUNET_strdup ("");
803   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (
804       cm->h->cfg, "arm", "OPTIONS", &lopostfix))
805     lopostfix = GNUNET_strdup ("");
806   if (GNUNET_OK !=
807       GNUNET_CONFIGURATION_get_value_string (cm->h->cfg,
808                                              "arm",
809                                              "BINARY",
810                                              &cbinary))
811   {
812     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING,
813                                "arm",
814                                "BINARY");
815     if (cm->result_cont)
816       cm->result_cont (cm->cont_cls,
817                        GNUNET_ARM_REQUEST_SENT_OK, "arm",
818                        GNUNET_ARM_RESULT_IS_NOT_KNOWN);
819     GNUNET_free (cm);
820     GNUNET_free (loprefix);
821     GNUNET_free (lopostfix);
822     return;
823   }
824   if (GNUNET_OK !=
825       GNUNET_CONFIGURATION_get_value_filename (cm->h->cfg,
826                                                "arm", "CONFIG",
827                                                &config))
828     config = NULL;
829   binary = GNUNET_OS_get_libexec_binary_path (cbinary);
830   GNUNET_asprintf (&quotedbinary,
831                    "\"%s\"",
832                    binary);
833   GNUNET_free (cbinary);
834   if ( (GNUNET_YES ==
835         GNUNET_CONFIGURATION_have_value (cm->h->cfg,
836                                          "TESTING",
837                                          "WEAKRANDOM")) &&
838        (GNUNET_YES ==
839         GNUNET_CONFIGURATION_get_value_yesno (cm->h->cfg,
840                                               "TESTING",
841                                               "WEAKRANDOM")) &&
842        (GNUNET_NO ==
843         GNUNET_CONFIGURATION_have_value (cm->h->cfg,
844                                          "TESTING",
845                                          "HOSTFILE")))
846   {
847     /* Means we are ONLY running locally */
848     /* we're clearly running a test, don't daemonize */
849     if (NULL == config)
850       proc = GNUNET_OS_start_process_s (GNUNET_NO, cm->std_inheritance,
851                                         NULL, loprefix, quotedbinary,
852                                         /* no daemonization! */
853                                         lopostfix, NULL);
854     else
855       proc = GNUNET_OS_start_process_s (GNUNET_NO, cm->std_inheritance,
856                                         NULL, loprefix, quotedbinary, "-c", config,
857                                         /* no daemonization! */
858                                         lopostfix, NULL);
859   }
860   else
861   {
862     if (NULL == config)
863       proc = GNUNET_OS_start_process_s (GNUNET_NO, cm->std_inheritance,
864                                         NULL, loprefix, quotedbinary,
865                                         "-d", lopostfix, NULL);
866     else
867       proc = GNUNET_OS_start_process_s (GNUNET_NO, cm->std_inheritance,
868                                         NULL, loprefix, quotedbinary, "-c",
869                                         config,
870                                         "-d", lopostfix, NULL);
871   }
872   GNUNET_free (binary);
873   GNUNET_free (quotedbinary);
874   GNUNET_free_non_null (config);
875   GNUNET_free (loprefix);
876   GNUNET_free (lopostfix);
877   if (NULL == proc)
878   {
879     if (cm->result_cont)
880       cm->result_cont (cm->cont_cls,
881                        GNUNET_ARM_REQUEST_SENT_OK, "arm",
882                        GNUNET_ARM_RESULT_START_FAILED);
883     GNUNET_free (cm);
884     return;
885   }
886   if (cm->result_cont)
887     cm->result_cont (cm->cont_cls,
888                      GNUNET_ARM_REQUEST_SENT_OK, "arm",
889                      GNUNET_ARM_RESULT_STARTING);
890   GNUNET_OS_process_destroy (proc);
891   h = cm->h;
892   GNUNET_free (cm);
893   reconnect_arm (h);
894 }
895
896
897 /**
898  * Start or stop a service.
899  *
900  * @param h handle to ARM
901  * @param service_name name of the service
902  * @param timeout how long to wait before failing for good
903  * @param cb callback to invoke when service is ready
904  * @param cb_cls closure for callback
905  * @param type type of the request
906  */
907 static void
908 change_service (struct GNUNET_ARM_Handle *h, const char *service_name,
909                 struct GNUNET_TIME_Relative timeout, GNUNET_ARM_ResultCallback cb,
910                 void *cb_cls, uint16_t type)
911 {
912   struct ARMControlMessage *cm;
913   size_t slen;
914   struct GNUNET_ARM_Message *msg;
915
916   slen = strlen (service_name) + 1;
917   if (slen + sizeof (struct GNUNET_ARM_Message) >=
918       GNUNET_SERVER_MAX_MESSAGE_SIZE)
919   {
920     GNUNET_break (0);
921     if (cb != NULL)
922       cb (cb_cls, GNUNET_ARM_REQUEST_TOO_LONG, NULL, 0);
923     return;
924   }
925   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting %s of service `%s'.\n",
926        (GNUNET_MESSAGE_TYPE_ARM_START == type) ? "start" : "termination",
927        service_name);
928   cm = GNUNET_malloc (sizeof (struct ARMControlMessage) + slen);
929   cm->h = h;
930   cm->result_cont = cb;
931   cm->cont_cls = cb_cls;
932   cm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
933   memcpy (&cm[1], service_name, slen);
934   msg = GNUNET_malloc (sizeof (struct GNUNET_ARM_Message) + slen);
935   msg->header.size = htons (sizeof (struct GNUNET_ARM_Message) + slen);
936   msg->header.type = htons (type);
937   msg->reserved = htonl (0);
938   memcpy (&msg[1], service_name, slen);
939   cm->msg = msg;
940   LOG (GNUNET_ERROR_TYPE_DEBUG,
941       "Inserting a control message into the queue. Timeout is %s\n",
942        GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (cm->timeout),
943                                                GNUNET_NO));
944   GNUNET_CONTAINER_DLL_insert_tail (h->control_pending_head,
945                                     h->control_pending_tail, cm);
946   cm->timeout_task_id =
947       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
948                                     (cm->timeout),
949                                     &control_message_timeout, cm);
950   trigger_next_request (h, GNUNET_NO);
951 }
952
953
954 /**
955  * Request for a service to be started.
956  *
957  * @param h handle to ARM
958  * @param service_name name of the service
959  * @param std_inheritance inheritance of std streams
960  * @param timeout how long to wait before failing for good
961  * @param cont callback to invoke after request is sent or not sent
962  * @param cont_cls closure for callback
963  */
964 void
965 GNUNET_ARM_request_service_start (struct GNUNET_ARM_Handle *h,
966                                   const char *service_name,
967                                   enum GNUNET_OS_InheritStdioFlags std_inheritance,
968                                   struct GNUNET_TIME_Relative timeout,
969                                   GNUNET_ARM_ResultCallback cont,
970                                   void *cont_cls)
971 {
972   struct ARMControlMessage *cm;
973   size_t slen;
974
975   LOG (GNUNET_ERROR_TYPE_DEBUG,
976        "Asked to start service `%s' within %s\n", service_name,
977        GNUNET_STRINGS_relative_time_to_string (timeout, GNUNET_NO));
978   if (0 == strcasecmp ("arm", service_name))
979   {
980     /* Possible cases:
981      * 1) We're connected to ARM already. Invoke the callback immediately.
982      * 2) We're not connected to ARM.
983      *    Cancel any reconnection attempts temporarily, then perform
984      *    a service test.
985      */
986     if (GNUNET_NO == h->currently_down)
987     {
988       LOG (GNUNET_ERROR_TYPE_DEBUG,
989            "ARM is already running\n");
990       if (NULL != cont)
991         cont (cont_cls,
992               GNUNET_ARM_REQUEST_SENT_OK,
993               "arm",
994               GNUNET_ARM_RESULT_IS_STARTED_ALREADY);
995     }
996     else if (GNUNET_NO == h->service_test_is_active)
997     {
998       if (NULL != h->cth)
999       {
1000         GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
1001         h->cth = NULL;
1002       }
1003       if (NULL != h->client)
1004       {
1005         GNUNET_CLIENT_disconnect (h->client);
1006         h->client = NULL;
1007       }
1008       if (NULL != h->reconnect_task)
1009       {
1010         GNUNET_SCHEDULER_cancel (h->reconnect_task);
1011         h->reconnect_task = NULL;
1012       }
1013
1014       LOG (GNUNET_ERROR_TYPE_DEBUG,
1015           "Not connected to ARM, will do a service test\n");
1016
1017       slen = strlen ("arm") + 1;
1018       cm = GNUNET_malloc (sizeof (struct ARMControlMessage) + slen);
1019       cm->h = h;
1020       cm->result_cont = cont;
1021       cm->cont_cls = cont_cls;
1022       cm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1023       cm->std_inheritance = std_inheritance;
1024       memcpy (&cm[1], service_name, slen);
1025       h->service_test_is_active = GNUNET_YES;
1026       GNUNET_CLIENT_service_test ("arm",
1027                                   h->cfg,
1028                                   timeout,
1029                                   &arm_service_report,
1030                                   cm);
1031     }
1032     else
1033     {
1034       /* Service test is already running - tell user to chill out and try
1035        * again later.
1036        */
1037       LOG (GNUNET_ERROR_TYPE_DEBUG,
1038            "Service test is already in progress, we're busy\n");
1039       if (NULL != cont)
1040         cont (cont_cls, GNUNET_ARM_REQUEST_BUSY, NULL, 0);
1041     }
1042     return;
1043   }
1044   change_service (h, service_name, timeout, cont, cont_cls,
1045                   GNUNET_MESSAGE_TYPE_ARM_START);
1046 }
1047
1048
1049 /**
1050  * Request a service to be stopped.
1051  * Stopping arm itself will not invalidate its handle, and
1052  * ARM API will try to restore connection to the ARM service,
1053  * even if ARM connection was lost because you asked for ARM to be stopped.
1054  * Call #GNUNET_ARM_disconnect_and_free() to free the handle and prevent
1055  * further connection attempts.
1056  *
1057  * @param h handle to ARM
1058  * @param service_name name of the service
1059  * @param timeout how long to wait before failing for good
1060  * @param cont callback to invoke after request is sent or is not sent
1061  * @param cont_cls closure for callback
1062  */
1063 void
1064 GNUNET_ARM_request_service_stop (struct GNUNET_ARM_Handle *h,
1065                                  const char *service_name,
1066                                  struct GNUNET_TIME_Relative timeout,
1067                                  GNUNET_ARM_ResultCallback cont,
1068                                  void *cont_cls)
1069 {
1070   LOG (GNUNET_ERROR_TYPE_DEBUG,
1071        "Stopping service `%s' within %s\n",
1072        service_name,
1073        GNUNET_STRINGS_relative_time_to_string (timeout, GNUNET_NO));
1074   change_service (h, service_name, timeout, cont, cont_cls,
1075                   GNUNET_MESSAGE_TYPE_ARM_STOP);
1076 }
1077
1078
1079 /**
1080  * Request a list of running services.
1081  *
1082  * @param h handle to ARM
1083  * @param timeout how long to wait before failing for good
1084  * @param cont callback to invoke after request is sent or is not sent
1085  * @param cont_cls closure for callback
1086  */
1087 void
1088 GNUNET_ARM_request_service_list (struct GNUNET_ARM_Handle *h,
1089                                  struct GNUNET_TIME_Relative timeout,
1090                                  GNUNET_ARM_ServiceListCallback cont,
1091                                  void *cont_cls)
1092 {
1093   struct ARMControlMessage *cm;
1094   struct GNUNET_ARM_Message *msg;
1095
1096   LOG (GNUNET_ERROR_TYPE_DEBUG,
1097        "Requesting LIST from ARM service with timeout: %s\n",
1098        GNUNET_STRINGS_relative_time_to_string (timeout, GNUNET_YES));
1099   cm = GNUNET_new (struct ARMControlMessage);
1100   cm->h = h;
1101   cm->list_cont = cont;
1102   cm->cont_cls = cont_cls;
1103   cm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1104   msg = GNUNET_malloc (sizeof (struct GNUNET_ARM_Message));
1105   msg->header.size = htons (sizeof (struct GNUNET_ARM_Message));
1106   msg->header.type = htons (GNUNET_MESSAGE_TYPE_ARM_LIST);
1107   msg->reserved = htonl (0);
1108   cm->msg = msg;
1109   GNUNET_CONTAINER_DLL_insert_tail (h->control_pending_head,
1110                                     h->control_pending_tail, cm);
1111   cm->timeout_task_id =
1112       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1113                                     (cm->timeout),
1114                                     &control_message_timeout, cm);
1115   trigger_next_request (h, GNUNET_NO);
1116 }
1117
1118
1119 /* end of arm_api.c */