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