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