- max name len
[oweals/gnunet.git] / src / gns / gnunet-service-gns.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011 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  *
23  * @file gns/gnunet-service-gns.c
24  * @brief GNUnet GNS service
25  * @author Martin Schanzenbach
26  */
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_transport_service.h"
30 #include "gnunet_dns_service.h"
31 #include "gnunet_dnsparser_lib.h"
32 #include "gnunet_dht_service.h"
33 #include "gnunet_namestore_service.h"
34 #include "gnunet_gns_service.h"
35 #include "block_gns.h"
36 #include "gns.h"
37 #include "gnunet-service-gns_resolver.h"
38 #include "gnunet-service-gns_interceptor.h"
39
40 /* FIXME move to proper header in include */
41 #define GNUNET_MESSAGE_TYPE_GNS_LOOKUP 23
42 #define GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT 24
43 #define GNUNET_MESSAGE_TYPE_GNS_SHORTEN 25
44 #define GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT 26
45 #define GNUNET_MESSAGE_TYPE_GNS_GET_AUTH 27
46 #define GNUNET_MESSAGE_TYPE_GNS_GET_AUTH_RESULT 28
47
48
49 /**
50  * Handle to a shorten operation from api
51  */
52 struct ClientShortenHandle
53 {
54   /* the requesting client that */
55   struct GNUNET_SERVER_Client *client;
56
57   /* request id */
58   uint64_t unique_id;
59
60   /* request type */
61   enum GNUNET_GNS_RecordType type;
62
63   /* name to shorten */
64   char* name;
65
66 };
67
68
69 /**
70  * Handle to a get auhtority operation from api
71  */
72 struct ClientGetAuthHandle
73 {
74   /* the requesting client that */
75   struct GNUNET_SERVER_Client *client;
76
77   /* request id */
78   uint64_t unique_id;
79
80   /* name to lookup authority */
81   char* name;
82
83 };
84
85
86 /**
87  * Handle to a lookup operation from api
88  */
89 struct ClientLookupHandle
90 {
91   /* the requesting client that */
92   struct GNUNET_SERVER_Client *client;
93
94   /* request id */
95   uint64_t unique_id;
96
97   /* request type */
98   enum GNUNET_GNS_RecordType type;
99
100   /* the name to look up */
101   char* name; //Needed?
102 };
103
104 /**
105  * Our handle to the DHT
106  */
107 static struct GNUNET_DHT_Handle *dht_handle;
108
109 /**
110  * Our zone's private key
111  */
112 struct GNUNET_CRYPTO_RsaPrivateKey *zone_key;
113
114 /**
115  * Our handle to the namestore service
116  * FIXME maybe need a second handle for iteration
117  */
118 struct GNUNET_NAMESTORE_Handle *namestore_handle;
119
120 /**
121  * Handle to iterate over our authoritative zone in namestore
122  */
123 struct GNUNET_NAMESTORE_ZoneIterator *namestore_iter;
124
125 /**
126  * The configuration the GNS service is running with
127  */
128 const struct GNUNET_CONFIGURATION_Handle *GNS_cfg;
129
130 /**
131  * Our notification context.
132  */
133 static struct GNUNET_SERVER_NotificationContext *nc;
134
135 /**
136  * Our zone hash
137  */
138 struct GNUNET_CRYPTO_ShortHashCode zone_hash;
139
140 /**
141  * Useful for zone update for DHT put
142  */
143 static int num_public_records =  3600;
144
145 /**
146  * update interval in seconds
147  */
148 static unsigned long long int dht_max_update_interval;
149
150 /* dht update interval FIXME define? */
151 static struct GNUNET_TIME_Relative dht_update_interval;
152
153 /* zone update task */
154 GNUNET_SCHEDULER_TaskIdentifier zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;
155
156 /* automatic pkey import for name shortening */
157 static int auto_import_pkey;
158
159 /* lookup timeout */
160 static struct GNUNET_TIME_Relative default_lookup_timeout;
161
162 /**
163  * Continue shutdown
164  */
165 static void
166 on_resolver_cleanup(void)
167 {
168   GNUNET_NAMESTORE_disconnect(namestore_handle, 1);
169   GNUNET_DHT_disconnect(dht_handle);
170 }
171
172 /**
173  * Task run during shutdown.
174  *
175  * @param cls unused
176  * @param tc unused
177  */
178 static void
179 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
180 {
181
182   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
183              "Shutting down!");
184   /* Kill zone task for it may make the scheduler hang */
185   if (zone_update_taskid)
186     GNUNET_SCHEDULER_cancel(zone_update_taskid);
187   
188   GNUNET_SERVER_notification_context_destroy (nc);
189   
190   gns_interceptor_stop();
191   gns_resolver_cleanup(&on_resolver_cleanup);
192
193 }
194
195
196 /**
197  * Method called periodicattluy that triggers
198  * iteration over root zone
199  *
200  * @param cls closure
201  * @param tc task context
202  */
203 static void
204 update_zone_dht_next(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
205 {
206   GNUNET_NAMESTORE_zone_iterator_next(namestore_iter);
207 }
208
209 /**
210  * Continuation for DHT put
211  *
212  * @param cls closure
213  * @param tc task context
214  */
215 static void
216 record_dht_put(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
217 {
218   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "put request transmitted\n");
219 }
220
221 /* prototype */
222 static void
223 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
224
225 /**
226  * Function used to put all records successively into the DHT.
227  *
228  * @param cls the closure (NULL)
229  * @param key the public key of the authority (ours)
230  * @param expiration lifetime of the namestore entry
231  * @param name the name of the records
232  * @param rd_count the number of records in data
233  * @param rd the record data
234  * @param signature the signature for the record data
235  */
236 static void
237 put_gns_record(void *cls,
238                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
239                 struct GNUNET_TIME_Absolute expiration,
240                 const char *name,
241                 unsigned int rd_count,
242                 const struct GNUNET_NAMESTORE_RecordData *rd,
243                 const struct GNUNET_CRYPTO_RsaSignature *signature)
244 {
245   
246   struct GNSNameRecordBlock *nrb;
247   struct GNUNET_CRYPTO_ShortHashCode name_hash;
248   GNUNET_HashCode xor_hash;
249   GNUNET_HashCode name_hash_double;
250   GNUNET_HashCode zone_hash_double;
251   struct GNUNET_CRYPTO_HashAsciiEncoded xor_hash_string;
252   uint32_t rd_payload_length;
253   char* nrb_data = NULL;
254   size_t namelen;
255
256   /* we're done */
257   if (NULL == name)
258   {
259     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
260                "Zone iteration finished. Rescheduling put in %ds\n",
261                dht_max_update_interval);
262     zone_update_taskid = GNUNET_SCHEDULER_add_delayed (
263                                         GNUNET_TIME_relative_multiply(
264                                             GNUNET_TIME_UNIT_SECONDS,
265                                             dht_max_update_interval
266                                             ),
267                                             &update_zone_dht_start,
268                                             NULL);
269     return;
270   }
271   
272   namelen = strlen(name) + 1;
273   
274   if (signature == NULL)
275   {
276     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
277                "No signature for %s record data provided! Skipping...\n",
278                name);
279     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_next,
280                                                    NULL);
281     return;
282
283   }
284   
285   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
286              "Putting records for %s into the DHT\n", name);
287   
288   rd_payload_length = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
289   
290   nrb = GNUNET_malloc(rd_payload_length + namelen
291                       + sizeof(struct GNSNameRecordBlock));
292   
293   nrb->signature = *signature;
294   
295   nrb->public_key = *key;
296
297   nrb->rd_count = htonl(rd_count);
298   
299   memcpy(&nrb[1], name, namelen);
300
301   nrb_data = (char*)&nrb[1];
302   nrb_data += namelen;
303
304   rd_payload_length += sizeof(struct GNSNameRecordBlock) + namelen;
305
306   if (-1 == GNUNET_NAMESTORE_records_serialize (rd_count,
307                                                 rd,
308                                                 rd_payload_length,
309                                                 nrb_data))
310   {
311     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
312                "Record serialization failed! Skipping...\n");
313     GNUNET_free(nrb);
314     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_next,
315                                                    NULL);
316     return;
317   }
318
319
320   /*
321    * calculate DHT key: H(name) xor H(pubkey)
322    */
323   GNUNET_CRYPTO_short_hash(name, strlen(name), &name_hash);
324   GNUNET_CRYPTO_short_hash_double (&name_hash, &name_hash_double);
325   GNUNET_CRYPTO_short_hash_double (&zone_hash, &zone_hash_double);
326   GNUNET_CRYPTO_hash_xor(&zone_hash_double, &name_hash_double, &xor_hash);
327   GNUNET_CRYPTO_hash_to_enc (&xor_hash, &xor_hash_string);
328
329   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
330              "putting records for %s under key: %s with size %d\n",
331              name, (char*)&xor_hash_string, rd_payload_length);
332   
333   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
334              "DHT req to %d\n", DHT_OPERATION_TIMEOUT.rel_value);
335
336   GNUNET_DHT_put (dht_handle, &xor_hash,
337                   DHT_GNS_REPLICATION_LEVEL,
338                   GNUNET_DHT_RO_NONE,
339                   GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
340                   rd_payload_length,
341                   (char*)nrb,
342                   expiration,
343                   DHT_OPERATION_TIMEOUT,
344                   &record_dht_put,
345                   NULL); //cls for cont
346   
347   num_public_records++;
348
349   /**
350    * Reschedule periodic put
351    */
352   zone_update_taskid = GNUNET_SCHEDULER_add_delayed (dht_update_interval,
353                                 &update_zone_dht_next,
354                                 NULL);
355
356   GNUNET_free(nrb);
357
358 }
359
360 /**
361  * Periodically iterate over our zone and store everything in dht
362  *
363  * @param cls NULL
364  * @param tc task context
365  */
366 static void
367 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
368 {
369   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Scheduling DHT zone update!\n");
370   if (0 == num_public_records)
371   {
372     dht_update_interval = GNUNET_TIME_relative_multiply(
373                                             GNUNET_TIME_UNIT_SECONDS,
374                                             dht_max_update_interval);
375     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
376                "No records in db. Adjusted DHT update interval to %ds\n",
377                dht_max_update_interval);
378   }
379   else
380   {
381     
382     dht_update_interval = GNUNET_TIME_relative_multiply(
383                                   GNUNET_TIME_UNIT_SECONDS,
384                                   (dht_max_update_interval/num_public_records));
385     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
386                "Adjusted DHT update interval to %ds!\n",
387                (dht_max_update_interval/num_public_records));
388   }
389
390   /* start counting again */
391   num_public_records = 0;
392   namestore_iter = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
393                                                  &zone_hash,
394                                                  GNUNET_NAMESTORE_RF_AUTHORITY,
395                                                  GNUNET_NAMESTORE_RF_PRIVATE,
396                                                  &put_gns_record,
397                                                  NULL);
398 }
399
400
401 /* END DHT ZONE PROPAGATION */
402
403 /**
404  * Send shorten response back to client
405  * 
406  * @param cls the closure containing a client shorten handle
407  * @param name the shortened name result or NULL if cannot be shortened
408  */
409 static void
410 send_shorten_response(void* cls, const char* name)
411 {
412   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
413               "SHORTEN_RESULT", name);
414   struct GNUNET_GNS_ClientShortenResultMessage *rmsg;
415   struct ClientShortenHandle *csh = (struct ClientShortenHandle *)cls;
416   
417   if (name == NULL)
418   {
419     name = "";
420   }
421
422   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientShortenResultMessage)
423                        + strlen(name) + 1);
424   
425   rmsg->id = csh->unique_id;
426   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT);
427   rmsg->header.size = 
428     htons(sizeof(struct GNUNET_GNS_ClientShortenResultMessage) +
429           strlen(name) + 1);
430
431   strcpy((char*)&rmsg[1], name);
432
433   GNUNET_SERVER_notification_context_unicast (nc, csh->client,
434                               (const struct GNUNET_MessageHeader *) rmsg,
435                               GNUNET_NO);
436   GNUNET_SERVER_receive_done (csh->client, GNUNET_OK);
437   
438   GNUNET_free(rmsg);
439   GNUNET_free_non_null(csh->name);
440   GNUNET_free(csh);
441
442 }
443
444 /**
445  * Handle a shorten message from the api
446  *
447  * @param cls the closure
448  * @param client the client
449  * @param message the message
450  */
451 static void handle_shorten(void *cls,
452                            struct GNUNET_SERVER_Client * client,
453                            const struct GNUNET_MessageHeader * message)
454 {
455   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "SHORTEN");
456
457   size_t msg_size = 0;
458   struct ClientShortenHandle *csh;
459   char name[MAX_DNS_NAME_LENGTH];
460   char* nameptr = name;
461
462   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientShortenMessage))
463   {
464     GNUNET_break_op (0);
465     GNUNET_SERVER_receive_done (client, GNUNET_OK);
466     return;
467   }
468
469
470   struct GNUNET_GNS_ClientShortenMessage *sh_msg =
471     (struct GNUNET_GNS_ClientShortenMessage *) message;
472   
473   msg_size = ntohs(message->size);
474
475   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
476   {
477     GNUNET_break_op (0);
478     GNUNET_SERVER_receive_done (client, GNUNET_OK);
479     return;
480   }
481
482   csh = GNUNET_malloc(sizeof(struct ClientShortenHandle));
483   csh->client = client;
484   csh->unique_id = sh_msg->id;
485   
486   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
487
488   if (strlen (name) < strlen(GNUNET_GNS_TLD)) {
489     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
490                "SHORTEN: %s is too short", name);
491     csh->name = NULL;
492     send_shorten_response(csh, name);
493     return;
494   }
495
496   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
497     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
498                "SHORTEN: %s is too long", name);
499     csh->name = NULL;
500     send_shorten_response(csh, name);
501     return;
502   }
503   
504   if (!is_gnunet_tld(name) && !is_zkey_tld(name))
505   {
506     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
507                 "%s is not our domain. Returning\n", name);
508     csh->name = NULL;
509     send_shorten_response(csh, name);
510     return;
511   }
512   
513   GNUNET_SERVER_notification_context_add (nc, client);
514   
515   /* Start shortening */
516   if (GNUNET_YES == auto_import_pkey)
517     gns_resolver_shorten_name(zone_hash, name, zone_key,
518                               &send_shorten_response, csh);
519   else
520     gns_resolver_shorten_name(zone_hash, name, NULL,
521                               &send_shorten_response, csh);
522 }
523
524
525 /**
526  * Send get authority response back to client
527  * 
528  * @param cls the closure containing a client get auth handle
529  * @param name the shortened name result or NULL if cannot be shortened
530  */
531 static void
532 send_get_auth_response(void *cls, const char* name)
533 {
534   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
535               "GET_AUTH_RESULT", name);
536   struct GNUNET_GNS_ClientGetAuthResultMessage *rmsg;
537   struct ClientGetAuthHandle *cah = (struct ClientGetAuthHandle *)cls;
538   
539   if (name == NULL)
540   {
541     name = "";
542   }
543
544   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage)
545                        + strlen(name) + 1);
546   
547   rmsg->id = cah->unique_id;
548   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_GET_AUTH_RESULT);
549   rmsg->header.size = 
550     htons(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage) +
551           strlen(name) + 1);
552
553   strcpy((char*)&rmsg[1], name);
554
555   GNUNET_SERVER_notification_context_unicast (nc, cah->client,
556                               (const struct GNUNET_MessageHeader *) rmsg,
557                               GNUNET_NO);
558   GNUNET_SERVER_receive_done (cah->client, GNUNET_OK);
559   
560   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up handles...\n");
561
562   GNUNET_free(rmsg);
563   GNUNET_free_non_null(cah->name);
564   GNUNET_free(cah);
565
566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done.\n");
567
568 }
569
570
571 /**
572  * Handle a get authority message from the api
573  *
574  * @param cls the closure
575  * @param client the client
576  * @param message the message
577  */
578 static void handle_get_authority(void *cls,
579                            struct GNUNET_SERVER_Client * client,
580                            const struct GNUNET_MessageHeader * message)
581 {
582   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "GET_AUTH");
583
584   size_t msg_size = 0;
585   struct ClientGetAuthHandle *cah;
586   char name[MAX_DNS_NAME_LENGTH];
587   char* nameptr = name;
588
589
590   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientGetAuthMessage))
591   {
592     GNUNET_break_op (0);
593     GNUNET_SERVER_receive_done (client, GNUNET_OK);
594     return;
595   }
596
597   GNUNET_SERVER_notification_context_add (nc, client);
598
599   struct GNUNET_GNS_ClientGetAuthMessage *sh_msg =
600     (struct GNUNET_GNS_ClientGetAuthMessage *) message;
601   
602   msg_size = ntohs(message->size);
603
604   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
605   {
606     GNUNET_break_op (0);
607     GNUNET_SERVER_receive_done (client, GNUNET_OK);
608     return;
609   }
610   
611   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
612
613
614   cah = GNUNET_malloc(sizeof(struct ClientGetAuthHandle));
615   cah->client = client;
616   cah->unique_id = sh_msg->id;
617
618   if (strlen(name) < strlen(GNUNET_GNS_TLD))
619   {
620     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
621                 "GET_AUTH: %s is too short. Returning\n", name);
622     cah->name = NULL;
623     send_get_auth_response(cah, name);
624     return;
625   }
626   
627   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
628     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
629                "GET_AUTH: %s is too long", name);
630     cah->name = NULL;
631     send_get_auth_response(cah, name);
632     return;
633   }
634   
635   if (strcmp(name+strlen(name)-strlen(GNUNET_GNS_TLD),
636              GNUNET_GNS_TLD) != 0)
637   {
638     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
639                 "GET_AUTH: %s is not our domain. Returning\n", name);
640     cah->name = NULL;
641     send_get_auth_response(cah, name);
642     return;
643   }
644
645   if (strcmp(name, GNUNET_GNS_TLD) == 0)
646   {
647     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
648                 "GET_AUTH: %s is us. Returning\n", name);
649     cah->name = NULL;
650     send_get_auth_response(cah, name);
651     return;
652   }
653   
654   cah->name = GNUNET_malloc(strlen(name)
655                             - strlen(GNUNET_GNS_TLD) + 1);
656   memset(cah->name, 0,
657          strlen(name)-strlen(GNUNET_GNS_TLD) + 1);
658   memcpy(cah->name, name,
659          strlen(name)-strlen(GNUNET_GNS_TLD));
660
661   /* Start delegation resolution in our namestore */
662   gns_resolver_get_authority(zone_hash, name, &send_get_auth_response, cah);
663 }
664
665
666 /**
667  * Reply to client with the result from our lookup.
668  *
669  * @param cls the closure (our client lookup handle)
670  * @param rd_count the number of records
671  * @param rd the record data
672  */
673 static void
674 send_lookup_response(void* cls,
675                      uint32_t rd_count,
676                      const struct GNUNET_NAMESTORE_RecordData *rd)
677 {
678   struct ClientLookupHandle* clh = (struct ClientLookupHandle*)cls;
679   struct GNUNET_GNS_ClientLookupResultMessage *rmsg;
680   size_t len;
681   
682   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %d results\n",
683               "LOOKUP_RESULT", rd_count);
684   
685   len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
686   rmsg = GNUNET_malloc(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
687   
688   rmsg->id = clh->unique_id;
689   rmsg->rd_count = htonl(rd_count);
690   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT);
691   rmsg->header.size = 
692     htons(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
693
694   GNUNET_NAMESTORE_records_serialize (rd_count, rd, len, (char*)&rmsg[1]);
695   
696   GNUNET_SERVER_notification_context_unicast (nc, clh->client,
697                                 (const struct GNUNET_MessageHeader *) rmsg,
698                                 GNUNET_NO);
699   GNUNET_SERVER_receive_done (clh->client, GNUNET_OK);
700   
701   GNUNET_free(rmsg);
702   GNUNET_free(clh->name);
703   GNUNET_free(clh);
704
705 }
706
707
708 /**
709  * Handle lookup requests from client
710  *
711  * @param cls the closure
712  * @param client the client
713  * @param message the message
714  */
715 static void
716 handle_lookup(void *cls,
717               struct GNUNET_SERVER_Client * client,
718               const struct GNUNET_MessageHeader * message)
719 {
720   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "LOOKUP");
721
722   size_t msg_size = 0;
723   size_t namelen;
724   char name[MAX_DNS_NAME_LENGTH];
725   struct ClientLookupHandle *clh;
726   char* nameptr = name;
727
728   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientLookupMessage))
729   {
730     GNUNET_break_op (0);
731     GNUNET_SERVER_receive_done (client, GNUNET_OK);
732     return;
733   }
734
735   GNUNET_SERVER_notification_context_add (nc, client);
736
737   struct GNUNET_GNS_ClientLookupMessage *sh_msg =
738     (struct GNUNET_GNS_ClientLookupMessage *) message;
739   
740   msg_size = ntohs(message->size);
741
742   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
743   {
744     GNUNET_break_op (0);
745     GNUNET_SERVER_receive_done (client, GNUNET_OK);
746     return;
747   }
748   
749   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
750   namelen = strlen(name)+1;
751   clh = GNUNET_malloc(sizeof(struct ClientLookupHandle));
752   clh->client = client;
753   clh->name = GNUNET_malloc(namelen);
754   strcpy(clh->name, name);
755   clh->unique_id = sh_msg->id;
756   clh->type = ntohl(sh_msg->type);
757   
758   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
759     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
760                "LOOKUP: %s is too long", name);
761     clh->name = NULL;
762     send_lookup_response(clh, 0, NULL);
763     return;
764   }
765   
766   if (GNUNET_YES == auto_import_pkey)
767   {
768     gns_resolver_lookup_record(zone_hash, clh->type, name,
769                                zone_key,
770                                default_lookup_timeout,
771                                &send_lookup_response, clh);
772   }
773   else
774   {
775     gns_resolver_lookup_record(zone_hash, clh->type, name,
776                                NULL,
777                                default_lookup_timeout,
778                                &send_lookup_response, clh);
779   }
780 }
781
782
783
784 /**
785  * Process GNS requests.
786  *
787  * @param cls closure)
788  * @param server the initialized server
789  * @param c configuration to use
790  */
791 static void
792 run (void *cls, struct GNUNET_SERVER_Handle *server,
793      const struct GNUNET_CONFIGURATION_Handle *c)
794 {
795   
796   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initializing GNS\n");
797   
798   char* keyfile;
799   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
800   unsigned long long max_parallel_bg_queries = 0;
801   unsigned long long default_lookup_timeout_secs = 0;
802   int ignore_pending = GNUNET_NO;
803
804   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
805     {&handle_shorten, NULL, GNUNET_MESSAGE_TYPE_GNS_SHORTEN, 0},
806     {&handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0},
807     {&handle_get_authority, NULL, GNUNET_MESSAGE_TYPE_GNS_GET_AUTH, 0}
808   };
809
810   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "gns",
811                                              "ZONEKEY", &keyfile))
812   {
813     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
814                 "No private key for root zone specified!\n");
815     GNUNET_SCHEDULER_shutdown(0);
816     return;
817   }
818
819   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
820              "Using keyfile %s for root zone.\n", keyfile);
821
822   zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
823   GNUNET_CRYPTO_rsa_key_get_public (zone_key, &pkey);
824
825   GNUNET_CRYPTO_short_hash(&pkey,
826                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
827                      &zone_hash);
828   GNUNET_free(keyfile);
829   
830   /**
831    * handle to our local namestore
832    */
833   namestore_handle = GNUNET_NAMESTORE_connect(c);
834
835   if (NULL == namestore_handle)
836   {
837     //FIXME do error handling;
838     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
839                "Failed to connect to the namestore!\n");
840     GNUNET_SCHEDULER_shutdown(0);
841     return;
842   }
843   
844   
845
846   auto_import_pkey = GNUNET_NO;
847
848   if (GNUNET_YES ==
849       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
850                                             "AUTO_IMPORT_PKEY"))
851   {
852     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
853                "Automatic PKEY import is enabled.\n");
854     auto_import_pkey = GNUNET_YES;
855
856   }
857
858   dht_max_update_interval = GNUNET_GNS_DHT_MAX_UPDATE_INTERVAL;
859
860   if (GNUNET_OK ==
861       GNUNET_CONFIGURATION_get_value_number (c, "gns",
862                                              "DHT_MAX_UPDATE_INTERVAL",
863                                              &dht_max_update_interval))
864   {
865     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
866                "DHT zone update interval: %d\n",
867                dht_max_update_interval);
868   }
869
870   if (GNUNET_OK ==
871       GNUNET_CONFIGURATION_get_value_number (c, "gns",
872                                             "MAX_PARALLEL_BACKGROUND_QUERIES",
873                                             &max_parallel_bg_queries))
874   {
875     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
876                "Number of allowed parallel background queries: %d\n",
877                max_parallel_bg_queries);
878   }
879
880   if (GNUNET_YES ==
881       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
882                                             "AUTO_IMPORT_CONFIRMATION_REQ"))
883   {
884     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
885                "Auto import requires user confirmation\n");
886     ignore_pending = GNUNET_YES;
887   }
888
889   if (GNUNET_OK ==
890       GNUNET_CONFIGURATION_get_value_number(c, "gns",
891                                             "DEFAULT_LOOKUP_TIMEOUT",
892                                             &default_lookup_timeout_secs))
893   {
894     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
895                "Default lookup timeout: %ds\n", default_lookup_timeout_secs);
896     default_lookup_timeout = GNUNET_TIME_relative_multiply(
897                                             GNUNET_TIME_UNIT_SECONDS,
898                                             default_lookup_timeout_secs);
899   }
900   
901   /**
902    * handle to the dht
903    */
904   dht_handle = GNUNET_DHT_connect(c,
905                        //max_parallel_bg_queries); //FIXME get ht_len from cfg
906                        1024);
907
908   if (NULL == dht_handle)
909   {
910     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
911   }
912   
913   if (gns_resolver_init(namestore_handle, dht_handle, zone_hash,
914                         max_parallel_bg_queries,
915                         ignore_pending)
916       == GNUNET_SYSERR)
917   {
918     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
919                "Unable to initialize resolver!\n");
920     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
921     return;
922   }
923
924   if (GNUNET_YES ==
925       GNUNET_CONFIGURATION_get_value_yesno (c, "gns", "HIJACK_DNS"))
926   {
927     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
928                "DNS hijacking enabled... connecting to service.\n");
929
930     if (gns_interceptor_init(zone_hash, zone_key, c) == GNUNET_SYSERR)
931     {
932       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
933                "Failed to enable the dns interceptor!\n");
934     }
935   }
936   
937   /**
938    * Schedule periodic put
939    * for our records
940    * We have roughly an hour for all records;
941    */
942   dht_update_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
943                                                       1);
944   zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);
945
946   GNUNET_SERVER_add_handlers (server, handlers);
947   
948   //FIXME
949   //GNUNET_SERVER_disconnect_notify (server,
950   //                                 &client_disconnect_notification,
951   //                                 NULL);
952
953   nc = GNUNET_SERVER_notification_context_create (server, 1);
954
955   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
956                                 NULL);
957 }
958
959
960 /**
961  * The main function for the GNS service.
962  *
963  * @param argc number of arguments from the command line
964  * @param argv command line arguments
965  * @return 0 ok, 1 on error
966  */
967 int
968 main (int argc, char *const *argv)
969 {
970   int ret;
971
972   ret =
973       (GNUNET_OK ==
974        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
975                            NULL)) ? 0 : 1;
976   return ret;
977 }
978
979 /* end of gnunet-service-gns.c */