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