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