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