full support for ATSi parsing
[oweals/gnunet.git] / src / core / core_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010 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/core_api.c
23  * @brief core service; this is the main API for encrypted P2P
24  *        communications
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_core_service.h"
30 #include "core.h"
31
32
33 /**
34  * Information we track for each peer.
35  */
36 struct PeerRecord
37 {
38
39   /**
40    * We generally do NOT keep peer records in a DLL; this
41    * DLL is only used IF this peer's 'pending_head' message
42    * is ready for transmission.  
43    */
44   struct PeerRecord *prev;
45
46   /**
47    * We generally do NOT keep peer records in a DLL; this
48    * DLL is only used IF this peer's 'pending_head' message
49    * is ready for transmission. 
50    */
51   struct PeerRecord *next;
52
53   /**
54    * Peer the record is about.
55    */
56   struct GNUNET_PeerIdentity peer;
57
58   /**
59    * Corresponding core handle.
60    */
61   struct GNUNET_CORE_Handle *ch;
62
63   /**
64    * Head of doubly-linked list of pending requests.
65    * Requests are sorted by deadline *except* for HEAD,
66    * which is only modified upon transmission to core.
67    */
68   struct GNUNET_CORE_TransmitHandle *pending_head;
69
70   /**
71    * Tail of doubly-linked list of pending requests.
72    */
73   struct GNUNET_CORE_TransmitHandle *pending_tail;
74
75   /**
76    * Pending callback waiting for peer information, or NULL for none.
77    */
78   GNUNET_CORE_PeerConfigurationInfoCallback pcic;
79
80   /**
81    * Closure for pcic.
82    */
83   void *pcic_cls;
84
85   /**
86    * Request information ID for the given pcic (needed in case a
87    * request is cancelled after being submitted to core and a new
88    * one is generated; in this case, we need to avoid matching the
89    * reply to the first (cancelled) request to the second request).
90    */
91   uint32_t rim_id;
92
93   /**
94    * ID of timeout task for the 'pending_head' handle
95    * which is the one with the smallest timeout. 
96    */
97   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
98
99   /**
100    * Current size of the queue of pending requests.
101    */
102   unsigned int queue_size;
103
104   /**
105    * SendMessageRequest ID generator for this peer.
106    */
107   uint16_t smr_id_gen;
108   
109 };
110
111
112 /**
113  * Entry in a doubly-linked list of control messages to be transmitted
114  * to the core service.  Control messages include traffic allocation,
115  * connection requests and of course our initial 'init' request.
116  * 
117  * The actual message is allocated at the end of this struct.
118  */
119 struct ControlMessage
120 {
121   /**
122    * This is a doubly-linked list.
123    */
124   struct ControlMessage *next;
125
126   /**
127    * This is a doubly-linked list.
128    */
129   struct ControlMessage *prev;
130
131   /**
132    * Function to run after successful transmission (or call with
133    * reason 'TIMEOUT' on error); called with scheduler context 'NULL'
134    * on disconnect.
135    */
136   GNUNET_SCHEDULER_Task cont;
137
138   /**
139    * Closure for 'cont'.
140    */
141   void *cont_cls;
142
143   /**
144    * Transmit handle (if one is associated with this ControlMessage), or NULL.
145    */
146   struct GNUNET_CORE_TransmitHandle *th;
147 };
148
149
150
151 /**
152  * Context for the core service connection.
153  */
154 struct GNUNET_CORE_Handle
155 {
156
157   /**
158    * Configuration we're using.
159    */
160   const struct GNUNET_CONFIGURATION_Handle *cfg;
161
162   /**
163    * Closure for the various callbacks.
164    */
165   void *cls;
166
167   /**
168    * Function to call once we've handshaked with the core service.
169    */
170   GNUNET_CORE_StartupCallback init;
171
172   /**
173    * Function to call whenever we're notified about a peer connecting.
174    */
175   GNUNET_CORE_ConnectEventHandler connects;
176
177   /**
178    * Function to call whenever we're notified about a peer disconnecting.
179    */
180   GNUNET_CORE_DisconnectEventHandler disconnects;
181
182   /**
183    * Function to call whenever we're notified about a peer changing status.
184    */  
185   GNUNET_CORE_PeerStatusEventHandler status_events;
186   
187   /**
188    * Function to call whenever we receive an inbound message.
189    */
190   GNUNET_CORE_MessageCallback inbound_notify;
191
192   /**
193    * Function to call whenever we receive an outbound message.
194    */
195   GNUNET_CORE_MessageCallback outbound_notify;
196
197   /**
198    * Function handlers for messages of particular type.
199    */
200   const struct GNUNET_CORE_MessageHandler *handlers;
201
202   /**
203    * Our connection to the service.
204    */
205   struct GNUNET_CLIENT_Connection *client;
206
207   /**
208    * Handle for our current transmission request.
209    */
210   struct GNUNET_CLIENT_TransmitHandle *cth;
211
212   /**
213    * Head of doubly-linked list of pending requests.
214    */
215   struct ControlMessage *pending_head;
216
217   /**
218    * Tail of doubly-linked list of pending requests.
219    */
220   struct ControlMessage *pending_tail;
221
222   /**
223    * Head of doubly-linked list of peers that are core-approved
224    * to send their next message.
225    */
226   struct PeerRecord *ready_peer_head;
227
228   /**
229    * Tail of doubly-linked list of peers that are core-approved
230    * to send their next message.
231    */
232   struct PeerRecord *ready_peer_tail;
233
234   /**
235    * Hash map listing all of the peers that we are currently
236    * connected to.
237    */
238   struct GNUNET_CONTAINER_MultiHashMap *peers;
239
240   /**
241    * Identity of this peer.
242    */
243   struct GNUNET_PeerIdentity me;
244
245   /**
246    * ID of reconnect task (if any).
247    */
248   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
249
250   /**
251    * Current delay we use for re-trying to connect to core.
252    */
253   struct GNUNET_TIME_Relative retry_backoff;
254
255   /**
256    * Request information ID generator.
257    */
258   uint32_t rim_id_gen;
259
260   /**
261    * Number of messages we are allowed to queue per target.
262    */
263   unsigned int queue_size;
264
265   /**
266    * Number of entries in the handlers array.
267    */
268   unsigned int hcnt;
269
270   /**
271    * For inbound notifications without a specific handler, do
272    * we expect to only receive headers?
273    */
274   int inbound_hdr_only;
275
276   /**
277    * For outbound notifications without a specific handler, do
278    * we expect to only receive headers?
279    */
280   int outbound_hdr_only;
281
282   /**
283    * Are we currently disconnected and hence unable to forward
284    * requests?
285    */
286   int currently_down;
287
288 };
289
290
291 /**
292  * Handle for a transmission request.
293  */
294 struct GNUNET_CORE_TransmitHandle
295 {
296
297   /**
298    * We keep active transmit handles in a doubly-linked list.
299    */
300   struct GNUNET_CORE_TransmitHandle *next;
301
302   /**
303    * We keep active transmit handles in a doubly-linked list.
304    */
305   struct GNUNET_CORE_TransmitHandle *prev;
306
307   /**
308    * Corresponding peer record.
309    */
310   struct PeerRecord *peer;
311
312   /**
313    * Corresponding SEND_REQUEST message.  Only non-NULL 
314    * while SEND_REQUEST message is pending.
315    */
316   struct ControlMessage *cm;
317
318   /**
319    * Function that will be called to get the actual request
320    * (once we are ready to transmit this request to the core).
321    * The function will be called with a NULL buffer to signal
322    * timeout.
323    */
324   GNUNET_CONNECTION_TransmitReadyNotify get_message;
325
326   /**
327    * Closure for get_message.
328    */
329   void *get_message_cls;
330
331   /**
332    * Timeout for this handle.
333    */
334   struct GNUNET_TIME_Absolute timeout;
335
336   /**
337    * How important is this message?
338    */
339   uint32_t priority;
340
341   /**
342    * Size of this request.
343    */
344   uint16_t msize;
345
346   /**
347    * Send message request ID for this request.
348    */
349   uint16_t smr_id;
350
351 };
352
353
354 /**
355  * Our current client connection went down.  Clean it up
356  * and try to reconnect!
357  *
358  * @param h our handle to the core service
359  */
360 static void
361 reconnect (struct GNUNET_CORE_Handle *h);
362
363
364 /**
365  * Task schedule to try to re-connect to core.
366  *
367  * @param cls the 'struct GNUNET_CORE_Handle'
368  * @param tc task context
369  */
370 static void
371 reconnect_task (void *cls, 
372                 const struct GNUNET_SCHEDULER_TaskContext *tc)
373 {
374   struct GNUNET_CORE_Handle *h = cls;
375
376   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
377 #if DEBUG_CORE
378   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
379               "Connecting to CORE service after delay\n");
380 #endif
381   reconnect (h);
382 }
383
384
385 /**
386  * Notify clients about disconnect and free 
387  * the entry for connected peer.
388  *
389  * @param cls the 'struct GNUNET_CORE_Handle*'
390  * @param key the peer identity (not used)
391  * @param value the 'struct PeerRecord' to free.
392  * @return GNUNET_YES (continue)
393  */
394 static int
395 disconnect_and_free_peer_entry (void *cls,
396                                 const GNUNET_HashCode *key,
397                                 void *value)
398 {
399   static struct GNUNET_BANDWIDTH_Value32NBO zero;
400   struct GNUNET_CORE_Handle *h = cls;
401   struct GNUNET_CORE_TransmitHandle *th;
402   struct PeerRecord *pr = value;
403   GNUNET_CORE_PeerConfigurationInfoCallback pcic;
404
405   while (NULL != (th = pr->pending_head))
406     {
407       GNUNET_CONTAINER_DLL_remove (pr->pending_head,
408                                    pr->pending_tail,
409                                    th);
410       pr->queue_size--;
411       GNUNET_assert (0 == 
412                      th->get_message (th->get_message_cls,
413                                       0, NULL));
414       GNUNET_free (th);
415     }
416   if (NULL != (pcic = pr->pcic))
417     {
418       pr->pcic = NULL;
419       pcic (pr->pcic_cls,
420             &pr->peer,
421             zero,
422             0, 0);
423     }
424   if (pr->timeout_task != GNUNET_SCHEDULER_NO_TASK)
425     {
426       GNUNET_SCHEDULER_cancel (pr->timeout_task);
427       pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
428     }
429   GNUNET_assert (pr->queue_size == 0);
430   if ( (pr->prev != NULL) ||
431        (pr->next != NULL) ||
432        (h->ready_peer_head == pr) )
433     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head,
434                                  h->ready_peer_tail,
435                                  pr);
436   if (h->disconnects != NULL)
437     h->disconnects (h->cls,
438                     &pr->peer);    
439   GNUNET_assert (GNUNET_YES ==
440                  GNUNET_CONTAINER_multihashmap_remove (h->peers,
441                                                        key,
442                                                        pr));
443   GNUNET_assert (pr->pending_head == NULL);
444   GNUNET_assert (pr->pending_tail == NULL);
445   GNUNET_assert (pr->ch = h);
446   GNUNET_assert (pr->queue_size == 0);
447   GNUNET_assert (pr->timeout_task == GNUNET_SCHEDULER_NO_TASK);
448   GNUNET_free (pr);  
449   return GNUNET_YES;
450 }
451
452
453 /**
454  * Close down any existing connection to the CORE service and
455  * try re-establishing it later.
456  *
457  * @param h our handle
458  */
459 static void
460 reconnect_later (struct GNUNET_CORE_Handle *h)
461 {
462   struct ControlMessage *cm;
463   struct PeerRecord *pr;
464
465   while (NULL != (cm = h->pending_head))
466     {
467       GNUNET_CONTAINER_DLL_remove (h->pending_head,
468                                    h->pending_tail,
469                                    cm);
470       if (cm->th != NULL)
471         cm->th->cm = NULL; 
472       if (cm->cont != NULL)
473         cm->cont (cm->cont_cls, NULL);
474       GNUNET_free (cm);
475     }
476   if (h->client != NULL)
477     {
478       GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
479       h->client = NULL;
480       h->cth = NULL;
481       GNUNET_CONTAINER_multihashmap_iterate (h->peers,
482                                              &disconnect_and_free_peer_entry,
483                                              h);
484     }
485   while (NULL != (pr = h->ready_peer_head))    
486     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head,
487                                  h->ready_peer_tail,
488                                  pr);
489   
490   GNUNET_assert (h->pending_head == NULL);
491   h->currently_down = GNUNET_YES;
492   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
493   h->retry_backoff = GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS,
494                                                h->retry_backoff);
495   h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->retry_backoff,
496                                                     &reconnect_task,
497                                                     h);
498   h->retry_backoff = GNUNET_TIME_relative_multiply (h->retry_backoff, 2);
499 }
500
501
502 /**
503  * Check the list of pending requests, send the next
504  * one to the core.
505  *
506  * @param h core handle
507  * @param ignore_currently_down transmit message even if not initialized?
508  */
509 static void
510 trigger_next_request (struct GNUNET_CORE_Handle *h,
511                       int ignore_currently_down);
512
513
514 /**
515  * The given request hit its timeout.  Remove from the
516  * doubly-linked list and call the respective continuation.
517  *
518  * @param cls the transmit handle of the request that timed out
519  * @param tc context, can be NULL (!)
520  */
521 static void
522 transmission_timeout (void *cls, 
523                       const struct GNUNET_SCHEDULER_TaskContext *tc);
524
525
526 /**
527  * Send a control message to the peer asking for transmission
528  * of the message in the given peer record.
529  *
530  * @param pr peer to request transmission to
531  */
532 static void
533 request_next_transmission (struct PeerRecord *pr)
534 {
535   struct GNUNET_CORE_Handle *h = pr->ch;
536   struct ControlMessage *cm;
537   struct SendMessageRequest *smr;
538   struct GNUNET_CORE_TransmitHandle *th;
539
540   if (pr->timeout_task != GNUNET_SCHEDULER_NO_TASK)
541     {
542       GNUNET_SCHEDULER_cancel (pr->timeout_task);
543       pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
544     }
545   if (NULL == (th = pr->pending_head))
546     {
547       trigger_next_request (h, GNUNET_NO);
548       return;
549     }
550   GNUNET_assert (pr->prev == NULL);
551   GNUNET_assert (pr->next == NULL);
552   pr->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (th->timeout),
553                                                    &transmission_timeout,
554                                                    pr);
555   cm = GNUNET_malloc (sizeof (struct ControlMessage) + 
556                       sizeof (struct SendMessageRequest));
557   th->cm = cm;
558   cm->th = th;
559   smr = (struct SendMessageRequest*) &cm[1];
560   smr->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST);
561   smr->header.size = htons (sizeof (struct SendMessageRequest));
562   smr->priority = htonl (th->priority);
563   smr->deadline = GNUNET_TIME_absolute_hton (th->timeout);
564   smr->peer = pr->peer;
565   smr->queue_size = htonl (pr->queue_size);
566   smr->size = htons (th->msize);
567   smr->smr_id = htons (th->smr_id = pr->smr_id_gen++);
568   GNUNET_CONTAINER_DLL_insert_after (h->pending_head,
569                                      h->pending_tail,
570                                      h->pending_tail,
571                                      cm);
572 #if DEBUG_CORE
573   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
574               "Adding SEND REQUEST for peer `%s' to message queue\n",
575               GNUNET_i2s (&pr->peer));
576 #endif
577   trigger_next_request (h, GNUNET_NO);
578 }
579
580
581 /**
582  * The given request hit its timeout.  Remove from the
583  * doubly-linked list and call the respective continuation.
584  *
585  * @param cls the transmit handle of the request that timed out
586  * @param tc context, can be NULL (!)
587  */
588 static void
589 transmission_timeout (void *cls, 
590                       const struct GNUNET_SCHEDULER_TaskContext *tc)
591 {
592   struct PeerRecord *pr = cls;
593   struct GNUNET_CORE_TransmitHandle *th;
594
595   pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
596   th = pr->pending_head;
597   GNUNET_CONTAINER_DLL_remove (pr->pending_head,
598                                pr->pending_tail,
599                                th);
600   pr->queue_size--;
601 #if DEBUG_CORE
602   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
603               "Signalling timeout of request for transmission to CORE service\n");
604 #endif
605   GNUNET_assert (0 == th->get_message (th->get_message_cls, 0, NULL));
606   request_next_transmission (pr);
607 }
608
609
610 /**
611  * Transmit the next message to the core service.
612  */
613 static size_t
614 transmit_message (void *cls,
615                   size_t size, 
616                   void *buf)
617 {
618   struct GNUNET_CORE_Handle *h = cls;
619   struct ControlMessage *cm;
620   struct GNUNET_CORE_TransmitHandle *th;
621   struct PeerRecord *pr;
622   struct SendMessage *sm;
623   const struct GNUNET_MessageHeader *hdr;
624   uint16_t msize;
625   size_t ret;
626
627   h->cth = NULL;
628   if (buf == NULL)
629     {
630 #if DEBUG_CORE
631       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
632                   "Transmission failed, initiating reconnect\n");
633 #endif
634       reconnect_later (h);
635       return 0;
636     }
637   /* first check for control messages */
638   if (NULL != (cm = h->pending_head))
639     {
640       hdr = (const struct GNUNET_MessageHeader*) &cm[1];
641       msize = ntohs (hdr->size);
642       if (size < msize)
643         {
644           trigger_next_request (h, GNUNET_NO);
645           return 0;
646         }
647 #if DEBUG_CORE
648       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
649                   "Transmitting control message with %u bytes of type %u to core.\n",
650                   (unsigned int) msize,
651                   (unsigned int) ntohs (hdr->type));
652 #endif
653       memcpy (buf, hdr, msize);
654       GNUNET_CONTAINER_DLL_remove (h->pending_head,
655                                    h->pending_tail,
656                                    cm);     
657       if (cm->th != NULL)
658         cm->th->cm = NULL;
659       if (NULL != cm->cont)
660         GNUNET_SCHEDULER_add_continuation (cm->cont, 
661                                            cm->cont_cls,
662                                            GNUNET_SCHEDULER_REASON_PREREQ_DONE);
663       GNUNET_free (cm);
664       trigger_next_request (h, GNUNET_NO);
665       return msize;
666     }
667   /* now check for 'ready' P2P messages */
668   if (NULL != (pr = h->ready_peer_head))
669     {
670       GNUNET_assert (pr->pending_head != NULL);
671       th = pr->pending_head;
672       if (size < th->msize + sizeof (struct SendMessage))
673         {
674           trigger_next_request (h, GNUNET_NO);
675           return 0;
676         }
677       GNUNET_CONTAINER_DLL_remove (h->ready_peer_head,
678                                    h->ready_peer_tail,
679                                    pr);
680       GNUNET_CONTAINER_DLL_remove (pr->pending_head,
681                                    pr->pending_tail,
682                                    th);
683       pr->queue_size--;
684       if (pr->timeout_task != GNUNET_SCHEDULER_NO_TASK)
685         {
686           GNUNET_SCHEDULER_cancel (pr->timeout_task);
687           pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
688         }
689 #if DEBUG_CORE
690       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
691                   "Transmitting SEND request to `%s' with %u bytes.\n",
692                   GNUNET_i2s (&pr->peer),
693                   (unsigned int) th->msize);
694 #endif
695       sm = (struct SendMessage *) buf;
696       sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND);
697       sm->priority = htonl (th->priority);
698       sm->deadline = GNUNET_TIME_absolute_hton (th->timeout);
699       sm->peer = pr->peer;
700       ret = th->get_message (th->get_message_cls,
701                              size - sizeof (struct SendMessage),
702                              &sm[1]);
703
704       if (0 == ret)
705         {
706 #if DEBUG_CORE
707           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
708                       "Size of clients message to peer %s is 0!\n",
709                       GNUNET_i2s(&pr->peer));
710 #endif
711           /* client decided to send nothing! */
712           request_next_transmission (pr);
713           return 0;       
714         }
715 #if DEBUG_CORE
716       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
717                   "Produced SEND message to core with %u bytes payload\n",
718                   (unsigned int) ret);
719 #endif
720       GNUNET_assert (ret >= sizeof (struct GNUNET_MessageHeader));
721       if (ret + sizeof (struct SendMessage) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
722         {
723           GNUNET_break (0);
724           request_next_transmission (pr);
725           return 0;
726         }
727       ret += sizeof (struct SendMessage);
728       sm->header.size = htons (ret);
729       GNUNET_assert (ret <= size);
730       GNUNET_free (th);
731       request_next_transmission (pr);
732       return ret;
733     }
734   return 0;
735 }
736
737
738 /**
739  * Check the list of pending requests, send the next
740  * one to the core.
741  *
742  * @param h core handle
743  * @param ignore_currently_down transmit message even if not initialized?
744  */
745 static void
746 trigger_next_request (struct GNUNET_CORE_Handle *h,
747                       int ignore_currently_down)
748 {
749   uint16_t msize;
750
751   if ( (GNUNET_YES == h->currently_down) &&
752        (ignore_currently_down == GNUNET_NO) )
753     {
754 #if DEBUG_CORE
755       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
756                   "Core connection down, not processing queue\n");
757 #endif
758       return;
759     }
760   if (NULL != h->cth)
761     {
762 #if DEBUG_CORE
763       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
764                   "Request pending, not processing queue\n");
765 #endif
766       return;
767     }
768   if (h->pending_head != NULL)
769     msize = ntohs (((struct GNUNET_MessageHeader*) &h->pending_head[1])->size);    
770   else if (h->ready_peer_head != NULL) 
771     msize = h->ready_peer_head->pending_head->msize + sizeof (struct SendMessage);    
772   else
773     {
774 #if DEBUG_CORE
775       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
776                   "Request queue empty, not processing queue\n");
777 #endif
778       return; /* no pending message */
779     }
780   h->cth = GNUNET_CLIENT_notify_transmit_ready (h->client,
781                                                 msize,
782                                                 GNUNET_TIME_UNIT_FOREVER_REL,
783                                                 GNUNET_NO,
784                                                 &transmit_message, h);
785 }
786
787
788 /**
789  * Handler for notification messages received from the core.
790  *
791  * @param cls our "struct GNUNET_CORE_Handle"
792  * @param msg the message received from the core service
793  */
794 static void
795 main_notify_handler (void *cls, 
796                      const struct GNUNET_MessageHeader *msg)
797 {
798   struct GNUNET_CORE_Handle *h = cls;
799   const struct InitReplyMessage *m;
800   const struct ConnectNotifyMessage *cnm;
801   const struct DisconnectNotifyMessage *dnm;
802   const struct NotifyTrafficMessage *ntm;
803   const struct GNUNET_MessageHeader *em;
804   const struct ConfigurationInfoMessage *cim;
805   const struct PeerStatusNotifyMessage *psnm;
806   const struct SendMessageReady *smr;
807   const struct GNUNET_CORE_MessageHandler *mh;
808   GNUNET_CORE_StartupCallback init;
809   GNUNET_CORE_PeerConfigurationInfoCallback pcic;
810   struct PeerRecord *pr;
811   struct GNUNET_CORE_TransmitHandle *th;
812   unsigned int hpos;
813   int trigger;
814   uint16_t msize;
815   uint16_t et;
816   uint32_t ats_count;
817
818   if (msg == NULL)
819     {
820       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
821                   _
822                   ("Client was disconnected from core service, trying to reconnect.\n"));
823       reconnect_later (h);
824       return;
825     }
826   msize = ntohs (msg->size);
827 #if DEBUG_CORE
828   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
829               "Processing message of type %u and size %u from core service\n",
830               ntohs (msg->type), msize);
831 #endif
832   switch (ntohs (msg->type))
833     {
834     case GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY:
835       if (ntohs (msg->size) != sizeof (struct InitReplyMessage))
836         {
837           GNUNET_break (0);
838           reconnect_later (h);
839           return;
840         }
841       m = (const struct InitReplyMessage *) msg;
842       GNUNET_break (0 == ntohl (m->reserved));
843       /* start our message processing loop */
844       if (GNUNET_YES == h->currently_down)
845         {
846           h->currently_down = GNUNET_NO;
847           trigger_next_request (h, GNUNET_NO);
848         }
849       h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
850       if (NULL != (init = h->init))
851         {
852           /* mark so we don't call init on reconnect */
853           h->init = NULL;
854           GNUNET_CRYPTO_hash (&m->publicKey,
855                               sizeof (struct
856                                       GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
857                               &h->me.hashPubKey);
858 #if DEBUG_CORE
859           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
860                       "Connected to core service of peer `%s'.\n",
861                       GNUNET_i2s (&h->me));
862 #endif
863           init (h->cls, h, &h->me, &m->publicKey);
864         }
865       else
866         {
867 #if DEBUG_CORE
868           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
869                       "Successfully reconnected to core service.\n");
870 #endif
871         }
872       break;
873     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT:
874       if (msize < sizeof (struct ConnectNotifyMessage))
875         {
876           GNUNET_break (0);
877           reconnect_later (h);
878           return;
879         }
880       cnm = (const struct ConnectNotifyMessage *) msg;
881       ats_count = ntohl (cnm->ats_count);
882       if ( (msize != sizeof (struct ConnectNotifyMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)) ||
883            (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR != ntohl ((&cnm->ats)[ats_count].type)) )
884         {
885           GNUNET_break (0);
886           reconnect_later (h);
887           return;
888         }
889 #if DEBUG_CORE
890       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
891                   "Received notification about connection from `%s'.\n",
892                   GNUNET_i2s (&cnm->peer));
893 #endif
894       if (0 == memcmp (&h->me,
895                        &cnm->peer,
896                        sizeof (struct GNUNET_PeerIdentity)))
897         {
898           /* disconnect from self!? */
899           GNUNET_break (0);
900           return;
901         }
902       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
903                                               &cnm->peer.hashPubKey);
904       if (pr != NULL)
905         {
906           GNUNET_break (0);
907           reconnect_later (h);
908           return;
909         }
910       pr = GNUNET_malloc (sizeof (struct PeerRecord));
911       pr->peer = cnm->peer;
912       pr->ch = h;
913       GNUNET_assert (GNUNET_YES ==
914                      GNUNET_CONTAINER_multihashmap_put (h->peers,
915                                                         &cnm->peer.hashPubKey,
916                                                         pr,
917                                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
918       if (NULL != h->connects)
919         h->connects (h->cls,
920                      &cnm->peer,
921                      &cnm->ats);
922       break;
923     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT:
924       if (msize != sizeof (struct DisconnectNotifyMessage))
925         {
926           GNUNET_break (0);
927           reconnect_later (h);
928           return;
929         }
930       dnm = (const struct DisconnectNotifyMessage *) msg;
931       if (0 == memcmp (&h->me,
932                        &dnm->peer,
933                        sizeof (struct GNUNET_PeerIdentity)))
934         {
935           /* connection to self!? */
936           GNUNET_break (0);
937           return;
938         }
939 #if DEBUG_CORE
940       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
941                   "Received notification about disconnect from `%s'.\n",
942                   GNUNET_i2s (&dnm->peer));
943 #endif
944       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
945                                               &dnm->peer.hashPubKey);
946       if (pr == NULL)
947         {
948           GNUNET_break (0);
949           reconnect_later (h);
950           return;
951         }
952       trigger = ( (pr->prev != NULL) ||
953                   (pr->next != NULL) ||
954                   (h->ready_peer_head == pr) );
955       disconnect_and_free_peer_entry (h, &dnm->peer.hashPubKey, pr);
956       if (trigger)
957         trigger_next_request (h, GNUNET_NO);
958       break;
959     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE:
960       if (NULL == h->status_events)
961         {
962           GNUNET_break (0);
963           break;
964         }
965       if (msize < sizeof (struct PeerStatusNotifyMessage))
966         {
967           GNUNET_break (0);
968           reconnect_later (h);
969           return;
970         }
971       psnm = (const struct PeerStatusNotifyMessage *) msg;
972       if (0 == memcmp (&h->me,
973                        &psnm->peer,
974                        sizeof (struct GNUNET_PeerIdentity)))
975         {
976           /* self-change!? */
977           GNUNET_break (0);
978           return;
979         }
980       ats_count = ntohl (psnm->ats_count);
981       if ( (msize != sizeof (struct PeerStatusNotifyMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)) ||
982            (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR != ntohl ((&psnm->ats)[ats_count].type)) )
983         {
984           GNUNET_break (0);
985           reconnect_later (h);
986           return;
987         }
988 #if DEBUG_CORE
989       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
990                   "Received notification about status change by `%s'.\n",
991                   GNUNET_i2s (&psnm->peer));
992 #endif
993       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
994                                               &psnm->peer.hashPubKey);
995       if (pr == NULL)
996         {
997           GNUNET_break (0);
998           reconnect_later (h);
999           return;
1000         }
1001       h->status_events (h->cls,
1002                         &psnm->peer,
1003                         psnm->bandwidth_in,
1004                         psnm->bandwidth_out,
1005                         GNUNET_TIME_absolute_ntoh (psnm->timeout),
1006                         &psnm->ats);
1007       break;
1008     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND:
1009       if (msize < sizeof (struct NotifyTrafficMessage))
1010         {
1011           GNUNET_break (0);
1012           reconnect_later (h);
1013           return;
1014         }
1015       ntm = (const struct NotifyTrafficMessage *) msg;
1016       if (0 == memcmp (&h->me,
1017                        &ntm->peer,
1018                        sizeof (struct GNUNET_PeerIdentity)))
1019         {
1020           /* self-change!? */
1021           GNUNET_break (0);
1022           return;
1023         }
1024       ats_count = ntohl (ntm->ats_count);
1025       if ( (msize < sizeof (struct NotifyTrafficMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)
1026             + sizeof (struct GNUNET_MessageHeader)) ||
1027            (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR != ntohl ((&ntm->ats)[ats_count].type)) )
1028         {
1029           GNUNET_break (0);
1030           reconnect_later (h);
1031           return;
1032         }
1033       em = (const struct GNUNET_MessageHeader *) &(&ntm->ats)[ats_count+1];
1034 #if DEBUG_CORE
1035       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1036                   "Received message of type %u and size %u from peer `%4s'\n",
1037                   ntohs (em->type), 
1038                   ntohs (em->size),
1039                   GNUNET_i2s (&ntm->peer));
1040 #endif
1041       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1042                                               &ntm->peer.hashPubKey);
1043       if (pr == NULL)
1044         {
1045           GNUNET_break (0);
1046           reconnect_later (h);
1047           return;
1048         }
1049       if ((GNUNET_NO == h->inbound_hdr_only) &&
1050           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage) + 
1051            + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)) )
1052         {
1053           GNUNET_break (0);
1054           reconnect_later (h);
1055           return;
1056         }
1057       et = ntohs (em->type);
1058       for (hpos = 0; hpos < h->hcnt; hpos++)
1059         {
1060           mh = &h->handlers[hpos];
1061           if (mh->type != et)
1062             continue;
1063           if ((mh->expected_size != ntohs (em->size)) &&
1064               (mh->expected_size != 0))
1065             {
1066               GNUNET_break (0);
1067               continue;
1068             }
1069           if (GNUNET_OK !=
1070               h->handlers[hpos].callback (h->cls, &ntm->peer, em,
1071                                           &ntm->ats))
1072             {
1073               /* error in processing, do not process other messages! */
1074               break;
1075             }
1076         }
1077       if (NULL != h->inbound_notify)
1078         h->inbound_notify (h->cls, &ntm->peer, em,
1079                            &ntm->ats);
1080       break;
1081     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND:
1082       if (msize < sizeof (struct NotifyTrafficMessage))
1083         {
1084           GNUNET_break (0);
1085           reconnect_later (h);
1086           return;
1087         }
1088       ntm = (const struct NotifyTrafficMessage *) msg;
1089       if (0 == memcmp (&h->me,
1090                        &ntm->peer,
1091                        sizeof (struct GNUNET_PeerIdentity)))
1092         {
1093           /* self-change!? */
1094           GNUNET_break (0);
1095           return;
1096         }
1097       ats_count = ntohl (ntm->ats_count);
1098       if ( (msize < sizeof (struct NotifyTrafficMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)
1099             + sizeof (struct GNUNET_MessageHeader)) ||
1100            (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR != ntohl ((&ntm->ats)[ats_count].type)) )
1101         {
1102           GNUNET_break (0);
1103           reconnect_later (h);
1104           return;
1105         }
1106       em = (const struct GNUNET_MessageHeader *) &(&ntm->ats)[ats_count+1];
1107       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1108                                               &ntm->peer.hashPubKey);
1109       if (pr == NULL)
1110         {
1111           GNUNET_break (0);
1112           reconnect_later (h);
1113           return;
1114         }
1115 #if DEBUG_CORE
1116       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1117                   "Received notification about transmission to `%s'.\n",
1118                   GNUNET_i2s (&ntm->peer));
1119 #endif
1120       if ((GNUNET_NO == h->outbound_hdr_only) &&
1121           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage) + 
1122            + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)) )
1123         {
1124           GNUNET_break (0);
1125           reconnect_later (h);
1126           return;
1127         }
1128       if (NULL == h->outbound_notify)
1129         {
1130           GNUNET_break (0);
1131           break;
1132         }
1133       h->outbound_notify (h->cls, &ntm->peer, em,
1134                           &ntm->ats);
1135       break;
1136     case GNUNET_MESSAGE_TYPE_CORE_SEND_READY:
1137       if (msize != sizeof (struct SendMessageReady))
1138         {
1139           GNUNET_break (0);
1140           reconnect_later (h);
1141           return;
1142         }
1143       smr = (const struct SendMessageReady *) msg;
1144       if (0 == memcmp (&h->me,
1145                        &smr->peer,
1146                        sizeof (struct GNUNET_PeerIdentity)))
1147         {
1148           /* self-change!? */
1149           GNUNET_break (0);
1150           return;
1151         }
1152       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1153                                               &smr->peer.hashPubKey);
1154       if (pr == NULL)
1155         {
1156           GNUNET_break (0);
1157           reconnect_later (h);
1158           return;
1159         }
1160 #if DEBUG_CORE
1161       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1162                   "Received notification about transmission readiness to `%s'.\n",
1163                   GNUNET_i2s (&smr->peer));
1164 #endif
1165       if (pr->pending_head == NULL)
1166         {
1167           /* request must have been cancelled between the original request
1168              and the response from core, ignore core's readiness */
1169           return;
1170         }
1171
1172       th = pr->pending_head;
1173       if (ntohs (smr->smr_id) != th->smr_id)
1174         {
1175           /* READY message is for expired or cancelled message,
1176              ignore! (we should have already sent another request) */
1177           break;
1178         }
1179       if ( (pr->prev != NULL) ||
1180            (pr->next != NULL) ||
1181            (h->ready_peer_head == pr) )
1182         {
1183           /* we should not already be on the ready list... */
1184           GNUNET_break (0);
1185           reconnect_later (h);
1186           return;
1187         }
1188       GNUNET_CONTAINER_DLL_insert (h->ready_peer_head,
1189                                    h->ready_peer_tail,
1190                                    pr);
1191       trigger_next_request (h, GNUNET_NO);
1192       break;
1193     case GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO:
1194       if (ntohs (msg->size) != sizeof (struct ConfigurationInfoMessage))
1195         {
1196           GNUNET_break (0);
1197           reconnect_later (h);
1198           return;
1199         }
1200       cim = (const struct ConfigurationInfoMessage*) msg;
1201       if (0 == memcmp (&h->me,
1202                        &cim->peer,
1203                        sizeof (struct GNUNET_PeerIdentity)))
1204         {
1205           /* self-change!? */
1206           GNUNET_break (0);
1207           return;
1208         }
1209 #if DEBUG_CORE
1210       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1211                   "Received notification about configuration update for `%s'.\n",
1212                   GNUNET_i2s (&cim->peer));
1213 #endif
1214       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1215                                               &cim->peer.hashPubKey);
1216       if (pr == NULL)
1217         {
1218           GNUNET_break (0);
1219           reconnect_later (h);
1220           return;
1221         }
1222       if (pr->rim_id != ntohl (cim->rim_id))
1223         break;
1224       pcic = pr->pcic;
1225       pr->pcic = NULL;
1226       if (pcic != NULL)
1227         pcic (pr->pcic_cls,
1228               &pr->peer,
1229               cim->bw_out,
1230               ntohl (cim->reserved_amount),
1231               GNUNET_ntohll (cim->preference));
1232       break;
1233     default:
1234       reconnect_later (h);
1235       return;
1236     }
1237   GNUNET_CLIENT_receive (h->client,
1238                          &main_notify_handler, h, 
1239                          GNUNET_TIME_UNIT_FOREVER_REL);
1240 }
1241
1242
1243 /**
1244  * Task executed once we are done transmitting the INIT message.
1245  * Starts our 'receive' loop.
1246  *
1247  * @param cls the 'struct GNUNET_CORE_Handle'
1248  * @param tc task context
1249  */
1250 static void
1251 init_done_task (void *cls, 
1252                 const struct GNUNET_SCHEDULER_TaskContext *tc)
1253 {
1254   struct GNUNET_CORE_Handle *h = cls;
1255
1256   if (tc == NULL)
1257     return; /* error */
1258   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_PREREQ_DONE))
1259     {
1260 #if DEBUG_CORE
1261       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1262                   "Failed to exchange INIT with core, retrying\n");
1263 #endif
1264       reconnect_later (h);
1265       return;
1266     }
1267   GNUNET_CLIENT_receive (h->client,
1268                          &main_notify_handler, 
1269                          h, 
1270                          GNUNET_TIME_UNIT_FOREVER_REL);
1271 }
1272
1273
1274 /**
1275  * Our current client connection went down.  Clean it up
1276  * and try to reconnect!
1277  *
1278  * @param h our handle to the core service
1279  */
1280 static void
1281 reconnect (struct GNUNET_CORE_Handle *h)
1282 {
1283   struct ControlMessage *cm;
1284   struct InitMessage *init;
1285   uint32_t opt;
1286   uint16_t msize;
1287   uint16_t *ts;
1288   unsigned int hpos;
1289
1290 #if DEBUG_CORE
1291   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1292               "Reconnecting to CORE service\n");
1293 #endif
1294   GNUNET_assert (h->client == NULL);
1295   GNUNET_assert (h->currently_down == GNUNET_YES);
1296   h->client = GNUNET_CLIENT_connect ("core", h->cfg);
1297   if (h->client == NULL)
1298     {
1299       reconnect_later (h);
1300       return;
1301     }
1302   msize = h->hcnt * sizeof (uint16_t) + sizeof (struct InitMessage);
1303   cm = GNUNET_malloc (sizeof (struct ControlMessage) +
1304                       msize);
1305   cm->cont = &init_done_task;
1306   cm->cont_cls = h;
1307   init = (struct InitMessage*) &cm[1];
1308   init->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT);
1309   init->header.size = htons (msize);
1310   opt = GNUNET_CORE_OPTION_SEND_CONNECT | GNUNET_CORE_OPTION_SEND_DISCONNECT;
1311   if (h->status_events != NULL)
1312     opt |= GNUNET_CORE_OPTION_SEND_STATUS_CHANGE;
1313   if (h->inbound_notify != NULL)
1314     {
1315       if (h->inbound_hdr_only)
1316         opt |= GNUNET_CORE_OPTION_SEND_HDR_INBOUND;
1317       else
1318         opt |= GNUNET_CORE_OPTION_SEND_FULL_INBOUND;
1319     }
1320   if (h->outbound_notify != NULL)
1321     {
1322       if (h->outbound_hdr_only)
1323         opt |= GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND;
1324       else
1325         opt |= GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND;
1326     }
1327   init->options = htonl (opt);
1328   ts = (uint16_t *) &init[1];
1329   for (hpos = 0; hpos < h->hcnt; hpos++)
1330     ts[hpos] = htons (h->handlers[hpos].type);
1331   GNUNET_CONTAINER_DLL_insert (h->pending_head,
1332                                h->pending_tail,
1333                                cm);
1334   trigger_next_request (h, GNUNET_YES);
1335 }
1336
1337
1338
1339 /**
1340  * Connect to the core service.  Note that the connection may
1341  * complete (or fail) asynchronously.
1342  *
1343  * @param cfg configuration to use
1344  * @param queue_size size of the per-peer message queue
1345  * @param cls closure for the various callbacks that follow (including handlers in the handlers array)
1346  * @param init callback to call on timeout or once we have successfully
1347  *        connected to the core service; note that timeout is only meaningful if init is not NULL
1348  * @param connects function to call on peer connect, can be NULL
1349  * @param disconnects function to call on peer disconnect / timeout, can be NULL
1350  * @param status_events function to call on changes to peer connection status, can be NULL
1351  * @param inbound_notify function to call for all inbound messages, can be NULL
1352  * @param inbound_hdr_only set to GNUNET_YES if inbound_notify will only read the
1353  *                GNUNET_MessageHeader and hence we do not need to give it the full message;
1354  *                can be used to improve efficiency, ignored if inbound_notify is NULLL
1355  * @param outbound_notify function to call for all outbound messages, can be NULL
1356  * @param outbound_hdr_only set to GNUNET_YES if outbound_notify will only read the
1357  *                GNUNET_MessageHeader and hence we do not need to give it the full message
1358  *                can be used to improve efficiency, ignored if outbound_notify is NULLL
1359  * @param handlers callbacks for messages we care about, NULL-terminated
1360  * @return handle to the core service (only useful for disconnect until 'init' is called);
1361  *                NULL on error (in this case, init is never called)
1362  */
1363 struct GNUNET_CORE_Handle *
1364 GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1365                      unsigned int queue_size,
1366                      void *cls,
1367                      GNUNET_CORE_StartupCallback init,
1368                      GNUNET_CORE_ConnectEventHandler connects,
1369                      GNUNET_CORE_DisconnectEventHandler disconnects,
1370                      GNUNET_CORE_PeerStatusEventHandler status_events,
1371                      GNUNET_CORE_MessageCallback inbound_notify,
1372                      int inbound_hdr_only,
1373                      GNUNET_CORE_MessageCallback outbound_notify,
1374                      int outbound_hdr_only,
1375                      const struct GNUNET_CORE_MessageHandler *handlers)
1376 {
1377   struct GNUNET_CORE_Handle *h;
1378
1379   h = GNUNET_malloc (sizeof (struct GNUNET_CORE_Handle));
1380   h->cfg = cfg;
1381   h->queue_size = queue_size;
1382   h->cls = cls;
1383   h->init = init;
1384   h->connects = connects;
1385   h->disconnects = disconnects;
1386   h->status_events = status_events;
1387   h->inbound_notify = inbound_notify;
1388   h->outbound_notify = outbound_notify;
1389   h->inbound_hdr_only = inbound_hdr_only;
1390   h->outbound_hdr_only = outbound_hdr_only;
1391   h->handlers = handlers;
1392   h->hcnt = 0;
1393   h->currently_down = GNUNET_YES;
1394   h->peers = GNUNET_CONTAINER_multihashmap_create (128);
1395   h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1396   while (handlers[h->hcnt].callback != NULL)
1397     h->hcnt++;
1398   GNUNET_assert (h->hcnt <
1399                  (GNUNET_SERVER_MAX_MESSAGE_SIZE -
1400                   sizeof (struct InitMessage)) / sizeof (uint16_t));
1401 #if DEBUG_CORE
1402   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1403               "Connecting to CORE service\n");
1404 #endif
1405   reconnect (h);
1406   return h;
1407 }
1408
1409
1410 /**
1411  * Disconnect from the core service.  This function can only 
1412  * be called *after* all pending 'GNUNET_CORE_notify_transmit_ready'
1413  * requests have been explicitly canceled.
1414  *
1415  * @param handle connection to core to disconnect
1416  */
1417 void
1418 GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle)
1419 {
1420   struct ControlMessage *cm;
1421   
1422 #if DEBUG_CORE
1423   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1424               "Disconnecting from CORE service\n");
1425 #endif
1426   if (handle->cth != NULL)
1427     {
1428       GNUNET_CLIENT_notify_transmit_ready_cancel (handle->cth);
1429       handle->cth = NULL;
1430     }
1431   if (handle->client != NULL)
1432     {
1433       GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
1434       handle->client = NULL;
1435     }
1436   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1437     {
1438       GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1439       handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1440     }
1441   while (NULL != (cm = handle->pending_head))
1442     {
1443       GNUNET_CONTAINER_DLL_remove (handle->pending_head,
1444                                    handle->pending_tail,
1445                                    cm);
1446       if (cm->th != NULL)
1447         cm->th->cm = NULL;
1448       if (cm->cont != NULL)
1449         cm->cont (cm->cont_cls, NULL);
1450       GNUNET_free (cm);
1451     }
1452   GNUNET_CONTAINER_multihashmap_iterate (handle->peers,
1453                                          &disconnect_and_free_peer_entry,
1454                                          handle);
1455   GNUNET_CONTAINER_multihashmap_destroy (handle->peers);
1456   GNUNET_break (handle->ready_peer_head == NULL);
1457   GNUNET_free (handle);
1458 }
1459
1460
1461 /**
1462  * Ask the core to call "notify" once it is ready to transmit the
1463  * given number of bytes to the specified "target".  If we are not yet
1464  * connected to the specified peer, a call to this function will cause
1465  * us to try to establish a connection.
1466  *
1467  * @param handle connection to core service
1468  * @param priority how important is the message?
1469  * @param maxdelay how long can the message wait?
1470  * @param target who should receive the message,
1471  *        use NULL for this peer (loopback)
1472  * @param notify_size how many bytes of buffer space does notify want?
1473  * @param notify function to call when buffer space is available
1474  * @param notify_cls closure for notify
1475  * @return non-NULL if the notify callback was queued,
1476  *         NULL if we can not even queue the request (insufficient
1477  *         memory); if NULL is returned, "notify" will NOT be called.
1478  */
1479 struct GNUNET_CORE_TransmitHandle *
1480 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle,
1481                                    uint32_t priority,
1482                                    struct GNUNET_TIME_Relative maxdelay,
1483                                    const struct GNUNET_PeerIdentity *target,
1484                                    size_t notify_size,
1485                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1486                                    void *notify_cls)
1487 {
1488   struct PeerRecord *pr;
1489   struct GNUNET_CORE_TransmitHandle *th;
1490   struct GNUNET_CORE_TransmitHandle *pos;
1491   struct GNUNET_CORE_TransmitHandle *prev;
1492   struct GNUNET_CORE_TransmitHandle *minp;
1493
1494   pr = GNUNET_CONTAINER_multihashmap_get (handle->peers,
1495                                           &target->hashPubKey);
1496   if (NULL == pr)
1497     {
1498       /* attempt to send to peer that is not connected */
1499       GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1500                  "Attempting to send to peer `%s' from peer `%s', but not connected!\n",
1501                  GNUNET_i2s(target), GNUNET_h2s(&handle->me.hashPubKey));
1502       GNUNET_break (0);
1503       return NULL;
1504     }
1505   GNUNET_assert (notify_size + sizeof (struct SendMessage) <
1506                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
1507   th = GNUNET_malloc (sizeof (struct GNUNET_CORE_TransmitHandle));
1508   th->peer = pr;
1509   th->get_message = notify;
1510   th->get_message_cls = notify_cls;
1511   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1512   th->priority = priority;
1513   th->msize = notify_size;
1514   /* bound queue size */
1515   if (pr->queue_size == handle->queue_size)
1516     {
1517       /* find lowest-priority entry */
1518       minp = pr->pending_head;
1519       prev = minp->next;
1520       while (prev != NULL)
1521         {
1522           if (prev->priority < minp->priority)
1523             minp = prev;
1524           prev = prev->next;
1525         }
1526       if (minp == NULL) 
1527         {
1528           GNUNET_break (handle->queue_size != 0);
1529           GNUNET_break (pr->queue_size == 0);
1530           return NULL;
1531         }
1532       if (priority <= minp->priority)
1533         {
1534 #if DEBUG_CORE
1535           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1536                       "Dropping transmission request: priority too low\n");
1537 #endif
1538           return NULL; /* priority too low */
1539         }
1540       GNUNET_CONTAINER_DLL_remove (pr->pending_head,
1541                                    pr->pending_tail,
1542                                    minp);
1543       pr->queue_size--;
1544       GNUNET_assert (0 ==
1545                      minp->get_message (minp->get_message_cls,
1546                                         0, NULL));
1547       GNUNET_free (minp);
1548     }
1549
1550   /* Order entries by deadline, but SKIP 'HEAD' if
1551      we're in the 'ready_peer_*' DLL */
1552   pos = pr->pending_head;
1553   if ( (pr->prev != NULL) ||
1554        (pr->next != NULL) ||
1555        (pr == handle->ready_peer_head) )
1556     {
1557       GNUNET_assert (pos != NULL);
1558       pos = pos->next; /* skip head */
1559     }
1560
1561   /* insertion sort */
1562   prev = pos;
1563   while ( (pos != NULL) &&
1564           (pos->timeout.abs_value < th->timeout.abs_value) )      
1565     {
1566       prev = pos;
1567       pos = pos->next;
1568     }
1569   GNUNET_CONTAINER_DLL_insert_after (pr->pending_head,
1570                                      pr->pending_tail,
1571                                      prev,
1572                                      th);
1573   pr->queue_size++;
1574   /* was the request queue previously empty? */
1575 #if DEBUG_CORE
1576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1577               "Transmission request added to queue\n");
1578 #endif
1579   if (pr->pending_head == th) 
1580     request_next_transmission (pr);
1581   return th;
1582 }
1583
1584
1585 /**
1586  * Cancel the specified transmission-ready notification.
1587  *
1588  * @param th handle that was returned by "notify_transmit_ready".
1589  */
1590 void
1591 GNUNET_CORE_notify_transmit_ready_cancel (struct GNUNET_CORE_TransmitHandle
1592                                           *th)
1593 {
1594   struct PeerRecord *pr = th->peer;
1595   struct GNUNET_CORE_Handle *h = pr->ch;
1596   int was_head;
1597   
1598   was_head = (pr->pending_head == th);
1599   GNUNET_CONTAINER_DLL_remove (pr->pending_head,
1600                                pr->pending_tail,
1601                                th);    
1602   pr->queue_size--;
1603   if (th->cm != NULL)
1604     {
1605       /* we're currently in the control queue, remove */
1606       GNUNET_CONTAINER_DLL_remove (h->pending_head,
1607                                    h->pending_tail,
1608                                    th->cm);
1609       GNUNET_free (th->cm);      
1610     }
1611   GNUNET_free (th);
1612   if (was_head)
1613     {
1614       if ( (pr->prev != NULL) ||
1615            (pr->next != NULL) ||
1616            (pr == h->ready_peer_head) )
1617         {
1618           /* the request that was 'approved' by core was
1619              canceled before it could be transmitted; remove
1620              us from the 'ready' list */
1621           GNUNET_CONTAINER_DLL_remove (h->ready_peer_head,
1622                                        h->ready_peer_tail,
1623                                        pr);
1624         }
1625       request_next_transmission (pr);
1626     }
1627 }
1628
1629
1630 /* ****************** GNUNET_CORE_peer_request_connect ******************** */
1631
1632 /**
1633  * Handle for a request to the core to connect to
1634  * a particular peer.  Can be used to cancel the request
1635  * (before the 'cont'inuation is called).
1636  */
1637 struct GNUNET_CORE_PeerRequestHandle
1638 {
1639
1640   /**
1641    * Link to control message.
1642    */
1643   struct ControlMessage *cm;
1644
1645   /**
1646    * Core handle used.
1647    */
1648   struct GNUNET_CORE_Handle *h;
1649
1650   /**
1651    * Continuation to run when done.
1652    */
1653   GNUNET_SCHEDULER_Task cont;
1654
1655   /**
1656    * Closure for 'cont'.
1657    */
1658   void *cont_cls;
1659
1660 };
1661
1662
1663 /**
1664  * Continuation called when the control message was transmitted.
1665  * Calls the original continuation and frees the remaining
1666  * resources.
1667  *
1668  * @param cls the 'struct GNUNET_CORE_PeerRequestHandle'
1669  * @param tc scheduler context
1670  */
1671 static void
1672 peer_request_connect_cont (void *cls,
1673                            const struct GNUNET_SCHEDULER_TaskContext *tc)
1674 {
1675   struct GNUNET_CORE_PeerRequestHandle *ret = cls;
1676   
1677   if (ret->cont != NULL)
1678     {
1679       if (tc == NULL)
1680         GNUNET_SCHEDULER_add_now (ret->cont,
1681                                   ret->cont_cls);
1682       else
1683         ret->cont (ret->cont_cls, tc);
1684     }
1685   GNUNET_free (ret);
1686 }
1687
1688
1689 /**
1690  * Request that the core should try to connect to a particular peer.
1691  * Once the request has been transmitted to the core, the continuation
1692  * function will be called.  Note that this does NOT mean that a
1693  * connection was successfully established -- it only means that the
1694  * core will now try.  Successful establishment of the connection
1695  * will be signalled to the 'connects' callback argument of
1696  * 'GNUNET_CORE_connect' only.  If the core service does not respond
1697  * to our connection attempt within the given time frame, 'cont' will
1698  * be called with the TIMEOUT reason code.
1699  *
1700  * @param h core handle
1701  * @param timeout how long to try to talk to core
1702  * @param peer who should we connect to
1703  * @param cont function to call once the request has been completed (or timed out)
1704  * @param cont_cls closure for cont
1705  * @return NULL on error (cont will not be called), otherwise handle for cancellation
1706  */
1707 struct GNUNET_CORE_PeerRequestHandle *
1708 GNUNET_CORE_peer_request_connect (struct GNUNET_CORE_Handle *h,
1709                                   struct GNUNET_TIME_Relative timeout,
1710                                   const struct GNUNET_PeerIdentity * peer,
1711                                   GNUNET_SCHEDULER_Task cont,
1712                                   void *cont_cls)
1713 {
1714   struct GNUNET_CORE_PeerRequestHandle *ret;
1715   struct ControlMessage *cm;
1716   struct ConnectMessage *msg;
1717   
1718   cm = GNUNET_malloc (sizeof (struct ControlMessage) + 
1719                       sizeof (struct ConnectMessage));
1720   msg = (struct ConnectMessage*) &cm[1];
1721   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT);
1722   msg->header.size = htons (sizeof (struct ConnectMessage));
1723   msg->reserved = htonl (0);
1724   msg->timeout = GNUNET_TIME_relative_hton (timeout);
1725   msg->peer = *peer;
1726   GNUNET_CONTAINER_DLL_insert (h->pending_head,
1727                                h->pending_tail,
1728                                cm);
1729   ret = GNUNET_malloc (sizeof (struct GNUNET_CORE_PeerRequestHandle));
1730   ret->h = h;
1731   ret->cm = cm;
1732   ret->cont = cont;
1733   ret->cont_cls = cont_cls;
1734   cm->cont = &peer_request_connect_cont;
1735   cm->cont_cls = ret;
1736 #if DEBUG_CORE
1737   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1738               "Queueing REQUEST_CONNECT request\n");
1739 #endif
1740   if (h->pending_head == cm)
1741     trigger_next_request (h, GNUNET_NO);
1742   return ret;
1743 }
1744
1745
1746 /**
1747  * Cancel a pending request to connect to a particular peer.  Must not
1748  * be called after the 'cont' function was invoked.
1749  *
1750  * @param req request handle that was returned for the original request
1751  */
1752 void
1753 GNUNET_CORE_peer_request_connect_cancel (struct GNUNET_CORE_PeerRequestHandle *req)
1754 {
1755   struct GNUNET_CORE_Handle *h = req->h;
1756   struct ControlMessage *cm = req->cm;
1757
1758   GNUNET_CONTAINER_DLL_remove (h->pending_head,
1759                                h->pending_tail,
1760                                cm);
1761   GNUNET_free (cm);
1762   GNUNET_free (req);
1763 }
1764
1765
1766 /* ****************** GNUNET_CORE_peer_change_preference ******************** */
1767
1768
1769 struct GNUNET_CORE_InformationRequestContext 
1770 {
1771   
1772   /**
1773    * Our connection to the service.
1774    */
1775   struct GNUNET_CORE_Handle *h;
1776
1777   /**
1778    * Function to call with the information.
1779    */
1780   GNUNET_CORE_PeerConfigurationInfoCallback info;
1781
1782   /**
1783    * Closure for info.
1784    */
1785   void *info_cls;
1786
1787   /**
1788    * Link to control message, NULL if CM was sent.
1789    */ 
1790   struct ControlMessage *cm;
1791
1792   /**
1793    * Link to peer record.
1794    */
1795   struct PeerRecord *pr;
1796 };
1797
1798
1799 /**
1800  * CM was sent, remove link so we don't double-free.
1801  *
1802  * @param cls the 'struct GNUNET_CORE_InformationRequestContext'
1803  * @param tc scheduler context
1804  */
1805 static void
1806 change_preference_send_continuation (void *cls,
1807                                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1808 {
1809   struct GNUNET_CORE_InformationRequestContext *irc = cls;
1810
1811   irc->cm = NULL;
1812 }
1813
1814
1815 /**
1816  * Obtain statistics and/or change preferences for the given peer.
1817  *
1818  * @param h core handle
1819  * @param peer identifies the peer
1820  * @param timeout after how long should we give up (and call "info" with NULL
1821  *                for "peer" to signal an error)?
1822  * @param bw_out set to the current bandwidth limit (sending) for this peer,
1823  *                caller should set "bw_out" to "-1" to avoid changing
1824  *                the current value; otherwise "bw_out" will be lowered to
1825  *                the specified value; passing a pointer to "0" can be used to force
1826  *                us to disconnect from the peer; "bw_out" might not increase
1827  *                as specified since the upper bound is generally
1828  *                determined by the other peer!
1829  * @param amount reserve N bytes for receiving, negative
1830  *                amounts can be used to undo a (recent) reservation;
1831  * @param preference increase incoming traffic share preference by this amount;
1832  *                in the absence of "amount" reservations, we use this
1833  *                preference value to assign proportional bandwidth shares
1834  *                to all connected peers
1835  * @param info function to call with the resulting configuration information
1836  * @param info_cls closure for info
1837  * @return NULL on error
1838  */
1839 struct GNUNET_CORE_InformationRequestContext *
1840 GNUNET_CORE_peer_change_preference (struct GNUNET_CORE_Handle *h,
1841                                     const struct GNUNET_PeerIdentity *peer,
1842                                     struct GNUNET_TIME_Relative timeout,
1843                                     struct GNUNET_BANDWIDTH_Value32NBO bw_out,
1844                                     int32_t amount,
1845                                     uint64_t preference,
1846                                     GNUNET_CORE_PeerConfigurationInfoCallback info,
1847                                     void *info_cls)
1848 {
1849   struct GNUNET_CORE_InformationRequestContext *irc;
1850   struct PeerRecord *pr;
1851   struct RequestInfoMessage *rim;
1852   struct ControlMessage *cm;
1853
1854   pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1855                                           &peer->hashPubKey);
1856   if (NULL == pr)
1857     {
1858       /* attempt to change preference on peer that is not connected */
1859       GNUNET_break (0);
1860       return NULL;
1861     }
1862   if (pr->pcic != NULL)
1863     {
1864       /* second change before first one is done */
1865       GNUNET_break (0);
1866       return NULL;
1867     }
1868   irc = GNUNET_malloc (sizeof (struct GNUNET_CORE_InformationRequestContext));
1869   irc->h = h;
1870   irc->pr = pr;
1871   irc->info = info;
1872   irc->info_cls = info_cls;
1873   cm = GNUNET_malloc (sizeof (struct ControlMessage) +
1874                       sizeof (struct RequestInfoMessage));
1875   cm->cont = &change_preference_send_continuation;
1876   cm->cont_cls = irc;
1877   irc->cm = cm;
1878   rim = (struct RequestInfoMessage*) &cm[1];
1879   rim->header.size = htons (sizeof (struct RequestInfoMessage));
1880   rim->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO);
1881   rim->rim_id = htonl (pr->rim_id = h->rim_id_gen++);
1882   rim->limit_outbound = bw_out;
1883   rim->reserve_inbound = htonl (amount);
1884   rim->preference_change = GNUNET_htonll(preference);
1885   rim->peer = *peer;
1886 #if DEBUG_CORE
1887   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1888               "Queueing CHANGE PREFERENCE request\n");
1889 #endif
1890   GNUNET_CONTAINER_DLL_insert (h->pending_head,
1891                                h->pending_tail,
1892                                cm); 
1893   pr->pcic = info;
1894   pr->pcic_cls = info_cls;
1895   if (h->pending_head == cm)
1896     trigger_next_request (h, GNUNET_NO);
1897   return irc;
1898 }
1899
1900
1901 /**
1902  * Cancel request for getting information about a peer.
1903  * Note that an eventual change in preference, trust or bandwidth
1904  * assignment MAY have already been committed at the time, 
1905  * so cancelling a request is NOT sure to undo the original
1906  * request.  The original request may or may not still commit.
1907  * The only thing cancellation ensures is that the callback
1908  * from the original request will no longer be called.
1909  *
1910  * @param irc context returned by the original GNUNET_CORE_peer_get_info call
1911  */
1912 void
1913 GNUNET_CORE_peer_change_preference_cancel (struct GNUNET_CORE_InformationRequestContext *irc)
1914 {
1915   struct GNUNET_CORE_Handle *h = irc->h;
1916   struct PeerRecord *pr = irc->pr;
1917
1918   if (irc->cm != NULL)
1919     {
1920       GNUNET_CONTAINER_DLL_remove (h->pending_head,
1921                                    h->pending_tail,
1922                                    irc->cm);
1923       GNUNET_free (irc->cm);
1924     }
1925   pr->pcic = NULL;
1926   pr->pcic_cls = NULL;
1927   GNUNET_free (irc);
1928 }
1929
1930
1931 /* end of core_api.c */