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