-dht put, some serialization
[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  * @file gns/gnunet-service-gns.c
23  * @brief GNUnet GNS service
24  * @author Martin Schanzenbach
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_transport_service.h"
29 #include "gnunet_dns_service.h"
30 #include "gnunet_dnsparser_lib.h"
31 #include "gnunet_dht_service.h"
32 #include "gnunet_namestore_service.h"
33 #include "gnunet_gns_service.h"
34 #include "gns.h"
35
36
37 /* TODO into gnunet_protocols */
38 #define GNUNET_MESSAGE_TYPE_GNS_CLIENT_LOOKUP 23
39 #define GNUNET_MESSAGE_TYPE_GNS_CLIENT_RESULT 24
40
41 struct GNUNET_GNS_QueryRecordList
42 {
43   /**
44    * DLL
45    */
46   struct GNUNET_GNS_QueryRecordList * next;
47   struct GNUNET_GNS_QueryRecordList * prev;
48
49   struct GNUNET_DNSPARSER_Record * record;
50 };
51
52 /**
53  * A result list for namestore queries
54  */
55 struct GNUNET_GNS_PendingQuery
56 {
57   /* the answer packet */
58   struct GNUNET_DNSPARSER_Packet *answer;
59
60   /* records to put into answer packet */
61   struct GNUNET_GNS_QueryRecordList * records_head;
62   struct GNUNET_GNS_QueryRecordList * records_tail;
63
64   int num_records;
65   int num_authority_records; //FIXME are all of our replies auth?
66   
67   char *name;
68   uint16_t type;
69   /* the dns request id */
70   int id; // FIXME can handle->request_id also be used here?
71
72   /* the request handle to reply to */
73   struct GNUNET_DNS_RequestHandle *request_handle;
74
75   /* hast this query been answered? */
76   int answered;
77 };
78
79
80 /**
81  * Our handle to the DNS handler library
82  */
83 struct GNUNET_DNS_Handle *dns_handle;
84
85 /**
86  * Our handle to the DHT
87  */
88 struct GNUNET_DHT_Handle *dht_handle;
89
90 struct GNUNET_TIME_Relative dht_update_interval;
91
92 /**
93  * Our private "key"
94  * FIXME get the real deal
95  */
96 struct GNUNET_CRYPTO_RsaPrivateKey *zone_key;
97
98 /**
99  * Our handle to the namestore service
100  */
101 struct GNUNET_NAMESTORE_Handle *namestore_handle;
102
103 /**
104  * The configuration the GNS service is running with
105  */
106 const struct GNUNET_CONFIGURATION_Handle *GNS_cfg;
107
108 /**
109  * Our notification context.
110  */
111 static struct GNUNET_SERVER_NotificationContext *nc;
112
113 /**
114  * Our zone hash
115  */
116 GNUNET_HashCode *zone_hash;
117
118 /**
119  * Task run during shutdown.
120  *
121  * @param cls unused
122  * @param tc unused
123  */
124 static void
125 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
126 {
127   GNUNET_DNS_disconnect(dns_handle);
128   GNUNET_NAMESTORE_disconnect(namestore_handle, 0);
129 }
130
131 /**
132  * Phase 2 of resolution.
133  */
134 void
135 lookup_dht(struct GNUNET_GNS_PendingQuery *answer)
136 {
137 }
138
139 void
140 reply_to_dns(struct GNUNET_GNS_PendingQuery *answer)
141 {
142   struct GNUNET_GNS_QueryRecordList *i;
143   struct GNUNET_DNSPARSER_Packet *packet;
144   struct GNUNET_DNSPARSER_Flags dnsflags;
145   int j;
146   size_t len;
147   int ret;
148   char *buf;
149   
150   packet = GNUNET_malloc(sizeof(struct GNUNET_DNSPARSER_Packet));
151   packet->answers =
152     GNUNET_malloc(sizeof(struct GNUNET_DNSPARSER_Record) * answer->num_records);
153   
154   len = sizeof(struct GNUNET_DNSPARSER_Record*);
155   j = 0;
156   for (i=answer->records_head; i != NULL; i=i->next)
157   {
158     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
159                "Adding %s to DNS response\n", i->record->name);
160     memcpy(&packet->answers[j], 
161            i->record,
162            sizeof (struct GNUNET_DNSPARSER_Record));
163     GNUNET_free(i->record);
164     j++;
165   }
166   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "after memcpy\n");
167   /* FIXME how to handle auth, additional etc */
168   packet->num_answers = answer->num_records;
169   packet->num_authority_records = answer->num_authority_records;
170
171   dnsflags.authoritative_answer = 1;
172   dnsflags.opcode = GNUNET_DNSPARSER_OPCODE_QUERY;
173   dnsflags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NO_ERROR; //not sure
174   dnsflags.query_or_response = 1;
175   packet->flags = dnsflags;
176
177   packet->id = answer->id;
178   ret = GNUNET_DNSPARSER_pack (packet,
179                                1024, /* FIXME magic from dns redirector */
180                                &buf,
181                                &len);
182   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
183              "Built DNS response! (ret=%d)\n", ret);
184   if (ret == GNUNET_OK)
185   {
186     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
187                "Answering DNS request\n");
188     GNUNET_DNS_request_answer(answer->request_handle,
189                               len,
190                               buf);
191     GNUNET_free(answer);
192     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Answered DNS request\n");
193     //FIXME return code, free datastructures
194   }
195   else
196   {
197     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
198                "Error building DNS response! (ret=%d)", ret);
199   }
200 }
201
202 static void
203 process_ns_result(void* cls, const GNUNET_HashCode *zone,
204                   const char *name, uint32_t record_type,
205                   struct GNUNET_TIME_Absolute expiration,
206                   enum GNUNET_NAMESTORE_RecordFlags flags,
207                   const struct GNUNET_NAMESTORE_SignatureLocation *sig_loc,
208                   size_t size, const void *data)
209 {
210   struct GNUNET_GNS_PendingQuery *query;
211   struct GNUNET_GNS_QueryRecordList *qrecord;
212   struct GNUNET_DNSPARSER_Record *record;
213   query = (struct GNUNET_GNS_PendingQuery *) cls;
214
215
216   if (NULL == data)
217   {
218     /**
219      * Last result received (or none)
220      * Do we have what we need to answer?
221      * If not -> DHT Phase
222      * FIXME free memory
223      */
224     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
225                "Namestore lookup terminated. (answered=%d)", query->answered);
226
227     if (query->answered)
228       reply_to_dns(query);
229     else
230       lookup_dht(query); //TODO
231
232   }
233   else
234   {
235     /**
236      * New result
237      */
238     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
239                "Processing additional result %s from namestore\n", name);
240
241     qrecord = GNUNET_malloc(sizeof(struct GNUNET_GNS_QueryRecordList));
242     record = GNUNET_malloc(sizeof(struct GNUNET_DNSPARSER_Record));
243     qrecord->record = record;
244
245     record->name = (char*)name;
246     /* FIXME for gns records this requires the dnsparser to be modified!
247      * or use RAW
248      * maybe store record data appropriately in namestore to avoid this
249      * huge switch?
250      **/
251     if (record_type == GNUNET_DNSPARSER_TYPE_A)
252     {
253       record->data.raw.data = (char*)data;
254       record->data.raw.data_len = size;
255     }
256     record->expiration_time = expiration;
257     record->type = record_type;
258     record->class = GNUNET_DNSPARSER_CLASS_INTERNET; /* srsly? */
259
260     if (flags == GNUNET_NAMESTORE_RF_AUTHORITY)
261     {
262       //query->num_authority_records++;
263     }
264
265     if ((0 == strcmp(query->name , name)) &&
266         (query->type == record_type))
267     {
268       GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Found answer to query!\n");
269       query->answered = 1;
270     }
271
272     query->num_records++;
273
274     //FIXME watch for leaks
275     GNUNET_CONTAINER_DLL_insert(query->records_head,
276                                 query->records_tail,
277                                 qrecord);
278   }
279 }
280
281
282 /**
283  * Phase 1 of name resolution: Lookup local namestore
284  *
285  * @param name the name to look up
286  * @param id the id of the dns request (for the reply)
287  * @param type the record type to look for
288  */
289 void
290 lookup_namestore(struct GNUNET_DNS_RequestHandle *rh,
291                  char* name, uint16_t id, uint16_t type)
292 {
293   struct GNUNET_GNS_PendingQuery *answer;
294   
295   /**
296    * Do db lookup here. Make dht lookup if necessary 
297    * FIXME for now only local lookups for our zone!
298    */
299   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "This is .gnunet (%s)!\n", name);
300   answer = GNUNET_malloc(sizeof (struct GNUNET_GNS_PendingQuery));
301   answer->id = id;
302   answer->name = name;
303   answer->type =type;
304   answer->request_handle = rh;
305   
306   GNUNET_NAMESTORE_lookup_name(namestore_handle,
307                                zone_hash,
308                                name,
309                                type,
310                                &process_ns_result,
311                                answer);
312 }
313
314 /**
315  * The DNS request handler
316  *
317  * @param cls closure
318  * @param rh request handle to user for reply
319  * @param request_length number of bytes in request
320  * @param request udp payload of the DNS request
321  */
322 void
323 handle_dns_request(void *cls,
324                    struct GNUNET_DNS_RequestHandle *rh,
325                    size_t request_length,
326                    const char *request)
327 {
328   /**
329    * parse request for tld
330    */
331   struct GNUNET_DNSPARSER_Packet *p;
332   int namelen;
333   int i;
334   char *tail;
335
336   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "hijacked a request...processing\n");
337   p = GNUNET_DNSPARSER_parse (request, request_length);
338   
339   if (NULL == p)
340   {
341     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
342                 "Received malformed DNS packet, leaving it untouched\n");
343     GNUNET_DNS_request_forward (rh);
344     return;
345   }
346   
347   /**
348    * Check tld and decide if we or
349    * legacy dns is responsible
350    */
351   for (i=0;i<p->num_queries;i++)
352   {
353     namelen = strlen(p->queries[i].name);
354     
355     if (namelen < 7) /* this can't be .gnunet */
356       continue;
357     /**
358      * Move our tld/root to config file
359      * Generate fake DNS reply that replaces .gnunet with .org for testing?
360      */
361     tail = p->queries[i].name+(namelen-7);
362     if (0 == strcmp(tail, ".gnunet"))
363     {
364       /* FIXME we need to answer to ALL queries in ONE response...
365        * What happens if some requests should be handles by us and
366        * others by DNS?
367        * Like this we only answer one...
368        */
369       lookup_namestore(rh, p->queries[i].name, p->id, p->queries[i].type);
370     }
371     else
372     {
373       /**
374        * This request does not concern us. Forward to real DNS.
375        */
376       GNUNET_log(GNUNET_ERROR_TYPE_INFO,
377                  "Request for %s is forwarded to DNS\n", p->queries[i].name);
378       GNUNET_DNS_request_forward (rh);
379     }
380   }
381 }
382
383 /*TODO*/
384 static void
385 handle_client_record_lookup(void *cls,
386                             struct GNUNET_SERVER_Client *client,
387                             const struct GNUNET_MessageHeader *message)
388 {
389 }
390
391 /**
392  * test function
393  */
394 void
395 put_some_records(void)
396 {
397   /* put a few records into namestore */
398   char* ipA = "1.2.3.4";
399   char* ipB = "5.6.7.8";
400   struct in_addr *alice = GNUNET_malloc(sizeof(struct in_addr));
401   struct in_addr *bob = GNUNET_malloc(sizeof(struct in_addr));
402   GNUNET_assert(1 == inet_pton (AF_INET, ipA, alice));
403   GNUNET_assert(1 == inet_pton (AF_INET, ipB, bob));
404   GNUNET_NAMESTORE_record_put (namestore_handle,
405                                zone_hash,
406                                "alice.gnunet",
407                                GNUNET_GNS_RECORD_TYPE_A,
408                                GNUNET_TIME_absolute_get_forever(),
409                                GNUNET_NAMESTORE_RF_AUTHORITY,
410                                NULL, //sig loc
411                                sizeof(struct in_addr),
412                                alice,
413                                NULL,
414                                NULL);
415   GNUNET_NAMESTORE_record_put (namestore_handle,
416                                zone_hash,
417                                "bob.gnunet",
418                                GNUNET_GNS_RECORD_TYPE_A,
419                                GNUNET_TIME_absolute_get_forever(),
420                                GNUNET_NAMESTORE_RF_AUTHORITY,
421                                NULL, //sig loc
422                                sizeof(struct in_addr),
423                                bob,
424                                NULL,
425                                NULL);
426 }
427
428 void
429 put_gns_record(void *cls, const GNUNET_HashCode *zone, const char *name,
430                uint32_t record_type, struct GNUNET_TIME_Absolute expiration,
431                enum GNUNET_NAMESTORE_RecordFlags flags,
432                const struct GNUNET_NAMESTORE_SignatureLocation *sig_loc,
433                size_t size, const void *record_data)
434 {
435   struct GNUNET_TIME_Relative timeout;
436
437   char* data;
438   char* data_ptr;
439   struct GNUNET_TIME_AbsoluteNBO exp_nbo;
440   exp_nbo = GNUNET_TIME_absolute_hton (expiration);
441   uint32_t namelen = htonl(strlen(name));
442   uint16_t flags_nbo = htons(flags);
443   uint64_t offset = GNUNET_htonll(sig_loc->offset);
444   uint32_t depth = htonl(sig_loc->depth);
445   uint32_t revision = htonl(sig_loc->revision);
446
447   /**
448    * I guess this can be done prettier
449    */
450   size_t record_len = sizeof(size_t) + sizeof(uint32_t) +
451     sizeof(uint16_t) +
452     sizeof(struct GNUNET_NAMESTORE_SignatureLocation) +
453     sizeof(uint32_t) + strlen(name) + size;
454   
455   record_type = htonl(record_type);
456
457   data = GNUNET_malloc(record_len);
458   
459   /* -_- */
460   data_ptr = data;
461   memcpy(data_ptr, &namelen, sizeof(size_t));
462   data_ptr += sizeof(size_t);
463
464   memcpy(data_ptr, name, namelen);
465   data_ptr += namelen;
466   
467   memcpy(data_ptr, &record_type, sizeof(uint32_t));
468   data_ptr += sizeof(uint32_t);
469
470   memcpy(data_ptr, &exp_nbo, sizeof(struct GNUNET_TIME_AbsoluteNBO));
471   data_ptr += sizeof(struct GNUNET_TIME_AbsoluteNBO);
472
473   memcpy(data_ptr, &flags_nbo, sizeof(uint16_t));
474   data_ptr += sizeof(uint16_t);
475
476   memcpy(data_ptr, &offset, sizeof(uint64_t));
477   data_ptr += sizeof(uint64_t);
478
479   memcpy(data_ptr, &depth, sizeof(uint32_t));
480   data_ptr += sizeof(uint32_t);
481   
482   memcpy(data_ptr, &revision, sizeof(uint32_t));
483   data_ptr += sizeof(uint32_t);
484
485   memcpy(data_ptr, &size, sizeof(uint32_t));
486   data_ptr += sizeof(uint32_t);
487
488   /**
489    * FIXME note that this only works with raw data in nbo
490    * write helper function that converts properly and returns buffer
491    */
492   memcpy(data_ptr, record_data, size);
493   data_ptr += size;
494   /*Doing this made me sad...*/
495
496   /**
497    * FIXME magic number
498    */
499   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 20);
500
501   GNUNET_DHT_put (dht_handle, zone_hash,
502                   5, //replication
503                   GNUNET_DHT_RO_NONE,
504                   GNUNET_BLOCK_TYPE_TEST, //FIXME todo
505                   (data_ptr-data),
506                   data,
507                   expiration, //FIXME from record makes sense?
508                   timeout,
509                   NULL, //FIXME continuation needed? success check?
510                   NULL); //cls for cont
511
512 }
513
514 /**
515  * Periodically iterate over our zone and store everything in dht
516  */
517 static void
518 update_zone_dht(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
519 {
520   GNUNET_NAMESTORE_zone_transfer (namestore_handle, zone_hash,
521                                   &put_gns_record,
522                                   NULL);
523 }
524
525 /**
526  * Process GNS requests.
527  *
528  * @param cls closure
529  * @param server the initialized server
530  * @param c configuration to use
531  */
532 static void
533 run (void *cls, struct GNUNET_SERVER_Handle *server,
534      const struct GNUNET_CONFIGURATION_Handle *c)
535 {
536   
537   /* The IPC message types */
538   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
539     /* callback, cls, type, size */
540     {&handle_client_record_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_CLIENT_LOOKUP,
541       0},
542     {NULL, NULL, 0, 0}
543   };
544   
545   zone_key = GNUNET_CRYPTO_rsa_key_create ();
546   GNUNET_CRYPTO_hash(zone_key, GNUNET_CRYPTO_RSA_KEY_LENGTH,//FIXME is this ok?
547                      zone_hash);
548
549   nc = GNUNET_SERVER_notification_context_create (server, 1);
550
551   /* FIXME - do some config parsing 
552    *       - Maybe only hijack dns if option is set (HIJACK_DNS=1)
553    */
554
555   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
556                                 NULL);
557   /**
558    * Do gnunet dns init here
559    */
560   dns_handle = GNUNET_DNS_connect(c,
561                                   GNUNET_DNS_FLAG_PRE_RESOLUTION,
562                                   &handle_dns_request, /* rh */
563                                   NULL); /* Closure */
564
565   if (NULL == dns_handle)
566   {
567     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
568                "Failed to connect to the dnsservice!\n");
569   }
570
571   /**
572    * handle to our local namestore
573    */
574   namestore_handle = GNUNET_NAMESTORE_connect(c);
575
576   if (NULL == namestore_handle)
577   {
578     //FIXME do error handling;
579     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
580                "Failed to connect to the namestore!\n");
581   }
582
583   /**
584    * handle to the dht
585    */
586   dht_handle = GNUNET_DHT_connect(c, 1); //FIXME get ht_len from cfg
587
588   if (NULL == dht_handle)
589   {
590     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
591   }
592   
593   dht_update_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
594                                                       60); //FIXME from cfg
595   GNUNET_SCHEDULER_add_delayed (dht_update_interval,
596                                 &update_zone_dht,
597                                 NULL);
598   
599   put_some_records();
600
601   GNUNET_SERVER_add_handlers (server, handlers);
602   /**
603    * Esp the lookup would require to keep track of the clients' context
604    * See dht.
605    * GNUNET_SERVER_disconnect_notify (server, &client_disconnect, NULL);
606    **/
607 }
608
609
610 /**
611  * The main function for the GNS service.
612  *
613  * @param argc number of arguments from the command line
614  * @param argv command line arguments
615  * @return 0 ok, 1 on error
616  */
617 int
618 main (int argc, char *const *argv)
619 {
620   int ret;
621
622   ret =
623       (GNUNET_OK ==
624        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
625                            NULL)) ? 0 : 1;
626   return ret;
627 }
628
629 /* end of gnunet-service-gns.c */