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