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