another core API simplification due to ATS introduction
[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    * ID of timeout task for the 'pending_head' handle
77    * which is the one with the smallest timeout.
78    */
79   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
80
81   /**
82    * ID of task to run 'next_request_transmission'.
83    */
84   GNUNET_SCHEDULER_TaskIdentifier ntr_task;
85
86   /**
87    * Current size of the queue of pending requests.
88    */
89   unsigned int queue_size;
90
91   /**
92    * SendMessageRequest ID generator for this peer.
93    */
94   uint16_t smr_id_gen;
95
96 };
97
98
99 /**
100  * Type of function called upon completion.
101  *
102  * @param cls closure
103  * @param success GNUNET_OK on success (which for request_connect
104  *        ONLY means that we transmitted the connect request to CORE,
105  *        it does not mean that we are actually now connected!);
106  *        GNUNET_NO on timeout,
107  *        GNUNET_SYSERR if core was shut down
108  */
109 typedef void (*GNUNET_CORE_ControlContinuation) (void *cls, int success);
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 transmission failed/succeeded.
133    */
134   GNUNET_CORE_ControlContinuation cont;
135
136   /**
137    * Closure for 'cont'.
138    */
139   void *cont_cls;
140
141   /**
142    * Transmit handle (if one is associated with this ControlMessage), or NULL.
143    */
144   struct GNUNET_CORE_TransmitHandle *th;
145 };
146
147
148
149 /**
150  * Context for the core service connection.
151  */
152 struct GNUNET_CORE_Handle
153 {
154
155   /**
156    * Configuration we're using.
157    */
158   const struct GNUNET_CONFIGURATION_Handle *cfg;
159
160   /**
161    * Closure for the various callbacks.
162    */
163   void *cls;
164
165   /**
166    * Function to call once we've handshaked with the core service.
167    */
168   GNUNET_CORE_StartupCallback init;
169
170   /**
171    * Function to call whenever we're notified about a peer connecting.
172    */
173   GNUNET_CORE_ConnectEventHandler connects;
174
175   /**
176    * Function to call whenever we're notified about a peer disconnecting.
177    */
178   GNUNET_CORE_DisconnectEventHandler disconnects;
179
180   /**
181    * Function to call whenever we receive an inbound message.
182    */
183   GNUNET_CORE_MessageCallback inbound_notify;
184
185   /**
186    * Function to call whenever we receive an outbound message.
187    */
188   GNUNET_CORE_MessageCallback outbound_notify;
189
190   /**
191    * Function handlers for messages of particular type.
192    */
193   const struct GNUNET_CORE_MessageHandler *handlers;
194
195   /**
196    * Our connection to the service.
197    */
198   struct GNUNET_CLIENT_Connection *client;
199
200   /**
201    * Handle for our current transmission request.
202    */
203   struct GNUNET_CLIENT_TransmitHandle *cth;
204
205   /**
206    * Head of doubly-linked list of pending requests.
207    */
208   struct ControlMessage *control_pending_head;
209
210   /**
211    * Tail of doubly-linked list of pending requests.
212    */
213   struct ControlMessage *control_pending_tail;
214
215   /**
216    * Head of doubly-linked list of peers that are core-approved
217    * to send their next message.
218    */
219   struct PeerRecord *ready_peer_head;
220
221   /**
222    * Tail of doubly-linked list of peers that are core-approved
223    * to send their next message.
224    */
225   struct PeerRecord *ready_peer_tail;
226
227   /**
228    * Hash map listing all of the peers that we are currently
229    * connected to.
230    */
231   struct GNUNET_CONTAINER_MultiHashMap *peers;
232
233   /**
234    * Identity of this peer.
235    */
236   struct GNUNET_PeerIdentity me;
237
238   /**
239    * ID of reconnect task (if any).
240    */
241   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
242
243   /**
244    * Current delay we use for re-trying to connect to core.
245    */
246   struct GNUNET_TIME_Relative retry_backoff;
247
248   /**
249    * Number of messages we are allowed to queue per target.
250    */
251   unsigned int queue_size;
252
253   /**
254    * Number of entries in the handlers array.
255    */
256   unsigned int hcnt;
257
258   /**
259    * For inbound notifications without a specific handler, do
260    * we expect to only receive headers?
261    */
262   int inbound_hdr_only;
263
264   /**
265    * For outbound notifications without a specific handler, do
266    * we expect to only receive headers?
267    */
268   int outbound_hdr_only;
269
270   /**
271    * Are we currently disconnected and hence unable to forward
272    * requests?
273    */
274   int currently_down;
275
276 };
277
278
279 /**
280  * Handle for a transmission request.
281  */
282 struct GNUNET_CORE_TransmitHandle
283 {
284
285   /**
286    * We keep active transmit handles in a doubly-linked list.
287    */
288   struct GNUNET_CORE_TransmitHandle *next;
289
290   /**
291    * We keep active transmit handles in a doubly-linked list.
292    */
293   struct GNUNET_CORE_TransmitHandle *prev;
294
295   /**
296    * Corresponding peer record.
297    */
298   struct PeerRecord *peer;
299
300   /**
301    * Corresponding SEND_REQUEST message.  Only non-NULL
302    * while SEND_REQUEST message is pending.
303    */
304   struct ControlMessage *cm;
305
306   /**
307    * Function that will be called to get the actual request
308    * (once we are ready to transmit this request to the core).
309    * The function will be called with a NULL buffer to signal
310    * timeout.
311    */
312   GNUNET_CONNECTION_TransmitReadyNotify get_message;
313
314   /**
315    * Closure for get_message.
316    */
317   void *get_message_cls;
318
319   /**
320    * Timeout for this handle.
321    */
322   struct GNUNET_TIME_Absolute timeout;
323
324   /**
325    * How important is this message?
326    */
327   uint32_t priority;
328
329   /**
330    * Size of this request.
331    */
332   uint16_t msize;
333
334   /**
335    * Send message request ID for this request.
336    */
337   uint16_t smr_id;
338
339   /**
340    * Is corking allowed?
341    */
342   int cork;
343
344 };
345
346
347 /**
348  * Our current client connection went down.  Clean it up
349  * and try to reconnect!
350  *
351  * @param h our handle to the core service
352  */
353 static void
354 reconnect (struct GNUNET_CORE_Handle *h);
355
356
357 /**
358  * Task schedule to try to re-connect to core.
359  *
360  * @param cls the 'struct GNUNET_CORE_Handle'
361  * @param tc task context
362  */
363 static void
364 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
365 {
366   struct GNUNET_CORE_Handle *h = cls;
367
368   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
369 #if DEBUG_CORE
370   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
371               "Connecting to CORE service after delay\n");
372 #endif
373   reconnect (h);
374 }
375
376
377 /**
378  * Notify clients about disconnect and free
379  * the entry for connected peer.
380  *
381  * @param cls the 'struct GNUNET_CORE_Handle*'
382  * @param key the peer identity (not used)
383  * @param value the 'struct PeerRecord' to free.
384  * @return GNUNET_YES (continue)
385  */
386 static int
387 disconnect_and_free_peer_entry (void *cls, const GNUNET_HashCode * key,
388                                 void *value)
389 {
390   struct GNUNET_CORE_Handle *h = cls;
391   struct GNUNET_CORE_TransmitHandle *th;
392   struct PeerRecord *pr = value;
393
394   if (pr->timeout_task != GNUNET_SCHEDULER_NO_TASK)
395   {
396     GNUNET_SCHEDULER_cancel (pr->timeout_task);
397     pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
398   }
399   if (pr->ntr_task != GNUNET_SCHEDULER_NO_TASK)
400   {
401     GNUNET_SCHEDULER_cancel (pr->ntr_task);
402     pr->ntr_task = GNUNET_SCHEDULER_NO_TASK;
403   }
404   if ((pr->prev != NULL) || (pr->next != NULL) || (h->ready_peer_head == pr))
405     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
406   if (h->disconnects != NULL)
407     h->disconnects (h->cls, &pr->peer);
408   /* all requests should have been cancelled, clean up anyway, just in case */
409   GNUNET_break (pr->queue_size == 0);
410   while (NULL != (th = pr->pending_head))
411   {
412     GNUNET_break (0);
413     GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, th);
414     pr->queue_size--;
415     if (th->cm != NULL)
416       th->cm->th = NULL;
417     GNUNET_free (th);
418   }
419   /* done with 'voluntary' cleanups, now on to normal freeing */
420   GNUNET_assert (GNUNET_YES ==
421                  GNUNET_CONTAINER_multihashmap_remove (h->peers, key, pr));
422   GNUNET_assert (pr->pending_head == NULL);
423   GNUNET_assert (pr->pending_tail == NULL);
424   GNUNET_assert (pr->ch = h);
425   GNUNET_assert (pr->queue_size == 0);
426   GNUNET_assert (pr->timeout_task == GNUNET_SCHEDULER_NO_TASK);
427   GNUNET_assert (pr->ntr_task == GNUNET_SCHEDULER_NO_TASK);
428   GNUNET_free (pr);
429   return GNUNET_YES;
430 }
431
432
433 /**
434  * Close down any existing connection to the CORE service and
435  * try re-establishing it later.
436  *
437  * @param h our handle
438  */
439 static void
440 reconnect_later (struct GNUNET_CORE_Handle *h)
441 {
442   struct ControlMessage *cm;
443   struct PeerRecord *pr;
444
445   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
446   if (NULL != h->cth)
447   {
448     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
449     h->cth = NULL;
450   }
451   if (h->client != NULL)
452   {
453     GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
454     h->client = NULL;
455   }
456   h->currently_down = GNUNET_YES;
457   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
458   h->reconnect_task =
459       GNUNET_SCHEDULER_add_delayed (h->retry_backoff, &reconnect_task, h);
460   while (NULL != (cm = h->control_pending_head))
461   {
462     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
463                                  h->control_pending_tail, cm);
464     if (cm->th != NULL)
465       cm->th->cm = NULL;
466     if (cm->cont != NULL)
467       cm->cont (cm->cont_cls, GNUNET_NO);
468     GNUNET_free (cm);
469   }
470   GNUNET_CONTAINER_multihashmap_iterate (h->peers,
471                                          &disconnect_and_free_peer_entry, h);
472   while (NULL != (pr = h->ready_peer_head))
473     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
474   GNUNET_assert (h->control_pending_head == NULL);
475   h->retry_backoff =
476       GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS, h->retry_backoff);
477   h->retry_backoff = GNUNET_TIME_relative_multiply (h->retry_backoff, 2);
478 }
479
480
481 /**
482  * Check the list of pending requests, send the next
483  * one to the core.
484  *
485  * @param h core handle
486  * @param ignore_currently_down transmit message even if not initialized?
487  */
488 static void
489 trigger_next_request (struct GNUNET_CORE_Handle *h, int ignore_currently_down);
490
491
492 /**
493  * The given request hit its timeout.  Remove from the
494  * doubly-linked list and call the respective continuation.
495  *
496  * @param cls the transmit handle of the request that timed out
497  * @param tc context, can be NULL (!)
498  */
499 static void
500 transmission_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
501
502
503 /**
504  * Send a control message to the peer asking for transmission
505  * of the message in the given peer record.
506  *
507  * @param pr peer to request transmission to
508  */
509 static void
510 request_next_transmission (struct PeerRecord *pr)
511 {
512   struct GNUNET_CORE_Handle *h = pr->ch;
513   struct ControlMessage *cm;
514   struct SendMessageRequest *smr;
515   struct GNUNET_CORE_TransmitHandle *th;
516
517   if (pr->timeout_task != GNUNET_SCHEDULER_NO_TASK)
518   {
519     GNUNET_SCHEDULER_cancel (pr->timeout_task);
520     pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
521   }
522   if (NULL == (th = pr->pending_head))
523   {
524     trigger_next_request (h, GNUNET_NO);
525     return;
526   }
527   if (th->cm != NULL)
528     return;                     /* already done */
529   GNUNET_assert (pr->prev == NULL);
530   GNUNET_assert (pr->next == NULL);
531   pr->timeout_task =
532       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
533                                     (th->timeout), &transmission_timeout, pr);
534   cm = GNUNET_malloc (sizeof (struct ControlMessage) +
535                       sizeof (struct SendMessageRequest));
536   th->cm = cm;
537   cm->th = th;
538   smr = (struct SendMessageRequest *) &cm[1];
539   smr->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST);
540   smr->header.size = htons (sizeof (struct SendMessageRequest));
541   smr->priority = htonl (th->priority);
542   smr->deadline = GNUNET_TIME_absolute_hton (th->timeout);
543   smr->peer = pr->peer;
544   smr->queue_size = htonl (pr->queue_size);
545   smr->size = htons (th->msize);
546   smr->smr_id = htons (th->smr_id = pr->smr_id_gen++);
547   GNUNET_CONTAINER_DLL_insert_tail (h->control_pending_head,
548                                     h->control_pending_tail, cm);
549 #if DEBUG_CORE
550   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
551               "Adding SEND REQUEST for peer `%s' to message queue\n",
552               GNUNET_i2s (&pr->peer));
553 #endif
554   trigger_next_request (h, GNUNET_NO);
555 }
556
557
558 /**
559  * The given request hit its timeout.  Remove from the
560  * doubly-linked list and call the respective continuation.
561  *
562  * @param cls the transmit handle of the request that timed out
563  * @param tc context, can be NULL (!)
564  */
565 static void
566 transmission_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
567 {
568   struct PeerRecord *pr = cls;
569   struct GNUNET_CORE_Handle *h = pr->ch;
570   struct GNUNET_CORE_TransmitHandle *th;
571
572   pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
573   th = pr->pending_head;
574   GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, th);
575   pr->queue_size--;
576   if ((pr->prev != NULL) || (pr->next != NULL) || (pr == h->ready_peer_head))
577   {
578     /* the request that was 'approved' by core was
579      * canceled before it could be transmitted; remove
580      * us from the 'ready' list */
581     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
582   }
583 #if DEBUG_CORE
584   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
585               "Signalling timeout of request for transmission to CORE service\n");
586 #endif
587   request_next_transmission (pr);
588   GNUNET_assert (0 == th->get_message (th->get_message_cls, 0, NULL));
589   GNUNET_free (th);
590 }
591
592
593 /**
594  * Transmit the next message to the core service.
595  */
596 static size_t
597 transmit_message (void *cls, size_t size, void *buf)
598 {
599   struct GNUNET_CORE_Handle *h = cls;
600   struct ControlMessage *cm;
601   struct GNUNET_CORE_TransmitHandle *th;
602   struct PeerRecord *pr;
603   struct SendMessage *sm;
604   const struct GNUNET_MessageHeader *hdr;
605   uint16_t msize;
606   size_t ret;
607
608   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
609   h->cth = NULL;
610   if (buf == NULL)
611   {
612 #if DEBUG_CORE
613     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
614                 "Transmission failed, initiating reconnect\n");
615 #endif
616     reconnect_later (h);
617     return 0;
618   }
619   /* first check for control messages */
620   if (NULL != (cm = h->control_pending_head))
621   {
622     hdr = (const struct GNUNET_MessageHeader *) &cm[1];
623     msize = ntohs (hdr->size);
624     if (size < msize)
625     {
626       trigger_next_request (h, GNUNET_NO);
627       return 0;
628     }
629 #if DEBUG_CORE
630     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
631                 "Transmitting control message with %u bytes of type %u to core.\n",
632                 (unsigned int) msize, (unsigned int) ntohs (hdr->type));
633 #endif
634     memcpy (buf, hdr, msize);
635     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
636                                  h->control_pending_tail, cm);
637     if (cm->th != NULL)
638       cm->th->cm = NULL;
639     if (NULL != cm->cont)
640       cm->cont (cm->cont_cls, GNUNET_OK);
641     GNUNET_free (cm);
642     trigger_next_request (h, GNUNET_NO);
643     return msize;
644   }
645   /* now check for 'ready' P2P messages */
646   if (NULL != (pr = h->ready_peer_head))
647   {
648     GNUNET_assert (pr->pending_head != NULL);
649     th = pr->pending_head;
650     if (size < th->msize + sizeof (struct SendMessage))
651     {
652       trigger_next_request (h, GNUNET_NO);
653       return 0;
654     }
655     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
656     GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, th);
657     pr->queue_size--;
658     if (pr->timeout_task != GNUNET_SCHEDULER_NO_TASK)
659     {
660       GNUNET_SCHEDULER_cancel (pr->timeout_task);
661       pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
662     }
663 #if DEBUG_CORE
664     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
665                 "Transmitting SEND request to `%s' with %u bytes.\n",
666                 GNUNET_i2s (&pr->peer), (unsigned int) th->msize);
667 #endif
668     sm = (struct SendMessage *) buf;
669     sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND);
670     sm->priority = htonl (th->priority);
671     sm->deadline = GNUNET_TIME_absolute_hton (th->timeout);
672     sm->peer = pr->peer;
673     sm->cork = htonl ((uint32_t) th->cork);
674     sm->reserved = htonl (0);
675     ret =
676         th->get_message (th->get_message_cls,
677                          size - sizeof (struct SendMessage), &sm[1]);
678
679 #if DEBUG_CORE
680     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
681                 "Transmitting SEND request to `%s' yielded %u bytes.\n",
682                 GNUNET_i2s (&pr->peer), ret);
683 #endif
684     GNUNET_free (th);
685     if (0 == ret)
686     {
687 #if DEBUG_CORE
688       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
689                   "Size of clients message to peer %s is 0!\n",
690                   GNUNET_i2s (&pr->peer));
691 #endif
692       /* client decided to send nothing! */
693       request_next_transmission (pr);
694       return 0;
695     }
696 #if DEBUG_CORE
697     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
698                 "Produced SEND message to core with %u bytes payload\n",
699                 (unsigned int) ret);
700 #endif
701     GNUNET_assert (ret >= sizeof (struct GNUNET_MessageHeader));
702     if (ret + sizeof (struct SendMessage) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
703     {
704       GNUNET_break (0);
705       request_next_transmission (pr);
706       return 0;
707     }
708     ret += sizeof (struct SendMessage);
709     sm->header.size = htons (ret);
710     GNUNET_assert (ret <= size);
711     request_next_transmission (pr);
712     return ret;
713   }
714   return 0;
715 }
716
717
718 /**
719  * Check the list of pending requests, send the next
720  * one to the core.
721  *
722  * @param h core handle
723  * @param ignore_currently_down transmit message even if not initialized?
724  */
725 static void
726 trigger_next_request (struct GNUNET_CORE_Handle *h, int ignore_currently_down)
727 {
728   uint16_t msize;
729
730   if ((GNUNET_YES == h->currently_down) && (ignore_currently_down == GNUNET_NO))
731   {
732 #if DEBUG_CORE
733     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
734                 "Core connection down, not processing queue\n");
735 #endif
736     return;
737   }
738   if (NULL != h->cth)
739   {
740 #if DEBUG_CORE
741     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
742                 "Request pending, not processing queue\n");
743 #endif
744     return;
745   }
746   if (h->control_pending_head != NULL)
747     msize =
748         ntohs (((struct GNUNET_MessageHeader *) &h->
749                 control_pending_head[1])->size);
750   else if (h->ready_peer_head != NULL)
751     msize =
752         h->ready_peer_head->pending_head->msize + sizeof (struct SendMessage);
753   else
754   {
755 #if DEBUG_CORE
756     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
757                 "Request queue empty, not processing queue\n");
758 #endif
759     return;                     /* no pending message */
760   }
761   h->cth =
762       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
763                                            GNUNET_TIME_UNIT_FOREVER_REL,
764                                            GNUNET_NO, &transmit_message, h);
765 }
766
767
768 /**
769  * Handler for notification messages received from the core.
770  *
771  * @param cls our "struct GNUNET_CORE_Handle"
772  * @param msg the message received from the core service
773  */
774 static void
775 main_notify_handler (void *cls, const struct GNUNET_MessageHeader *msg)
776 {
777   struct GNUNET_CORE_Handle *h = cls;
778   const struct InitReplyMessage *m;
779   const struct ConnectNotifyMessage *cnm;
780   const struct DisconnectNotifyMessage *dnm;
781   const struct NotifyTrafficMessage *ntm;
782   const struct GNUNET_MessageHeader *em;
783   const struct SendMessageReady *smr;
784   const struct GNUNET_CORE_MessageHandler *mh;
785   GNUNET_CORE_StartupCallback init;
786   struct PeerRecord *pr;
787   struct GNUNET_CORE_TransmitHandle *th;
788   unsigned int hpos;
789   int trigger;
790   uint16_t msize;
791   uint16_t et;
792   uint32_t ats_count;
793
794   if (msg == NULL)
795   {
796     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
797                 _
798                 ("Client was disconnected from core service, trying to reconnect.\n"));
799     reconnect_later (h);
800     return;
801   }
802   msize = ntohs (msg->size);
803 #if DEBUG_CORE > 2
804   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
805               "Processing message of type %u and size %u from core service\n",
806               ntohs (msg->type), msize);
807 #endif
808   switch (ntohs (msg->type))
809   {
810   case GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY:
811     if (ntohs (msg->size) != sizeof (struct InitReplyMessage))
812     {
813       GNUNET_break (0);
814       reconnect_later (h);
815       return;
816     }
817     m = (const struct InitReplyMessage *) msg;
818     GNUNET_break (0 == ntohl (m->reserved));
819     /* start our message processing loop */
820     if (GNUNET_YES == h->currently_down)
821     {
822       h->currently_down = GNUNET_NO;
823       trigger_next_request (h, GNUNET_NO);
824     }
825     h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
826     h->me = m->my_identity;
827     if (NULL != (init = h->init))
828     {
829       /* mark so we don't call init on reconnect */
830       h->init = NULL;
831 #if DEBUG_CORE
832       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
833                   "Connected to core service of peer `%s'.\n",
834                   GNUNET_i2s (&h->me));
835 #endif
836       init (h->cls, h, &h->me);
837     }
838     else
839     {
840 #if DEBUG_CORE
841       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
842                   "Successfully reconnected to core service.\n");
843 #endif
844     }
845     /* fake 'connect to self' */
846     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &h->me.hashPubKey);
847     GNUNET_assert (pr == NULL);
848     pr = GNUNET_malloc (sizeof (struct PeerRecord));
849     pr->peer = h->me;
850     pr->ch = h;
851     GNUNET_assert (GNUNET_YES ==
852                    GNUNET_CONTAINER_multihashmap_put (h->peers,
853                                                       &h->me.hashPubKey, pr,
854                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
855     if (NULL != h->connects)
856       h->connects (h->cls, &h->me, NULL);
857     break;
858   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT:
859     if (msize < sizeof (struct ConnectNotifyMessage))
860     {
861       GNUNET_break (0);
862       reconnect_later (h);
863       return;
864     }
865     cnm = (const struct ConnectNotifyMessage *) msg;
866     ats_count = ntohl (cnm->ats_count);
867     if ((msize !=
868          sizeof (struct ConnectNotifyMessage) +
869          ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)) ||
870         (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR !=
871          ntohl ((&cnm->ats)[ats_count].type)))
872     {
873       GNUNET_break (0);
874       reconnect_later (h);
875       return;
876     }
877 #if DEBUG_CORE
878     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
879                 "Received notification about connection from `%s'.\n",
880                 GNUNET_i2s (&cnm->peer));
881 #endif
882     if (0 == memcmp (&h->me, &cnm->peer, sizeof (struct GNUNET_PeerIdentity)))
883     {
884       /* connect to self!? */
885       GNUNET_break (0);
886       return;
887     }
888     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &cnm->peer.hashPubKey);
889     if (pr != NULL)
890     {
891       GNUNET_break (0);
892       reconnect_later (h);
893       return;
894     }
895     pr = GNUNET_malloc (sizeof (struct PeerRecord));
896     pr->peer = cnm->peer;
897     pr->ch = h;
898     GNUNET_assert (GNUNET_YES ==
899                    GNUNET_CONTAINER_multihashmap_put (h->peers,
900                                                       &cnm->peer.hashPubKey, pr,
901                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
902     if (NULL != h->connects)
903       h->connects (h->cls, &cnm->peer, &cnm->ats);
904     break;
905   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT:
906     if (msize != sizeof (struct DisconnectNotifyMessage))
907     {
908       GNUNET_break (0);
909       reconnect_later (h);
910       return;
911     }
912     dnm = (const struct DisconnectNotifyMessage *) msg;
913     if (0 == memcmp (&h->me, &dnm->peer, sizeof (struct GNUNET_PeerIdentity)))
914     {
915       /* connection to self!? */
916       GNUNET_break (0);
917       return;
918     }
919     GNUNET_break (0 == ntohl (dnm->reserved));
920 #if DEBUG_CORE
921     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
922                 "Received notification about disconnect from `%s'.\n",
923                 GNUNET_i2s (&dnm->peer));
924 #endif
925     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &dnm->peer.hashPubKey);
926     if (pr == NULL)
927     {
928       GNUNET_break (0);
929       reconnect_later (h);
930       return;
931     }
932     trigger = ((pr->prev != NULL) || (pr->next != NULL) ||
933                (h->ready_peer_head == pr));
934     disconnect_and_free_peer_entry (h, &dnm->peer.hashPubKey, pr);
935     if (trigger)
936       trigger_next_request (h, GNUNET_NO);
937     break;
938   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND:
939     if (msize < sizeof (struct NotifyTrafficMessage))
940     {
941       GNUNET_break (0);
942       reconnect_later (h);
943       return;
944     }
945     ntm = (const struct NotifyTrafficMessage *) msg;
946
947     ats_count = ntohl (ntm->ats_count);
948     if ((msize <
949          sizeof (struct NotifyTrafficMessage) +
950          ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) +
951          sizeof (struct GNUNET_MessageHeader)) ||
952         (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR !=
953          ntohl ((&ntm->ats)[ats_count].type)))
954     {
955       GNUNET_break (0);
956       reconnect_later (h);
957       return;
958     }
959     em = (const struct GNUNET_MessageHeader *) &(&ntm->ats)[ats_count + 1];
960 #if DEBUG_CORE
961     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
962                 "Received message of type %u and size %u from peer `%4s'\n",
963                 ntohs (em->type), ntohs (em->size), GNUNET_i2s (&ntm->peer));
964 #endif
965     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &ntm->peer.hashPubKey);
966     if (pr == NULL)
967     {
968       GNUNET_break (0);
969       reconnect_later (h);
970       return;
971     }
972     if ((GNUNET_NO == h->inbound_hdr_only) &&
973         (msize !=
974          ntohs (em->size) + sizeof (struct NotifyTrafficMessage) +
975          +ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)))
976     {
977       GNUNET_break (0);
978       reconnect_later (h);
979       return;
980     }
981     et = ntohs (em->type);
982     for (hpos = 0; hpos < h->hcnt; hpos++)
983     {
984       mh = &h->handlers[hpos];
985       if (mh->type != et)
986         continue;
987       if ((mh->expected_size != ntohs (em->size)) && (mh->expected_size != 0))
988       {
989         GNUNET_break (0);
990         continue;
991       }
992       if (GNUNET_OK !=
993           h->handlers[hpos].callback (h->cls, &ntm->peer, em, &ntm->ats))
994       {
995         /* error in processing, do not process other messages! */
996         break;
997       }
998     }
999     if (NULL != h->inbound_notify)
1000       h->inbound_notify (h->cls, &ntm->peer, em, &ntm->ats);
1001     break;
1002   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND:
1003     if (msize < sizeof (struct NotifyTrafficMessage))
1004     {
1005       GNUNET_break (0);
1006       reconnect_later (h);
1007       return;
1008     }
1009     ntm = (const struct NotifyTrafficMessage *) msg;
1010     if (0 == memcmp (&h->me, &ntm->peer, sizeof (struct GNUNET_PeerIdentity)))
1011     {
1012       /* self-change!? */
1013       GNUNET_break (0);
1014       return;
1015     }
1016     ats_count = ntohl (ntm->ats_count);
1017     if ((msize <
1018          sizeof (struct NotifyTrafficMessage) +
1019          ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) +
1020          sizeof (struct GNUNET_MessageHeader)) ||
1021         (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR !=
1022          ntohl ((&ntm->ats)[ats_count].type)))
1023     {
1024       GNUNET_break (0);
1025       reconnect_later (h);
1026       return;
1027     }
1028     em = (const struct GNUNET_MessageHeader *) &(&ntm->ats)[ats_count + 1];
1029     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &ntm->peer.hashPubKey);
1030     if (pr == NULL)
1031     {
1032       GNUNET_break (0);
1033       reconnect_later (h);
1034       return;
1035     }
1036 #if DEBUG_CORE
1037     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1038                 "Received notification about transmission to `%s'.\n",
1039                 GNUNET_i2s (&ntm->peer));
1040 #endif
1041     if ((GNUNET_NO == h->outbound_hdr_only) &&
1042         (msize !=
1043          ntohs (em->size) + sizeof (struct NotifyTrafficMessage) +
1044          ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)))
1045     {
1046       GNUNET_break (0);
1047       reconnect_later (h);
1048       return;
1049     }
1050     if (NULL == h->outbound_notify)
1051     {
1052       GNUNET_break (0);
1053       break;
1054     }
1055     h->outbound_notify (h->cls, &ntm->peer, em, &ntm->ats);
1056     break;
1057   case GNUNET_MESSAGE_TYPE_CORE_SEND_READY:
1058     if (msize != sizeof (struct SendMessageReady))
1059     {
1060       GNUNET_break (0);
1061       reconnect_later (h);
1062       return;
1063     }
1064     smr = (const struct SendMessageReady *) msg;
1065     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &smr->peer.hashPubKey);
1066     if (pr == NULL)
1067     {
1068       GNUNET_break (0);
1069       reconnect_later (h);
1070       return;
1071     }
1072 #if DEBUG_CORE
1073     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1074                 "Received notification about transmission readiness to `%s'.\n",
1075                 GNUNET_i2s (&smr->peer));
1076 #endif
1077     if (pr->pending_head == NULL)
1078     {
1079       /* request must have been cancelled between the original request
1080        * and the response from core, ignore core's readiness */
1081       break;
1082     }
1083
1084     th = pr->pending_head;
1085     if (ntohs (smr->smr_id) != th->smr_id)
1086     {
1087       /* READY message is for expired or cancelled message,
1088        * ignore! (we should have already sent another request) */
1089       break;
1090     }
1091     if ((pr->prev != NULL) || (pr->next != NULL) || (h->ready_peer_head == pr))
1092     {
1093       /* we should not already be on the ready list... */
1094       GNUNET_break (0);
1095       reconnect_later (h);
1096       return;
1097     }
1098     GNUNET_CONTAINER_DLL_insert (h->ready_peer_head, h->ready_peer_tail, pr);
1099     trigger_next_request (h, GNUNET_NO);
1100     break;
1101   default:
1102     reconnect_later (h);
1103     return;
1104   }
1105   GNUNET_CLIENT_receive (h->client, &main_notify_handler, h,
1106                          GNUNET_TIME_UNIT_FOREVER_REL);
1107 }
1108
1109
1110 /**
1111  * Task executed once we are done transmitting the INIT message.
1112  * Starts our 'receive' loop.
1113  *
1114  * @param cls the 'struct GNUNET_CORE_Handle'
1115  * @param success were we successful
1116  */
1117 static void
1118 init_done_task (void *cls, int success)
1119 {
1120   struct GNUNET_CORE_Handle *h = cls;
1121
1122   if (success == GNUNET_SYSERR)
1123     return;                     /* shutdown */
1124   if (success == GNUNET_NO)
1125   {
1126 #if DEBUG_CORE
1127     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1128                 "Failed to exchange INIT with core, retrying\n");
1129 #endif
1130     if (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK)
1131       reconnect_later (h);
1132     return;
1133   }
1134   GNUNET_CLIENT_receive (h->client, &main_notify_handler, h,
1135                          GNUNET_TIME_UNIT_FOREVER_REL);
1136 }
1137
1138
1139 /**
1140  * Our current client connection went down.  Clean it up
1141  * and try to reconnect!
1142  *
1143  * @param h our handle to the core service
1144  */
1145 static void
1146 reconnect (struct GNUNET_CORE_Handle *h)
1147 {
1148   struct ControlMessage *cm;
1149   struct InitMessage *init;
1150   uint32_t opt;
1151   uint16_t msize;
1152   uint16_t *ts;
1153   unsigned int hpos;
1154
1155 #if DEBUG_CORE
1156   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Reconnecting to CORE service\n");
1157 #endif
1158   GNUNET_assert (h->client == NULL);
1159   GNUNET_assert (h->currently_down == GNUNET_YES);
1160   h->client = GNUNET_CLIENT_connect ("core", h->cfg);
1161   if (h->client == NULL)
1162   {
1163     reconnect_later (h);
1164     return;
1165   }
1166   msize = h->hcnt * sizeof (uint16_t) + sizeof (struct InitMessage);
1167   cm = GNUNET_malloc (sizeof (struct ControlMessage) + msize);
1168   cm->cont = &init_done_task;
1169   cm->cont_cls = h;
1170   init = (struct InitMessage *) &cm[1];
1171   init->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT);
1172   init->header.size = htons (msize);
1173   opt = GNUNET_CORE_OPTION_SEND_CONNECT | GNUNET_CORE_OPTION_SEND_DISCONNECT;
1174   if (h->inbound_notify != NULL)
1175   {
1176     if (h->inbound_hdr_only)
1177       opt |= GNUNET_CORE_OPTION_SEND_HDR_INBOUND;
1178     else
1179       opt |= GNUNET_CORE_OPTION_SEND_FULL_INBOUND;
1180   }
1181   if (h->outbound_notify != NULL)
1182   {
1183     if (h->outbound_hdr_only)
1184       opt |= GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND;
1185     else
1186       opt |= GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND;
1187   }
1188   init->options = htonl (opt);
1189   ts = (uint16_t *) & init[1];
1190   for (hpos = 0; hpos < h->hcnt; hpos++)
1191     ts[hpos] = htons (h->handlers[hpos].type);
1192   GNUNET_CONTAINER_DLL_insert (h->control_pending_head, h->control_pending_tail,
1193                                cm);
1194   trigger_next_request (h, GNUNET_YES);
1195 }
1196
1197
1198
1199 /**
1200  * Connect to the core service.  Note that the connection may
1201  * complete (or fail) asynchronously.
1202  *
1203  * @param cfg configuration to use
1204  * @param queue_size size of the per-peer message queue
1205  * @param cls closure for the various callbacks that follow (including handlers in the handlers array)
1206  * @param init callback to call on timeout or once we have successfully
1207  *        connected to the core service; note that timeout is only meaningful if init is not NULL
1208  * @param connects function to call on peer connect, can be NULL
1209  * @param disconnects function to call on peer disconnect / timeout, can be NULL
1210  * @param inbound_notify function to call for all inbound messages, can be NULL
1211  * @param inbound_hdr_only set to GNUNET_YES if inbound_notify will only read the
1212  *                GNUNET_MessageHeader and hence we do not need to give it the full message;
1213  *                can be used to improve efficiency, ignored if inbound_notify is NULLL
1214  * @param outbound_notify function to call for all outbound messages, can be NULL
1215  * @param outbound_hdr_only set to GNUNET_YES if outbound_notify will only read the
1216  *                GNUNET_MessageHeader and hence we do not need to give it the full message
1217  *                can be used to improve efficiency, ignored if outbound_notify is NULLL
1218  * @param handlers callbacks for messages we care about, NULL-terminated
1219  * @return handle to the core service (only useful for disconnect until 'init' is called);
1220  *                NULL on error (in this case, init is never called)
1221  */
1222 struct GNUNET_CORE_Handle *
1223 GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1224                      unsigned int queue_size, void *cls,
1225                      GNUNET_CORE_StartupCallback init,
1226                      GNUNET_CORE_ConnectEventHandler connects,
1227                      GNUNET_CORE_DisconnectEventHandler disconnects,
1228                      GNUNET_CORE_MessageCallback inbound_notify,
1229                      int inbound_hdr_only,
1230                      GNUNET_CORE_MessageCallback outbound_notify,
1231                      int outbound_hdr_only,
1232                      const struct GNUNET_CORE_MessageHandler *handlers)
1233 {
1234   struct GNUNET_CORE_Handle *h;
1235
1236   h = GNUNET_malloc (sizeof (struct GNUNET_CORE_Handle));
1237   h->cfg = cfg;
1238   h->queue_size = queue_size;
1239   h->cls = cls;
1240   h->init = init;
1241   h->connects = connects;
1242   h->disconnects = disconnects;
1243   h->inbound_notify = inbound_notify;
1244   h->outbound_notify = outbound_notify;
1245   h->inbound_hdr_only = inbound_hdr_only;
1246   h->outbound_hdr_only = outbound_hdr_only;
1247   h->handlers = handlers;
1248   h->hcnt = 0;
1249   h->currently_down = GNUNET_YES;
1250   h->peers = GNUNET_CONTAINER_multihashmap_create (128);
1251   h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1252   if (NULL != handlers)
1253     while (handlers[h->hcnt].callback != NULL)
1254       h->hcnt++;
1255   GNUNET_assert (h->hcnt <
1256                  (GNUNET_SERVER_MAX_MESSAGE_SIZE -
1257                   sizeof (struct InitMessage)) / sizeof (uint16_t));
1258 #if DEBUG_CORE
1259   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting to CORE service\n");
1260 #endif
1261   reconnect (h);
1262   return h;
1263 }
1264
1265
1266 /**
1267  * Disconnect from the core service.  This function can only
1268  * be called *after* all pending 'GNUNET_CORE_notify_transmit_ready'
1269  * requests have been explicitly canceled.
1270  *
1271  * @param handle connection to core to disconnect
1272  */
1273 void
1274 GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle)
1275 {
1276   struct ControlMessage *cm;
1277
1278 #if DEBUG_CORE
1279   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from CORE service\n");
1280 #endif
1281   if (handle->cth != NULL)
1282   {
1283     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->cth);
1284     handle->cth = NULL;
1285   }
1286   while (NULL != (cm = handle->control_pending_head))
1287   {
1288     GNUNET_CONTAINER_DLL_remove (handle->control_pending_head,
1289                                  handle->control_pending_tail, cm);
1290     if (cm->th != NULL)
1291       cm->th->cm = NULL;
1292     if (cm->cont != NULL)
1293       cm->cont (cm->cont_cls, GNUNET_SYSERR);
1294     GNUNET_free (cm);
1295   }
1296   if (handle->client != NULL)
1297   {
1298     GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
1299     handle->client = NULL;
1300   }
1301   GNUNET_CONTAINER_multihashmap_iterate (handle->peers,
1302                                          &disconnect_and_free_peer_entry,
1303                                          handle);
1304   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1305   {
1306     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1307     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1308   }
1309   GNUNET_CONTAINER_multihashmap_destroy (handle->peers);
1310   handle->peers = NULL;
1311   GNUNET_break (handle->ready_peer_head == NULL);
1312   GNUNET_free (handle);
1313 }
1314
1315
1316 /**
1317  * Task that calls 'request_next_transmission'.
1318  *
1319  * @param cls the 'struct PeerRecord*'
1320  * @param tc scheduler context
1321  */
1322 static void
1323 run_request_next_transmission (void *cls,
1324                                const struct GNUNET_SCHEDULER_TaskContext *tc)
1325 {
1326   struct PeerRecord *pr = cls;
1327
1328   pr->ntr_task = GNUNET_SCHEDULER_NO_TASK;
1329   request_next_transmission (pr);
1330 }
1331
1332
1333 /**
1334  * Ask the core to call "notify" once it is ready to transmit the
1335  * given number of bytes to the specified "target".    Must only be
1336  * called after a connection to the respective peer has been
1337  * established (and the client has been informed about this).
1338  *
1339  * @param handle connection to core service
1340  * @param cork is corking allowed for this transmission?
1341  * @param priority how important is the message?
1342  * @param maxdelay how long can the message wait?
1343  * @param target who should receive the message,
1344  *        use NULL for this peer (loopback)
1345  * @param notify_size how many bytes of buffer space does notify want?
1346  * @param notify function to call when buffer space is available
1347  * @param notify_cls closure for notify
1348  * @return non-NULL if the notify callback was queued,
1349  *         NULL if we can not even queue the request (insufficient
1350  *         memory); if NULL is returned, "notify" will NOT be called.
1351  */
1352 struct GNUNET_CORE_TransmitHandle *
1353 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle, int cork,
1354                                    uint32_t priority,
1355                                    struct GNUNET_TIME_Relative maxdelay,
1356                                    const struct GNUNET_PeerIdentity *target,
1357                                    size_t notify_size,
1358                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1359                                    void *notify_cls)
1360 {
1361   struct PeerRecord *pr;
1362   struct GNUNET_CORE_TransmitHandle *th;
1363   struct GNUNET_CORE_TransmitHandle *pos;
1364   struct GNUNET_CORE_TransmitHandle *prev;
1365   struct GNUNET_CORE_TransmitHandle *minp;
1366
1367   pr = GNUNET_CONTAINER_multihashmap_get (handle->peers, &target->hashPubKey);
1368   if (NULL == pr)
1369   {
1370     /* attempt to send to peer that is not connected */
1371     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1372                 "Attempting to send to peer `%s' from peer `%s', but not connected!\n",
1373                 GNUNET_i2s (target), GNUNET_h2s (&handle->me.hashPubKey));
1374     GNUNET_break (0);
1375     return NULL;
1376   }
1377   GNUNET_assert (notify_size + sizeof (struct SendMessage) <
1378                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
1379   th = GNUNET_malloc (sizeof (struct GNUNET_CORE_TransmitHandle));
1380   th->peer = pr;
1381   GNUNET_assert (NULL != notify);
1382   th->get_message = notify;
1383   th->get_message_cls = notify_cls;
1384   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1385   th->priority = priority;
1386   th->msize = notify_size;
1387   th->cork = cork;
1388   /* bound queue size */
1389   if (pr->queue_size == handle->queue_size)
1390   {
1391     /* find lowest-priority entry, but skip the head of the list */
1392     minp = pr->pending_head->next;
1393     prev = minp;
1394     while (prev != NULL)
1395     {
1396       if (prev->priority < minp->priority)
1397         minp = prev;
1398       prev = prev->next;
1399     }
1400     if (minp == NULL)
1401     {
1402       GNUNET_break (handle->queue_size != 0);
1403       GNUNET_break (pr->queue_size == 1);
1404       GNUNET_free (th);
1405 #if DEBUG_CORE
1406       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1407                   "Dropping transmission request: cannot drop queue head and limit is one\n");
1408 #endif
1409       return NULL;
1410     }
1411     if (priority <= minp->priority)
1412     {
1413 #if DEBUG_CORE
1414       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1415                   "Dropping transmission request: priority too low\n");
1416 #endif
1417       GNUNET_free (th);
1418       return NULL;              /* priority too low */
1419     }
1420     GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, minp);
1421     pr->queue_size--;
1422     GNUNET_assert (0 == minp->get_message (minp->get_message_cls, 0, NULL));
1423     GNUNET_free (minp);
1424   }
1425
1426   /* Order entries by deadline, but SKIP 'HEAD' if
1427    * we're in the 'ready_peer_*' DLL */
1428   pos = pr->pending_head;
1429   if ((pr->prev != NULL) || (pr->next != NULL) ||
1430       (pr == handle->ready_peer_head))
1431   {
1432     GNUNET_assert (pos != NULL);
1433     pos = pos->next;            /* skip head */
1434   }
1435
1436   /* insertion sort */
1437   prev = pos;
1438   while ((pos != NULL) && (pos->timeout.abs_value < th->timeout.abs_value))
1439   {
1440     prev = pos;
1441     pos = pos->next;
1442   }
1443   GNUNET_CONTAINER_DLL_insert_after (pr->pending_head, pr->pending_tail, prev,
1444                                      th);
1445   pr->queue_size++;
1446   /* was the request queue previously empty? */
1447 #if DEBUG_CORE
1448   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmission request added to queue\n");
1449 #endif
1450   if ((pr->pending_head == th) && (pr->ntr_task == GNUNET_SCHEDULER_NO_TASK) &&
1451       (pr->next == NULL) && (pr->prev == NULL) &&
1452       (handle->ready_peer_head != pr))
1453     pr->ntr_task =
1454         GNUNET_SCHEDULER_add_now (&run_request_next_transmission, pr);
1455   return th;
1456 }
1457
1458
1459 /**
1460  * Cancel the specified transmission-ready notification.
1461  *
1462  * @param th handle that was returned by "notify_transmit_ready".
1463  */
1464 void
1465 GNUNET_CORE_notify_transmit_ready_cancel (struct GNUNET_CORE_TransmitHandle *th)
1466 {
1467   struct PeerRecord *pr = th->peer;
1468   struct GNUNET_CORE_Handle *h = pr->ch;
1469   int was_head;
1470
1471   was_head = (pr->pending_head == th);
1472   GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, th);
1473   pr->queue_size--;
1474   if (th->cm != NULL)
1475   {
1476     /* we're currently in the control queue, remove */
1477     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
1478                                  h->control_pending_tail, th->cm);
1479     GNUNET_free (th->cm);
1480   }
1481   GNUNET_free (th);
1482   if (was_head)
1483   {
1484     if ((pr->prev != NULL) || (pr->next != NULL) || (pr == h->ready_peer_head))
1485     {
1486       /* the request that was 'approved' by core was
1487        * canceled before it could be transmitted; remove
1488        * us from the 'ready' list */
1489       GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
1490     }
1491     request_next_transmission (pr);
1492   }
1493 }
1494
1495
1496 /* end of core_api.c */