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