added lookup test + fix in test
[oweals/gnunet.git] / src / namestore / namestore_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010-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 namestore/namestore_api.c
23  * @brief API to access the NAMESTORE service
24  * @author Martin Schanzenbach
25  * @author Matthias Wachs
26  * @author Christian Grothoff
27  */
28
29 #include "platform.h"
30 #include "gnunet_util_lib.h"
31 #include "gnunet_crypto_lib.h"
32 #include "gnunet_constants.h"
33 #include "gnunet_dnsparser_lib.h"
34 #include "gnunet_arm_service.h"
35 #include "gnunet_signatures.h"
36 #include "gnunet_namestore_service.h"
37 #include "namestore.h"
38
39
40 #define LOG(kind,...) GNUNET_log_from (kind, "namestore-api",__VA_ARGS__)
41
42
43 /**
44  * An QueueEntry used to store information for a pending
45  * NAMESTORE record operation
46  */
47 struct GNUNET_NAMESTORE_QueueEntry
48 {
49
50   /**
51    * Kept in a DLL.
52    */
53   struct GNUNET_NAMESTORE_QueueEntry *next;
54
55   /**
56    * Kept in a DLL.
57    */
58   struct GNUNET_NAMESTORE_QueueEntry *prev;
59
60   /**
61    * Main handle to access the namestore.
62    */
63   struct GNUNET_NAMESTORE_Handle *nsh;
64
65   /**
66    * Continuation to call
67    */
68   GNUNET_NAMESTORE_ContinuationWithStatus cont;
69
70   /**
71    * Closure for 'cont'.
72    */
73   void *cont_cls;
74
75   /**
76    * Function to call with the records we get back; or NULL.
77    */
78   GNUNET_NAMESTORE_RecordMonitor proc;
79
80   /**
81    * Closure for @e proc.
82    */
83   void *proc_cls;
84
85   /**
86    * The operation id this zone iteration operation has
87    */
88   uint32_t op_id;
89
90 };
91
92
93 /**
94  * Handle for a zone iterator operation
95  */
96 struct GNUNET_NAMESTORE_ZoneIterator
97 {
98
99   /**
100    * Kept in a DLL.
101    */
102   struct GNUNET_NAMESTORE_ZoneIterator *next;
103
104   /**
105    * Kept in a DLL.
106    */
107   struct GNUNET_NAMESTORE_ZoneIterator *prev;
108
109   /**
110    * Main handle to access the namestore.
111    */
112   struct GNUNET_NAMESTORE_Handle *h;
113
114   /**
115    * The continuation to call with the results
116    */
117   GNUNET_NAMESTORE_RecordMonitor proc;
118
119   /**
120    * Closure for @e proc.
121    */
122   void* proc_cls;
123
124   /**
125    * Private key of the zone.
126    */
127   struct GNUNET_CRYPTO_EcdsaPrivateKey zone;
128
129   /**
130    * The operation id this zone iteration operation has
131    */
132   uint32_t op_id;
133
134 };
135
136
137 /**
138  * Message in linked list we should send to the service.  The
139  * actual binary message follows this struct.
140  */
141 struct PendingMessage
142 {
143
144   /**
145    * Kept in a DLL.
146    */
147   struct PendingMessage *next;
148
149   /**
150    * Kept in a DLL.
151    */
152   struct PendingMessage *prev;
153
154   /**
155    * Size of the message.
156    */
157   size_t size;
158
159 };
160
161
162 /**
163  * Connection to the NAMESTORE service.
164  */
165 struct GNUNET_NAMESTORE_Handle
166 {
167
168   /**
169    * Configuration to use.
170    */
171   const struct GNUNET_CONFIGURATION_Handle *cfg;
172
173   /**
174    * Socket (if available).
175    */
176   struct GNUNET_CLIENT_Connection *client;
177
178   /**
179    * Currently pending transmission request (or NULL).
180    */
181   struct GNUNET_CLIENT_TransmitHandle *th;
182
183   /**
184    * Head of linked list of pending messages to send to the service
185    */
186   struct PendingMessage *pending_head;
187
188   /**
189    * Tail of linked list of pending messages to send to the service
190    */
191   struct PendingMessage *pending_tail;
192
193   /**
194    * Head of pending namestore queue entries
195    */
196   struct GNUNET_NAMESTORE_QueueEntry *op_head;
197
198   /**
199    * Tail of pending namestore queue entries
200    */
201   struct GNUNET_NAMESTORE_QueueEntry *op_tail;
202
203   /**
204    * Head of pending namestore zone iterator entries
205    */
206   struct GNUNET_NAMESTORE_ZoneIterator *z_head;
207
208   /**
209    * Tail of pending namestore zone iterator entries
210    */
211   struct GNUNET_NAMESTORE_ZoneIterator *z_tail;
212
213   /**
214    * Reconnect task
215    */
216   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
217
218   /**
219    * Delay introduced before we reconnect.
220    */
221   struct GNUNET_TIME_Relative reconnect_delay;
222
223   /**
224    * Should we reconnect to service due to some serious error?
225    */
226   int reconnect;
227
228   /**
229    * Did we start to receive yet?
230    */
231   int is_receiving;
232
233   /**
234    * The last operation id used for a NAMESTORE operation
235    */
236   uint32_t last_op_id_used;
237
238 };
239
240
241 /**
242  * Disconnect from service and then reconnect.
243  *
244  * @param h our handle
245  */
246 static void
247 force_reconnect (struct GNUNET_NAMESTORE_Handle *h);
248
249
250 /**
251  * Handle an incoming message of type
252  * #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE_RESPONSE
253  *
254  * @param qe the respective entry in the message queue
255  * @param msg the message we received
256  * @param size the message size
257  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and we did NOT notify the client
258  */
259 static int
260 handle_record_store_response (struct GNUNET_NAMESTORE_QueueEntry *qe,
261                               const struct RecordStoreResponseMessage* msg,
262                               size_t size)
263 {
264   int res;
265   const char *emsg;
266
267   LOG (GNUNET_ERROR_TYPE_DEBUG,
268        "Received `%s'\n",
269        "RECORD_STORE_RESPONSE");
270   /* TODO: add actual error message from namestore to response... */
271   res = ntohl (msg->op_result);
272   if (GNUNET_SYSERR == res)
273     emsg = _("Namestore failed to store record\n");
274   else
275     emsg = NULL;
276   if (NULL != qe->cont)
277     qe->cont (qe->cont_cls, res, emsg);
278   return GNUNET_OK;
279 }
280
281
282 /**
283  * Handle an incoming message of type
284  * #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT
285  *
286  * @param qe the respective entry in the message queue
287  * @param msg the message we received
288  * @param size the message size
289  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and we did NOT notify the client
290  */
291 static int
292 handle_record_result (struct GNUNET_NAMESTORE_QueueEntry *qe,
293                       const struct RecordResultMessage *msg,
294                       size_t size)
295 {
296   const char *name;
297   const char *rd_tmp;
298   size_t exp_msg_len;
299   size_t msg_len;
300   size_t name_len;
301   size_t rd_len;
302   unsigned int rd_count;
303
304   LOG (GNUNET_ERROR_TYPE_DEBUG,
305        "Received `%s'\n",
306        "RECORD_RESULT");
307   rd_len = ntohs (msg->rd_len);
308   rd_count = ntohs (msg->rd_count);
309   msg_len = ntohs (msg->gns_header.header.size);
310   name_len = ntohs (msg->name_len);
311   GNUNET_break (0 == ntohs (msg->reserved));
312   exp_msg_len = sizeof (struct RecordResultMessage) + name_len + rd_len;
313   if (msg_len != exp_msg_len)
314   {
315     GNUNET_break (0);
316     return GNUNET_SYSERR;
317   }
318   name = (const char *) &msg[1];
319   if ( (name_len > 0) &&
320        ('\0' != name[name_len -1]) )
321   {
322     GNUNET_break (0);
323     return GNUNET_SYSERR;
324   }
325   rd_tmp = &name[name_len];
326   {
327     struct GNUNET_GNSRECORD_Data rd[rd_count];
328
329     if (GNUNET_OK != GNUNET_GNSRECORD_records_deserialize(rd_len, rd_tmp, rd_count, rd))
330     {
331       GNUNET_break (0);
332       return GNUNET_SYSERR;
333     }
334     if (0 == name_len)
335       name = NULL;
336     if (NULL != qe->proc)
337       qe->proc (qe->proc_cls,
338                 &msg->private_key,
339                 name,
340                 rd_count,
341                 (rd_count > 0) ? rd : NULL);
342   }
343   return GNUNET_OK;
344 }
345
346
347 /**
348  * Handle an incoming message of type
349  * #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE.
350  *
351  * @param qe the respective entry in the message queue
352  * @param msg the message we received
353  * @param size the message size
354  * @return #GNUNET_OK on success, #GNUNET_NO if we notified the client about
355  *         the error, #GNUNET_SYSERR on error and we did NOT notify the client
356  */
357 static int
358 handle_zone_to_name_response (struct GNUNET_NAMESTORE_QueueEntry *qe,
359                               const struct ZoneToNameResponseMessage *msg,
360                               size_t size)
361 {
362   int res;
363   size_t name_len;
364   size_t rd_ser_len;
365   unsigned int rd_count;
366   const char *name_tmp;
367   const char *rd_tmp;
368
369   LOG (GNUNET_ERROR_TYPE_DEBUG,
370        "Received `%s'\n",
371        "ZONE_TO_NAME_RESPONSE");
372   res = ntohs (msg->res);
373   switch (res)
374   {
375   case GNUNET_SYSERR:
376     LOG (GNUNET_ERROR_TYPE_DEBUG,
377          "An error occured during zone to name operation\n");
378     break;
379   case GNUNET_NO:
380     LOG (GNUNET_ERROR_TYPE_DEBUG,
381          "Namestore has no result for zone to name mapping \n");
382     break;
383   case GNUNET_YES:
384     LOG (GNUNET_ERROR_TYPE_DEBUG,
385          "Namestore has result for zone to name mapping \n");
386     name_len = ntohs (msg->name_len);
387     rd_count = ntohs (msg->rd_count);
388     rd_ser_len = ntohs (msg->rd_len);
389     name_tmp = (const char *) &msg[1];
390     if ( (name_len > 0) &&
391          ('\0' != name_tmp[name_len -1]) )
392     {
393       GNUNET_break (0);
394       return GNUNET_SYSERR;
395     }
396     rd_tmp = &name_tmp[name_len];
397     {
398       struct GNUNET_GNSRECORD_Data rd[rd_count];
399
400       if (GNUNET_OK != GNUNET_GNSRECORD_records_deserialize(rd_ser_len, rd_tmp, rd_count, rd))
401       {
402         GNUNET_break (0);
403         return GNUNET_SYSERR;
404       }
405       /* normal end, call continuation with result */
406       if (NULL != qe->proc)
407         qe->proc (qe->proc_cls,
408                   &msg->zone,
409                   name_tmp,
410                   rd_count, rd);
411       /* return is important here: break would call continuation with error! */
412       return GNUNET_OK;
413     }
414   default:
415     GNUNET_break (0);
416     return GNUNET_SYSERR;
417   }
418   /* error case, call continuation with error */
419   if (NULL != qe->proc)
420     qe->proc (qe->proc_cls, NULL, NULL, 0, NULL);
421   return GNUNET_NO;
422 }
423
424
425 /**
426  * Handle incoming messages for record operations
427  *
428  * @param qe the respective zone iteration handle
429  * @param msg the message we received
430  * @param type the message type in host byte order
431  * @param size the message size
432  * @return #GNUNET_OK on success, #GNUNET_NO if we notified the client about
433  *         the error, #GNUNET_SYSERR on error and we did NOT notify the client
434  */
435 static int
436 manage_record_operations (struct GNUNET_NAMESTORE_QueueEntry *qe,
437                           const struct GNUNET_MessageHeader *msg,
438                           uint16_t type,
439                           size_t size)
440 {
441   /* handle different message type */
442   switch (type)
443   {
444   case GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE_RESPONSE:
445     if (size != sizeof (struct RecordStoreResponseMessage))
446     {
447       GNUNET_break (0);
448       return GNUNET_SYSERR;
449     }
450     return handle_record_store_response (qe, (const struct RecordStoreResponseMessage *) msg, size);
451   case GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE:
452     if (size < sizeof (struct ZoneToNameResponseMessage))
453     {
454       GNUNET_break (0);
455       return GNUNET_SYSERR;
456     }
457     return handle_zone_to_name_response (qe, (const struct ZoneToNameResponseMessage *) msg, size);
458   case GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT:
459     if (size < sizeof (struct RecordResultMessage))
460     {
461       GNUNET_break (0);
462       return GNUNET_SYSERR;
463     }
464     return handle_record_result (qe, (const struct RecordResultMessage *) msg, size);
465   default:
466     GNUNET_break (0);
467     return GNUNET_SYSERR;
468   }
469 }
470
471
472 /**
473  * Handle a response from NAMESTORE service for a zone iteration request
474  *
475  * @param ze the respective iterator for this operation
476  * @param msg the message containing the respoonse
477  * @param size the message size
478  * @return #GNUNET_YES on success, @a ze should be kept, #GNUNET_NO on success if @a ze should
479  *         not be kept any longer, #GNUNET_SYSERR on error (disconnect) and @a ze should be kept
480  */
481 static int
482 handle_zone_iteration_response (struct GNUNET_NAMESTORE_ZoneIterator *ze,
483                                 const struct RecordResultMessage *msg,
484                                 size_t size)
485 {
486   static struct GNUNET_CRYPTO_EcdsaPrivateKey priv_dummy;
487   size_t msg_len;
488   size_t exp_msg_len;
489   size_t name_len;
490   size_t rd_len;
491   unsigned rd_count;
492   const char *name_tmp;
493   const char *rd_ser_tmp;
494
495   LOG (GNUNET_ERROR_TYPE_DEBUG,
496        "Received `%s'\n",
497        "ZONE_ITERATION_RESPONSE");
498   msg_len = ntohs (msg->gns_header.header.size);
499   rd_len = ntohs (msg->rd_len);
500   rd_count = ntohs (msg->rd_count);
501   name_len = ntohs (msg->name_len);
502   exp_msg_len = sizeof (struct RecordResultMessage) + name_len + rd_len;
503   if (msg_len != exp_msg_len)
504   {
505     GNUNET_break (0);
506     return GNUNET_SYSERR;
507   }
508   if ( (0 == name_len) &&
509        (0 == (memcmp (&msg->private_key,
510                       &priv_dummy,
511                       sizeof (priv_dummy)))) )
512   {
513     LOG (GNUNET_ERROR_TYPE_DEBUG,
514          "Zone iteration completed!\n");
515     if (NULL != ze->proc)
516       ze->proc (ze->proc_cls, NULL, NULL, 0, NULL);
517     return GNUNET_NO;
518   }
519   name_tmp = (const char *) &msg[1];
520   if ((name_tmp[name_len -1] != '\0') || (name_len > MAX_NAME_LEN))
521   {
522     GNUNET_break (0);
523     return GNUNET_SYSERR;
524   }
525   rd_ser_tmp = (const char *) &name_tmp[name_len];
526   {
527     struct GNUNET_GNSRECORD_Data rd[rd_count];
528
529     if (GNUNET_OK != GNUNET_GNSRECORD_records_deserialize (rd_len,
530                                                            rd_ser_tmp,
531                                                            rd_count,
532                                                            rd))
533     {
534       GNUNET_break (0);
535       return GNUNET_SYSERR;
536     }
537     if (NULL != ze->proc)
538       ze->proc (ze->proc_cls,
539                 &msg->private_key,
540                 name_tmp,
541                 rd_count, rd);
542     return GNUNET_YES;
543   }
544 }
545
546
547 /**
548  * Handle incoming messages for zone iterations
549  *
550  * @param ze the respective zone iteration handle
551  * @param msg the message we received
552  * @param type the message type in HBO
553  * @param size the message size
554  * @return #GNUNET_YES on success, @a ze should be kept, #GNUNET_NO on success if @a ze should
555  *         not be kept any longer, #GNUNET_SYSERR on error (disconnect) and @a ze should be kept
556  */
557 static int
558 manage_zone_operations (struct GNUNET_NAMESTORE_ZoneIterator *ze,
559                         const struct GNUNET_MessageHeader *msg,
560                         int type, size_t size)
561 {
562   /* handle different message type */
563   switch (type)
564   {
565   case GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT:
566     if (size < sizeof (struct RecordResultMessage))
567     {
568       GNUNET_break (0);
569       return GNUNET_SYSERR;
570     }
571     return handle_zone_iteration_response (ze,
572                                            (const struct RecordResultMessage *) msg,
573                                            size);
574   default:
575     GNUNET_break (0);
576     return GNUNET_SYSERR;
577   }
578 }
579
580
581 /**
582  * Type of a function to call when we receive a message
583  * from the service.
584  *
585  * @param cls the `struct GNUNET_NAMESTORE_SchedulingHandle`
586  * @param msg message received, NULL on timeout or fatal error
587  */
588 static void
589 process_namestore_message (void *cls,
590                            const struct GNUNET_MessageHeader *msg)
591 {
592   struct GNUNET_NAMESTORE_Handle *h = cls;
593   const struct GNUNET_NAMESTORE_Header *gm;
594   struct GNUNET_NAMESTORE_QueueEntry *qe;
595   struct GNUNET_NAMESTORE_ZoneIterator *ze;
596   uint16_t size;
597   uint16_t type;
598   uint32_t r_id;
599   int ret;
600
601   if (NULL == msg)
602   {
603     force_reconnect (h);
604     return;
605   }
606   size = ntohs (msg->size);
607   type = ntohs (msg->type);
608   if (size < sizeof (struct GNUNET_NAMESTORE_Header))
609   {
610     GNUNET_break_op (0);
611     GNUNET_CLIENT_receive (h->client,
612                            &process_namestore_message, h,
613                            GNUNET_TIME_UNIT_FOREVER_REL);
614     return;
615   }
616   gm = (const struct GNUNET_NAMESTORE_Header *) msg;
617   r_id = ntohl (gm->r_id);
618
619   LOG (GNUNET_ERROR_TYPE_DEBUG,
620        "Received message type %u size %u op %u\n",
621        (unsigned int) type,
622        (unsigned int) size,
623        (unsigned int) r_id);
624
625   /* Is it a record related operation ? */
626   for (qe = h->op_head; qe != NULL; qe = qe->next)
627     if (qe->op_id == r_id)
628       break;
629   if (NULL != qe)
630   {
631     ret = manage_record_operations (qe, msg, type, size);
632     if (GNUNET_SYSERR == ret)
633     {
634       /* protocol error, need to reconnect */
635       h->reconnect = GNUNET_YES;
636     }
637     else
638     {
639       /* client was notified about success or failure, clean up 'qe' */
640       GNUNET_CONTAINER_DLL_remove (h->op_head,
641                                    h->op_tail,
642                                    qe);
643       GNUNET_free (qe);
644     }
645   }
646   /* Is it a zone iteration operation? */
647   for (ze = h->z_head; ze != NULL; ze = ze->next)
648     if (ze->op_id == r_id)
649       break;
650   if (NULL != ze)
651   {
652     ret = manage_zone_operations (ze, msg, type, size);
653     if (GNUNET_NO == ret)
654     {
655       /* end of iteration, clean up 'ze' */
656       GNUNET_CONTAINER_DLL_remove (h->z_head,
657                                    h->z_tail,
658                                    ze);
659       GNUNET_free (ze);
660     }
661     if (GNUNET_SYSERR == ret)
662     {
663       /* protocol error, need to reconnect */
664       h->reconnect = GNUNET_YES;
665     }
666   }
667   if (GNUNET_YES == h->reconnect)
668   {
669     force_reconnect (h);
670     return;
671   }
672   GNUNET_CLIENT_receive (h->client, &process_namestore_message, h,
673                          GNUNET_TIME_UNIT_FOREVER_REL);
674 }
675
676
677 /**
678  * Transmit messages from the message queue to the service
679  * (if there are any, and if we are not already trying).
680  *
681  * @param h handle to use
682  */
683 static void
684 do_transmit (struct GNUNET_NAMESTORE_Handle *h);
685
686
687 /**
688  * We can now transmit a message to NAMESTORE. Do it.
689  *
690  * @param cls the `struct GNUNET_NAMESTORE_Handle`
691  * @param size number of bytes we can transmit
692  * @param buf where to copy the messages
693  * @return number of bytes copied into @a buf
694  */
695 static size_t
696 transmit_message_to_namestore (void *cls,
697                                size_t size,
698                                void *buf)
699 {
700   struct GNUNET_NAMESTORE_Handle *h = cls;
701   struct PendingMessage *p;
702   size_t ret;
703   char *cbuf;
704
705   h->th = NULL;
706   if ((0 == size) || (NULL == buf))
707   {
708     force_reconnect (h);
709     return 0;
710   }
711   ret = 0;
712   cbuf = buf;
713   while ( (NULL != (p = h->pending_head)) &&
714           (p->size <= size) )
715   {
716     memcpy (&cbuf[ret], &p[1], p->size);
717     ret += p->size;
718     size -= p->size;
719     GNUNET_CONTAINER_DLL_remove (h->pending_head,
720                                  h->pending_tail,
721                                  p);
722     if (GNUNET_NO == h->is_receiving)
723     {
724       h->is_receiving = GNUNET_YES;
725       GNUNET_CLIENT_receive (h->client,
726                              &process_namestore_message, h,
727                              GNUNET_TIME_UNIT_FOREVER_REL);
728     }
729     GNUNET_free (p);
730   }
731   do_transmit (h);
732   return ret;
733 }
734
735
736 /**
737  * Transmit messages from the message queue to the service
738  * (if there are any, and if we are not already trying).
739  *
740  * @param h handle to use
741  */
742 static void
743 do_transmit (struct GNUNET_NAMESTORE_Handle *h)
744 {
745   struct PendingMessage *p;
746
747   if (NULL != h->th)
748     return; /* transmission request already pending */
749   if (NULL == (p = h->pending_head))
750     return; /* transmission queue empty */
751   if (NULL == h->client)
752     return;                     /* currently reconnecting */
753   h->th = GNUNET_CLIENT_notify_transmit_ready (h->client, p->size,
754                                                GNUNET_TIME_UNIT_FOREVER_REL,
755                                                GNUNET_NO, &transmit_message_to_namestore,
756                                                h);
757   GNUNET_break (NULL != h->th);
758 }
759
760
761 /**
762  * Reconnect to namestore service.
763  *
764  * @param h the handle to the NAMESTORE service
765  */
766 static void
767 reconnect (struct GNUNET_NAMESTORE_Handle *h)
768 {
769   GNUNET_assert (NULL == h->client);
770   h->client = GNUNET_CLIENT_connect ("namestore", h->cfg);
771   GNUNET_assert (NULL != h->client);
772   do_transmit (h);
773 }
774
775
776 /**
777  * Re-establish the connection to the service.
778  *
779  * @param cls handle to use to re-connect.
780  * @param tc scheduler context
781  */
782 static void
783 reconnect_task (void *cls,
784                 const struct GNUNET_SCHEDULER_TaskContext *tc)
785 {
786   struct GNUNET_NAMESTORE_Handle *h = cls;
787
788   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
789   reconnect (h);
790 }
791
792
793 /**
794  * Disconnect from service and then reconnect.
795  *
796  * @param h our handle
797  */
798 static void
799 force_reconnect (struct GNUNET_NAMESTORE_Handle *h)
800 {
801   if (NULL != h->th)
802   {
803     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
804     h->th = NULL;
805   }
806   h->reconnect = GNUNET_NO;
807   GNUNET_CLIENT_disconnect (h->client);
808   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
809               "Reconnecting to namestore\n");
810   h->is_receiving = GNUNET_NO;
811   h->client = NULL;
812   h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay);
813   h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_delay,
814                                                     &reconnect_task,
815                                                     h);
816 }
817
818
819 /**
820  * Get a fresh operation id to distinguish between namestore requests
821  *
822  * @param h the namestore handle
823  * @return next operation id to use
824  */
825 static uint32_t
826 get_op_id (struct GNUNET_NAMESTORE_Handle *h)
827 {
828   return h->last_op_id_used++;
829 }
830
831
832 /**
833  * Initialize the connection with the NAMESTORE service.
834  *
835  * @param cfg configuration to use
836  * @return handle to the GNS service, or NULL on error
837  */
838 struct GNUNET_NAMESTORE_Handle *
839 GNUNET_NAMESTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
840 {
841   struct GNUNET_NAMESTORE_Handle *h;
842
843   h = GNUNET_new (struct GNUNET_NAMESTORE_Handle);
844   h->cfg = cfg;
845   h->reconnect_task = GNUNET_SCHEDULER_add_now (&reconnect_task, h);
846   h->last_op_id_used = 0;
847   return h;
848 }
849
850
851 /**
852  * Disconnect from the namestore service (and free associated
853  * resources).
854  *
855  * @param h handle to the namestore
856  */
857 void
858 GNUNET_NAMESTORE_disconnect (struct GNUNET_NAMESTORE_Handle *h)
859 {
860   struct PendingMessage *p;
861   struct GNUNET_NAMESTORE_QueueEntry *q;
862   struct GNUNET_NAMESTORE_ZoneIterator *z;
863
864   LOG (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n");
865   GNUNET_assert (NULL != h);
866   if (NULL != h->th)
867   {
868     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
869     h->th = NULL;
870   }
871   while (NULL != (p = h->pending_head))
872   {
873     GNUNET_CONTAINER_DLL_remove (h->pending_head, h->pending_tail, p);
874     GNUNET_free (p);
875   }
876   GNUNET_break (NULL == h->op_head);
877   while (NULL != (q = h->op_head))
878   {
879     GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, q);
880     GNUNET_free (q);
881   }
882   GNUNET_break (NULL == h->z_head);
883   while (NULL != (z = h->z_head))
884   {
885     GNUNET_CONTAINER_DLL_remove (h->z_head, h->z_tail, z);
886     GNUNET_free (z);
887   }
888   if (NULL != h->client)
889   {
890     GNUNET_CLIENT_disconnect (h->client);
891     h->client = NULL;
892   }
893   if (GNUNET_SCHEDULER_NO_TASK != h->reconnect_task)
894   {
895     GNUNET_SCHEDULER_cancel (h->reconnect_task);
896     h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
897   }
898   GNUNET_free (h);
899 }
900
901
902 /**
903  * Store an item in the namestore.  If the item is already present,
904  * it is replaced with the new record.  Use an empty array to
905  * remove all records under the given name.
906  *
907  * @param h handle to the namestore
908  * @param pkey private key of the zone
909  * @param label name that is being mapped (at most 255 characters long)
910  * @param rd_count number of records in the 'rd' array
911  * @param rd array of records with data to store
912  * @param cont continuation to call when done
913  * @param cont_cls closure for 'cont'
914  * @return handle to abort the request
915  */
916 struct GNUNET_NAMESTORE_QueueEntry *
917 GNUNET_NAMESTORE_records_store (struct GNUNET_NAMESTORE_Handle *h,
918                                 const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey,
919                                 const char *label,
920                                 unsigned int rd_count,
921                                 const struct GNUNET_GNSRECORD_Data *rd,
922                                 GNUNET_NAMESTORE_ContinuationWithStatus cont,
923                                 void *cont_cls)
924 {
925   struct GNUNET_NAMESTORE_QueueEntry *qe;
926   struct PendingMessage *pe;
927   char *name_tmp;
928   char *rd_ser;
929   size_t rd_ser_len;
930   size_t msg_size;
931   size_t name_len;
932   uint32_t rid;
933   struct RecordStoreMessage *msg;
934
935   GNUNET_assert (NULL != h);
936   GNUNET_assert (NULL != pkey);
937   GNUNET_assert (NULL != label);
938   name_len = strlen (label) + 1;
939   if (name_len > MAX_NAME_LEN)
940   {
941     GNUNET_break (0);
942     return NULL;
943   }
944   rid = get_op_id (h);
945   qe = GNUNET_new (struct GNUNET_NAMESTORE_QueueEntry);
946   qe->nsh = h;
947   qe->cont = cont;
948   qe->cont_cls = cont_cls;
949   qe->op_id = rid;
950   GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, qe);
951
952   /* setup msg */
953   rd_ser_len = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
954   msg_size = sizeof (struct RecordStoreMessage) + name_len + rd_ser_len;
955   pe = GNUNET_malloc (sizeof (struct PendingMessage) + msg_size);
956   pe->size = msg_size;
957   msg = (struct RecordStoreMessage *) &pe[1];
958   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE);
959   msg->gns_header.header.size = htons (msg_size);
960   msg->gns_header.r_id = htonl (rid);
961   msg->name_len = htons (name_len);
962   msg->rd_count = htons (rd_count);
963   msg->rd_len = htons (rd_ser_len);
964   msg->reserved = htons (0);
965   msg->private_key = *pkey;
966
967   name_tmp = (char *) &msg[1];
968   memcpy (name_tmp, label, name_len);
969   rd_ser = &name_tmp[name_len];
970   GNUNET_break (rd_ser_len ==
971                 GNUNET_GNSRECORD_records_serialize (rd_count, rd,
972                                                     rd_ser_len,
973                                                     rd_ser));
974   LOG (GNUNET_ERROR_TYPE_DEBUG,
975        "Sending `%s' message for name `%s' with size %u and %u records\n",
976        "NAMESTORE_RECORD_STORE", label, msg_size,
977        rd_count);
978   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
979   do_transmit (h);
980   return qe;
981 }
982
983
984 /**
985  * Lookup an item in the namestore.
986  *
987  * @param h handle to the namestore
988  * @param pkey private key of the zone
989  * @param label name that is being mapped (at most 255 characters long)
990  * @param rm function to call with the result (with 0 records if we don't have that label)
991  * @param rm_cls closure for @a rm
992  * @return handle to abort the request
993  */
994 struct GNUNET_NAMESTORE_QueueEntry *
995 GNUNET_NAMESTORE_records_lookup (struct GNUNET_NAMESTORE_Handle *h,
996                                  const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey,
997                                  const char *label,
998                                  GNUNET_NAMESTORE_RecordMonitor rm,
999                                  void *rm_cls)
1000 {
1001   struct GNUNET_NAMESTORE_QueueEntry *qe;
1002   struct PendingMessage *pe;
1003   struct LabelLookupMessage * msg;
1004   size_t msg_size;
1005   size_t label_len;
1006
1007   GNUNET_assert (NULL != h);
1008   GNUNET_assert (NULL != pkey);
1009   GNUNET_assert (NULL != label);
1010
1011   if (1 == (label_len = strlen (label) + 1))
1012     return NULL;
1013
1014   qe = GNUNET_new (struct GNUNET_NAMESTORE_QueueEntry);
1015   qe->nsh = h;
1016   qe->proc = rm;
1017   qe->proc_cls = rm_cls;
1018   qe->op_id = get_op_id(h);
1019   GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, qe);
1020
1021   msg_size = sizeof (struct LabelLookupMessage) + label_len;
1022   pe = GNUNET_malloc (sizeof (struct PendingMessage) + msg_size);
1023   pe->size = msg_size;
1024   msg = (struct LabelLookupMessage *) &pe[1];
1025   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP);
1026   msg->gns_header.header.size = htons (msg_size);
1027   msg->gns_header.r_id = htonl (qe->op_id);
1028   msg->zone = *pkey;
1029   msg->label_len = htons(label_len);
1030   memcpy (&msg[1], label, label_len);
1031
1032   /* transmit message */
1033   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
1034   do_transmit (h);
1035   return qe;
1036 }
1037
1038
1039 /**
1040  * Look for an existing PKEY delegation record for a given public key.
1041  * Returns at most one result to the processor.
1042  *
1043  * @param h handle to the namestore
1044  * @param zone public key of the zone to look up in, never NULL
1045  * @param value_zone public key of the target zone (value), never NULL
1046  * @param proc function to call on the matching records, or with
1047  *        NULL (rd_count == 0) if there are no matching records
1048  * @param proc_cls closure for @a proc
1049  * @return a handle that can be used to
1050  *         cancel
1051  */
1052 struct GNUNET_NAMESTORE_QueueEntry *
1053 GNUNET_NAMESTORE_zone_to_name (struct GNUNET_NAMESTORE_Handle *h,
1054                                const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
1055                                const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
1056                                GNUNET_NAMESTORE_RecordMonitor proc, void *proc_cls)
1057 {
1058   struct GNUNET_NAMESTORE_QueueEntry *qe;
1059   struct PendingMessage *pe;
1060   struct ZoneToNameMessage * msg;
1061   size_t msg_size;
1062   uint32_t rid;
1063
1064   GNUNET_assert (NULL != h);
1065   GNUNET_assert (NULL != zone);
1066   GNUNET_assert (NULL != value_zone);
1067   rid = get_op_id(h);
1068   qe = GNUNET_new (struct GNUNET_NAMESTORE_QueueEntry);
1069   qe->nsh = h;
1070   qe->proc = proc;
1071   qe->proc_cls = proc_cls;
1072   qe->op_id = rid;
1073   GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, qe);
1074
1075   msg_size = sizeof (struct ZoneToNameMessage);
1076   pe = GNUNET_malloc (sizeof (struct PendingMessage) + msg_size);
1077   pe->size = msg_size;
1078   msg = (struct ZoneToNameMessage *) &pe[1];
1079   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME);
1080   msg->gns_header.header.size = htons (msg_size);
1081   msg->gns_header.r_id = htonl (rid);
1082   msg->zone = *zone;
1083   msg->value_zone = *value_zone;
1084
1085   /* transmit message */
1086   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
1087   do_transmit (h);
1088   return qe;
1089 }
1090
1091
1092 /**
1093  * Starts a new zone iteration (used to periodically PUT all of our
1094  * records into our DHT). This MUST lock the struct GNUNET_NAMESTORE_Handle
1095  * for any other calls than #GNUNET_NAMESTORE_zone_iterator_next and
1096  * #GNUNET_NAMESTORE_zone_iteration_stop. @a proc will be called once
1097  * immediately, and then again after
1098  * #GNUNET_NAMESTORE_zone_iterator_next is invoked.
1099  *
1100  * @param h handle to the namestore
1101  * @param zone zone to access, NULL for all zones
1102  * @param proc function to call on each name from the zone; it
1103  *        will be called repeatedly with a value (if available)
1104  *        and always once at the end with a name of NULL.
1105  * @param proc_cls closure for @a proc
1106  * @return an iterator handle to use for iteration
1107  */
1108 struct GNUNET_NAMESTORE_ZoneIterator *
1109 GNUNET_NAMESTORE_zone_iteration_start (struct GNUNET_NAMESTORE_Handle *h,
1110                                        const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
1111                                        GNUNET_NAMESTORE_RecordMonitor proc,
1112                                        void *proc_cls)
1113 {
1114   struct GNUNET_NAMESTORE_ZoneIterator *it;
1115   struct PendingMessage *pe;
1116   struct ZoneIterationStartMessage * msg;
1117   size_t msg_size;
1118   uint32_t rid;
1119
1120   GNUNET_assert (NULL != h);
1121   rid = get_op_id(h);
1122   it = GNUNET_new (struct GNUNET_NAMESTORE_ZoneIterator);
1123   it->h = h;
1124   it->proc = proc;
1125   it->proc_cls = proc_cls;
1126   it->op_id = rid;
1127   if (NULL != zone)
1128     it->zone = *zone;
1129   GNUNET_CONTAINER_DLL_insert_tail (h->z_head, h->z_tail, it);
1130
1131   msg_size = sizeof (struct ZoneIterationStartMessage);
1132   pe = GNUNET_malloc (sizeof (struct PendingMessage) + msg_size);
1133   pe->size = msg_size;
1134   msg = (struct ZoneIterationStartMessage *) &pe[1];
1135   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START);
1136   msg->gns_header.header.size = htons (msg_size);
1137   msg->gns_header.r_id = htonl (rid);
1138   if (NULL != zone)
1139     msg->zone = *zone;
1140   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
1141   do_transmit (h);
1142   return it;
1143 }
1144
1145
1146 /**
1147  * Calls the record processor specified in #GNUNET_NAMESTORE_zone_iteration_start
1148  * for the next record.
1149  *
1150  * @param it the iterator
1151  */
1152 void
1153 GNUNET_NAMESTORE_zone_iterator_next (struct GNUNET_NAMESTORE_ZoneIterator *it)
1154 {
1155   struct GNUNET_NAMESTORE_Handle *h;
1156   struct ZoneIterationNextMessage * msg;
1157   struct PendingMessage *pe;
1158   size_t msg_size;
1159
1160   GNUNET_assert (NULL != it);
1161   h = it->h;
1162   msg_size = sizeof (struct ZoneIterationNextMessage);
1163   pe = GNUNET_malloc (sizeof (struct PendingMessage) + msg_size);
1164   pe->size = msg_size;
1165   msg = (struct ZoneIterationNextMessage *) &pe[1];
1166   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT);
1167   msg->gns_header.header.size = htons (msg_size);
1168   msg->gns_header.r_id = htonl (it->op_id);
1169   LOG (GNUNET_ERROR_TYPE_DEBUG,
1170        "Sending `%s' message\n",
1171        "ZONE_ITERATION_NEXT");
1172   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
1173   do_transmit (h);
1174 }
1175
1176
1177 /**
1178  * Stops iteration and releases the namestore handle for further calls.
1179  *
1180  * @param it the iterator
1181  */
1182 void
1183 GNUNET_NAMESTORE_zone_iteration_stop (struct GNUNET_NAMESTORE_ZoneIterator *it)
1184 {
1185   struct GNUNET_NAMESTORE_Handle *h;
1186   struct PendingMessage *pe;
1187   size_t msg_size;
1188   struct ZoneIterationStopMessage * msg;
1189
1190   GNUNET_assert (NULL != it);
1191   h = it->h;
1192   GNUNET_CONTAINER_DLL_remove (h->z_head,
1193                                h->z_tail,
1194                                it);
1195   msg_size = sizeof (struct ZoneIterationStopMessage);
1196   pe = GNUNET_malloc (sizeof (struct PendingMessage) + msg_size);
1197   pe->size = msg_size;
1198   msg = (struct ZoneIterationStopMessage *) &pe[1];
1199   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP);
1200   msg->gns_header.header.size = htons (msg_size);
1201   msg->gns_header.r_id = htonl (it->op_id);
1202   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1203               "Sending `%s' message\n",
1204               "ZONE_ITERATION_STOP");
1205   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
1206   do_transmit (h);
1207   GNUNET_free (it);
1208 }
1209
1210
1211 /**
1212  * Cancel a namestore operation.  The final callback from the
1213  * operation must not have been done yet.
1214  *
1215  * @param qe operation to cancel
1216  */
1217 void
1218 GNUNET_NAMESTORE_cancel (struct GNUNET_NAMESTORE_QueueEntry *qe)
1219 {
1220   struct GNUNET_NAMESTORE_Handle *h = qe->nsh;
1221
1222   GNUNET_assert (NULL != qe);
1223   GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, qe);
1224   GNUNET_free(qe);
1225 }
1226
1227
1228 /* end of namestore_api.c */