corrected HELLO_ACK message size
[oweals/gnunet.git] / src / namestore / namestore_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010 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  */
27
28 #include "platform.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_crypto_lib.h"
31 #include "gnunet_constants.h"
32 #include "gnunet_dnsparser_lib.h"
33 #include "gnunet_arm_service.h"
34 #include "gnunet_signatures.h"
35 #include "gnunet_namestore_service.h"
36 #include "namestore.h"
37
38 #define DEBUG_GNS_API GNUNET_EXTRA_LOGGING
39
40 #define LOG(kind,...) GNUNET_log_from (kind, "gns-api",__VA_ARGS__)
41
42 /**
43  * A QueueEntry.
44  */
45 struct GNUNET_NAMESTORE_QueueEntry
46 {
47
48   /**
49    * Kept in a DLL.
50    */
51   struct GNUNET_NAMESTORE_QueueEntry *next;
52
53   /**
54    * Kept in a DLL.
55    */
56   struct GNUNET_NAMESTORE_QueueEntry *prev;
57
58   struct GNUNET_NAMESTORE_Handle *nsh;
59
60   uint32_t op_id;
61
62   GNUNET_NAMESTORE_ContinuationWithStatus cont;
63   void *cont_cls;
64
65   GNUNET_NAMESTORE_RecordProcessor proc;
66   void *proc_cls;
67
68   char *data; /*stub data pointer*/
69 };
70
71
72 /**
73  * Zone iterator
74  */
75 struct GNUNET_NAMESTORE_ZoneIterator
76 {
77
78   /**
79    * Kept in a DLL.
80    */
81   struct GNUNET_NAMESTORE_ZoneIterator *next;
82
83   /**
84    * Kept in a DLL.
85    */
86   struct GNUNET_NAMESTORE_ZoneIterator *prev;
87
88   uint32_t op_id;
89
90   struct GNUNET_NAMESTORE_Handle *h;
91   GNUNET_NAMESTORE_RecordProcessor proc;
92   void* proc_cls;
93   GNUNET_HashCode zone;
94   uint32_t no_flags;
95   uint32_t flags;
96   int has_zone;
97 };
98
99
100 /**
101  * Message in linked list we should send to the service.  The
102  * actual binary message follows this struct.
103  */
104 struct PendingMessage
105 {
106
107   /**
108    * Kept in a DLL.
109    */
110   struct PendingMessage *next;
111
112   /**
113    * Kept in a DLL.
114    */
115   struct PendingMessage *prev;
116
117   /**
118    * Size of the message.
119    */
120   size_t size;
121
122   /**
123    * Is this the 'START' message?
124    */
125   int is_init;
126 };
127
128
129 /**
130  * Connection to the NAMESTORE service.
131  */
132 struct GNUNET_NAMESTORE_Handle
133 {
134
135   /**
136    * Configuration to use.
137    */
138   const struct GNUNET_CONFIGURATION_Handle *cfg;
139
140   /**
141    * Socket (if available).
142    */
143   struct GNUNET_CLIENT_Connection *client;
144
145   /**
146    * Currently pending transmission request (or NULL).
147    */
148   struct GNUNET_CLIENT_TransmitHandle *th;
149
150   /**
151    * Reconnect task
152    */
153   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
154
155   /**
156    * Pending messages to send to the service
157    */
158
159   struct PendingMessage * pending_head;
160   struct PendingMessage * pending_tail;
161
162   /**
163    * Should we reconnect to service due to some serious error?
164    */
165   int reconnect;
166
167
168   /**
169    * Pending namestore queue entries
170    */
171   struct GNUNET_NAMESTORE_QueueEntry * op_head;
172   struct GNUNET_NAMESTORE_QueueEntry * op_tail;
173
174   uint32_t op_id;
175
176   /**
177    * Pending namestore zone iterator entries
178    */
179   struct GNUNET_NAMESTORE_ZoneIterator * z_head;
180   struct GNUNET_NAMESTORE_ZoneIterator * z_tail;
181 };
182
183 struct GNUNET_NAMESTORE_SimpleRecord
184 {
185   /**
186    * DLL
187    */
188   struct GNUNET_NAMESTORE_SimpleRecord *next;
189
190   /**
191    * DLL
192    */
193   struct GNUNET_NAMESTORE_SimpleRecord *prev;
194   
195   const char *name;
196   const GNUNET_HashCode *zone;
197   uint32_t record_type;
198   struct GNUNET_TIME_Absolute expiration;
199   enum GNUNET_NAMESTORE_RecordFlags flags;
200   size_t data_size;
201   const void *data;
202 };
203
204
205
206 /**
207  * Disconnect from service and then reconnect.
208  *
209  * @param h our handle
210  */
211 static void
212 force_reconnect (struct GNUNET_NAMESTORE_Handle *h);
213
214 static void
215 handle_lookup_name_response (struct GNUNET_NAMESTORE_QueueEntry *qe,
216                              struct LookupNameResponseMessage * msg,
217                              size_t size)
218 {
219   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' \n",
220               "LOOKUP_NAME_RESPONSE");
221
222   struct GNUNET_NAMESTORE_Handle *h = qe->nsh;
223
224   /* Operation done, remove */
225   GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, qe);
226
227
228   char *name;
229   char * rd_tmp;
230
231   struct GNUNET_CRYPTO_RsaSignature *signature = NULL;
232   struct GNUNET_TIME_Absolute expire;
233   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key_tmp;
234   size_t exp_msg_len;
235   size_t msg_len = 0;
236   size_t name_len = 0;
237   size_t rd_len = 0;
238   int contains_sig = GNUNET_NO;
239   int rd_count = 0;
240
241   rd_len = ntohs (msg->rd_len);
242   rd_count = ntohs (msg->rd_count);
243   msg_len = ntohs (msg->gns_header.header.size);
244   name_len = ntohs (msg->name_len);
245   contains_sig = ntohs (msg->contains_sig);
246   expire = GNUNET_TIME_absolute_ntoh(msg->expire);
247
248   exp_msg_len = sizeof (struct LookupNameResponseMessage) +
249       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
250       name_len + rd_len;
251
252   if (msg_len != exp_msg_len)
253   {
254     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message size describes with `%u' bytes but calculated size is %u bytes \n",
255                 msg_len, exp_msg_len);
256     GNUNET_break_op (0);
257     return;
258   }
259
260   name = (char *) &msg[1];
261   rd_tmp = &name[name_len];
262
263   /* deserialize records */
264   struct GNUNET_NAMESTORE_RecordData rd[rd_count];
265   if (GNUNET_OK != GNUNET_NAMESTORE_records_deserialize(rd_len, rd_tmp, rd_count, rd))
266   {
267     GNUNET_break_op (0);
268     return;
269   }
270
271
272   /* reset values if values not contained */
273   if (contains_sig == GNUNET_NO)
274     signature = NULL;
275   else
276     signature = &msg->signature;
277   if (name_len == 0)
278     name = NULL;
279
280   if (name != NULL)
281       public_key_tmp =  &msg->public_key;
282   else
283       public_key_tmp = NULL;
284
285   if (qe->proc != NULL)
286   {
287     qe->proc (qe->proc_cls, public_key_tmp, expire, name, rd_count, (rd_count > 0) ? rd : NULL, signature);
288   }
289   GNUNET_free (qe);
290 }
291
292
293 static void
294 handle_record_put_response (struct GNUNET_NAMESTORE_QueueEntry *qe,
295                              struct RecordPutResponseMessage* msg,
296                              size_t size)
297 {
298   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' \n",
299               "RECORD_PUT_RESPONSE");
300
301   struct GNUNET_NAMESTORE_Handle *h = qe->nsh;
302   /* Operation done, remove */
303   GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, qe);
304
305   int res = ntohl (msg->op_result);
306
307   if (res == GNUNET_OK)
308   {
309     if (qe->cont != NULL)
310     {
311       qe->cont (qe->cont_cls, res, _("Namestore added record successfully"));
312     }
313
314   }
315   else if (res == GNUNET_SYSERR)
316   {
317     if (qe->cont != NULL)
318     {
319       qe->cont (qe->cont_cls, res, _("Namestore failed to add record"));
320     }
321   }
322   else
323   {
324     GNUNET_break_op (0);
325     return;
326   }
327
328   GNUNET_free (qe);
329 }
330
331
332 static void
333 handle_record_create_response (struct GNUNET_NAMESTORE_QueueEntry *qe,
334                              struct RecordCreateResponseMessage* msg,
335                              size_t size)
336 {
337   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' \n",
338               "RECORD_CREATE_RESPONSE");
339
340   struct GNUNET_NAMESTORE_Handle *h = qe->nsh;
341   /* Operation done, remove */
342   GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, qe);
343
344   int res = ntohl (msg->op_result);
345   if (res == GNUNET_YES)
346   {
347     if (qe->cont != NULL)
348     {
349       qe->cont (qe->cont_cls, res, _("Namestore added record successfully"));
350     }
351
352   }
353   else if (res == GNUNET_NO)
354   {
355     if (qe->cont != NULL)
356     {
357       qe->cont (qe->cont_cls, res, _("Namestore record already existed"));
358     }
359   }
360   else
361   {
362     if (qe->cont != NULL)
363     {
364       qe->cont (qe->cont_cls, GNUNET_SYSERR, _("Namestore failed to add record\n"));
365     }
366   }
367
368   GNUNET_free (qe);
369 }
370
371
372 static void
373 handle_record_remove_response (struct GNUNET_NAMESTORE_QueueEntry *qe,
374                              struct RecordRemoveResponseMessage* msg,
375                              size_t size)
376 {
377   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' \n",
378               "RECORD_REMOVE_RESPONSE");
379
380   struct GNUNET_NAMESTORE_Handle *h = qe->nsh;
381   /* Operation done, remove */
382   GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, qe);
383
384   int res = ntohl (msg->op_result);
385   /**
386    *  result:
387    *  0 : successful
388    *  1 : No records for entry
389    *  2 : Could not find record to remove
390    *  3 : Failed to create new signature
391    *  4 : Failed to put new set of records in database
392    */
393   switch (res) {
394     case 0:
395       if (qe->cont != NULL)
396       {
397         qe->cont (qe->cont_cls, GNUNET_YES, _("Namestore removed record successfully"));
398       }
399
400       break;
401     case 1:
402       if (qe->cont != NULL)
403       {
404         qe->cont (qe->cont_cls, GNUNET_NO, _("No records for entry"));
405       }
406
407       break;
408     case 2:
409       if (qe->cont != NULL)
410       {
411         qe->cont (qe->cont_cls, GNUNET_NO, _("Could not find record to remove"));
412       }
413
414       break;
415     case 3:
416       if (qe->cont != NULL)
417       {
418         qe->cont (qe->cont_cls, GNUNET_SYSERR, _("Failed to create new signature"));
419       }
420
421       break;
422     case 4:
423       if (qe->cont != NULL)
424       {
425         qe->cont (qe->cont_cls, GNUNET_SYSERR, _("Failed to put new set of records in database"));
426       }
427       break;
428     default:
429         GNUNET_break_op (0);
430       break;
431   }
432
433   GNUNET_free (qe);
434 }
435
436 static void
437 handle_zone_to_name_response (struct GNUNET_NAMESTORE_QueueEntry *qe,
438                              struct ZoneToNameResponseMessage* msg,
439                              size_t size)
440 {
441   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' \n",
442               "ZONE_TO_NAME_RESPONSE");
443
444   struct GNUNET_NAMESTORE_Handle *h = qe->nsh;
445   /* Operation done, remove */
446   GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, qe);
447
448   int res = ntohs (msg->res);
449
450   struct GNUNET_TIME_Absolute expire;
451   size_t name_len;
452   size_t rd_ser_len;
453   unsigned int rd_count;
454
455   char * name_tmp;
456   char * rd_tmp;
457
458   if (res == GNUNET_SYSERR)
459   {
460     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "An error occured during zone to name operation\n");
461     if (qe->proc != NULL)
462       qe->proc (qe->proc_cls, NULL, GNUNET_TIME_absolute_get_zero(), NULL, 0, NULL, NULL);
463   }
464   else if (res == GNUNET_NO)
465   {
466       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Namestore has no result for zone to name mapping \n");
467       if (qe->proc != NULL)
468         qe->proc (qe->proc_cls, NULL, GNUNET_TIME_absolute_get_zero(), NULL, 0, NULL, NULL);
469   }
470   else if (res == GNUNET_YES)
471   {
472     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Namestore has result for zone to name mapping \n");
473
474     name_len = ntohs (msg->name_len);
475     rd_count = ntohs (msg->rd_count);
476     rd_ser_len = ntohs (msg->rd_len);
477     expire = GNUNET_TIME_absolute_ntoh(msg->expire);
478
479     name_tmp = (char *) &msg[1];
480     rd_tmp = &name_tmp[name_len];
481
482     struct GNUNET_NAMESTORE_RecordData rd[rd_count];
483     if (GNUNET_OK != GNUNET_NAMESTORE_records_deserialize(rd_ser_len, rd_tmp, rd_count, rd))
484     {
485       GNUNET_break_op (0);
486       return;
487     }
488
489     if (qe->proc != NULL)
490       qe->proc (qe->proc_cls, &msg->zone_key, expire, name_tmp, rd_count, rd, &msg->signature);
491   }
492   else
493     GNUNET_break_op (0);
494
495   GNUNET_free (qe);
496 }
497
498
499 static void
500 manage_record_operations (struct GNUNET_NAMESTORE_QueueEntry *qe,
501                           const struct GNUNET_MessageHeader *msg,
502                           int type, size_t size)
503 {
504
505   /* handle different message type */
506   switch (type) {
507     case GNUNET_MESSAGE_TYPE_NAMESTORE_LOOKUP_NAME_RESPONSE:
508         if (size < sizeof (struct LookupNameResponseMessage))
509         {
510           GNUNET_break_op (0);
511           break;
512         }
513         handle_lookup_name_response (qe, (struct LookupNameResponseMessage *) msg, size);
514       break;
515     case GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_PUT_RESPONSE:
516         if (size != sizeof (struct RecordPutResponseMessage))
517         {
518           GNUNET_break_op (0);
519           break;
520         }
521         handle_record_put_response (qe, (struct RecordPutResponseMessage *) msg, size);
522       break;
523     case GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_CREATE_RESPONSE:
524         if (size != sizeof (struct RecordCreateResponseMessage))
525         {
526           GNUNET_break_op (0);
527           break;
528         }
529         handle_record_create_response (qe, (struct RecordCreateResponseMessage *) msg, size);
530       break;
531     case GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_REMOVE_RESPONSE:
532         if (size != sizeof (struct RecordRemoveResponseMessage))
533         {
534           GNUNET_break_op (0);
535           break;
536         }
537         handle_record_remove_response (qe, (struct RecordRemoveResponseMessage *) msg, size);
538       break;
539     case GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE:
540         if (size < sizeof (struct ZoneToNameResponseMessage))
541         {
542           GNUNET_break_op (0);
543           break;
544         }
545         handle_zone_to_name_response (qe, (struct ZoneToNameResponseMessage *) msg, size);
546       break;
547     default:
548       GNUNET_break_op (0);
549       break;
550   }
551 }
552
553 static void
554 handle_zone_iteration_response (struct GNUNET_NAMESTORE_ZoneIterator *ze,
555                                 struct ZoneIterationResponseMessage *msg,
556                                 size_t size)
557 {
558   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' \n",
559               "ZONE_ITERATION_RESPONSE");
560
561   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pubdummy;
562   size_t msg_len = 0;
563   size_t exp_msg_len = 0;
564   size_t name_len = 0;
565   size_t rd_len = 0;
566   unsigned rd_count = 0;
567
568   char *name_tmp;
569   char *rd_ser_tmp;
570   struct GNUNET_TIME_Absolute expire;
571
572   msg_len = ntohs (msg->gns_header.header.size);
573   rd_len = ntohs (msg->rd_len);
574   rd_count = ntohs (msg->rd_count);
575   name_len = ntohs (msg->name_len);
576   expire = GNUNET_TIME_absolute_ntoh (msg->expire);
577
578   exp_msg_len = sizeof (struct ZoneIterationResponseMessage) + name_len + rd_len;
579   if (msg_len != exp_msg_len)
580   {
581     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message size describes with `%u' bytes but calculated size is %u bytes \n",
582                 msg_len, exp_msg_len);
583     GNUNET_break_op (0);
584     return;
585   }
586   if (0 != ntohs (msg->reserved))
587   {
588     GNUNET_break_op (0);
589     return;
590   }
591
592   memset (&pubdummy, '\0', sizeof (pubdummy));
593   if ((0 == name_len) && (0 == (memcmp (&msg->public_key, &pubdummy, sizeof (pubdummy)))))
594   {
595     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Zone iteration is completed!\n");
596
597     GNUNET_CONTAINER_DLL_remove(ze->h->z_head, ze->h->z_tail, ze);
598
599     if (ze->proc != NULL)
600       ze->proc(ze->proc_cls, NULL, GNUNET_TIME_absolute_get_zero (), NULL , 0, NULL, NULL);
601
602     GNUNET_free (ze);
603     return;
604   }
605
606   name_tmp = (char *) &msg[1];
607   if ((name_tmp[name_len -1] != '\0') || (name_len > 256))
608   {
609     GNUNET_break_op (0);
610     return;
611   }
612   rd_ser_tmp = (char *) &name_tmp[name_len];
613   struct GNUNET_NAMESTORE_RecordData rd[rd_count];
614   if (GNUNET_OK != GNUNET_NAMESTORE_records_deserialize (rd_len, rd_ser_tmp, rd_count, rd))
615   {
616     GNUNET_break_op (0);
617     return;
618   }
619
620   if (ze->proc != NULL)
621     ze->proc(ze->proc_cls, &msg->public_key, expire, name_tmp, rd_count, rd, &msg->signature);
622 }
623
624
625 static void
626 manage_zone_operations (struct GNUNET_NAMESTORE_ZoneIterator *ze,
627                         const struct GNUNET_MessageHeader *msg,
628                         int type, size_t size)
629 {
630
631   /* handle different message type */
632   switch (type) {
633     case GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_RESPONSE:
634         if (size < sizeof (struct ZoneIterationResponseMessage))
635         {
636           GNUNET_break_op (0);
637           break;
638         }
639         handle_zone_iteration_response (ze, (struct ZoneIterationResponseMessage *) msg, size);
640       break;
641     default:
642       GNUNET_break_op (0);
643       break;
644   }
645 }
646
647 /**
648  * Type of a function to call when we receive a message
649  * from the service.
650  *
651  * @param cls the 'struct GNUNET_NAMESTORE_SchedulingHandle'
652  * @param msg message received, NULL on timeout or fatal error
653  */
654 static void
655 process_namestore_message (void *cls, const struct GNUNET_MessageHeader *msg)
656 {
657   struct GNUNET_NAMESTORE_Handle *h = cls;
658   struct GNUNET_NAMESTORE_Header * gm;
659   struct GNUNET_NAMESTORE_QueueEntry *qe;
660   struct GNUNET_NAMESTORE_ZoneIterator *ze;
661   uint16_t size;
662   uint16_t type;
663   uint32_t r_id = UINT32_MAX;
664
665   if (NULL == msg)
666   {
667     force_reconnect (h);
668     return;
669   }
670
671   size = ntohs (msg->size);
672   type = ntohs (msg->type);
673
674   if (size < sizeof (struct GNUNET_NAMESTORE_Header))
675   {
676     GNUNET_break_op (0);
677     GNUNET_CLIENT_receive (h->client, &process_namestore_message, h,
678                            GNUNET_TIME_UNIT_FOREVER_REL);
679     return;
680   }
681
682   gm = (struct GNUNET_NAMESTORE_Header *) msg;
683   r_id = ntohl (gm->r_id);
684
685   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received message type %i size %i op %u\n", type, size, r_id);
686
687   /* Find matching operation */
688   if (r_id > h->op_id)
689   {
690     /* No matching pending operation found */
691     GNUNET_break_op (0);
692     GNUNET_CLIENT_receive (h->client, &process_namestore_message, h,
693                            GNUNET_TIME_UNIT_FOREVER_REL);
694     return;
695   }
696
697   /* Is it a record related operation ? */
698   for (qe = h->op_head; qe != NULL; qe = qe->next)
699   {
700     if (qe->op_id == r_id)
701       break;
702   }
703   if (qe != NULL)
704   {
705     manage_record_operations (qe, msg, type, size);
706   }
707
708   /* Is it a zone iteration operation ? */
709   for (ze = h->z_head; ze != NULL; ze = ze->next)
710   {
711     if (ze->op_id == r_id)
712       break;
713   }
714   if (ze != NULL)
715   {
716     manage_zone_operations (ze, msg, type, size);
717   }
718
719   GNUNET_CLIENT_receive (h->client, &process_namestore_message, h,
720                          GNUNET_TIME_UNIT_FOREVER_REL);
721
722   if (GNUNET_YES == h->reconnect)
723     force_reconnect (h);
724
725 }
726
727
728 /**
729  * Transmit messages from the message queue to the service
730  * (if there are any, and if we are not already trying).
731  *
732  * @param h handle to use
733  */
734 static void
735 do_transmit (struct GNUNET_NAMESTORE_Handle *h);
736
737
738 /**
739  * We can now transmit a message to NAMESTORE. Do it.
740  *
741  * @param cls the 'struct GNUNET_NAMESTORE_Handle'
742  * @param size number of bytes we can transmit
743  * @param buf where to copy the messages
744  * @return number of bytes copied into buf
745  */
746 static size_t
747 transmit_message_to_namestore (void *cls, size_t size, void *buf)
748 {
749   struct GNUNET_NAMESTORE_Handle *h = cls;
750   struct PendingMessage *p;
751   size_t ret;
752   char *cbuf;
753
754   h->th = NULL;
755   if ((size == 0) || (buf == NULL))
756   {
757     force_reconnect (h);
758     return 0;
759   }
760   ret = 0;
761   cbuf = buf;
762   while ((NULL != (p = h->pending_head)) && (p->size <= size))
763   {
764     memcpy (&cbuf[ret], &p[1], p->size);
765     ret += p->size;
766     size -= p->size;
767     GNUNET_CONTAINER_DLL_remove (h->pending_head, h->pending_tail, p);
768     if (GNUNET_YES == p->is_init)
769       GNUNET_CLIENT_receive (h->client, &process_namestore_message, h,
770                              GNUNET_TIME_UNIT_FOREVER_REL);
771     GNUNET_free (p);
772   }
773   do_transmit (h);
774   return ret;
775 }
776
777
778 /**
779  * Transmit messages from the message queue to the service
780  * (if there are any, and if we are not already trying).
781  *
782  * @param h handle to use
783  */
784 static void
785 do_transmit (struct GNUNET_NAMESTORE_Handle *h)
786 {
787   struct PendingMessage *p;
788
789   if (NULL != h->th)
790     return;
791   if (NULL == (p = h->pending_head))
792     return;
793   if (NULL == h->client)
794     return;                     /* currently reconnecting */
795
796   h->th = GNUNET_CLIENT_notify_transmit_ready (h->client, p->size,
797                                            GNUNET_TIME_UNIT_FOREVER_REL,
798                                            GNUNET_NO, &transmit_message_to_namestore,
799                                            h);
800 }
801
802
803 /**
804  * Reconnect to namestore service.
805  *
806  * @param h the handle to the namestore service
807  */
808 static void
809 reconnect (struct GNUNET_NAMESTORE_Handle *h)
810 {
811   struct PendingMessage *p;
812   struct StartMessage *init;
813
814   GNUNET_assert (NULL == h->client);
815   h->client = GNUNET_CLIENT_connect ("namestore", h->cfg);
816   GNUNET_assert (NULL != h->client);
817
818   if ((NULL == (p = h->pending_head)) || (GNUNET_YES != p->is_init))
819   {
820     p = GNUNET_malloc (sizeof (struct PendingMessage) +
821                        sizeof (struct StartMessage));
822     p->size = sizeof (struct StartMessage);
823     p->is_init = GNUNET_YES;
824     init = (struct StartMessage *) &p[1];
825     init->header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_START);
826     init->header.size = htons (sizeof (struct StartMessage));
827     GNUNET_CONTAINER_DLL_insert (h->pending_head, h->pending_tail, p);
828   }
829   do_transmit (h);
830 }
831
832 /**
833  * Re-establish the connection to the service.
834  *
835  * @param cls handle to use to re-connect.
836  * @param tc scheduler context
837  */
838 static void
839 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
840 {
841   struct GNUNET_NAMESTORE_Handle *h = cls;
842
843   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
844   reconnect (h);
845 }
846
847
848 /**
849  * Disconnect from service and then reconnect.
850  *
851  * @param h our handle
852  */
853 static void
854 force_reconnect (struct GNUNET_NAMESTORE_Handle *h)
855 {
856   h->reconnect = GNUNET_NO;
857   GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
858   h->client = NULL;
859   h->reconnect_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
860                                     &reconnect_task,
861                                     h);
862 }
863
864 static uint32_t
865 get_op_id (struct GNUNET_NAMESTORE_Handle *h)
866 {
867   uint32_t op_id = h->op_id;
868   h->op_id ++;
869   return op_id;
870 }
871
872 /**
873  * Initialize the connection with the NAMESTORE service.
874  *
875  * @param cfg configuration to use
876  * @return handle to the GNS service, or NULL on error
877  */
878 struct GNUNET_NAMESTORE_Handle *
879 GNUNET_NAMESTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
880 {
881   struct GNUNET_NAMESTORE_Handle *h;
882
883   h = GNUNET_malloc (sizeof (struct GNUNET_NAMESTORE_Handle));
884   h->cfg = cfg;
885   h->reconnect_task = GNUNET_SCHEDULER_add_now (&reconnect_task, h);
886   h->op_id = 0;
887   return h;
888 }
889
890 static void
891 clean_up_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
892 {
893   struct PendingMessage *p;
894   struct GNUNET_NAMESTORE_QueueEntry *q;
895   struct GNUNET_NAMESTORE_ZoneIterator *z;
896   struct GNUNET_NAMESTORE_Handle *h = cls;
897   GNUNET_assert (h != NULL);
898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n");
899   while (NULL != (p = h->pending_head))
900   {
901     GNUNET_CONTAINER_DLL_remove (h->pending_head, h->pending_tail, p);
902     GNUNET_free (p);
903   }
904
905   while (NULL != (q = h->op_head))
906   {
907     GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, q);
908     GNUNET_free (q);
909   }
910
911   while (NULL != (z = h->z_head))
912   {
913     GNUNET_CONTAINER_DLL_remove (h->z_head, h->z_tail, z);
914     GNUNET_free (z);
915   }
916
917   if (NULL != h->client)
918   {
919     GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
920     h->client = NULL;
921   }
922   if (GNUNET_SCHEDULER_NO_TASK != h->reconnect_task)
923   {
924     GNUNET_SCHEDULER_cancel (h->reconnect_task);
925     h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
926   }
927   GNUNET_free(h);
928   h = NULL;
929 };
930
931 /**
932  * Disconnect from the namestore service (and free associated
933  * resources).
934  *
935  * @param h handle to the namestore
936  * @param drop set to GNUNET_YES to delete all data in namestore (!)
937  */
938 void
939 GNUNET_NAMESTORE_disconnect (struct GNUNET_NAMESTORE_Handle *h, int drop)
940 {
941   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from namestore service\n");
942   GNUNET_SCHEDULER_add_now (&clean_up_task, h);
943 }
944
945
946 /**
947  * Store an item in the namestore.  If the item is already present,
948  * the expiration time is updated to the max of the existing time and
949  * the new time.  This API is used when we cache signatures from other
950  * authorities.
951  *
952  * @param h handle to the namestore
953  * @param zone_key public key of the zone
954  * @param name name that is being mapped (at most 255 characters long)
955  * @param expire when does the corresponding block in the DHT expire (until
956  *               when should we never do a DHT lookup for the same name again)?
957  * @param rd_count number of entries in 'rd' array
958  * @param rd array of records with data to store
959  * @param signature signature for all the records in the zone under the given name
960  * @param cont continuation to call when done
961  * @param cont_cls closure for cont
962  * @return handle to abort the request
963  */
964 struct GNUNET_NAMESTORE_QueueEntry *
965 GNUNET_NAMESTORE_record_put (struct GNUNET_NAMESTORE_Handle *h,
966                              const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
967                              const char *name,
968                              struct GNUNET_TIME_Absolute expire,
969                              unsigned int rd_count,
970                              const struct GNUNET_NAMESTORE_RecordData *rd,
971                              const struct GNUNET_CRYPTO_RsaSignature *signature,
972                              GNUNET_NAMESTORE_ContinuationWithStatus cont,
973                              void *cont_cls)
974 {
975   struct GNUNET_NAMESTORE_QueueEntry *qe;
976   struct PendingMessage *pe;
977
978   /* pointer to elements */
979   char * rd_tmp;
980   char * name_tmp;
981
982   size_t msg_size = 0;
983   size_t name_len = 0;
984   size_t rd_ser_len = 0;
985   uint32_t rid = 0;
986
987   GNUNET_assert (NULL != h);
988   GNUNET_assert (NULL != zone_key);
989   GNUNET_assert (NULL != name);
990   GNUNET_assert (NULL != rd);
991   GNUNET_assert (NULL != signature);
992
993   name_len = strlen(name) + 1;
994   if (name_len > 256)
995   {
996     GNUNET_break (0);
997     return NULL;
998   }
999
1000   rid = get_op_id(h);
1001   qe = GNUNET_malloc(sizeof (struct GNUNET_NAMESTORE_QueueEntry));
1002   qe->nsh = h;
1003   qe->cont = cont;
1004   qe->cont_cls = cont_cls;
1005   qe->op_id = rid;
1006   GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, qe);
1007
1008   /* set msg_size*/
1009   rd_ser_len = GNUNET_NAMESTORE_records_get_size(rd_count, rd);
1010   char rd_ser[rd_ser_len];
1011   GNUNET_NAMESTORE_records_serialize(rd_count, rd, rd_ser_len, rd_ser);
1012
1013   struct RecordPutMessage * msg;
1014   msg_size = sizeof (struct RecordPutMessage) + name_len  + rd_ser_len;
1015
1016   /* create msg here */
1017   pe = GNUNET_malloc(sizeof (struct PendingMessage) + msg_size);
1018   pe->size = msg_size;
1019   pe->is_init = GNUNET_NO;
1020   msg = (struct RecordPutMessage *) &pe[1];
1021   name_tmp = (char *) &msg[1];
1022   rd_tmp = &name_tmp[name_len];
1023
1024   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_PUT);
1025   msg->gns_header.header.size = htons (msg_size);
1026   msg->gns_header.r_id = htonl (rid);
1027   msg->signature = *signature;
1028   msg->name_len = htons (name_len);
1029   msg->expire = GNUNET_TIME_absolute_hton (expire);
1030   msg->rd_len = htons (rd_ser_len);
1031   msg->rd_count = htons (rd_count);
1032
1033   msg->public_key = *zone_key;
1034   memcpy (name_tmp, name, name_len);
1035   memcpy (rd_tmp, rd_ser, rd_ser_len);
1036
1037   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message for name `%s' with size %u\n", "NAMESTORE_RECORD_PUT", name, msg_size);
1038
1039   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
1040   do_transmit(h);
1041
1042   return qe;
1043 }
1044
1045
1046 /**
1047  * Check if a signature is valid.  This API is used by the GNS Block
1048  * to validate signatures received from the network.
1049  *
1050  * @param public_key public key of the zone
1051  * @param name name that is being mapped (at most 255 characters long)
1052  * @param rd_count number of entries in 'rd' array
1053  * @param rd array of records with data to store
1054  * @param signature signature for all the records in the zone under the given name
1055  * @return GNUNET_OK if the signature is valid
1056  */
1057 int
1058 GNUNET_NAMESTORE_verify_signature (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key,
1059                                    const char *name,
1060                                    unsigned int rd_count,
1061                                    const struct GNUNET_NAMESTORE_RecordData *rd,
1062                                    const struct GNUNET_CRYPTO_RsaSignature *signature)
1063 {
1064   int res = GNUNET_SYSERR;
1065   size_t rd_ser_len = 0;
1066   size_t name_len = 0;
1067   char * name_tmp;
1068   char * rd_tmp;
1069   struct GNUNET_CRYPTO_RsaSignaturePurpose *sig_purpose;
1070
1071   GNUNET_assert (public_key != NULL);
1072   GNUNET_assert (name != NULL);
1073   GNUNET_assert (rd != NULL);
1074   GNUNET_assert (signature != NULL);
1075
1076
1077   rd_ser_len = GNUNET_NAMESTORE_records_get_size(rd_count, rd);
1078   char rd_ser[rd_ser_len];
1079   GNUNET_NAMESTORE_records_serialize(rd_count, rd, rd_ser_len, rd_ser);
1080
1081   name_len = strlen (name) + 1;
1082   if (name_len > 256)
1083   {
1084     GNUNET_break (0);
1085     return GNUNET_SYSERR;
1086   }
1087
1088   sig_purpose = GNUNET_malloc(sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) + rd_ser_len + name_len);
1089   sig_purpose->size = htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)+ rd_ser_len + name_len);
1090   sig_purpose->purpose = htonl (GNUNET_SIGNATURE_PURPOSE_GNS_RECORD_SIGN);
1091   name_tmp = (char *) &sig_purpose[1];
1092   rd_tmp = &name_tmp[name_len];
1093   memcpy (name_tmp, name, name_len);
1094   memcpy (rd_tmp, rd_ser, rd_ser_len);
1095
1096   res = GNUNET_CRYPTO_rsa_verify(GNUNET_SIGNATURE_PURPOSE_GNS_RECORD_SIGN, sig_purpose, signature, public_key);
1097
1098   GNUNET_free (sig_purpose);
1099
1100   return res;
1101 }
1102
1103 /**
1104  * Store an item in the namestore.  If the item is already present,
1105  * the expiration time is updated to the max of the existing time and
1106  * the new time.  This API is used by the authority of a zone.
1107  *
1108  * @param h handle to the namestore
1109  * @param pkey private key of the zone
1110  * @param expire block expiration time
1111  * @param name name that is being mapped (at most 255 characters long)
1112  * @param rd record data to store
1113  * @param cont continuation to call when done
1114  * @param cont_cls closure for cont
1115  * @return handle to abort the request
1116  */
1117 struct GNUNET_NAMESTORE_QueueEntry *
1118 GNUNET_NAMESTORE_record_create (struct GNUNET_NAMESTORE_Handle *h,
1119                                 const struct GNUNET_CRYPTO_RsaPrivateKey *pkey,
1120                                 const char *name,
1121                                 const struct GNUNET_NAMESTORE_RecordData *rd,
1122                                 GNUNET_NAMESTORE_ContinuationWithStatus cont,
1123                                 void *cont_cls)
1124 {
1125   struct GNUNET_NAMESTORE_QueueEntry *qe;
1126   struct PendingMessage *pe;
1127   char * name_tmp;
1128   char * pkey_tmp;
1129   char * rd_tmp;
1130   size_t rd_ser_len = 0;
1131   size_t msg_size = 0;
1132   size_t name_len = 0;
1133   size_t key_len = 0;
1134   uint32_t rid = 0;
1135
1136   GNUNET_assert (NULL != h);
1137   GNUNET_assert (NULL != pkey);
1138   GNUNET_assert (NULL != name);
1139   GNUNET_assert (NULL != rd);
1140
1141   name_len = strlen(name) + 1;
1142   if (name_len > 256)
1143   {
1144     GNUNET_break (0);
1145     return NULL;
1146   }
1147
1148   rid = get_op_id(h);
1149   qe = GNUNET_malloc(sizeof (struct GNUNET_NAMESTORE_QueueEntry));
1150   qe->nsh = h;
1151   qe->cont = cont;
1152   qe->cont_cls = cont_cls;
1153   qe->op_id = rid;
1154   GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, qe);
1155
1156   /* set msg_size*/
1157   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded * pkey_enc = GNUNET_CRYPTO_rsa_encode_key (pkey);
1158   GNUNET_assert (pkey_enc != NULL);
1159   key_len = ntohs (pkey_enc->len);
1160
1161   rd_ser_len = GNUNET_NAMESTORE_records_get_size(1, rd);
1162   char rd_ser[rd_ser_len];
1163   GNUNET_NAMESTORE_records_serialize(1, rd, rd_ser_len, rd_ser);
1164
1165   struct RecordCreateMessage * msg;
1166   msg_size = sizeof (struct RecordCreateMessage) + key_len + name_len + rd_ser_len;
1167
1168   /* create msg here */
1169   pe = GNUNET_malloc(sizeof (struct PendingMessage) + msg_size);
1170   pe->size = msg_size;
1171   pe->is_init = GNUNET_NO;
1172   msg = (struct RecordCreateMessage *) &pe[1];
1173
1174   pkey_tmp = (char *) &msg[1];
1175   name_tmp = &pkey_tmp[key_len];
1176   rd_tmp = &name_tmp[name_len];
1177
1178   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_CREATE);
1179   msg->gns_header.header.size = htons (msg_size);
1180   msg->gns_header.r_id = htonl (rid);
1181   msg->name_len = htons (name_len);
1182   msg->rd_count = htons (1);
1183   msg->rd_len = htons (rd_ser_len);
1184   msg->pkey_len = htons (key_len);
1185   msg->expire = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
1186   memcpy (pkey_tmp, pkey_enc, key_len);
1187   memcpy (name_tmp, name, name_len);
1188   memcpy (rd_tmp, rd_ser, rd_ser_len);
1189   GNUNET_free (pkey_enc);
1190
1191   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message for name `%s' with size %u\n", "NAMESTORE_RECORD_CREATE", name, msg_size);
1192
1193   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
1194   do_transmit(h);
1195   return qe;
1196 }
1197
1198
1199 /**
1200  * Explicitly remove some content from the database.  The
1201  * "cont"inuation will be called with status "GNUNET_OK" if content
1202  * was removed, "GNUNET_NO" if no matching entry was found and
1203  * "GNUNET_SYSERR" on all other types of errors.
1204  * This API is used by the authority of a zone.
1205  *
1206  * @param h handle to the namestore
1207  * @param pkey private key of the zone
1208  * @param name name that is being mapped (at most 255 characters long)
1209  * @param rd record data
1210  * @param cont continuation to call when done
1211  * @param cont_cls closure for cont
1212  * @return handle to abort the request
1213  */
1214 struct GNUNET_NAMESTORE_QueueEntry *
1215 GNUNET_NAMESTORE_record_remove (struct GNUNET_NAMESTORE_Handle *h,
1216                                 const struct GNUNET_CRYPTO_RsaPrivateKey *pkey,
1217                                 const char *name,
1218                                 const struct GNUNET_NAMESTORE_RecordData *rd,
1219                                 GNUNET_NAMESTORE_ContinuationWithStatus cont,
1220                                 void *cont_cls)
1221 {
1222   struct GNUNET_NAMESTORE_QueueEntry *qe;
1223   struct PendingMessage *pe;
1224   char *pkey_tmp;
1225   char *rd_tmp;
1226   char *name_tmp;
1227   size_t rd_ser_len = 0;
1228   size_t msg_size = 0;
1229   size_t name_len = 0;
1230   size_t key_len = 0;
1231   uint32_t rid = 0;
1232
1233   GNUNET_assert (NULL != h);
1234
1235   rid = get_op_id(h);
1236   qe = GNUNET_malloc(sizeof (struct GNUNET_NAMESTORE_QueueEntry));
1237   qe->nsh = h;
1238   qe->cont = cont;
1239   qe->cont_cls = cont_cls;
1240   qe->op_id = rid;
1241   GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, qe);
1242
1243   /* set msg_size*/
1244   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded * pkey_enc = GNUNET_CRYPTO_rsa_encode_key (pkey);
1245   GNUNET_assert (pkey_enc != NULL);
1246   key_len = ntohs (pkey_enc->len);
1247
1248   rd_ser_len = GNUNET_NAMESTORE_records_get_size(1, rd);
1249   char rd_ser[rd_ser_len];
1250   GNUNET_NAMESTORE_records_serialize(1, rd, rd_ser_len, rd_ser);
1251
1252   name_len = strlen (name) + 1;
1253
1254   struct RecordRemoveMessage * msg;
1255   msg_size = sizeof (struct RecordRemoveMessage) + key_len + name_len + rd_ser_len;
1256
1257   /* create msg here */
1258   pe = GNUNET_malloc(sizeof (struct PendingMessage) + msg_size);
1259   pe->size = msg_size;
1260   pe->is_init = GNUNET_NO;
1261   msg = (struct RecordRemoveMessage *) &pe[1];
1262
1263   pkey_tmp = (char *) &msg[1];
1264   name_tmp = &pkey_tmp[key_len];
1265   rd_tmp = &name_tmp[name_len];
1266
1267   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_REMOVE);
1268   msg->gns_header.header.size = htons (msg_size);
1269   msg->gns_header.r_id = htonl (rid);
1270   msg->name_len = htons (name_len);
1271   msg->rd_len = htons (rd_ser_len);
1272   msg->rd_count = htons (1);
1273   msg->pkey_len = htons (key_len);
1274   memcpy (pkey_tmp, pkey_enc, key_len);
1275   memcpy (name_tmp, name, name_len);
1276   memcpy (rd_tmp, rd_ser, rd_ser_len);
1277
1278   GNUNET_free (pkey_enc);
1279
1280   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message for name `%s' with size %u\n", "NAMESTORE_RECORD_REMOVE", name, msg_size);
1281
1282   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
1283   do_transmit(h);
1284   return qe;
1285 }
1286
1287
1288 /**
1289  * Get a result for a particular key from the namestore.  The processor
1290  * will only be called once.  
1291  *
1292  * @param h handle to the namestore
1293  * @param zone zone to look up a record from
1294  * @param name name to look up
1295  * @param record_type desired record type, 0 for all
1296  * @param proc function to call on the matching records, or with
1297  *        NULL (rd_count == 0) if there are no matching records
1298  * @param proc_cls closure for proc
1299  * @return a handle that can be used to
1300  *         cancel
1301  */
1302 struct GNUNET_NAMESTORE_QueueEntry *
1303 GNUNET_NAMESTORE_lookup_record (struct GNUNET_NAMESTORE_Handle *h, 
1304                               const GNUNET_HashCode *zone,
1305                               const char *name,
1306                               uint32_t record_type,
1307                               GNUNET_NAMESTORE_RecordProcessor proc, void *proc_cls)
1308 {
1309   struct GNUNET_NAMESTORE_QueueEntry *qe;
1310   struct PendingMessage *pe;
1311   size_t msg_size = 0;
1312   size_t name_len = 0;
1313   uint32_t rid = 0;
1314
1315   GNUNET_assert (NULL != h);
1316   GNUNET_assert (NULL != zone);
1317   GNUNET_assert (NULL != name);
1318
1319   name_len = strlen (name) + 1;
1320   if ((name_len == 0) || (name_len > 256))
1321   {
1322     GNUNET_break (0);
1323     return NULL;
1324   }
1325
1326   rid = get_op_id(h);
1327   qe = GNUNET_malloc(sizeof (struct GNUNET_NAMESTORE_QueueEntry));
1328   qe->nsh = h;
1329   qe->proc = proc;
1330   qe->proc_cls = proc_cls;
1331   qe->op_id = rid;
1332   GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, qe);
1333
1334   /* set msg_size*/
1335   msg_size = sizeof (struct LookupNameMessage) + name_len;
1336   pe = GNUNET_malloc(sizeof (struct PendingMessage) + msg_size);
1337
1338   /* create msg here */
1339   struct LookupNameMessage * msg;
1340   pe->size = msg_size;
1341   pe->is_init = GNUNET_NO;
1342   msg = (struct LookupNameMessage *) &pe[1];
1343   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_LOOKUP_NAME);
1344   msg->gns_header.header.size = htons (msg_size);
1345   msg->gns_header.r_id = htonl (rid);
1346   msg->record_type = htonl (record_type);
1347   msg->name_len = htonl (name_len);
1348   msg->zone = *zone;
1349   memcpy (&msg[1], name, name_len);
1350
1351   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message for name `%s'\n", "NAMESTORE_LOOKUP_NAME", name);
1352
1353   /* transmit message */
1354   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
1355   do_transmit(h);
1356
1357   return qe;
1358 }
1359
1360
1361 /**
1362  * Look for an existing PKEY delegation record for a given public key.
1363  * Returns at most one result to the processor.
1364  *
1365  * @param h handle to the namestore
1366  * @param zone hash of public key of the zone to look up in, never NULL
1367  * @param value_zone hash of the public key of the target zone (value), never NULL
1368  * @param proc function to call on the matching records, or with
1369  *        NULL (rd_count == 0) if there are no matching records
1370  * @param proc_cls closure for proc
1371  * @return a handle that can be used to
1372  *         cancel
1373  */
1374 struct GNUNET_NAMESTORE_QueueEntry *
1375 GNUNET_NAMESTORE_zone_to_name (struct GNUNET_NAMESTORE_Handle *h,
1376                                const GNUNET_HashCode *zone,
1377                                const GNUNET_HashCode *value_zone,
1378                                GNUNET_NAMESTORE_RecordProcessor proc, void *proc_cls)
1379 {
1380   struct GNUNET_NAMESTORE_QueueEntry *qe;
1381   struct PendingMessage *pe;
1382   size_t msg_size = 0;
1383   uint32_t rid = 0;
1384
1385   GNUNET_assert (NULL != h);
1386   GNUNET_assert (NULL != zone);
1387   GNUNET_assert (NULL != value_zone);
1388
1389   rid = get_op_id(h);
1390   qe = GNUNET_malloc(sizeof (struct GNUNET_NAMESTORE_QueueEntry));
1391   qe->nsh = h;
1392   qe->proc = proc;
1393   qe->proc_cls = proc_cls;
1394   qe->op_id = rid;
1395   GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, qe);
1396
1397   /* set msg_size*/
1398   msg_size = sizeof (struct ZoneToNameMessage);
1399   pe = GNUNET_malloc(sizeof (struct PendingMessage) + msg_size);
1400
1401   /* create msg here */
1402   struct ZoneToNameMessage * msg;
1403   pe->size = msg_size;
1404   pe->is_init = GNUNET_NO;
1405   msg = (struct ZoneToNameMessage *) &pe[1];
1406   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME);
1407   msg->gns_header.header.size = htons (msg_size);
1408   msg->gns_header.r_id = htonl (rid);
1409   msg->zone = *zone;
1410   msg->value_zone = *value_zone;
1411
1412   char * z_tmp = strdup (GNUNET_h2s (zone));
1413   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message for zone `%s' in zone `%s'\n",
1414       "NAMESTORE_ZONE_TO_NAME",
1415       z_tmp,
1416       GNUNET_h2s (value_zone));
1417   GNUNET_free (z_tmp);
1418
1419   /* transmit message */
1420   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
1421   do_transmit(h);
1422
1423   return qe;
1424 }
1425
1426
1427
1428 /**
1429  * Starts a new zone iteration (used to periodically PUT all of our
1430  * records into our DHT). This MUST lock the GNUNET_NAMESTORE_Handle
1431  * for any other calls than GNUNET_NAMESTORE_zone_iterator_next and
1432  * GNUNET_NAMESTORE_zone_iteration_stop.  "proc" will be called once
1433  * immediately, and then again after
1434  * "GNUNET_NAMESTORE_zone_iterator_next" is invoked.
1435  *
1436  * @param h handle to the namestore
1437  * @param zone zone to access, NULL for all zones
1438  * @param must_have_flags flags that must be set for the record to be returned
1439  * @param must_not_have_flags flags that must NOT be set for the record to be returned
1440  * @param proc function to call on each name from the zone; it
1441  *        will be called repeatedly with a value (if available)
1442  *        and always once at the end with a name of NULL.
1443  * @param proc_cls closure for proc
1444  * @return an iterator handle to use for iteration
1445  */
1446 struct GNUNET_NAMESTORE_ZoneIterator *
1447 GNUNET_NAMESTORE_zone_iteration_start (struct GNUNET_NAMESTORE_Handle *h,
1448                                        const GNUNET_HashCode *zone,
1449                                        enum GNUNET_NAMESTORE_RecordFlags must_have_flags,
1450                                        enum GNUNET_NAMESTORE_RecordFlags must_not_have_flags,
1451                                        GNUNET_NAMESTORE_RecordProcessor proc,
1452                                        void *proc_cls)
1453 {
1454   struct GNUNET_NAMESTORE_ZoneIterator *it;
1455   struct PendingMessage *pe;
1456   size_t msg_size = 0;
1457   uint32_t rid = 0;
1458
1459   GNUNET_assert (NULL != h);
1460
1461
1462   rid = get_op_id(h);
1463   it = GNUNET_malloc (sizeof (struct GNUNET_NAMESTORE_ZoneIterator));
1464   it->h = h;
1465   it->proc = proc;
1466   it->proc_cls = proc;
1467   it->op_id = rid;
1468
1469   if (NULL != zone)
1470   {
1471     it->zone = *zone;
1472     it->has_zone = GNUNET_YES;
1473   }
1474   else
1475   {
1476     memset (&it->zone, '\0', sizeof (it->zone));
1477     it->has_zone = GNUNET_NO;
1478   }
1479   GNUNET_CONTAINER_DLL_insert_tail(h->z_head, h->z_tail, it);
1480
1481   /* set msg_size*/
1482   msg_size = sizeof (struct ZoneIterationStartMessage);
1483   pe = GNUNET_malloc(sizeof (struct PendingMessage) + msg_size);
1484
1485   /* create msg here */
1486   struct ZoneIterationStartMessage * msg;
1487   pe->size = msg_size;
1488   pe->is_init = GNUNET_NO;
1489   msg = (struct ZoneIterationStartMessage *) &pe[1];
1490   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START);
1491   msg->gns_header.header.size = htons (msg_size);
1492   msg->gns_header.r_id = htonl (rid);
1493   if (NULL != zone)
1494   {
1495     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message for zone `%s'\n", "ZONE_ITERATION_START", GNUNET_h2s(zone));
1496     msg->zone = *zone;
1497   }
1498   else
1499   {
1500     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message for all zones\n", "ZONE_ITERATION_START");
1501     memset (&msg->zone, '\0', sizeof (msg->zone));
1502   }
1503   msg->must_have_flags = ntohs (must_have_flags);
1504   msg->must_not_have_flags = ntohs (must_not_have_flags);
1505
1506
1507
1508   /* transmit message */
1509   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
1510   do_transmit(h);
1511
1512   return it;
1513 }
1514
1515
1516 /**
1517  * Calls the record processor specified in GNUNET_NAMESTORE_zone_iteration_start
1518  * for the next record.
1519  *
1520  * @param it the iterator
1521  */
1522 void
1523 GNUNET_NAMESTORE_zone_iterator_next (struct GNUNET_NAMESTORE_ZoneIterator *it)
1524 {
1525   struct GNUNET_NAMESTORE_Handle *h;
1526   struct PendingMessage *pe;
1527   size_t msg_size = 0;
1528
1529   GNUNET_assert (NULL != it);
1530   h = it->h;
1531
1532   /* set msg_size*/
1533   msg_size = sizeof (struct ZoneIterationNextMessage);
1534   pe = GNUNET_malloc(sizeof (struct PendingMessage) + msg_size);
1535
1536   /* create msg here */
1537   struct ZoneIterationNextMessage * msg;
1538   pe->size = msg_size;
1539   pe->is_init = GNUNET_NO;
1540   msg = (struct ZoneIterationNextMessage *) &pe[1];
1541   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT);
1542   msg->gns_header.header.size = htons (msg_size);
1543   msg->gns_header.r_id = htonl (it->op_id);
1544
1545   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message\n", "ZONE_ITERATION_NEXT");
1546
1547   /* transmit message */
1548   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
1549   do_transmit(h);
1550 }
1551
1552
1553 /**
1554  * Stops iteration and releases the namestore handle for further calls.
1555  *
1556  * @param it the iterator
1557  */
1558 void
1559 GNUNET_NAMESTORE_zone_iteration_stop (struct GNUNET_NAMESTORE_ZoneIterator *it)
1560 {
1561   GNUNET_assert (NULL != it);
1562   struct PendingMessage *pe;
1563   size_t msg_size = 0;
1564   struct GNUNET_NAMESTORE_Handle *h = it->h;
1565
1566   /* set msg_size*/
1567   msg_size = sizeof (struct ZoneIterationStopMessage);
1568   pe = GNUNET_malloc(sizeof (struct PendingMessage) + msg_size);
1569
1570   /* create msg here */
1571   struct ZoneIterationStopMessage * msg;
1572   pe->size = msg_size;
1573   pe->is_init = GNUNET_NO;
1574   msg = (struct ZoneIterationStopMessage *) &pe[1];
1575   msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP);
1576   msg->gns_header.header.size = htons (msg_size);
1577   msg->gns_header.r_id = htonl (it->op_id);
1578
1579   if (GNUNET_YES == it->has_zone)
1580     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message for zone `%s'\n", "ZONE_ITERATION_STOP", GNUNET_h2s(&it->zone));
1581   else
1582     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message for all zones\n", "ZONE_ITERATION_STOP");
1583
1584   /* transmit message */
1585   GNUNET_CONTAINER_DLL_insert_tail (h->pending_head, h->pending_tail, pe);
1586   do_transmit(h);
1587 }
1588
1589
1590 /**
1591  * Cancel a namestore operation.  The final callback from the
1592  * operation must not have been done yet.
1593  *
1594  * @param qe operation to cancel
1595  */
1596 void
1597 GNUNET_NAMESTORE_cancel (struct GNUNET_NAMESTORE_QueueEntry *qe)
1598 {
1599   struct GNUNET_NAMESTORE_Handle *h = qe->nsh;
1600
1601   GNUNET_assert (qe != NULL);
1602
1603   GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, qe);
1604   GNUNET_free(qe);
1605
1606 }
1607
1608 /* end of namestore_api.c */