2da392fb4b2a325e6f92bcc43b81237653ea018b
[oweals/gnunet.git] / src / util / client.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2006, 2008, 2009 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 2, 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 util/client.c
23  * @brief code for access to services
24  * @author Christian Grothoff
25  *
26  * Generic TCP code for reliable, record-oriented TCP
27  * connections between clients and service providers.
28  */
29
30 #include "platform.h"
31 #include "gnunet_common.h"
32 #include "gnunet_client_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_server_lib.h"
35 #include "gnunet_scheduler_lib.h"
36
37 #define DEBUG_CLIENT GNUNET_NO
38
39 /**
40  * Struct to refer to a GNUnet TCP connection.
41  * This is more than just a socket because if the server
42  * drops the connection, the client automatically tries
43  * to reconnect (and for that needs connection information).
44  */
45 struct GNUNET_CLIENT_Connection
46 {
47
48   /**
49    * the socket handle, NULL if not live
50    */
51   struct GNUNET_CONNECTION_Handle *sock;
52
53   /**
54    * Our scheduler.
55    */
56   struct GNUNET_SCHEDULER_Handle *sched;
57
58   /**
59    * Name of the service we interact with.
60    */
61   char *service_name;
62
63   /**
64    * ID of task used for receiving.
65    */
66   GNUNET_SCHEDULER_TaskIdentifier receiver_task;
67
68   /**
69    * Handler for current receiver task.
70    */
71   GNUNET_CLIENT_MessageHandler receiver_handler;
72
73   /**
74    * Closure for receiver_handler.
75    */
76   void *receiver_handler_cls;
77
78   /**
79    * Handler for service test completion (NULL unless in service_test)
80    */
81   GNUNET_SCHEDULER_Task test_cb;
82
83   /**
84    * Closure for test_cb (NULL unless in service_test)
85    */
86   void *test_cb_cls;
87
88   /**
89    * Buffer for received message.
90    */
91   char *received_buf;
92
93   /**
94    * Timeout for receiving a response (absolute time).
95    */
96   struct GNUNET_TIME_Absolute receive_timeout;
97
98   /**
99    * Number of bytes in received_buf that are valid.
100    */
101   size_t received_pos;
102
103   /**
104    * Size of received_buf.
105    */
106   unsigned int received_size;
107
108   /**
109    * Do we have a complete response in received_buf?
110    */
111   int msg_complete;
112
113 };
114
115
116 /**
117  * Get a connection with a service.
118  *
119  * @param sched scheduler to use
120  * @param service_name name of the service
121  * @param cfg configuration to use
122  * @return NULL on error (service unknown to configuration)
123  */
124 struct GNUNET_CLIENT_Connection *
125 GNUNET_CLIENT_connect (struct GNUNET_SCHEDULER_Handle *sched,
126                        const char *service_name,
127                        const struct GNUNET_CONFIGURATION_Handle *cfg)
128 {
129   struct GNUNET_CLIENT_Connection *ret;
130   struct GNUNET_CONNECTION_Handle *sock;
131   char *hostname;
132   unsigned long long port;
133
134   if ((GNUNET_OK !=
135        GNUNET_CONFIGURATION_get_value_number (cfg,
136                                               service_name,
137                                               "PORT",
138                                               &port)) ||
139       (port > 65535) ||
140       (GNUNET_OK !=
141        GNUNET_CONFIGURATION_get_value_string (cfg,
142                                               service_name,
143                                               "HOSTNAME", &hostname)))
144     {
145       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
146                   _("Could not determine valid hostname and port for service `%s' from configuration.\n"),
147                   service_name);
148       return NULL;
149     }
150   if (0 == strlen (hostname))
151     {
152       GNUNET_free (hostname);
153       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
154                   _("Need a non-empty hostname for service `%s'.\n"),
155                   service_name);
156       return NULL;
157     }
158   sock = GNUNET_CONNECTION_create_from_connect (sched,
159                                                 hostname,
160                                                 port,
161                                                 GNUNET_SERVER_MAX_MESSAGE_SIZE);
162   GNUNET_free (hostname);
163   if (sock == NULL)
164     return NULL;
165   ret = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_Connection));
166   ret->sock = sock;
167   ret->sched = sched;
168   ret->service_name = GNUNET_strdup (service_name);
169   return ret;
170 }
171
172
173 /**
174  * Receiver task has completed, free rest of client
175  * data structures.
176  */
177 static void
178 finish_cleanup (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
179 {
180   struct GNUNET_CLIENT_Connection *sock = cls;
181
182   GNUNET_array_grow (sock->received_buf, sock->received_size, 0);
183   GNUNET_free (sock->service_name);
184   GNUNET_free (sock);
185 }
186
187
188 /**
189  * Destroy connection with the service.
190  */
191 void
192 GNUNET_CLIENT_disconnect (struct GNUNET_CLIENT_Connection *sock)
193 {
194   GNUNET_assert (sock->sock != NULL);
195   GNUNET_CONNECTION_destroy (sock->sock);
196   sock->sock = NULL;
197   sock->receiver_handler = NULL;
198   GNUNET_SCHEDULER_add_after (sock->sched,
199                               GNUNET_YES,
200                               GNUNET_SCHEDULER_PRIORITY_KEEP,
201                               sock->receiver_task, &finish_cleanup, sock);
202 }
203
204
205 /**
206  * check if message is complete
207  */
208 static void
209 check_complete (struct GNUNET_CLIENT_Connection *conn)
210 {
211   if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
212       (conn->received_pos >=
213        ntohs (((const struct GNUNET_MessageHeader *) conn->
214                received_buf)->size)))
215     conn->msg_complete = GNUNET_YES;
216 }
217
218
219 /**
220  * Callback function for data received from the network.  Note that
221  * both "available" and "errCode" would be 0 if the read simply timed out.
222  *
223  * @param cls closure
224  * @param buf pointer to received data
225  * @param available number of bytes availabe in "buf",
226  *        possibly 0 (on errors)
227  * @param addr address of the sender
228  * @param addrlen size of addr
229  * @param errCode value of errno (on errors receiving)
230  */
231 static void
232 receive_helper (void *cls,
233                 const void *buf,
234                 size_t available,
235                 const struct sockaddr *addr, socklen_t addrlen, int errCode)
236 {
237   struct GNUNET_CLIENT_Connection *conn = cls;
238   struct GNUNET_TIME_Relative remaining;
239
240   GNUNET_assert (conn->msg_complete == GNUNET_NO);
241   conn->receiver_task = GNUNET_SCHEDULER_NO_TASK;
242
243   if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
244     {
245       /* signal timeout! */
246       if (conn->receiver_handler != NULL)
247         {
248           conn->receiver_handler (conn->receiver_handler_cls, NULL);
249           conn->receiver_handler = NULL;
250         }
251       return;
252     }
253
254   /* FIXME: optimize for common fast case where buf contains the
255      entire message and we need no copying... */
256
257
258   /* slow path: append to array */
259   if (conn->received_size < conn->received_pos + available)
260     GNUNET_array_grow (conn->received_buf,
261                        conn->received_size, conn->received_pos + available);
262   memcpy (&conn->received_buf[conn->received_pos], buf, available);
263   conn->received_pos += available;
264   check_complete (conn);
265   /* check for timeout */
266   remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
267   if (remaining.value == 0)
268     {
269       /* signal timeout! */
270       conn->receiver_handler (conn->receiver_handler_cls, NULL);
271       return;
272     }
273   /* back to receive -- either for more data or to call callback! */
274   GNUNET_CLIENT_receive (conn,
275                          conn->receiver_handler,
276                          conn->receiver_handler_cls, remaining);
277 }
278
279
280 /**
281  * Continuation to call the receive callback.
282  */
283 static void
284 receive_task (void *scls, const struct GNUNET_SCHEDULER_TaskContext *tc)
285 {
286   struct GNUNET_CLIENT_Connection *sock = scls;
287   GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
288   const struct GNUNET_MessageHeader *cmsg = (const struct GNUNET_MessageHeader *) sock->received_buf;
289   void *cls = sock->receiver_handler_cls;
290   uint16_t msize = ntohs (cmsg->size);
291   char mbuf[msize];
292   struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader*) mbuf;
293
294   GNUNET_assert (GNUNET_YES == sock->msg_complete);
295   sock->receiver_task = GNUNET_SCHEDULER_NO_TASK;
296   GNUNET_assert (sock->received_pos >= msize);
297   memcpy (msg, cmsg, msize);
298   memmove (sock->received_buf,
299            &sock->received_buf[msize], sock->received_pos - msize);
300   sock->received_pos -= msize;
301   sock->msg_complete = GNUNET_NO;
302   sock->receiver_handler = NULL;  
303   check_complete (sock);
304   if (handler != NULL)
305     handler (cls, msg);
306 }
307
308
309 /**
310  * Read from the service.
311  *
312  * @param sock the service
313  * @param handler function to call with the message
314  * @param handler_cls closure for handler
315  * @param timeout how long to wait until timing out
316  */
317 void
318 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
319                        GNUNET_CLIENT_MessageHandler handler,
320                        void *handler_cls, struct GNUNET_TIME_Relative timeout)
321 {
322   if (sock->sock == NULL)
323     {
324       /* already disconnected, fail instantly! */
325       GNUNET_break (0);         /* this should not happen in well-written code! */
326       handler (handler_cls, NULL);
327       return;
328     }
329   GNUNET_assert (sock->receiver_task ==
330                  GNUNET_SCHEDULER_NO_TASK);
331   sock->receiver_handler = handler;
332   sock->receiver_handler_cls = handler_cls;
333   sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
334   if (GNUNET_YES == sock->msg_complete)
335     sock->receiver_task = GNUNET_SCHEDULER_add_after (sock->sched,
336                                                       GNUNET_YES,
337                                                       GNUNET_SCHEDULER_PRIORITY_KEEP,
338                                                       GNUNET_SCHEDULER_NO_TASK,
339                                                       &receive_task, sock);
340   else
341     sock->receiver_task = GNUNET_CONNECTION_receive (sock->sock,
342                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE,
343                                                      timeout,
344                                                      &receive_helper, sock);
345 }
346
347
348 static size_t
349 write_shutdown (void *cls, size_t size, void *buf)
350 {
351   struct GNUNET_MessageHeader *msg;
352
353   if (size < sizeof (struct GNUNET_MessageHeader))
354     return 0;                   /* client disconnected */
355   msg = (struct GNUNET_MessageHeader *) buf;
356   msg->type = htons (GNUNET_MESSAGE_TYPE_SHUTDOWN);
357   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
358   return sizeof (struct GNUNET_MessageHeader);
359 }
360
361
362 /**
363  * Request that the service should shutdown.
364  * Afterwards, the connection should be disconnected.
365  *
366  * @param sock the socket connected to the service
367  */
368 void
369 GNUNET_CLIENT_service_shutdown (struct GNUNET_CLIENT_Connection *sock)
370 {
371   GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
372                                         sizeof (struct GNUNET_MessageHeader),
373                                         GNUNET_TIME_UNIT_FOREVER_REL,
374                                         &write_shutdown, NULL);
375 }
376
377
378 /**
379  * Report service unavailable.
380  */
381 static void
382 service_test_error (struct GNUNET_SCHEDULER_Handle *s,
383                     GNUNET_SCHEDULER_Task task, void *task_cls)
384 {
385   GNUNET_SCHEDULER_add_continuation (s,
386                                      GNUNET_YES,
387                                      task,
388                                      task_cls,
389                                      GNUNET_SCHEDULER_REASON_TIMEOUT);
390 }
391
392
393 /**
394  * Receive confirmation from test, service is up.
395  *
396  * @param cls closure
397  * @param msg message received, NULL on timeout or fatal error
398  */
399 static void
400 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
401 {
402   struct GNUNET_CLIENT_Connection *conn = cls;
403   /* We may want to consider looking at the reply in more
404      detail in the future, for example, is this the
405      correct service? FIXME! */
406   if (msg != NULL)
407     {
408 #if DEBUG_CLIENT
409       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
410                   "Received confirmation that service is running.\n");
411 #endif
412       GNUNET_SCHEDULER_add_continuation (conn->sched,
413                                          GNUNET_YES,
414                                          conn->test_cb,
415                                          conn->test_cb_cls,
416                                          GNUNET_SCHEDULER_REASON_PREREQ_DONE);
417     }
418   else
419     {
420       service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
421     }
422   GNUNET_CLIENT_disconnect (conn);
423 }
424
425
426 static size_t
427 write_test (void *cls, size_t size, void *buf)
428 {
429   struct GNUNET_MessageHeader *msg;
430
431   if (size < sizeof (struct GNUNET_MessageHeader))
432     {
433 #if DEBUG_CLIENT
434       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
435                   _("Failure to transmit TEST request.\n"));
436 #endif
437       return 0;                 /* client disconnected */
438     }
439 #if DEBUG_CLIENT
440   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Transmitting TEST request.\n"));
441 #endif
442   msg = (struct GNUNET_MessageHeader *) buf;
443   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
444   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
445   return sizeof (struct GNUNET_MessageHeader);
446 }
447
448
449 /**
450  * Wait until the service is running.
451  *
452  * @param sched scheduler to use
453  * @param service name of the service to wait for
454  * @param cfg configuration to use
455  * @param timeout how long to wait at most in ms
456  * @param task task to run if service is running
457  *        (reason will be "PREREQ_DONE" (service running)
458  *         or "TIMEOUT" (service not known to be running))
459  * @param task_cls closure for task
460  */
461 void
462 GNUNET_CLIENT_service_test (struct GNUNET_SCHEDULER_Handle *sched,
463                             const char *service,
464                             const struct GNUNET_CONFIGURATION_Handle *cfg,
465                             struct GNUNET_TIME_Relative timeout,
466                             GNUNET_SCHEDULER_Task task, void *task_cls)
467 {
468   struct GNUNET_CLIENT_Connection *conn;
469
470 #if DEBUG_CLIENT
471   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
472               "Testing if service `%s' is running.\n", service);
473 #endif
474   conn = GNUNET_CLIENT_connect (sched, service, cfg);
475   if (conn == NULL)
476     {
477       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
478                   _
479                   ("Could not connect to service `%s', must not be running.\n"),
480                   service);
481       service_test_error (sched, task, task_cls);
482       return;
483     }
484   conn->test_cb = task;
485   conn->test_cb_cls = task_cls;
486   if (NULL ==
487       GNUNET_CONNECTION_notify_transmit_ready (conn->sock,
488                                             sizeof (struct
489                                                     GNUNET_MessageHeader),
490                                             timeout, &write_test, NULL))
491     {
492       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
493                   _("Failure to transmit request to service `%s'\n"),
494                   service);
495       service_test_error (sched, task, task_cls);
496       GNUNET_CLIENT_disconnect (conn);
497       return;
498     }
499   GNUNET_CLIENT_receive (conn, &confirm_handler, conn, timeout);
500 }
501
502
503 /**
504  * Ask the client to call us once the specified number of bytes
505  * are free in the transmission buffer.  May call the notify
506  * method immediately if enough space is available.
507  *
508  * @param sock connection to the service
509  * @param size number of bytes to send
510  * @param timeout after how long should we give up (and call
511  *        notify with buf NULL and size 0)?
512  * @param notify function to call
513  * @param notify_cls closure for notify
514  * @return NULL if our buffer will never hold size bytes,
515  *         a handle if the notify callback was queued (can be used to cancel)
516  */
517 struct GNUNET_CONNECTION_TransmitHandle *
518 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
519                                      size_t size,
520                                      struct GNUNET_TIME_Relative timeout,
521                                      GNUNET_CONNECTION_TransmitReadyNotify
522                                      notify, void *notify_cls)
523 {
524   return GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
525                                                size,
526                                                timeout, notify, notify_cls);
527 }
528
529
530 /**
531  * Context for processing 
532  * "GNUNET_CLIENT_transmit_and_get_response" requests.
533  */
534 struct TARCtx
535 {
536   /**
537    * Client handle.
538    */
539   struct GNUNET_CLIENT_Connection *sock;
540
541   /**
542    * Message to transmit; do not free, allocated
543    * right after this struct.
544    */
545   const struct GNUNET_MessageHeader *hdr;
546
547   /**
548    * Timeout to use.
549    */
550   struct GNUNET_TIME_Absolute timeout;
551
552   /**
553    * Function to call when done.
554    */
555   GNUNET_CLIENT_MessageHandler rn;
556
557   /**
558    * Closure for "rn".
559    */
560   void *rn_cls;
561 };
562
563
564 /**
565  * Function called to notify a client about the socket
566  * begin ready to queue the message.  "buf" will be
567  * NULL and "size" zero if the socket was closed for
568  * writing in the meantime.
569  *
570  * @param cls closure of type "struct TARCtx*"
571  * @param size number of bytes available in buf
572  * @param buf where the callee should write the message
573  * @return number of bytes written to buf
574  */
575 static size_t
576 transmit_for_response (void *cls,
577                        size_t size, 
578                        void *buf)
579 {
580   struct TARCtx *tc = cls;
581   uint16_t msize;
582
583   msize = ntohs(tc->hdr->size);
584   if (NULL == buf)
585     {
586       tc->rn (tc->rn_cls, NULL);
587       GNUNET_free (tc);
588       return 0;
589     }
590   GNUNET_assert (size >= msize);
591   memcpy (buf, tc->hdr, msize);
592   GNUNET_CLIENT_receive (tc->sock,
593                          tc->rn,
594                          tc->rn_cls,
595                          GNUNET_TIME_absolute_get_remaining (tc->timeout));
596   GNUNET_free (tc);
597   return msize;
598 }
599
600
601 /**
602  * Convenience API that combines sending a request
603  * to the service and waiting for a response.
604  * If either operation times out, the callback
605  * will be called with a "NULL" response (in which
606  * case the connection should probably be destroyed).
607  *
608  * @param sock connection to use
609  * @param hdr message to transmit
610  * @param timeout when to give up (for both transmission
611  *         and for waiting for a response)
612  * @param rn function to call with the response
613  * @param rn_cls closure for rn 
614  */
615 void
616 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection *sock,
617                                          const struct GNUNET_MessageHeader *hdr,
618                                          struct GNUNET_TIME_Relative timeout,
619                                          GNUNET_CLIENT_MessageHandler rn,
620                                          void *rn_cls)
621 {
622   struct TARCtx *tc;
623   uint16_t msize;
624
625   msize = ntohs(hdr->size);
626   tc = GNUNET_malloc(sizeof (struct TARCtx) + msize);
627   tc->sock = sock;
628   tc->hdr = (const struct GNUNET_MessageHeader*) &tc[1]; 
629   memcpy (&tc[1], hdr, msize);
630   tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
631   tc->rn = rn;
632   tc->rn_cls = rn_cls;
633   GNUNET_CLIENT_notify_transmit_ready (sock,
634                                        msize,
635                                        timeout,
636                                        &transmit_for_response,
637                                        tc);
638 }
639
640
641
642 /*  end of client.c */