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