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