small API change: do no longer pass rarely needed GNUNET_SCHEDULER_TaskContext to...
[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, &reconnect_arm_task, h);
245   /* Don't clear pending messages on disconnection, deliver them later
246   clear_pending_messages (h, GNUNET_ARM_REQUEST_DISCONNECTED);
247   GNUNET_assert (NULL == h->control_pending_head);
248   */
249   h->retry_backoff = GNUNET_TIME_STD_BACKOFF (h->retry_backoff);
250   if (NULL != h->conn_status)
251     h->conn_status (h->conn_status_cls, GNUNET_NO);
252 }
253
254
255 /**
256  * Find a control message by its unique ID.
257  *
258  * @param h ARM handle
259  * @param id unique message ID to use for the lookup
260  * @return NULL if not found
261  */
262 static struct ARMControlMessage *
263 find_cm_by_id (struct GNUNET_ARM_Handle *h, uint64_t id)
264 {
265   struct ARMControlMessage *result;
266   for (result = h->control_sent_head; result; result = result->next)
267     if (id == result->msg->request_id)
268       return result;
269   return NULL;
270 }
271
272
273 /**
274  * Handler for ARM 'termination' reply (failure to receive).
275  *
276  * @param cls our "struct GNUNET_ARM_Handle"
277  * @param msg expected to be NULL
278  */
279 static void
280 arm_termination_handler (void *cls, const struct GNUNET_MessageHeader *msg)
281 {
282   struct GNUNET_ARM_Handle *h = cls;
283   struct ARMControlMessage *cm;
284
285   if (NULL != msg)
286   {
287     GNUNET_break (0);
288     GNUNET_CLIENT_receive (h->client, &arm_termination_handler, h,
289                            GNUNET_TIME_UNIT_FOREVER_REL);
290     return;
291   }
292   cm = h->thm;
293   h->thm = NULL;
294   h->currently_down = GNUNET_YES;
295   GNUNET_CLIENT_disconnect (h->client);
296   h->client = NULL;
297   if (NULL != cm->result_cont)
298     cm->result_cont (cm->cont_cls,
299                      GNUNET_ARM_REQUEST_SENT_OK,
300                      (const char *) &cm->msg[1],
301                      GNUNET_ARM_RESULT_STOPPED);
302   GNUNET_free (cm->msg);
303   GNUNET_free (cm);
304 }
305
306
307 /**
308  * Handler for ARM replies.
309  *
310  * @param cls our `struct GNUNET_ARM_Handle`
311  * @param msg the message received from the arm service
312  */
313 static void
314 client_notify_handler (void *cls,
315                        const struct GNUNET_MessageHeader *msg)
316 {
317   struct GNUNET_ARM_Handle *h = cls;
318   const struct GNUNET_ARM_Message *arm_msg;
319   const struct GNUNET_ARM_ResultMessage *res;
320   const struct GNUNET_ARM_ListResultMessage *lres;
321   struct ARMControlMessage *cm;
322   const char **list;
323   const char *pos;
324   uint64_t id;
325   enum GNUNET_ARM_Result result;
326   uint16_t size_check;
327   uint16_t rcount;
328   uint16_t msize;
329   unsigned char fail;
330
331   list = NULL;
332   rcount = 0;
333   if (NULL == msg)
334   {
335     LOG (GNUNET_ERROR_TYPE_INFO,
336          _("Client was disconnected from arm service, trying to reconnect.\n"));
337     reconnect_arm_later (h);
338     return;
339   }
340   msize = ntohs (msg->size);
341   LOG (GNUNET_ERROR_TYPE_DEBUG,
342        "Processing message of type %u and size %u from arm service\n",
343        ntohs (msg->type), msize);
344   if (msize < sizeof (struct GNUNET_ARM_Message))
345   {
346     GNUNET_break (0);
347     reconnect_arm_later (h);
348     return;
349   }
350   arm_msg = (const struct GNUNET_ARM_Message *) msg;
351   GNUNET_break (0 == ntohl (arm_msg->reserved));
352   id = GNUNET_ntohll (arm_msg->request_id);
353   cm = find_cm_by_id (h, id);
354   if (NULL == cm)
355   {
356     LOG (GNUNET_ERROR_TYPE_DEBUG,
357          "Message with unknown id %llu\n",
358          id);
359     return;
360   }
361   fail = GNUNET_NO;
362   switch (ntohs (msg->type))
363   {
364   case GNUNET_MESSAGE_TYPE_ARM_RESULT:
365     if (msize < sizeof (struct GNUNET_ARM_ResultMessage))
366     {
367       GNUNET_assert (0);
368       fail = GNUNET_YES;
369     }
370     break;
371   case GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT:
372     if (msize < sizeof (struct GNUNET_ARM_ListResultMessage))
373     {
374       GNUNET_break (0);
375       fail = GNUNET_YES;
376       break;
377     }
378     size_check = 0;
379     lres = (const struct GNUNET_ARM_ListResultMessage *) msg;
380     rcount = ntohs (lres->count);
381     {
382       unsigned int i;
383
384       list = GNUNET_malloc (sizeof (const char *) * rcount);
385       pos = (const char *)&lres[1];
386       for (i = 0; i < rcount; i++)
387       {
388         const char *end = memchr (pos, 0, msize - size_check);
389         if (NULL == end)
390         {
391           GNUNET_break (0);
392           fail = GNUNET_YES;
393           break;
394         }
395         list[i] = pos;
396         size_check += (end - pos) + 1;
397         pos = end + 1;
398       }
399       if (GNUNET_YES == fail)
400       {
401         GNUNET_free (list);
402         list = NULL;
403       }
404     }
405     break;
406   default:
407     fail = GNUNET_YES;
408     break;
409   }
410   GNUNET_assert (NULL != cm->timeout_task_id);
411   GNUNET_SCHEDULER_cancel (cm->timeout_task_id);
412   GNUNET_CONTAINER_DLL_remove (h->control_sent_head,
413                                h->control_sent_tail, cm);
414   if (GNUNET_YES == fail)
415   {
416     reconnect_arm_later (h);
417     GNUNET_free (cm->msg);
418     GNUNET_free (cm);
419     return;
420   }
421   if ( (GNUNET_MESSAGE_TYPE_ARM_RESULT == ntohs (msg->type)) &&
422        (0 == strcasecmp ((const char *) &cm->msg[1],
423                          "arm")) &&
424        (NULL != (res = (const struct GNUNET_ARM_ResultMessage *) msg)) &&
425        (GNUNET_ARM_RESULT_STOPPING == ntohl (res->result)) )
426   {
427     /* special case: if we are stopping 'gnunet-service-arm', we do not just
428        wait for the result message, but also wait for the service to close
429        the connection (and then we have to close our client handle as well);
430        this is done by installing a different receive handler, waiting for
431        the connection to go down */
432     if (NULL != h->thm)
433     {
434       GNUNET_break (0);
435       cm->result_cont (h->thm->cont_cls,
436                        GNUNET_ARM_REQUEST_SENT_OK,
437                        (const char *) &h->thm->msg[1],
438                        GNUNET_ARM_RESULT_IS_NOT_KNOWN);
439       GNUNET_free (h->thm->msg);
440       GNUNET_free (h->thm);
441     }
442     h->thm = cm;
443     GNUNET_CLIENT_receive (h->client, &arm_termination_handler, h,
444                            GNUNET_TIME_UNIT_FOREVER_REL);
445     return;
446   }
447   GNUNET_CLIENT_receive (h->client, &client_notify_handler, h,
448                          GNUNET_TIME_UNIT_FOREVER_REL);
449   switch (ntohs (msg->type))
450   {
451   case GNUNET_MESSAGE_TYPE_ARM_RESULT:
452     res = (const struct GNUNET_ARM_ResultMessage *) msg;
453     LOG (GNUNET_ERROR_TYPE_DEBUG,
454          "Received response from ARM for service `%s': %u\n",
455          (const char *) &cm->msg[1], ntohs (msg->type));
456     result = (enum GNUNET_ARM_Result) ntohl (res->result);
457     if (NULL != cm->result_cont)
458       cm->result_cont (cm->cont_cls, GNUNET_ARM_REQUEST_SENT_OK,
459                        (const char *) &cm->msg[1], result);
460     break;
461   case GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT:
462     if (NULL != cm->list_cont)
463         cm->list_cont (cm->cont_cls, GNUNET_ARM_REQUEST_SENT_OK, rcount,
464                        list);
465     GNUNET_free_non_null (list);
466     break;
467   }
468   GNUNET_free (cm->msg);
469   GNUNET_free (cm);
470 }
471
472
473 /**
474  * Transmit the next message to the arm service.
475  *
476  * @param cls closure with the `struct GNUNET_ARM_Handle`
477  * @param size number of bytes available in @a buf
478  * @param buf where the callee should write the message
479  * @return number of bytes written to @a buf
480  */
481 static size_t
482 transmit_arm_message (void *cls, size_t size, void *buf)
483 {
484   struct GNUNET_ARM_Handle *h = cls;
485   struct ARMControlMessage *cm;
486   struct GNUNET_ARM_Message *arm_msg;
487   uint64_t request_id;
488   int notify_connection;
489   uint16_t msize;
490
491   notify_connection = GNUNET_NO;
492   LOG (GNUNET_ERROR_TYPE_DEBUG,
493        "transmit_arm_message is running with %p buffer of size %lu. ARM is known to be %s\n",
494        buf, size, h->currently_down ? "unconnected" : "connected");
495   GNUNET_assert (NULL == h->reconnect_task);
496   h->cth = NULL;
497   if ((GNUNET_YES == h->currently_down) && (NULL != buf))
498   {
499     h->currently_down = GNUNET_NO;
500     notify_connection = GNUNET_YES;
501     h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
502     GNUNET_CLIENT_receive (h->client, &client_notify_handler, h,
503                            GNUNET_TIME_UNIT_FOREVER_REL);
504   }
505   if (NULL == buf)
506   {
507     LOG (GNUNET_ERROR_TYPE_DEBUG,
508          "Transmission failed, initiating reconnect\n");
509     reconnect_arm_later (h);
510     return 0;
511   }
512   if (NULL == (cm = h->control_pending_head))
513   {
514     LOG (GNUNET_ERROR_TYPE_DEBUG,
515          "Queue is empty, not sending anything\n");
516     msize = 0;
517     goto end;
518   }
519   GNUNET_assert (NULL != cm->msg);
520   msize = ntohs (cm->msg->header.size);
521   if (size < msize)
522   {
523     LOG (GNUNET_ERROR_TYPE_DEBUG,
524         "Request is too big (%u < %u), not sending it\n", size, msize);
525     trigger_next_request (h, GNUNET_NO);
526     msize = 0;
527     goto end;
528   }
529   arm_msg = cm->msg;
530   if (0 == h->request_id_counter)
531     h->request_id_counter++;
532   request_id = h->request_id_counter++;
533   LOG (GNUNET_ERROR_TYPE_DEBUG,
534        "Transmitting control message with %u bytes of type %u to arm with id %llu\n",
535        (unsigned int) msize, (unsigned int) ntohs (cm->msg->header.type), request_id);
536   arm_msg->reserved = htonl (0);
537   arm_msg->request_id = GNUNET_htonll (request_id);
538   memcpy (buf, cm->msg, msize);
539   /* Otherwise we won't be able to find it later! */
540   arm_msg->request_id = request_id;
541   GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
542                                h->control_pending_tail, cm);
543   GNUNET_CONTAINER_DLL_insert_tail (h->control_sent_head,
544                                     h->control_sent_tail, cm);
545   /* Don't free msg, keep it around (kind of wasteful, but then we don't
546    * really have many messages to handle, and it'll be freed when it times
547    * out anyway.
548    */
549   trigger_next_request (h, GNUNET_NO);
550
551  end:
552   if ((GNUNET_YES == notify_connection) && (NULL != h->conn_status))
553     h->conn_status (h->conn_status_cls, GNUNET_YES);
554   return msize;
555 }
556
557
558 /**
559  * Check the list of pending requests, send the next
560  * one to the arm.
561  *
562  * @param h arm handle
563  * @param ignore_currently_down transmit message even if not initialized?
564  */
565 static void
566 trigger_next_request (struct GNUNET_ARM_Handle *h, int ignore_currently_down)
567 {
568   uint16_t msize;
569
570   msize = sizeof (struct GNUNET_MessageHeader);
571   if ((GNUNET_YES == h->currently_down) && (ignore_currently_down == GNUNET_NO))
572   {
573     LOG (GNUNET_ERROR_TYPE_DEBUG,
574          "ARM connection down, not processing queue\n");
575     return;
576   }
577   if (NULL != h->cth)
578   {
579     LOG (GNUNET_ERROR_TYPE_DEBUG, "Request pending, not processing queue\n");
580     return;
581   }
582   if (NULL != h->control_pending_head)
583     msize =
584         ntohs (h->control_pending_head->msg->header.size);
585   else if (GNUNET_NO == ignore_currently_down)
586   {
587     LOG (GNUNET_ERROR_TYPE_DEBUG,
588          "Request queue empty, not processing queue\n");
589     return;                     /* no pending message */
590   }
591   h->cth =
592       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
593                                            GNUNET_TIME_UNIT_FOREVER_REL,
594                                            GNUNET_NO, &transmit_arm_message, h);
595 }
596
597
598 /**
599  * Connect to arm.
600  *
601  * @param h arm handle
602  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
603  */
604 static int
605 reconnect_arm (struct GNUNET_ARM_Handle *h)
606 {
607   GNUNET_assert (NULL == h->client);
608   GNUNET_assert (GNUNET_YES == h->currently_down);
609   h->client = GNUNET_CLIENT_connect ("arm", h->cfg);
610   if (NULL == h->client)
611   {
612     LOG (GNUNET_ERROR_TYPE_DEBUG,
613            "arm_api, GNUNET_CLIENT_connect returned NULL\n");
614     if (NULL != h->conn_status)
615       h->conn_status (h->conn_status_cls, GNUNET_SYSERR);
616     return GNUNET_SYSERR;
617   }
618   LOG (GNUNET_ERROR_TYPE_DEBUG,
619          "arm_api, GNUNET_CLIENT_connect returned non-NULL\n");
620   trigger_next_request (h, GNUNET_YES);
621   return GNUNET_OK;
622 }
623
624
625 /**
626  * Set up a context for communicating with ARM, then
627  * start connecting to the ARM service using that context.
628  *
629  * @param cfg configuration to use (needed to contact ARM;
630  *        the ARM service may internally use a different
631  *        configuration to determine how to start the service).
632  * @param conn_status will be called when connecting/disconnecting
633  * @param cls closure for conn_status
634  * @return context to use for further ARM operations, NULL on error.
635  */
636 struct GNUNET_ARM_Handle *
637 GNUNET_ARM_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
638                     GNUNET_ARM_ConnectionStatusCallback conn_status, void *cls)
639 {
640   struct GNUNET_ARM_Handle *h;
641
642   h = GNUNET_new (struct GNUNET_ARM_Handle);
643   h->cfg = GNUNET_CONFIGURATION_dup (cfg);
644   h->currently_down = GNUNET_YES;
645   h->reconnect_task = NULL;
646   h->conn_status = conn_status;
647   h->conn_status_cls = cls;
648   if (GNUNET_OK != reconnect_arm (h))
649   {
650     GNUNET_free (h);
651     return NULL;
652   }
653   return h;
654 }
655
656
657 /**
658  * Disconnect from the ARM service (if connected) and destroy the context.
659  *
660  * @param h the handle that was being used
661  */
662 void
663 GNUNET_ARM_disconnect_and_free (struct GNUNET_ARM_Handle *h)
664 {
665   struct ARMControlMessage *cm;
666
667   LOG (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from ARM service\n");
668   if (NULL != h->cth)
669   {
670     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
671     h->cth = NULL;
672   }
673   while ((NULL != (cm = h->control_pending_head))
674          || (NULL != (cm = h->control_sent_head)) )
675   {
676     if (NULL != h->control_pending_head)
677       GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
678                                    h->control_pending_tail, cm);
679     else
680       GNUNET_CONTAINER_DLL_remove (h->control_sent_head,
681                                    h->control_sent_tail, cm);
682     GNUNET_assert (NULL != cm->timeout_task_id);
683     GNUNET_SCHEDULER_cancel (cm->timeout_task_id);
684     if (NULL != cm->result_cont)
685       cm->result_cont (cm->cont_cls, GNUNET_ARM_REQUEST_DISCONNECTED,
686                        NULL, 0);
687     /* FIXME: What about list callback? */
688     GNUNET_free_non_null (cm->msg);
689     GNUNET_free (cm);
690   }
691   if (NULL != h->client)
692   {
693     GNUNET_CLIENT_disconnect (h->client);
694     h->client = NULL;
695   }
696   if (NULL != h->reconnect_task)
697   {
698     GNUNET_SCHEDULER_cancel (h->reconnect_task);
699     h->reconnect_task = NULL;
700   }
701   if (GNUNET_NO == h->service_test_is_active)
702   {
703     GNUNET_CONFIGURATION_destroy (h->cfg);
704     GNUNET_free (h);
705   }
706 }
707
708
709 /**
710  * Message timed out. Remove it from the queue.
711  *
712  * @param cls the message (struct ARMControlMessage *)
713  */
714 static void
715 control_message_timeout (void *cls)
716 {
717   struct ARMControlMessage *cm = cls;
718   struct GNUNET_ARM_Message *arm_msg;
719
720   LOG (GNUNET_ERROR_TYPE_DEBUG,
721        "Control message timed out\n");
722   arm_msg = cm->msg;
723   if ((NULL == arm_msg) || (0 == arm_msg->request_id))
724   {
725     GNUNET_CONTAINER_DLL_remove (cm->h->control_pending_head,
726                                  cm->h->control_pending_tail, cm);
727   }
728   else
729   {
730     GNUNET_CONTAINER_DLL_remove (cm->h->control_sent_head,
731                                  cm->h->control_sent_tail, cm);
732   }
733   if (NULL != cm->result_cont)
734     cm->result_cont (cm->cont_cls, GNUNET_ARM_REQUEST_TIMEOUT, NULL, 0);
735   else if (NULL != cm->list_cont)
736     cm->list_cont (cm->cont_cls, GNUNET_ARM_REQUEST_TIMEOUT, 0, NULL);
737   GNUNET_free_non_null (cm->msg);
738   GNUNET_free (cm);
739 }
740
741
742 /**
743  * A client specifically requested starting of ARM itself.
744  * This function is called with information about whether
745  * or not ARM is running; if it is, report success.  If
746  * it is not, start the ARM process.
747  *
748  * @param cls the context for the request that we will report on (struct ARMControlMessage *)
749  * @param result #GNUNET_YES if ARM is running
750  */
751 static void
752 arm_service_report (void *cls,
753                     int result)
754 {
755   struct ARMControlMessage *cm = cls;
756   struct GNUNET_ARM_Handle *h;
757   struct GNUNET_OS_Process *proc;
758   unsigned char test_is_active;
759   char *cbinary;
760   char *binary;
761   char *quotedbinary;
762   char *config;
763   char *loprefix;
764   char *lopostfix;
765
766   test_is_active = cm->h->service_test_is_active;
767   if ((GNUNET_YES == test_is_active) &&
768       (GNUNET_YES == result))
769   {
770     LOG (GNUNET_ERROR_TYPE_DEBUG,
771          "Looks like `%s' is already running.\n",
772          "gnunet-service-arm");
773     /* arm is running! */
774     if (cm->result_cont)
775       cm->result_cont (cm->cont_cls,
776                        GNUNET_ARM_REQUEST_SENT_OK, "arm",
777                        GNUNET_ARM_RESULT_IS_STARTED_ALREADY);
778   }
779   if (GNUNET_NO == test_is_active)
780   {
781     /* User disconnected & destroyed ARM handle in the middle of
782      * the service test, so we kept the handle around until now.
783      */
784     GNUNET_CONFIGURATION_destroy (cm->h->cfg);
785     GNUNET_free (cm->h);
786   }
787   if ((GNUNET_YES == result) ||
788       (GNUNET_NO == test_is_active))
789   {
790     GNUNET_free (cm);
791     return;
792   }
793   cm->h->service_test_is_active = GNUNET_NO;
794   LOG (GNUNET_ERROR_TYPE_DEBUG,
795        "Looks like `%s' is not running, will start it.\n",
796        "gnunet-service-arm");
797   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (
798       cm->h->cfg, "arm", "PREFIX", &loprefix))
799     loprefix = GNUNET_strdup ("");
800   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (
801       cm->h->cfg, "arm", "OPTIONS", &lopostfix))
802     lopostfix = GNUNET_strdup ("");
803   if (GNUNET_OK !=
804       GNUNET_CONFIGURATION_get_value_string (cm->h->cfg,
805                                              "arm",
806                                              "BINARY",
807                                              &cbinary))
808   {
809     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING,
810                                "arm",
811                                "BINARY");
812     if (cm->result_cont)
813       cm->result_cont (cm->cont_cls,
814                        GNUNET_ARM_REQUEST_SENT_OK, "arm",
815                        GNUNET_ARM_RESULT_IS_NOT_KNOWN);
816     GNUNET_free (cm);
817     GNUNET_free (loprefix);
818     GNUNET_free (lopostfix);
819     return;
820   }
821   if (GNUNET_OK !=
822       GNUNET_CONFIGURATION_get_value_filename (cm->h->cfg,
823                                                "arm", "CONFIG",
824                                                &config))
825     config = NULL;
826   binary = GNUNET_OS_get_libexec_binary_path (cbinary);
827   GNUNET_asprintf (&quotedbinary,
828                    "\"%s\"",
829                    binary);
830   GNUNET_free (cbinary);
831   if ( (GNUNET_YES ==
832         GNUNET_CONFIGURATION_have_value (cm->h->cfg,
833                                          "TESTING",
834                                          "WEAKRANDOM")) &&
835        (GNUNET_YES ==
836         GNUNET_CONFIGURATION_get_value_yesno (cm->h->cfg,
837                                               "TESTING",
838                                               "WEAKRANDOM")) &&
839        (GNUNET_NO ==
840         GNUNET_CONFIGURATION_have_value (cm->h->cfg,
841                                          "TESTING",
842                                          "HOSTFILE")))
843   {
844     /* Means we are ONLY running locally */
845     /* we're clearly running a test, don't daemonize */
846     if (NULL == config)
847       proc = GNUNET_OS_start_process_s (GNUNET_NO, cm->std_inheritance,
848                                         NULL, loprefix, quotedbinary,
849                                         /* no daemonization! */
850                                         lopostfix, NULL);
851     else
852       proc = GNUNET_OS_start_process_s (GNUNET_NO, cm->std_inheritance,
853                                         NULL, loprefix, quotedbinary, "-c", config,
854                                         /* no daemonization! */
855                                         lopostfix, NULL);
856   }
857   else
858   {
859     if (NULL == config)
860       proc = GNUNET_OS_start_process_s (GNUNET_NO, cm->std_inheritance,
861                                         NULL, loprefix, quotedbinary,
862                                         "-d", lopostfix, NULL);
863     else
864       proc = GNUNET_OS_start_process_s (GNUNET_NO, cm->std_inheritance,
865                                         NULL, loprefix, quotedbinary, "-c",
866                                         config,
867                                         "-d", lopostfix, NULL);
868   }
869   GNUNET_free (binary);
870   GNUNET_free (quotedbinary);
871   GNUNET_free_non_null (config);
872   GNUNET_free (loprefix);
873   GNUNET_free (lopostfix);
874   if (NULL == proc)
875   {
876     if (cm->result_cont)
877       cm->result_cont (cm->cont_cls,
878                        GNUNET_ARM_REQUEST_SENT_OK, "arm",
879                        GNUNET_ARM_RESULT_START_FAILED);
880     GNUNET_free (cm);
881     return;
882   }
883   if (cm->result_cont)
884     cm->result_cont (cm->cont_cls,
885                      GNUNET_ARM_REQUEST_SENT_OK, "arm",
886                      GNUNET_ARM_RESULT_STARTING);
887   GNUNET_OS_process_destroy (proc);
888   h = cm->h;
889   GNUNET_free (cm);
890   reconnect_arm (h);
891 }
892
893
894 /**
895  * Start or stop a service.
896  *
897  * @param h handle to ARM
898  * @param service_name name of the service
899  * @param timeout how long to wait before failing for good
900  * @param cb callback to invoke when service is ready
901  * @param cb_cls closure for callback
902  * @param type type of the request
903  */
904 static void
905 change_service (struct GNUNET_ARM_Handle *h, const char *service_name,
906                 struct GNUNET_TIME_Relative timeout, GNUNET_ARM_ResultCallback cb,
907                 void *cb_cls, uint16_t type)
908 {
909   struct ARMControlMessage *cm;
910   size_t slen;
911   struct GNUNET_ARM_Message *msg;
912
913   slen = strlen (service_name) + 1;
914   if (slen + sizeof (struct GNUNET_ARM_Message) >=
915       GNUNET_SERVER_MAX_MESSAGE_SIZE)
916   {
917     GNUNET_break (0);
918     if (cb != NULL)
919       cb (cb_cls, GNUNET_ARM_REQUEST_TOO_LONG, NULL, 0);
920     return;
921   }
922   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting %s of service `%s'.\n",
923        (GNUNET_MESSAGE_TYPE_ARM_START == type) ? "start" : "termination",
924        service_name);
925   cm = GNUNET_malloc (sizeof (struct ARMControlMessage) + slen);
926   cm->h = h;
927   cm->result_cont = cb;
928   cm->cont_cls = cb_cls;
929   cm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
930   memcpy (&cm[1], service_name, slen);
931   msg = GNUNET_malloc (sizeof (struct GNUNET_ARM_Message) + slen);
932   msg->header.size = htons (sizeof (struct GNUNET_ARM_Message) + slen);
933   msg->header.type = htons (type);
934   msg->reserved = htonl (0);
935   memcpy (&msg[1], service_name, slen);
936   cm->msg = msg;
937   LOG (GNUNET_ERROR_TYPE_DEBUG,
938       "Inserting a control message into the queue. Timeout is %s\n",
939        GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (cm->timeout),
940                                                GNUNET_NO));
941   GNUNET_CONTAINER_DLL_insert_tail (h->control_pending_head,
942                                     h->control_pending_tail, cm);
943   cm->timeout_task_id =
944       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
945                                     (cm->timeout), &control_message_timeout, cm);
946   trigger_next_request (h, GNUNET_NO);
947 }
948
949
950 /**
951  * Request for a service to be started.
952  *
953  * @param h handle to ARM
954  * @param service_name name of the service
955  * @param std_inheritance inheritance of std streams
956  * @param timeout how long to wait before failing for good
957  * @param cont callback to invoke after request is sent or not sent
958  * @param cont_cls closure for callback
959  */
960 void
961 GNUNET_ARM_request_service_start (struct GNUNET_ARM_Handle *h,
962                                   const char *service_name,
963                                   enum GNUNET_OS_InheritStdioFlags std_inheritance,
964                                   struct GNUNET_TIME_Relative timeout,
965                                   GNUNET_ARM_ResultCallback cont,
966                                   void *cont_cls)
967 {
968   struct ARMControlMessage *cm;
969   size_t slen;
970
971   LOG (GNUNET_ERROR_TYPE_DEBUG,
972        "Asked to start service `%s' within %s\n", service_name,
973        GNUNET_STRINGS_relative_time_to_string (timeout, GNUNET_NO));
974   if (0 == strcasecmp ("arm", service_name))
975   {
976     /* Possible cases:
977      * 1) We're connected to ARM already. Invoke the callback immediately.
978      * 2) We're not connected to ARM.
979      *    Cancel any reconnection attempts temporarily, then perform
980      *    a service test.
981      */
982     if (GNUNET_NO == h->currently_down)
983     {
984       LOG (GNUNET_ERROR_TYPE_DEBUG,
985            "ARM is already running\n");
986       if (NULL != cont)
987         cont (cont_cls,
988               GNUNET_ARM_REQUEST_SENT_OK,
989               "arm",
990               GNUNET_ARM_RESULT_IS_STARTED_ALREADY);
991     }
992     else if (GNUNET_NO == h->service_test_is_active)
993     {
994       if (NULL != h->cth)
995       {
996         GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
997         h->cth = NULL;
998       }
999       if (NULL != h->client)
1000       {
1001         GNUNET_CLIENT_disconnect (h->client);
1002         h->client = NULL;
1003       }
1004       if (NULL != h->reconnect_task)
1005       {
1006         GNUNET_SCHEDULER_cancel (h->reconnect_task);
1007         h->reconnect_task = NULL;
1008       }
1009
1010       LOG (GNUNET_ERROR_TYPE_DEBUG,
1011           "Not connected to ARM, will do a service test\n");
1012
1013       slen = strlen ("arm") + 1;
1014       cm = GNUNET_malloc (sizeof (struct ARMControlMessage) + slen);
1015       cm->h = h;
1016       cm->result_cont = cont;
1017       cm->cont_cls = cont_cls;
1018       cm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1019       cm->std_inheritance = std_inheritance;
1020       memcpy (&cm[1], service_name, slen);
1021       h->service_test_is_active = GNUNET_YES;
1022       GNUNET_CLIENT_service_test ("arm",
1023                                   h->cfg,
1024                                   timeout,
1025                                   &arm_service_report,
1026                                   cm);
1027     }
1028     else
1029     {
1030       /* Service test is already running - tell user to chill out and try
1031        * again later.
1032        */
1033       LOG (GNUNET_ERROR_TYPE_DEBUG,
1034            "Service test is already in progress, we're busy\n");
1035       if (NULL != cont)
1036         cont (cont_cls, GNUNET_ARM_REQUEST_BUSY, NULL, 0);
1037     }
1038     return;
1039   }
1040   change_service (h, service_name, timeout, cont, cont_cls,
1041                   GNUNET_MESSAGE_TYPE_ARM_START);
1042 }
1043
1044
1045 /**
1046  * Request a service to be stopped.
1047  * Stopping arm itself will not invalidate its handle, and
1048  * ARM API will try to restore connection to the ARM service,
1049  * even if ARM connection was lost because you asked for ARM to be stopped.
1050  * Call #GNUNET_ARM_disconnect_and_free() to free the handle and prevent
1051  * further connection attempts.
1052  *
1053  * @param h handle to ARM
1054  * @param service_name name of the service
1055  * @param timeout how long to wait before failing for good
1056  * @param cont callback to invoke after request is sent or is not sent
1057  * @param cont_cls closure for callback
1058  */
1059 void
1060 GNUNET_ARM_request_service_stop (struct GNUNET_ARM_Handle *h,
1061                                  const char *service_name,
1062                                  struct GNUNET_TIME_Relative timeout,
1063                                  GNUNET_ARM_ResultCallback cont,
1064                                  void *cont_cls)
1065 {
1066   LOG (GNUNET_ERROR_TYPE_DEBUG,
1067        "Stopping service `%s' within %s\n",
1068        service_name,
1069        GNUNET_STRINGS_relative_time_to_string (timeout, GNUNET_NO));
1070   change_service (h, service_name, timeout, cont, cont_cls,
1071                   GNUNET_MESSAGE_TYPE_ARM_STOP);
1072 }
1073
1074
1075 /**
1076  * Request a list of running services.
1077  *
1078  * @param h handle to ARM
1079  * @param timeout how long to wait before failing for good
1080  * @param cont callback to invoke after request is sent or is not sent
1081  * @param cont_cls closure for callback
1082  */
1083 void
1084 GNUNET_ARM_request_service_list (struct GNUNET_ARM_Handle *h,
1085                                  struct GNUNET_TIME_Relative timeout,
1086                                  GNUNET_ARM_ServiceListCallback cont,
1087                                  void *cont_cls)
1088 {
1089   struct ARMControlMessage *cm;
1090   struct GNUNET_ARM_Message *msg;
1091
1092   LOG (GNUNET_ERROR_TYPE_DEBUG,
1093        "Requesting LIST from ARM service with timeout: %s\n",
1094        GNUNET_STRINGS_relative_time_to_string (timeout, GNUNET_YES));
1095   cm = GNUNET_new (struct ARMControlMessage);
1096   cm->h = h;
1097   cm->list_cont = cont;
1098   cm->cont_cls = cont_cls;
1099   cm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1100   msg = GNUNET_malloc (sizeof (struct GNUNET_ARM_Message));
1101   msg->header.size = htons (sizeof (struct GNUNET_ARM_Message));
1102   msg->header.type = htons (GNUNET_MESSAGE_TYPE_ARM_LIST);
1103   msg->reserved = htonl (0);
1104   cm->msg = msg;
1105   GNUNET_CONTAINER_DLL_insert_tail (h->control_pending_head,
1106                                     h->control_pending_tail, cm);
1107   cm->timeout_task_id =
1108       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1109                                     (cm->timeout), &control_message_timeout, cm);
1110   trigger_next_request (h, GNUNET_NO);
1111 }
1112
1113
1114 /* end of arm_api.c */