f2992b38aba16998e6fa81cb519c2e9027e89602
[oweals/gnunet.git] / src / arm / arm_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2012 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  */
26 #include "platform.h"
27 #include "gnunet_arm_service.h"
28 #include "gnunet_client_lib.h"
29 #include "gnunet_getopt_lib.h"
30 #include "gnunet_os_lib.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet_server_lib.h"
33 #include "arm.h"
34
35 #define LOG(kind,...) GNUNET_log_from (kind, "arm-api",__VA_ARGS__)
36
37 /**
38  * Handle for interacting with ARM.
39  */
40 struct GNUNET_ARM_Handle
41 {
42
43   /**
44    * Our connection to the ARM service.
45    */
46   struct GNUNET_CLIENT_Connection *client;
47
48   /**
49    * The configuration that we are using.
50    */
51   struct GNUNET_CONFIGURATION_Handle *cfg;
52
53 };
54
55 /**
56  * Context for handling the shutdown of a service.
57  */
58 struct ShutdownContext
59 {
60   /**
61    * Connection to the service that is being shutdown.
62    */
63   struct GNUNET_CLIENT_Connection *sock;
64
65   /**
66    * Time allowed for shutdown to happen.
67    */
68   struct GNUNET_TIME_Absolute timeout;
69
70   /**
71    * Task set up to cancel the shutdown request on timeout.
72    */
73   GNUNET_SCHEDULER_TaskIdentifier cancel_task;
74
75   /**
76    * Task to call once shutdown complete
77    */
78   GNUNET_CLIENT_ShutdownTask cont;
79
80   /**
81    * Closure for shutdown continuation
82    */
83   void *cont_cls;
84
85   /**
86    * Handle for transmission request.
87    */
88   struct GNUNET_CLIENT_TransmitHandle *th;
89
90   /**
91    * Result of the operation
92    */
93   enum GNUNET_ARM_ProcessStatus confirmed;
94
95 };
96
97
98 /**
99  * Handler receiving response to service shutdown requests.
100  * First call with NULL: service misbehaving, or something.
101  * First call with GNUNET_MESSAGE_TYPE_ARM_SHUTDOWN_ACK:
102  *   - service will shutdown
103  * Second call with NULL:
104  *   - service has now really shut down.
105  *
106  * @param cls closure
107  * @param msg NULL, indicating socket closure.
108  */
109 static void
110 service_shutdown_handler (void *cls, const struct GNUNET_MessageHeader *msg)
111 {
112   struct ShutdownContext *shutdown_ctx = cls;
113   const struct GNUNET_ARM_ResultMessage *rmsg;
114
115   if (msg == NULL)
116   {
117     if (shutdown_ctx->cont != NULL)
118     {
119       /* shutdown is now complete, as we waited for the network disconnect... */
120       shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_ARM_PROCESS_DOWN);
121     }
122     GNUNET_SCHEDULER_cancel (shutdown_ctx->cancel_task);
123     GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
124     GNUNET_free (shutdown_ctx);
125     return;
126   }
127   if (ntohs (msg->size) ==
128       sizeof (struct GNUNET_ARM_ResultMessage))
129   {
130     rmsg = (const struct GNUNET_ARM_ResultMessage*) msg;
131     shutdown_ctx->confirmed = (enum GNUNET_ARM_ProcessStatus) ntohl (rmsg->status);
132     if (shutdown_ctx->confirmed != GNUNET_ARM_PROCESS_SHUTDOWN)
133     {
134       /* ARM is not shutting down, well, report the error and be done with it... */
135       shutdown_ctx->cont (shutdown_ctx->cont_cls, shutdown_ctx->confirmed);
136       GNUNET_SCHEDULER_cancel (shutdown_ctx->cancel_task);
137       GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
138       GNUNET_free (shutdown_ctx);
139       return;
140     }
141   }
142   GNUNET_CLIENT_receive (shutdown_ctx->sock, &service_shutdown_handler,
143                          shutdown_ctx, GNUNET_TIME_UNIT_FOREVER_REL);
144 }
145
146
147 /**
148  * Shutting down took too long, cancel receive and return error.
149  *
150  * @param cls closure
151  * @param tc context information (why was this task triggered now)
152  */
153 static void
154 service_shutdown_cancel (void *cls,
155                          const struct GNUNET_SCHEDULER_TaskContext *tc)
156 {
157   struct ShutdownContext *shutdown_ctx = cls;
158
159   shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_ARM_PROCESS_COMMUNICATION_TIMEOUT);
160   GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
161   GNUNET_free (shutdown_ctx);
162 }
163
164
165 /**
166  * If possible, write a shutdown message to the target
167  * buffer and destroy the client connection.
168  *
169  * @param cls the "struct GNUNET_CLIENT_Connection" to destroy
170  * @param size number of bytes available in buf
171  * @param buf NULL on error, otherwise target buffer
172  * @return number of bytes written to buf
173  */
174 static size_t
175 write_shutdown (void *cls, size_t size, void *buf)
176 {
177   struct ShutdownContext *shutdown_ctx = cls;
178   struct GNUNET_MessageHeader *msg;
179
180   shutdown_ctx->th = NULL;
181   if (size < sizeof (struct GNUNET_MessageHeader))
182   {
183     LOG (GNUNET_ERROR_TYPE_WARNING,
184          _("Failed to transmit shutdown request to client.\n"));
185     shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_ARM_PROCESS_COMMUNICATION_ERROR);
186     GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
187     GNUNET_free (shutdown_ctx);
188     return 0;                   /* client disconnected */
189   }
190   GNUNET_CLIENT_receive (shutdown_ctx->sock, &service_shutdown_handler,
191                          shutdown_ctx, GNUNET_TIME_UNIT_FOREVER_REL);
192   shutdown_ctx->cancel_task =
193     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
194                                   (shutdown_ctx->timeout),
195                                   &service_shutdown_cancel, shutdown_ctx);
196   msg = (struct GNUNET_MessageHeader *) buf;
197   msg->type = htons (GNUNET_MESSAGE_TYPE_ARM_SHUTDOWN);
198   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
199   return sizeof (struct GNUNET_MessageHeader);
200 }
201
202
203 /**
204  * Request that the service should shutdown.
205  * Afterwards, the connection will automatically be
206  * disconnected.  Hence the "sock" should not
207  * be used by the caller after this call
208  * (calling this function frees "sock" after a while).
209  *
210  * @param sock the socket connected to the service
211  * @param timeout how long to wait before giving up on transmission
212  * @param cont continuation to call once the service is really down
213  * @param cont_cls closure for continuation
214  *
215  */
216 static void
217 arm_service_shutdown (struct GNUNET_CLIENT_Connection *sock,
218                       struct GNUNET_TIME_Relative timeout,
219                       GNUNET_CLIENT_ShutdownTask cont, void *cont_cls)
220 {
221   struct ShutdownContext *shutdown_ctx;
222
223   shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
224   shutdown_ctx->cont = cont;
225   shutdown_ctx->cont_cls = cont_cls;
226   shutdown_ctx->sock = sock;
227   shutdown_ctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
228   shutdown_ctx->confirmed = GNUNET_ARM_PROCESS_COMMUNICATION_ERROR;    
229   shutdown_ctx->th = GNUNET_CLIENT_notify_transmit_ready (sock,
230                                                           sizeof (struct GNUNET_MessageHeader),
231                                                           timeout, GNUNET_NO, &write_shutdown,
232                                                           shutdown_ctx);
233 }
234
235
236 /**
237  * Setup a context for communicating with ARM.  Note that this
238  * can be done even if the ARM service is not yet running.
239  *
240  * @param cfg configuration to use (needed to contact ARM;
241  *        the ARM service may internally use a different
242  *        configuration to determine how to start the service).
243  * @param service service that *this* process is implementing/providing, can be NULL
244  * @return context to use for further ARM operations, NULL on error
245  */
246 struct GNUNET_ARM_Handle *
247 GNUNET_ARM_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
248                     const char *service)
249 {
250   struct GNUNET_ARM_Handle *ret;
251
252   ret = GNUNET_malloc (sizeof (struct GNUNET_ARM_Handle));
253   ret->cfg = GNUNET_CONFIGURATION_dup (cfg);
254   return ret;
255 }
256
257
258 /**
259  * Disconnect from the ARM service.
260  *
261  * @param h the handle that was being used
262  */
263 void
264 GNUNET_ARM_disconnect (struct GNUNET_ARM_Handle *h)
265 {
266   if (h->client != NULL)
267     GNUNET_CLIENT_disconnect (h->client);
268   GNUNET_CONFIGURATION_destroy (h->cfg);
269   GNUNET_free (h);
270 }
271
272
273 struct ARM_ShutdownContext
274 {
275   /**
276    * Callback to call once shutdown complete.
277    */
278   GNUNET_ARM_Callback cb;
279
280   /**
281    * Closure for callback.
282    */
283   void *cb_cls;
284 };
285
286
287 /**
288  * Internal state for a request with ARM.
289  */
290 struct RequestContext
291 {
292
293   /**
294    * Pointer to our handle with ARM.
295    */
296   struct GNUNET_ARM_Handle *h;
297
298   /**
299    * Function to call with a status code for the requested operation.
300    */
301   GNUNET_ARM_Callback callback;
302
303   /**
304    * Closure for "callback".
305    */
306   void *cls;
307
308   /**
309    * Timeout for the operation.
310    */
311   struct GNUNET_TIME_Absolute timeout;
312
313   /**
314    * Type of the request expressed as a message type (start or stop).
315    */
316   uint16_t type;
317
318 };
319
320 #include "do_start_process.c"
321
322
323 /**
324  * A client specifically requested starting of ARM itself.
325  * This function is called with information about whether
326  * or not ARM is running; if it is, report success.  If
327  * it is not, start the ARM process.
328  *
329  * @param cls the context for the request that we will report on (struct RequestContext*)
330  * @param tc why were we called (reason says if ARM is running)
331  */
332 static void
333 arm_service_report (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
334 {
335   struct RequestContext *pos = cls;
336   struct GNUNET_OS_Process *proc;
337   char *binary;
338   char *config;
339   char *loprefix;
340   char *lopostfix;
341
342   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_PREREQ_DONE))
343   {
344     LOG (GNUNET_ERROR_TYPE_DEBUG, "Looks like `%s' is already running.\n",
345          "gnunet-service-arm");
346     /* arm is running! */
347     if (pos->callback != NULL)
348       pos->callback (pos->cls, GNUNET_ARM_PROCESS_ALREADY_RUNNING);
349     GNUNET_free (pos);
350     return;
351   }
352   LOG (GNUNET_ERROR_TYPE_DEBUG,
353        "Looks like `%s' is not running, will start it.\n",
354        "gnunet-service-arm");
355   if (GNUNET_OK !=
356       GNUNET_CONFIGURATION_get_value_string (pos->h->cfg, "arm", "PREFIX",
357                                              &loprefix))
358     loprefix = GNUNET_strdup ("");
359   if (GNUNET_OK !=
360       GNUNET_CONFIGURATION_get_value_string (pos->h->cfg, "arm", "OPTIONS",
361                                              &lopostfix))
362     lopostfix = GNUNET_strdup ("");
363   if (GNUNET_OK !=
364       GNUNET_CONFIGURATION_get_value_string (pos->h->cfg, "arm", "BINARY",
365                                              &binary))
366   {
367     LOG (GNUNET_ERROR_TYPE_WARNING,
368          _
369          ("Configuration failes to specify option `%s' in section `%s'!\n"),
370          "BINARY", "arm");
371     if (pos->callback != NULL)
372       pos->callback (pos->cls, GNUNET_ARM_PROCESS_UNKNOWN);
373     GNUNET_free (pos);
374     GNUNET_free (loprefix);
375     GNUNET_free (lopostfix);
376     return;
377   }
378   if (GNUNET_OK !=
379       GNUNET_CONFIGURATION_get_value_filename (pos->h->cfg, "arm", "CONFIG",
380                                                &config))
381   {
382     LOG (GNUNET_ERROR_TYPE_WARNING,
383          _("Configuration fails to specify option `%s' in section `%s'!\n"),
384          "CONFIG", "arm");
385     if (pos->callback != NULL)
386       pos->callback (pos->cls, GNUNET_ARM_PROCESS_UNKNOWN);
387     GNUNET_free (binary);
388     GNUNET_free (pos);
389     GNUNET_free (loprefix);
390     GNUNET_free (lopostfix);
391     return;
392   }
393   if ((GNUNET_YES ==
394        GNUNET_CONFIGURATION_have_value (pos->h->cfg, "TESTING", "WEAKRANDOM"))
395       && (GNUNET_YES ==
396           GNUNET_CONFIGURATION_get_value_yesno (pos->h->cfg, "TESTING",
397                                                 "WEAKRANDOM"))
398       && (GNUNET_NO ==
399           GNUNET_CONFIGURATION_have_value (pos->h->cfg, "TESTING",
400                                            "HOSTFILE")))
401   {
402     /* Means we are ONLY running locally */
403     /* we're clearly running a test, don't daemonize */
404     proc = do_start_process (GNUNET_NO,
405                              NULL, loprefix, binary, "-c", config,
406 #if DEBUG_ARM
407                              "-L", "DEBUG",
408 #endif
409                              /* no daemonization! */
410                              lopostfix, NULL);
411   }
412   else
413   {
414     proc = do_start_process (GNUNET_NO,
415                              NULL, loprefix, binary, "-c", config,
416 #if DEBUG_ARM
417                              "-L", "DEBUG",
418 #endif
419                              "-d", lopostfix, NULL);
420   }
421   GNUNET_free (binary);
422   GNUNET_free (config);
423   GNUNET_free (loprefix);
424   GNUNET_free (lopostfix);
425   if (proc == NULL)
426     {
427       if (pos->callback != NULL)
428         pos->callback (pos->cls, GNUNET_ARM_PROCESS_FAILURE);
429       GNUNET_free (pos);
430       return;
431     }
432   if (pos->callback != NULL)
433     pos->callback (pos->cls, GNUNET_ARM_PROCESS_STARTING);
434   GNUNET_free (proc);
435   GNUNET_free (pos);
436 }
437
438
439 /**
440  * Process a response from ARM to a request for a change in service
441  * status.
442  *
443  * @param cls the request context
444  * @param msg the response
445  */
446 static void
447 handle_response (void *cls, const struct GNUNET_MessageHeader *msg)
448 {
449   struct RequestContext *sc = cls;
450   const struct GNUNET_ARM_ResultMessage *res;
451   enum GNUNET_ARM_ProcessStatus status;
452
453   if ((msg == NULL) ||
454       (ntohs (msg->size) != sizeof (struct GNUNET_ARM_ResultMessage)))
455   {
456     LOG (GNUNET_ERROR_TYPE_WARNING,
457          _
458          ("Error receiving response to `%s' request from ARM for service `%s'\n"),
459          (sc->type == GNUNET_MESSAGE_TYPE_ARM_START) ? "START" : "STOP",
460          (const char *) &sc[1]);
461     GNUNET_CLIENT_disconnect (sc->h->client);
462     sc->h->client = GNUNET_CLIENT_connect ("arm", sc->h->cfg);
463     GNUNET_assert (NULL != sc->h->client);
464     if (sc->callback != NULL)
465       sc->callback (sc->cls, GNUNET_ARM_PROCESS_COMMUNICATION_ERROR);
466     GNUNET_free (sc);
467     return;
468   }
469   res = (const struct GNUNET_ARM_ResultMessage *) msg;
470   LOG (GNUNET_ERROR_TYPE_DEBUG,
471        "Received response from ARM for service `%s': %u\n",
472        (const char *) &sc[1], ntohs (msg->type));
473   status = (enum GNUNET_ARM_ProcessStatus) ntohl (res->status);
474   if (sc->callback != NULL)
475     sc->callback (sc->cls, status);
476   GNUNET_free (sc);
477 }
478
479
480 /**
481  * Start or stop a service.
482  *
483  * @param h handle to ARM
484  * @param service_name name of the service
485  * @param timeout how long to wait before failing for good
486  * @param cb callback to invoke when service is ready
487  * @param cb_cls closure for callback
488  * @param type type of the request
489  */
490 static void
491 change_service (struct GNUNET_ARM_Handle *h, const char *service_name,
492                 struct GNUNET_TIME_Relative timeout, GNUNET_ARM_Callback cb,
493                 void *cb_cls, uint16_t type)
494 {
495   struct RequestContext *sctx;
496   size_t slen;
497   struct GNUNET_MessageHeader *msg;
498
499   slen = strlen (service_name) + 1;
500   if (slen + sizeof (struct GNUNET_MessageHeader) >=
501       GNUNET_SERVER_MAX_MESSAGE_SIZE)
502   {
503     GNUNET_break (0);
504     if (cb != NULL)
505       cb (cb_cls, GNUNET_NO);
506     return;
507   }
508   LOG (GNUNET_ERROR_TYPE_DEBUG,
509        (type ==
510         GNUNET_MESSAGE_TYPE_ARM_START) ?
511        _("Requesting start of service `%s'.\n") :
512        _("Requesting termination of service `%s'.\n"), service_name);
513   sctx = GNUNET_malloc (sizeof (struct RequestContext) + slen);
514   sctx->h = h;
515   sctx->callback = cb;
516   sctx->cls = cb_cls;
517   sctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
518   sctx->type = type;
519   memcpy (&sctx[1], service_name, slen);
520   msg = GNUNET_malloc (sizeof (struct GNUNET_MessageHeader) + slen);
521   msg->size = htons (sizeof (struct GNUNET_MessageHeader) + slen);
522   msg->type = htons (sctx->type);
523   memcpy (&msg[1], service_name, slen);
524   if (GNUNET_OK !=
525       GNUNET_CLIENT_transmit_and_get_response (sctx->h->client, msg,
526                                                GNUNET_TIME_absolute_get_remaining
527                                                (sctx->timeout), GNUNET_YES,
528                                                &handle_response, sctx))
529   {
530     LOG (GNUNET_ERROR_TYPE_WARNING,
531          (type ==
532           GNUNET_MESSAGE_TYPE_ARM_START)
533          ? _("Error while trying to transmit request to start `%s' to ARM\n")    
534          : _("Error while trying to transmit request to stop `%s' to ARM\n"),
535          (const char *) &service_name);
536     if (cb != NULL)
537       cb (cb_cls, GNUNET_SYSERR);
538     GNUNET_free (sctx);
539     GNUNET_free (msg);
540     return;
541   }
542   GNUNET_free (msg);
543 }
544
545
546 /**
547  * Start a service.
548  *
549  * @param h handle to ARM
550  * @param service_name name of the service
551  * @param timeout how long to wait before failing for good
552  * @param cb callback to invoke when service is ready
553  * @param cb_cls closure for callback
554  */
555 void
556 GNUNET_ARM_start_service (struct GNUNET_ARM_Handle *h,
557                           const char *service_name,
558                           struct GNUNET_TIME_Relative timeout,
559                           GNUNET_ARM_Callback cb, void *cb_cls)
560 {
561   struct RequestContext *sctx;
562   struct GNUNET_CLIENT_Connection *client;
563   size_t slen;
564
565   LOG (GNUNET_ERROR_TYPE_DEBUG,
566        _("Asked to start service `%s' within %llu ms\n"), service_name,
567        (unsigned long long) timeout.rel_value);
568   if (0 == strcasecmp ("arm", service_name))
569   {
570     slen = strlen ("arm") + 1;
571     sctx = GNUNET_malloc (sizeof (struct RequestContext) + slen);
572     sctx->h = h;
573     sctx->callback = cb;
574     sctx->cls = cb_cls;
575     sctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
576     memcpy (&sctx[1], service_name, slen);
577     GNUNET_CLIENT_service_test ("arm", h->cfg, timeout, &arm_service_report,
578                                 sctx);
579     return;
580   }
581   if (h->client == NULL)
582   {
583     client = GNUNET_CLIENT_connect ("arm", h->cfg);
584     if (client == NULL)
585     {
586       LOG (GNUNET_ERROR_TYPE_DEBUG,
587            "arm_api, GNUNET_CLIENT_connect returned NULL\n");
588       cb (cb_cls, GNUNET_ARM_PROCESS_COMMUNICATION_ERROR);
589       return;
590     }
591     LOG (GNUNET_ERROR_TYPE_DEBUG,
592          "arm_api, GNUNET_CLIENT_connect returned non-NULL\n");
593     h->client = client;
594   }
595   LOG (GNUNET_ERROR_TYPE_DEBUG, "arm_api, h->client non-NULL\n");
596   change_service (h, service_name, timeout, cb, cb_cls,
597                   GNUNET_MESSAGE_TYPE_ARM_START);
598 }
599
600
601 /**
602  * Callback from the arm stop service call, indicates that the arm service
603  * is well and truly dead, won't die, or an error occurred.
604  *
605  * @param cls closure for the callback
606  * @param reason reason for callback
607  */
608 static void
609 arm_shutdown_callback (void *cls, enum GNUNET_ARM_ProcessStatus reason)
610 {
611   struct ARM_ShutdownContext *arm_shutdown_ctx = cls;
612
613   if (arm_shutdown_ctx->cb != NULL)
614     arm_shutdown_ctx->cb (arm_shutdown_ctx->cb_cls, reason);
615
616   GNUNET_free (arm_shutdown_ctx);
617 }
618
619
620 /**
621  * Stop a service.
622  *
623  * @param h handle to ARM
624  * @param service_name name of the service
625  * @param timeout how long to wait before failing for good
626  * @param cb callback to invoke when service is ready
627  * @param cb_cls closure for callback
628  */
629 void
630 GNUNET_ARM_stop_service (struct GNUNET_ARM_Handle *h,
631                          const char *service_name,
632                          struct GNUNET_TIME_Relative timeout,
633                          GNUNET_ARM_Callback cb, void *cb_cls)
634 {
635   struct ARM_ShutdownContext *arm_shutdown_ctx;
636   struct GNUNET_CLIENT_Connection *client;
637
638   LOG (GNUNET_ERROR_TYPE_INFO, _("Stopping service `%s' within %llu ms\n"),
639        service_name, (unsigned long long) timeout.rel_value);
640   if (h->client == NULL)
641   {
642     client = GNUNET_CLIENT_connect ("arm", h->cfg);
643     if (client == NULL)
644     {
645       cb (cb_cls, GNUNET_SYSERR);
646       return;
647     }
648     h->client = client;
649   }
650   if (0 == strcasecmp ("arm", service_name))
651   {
652     arm_shutdown_ctx = GNUNET_malloc (sizeof (struct ARM_ShutdownContext));
653     arm_shutdown_ctx->cb = cb;
654     arm_shutdown_ctx->cb_cls = cb_cls;
655     arm_service_shutdown (h->client, timeout, &arm_shutdown_callback,
656                           arm_shutdown_ctx);
657     h->client = NULL;
658     return;
659   }
660   change_service (h, service_name, timeout, cb, cb_cls,
661                   GNUNET_MESSAGE_TYPE_ARM_STOP);
662 }
663
664
665 /**
666  * Internal state for a list request with ARM.
667  */
668 struct ListRequestContext
669 {
670
671   /**
672    * Pointer to our handle with ARM.
673    */
674   struct GNUNET_ARM_Handle *h;
675
676   /**
677    * Function to call with a status code for the requested operation.
678    */
679   GNUNET_ARM_List_Callback callback;
680
681   /**
682    * Closure for "callback".
683    */
684   void *cls;
685
686   /**
687    * Timeout for the operation.
688    */
689   struct GNUNET_TIME_Absolute timeout;
690 };
691
692
693 /**
694  * Process a response from ARM for the list request.
695  *
696  * @param cls the list request context
697  * @param msg the response
698  */
699 static void
700 handle_list_response (void *cls, const struct GNUNET_MessageHeader *msg)
701 {
702   struct ListRequestContext *sc = cls;
703   const struct GNUNET_ARM_ListResultMessage *res;
704   const char *pos;
705   uint16_t size_check;
706   uint16_t rcount;
707   uint16_t msize;
708   
709   if (NULL == msg)
710   {
711     LOG (GNUNET_ERROR_TYPE_WARNING,
712          "Error receiving response to LIST request from ARM\n");
713     GNUNET_CLIENT_disconnect (sc->h->client);
714     sc->h->client = GNUNET_CLIENT_connect ("arm", sc->h->cfg);
715     GNUNET_assert (NULL != sc->h->client);
716     if (sc->callback != NULL)
717       sc->callback (sc->cls, GNUNET_ARM_PROCESS_COMMUNICATION_ERROR, 0, NULL);
718     GNUNET_free (sc);
719     return;
720   }
721    
722   if (NULL == sc->callback) 
723   {
724     GNUNET_break (0);
725     GNUNET_free (sc);
726     return;
727   }  
728   msize = ntohs (msg->size);
729   if ( (msize < sizeof ( struct GNUNET_ARM_ListResultMessage)) ||
730        (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT) )
731   {
732     GNUNET_break (0);
733     sc->callback (sc->cls, GNUNET_NO, 0, NULL);
734     GNUNET_free (sc);
735     return;
736   }
737   size_check = 0;
738   res = (const struct GNUNET_ARM_ListResultMessage *) msg;
739   rcount = ntohs (res->count);
740   {
741     const char *list[rcount];
742     unsigned int i;
743     
744     pos = (const char *)&res[1];   
745     for (i=0; i<rcount; i++)
746     {
747       const char *end = memchr (pos, 0, msize - size_check);
748       if (NULL == end)
749       {
750         GNUNET_break (0);
751         sc->callback (sc->cls, GNUNET_NO, 0, NULL);
752         GNUNET_free (sc);
753         return;
754       }
755       list[i] = pos;
756       size_check += (end - pos) + 1;
757       pos = end + 1;
758     }
759     sc->callback (sc->cls, GNUNET_YES, rcount, list);
760   }
761   GNUNET_free (sc);
762 }
763
764
765 /**
766  * List all running services.
767  * 
768  * @param h handle to ARM
769  * @param timeout how long to wait before failing for good
770  * @param cb callback to invoke when service is ready
771  * @param cb_cls closure for callback
772  */
773 void
774 GNUNET_ARM_list_running_services (struct GNUNET_ARM_Handle *h,
775                                   struct GNUNET_TIME_Relative timeout,
776                                   GNUNET_ARM_List_Callback cb, void *cb_cls)
777 {
778   struct ListRequestContext *sctx;
779   struct GNUNET_MessageHeader msg;
780   struct GNUNET_CLIENT_Connection *client;
781   
782   if (h->client == NULL)
783   {
784     client = GNUNET_CLIENT_connect ("arm", h->cfg);
785     if (client == NULL)
786     {
787       LOG (GNUNET_ERROR_TYPE_DEBUG,
788            "arm_api, GNUNET_CLIENT_connect returned NULL\n");
789       cb (cb_cls, GNUNET_ARM_PROCESS_COMMUNICATION_ERROR, 0, NULL);
790       return;
791     }
792     LOG (GNUNET_ERROR_TYPE_DEBUG,
793          "arm_api, GNUNET_CLIENT_connect returned non-NULL\n");
794     h->client = client;
795   }
796   
797   sctx = GNUNET_malloc (sizeof (struct RequestContext));
798   sctx->h = h;
799   sctx->callback = cb;
800   sctx->cls = cb_cls;
801   sctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
802   msg.size = htons (sizeof (struct GNUNET_MessageHeader));
803   msg.type = htons (GNUNET_MESSAGE_TYPE_ARM_LIST);
804   
805   LOG (GNUNET_ERROR_TYPE_DEBUG, 
806        "Requesting LIST from ARM service with timeout: %llu ms\n", 
807        (unsigned long long)timeout.rel_value);
808   
809   if (GNUNET_OK !=
810       GNUNET_CLIENT_transmit_and_get_response (sctx->h->client, 
811                                                &msg,
812                                                GNUNET_TIME_absolute_get_remaining
813                                                (sctx->timeout), 
814                                                GNUNET_YES,
815                                                &handle_list_response, 
816                                                sctx))
817   {
818     LOG (GNUNET_ERROR_TYPE_WARNING, 
819          "Error while trying to transmit request to list services to ARM\n");
820     if (cb != NULL)
821       cb (cb_cls, GNUNET_SYSERR, 0, NULL);
822     GNUNET_free (sctx);
823     return;
824   }
825 }
826
827 /* end of arm_api.c */