hxing typemap
[oweals/gnunet.git] / src / core / gnunet-service-core_kx.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 core/gnunet-service-core_kx.c
23  * @brief code for managing the key exchange (SET_KEY, PING, PONG) with other peers
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet-service-core_kx.h"
28 #include "gnunet-service-core.h"
29 #include "gnunet-service-core_clients.h"
30 #include "gnunet-service-core_neighbours.h"
31 #include "gnunet-service-core_sessions.h"
32 #include "gnunet_statistics_service.h"
33 #include "gnunet_peerinfo_service.h"
34 #include "gnunet_hello_lib.h"
35 #include "gnunet_constants.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet_protocols.h"
38 #include "core.h"
39
40 /**
41  * How long do we wait for SET_KEY confirmation initially?
42  */
43 #define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
44
45 /**
46  * What is the minimum frequency for a PING message?
47  */
48 #define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
49
50 /**
51  * What is the maximum age of a message for us to consider processing
52  * it?  Note that this looks at the timestamp used by the other peer,
53  * so clock skew between machines does come into play here.  So this
54  * should be picked high enough so that a little bit of clock skew
55  * does not prevent peers from connecting to us.
56  */
57 #define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
58
59 /**
60  * What is the maximum delay for a SET_KEY message?
61  */
62 #define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
63
64
65 /**
66  * We're sending an (encrypted) PING to the other peer to check if he
67  * can decrypt.  The other peer should respond with a PONG with the
68  * same content, except this time encrypted with the receiver's key.
69  */
70 struct PingMessage
71 {
72   /**
73    * Message type is CORE_PING.
74    */
75   struct GNUNET_MessageHeader header;
76
77   /**
78    * Seed for the IV
79    */
80   uint32_t iv_seed GNUNET_PACKED;
81
82   /**
83    * Intended target of the PING, used primarily to check
84    * that decryption actually worked.
85    */
86   struct GNUNET_PeerIdentity target;
87
88   /**
89    * Random number chosen to make reply harder.
90    */
91   uint32_t challenge GNUNET_PACKED;
92 };
93
94
95 /**
96  * Response to a PING.  Includes data from the original PING
97  * plus initial bandwidth quota information.
98  */
99 struct PongMessage
100 {
101   /**
102    * Message type is CORE_PONG.
103    */
104   struct GNUNET_MessageHeader header;
105
106   /**
107    * Seed for the IV
108    */
109   uint32_t iv_seed GNUNET_PACKED;
110
111   /**
112    * Random number to make faking the reply harder.  Must be
113    * first field after header (this is where we start to encrypt!).
114    */
115   uint32_t challenge GNUNET_PACKED;
116
117   /**
118    * Desired bandwidth (how much we should send to this
119    * peer / how much is the sender willing to receive).
120    */
121   struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
122
123   /**
124    * Intended target of the PING, used primarily to check
125    * that decryption actually worked.
126    */
127   struct GNUNET_PeerIdentity target;
128 };
129
130
131 /**
132  * Message transmitted to set (or update) a session key.
133  */
134 struct SetKeyMessage
135 {
136
137   /**
138    * Message type is either CORE_SET_KEY.
139    */
140   struct GNUNET_MessageHeader header;
141
142   /**
143    * Status of the sender (should be in "enum PeerStateMachine"), nbo.
144    */
145   int32_t sender_status GNUNET_PACKED;
146
147   /**
148    * Purpose of the signature, will be
149    * GNUNET_SIGNATURE_PURPOSE_SET_KEY.
150    */
151   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
152
153   /**
154    * At what time was this key created?
155    */
156   struct GNUNET_TIME_AbsoluteNBO creation_time;
157
158   /**
159    * The encrypted session key.
160    */
161   struct GNUNET_CRYPTO_RsaEncryptedData encrypted_key;
162
163   /**
164    * Who is the intended recipient?
165    */
166   struct GNUNET_PeerIdentity target;
167
168   /**
169    * Signature of the stuff above (starting at purpose).
170    */
171   struct GNUNET_CRYPTO_RsaSignature signature;
172
173 };
174
175
176 /**
177  * Encapsulation for encrypted messages exchanged between
178  * peers.  Followed by the actual encrypted data.
179  */
180 struct EncryptedMessage
181 {
182   /**
183    * Message type is either CORE_ENCRYPTED_MESSAGE.
184    */
185   struct GNUNET_MessageHeader header;
186
187   /**
188    * Random value used for IV generation.
189    */
190   uint32_t iv_seed GNUNET_PACKED;
191
192   /**
193    * MAC of the encrypted message (starting at 'sequence_number'),
194    * used to verify message integrity. Everything after this value
195    * (excluding this value itself) will be encrypted and authenticated.
196    * ENCRYPTED_HEADER_SIZE must be set to the offset of the *next* field.
197    */
198   GNUNET_HashCode hmac;
199
200   /**
201    * Sequence number, in network byte order.  This field
202    * must be the first encrypted/decrypted field
203    */
204   uint32_t sequence_number GNUNET_PACKED;
205
206   /**
207    * Desired bandwidth (how much we should send to this peer / how
208    * much is the sender willing to receive)?
209    */
210   struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
211
212   /**
213    * Timestamp.  Used to prevent reply of ancient messages
214    * (recent messages are caught with the sequence number).
215    */
216   struct GNUNET_TIME_AbsoluteNBO timestamp;
217
218 };
219
220 /**
221  * Number of bytes (at the beginning) of "struct EncryptedMessage"
222  * that are NOT encrypted.
223  */
224 #define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
225
226
227 /**
228  * State machine for our P2P encryption handshake.  Everyone starts in
229  * "DOWN", if we receive the other peer's key (other peer initiated)
230  * we start in state RECEIVED (since we will immediately send our
231  * own); otherwise we start in SENT.  If we get back a PONG from
232  * within either state, we move up to CONFIRMED (the PONG will always
233  * be sent back encrypted with the key we sent to the other peer).
234  */
235 enum KxStateMachine
236 {
237   /**
238    * No handshake yet.
239    */
240   KX_STATE_DOWN,
241
242   /**
243    * We've sent our session key.
244    */
245   KX_STATE_KEY_SENT,
246
247   /**
248    * We've received the other peers session key.
249    */
250   KX_STATE_KEY_RECEIVED,
251
252   /**
253    * The other peer has confirmed our session key with a message
254    * encrypted with his session key (which we got).  Key exchange
255    * is done.
256    */
257   KX_STATE_UP
258 };
259
260
261 /**
262  * Information about the status of a key exchange with another peer.
263  */
264 struct GSC_KeyExchangeInfo
265 {
266   /**
267    * Identity of the peer.
268    */
269   struct GNUNET_PeerIdentity peer;
270
271   /**
272    * SetKeyMessage to transmit (initialized the first
273    * time our status goes past 'KX_STATE_KEY_SENT').
274    */
275   struct SetKeyMessage skm;
276
277   /**
278    * PING message we transmit to the other peer.
279    */
280   struct PingMessage ping;
281
282   /**
283    * SetKeyMessage we received and did not process yet.
284    */
285   struct SetKeyMessage *skm_received;
286
287   /**
288    * PING message we received from the other peer and
289    * did not process yet (or NULL).
290    */
291   struct PingMessage *ping_received;
292
293   /**
294    * PONG message we received from the other peer and
295    * did not process yet (or NULL).
296    */
297   struct PongMessage *pong_received;
298
299   /**
300    * Non-NULL if we are currently looking up HELLOs for this peer.
301    * for this peer.
302    */
303   struct GNUNET_PEERINFO_IteratorContext *pitr;
304
305   /**
306    * Public key of the neighbour, NULL if we don't have it yet.
307    */
308   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
309
310   /**
311    * We received a PONG message before we got the "public_key"
312    * (or the SET_KEY).  We keep it here until we have a key
313    * to decrypt it.  NULL if no PONG is pending.
314    */
315   struct PongMessage *pending_pong;
316
317   /**
318    * Key we use to encrypt our messages for the other peer
319    * (initialized by us when we do the handshake).
320    */
321   struct GNUNET_CRYPTO_AesSessionKey encrypt_key;
322
323   /**
324    * Key we use to decrypt messages from the other peer
325    * (given to us by the other peer during the handshake).
326    */
327   struct GNUNET_CRYPTO_AesSessionKey decrypt_key;
328
329   /**
330    * At what time did we generate our encryption key?
331    */
332   struct GNUNET_TIME_Absolute encrypt_key_created;
333
334   /**
335    * At what time did the other peer generate the decryption key?
336    */
337   struct GNUNET_TIME_Absolute decrypt_key_created;
338
339   /**
340    * When should the session time out (if there are no PONGs)?
341    */
342   struct GNUNET_TIME_Absolute timeout;
343
344   /**
345    * At what frequency are we currently re-trying SET_KEY messages?
346    */
347   struct GNUNET_TIME_Relative set_key_retry_frequency;
348
349   /**
350    * ID of task used for re-trying SET_KEY and PING message.
351    */
352   GNUNET_SCHEDULER_TaskIdentifier retry_set_key_task;
353
354   /**
355    * ID of task used for sending keep-alive pings.
356    */
357   GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
358
359   /**
360    * Bit map indicating which of the 32 sequence numbers before the last
361    * were received (good for accepting out-of-order packets and
362    * estimating reliability of the connection)
363    */
364   unsigned int last_packets_bitmap;
365
366   /**
367    * last sequence number received on this connection (highest)
368    */
369   uint32_t last_sequence_number_received;
370
371   /**
372    * last sequence number transmitted
373    */
374   uint32_t last_sequence_number_sent;
375
376   /**
377    * What was our PING challenge number (for this peer)?
378    */
379   uint32_t ping_challenge;
380
381   /**
382    * What is our connection status?
383    */
384   enum KxStateMachine status;
385
386 };
387
388
389
390 /**
391  * Handle to peerinfo service.
392  */
393 static struct GNUNET_PEERINFO_Handle *peerinfo;
394
395 /**
396  * Our private key.
397  */
398 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
399
400 /**
401  * Our public key.
402  */
403 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
404
405 /**
406  * Our message stream tokenizer (for encrypted payload).
407  */
408 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
409
410
411
412 /**
413  * Derive an authentication key from "set key" information
414  */
415 static void
416 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
417                  const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
418                  struct GNUNET_TIME_Absolute creation_time)
419 {
420   static const char ctx[] = "authentication key";
421   struct GNUNET_TIME_AbsoluteNBO ctbe;
422
423
424   ctbe = GNUNET_TIME_absolute_hton (creation_time);
425   GNUNET_CRYPTO_hmac_derive_key (akey, skey, &seed, sizeof (seed), &skey->key,
426                                  sizeof (skey->key), &ctbe, sizeof (ctbe), ctx,
427                                  sizeof (ctx), NULL);
428 }
429
430
431 /**
432  * Derive an IV from packet information
433  */
434 static void
435 derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
436            const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
437            const struct GNUNET_PeerIdentity *identity)
438 {
439   static const char ctx[] = "initialization vector";
440
441   GNUNET_CRYPTO_aes_derive_iv (iv, skey, &seed, sizeof (seed),
442                                &identity->hashPubKey.bits,
443                                sizeof (identity->hashPubKey.bits), ctx,
444                                sizeof (ctx), NULL);
445 }
446
447 /**
448  * Derive an IV from pong packet information
449  */
450 static void
451 derive_pong_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
452                 const struct GNUNET_CRYPTO_AesSessionKey *skey, uint32_t seed,
453                 uint32_t challenge, const struct GNUNET_PeerIdentity *identity)
454 {
455   static const char ctx[] = "pong initialization vector";
456
457   GNUNET_CRYPTO_aes_derive_iv (iv, skey, &seed, sizeof (seed),
458                                &identity->hashPubKey.bits,
459                                sizeof (identity->hashPubKey.bits), &challenge,
460                                sizeof (challenge), ctx, sizeof (ctx), NULL);
461 }
462
463
464 /**
465  * Encrypt size bytes from in and write the result to out.  Use the
466  * key for outbound traffic of the given neighbour.
467  *
468  * @param kx key information context
469  * @param iv initialization vector to use
470  * @param in ciphertext
471  * @param out plaintext
472  * @param size size of in/out
473  * @return GNUNET_OK on success
474  */
475 static int
476 do_encrypt (struct GSC_KeyExchangeInfo *kx,
477             const struct GNUNET_CRYPTO_AesInitializationVector *iv,
478             const void *in, void *out, size_t size)
479 {
480   if (size != (uint16_t) size)
481   {
482     GNUNET_break (0);
483     return GNUNET_NO;
484   }
485   GNUNET_assert (size ==
486                  GNUNET_CRYPTO_aes_encrypt (in, (uint16_t) size,
487                                             &kx->encrypt_key, iv, out));
488   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes encrypted"), size,
489                             GNUNET_NO);
490 #if DEBUG_CORE > 2
491   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
492               "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
493               (unsigned int) size, GNUNET_i2s (&kx->peer),
494               (unsigned int) kx->encrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
495                                                                           sizeof
496                                                                           (iv)));
497 #endif
498   return GNUNET_OK;
499 }
500
501
502
503
504 /**
505  * Decrypt size bytes from in and write the result to out.  Use the
506  * key for inbound traffic of the given neighbour.  This function does
507  * NOT do any integrity-checks on the result.
508  *
509  * @param kx key information context
510  * @param iv initialization vector to use
511  * @param in ciphertext
512  * @param out plaintext
513  * @param size size of in/out
514  * @return GNUNET_OK on success
515  */
516 static int
517 do_decrypt (struct GSC_KeyExchangeInfo *kx,
518             const struct GNUNET_CRYPTO_AesInitializationVector *iv,
519             const void *in, void *out, size_t size)
520 {
521   if (size != (uint16_t) size)
522   {
523     GNUNET_break (0);
524     return GNUNET_NO;
525   }
526   if ((kx->status != KX_STATE_KEY_RECEIVED) &&
527       (kx->status != KX_STATE_UP))
528   {
529     GNUNET_break_op (0);
530     return GNUNET_SYSERR;
531   }
532   if (size !=
533       GNUNET_CRYPTO_aes_decrypt (in, (uint16_t) size, &kx->decrypt_key, iv, out))
534   {
535     GNUNET_break (0);
536     return GNUNET_SYSERR;
537   }
538   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes decrypted"), size,
539                             GNUNET_NO);
540 #if DEBUG_CORE > 1
541   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
542               "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
543               (unsigned int) size, GNUNET_i2s (&kx->peer),
544               (unsigned int) kx->decrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
545                                                                           sizeof
546                                                                           (*iv)));
547 #endif
548   return GNUNET_OK;
549 }
550
551
552 /**
553  * Send our key (and encrypted PING) to the other peer.
554  *
555  * @param kx key exchange context
556  */
557 static void
558 send_key (struct GSC_KeyExchangeInfo *kx);
559
560
561 /**
562  * Task that will retry "send_key" if our previous attempt failed.
563  *
564  * @param cls our 'struct GSC_KeyExchangeInfo'
565  * @param tc scheduler context
566  */
567 static void
568 set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
569 {
570   struct GSC_KeyExchangeInfo *kx = cls;
571
572   kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
573   kx->set_key_retry_frequency = GNUNET_TIME_relative_multiply (kx->set_key_retry_frequency, 2);
574   send_key (kx);
575 }
576
577
578 /**
579  * PEERINFO is giving us a HELLO for a peer.  Add the public key to
580  * the neighbour's struct and continue with the key exchange.  Or, if
581  * we did not get a HELLO, just do nothing.
582  *
583  * @param cls the 'struct GSC_KeyExchangeInfo' to retry sending the key for
584  * @param peer the peer for which this is the HELLO
585  * @param hello HELLO message of that peer
586  * @param err_msg NULL if successful, otherwise contains error message
587  */
588 static void
589 process_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
590                const struct GNUNET_HELLO_Message *hello,
591                const char *err_msg)
592 {
593   struct GSC_KeyExchangeInfo *kx = cls;
594   struct SetKeyMessage *skm;
595
596   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->retry_set_key_task);
597   if (err_msg != NULL)
598   {
599     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
600                 _("Error in communication with PEERINFO service\n"));
601     kx->pitr = NULL;
602     return;
603   }
604   if (peer == NULL)
605   {
606     kx->pitr = NULL;
607     if (kx->public_key != NULL)
608       return; /* done here */
609 #if DEBUG_CORE
610     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
611                 "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
612                 GNUNET_i2s (&kx->peer));
613 #endif
614     GNUNET_STATISTICS_update (GSC_stats,
615                               gettext_noop
616                               ("# Delayed connecting due to lack of public key"),
617                               1, GNUNET_NO);
618     kx->retry_set_key_task =
619       GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
620                                     &set_key_retry_task, kx);
621     return;
622   }
623   if (kx->public_key != NULL)
624   {
625     /* already have public key, why are we here? */
626     GNUNET_break (0);
627     return;
628   }
629   kx->public_key =
630       GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
631   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, kx->public_key))
632   {
633     GNUNET_break (0);
634     GNUNET_free (kx->public_key);
635     kx->public_key = NULL;
636     return;
637   }
638   send_key (kx);
639   if (NULL != kx->skm_received)
640   {
641     skm = kx->skm_received;
642     kx->skm_received = NULL;
643     GSC_KX_handle_set_key (kx, &skm->header);
644     GNUNET_free (skm);
645   }
646 }
647
648
649 /**
650  * Start the key exchange with the given peer.
651  *
652  * @param pid identity of the peer to do a key exchange with
653  * @return key exchange information context
654  */
655 struct GSC_KeyExchangeInfo *
656 GSC_KX_start (const struct GNUNET_PeerIdentity *pid)
657 {
658   struct GSC_KeyExchangeInfo *kx;
659
660   kx = GNUNET_malloc (sizeof (struct GSC_KeyExchangeInfo));
661   kx->peer = *pid;
662   kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
663   kx->pitr = GNUNET_PEERINFO_iterate (peerinfo,
664                                       pid,
665                                       GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */,
666                                       &process_hello,
667                                       kx);  
668   return kx;
669 }
670
671
672 /**
673  * Stop key exchange with the given peer.  Clean up key material.
674  *
675  * @param kx key exchange to stop
676  */
677 void
678 GSC_KX_stop (struct GSC_KeyExchangeInfo *kx)
679 {
680   if (kx->pitr != NULL)
681   {
682     GNUNET_PEERINFO_iterate_cancel (kx->pitr);
683     kx->pitr = NULL;
684   }
685   if (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
686   {
687     GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
688     kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
689   }
690   if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
691   {
692     GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
693     kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
694   }
695   GNUNET_free_non_null (kx->skm_received);
696   GNUNET_free_non_null (kx->ping_received);
697   GNUNET_free_non_null (kx->pong_received);
698   GNUNET_free_non_null (kx->public_key);
699   GNUNET_free (kx);
700 }
701
702
703 /**
704  * We received a SET_KEY message.  Validate and update
705  * our key material and status.
706  *
707  * @param kx key exchange status for the corresponding peer
708  * @param msg the set key message we received
709  */
710 void
711 GSC_KX_handle_set_key (struct GSC_KeyExchangeInfo *kx,
712                        const struct GNUNET_MessageHeader *msg)
713 {
714   const struct SetKeyMessage *m;
715   struct GNUNET_TIME_Absolute t;
716   struct GNUNET_CRYPTO_AesSessionKey k;
717   struct PingMessage *ping;
718   struct PongMessage *pong;
719   enum KxStateMachine sender_status;
720   uint16_t size;
721   
722   size = ntohs (msg->size);
723   if (size != sizeof (struct SetKeyMessage))
724     {
725       GNUNET_break_op (0);
726       return;
727     }
728   m = (const struct SetKeyMessage*) msg;
729   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# session keys received"),
730                             1, GNUNET_NO);
731
732 #if DEBUG_CORE
733   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
734               "Core service receives `%s' request from `%4s'.\n", "SET_KEY",
735               GNUNET_i2s (&kx->peer));
736 #endif
737   if (kx->public_key == NULL)
738   {
739     GNUNET_free_non_null (kx->skm_received);
740     kx->skm_received = GNUNET_copy_message (msg);
741     return;
742   }
743   if (0 !=
744       memcmp (&m->target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
745   {
746     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
747                 _("`%s' is for `%s', not for me.  Ignoring.\n"),
748                 "SET_KEY", GNUNET_i2s (&m->target));
749     return;
750   }
751   if ((ntohl (m->purpose.size) !=
752        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
753        sizeof (struct GNUNET_TIME_AbsoluteNBO) +
754        sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
755        sizeof (struct GNUNET_PeerIdentity)) ||
756       (GNUNET_OK !=
757        GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_KEY, &m->purpose,
758                                  &m->signature, kx->public_key)))
759   {
760     /* invalid signature */
761     GNUNET_break_op (0);
762     return;
763   }
764   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
765   if (((kx->status == KX_STATE_KEY_RECEIVED) ||
766        (kx->status == KX_STATE_UP)) &&
767       (t.abs_value < kx->decrypt_key_created.abs_value))
768   {
769     /* this could rarely happen due to massive re-ordering of
770      * messages on the network level, but is most likely either
771      * a bug or some adversary messing with us.  Report. */
772     GNUNET_break_op (0);
773     return;
774   }
775   if ((GNUNET_CRYPTO_rsa_decrypt
776        (my_private_key, &m->encrypted_key, &k,
777         sizeof (struct GNUNET_CRYPTO_AesSessionKey)) !=
778        sizeof (struct GNUNET_CRYPTO_AesSessionKey)) ||
779       (GNUNET_OK != GNUNET_CRYPTO_aes_check_session_key (&k)))
780   {
781     /* failed to decrypt !? */
782     GNUNET_break_op (0);
783     return;
784   }
785   GNUNET_STATISTICS_update (GSC_stats,
786                             gettext_noop ("# SET_KEY messages decrypted"), 1,
787                             GNUNET_NO);
788   kx->decrypt_key = k;
789   if (kx->decrypt_key_created.abs_value != t.abs_value)
790   {
791     /* fresh key, reset sequence numbers */
792     kx->last_sequence_number_received = 0;
793     kx->last_packets_bitmap = 0;
794     kx->decrypt_key_created = t;
795   }
796   sender_status = (enum KxStateMachine) ntohl (m->sender_status);
797
798   switch (kx->status)
799   {
800   case KX_STATE_DOWN:
801     kx->status = KX_STATE_KEY_RECEIVED;
802     /* we're not up, so we are already doing 'send_key' */
803     break;
804   case KX_STATE_KEY_SENT:
805     kx->status = KX_STATE_KEY_RECEIVED;
806     /* we're not up, so we are already doing 'send_key' */
807     break;
808   case KX_STATE_KEY_RECEIVED:
809     /* we're not up, so we are already doing 'send_key' */
810     break;
811   case KX_STATE_UP:
812     if ( (sender_status == KX_STATE_DOWN) ||
813          (sender_status == KX_STATE_KEY_SENT) )
814       send_key (kx); /* we are up, but other peer is not! */
815     break;
816   default:
817     GNUNET_break (0);
818     break;
819   }
820   if (kx->ping_received != NULL)
821   {
822     ping = kx->ping_received;
823     kx->ping_received = NULL;
824     GSC_KX_handle_ping (kx, &ping->header);
825     GNUNET_free (ping);
826   }
827   if (kx->pong_received != NULL)
828   {
829     pong = kx->pong_received;
830     kx->pong_received = NULL;
831     GSC_KX_handle_pong (kx, &pong->header);
832     GNUNET_free (pong);
833   }
834 }
835
836
837 /**
838  * We received a PING message.  Validate and transmit
839  * a PONG message.
840  *
841  * @param kx key exchange status for the corresponding peer
842  * @param msg the encrypted PING message itself
843  */
844 void
845 GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *kx,
846                     const struct GNUNET_MessageHeader *msg)
847 {
848   const struct PingMessage *m;
849   struct PingMessage t;
850   struct PongMessage tx;
851   struct PongMessage tp;
852   struct GNUNET_CRYPTO_AesInitializationVector iv;
853   uint16_t msize;
854
855   msize = ntohs (msg->size);
856   if (msize != sizeof (struct PingMessage))
857     {
858       GNUNET_break_op (0);
859       return;
860     }
861   GNUNET_STATISTICS_update (GSC_stats, 
862                             gettext_noop ("# PING messages received"),
863                             1, GNUNET_NO);
864   if ( (kx->status != KX_STATE_KEY_RECEIVED) &&
865        (kx->status != KX_STATE_UP) )
866     {
867       /* defer */
868       GNUNET_free_non_null (kx->ping_received);
869       kx->ping_received = GNUNET_copy_message (msg);
870       return;
871     }
872   m = (const struct PingMessage*) msg;
873 #if DEBUG_CORE
874   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
875               "Core service receives `%s' request from `%4s'.\n", "PING",
876               GNUNET_i2s (&kx->peer));
877 #endif
878   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
879   if (GNUNET_OK !=
880       do_decrypt (kx, &iv, &m->target, &t.target,
881                   sizeof (struct PingMessage) - ((void *) &m->target -
882                                                  (void *) m)))
883   {
884     GNUNET_break_op (0);
885     return;
886   }
887   if (0 !=
888       memcmp (&t.target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
889   {
890     char sender[9];
891     char peer[9];
892
893     GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&kx->peer));
894     GNUNET_snprintf (peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
895     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
896                 _("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
897                 sender, GNUNET_i2s (&GSC_my_identity), peer);
898     GNUNET_break_op (0);
899     return;
900   }
901   /* construct PONG */
902   tx.inbound_bw_limit = kx->bw_in; // FIXME!
903   tx.challenge = t.challenge;
904   tx.target = t.target;
905   tp.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
906   tp.header.size = htons (sizeof (struct PongMessage));
907   tp.iv_seed =
908       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
909   derive_pong_iv (&iv, &kx->encrypt_key, tp.iv_seed, t.challenge, &kx->peer);
910   do_encrypt (kx, &iv, &tx.challenge, &tp.challenge,
911               sizeof (struct PongMessage) - ((void *) &tp.challenge -
912                                              (void *) &tp));
913   GNUNET_STATISTICS_update (GSC_stats, 
914                             gettext_noop ("# PONG messages created"), 1,
915                             GNUNET_NO);
916   GSC_NEIGHBOURS_transmit (&kx->peer,
917                            &tp.header,
918                            GNUNET_TIME_UNIT_FOREVER_REL /* FIXME: timeout */);
919 }
920
921
922 /**
923  * Create a fresh SET KEY message for transmission to the other peer.
924  * Also creates a new key.
925  *
926  * @param kx key exchange context to create SET KEY message for
927  */
928 static void
929 setup_fresh_setkey (struct GSC_KeyExchangeInfo *kx)
930 {
931   struct SetKeyMessage *skm;
932
933   GNUNET_CRYPTO_aes_create_session_key (&kx->encrypt_key);
934   kx->encrypt_key_created = GNUNET_TIME_absolute_get ();
935   skm = &kx->skm;
936   skm->header.size = htons (sizeof (struct SetKeyMessage));
937   skm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
938   skm->purpose.size =
939     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
940            sizeof (struct GNUNET_TIME_AbsoluteNBO) +
941            sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
942            sizeof (struct GNUNET_PeerIdentity));
943   skm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
944   skm->creation_time = GNUNET_TIME_absolute_hton (kx->encrypt_key_created);
945   skm->target = kx->peer;
946   GNUNET_assert (GNUNET_OK ==
947                  GNUNET_CRYPTO_rsa_encrypt (&kx->encrypt_key,
948                                             sizeof (struct
949                                                     GNUNET_CRYPTO_AesSessionKey),
950                                             kx->public_key, &skm->encrypted_key));
951   GNUNET_assert (GNUNET_OK ==
952                  GNUNET_CRYPTO_rsa_sign (my_private_key, &skm->purpose,
953                                          &skm->signature));
954 }
955
956
957 /**
958  * Create a fresh PING message for transmission to the other peer.
959  *
960  * @param kx key exchange context to create PING for
961  */
962 static void
963 setup_fresh_ping (struct GSC_KeyExchangeInfo *kx)
964 {
965   struct PingMessage pp;
966   struct PingMessage *pm;
967   struct GNUNET_CRYPTO_AesInitializationVector iv;
968
969   pm = &kx->ping;
970   pm->header.size = htons (sizeof (struct PingMessage));
971   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
972   pm->iv_seed =
973     GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
974   derive_iv (&iv, &kx->encrypt_key, pm->iv_seed, &kx->peer);
975   pp.challenge = kx->ping_challenge;
976   pp.target = kx->peer;
977   do_encrypt (kx, &iv, &pp.target, &pm->target,
978               sizeof (struct PingMessage) - ((void *) &pm->target -
979                                              (void *) pm));
980 }
981
982
983 /**
984  * Task triggered when a neighbour entry is about to time out
985  * (and we should prevent this by sending a PING).
986  *
987  * @param cls the 'struct GSC_KeyExchangeInfo'
988  * @param tc scheduler context (not used)
989  */
990 static void
991 send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
992 {
993   struct GSC_KeyExchangeInfo *kx = cls;
994   struct GNUNET_TIME_Relative retry;
995   struct GNUNET_TIME_Relative left;
996
997   kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
998   left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
999   if (left.rel_value == 0)
1000   {    
1001     GSC_SESSIONS_end (&kx->peer);
1002     kx->status = KX_STATE_DOWN;
1003     return;
1004   }
1005   setup_fresh_ping (kx);
1006   GSC_NEIGHBOURS_transmit (&kx->peer,
1007                            &kx->ping.header,
1008                            kx->set_key_retry_frequency);
1009   retry =
1010       GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
1011                                 MIN_PING_FREQUENCY);
1012   kx->keep_alive_task =
1013     GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
1014 }
1015
1016
1017 /**
1018  * We've seen a valid message from the other peer.
1019  * Update the time when the session would time out
1020  * and delay sending our keep alive message further.
1021  *
1022  * @param kx key exchange where we saw activity
1023  */
1024 static void
1025 update_timeout (struct GSC_KeyExchangeInfo *kx)
1026 {
1027   kx->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1028   if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
1029     GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
1030   kx->keep_alive_task =
1031     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
1032                                   (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1033                                    2), &send_keep_alive, kx);
1034 }
1035
1036
1037 /**
1038  * We received a PONG message.  Validate and update our status.
1039  *
1040  * @param kx key exchange context for the the PONG
1041  * @param m the encrypted PONG message itself
1042  */
1043 void
1044 GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx, const struct GNUNET_MessageHeader *msg)
1045 {
1046   const struct PongMessage *m;
1047   struct PongMessage t;
1048   struct GNUNET_CRYPTO_AesInitializationVector iv;
1049   uint16_t msize;
1050
1051   msize = ntohs (msg->size);
1052   if (msize != sizeof (struct PongMessage))
1053   {
1054     GNUNET_break_op (0);
1055     return;
1056   }
1057   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages received"),
1058                             1, GNUNET_NO);
1059
1060   if ( (kx->status != KX_STATE_KEY_RECEIVED) &&
1061        (kx->status != KX_STATE_UP) )
1062   {
1063     if (kx->status == KX_STATE_KEY_SENT)
1064     {
1065       GNUNET_free_non_null (kx->pong_received);
1066       kx->pong_received = GNUNET_copy_message (msg);
1067     }
1068     return;
1069   }
1070   m = (const struct PongMessage*) msg;
1071 #if DEBUG_HANDSHAKE
1072   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1073               "Core service receives `%s' response from `%4s'.\n", "PONG",
1074               GNUNET_i2s (&kx->peer));
1075 #endif
1076   /* mark as garbage, just to be sure */
1077   memset (&t, 255, sizeof (t));
1078   derive_pong_iv (&iv, &kx->decrypt_key, m->iv_seed, kx->ping_challenge,
1079                   &GSC_my_identity);
1080   if (GNUNET_OK !=
1081       do_decrypt (kx, &iv, &m->challenge, &t.challenge,
1082                   sizeof (struct PongMessage) - ((void *) &m->challenge -
1083                                                  (void *) m)))
1084   {
1085     GNUNET_break_op (0);
1086     return;
1087   }
1088   GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages decrypted"),
1089                             1, GNUNET_NO);
1090   if ((0 != memcmp (&t.target, &kx->peer, sizeof (struct GNUNET_PeerIdentity)))
1091       || (kx->ping_challenge != t.challenge))
1092   {
1093     /* PONG malformed */
1094 #if DEBUG_CORE
1095     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1096                 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
1097                 "PONG", GNUNET_i2s (&kx->peer),
1098                 (unsigned int) kx->ping_challenge);
1099     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100                 "Received malformed `%s' received from `%4s' with challenge %u\n",
1101                 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge);
1102 #endif
1103     return;
1104   }
1105   switch (kx->status)
1106   {
1107   case KX_STATE_DOWN:
1108     GNUNET_break (0);           /* should be impossible */
1109     return;
1110   case KX_STATE_KEY_SENT:
1111     GNUNET_break (0);           /* should be impossible */
1112     return;
1113   case KX_STATE_KEY_RECEIVED:
1114     GNUNET_STATISTICS_update (GSC_stats,
1115                               gettext_noop
1116                               ("# Session keys confirmed via PONG"), 1,
1117                               GNUNET_NO);
1118     kx->status = KX_STATE_UP;
1119     GSC_SESSIONS_create (&kx->peer, kx);
1120     GNUNET_assert (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK);
1121     GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
1122     kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
1123     GNUNET_assert (kx->keep_alive_task == GNUNET_SCHEDULER_NO_TASK);
1124     update_timeout (kx);
1125     break;
1126   case KX_STATE_UP:
1127     update_timeout (kx);
1128     break;
1129   default:
1130     GNUNET_break (0);
1131     break;
1132   }
1133 }
1134
1135
1136 /**
1137  * Send our key (and encrypted PING) to the other peer.
1138  *
1139  * @param kx key exchange context
1140  */
1141 static void
1142 send_key (struct GSC_KeyExchangeInfo *kx)
1143 {
1144   GNUNET_assert (kx->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK);
1145   if (KX_STATE_UP == kx->status) 
1146     return; /* nothing to do */
1147   if (kx->public_key == NULL)
1148   {
1149     /* lookup public key, then try again */
1150     kx->pitr =
1151       GNUNET_PEERINFO_iterate (peerinfo, &kx->peer,
1152                                GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */,
1153                                &process_hello, kx);
1154     return;
1155   }
1156
1157   /* update status */
1158   switch (kx->status)
1159   {
1160   case KX_STATE_DOWN:
1161     kx->status = KX_STATE_KEY_SENT;    
1162     /* setup SET KEY message */
1163     setup_fresh_setkey (kx);
1164     setup_fresh_ping (kx);
1165     GNUNET_STATISTICS_update (GSC_stats,
1166                               gettext_noop
1167                               ("# SET_KEY and PING messages created"), 1,
1168                               GNUNET_NO);
1169     break;
1170   case KX_STATE_KEY_SENT:
1171     break;
1172   case KX_STATE_KEY_RECEIVED:
1173     break;
1174   case KX_STATE_UP:
1175     GNUNET_break (0);
1176     return;
1177   default:
1178     GNUNET_break (0);
1179     return;
1180   }
1181
1182   /* always update sender status in SET KEY message */
1183   kx->skm.sender_status = htonl ((int32_t) kx->status);
1184
1185   GSC_NEIGHBOURS_transmit (&kx->peer,
1186                            &kx->skm.header,
1187                            kx->set_key_retry_frequency);
1188   GSC_NEIGHBOURS_transmit (&kx->peer,
1189                            &kx->ping.header,
1190                            kx->set_key_retry_frequency);
1191   kx->retry_set_key_task =
1192     GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
1193                                   &set_key_retry_task, kx);
1194 }
1195
1196
1197 /**
1198  * Encrypt and transmit a message with the given payload.
1199  *
1200  * @param kx key exchange context
1201  * @param bw_in bandwidth limit to transmit to the other peer;
1202  *              the other peer shall not send us more than the
1203  *              given rate
1204  * @param payload payload of the message
1205  * @param payload_size number of bytes in 'payload'
1206  */
1207 void
1208 GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
1209                              struct GNUNET_BANDWIDTH_Value32NBO bw_in,
1210                              const void *payload,
1211                              size_t payload_size)
1212 {
1213   size_t used = payload_size + sizeof (struct EncryptedMessage);
1214   char pbuf[used]; /* plaintext */
1215   char cbuf[used]; /* ciphertext */
1216   struct EncryptedMessage *em;  /* encrypted message */
1217   struct EncryptedMessage *ph;  /* plaintext header */
1218   struct GNUNET_CRYPTO_AesInitializationVector iv;
1219   struct GNUNET_CRYPTO_AuthKey auth_key;
1220
1221 #if DEBUG_CORE_QUOTA
1222   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1223               "Sending %u b/s as new limit to peer `%4s'\n",
1224               (unsigned int) ntohl (bw_in.value__),
1225               GNUNET_i2s (&kx->peer));
1226 #endif
1227   ph = (struct EncryptedMessage*) pbuf;
1228   ph->iv_seed =
1229       htonl (GNUNET_CRYPTO_random_u32
1230              (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
1231   ph->sequence_number = htonl (++kx->last_sequence_number_sent);
1232   ph->inbound_bw_limit = bw_in;
1233   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1234   memcpy (&ph[1], payload, payload_size);
1235
1236   em = (struct EncryptedMessage *) cbuf;
1237   em->header.size = htons (used);
1238   em->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
1239   em->iv_seed = ph->iv_seed;
1240   derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, &kx->peer);
1241   GNUNET_assert (GNUNET_OK ==
1242                  do_encrypt (kx, &iv, &ph->sequence_number, &em->sequence_number,
1243                              used - ENCRYPTED_HEADER_SIZE));
1244   derive_auth_key (&auth_key, &kx->encrypt_key, ph->iv_seed,
1245                    kx->encrypt_key_created);
1246   GNUNET_CRYPTO_hmac (&auth_key, &em->sequence_number,
1247                       used - ENCRYPTED_HEADER_SIZE, &em->hmac);
1248   GSC_NEIGHBOURS_transmit (&kx->peer,
1249                            &em->header,
1250                            GNUNET_TIME_UNIT_FOREVER_REL);
1251 }                  
1252
1253
1254 /**
1255  * Closure for 'deliver_message'
1256  */
1257 struct DeliverMessageContext
1258 {
1259   
1260   /**
1261    * Performance information for the connection.
1262    */
1263   const struct GNUNET_TRANSPORT_ATS_Information *atsi;
1264
1265   /**
1266    * Sender of the message.
1267    */
1268   const struct GNUNET_PeerIdentity *peer;
1269
1270   /**
1271    * Number of entries in 'atsi' array.
1272    */
1273   uint32_t atsi_count;
1274 };
1275
1276   
1277 /**
1278  * We received an encrypted message.  Decrypt, validate and
1279  * pass on to the appropriate clients.
1280  *
1281  * @param kx key exchange context for encrypting the message
1282  * @param m encrypted message
1283  * @param atsi performance data
1284  * @param atsi_count number of entries in ats (excluding 0-termination)
1285  */
1286 void
1287 GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *kx, 
1288                                  const struct GNUNET_MessageHeader *msg,
1289                                  const struct GNUNET_TRANSPORT_ATS_Information *atsi,
1290                                  uint32_t atsi_count)
1291 {
1292   const struct EncryptedMessage *m;
1293   struct EncryptedMessage *pt;  /* plaintext */
1294   GNUNET_HashCode ph;
1295   uint32_t snum;
1296   struct GNUNET_TIME_Absolute t;
1297   struct GNUNET_CRYPTO_AesInitializationVector iv;
1298   struct GNUNET_CRYPTO_AuthKey auth_key;
1299   struct DeliverMessageContext dmc;
1300   uint16_t size = ntohs (msg->size);
1301   char buf[size];
1302
1303   if (size <
1304       sizeof (struct EncryptedMessage) + sizeof (struct GNUNET_MessageHeader))
1305   {
1306     GNUNET_break_op (0);
1307     return;
1308   }
1309   m = (const struct EncryptedMessage*) msg;
1310   if ( (kx->status != KX_STATE_KEY_RECEIVED) &&
1311        (kx->status != KX_STATE_UP) )
1312   {
1313     GNUNET_STATISTICS_update (GSC_stats,
1314                               gettext_noop
1315                               ("# failed to decrypt message (no session key)"),
1316                               1, GNUNET_NO);
1317     return;
1318   }
1319   /* validate hash */
1320   derive_auth_key (&auth_key, &kx->decrypt_key, m->iv_seed,
1321                    kx->decrypt_key_created);
1322   GNUNET_CRYPTO_hmac (&auth_key, &m->sequence_number,
1323                       size - ENCRYPTED_HEADER_SIZE, &ph);
1324   if (0 != memcmp (&ph, &m->hmac, sizeof (GNUNET_HashCode)))
1325   {
1326     /* checksum failed */
1327     GNUNET_break_op (0);
1328     return;
1329   }
1330   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
1331   /* decrypt */
1332   if (GNUNET_OK !=
1333       do_decrypt (kx, &iv, &m->sequence_number, &buf[ENCRYPTED_HEADER_SIZE],
1334                   size - ENCRYPTED_HEADER_SIZE))
1335     return;
1336   pt = (struct EncryptedMessage *) buf;
1337
1338   /* validate sequence number */
1339   snum = ntohl (pt->sequence_number);
1340   if (kx->last_sequence_number_received == snum)
1341   {
1342     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1343                 "Received duplicate message, ignoring.\n");
1344     /* duplicate, ignore */
1345     GNUNET_STATISTICS_update (GSC_stats,
1346                               gettext_noop ("# bytes dropped (duplicates)"),
1347                               size, GNUNET_NO);
1348     return;
1349   }
1350   if ((kx->last_sequence_number_received > snum) &&
1351       (kx->last_sequence_number_received - snum > 32))
1352   {
1353     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1354                 "Received ancient out of sequence message, ignoring.\n");
1355     /* ancient out of sequence, ignore */
1356     GNUNET_STATISTICS_update (GSC_stats,
1357                               gettext_noop
1358                               ("# bytes dropped (out of sequence)"), size,
1359                               GNUNET_NO);
1360     return;
1361   }
1362   if (kx->last_sequence_number_received > snum)
1363   {
1364     unsigned int rotbit = 1 << (kx->last_sequence_number_received - snum - 1);
1365
1366     if ((kx->last_packets_bitmap & rotbit) != 0)
1367     {
1368       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1369                   "Received duplicate message, ignoring.\n");
1370       GNUNET_STATISTICS_update (GSC_stats,
1371                                 gettext_noop ("# bytes dropped (duplicates)"),
1372                                 size, GNUNET_NO);
1373       /* duplicate, ignore */
1374       return;
1375     }
1376     kx->last_packets_bitmap |= rotbit;
1377   }
1378   if (kx->last_sequence_number_received < snum)
1379   {
1380     unsigned int shift = (snum - kx->last_sequence_number_received);
1381
1382     if (shift >= 8 * sizeof (kx->last_packets_bitmap))
1383       kx->last_packets_bitmap = 0;
1384     else
1385       kx->last_packets_bitmap <<= shift;
1386     kx->last_sequence_number_received = snum;
1387   }
1388
1389   /* check timestamp */
1390   t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
1391   if (GNUNET_TIME_absolute_get_duration (t).rel_value >
1392       MAX_MESSAGE_AGE.rel_value)
1393   {
1394     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1395                 _("Message received far too old (%llu ms). Content ignored.\n"),
1396                 GNUNET_TIME_absolute_get_duration (t).rel_value);
1397     GNUNET_STATISTICS_update (GSC_stats,
1398                               gettext_noop
1399                               ("# bytes dropped (ancient message)"), size,
1400                               GNUNET_NO);
1401     return;
1402   }
1403
1404   /* process decrypted message(s) */
1405   update_timeout (kx);
1406   GSC_SESSIONS_update (&kx->peer,
1407                        pt->inbound_bw_limit);
1408   GNUNET_STATISTICS_update (GSC_stats,
1409                             gettext_noop ("# bytes of payload decrypted"),
1410                             size - sizeof (struct EncryptedMessage), GNUNET_NO);
1411   dmc.atsi = atsi;
1412   dmc.atsi_count = atsi_count;
1413   dmc.peer = &kx->peer;
1414   if (GNUNET_OK !=
1415       GNUNET_SERVER_mst_receive (mst, &dmc, &buf[sizeof (struct EncryptedMessage)],
1416                                  size - sizeof (struct EncryptedMessage),
1417                                  GNUNET_YES, GNUNET_NO))
1418     GNUNET_break_op (0);
1419 }
1420
1421
1422 /**
1423  * Deliver P2P message to interested clients.
1424  * Invokes send twice, once for clients that want the full message, and once
1425  * for clients that only want the header 
1426  *
1427  * @param cls always NULL
1428  * @param client who sent us the message (struct GSC_KeyExchangeInfo)
1429  * @param m the message
1430  */
1431 static void
1432 deliver_message (void *cls, void *client, const struct GNUNET_MessageHeader *m)
1433 {
1434   struct DeliverMessageContext *dmc = client;
1435
1436   GSC_CLIENTS_deliver_message (dmc->peer,
1437                                dmc->atsi, dmc->atsi_count,
1438                                m,
1439                                ntohs (m->size),
1440                                GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
1441   GSC_CLIENTS_deliver_message (dmc->peer,
1442                                dmc->atsi, dmc->atsi_count,
1443                                m,
1444                                sizeof (struct GNUNET_MessageHeader),
1445                                GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
1446 }
1447
1448
1449 /**
1450  * Initialize KX subsystem.
1451  *
1452  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1453  */
1454 int 
1455 GSC_KX_init ()
1456 {
1457   char *keyfile;
1458
1459   if (GNUNET_OK !=
1460       GNUNET_CONFIGURATION_get_value_filename (GSC_cfg, "GNUNETD", "HOSTKEY",
1461                                                &keyfile))
1462   {
1463     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1464                 _("Core service is lacking HOSTKEY configuration setting.  Exiting.\n"));
1465     return GNUNET_SYSERR;
1466   }
1467   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1468   GNUNET_free (keyfile);
1469   if (my_private_key == NULL)
1470   {
1471     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1472                 _("Core service could not access hostkey.  Exiting.\n"));
1473     return GNUNET_SYSERR;
1474   }
1475   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1476   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1477                       &GSC_my_identity.hashPubKey);
1478   peerinfo = GNUNET_PEERINFO_connect (GSC_cfg);
1479   if (NULL == peerinfo)
1480   {
1481     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1482                 _("Could not access PEERINFO service.  Exiting.\n"));
1483     GNUNET_CRYPTO_rsa_key_free (my_private_key);
1484     my_private_key = NULL;
1485     return GNUNET_SYSERR;
1486   }
1487   mst = GNUNET_SERVER_mst_create (&deliver_message, NULL);
1488   return GNUNET_OK;
1489 }
1490
1491
1492 /**
1493  * Shutdown KX subsystem.
1494  */
1495 void 
1496 GSC_KX_done ()
1497 {
1498   if (my_private_key != NULL)
1499   {
1500     GNUNET_CRYPTO_rsa_key_free (my_private_key);
1501     my_private_key = NULL;
1502   }
1503   if (peerinfo != NULL)
1504   {
1505     GNUNET_PEERINFO_disconnect (peerinfo);
1506     peerinfo = NULL;
1507   }
1508   if (mst != NULL)
1509   {
1510     GNUNET_SERVER_mst_destroy (mst);
1511     mst = NULL;
1512   }
1513 }
1514
1515 /* end of gnunet-service-core_kx.c */