-fix uint16/uint32 confusion
[oweals/gnunet.git] / src / gns / gns_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009-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  * @file gns/gns_api.c
22  * @brief library to access the GNS service
23  * @author Martin Schanzenbach
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_arm_service.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet_dht_service.h"
33 #include "gns.h"
34 #include "gnunet_gns_service.h"
35
36
37 #define LOG(kind,...) GNUNET_log_from (kind, "gns-api",__VA_ARGS__)
38
39 /**
40  * Handle to a lookup request
41  */
42 struct GNUNET_GNS_LookupRequest
43 {
44
45   /**
46    * DLL
47    */
48   struct GNUNET_GNS_LookupRequest *next;
49   
50   /**
51    * DLL
52    */
53   struct GNUNET_GNS_LookupRequest *prev;
54   
55   /**
56    * handle to gns 
57    */
58   struct GNUNET_GNS_Handle *gns_handle;
59   
60   /**
61    * processor to call on lookup result 
62    */
63   GNUNET_GNS_LookupResultProcessor lookup_proc;
64
65   /**
66    * processor closure 
67    */
68   void *proc_cls;
69  
70   /**
71    * request id 
72    */
73   uint32_t r_id;
74  
75 };
76
77
78 /**
79  * Entry in our list of messages to be (re-)transmitted.
80  */
81 struct PendingMessage
82 {
83   /**
84    * This is a doubly-linked list.
85    */
86   struct PendingMessage *prev;
87
88   /**
89    * This is a doubly-linked list.
90    */
91   struct PendingMessage *next;
92
93   /**
94    * Size of the message.
95    */
96   size_t size;
97
98   /**
99    * request id
100    */
101   uint32_t r_id;
102
103   /**
104    * This message has been transmitted.  GNUNET_NO if the message is
105    * in the "pending" DLL, GNUNET_YES if it has been transmitted to
106    * the service via the current client connection.
107    */
108   int transmitted;
109
110 };
111
112
113 /**
114  * Connection to the GNS service.
115  */
116 struct GNUNET_GNS_Handle
117 {
118
119   /**
120    * Configuration to use.
121    */
122   const struct GNUNET_CONFIGURATION_Handle *cfg;
123
124   /**
125    * Socket (if available).
126    */
127   struct GNUNET_CLIENT_Connection *client;
128
129   /**
130    * Currently pending transmission request (or NULL).
131    */
132   struct GNUNET_CLIENT_TransmitHandle *th;
133   
134   /**
135    * Head of linked list of shorten messages we would like to transmit.
136    */
137   struct PendingMessage *pending_head;
138
139   /**
140    * Tail of linked list of shorten messages we would like to transmit.
141    */
142   struct PendingMessage *pending_tail;
143   
144   /**
145    * Head of linked list of lookup messages we would like to transmit.
146    */
147   struct GNUNET_GNS_LookupRequest *lookup_head;
148
149   /**
150    * Tail of linked list of lookup messages we would like to transmit.
151    */
152   struct GNUNET_GNS_LookupRequest *lookup_tail;
153
154   /**
155    * Reconnect task
156    */
157   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
158   
159   /**
160    * How long do we wait until we try to reconnect?
161    */
162   struct GNUNET_TIME_Relative reconnect_backoff;
163
164   /**
165    * Request Id generator.  Incremented by one for each request.
166    */
167   uint32_t r_id_gen;
168   
169   /**
170    * Did we start our receive loop yet?
171    */
172   int in_receive;
173
174 };
175
176
177 /**
178  * Try to send messages from list of messages to send
179  * @param handle GNS_Handle
180  */
181 static void
182 process_pending_messages (struct GNUNET_GNS_Handle *handle);
183
184
185 /**
186  * Reconnect to GNS service.
187  *
188  * @param handle the handle to the GNS service
189  */
190 static void
191 reconnect (struct GNUNET_GNS_Handle *handle)
192 {
193   GNUNET_assert (NULL == handle->client);
194   LOG (GNUNET_ERROR_TYPE_DEBUG,
195        "Trying to connect to GNS\n");
196   handle->client = GNUNET_CLIENT_connect ("gns", handle->cfg);
197   GNUNET_assert (NULL != handle->client);
198   process_pending_messages (handle);
199 }
200
201
202 /**
203  * Reconnect to GNS
204  *
205  * @param cls the handle
206  * @param tc task context
207  */
208 static void
209 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
210 {
211   struct GNUNET_GNS_Handle *handle = cls;
212
213   handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
214   reconnect (handle);
215 }
216
217
218 /**
219  * Disconnect from service and then reconnect.
220  *
221  * @param handle our handle
222  */
223 static void
224 force_reconnect (struct GNUNET_GNS_Handle *handle)
225 {
226   struct GNUNET_GNS_LookupRequest *lh;
227   struct PendingMessage *p;
228
229   GNUNET_CLIENT_disconnect (handle->client);
230   handle->client = NULL;
231   handle->in_receive = GNUNET_NO;
232   for (lh = handle->lookup_head; NULL != lh; lh = lh->next)
233   {
234     p = (struct PendingMessage *) &lh[1];
235     if (GNUNET_NO == p->transmitted)
236       continue;
237     p->transmitted = GNUNET_NO;
238     GNUNET_CONTAINER_DLL_insert (handle->pending_head,
239                                  handle->pending_tail,
240                                  p);  
241   }
242   handle->reconnect_backoff = GNUNET_TIME_STD_BACKOFF (handle->reconnect_backoff);
243   handle->reconnect_task = GNUNET_SCHEDULER_add_delayed (handle->reconnect_backoff,
244                                                     &reconnect_task,
245                                                     handle);
246 }
247
248
249 /**
250  * Transmit the next pending message, called by notify_transmit_ready
251  *
252  * @param cls the closure
253  * @param size size of pending data
254  * @param buf buffer with pending data
255  * @return size data transmitted
256  */
257 static size_t
258 transmit_pending (void *cls, size_t size, void *buf);
259
260
261 /**
262  * Handler for messages received from the GNS service
263  *
264  * @param cls the 'struct GNUNET_GNS_Handle'
265  * @param msg the incoming message
266  */
267 static void
268 process_message (void *cls, const struct GNUNET_MessageHeader *msg);
269
270
271 /**
272  * Try to send messages from list of messages to send
273  *
274  * @param handle the GNS handle
275  */
276 static void
277 process_pending_messages (struct GNUNET_GNS_Handle *handle)
278 {
279   struct PendingMessage *p = handle->pending_head;
280
281   if (NULL == handle->client)
282     return; /* wait for reconnect */ 
283   if (NULL != handle->th)
284     return; /* transmission request already pending */ 
285
286   while ((NULL != p) && (p->transmitted == GNUNET_YES))
287     p = p->next;
288   if (NULL == p)
289     return; /* no messages pending */
290   
291   LOG (GNUNET_ERROR_TYPE_DEBUG,
292        "Trying to transmit %u bytes\n", 
293        (unsigned int) p->size);
294   handle->th =
295     GNUNET_CLIENT_notify_transmit_ready (handle->client,
296                                          p->size,
297                                          GNUNET_TIME_UNIT_FOREVER_REL,
298                                          GNUNET_NO, &transmit_pending,
299                                          handle);
300   GNUNET_break (NULL != handle->th);
301 }
302
303
304 /**
305  * Transmit the next pending message, called by notify_transmit_ready
306  *
307  * @param cls the closure
308  * @param size size of pending data
309  * @param buf buffer with pending data
310  * @return size data transmitted
311  */
312 static size_t
313 transmit_pending (void *cls, size_t size, void *buf)
314 {
315   struct GNUNET_GNS_Handle *handle = cls;
316   char *cbuf = buf;
317   struct PendingMessage *p;
318   size_t tsize;
319
320   handle->th = NULL;
321   if ((0 == size) || (NULL == buf))
322   {
323     LOG (GNUNET_ERROR_TYPE_DEBUG,
324          "Transmission to GNS service failed!\n");
325     force_reconnect (handle);
326     return 0;
327   }  
328   if (NULL == (p = handle->pending_head))
329     return 0;
330
331   tsize = 0;
332   while ((NULL != (p = handle->pending_head)) && (p->size <= size))
333   {
334     memcpy (&cbuf[tsize], &p[1], p->size);
335     tsize += p->size;
336     size -= p->size;
337     p->transmitted = GNUNET_YES;
338     GNUNET_CONTAINER_DLL_remove (handle->pending_head,
339                                  handle->pending_tail,
340                                  p);
341     if (GNUNET_YES != handle->in_receive)
342     {
343       GNUNET_CLIENT_receive (handle->client, &process_message, handle,
344                              GNUNET_TIME_UNIT_FOREVER_REL);
345       handle->in_receive = GNUNET_YES;
346     }
347   }
348   LOG (GNUNET_ERROR_TYPE_DEBUG,
349        "Sending %u bytes\n",
350        (unsigned int) tsize);
351   process_pending_messages (handle);
352   return tsize;
353 }
354
355
356 /**
357  * Process a given reply to the lookup request
358  *
359  * @param qe a queue entry
360  * @param msg the lookup message received
361  */
362 static void
363 process_lookup_reply (struct GNUNET_GNS_LookupRequest *qe,
364                       const struct GNUNET_GNS_ClientLookupResultMessage *msg)
365 {
366   struct GNUNET_GNS_Handle *handle = qe->gns_handle;
367   struct PendingMessage *p = (struct PendingMessage *) &qe[1];
368   uint32_t rd_count = ntohl (msg->rd_count);
369   struct GNUNET_NAMESTORE_RecordData rd[rd_count];
370   size_t mlen;
371
372   if (GNUNET_YES != p->transmitted)
373   {
374     /* service send reply to query we never managed to send!? */
375     GNUNET_break (0);
376     force_reconnect (handle);
377     return;
378   }
379   mlen = ntohs (msg->header.size);
380   mlen -= sizeof (struct GNUNET_GNS_ClientLookupResultMessage);
381   if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (mlen,
382                                                              (const char*) &msg[1],
383                                                              rd_count,
384                                                              rd))
385   {
386     LOG (GNUNET_ERROR_TYPE_ERROR,
387          _("Failed to serialize lookup reply from GNS service!\n"));
388     qe->lookup_proc (qe->proc_cls, 0, NULL);
389   }
390   else
391   { 
392     LOG (GNUNET_ERROR_TYPE_DEBUG,
393          "Received lookup reply from GNS service (%u records)\n",
394          (unsigned int) rd_count);
395     qe->lookup_proc (qe->proc_cls, rd_count, rd);
396   }
397   GNUNET_CONTAINER_DLL_remove (handle->lookup_head, handle->lookup_tail, qe);
398   GNUNET_free (qe);
399 }
400
401
402 /**
403  * Handler for messages received from the GNS service
404  *
405  * @param cls the 'struct GNUNET_GNS_Handle'
406  * @param msg the incoming message
407  */
408 static void
409 process_message (void *cls, const struct GNUNET_MessageHeader *msg)
410 {
411   struct GNUNET_GNS_Handle *handle = cls;
412   struct GNUNET_GNS_LookupRequest *lr;
413   const struct GNUNET_GNS_ClientLookupResultMessage *lookup_msg;
414   uint32_t r_id;
415   
416   if (NULL == msg)
417   {
418     force_reconnect (handle);
419     return;
420   }
421   switch (ntohs (msg->type))
422   {
423   case GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT:
424     LOG (GNUNET_ERROR_TYPE_DEBUG,
425          "Got LOOKUP_RESULT msg\n");
426     if (ntohs (msg->size) < sizeof (struct GNUNET_GNS_ClientLookupResultMessage))
427     {
428       GNUNET_break (0);
429       force_reconnect (handle);
430       return;
431     }
432     lookup_msg = (const struct GNUNET_GNS_ClientLookupResultMessage *) msg;
433     r_id = ntohl (lookup_msg->id);   
434     for (lr = handle->lookup_head; NULL != lr; lr = lr->next)    
435       if (lr->r_id == r_id)
436       {
437         process_lookup_reply(lr, lookup_msg);    
438         break;
439       }
440     break;
441   default:
442     GNUNET_break (0);
443     force_reconnect (handle);
444     return;
445   }
446   GNUNET_CLIENT_receive (handle->client, &process_message, handle,
447                          GNUNET_TIME_UNIT_FOREVER_REL);
448 }
449
450
451 /**
452  * Initialize the connection with the GNS service.
453  *
454  * @param cfg configuration to use
455  * @return handle to the GNS service, or NULL on error
456  */
457 struct GNUNET_GNS_Handle *
458 GNUNET_GNS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
459 {
460   struct GNUNET_GNS_Handle *handle;
461
462   handle = GNUNET_new (struct GNUNET_GNS_Handle);
463   handle->cfg = cfg;
464   reconnect (handle);
465   return handle;
466 }
467
468
469 /**
470  * Shutdown connection with the GNS service.
471  *
472  * @param handle handle of the GNS connection to stop
473  */
474 void
475 GNUNET_GNS_disconnect (struct GNUNET_GNS_Handle *handle)
476 {
477   GNUNET_CLIENT_disconnect (handle->client);
478   if (GNUNET_SCHEDULER_NO_TASK != handle->reconnect_task)
479   {
480     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
481     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
482   }
483   GNUNET_assert (NULL == handle->lookup_head);
484   GNUNET_free (handle);
485 }
486
487
488 /**
489  * Cancel pending lookup request
490  *
491  * @param lr the lookup request to cancel
492  */
493 void
494 GNUNET_GNS_lookup_cancel (struct GNUNET_GNS_LookupRequest *lr)
495 {
496   struct PendingMessage *p = (struct PendingMessage*) &lr[1];
497
498   GNUNET_assert (NULL != lr->gns_handle); 
499   if (GNUNET_NO == p->transmitted)
500     GNUNET_CONTAINER_DLL_remove (lr->gns_handle->pending_head,
501                                  lr->gns_handle->pending_tail,
502                                  p);
503   GNUNET_CONTAINER_DLL_remove (lr->gns_handle->lookup_head,
504                                lr->gns_handle->lookup_tail,
505                                lr);
506   GNUNET_free (lr);
507 }
508
509
510 /**
511  * Perform an asynchronous lookup operation on the GNS.
512  *
513  * @param handle handle to the GNS service
514  * @param name the name to look up
515  * @param zone the zone to start the resolution in
516  * @param type the record type to look up
517  * @param only_cached #GNUNET_YES to only check locally (not in the DHT)
518  * @param shorten_zone_key the private key of the shorten zone (can be NULL)
519  * @param proc processor to call on result
520  * @param proc_cls closure for processor
521  * @return handle to the get request
522  */
523 struct GNUNET_GNS_LookupRequest*
524 GNUNET_GNS_lookup (struct GNUNET_GNS_Handle *handle,
525                    const char *name,
526                    const struct GNUNET_CRYPTO_EccPublicSignKey *zone,
527                    int type,
528                    int only_cached,
529                    const struct GNUNET_CRYPTO_EccPrivateKey *shorten_zone_key,
530                    GNUNET_GNS_LookupResultProcessor proc,
531                    void *proc_cls)
532 {
533   /* IPC to shorten gns names, return shorten_handle */
534   struct GNUNET_GNS_ClientLookupMessage *lookup_msg;
535   struct GNUNET_GNS_LookupRequest *lr;
536   size_t msize;
537   struct PendingMessage *pending;
538
539   if (NULL == name)
540   {
541     GNUNET_break (0);
542     return NULL;
543   } 
544   LOG (GNUNET_ERROR_TYPE_DEBUG,
545        "Trying to lookup `%s' in GNS\n", 
546        name);
547   msize = sizeof (struct GNUNET_GNS_ClientLookupMessage)
548     + strlen (name) + 1;
549   if (msize > UINT16_MAX)
550   {
551     GNUNET_break (0);
552     return NULL;
553   }
554   lr = GNUNET_malloc (sizeof (struct GNUNET_GNS_LookupRequest) +
555                       sizeof (struct PendingMessage) + msize);
556   lr->gns_handle = handle;
557   lr->lookup_proc = proc;
558   lr->proc_cls = proc_cls;
559   lr->r_id = handle->r_id_gen++;
560   pending = (struct PendingMessage *)&lr[1];
561   pending->size = msize;
562   pending->r_id = lr->r_id;
563   GNUNET_CONTAINER_DLL_insert_tail (handle->lookup_head,
564                                     handle->lookup_tail, lr);
565
566   lookup_msg = (struct GNUNET_GNS_ClientLookupMessage *) &pending[1];
567   lookup_msg->header.type = htons (GNUNET_MESSAGE_TYPE_GNS_LOOKUP);
568   lookup_msg->header.size = htons (msize);
569   lookup_msg->id = htonl (lr->r_id);
570   lookup_msg->only_cached = htonl (only_cached);
571   lookup_msg->zone = *zone;
572   lookup_msg->type = htonl (type);
573   if (NULL != shorten_zone_key)
574   {
575     lookup_msg->have_key = htons (GNUNET_YES);
576     lookup_msg->shorten_key = *shorten_zone_key;
577   }
578   memcpy (&lookup_msg[1], name, strlen (name) + 1);
579   GNUNET_CONTAINER_DLL_insert_tail (handle->pending_head,
580                                     handle->pending_tail,
581                                     pending);
582   process_pending_messages (handle);
583   return lr;
584 }
585
586
587 /* end of gns_api.c */