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