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