remove unused options -- these bits were always set, no need to pass them
[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 #define LOG(kind,...) GNUNET_log_from (kind, "core-api",__VA_ARGS__)
33
34 /**
35  * Information we track for each peer.
36  */
37 struct PeerRecord
38 {
39
40   /**
41    * We generally do NOT keep peer records in a DLL; this
42    * DLL is only used IF this peer's 'pending_head' message
43    * is ready for transmission.
44    */
45   struct PeerRecord *prev;
46
47   /**
48    * We generally do NOT keep peer records in a DLL; this
49    * DLL is only used IF this peer's 'pending_head' message
50    * is ready for transmission.
51    */
52   struct PeerRecord *next;
53
54   /**
55    * Peer the record is about.
56    */
57   struct GNUNET_PeerIdentity peer;
58
59   /**
60    * Corresponding core handle.
61    */
62   struct GNUNET_CORE_Handle *ch;
63
64   /**
65    * Head of doubly-linked list of pending requests.
66    * Requests are sorted by deadline *except* for HEAD,
67    * which is only modified upon transmission to core.
68    */
69   struct GNUNET_CORE_TransmitHandle *pending_head;
70
71   /**
72    * Tail of doubly-linked list of pending requests.
73    */
74   struct GNUNET_CORE_TransmitHandle *pending_tail;
75
76   /**
77    * ID of timeout task for the 'pending_head' handle
78    * which is the one with the smallest timeout.
79    */
80   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
81
82   /**
83    * ID of task to run 'next_request_transmission'.
84    */
85   GNUNET_SCHEDULER_TaskIdentifier ntr_task;
86
87   /**
88    * Current size of the queue of pending requests.
89    */
90   unsigned int queue_size;
91
92   /**
93    * SendMessageRequest ID generator for this peer.
94    */
95   uint16_t smr_id_gen;
96
97 };
98
99
100 /**
101  * Type of function called upon completion.
102  *
103  * @param cls closure
104  * @param success GNUNET_OK on success (which for request_connect
105  *        ONLY means that we transmitted the connect request to CORE,
106  *        it does not mean that we are actually now connected!);
107  *        GNUNET_NO on timeout,
108  *        GNUNET_SYSERR if core was shut down
109  */
110 typedef void (*GNUNET_CORE_ControlContinuation) (void *cls, int success);
111
112
113 /**
114  * Entry in a doubly-linked list of control messages to be transmitted
115  * to the core service.  Control messages include traffic allocation,
116  * connection requests and of course our initial 'init' request.
117  *
118  * The actual message is allocated at the end of this struct.
119  */
120 struct ControlMessage
121 {
122   /**
123    * This is a doubly-linked list.
124    */
125   struct ControlMessage *next;
126
127   /**
128    * This is a doubly-linked list.
129    */
130   struct ControlMessage *prev;
131
132   /**
133    * Function to run after transmission failed/succeeded.
134    */
135   GNUNET_CORE_ControlContinuation cont;
136
137   /**
138    * Closure for 'cont'.
139    */
140   void *cont_cls;
141
142   /**
143    * Transmit handle (if one is associated with this ControlMessage), or NULL.
144    */
145   struct GNUNET_CORE_TransmitHandle *th;
146 };
147
148
149
150 /**
151  * Context for the core service connection.
152  */
153 struct GNUNET_CORE_Handle
154 {
155
156   /**
157    * Configuration we're using.
158    */
159   const struct GNUNET_CONFIGURATION_Handle *cfg;
160
161   /**
162    * Closure for the various callbacks.
163    */
164   void *cls;
165
166   /**
167    * Function to call once we've handshaked with the core service.
168    */
169   GNUNET_CORE_StartupCallback init;
170
171   /**
172    * Function to call whenever we're notified about a peer connecting.
173    */
174   GNUNET_CORE_ConnectEventHandler connects;
175
176   /**
177    * Function to call whenever we're notified about a peer disconnecting.
178    */
179   GNUNET_CORE_DisconnectEventHandler disconnects;
180
181   /**
182    * Function to call whenever we receive an inbound message.
183    */
184   GNUNET_CORE_MessageCallback inbound_notify;
185
186   /**
187    * Function to call whenever we receive an outbound message.
188    */
189   GNUNET_CORE_MessageCallback outbound_notify;
190
191   /**
192    * Function handlers for messages of particular type.
193    */
194   const struct GNUNET_CORE_MessageHandler *handlers;
195
196   /**
197    * Our connection to the service.
198    */
199   struct GNUNET_CLIENT_Connection *client;
200
201   /**
202    * Handle for our current transmission request.
203    */
204   struct GNUNET_CLIENT_TransmitHandle *cth;
205
206   /**
207    * Head of doubly-linked list of pending requests.
208    */
209   struct ControlMessage *control_pending_head;
210
211   /**
212    * Tail of doubly-linked list of pending requests.
213    */
214   struct ControlMessage *control_pending_tail;
215
216   /**
217    * Head of doubly-linked list of peers that are core-approved
218    * to send their next message.
219    */
220   struct PeerRecord *ready_peer_head;
221
222   /**
223    * Tail of doubly-linked list of peers that are core-approved
224    * to send their next message.
225    */
226   struct PeerRecord *ready_peer_tail;
227
228   /**
229    * Hash map listing all of the peers that we are currently
230    * connected to.
231    */
232   struct GNUNET_CONTAINER_MultiHashMap *peers;
233
234   /**
235    * Identity of this peer.
236    */
237   struct GNUNET_PeerIdentity me;
238
239   /**
240    * ID of reconnect task (if any).
241    */
242   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
243
244   /**
245    * Current delay we use for re-trying to connect to core.
246    */
247   struct GNUNET_TIME_Relative retry_backoff;
248
249   /**
250    * Number of messages we are allowed to queue per target.
251    */
252   unsigned int queue_size;
253
254   /**
255    * Number of entries in the handlers array.
256    */
257   unsigned int hcnt;
258
259   /**
260    * For inbound notifications without a specific handler, do
261    * we expect to only receive headers?
262    */
263   int inbound_hdr_only;
264
265   /**
266    * For outbound notifications without a specific handler, do
267    * we expect to only receive headers?
268    */
269   int outbound_hdr_only;
270
271   /**
272    * Are we currently disconnected and hence unable to forward
273    * requests?
274    */
275   int currently_down;
276
277 };
278
279
280 /**
281  * Handle for a transmission request.
282  */
283 struct GNUNET_CORE_TransmitHandle
284 {
285
286   /**
287    * We keep active transmit handles in a doubly-linked list.
288    */
289   struct GNUNET_CORE_TransmitHandle *next;
290
291   /**
292    * We keep active transmit handles in a doubly-linked list.
293    */
294   struct GNUNET_CORE_TransmitHandle *prev;
295
296   /**
297    * Corresponding peer record.
298    */
299   struct PeerRecord *peer;
300
301   /**
302    * Corresponding SEND_REQUEST message.  Only non-NULL
303    * while SEND_REQUEST message is pending.
304    */
305   struct ControlMessage *cm;
306
307   /**
308    * Function that will be called to get the actual request
309    * (once we are ready to transmit this request to the core).
310    * The function will be called with a NULL buffer to signal
311    * timeout.
312    */
313   GNUNET_CONNECTION_TransmitReadyNotify get_message;
314
315   /**
316    * Closure for get_message.
317    */
318   void *get_message_cls;
319
320   /**
321    * Timeout for this handle.
322    */
323   struct GNUNET_TIME_Absolute timeout;
324
325   /**
326    * How important is this message?
327    */
328   uint32_t priority;
329
330   /**
331    * Size of this request.
332    */
333   uint16_t msize;
334
335   /**
336    * Send message request ID for this request.
337    */
338   uint16_t smr_id;
339
340   /**
341    * Is corking allowed?
342    */
343   int cork;
344
345 };
346
347
348 /**
349  * Our current client connection went down.  Clean it up
350  * and try to reconnect!
351  *
352  * @param h our handle to the core service
353  */
354 static void
355 reconnect (struct GNUNET_CORE_Handle *h);
356
357
358 /**
359  * Task schedule to try to re-connect to core.
360  *
361  * @param cls the 'struct GNUNET_CORE_Handle'
362  * @param tc task context
363  */
364 static void
365 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
366 {
367   struct GNUNET_CORE_Handle *h = cls;
368
369   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
370 #if DEBUG_CORE
371   LOG (GNUNET_ERROR_TYPE_DEBUG, "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   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   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     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     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     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     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       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     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     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     LOG (GNUNET_ERROR_TYPE_DEBUG, "Request pending, not processing queue\n");
742 #endif
743     return;
744   }
745   if (h->control_pending_head != NULL)
746     msize =
747         ntohs (((struct GNUNET_MessageHeader *) &h->
748                 control_pending_head[1])->size);
749   else if (h->ready_peer_head != NULL)
750     msize =
751         h->ready_peer_head->pending_head->msize + sizeof (struct SendMessage);
752   else
753   {
754 #if DEBUG_CORE
755     LOG (GNUNET_ERROR_TYPE_DEBUG,
756          "Request queue empty, not processing queue\n");
757 #endif
758     return;                     /* no pending message */
759   }
760   h->cth =
761       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
762                                            GNUNET_TIME_UNIT_FOREVER_REL,
763                                            GNUNET_NO, &transmit_message, h);
764 }
765
766
767 /**
768  * Handler for notification messages received from the core.
769  *
770  * @param cls our "struct GNUNET_CORE_Handle"
771  * @param msg the message received from the core service
772  */
773 static void
774 main_notify_handler (void *cls, const struct GNUNET_MessageHeader *msg)
775 {
776   struct GNUNET_CORE_Handle *h = cls;
777   const struct InitReplyMessage *m;
778   const struct ConnectNotifyMessage *cnm;
779   const struct DisconnectNotifyMessage *dnm;
780   const struct NotifyTrafficMessage *ntm;
781   const struct GNUNET_MessageHeader *em;
782   const struct SendMessageReady *smr;
783   const struct GNUNET_CORE_MessageHandler *mh;
784   GNUNET_CORE_StartupCallback init;
785   struct PeerRecord *pr;
786   struct GNUNET_CORE_TransmitHandle *th;
787   unsigned int hpos;
788   int trigger;
789   uint16_t msize;
790   uint16_t et;
791   uint32_t ats_count;
792
793   if (msg == NULL)
794   {
795     LOG (GNUNET_ERROR_TYPE_INFO,
796          _
797          ("Client was disconnected from core service, trying to reconnect.\n"));
798     reconnect_later (h);
799     return;
800   }
801   msize = ntohs (msg->size);
802 #if DEBUG_CORE > 2
803   LOG (GNUNET_ERROR_TYPE_DEBUG,
804        "Processing message of type %u and size %u from core service\n",
805        ntohs (msg->type), msize);
806 #endif
807   switch (ntohs (msg->type))
808   {
809   case GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY:
810     if (ntohs (msg->size) != sizeof (struct InitReplyMessage))
811     {
812       GNUNET_break (0);
813       reconnect_later (h);
814       return;
815     }
816     m = (const struct InitReplyMessage *) msg;
817     GNUNET_break (0 == ntohl (m->reserved));
818     /* start our message processing loop */
819     if (GNUNET_YES == h->currently_down)
820     {
821       h->currently_down = GNUNET_NO;
822       trigger_next_request (h, GNUNET_NO);
823     }
824     h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
825     h->me = m->my_identity;
826     if (NULL != (init = h->init))
827     {
828       /* mark so we don't call init on reconnect */
829       h->init = NULL;
830 #if DEBUG_CORE
831       LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to core service of peer `%s'.\n",
832            GNUNET_i2s (&h->me));
833 #endif
834       init (h->cls, h, &h->me);
835     }
836     else
837     {
838 #if DEBUG_CORE
839       LOG (GNUNET_ERROR_TYPE_DEBUG,
840            "Successfully reconnected to core service.\n");
841 #endif
842     }
843     /* fake 'connect to self' */
844     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &h->me.hashPubKey);
845     GNUNET_assert (pr == NULL);
846     pr = GNUNET_malloc (sizeof (struct PeerRecord));
847     pr->peer = h->me;
848     pr->ch = h;
849     GNUNET_assert (GNUNET_YES ==
850                    GNUNET_CONTAINER_multihashmap_put (h->peers,
851                                                       &h->me.hashPubKey, pr,
852                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
853     if (NULL != h->connects)
854       h->connects (h->cls, &h->me, NULL);
855     break;
856   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT:
857     if (msize < sizeof (struct ConnectNotifyMessage))
858     {
859       GNUNET_break (0);
860       reconnect_later (h);
861       return;
862     }
863     cnm = (const struct ConnectNotifyMessage *) msg;
864     ats_count = ntohl (cnm->ats_count);
865     if ((msize !=
866          sizeof (struct ConnectNotifyMessage) +
867          ats_count * sizeof (struct GNUNET_ATS_Information)) ||
868         (GNUNET_ATS_ARRAY_TERMINATOR !=
869          ntohl ((&cnm->ats)[ats_count].type)))
870     {
871       GNUNET_break (0);
872       reconnect_later (h);
873       return;
874     }
875 #if DEBUG_CORE
876     LOG (GNUNET_ERROR_TYPE_DEBUG,
877          "Received notification about connection from `%s'.\n",
878          GNUNET_i2s (&cnm->peer));
879 #endif
880     if (0 == memcmp (&h->me, &cnm->peer, sizeof (struct GNUNET_PeerIdentity)))
881     {
882       /* connect to self!? */
883       GNUNET_break (0);
884       return;
885     }
886     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &cnm->peer.hashPubKey);
887     if (pr != NULL)
888     {
889       GNUNET_break (0);
890       reconnect_later (h);
891       return;
892     }
893     pr = GNUNET_malloc (sizeof (struct PeerRecord));
894     pr->peer = cnm->peer;
895     pr->ch = h;
896     GNUNET_assert (GNUNET_YES ==
897                    GNUNET_CONTAINER_multihashmap_put (h->peers,
898                                                       &cnm->peer.hashPubKey, pr,
899                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
900     if (NULL != h->connects)
901       h->connects (h->cls, &cnm->peer, &cnm->ats);
902     break;
903   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT:
904     if (msize != sizeof (struct DisconnectNotifyMessage))
905     {
906       GNUNET_break (0);
907       reconnect_later (h);
908       return;
909     }
910     dnm = (const struct DisconnectNotifyMessage *) msg;
911     if (0 == memcmp (&h->me, &dnm->peer, sizeof (struct GNUNET_PeerIdentity)))
912     {
913       /* connection to self!? */
914       GNUNET_break (0);
915       return;
916     }
917     GNUNET_break (0 == ntohl (dnm->reserved));
918 #if DEBUG_CORE
919     LOG (GNUNET_ERROR_TYPE_DEBUG,
920          "Received notification about disconnect from `%s'.\n",
921          GNUNET_i2s (&dnm->peer));
922 #endif
923     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &dnm->peer.hashPubKey);
924     if (pr == NULL)
925     {
926       GNUNET_break (0);
927       reconnect_later (h);
928       return;
929     }
930     trigger = ((pr->prev != NULL) || (pr->next != NULL) ||
931                (h->ready_peer_head == pr));
932     disconnect_and_free_peer_entry (h, &dnm->peer.hashPubKey, pr);
933     if (trigger)
934       trigger_next_request (h, GNUNET_NO);
935     break;
936   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND:
937     if (msize < sizeof (struct NotifyTrafficMessage))
938     {
939       GNUNET_break (0);
940       reconnect_later (h);
941       return;
942     }
943     ntm = (const struct NotifyTrafficMessage *) msg;
944
945     ats_count = ntohl (ntm->ats_count);
946     if ((msize <
947          sizeof (struct NotifyTrafficMessage) +
948          ats_count * sizeof (struct GNUNET_ATS_Information) +
949          sizeof (struct GNUNET_MessageHeader)) ||
950         (GNUNET_ATS_ARRAY_TERMINATOR !=
951          ntohl ((&ntm->ats)[ats_count].type)))
952     {
953       GNUNET_break (0);
954       reconnect_later (h);
955       return;
956     }
957     em = (const struct GNUNET_MessageHeader *) &(&ntm->ats)[ats_count + 1];
958 #if DEBUG_CORE
959     LOG (GNUNET_ERROR_TYPE_DEBUG,
960          "Received message of type %u and size %u from peer `%4s'\n",
961          ntohs (em->type), ntohs (em->size), GNUNET_i2s (&ntm->peer));
962 #endif
963     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &ntm->peer.hashPubKey);
964     if (pr == NULL)
965     {
966       GNUNET_break (0);
967       reconnect_later (h);
968       return;
969     }
970     if ((GNUNET_NO == h->inbound_hdr_only) &&
971         (msize !=
972          ntohs (em->size) + sizeof (struct NotifyTrafficMessage) +
973          +ats_count * sizeof (struct GNUNET_ATS_Information)))
974     {
975       GNUNET_break (0);
976       reconnect_later (h);
977       return;
978     }
979     et = ntohs (em->type);
980     for (hpos = 0; hpos < h->hcnt; hpos++)
981     {
982       mh = &h->handlers[hpos];
983       if (mh->type != et)
984         continue;
985       if ((mh->expected_size != ntohs (em->size)) && (mh->expected_size != 0))
986       {
987         GNUNET_break (0);
988         continue;
989       }
990       if (GNUNET_OK !=
991           h->handlers[hpos].callback (h->cls, &ntm->peer, em, &ntm->ats))
992       {
993         /* error in processing, do not process other messages! */
994         break;
995       }
996     }
997     if (NULL != h->inbound_notify)
998       h->inbound_notify (h->cls, &ntm->peer, em, &ntm->ats);
999     break;
1000   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND:
1001     if (msize < sizeof (struct NotifyTrafficMessage))
1002     {
1003       GNUNET_break (0);
1004       reconnect_later (h);
1005       return;
1006     }
1007     ntm = (const struct NotifyTrafficMessage *) msg;
1008     if (0 == memcmp (&h->me, &ntm->peer, sizeof (struct GNUNET_PeerIdentity)))
1009     {
1010       /* self-change!? */
1011       GNUNET_break (0);
1012       return;
1013     }
1014     ats_count = ntohl (ntm->ats_count);
1015     if ((msize <
1016          sizeof (struct NotifyTrafficMessage) +
1017          ats_count * sizeof (struct GNUNET_ATS_Information) +
1018          sizeof (struct GNUNET_MessageHeader)) ||
1019         (GNUNET_ATS_ARRAY_TERMINATOR !=
1020          ntohl ((&ntm->ats)[ats_count].type)))
1021     {
1022       GNUNET_break (0);
1023       reconnect_later (h);
1024       return;
1025     }
1026     em = (const struct GNUNET_MessageHeader *) &(&ntm->ats)[ats_count + 1];
1027     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &ntm->peer.hashPubKey);
1028     if (pr == NULL)
1029     {
1030       GNUNET_break (0);
1031       reconnect_later (h);
1032       return;
1033     }
1034 #if DEBUG_CORE
1035     LOG (GNUNET_ERROR_TYPE_DEBUG,
1036          "Received notification about transmission to `%s'.\n",
1037          GNUNET_i2s (&ntm->peer));
1038 #endif
1039     if ((GNUNET_NO == h->outbound_hdr_only) &&
1040         (msize !=
1041          ntohs (em->size) + sizeof (struct NotifyTrafficMessage) +
1042          ats_count * sizeof (struct GNUNET_ATS_Information)))
1043     {
1044       GNUNET_break (0);
1045       reconnect_later (h);
1046       return;
1047     }
1048     if (NULL == h->outbound_notify)
1049     {
1050       GNUNET_break (0);
1051       break;
1052     }
1053     h->outbound_notify (h->cls, &ntm->peer, em, &ntm->ats);
1054     break;
1055   case GNUNET_MESSAGE_TYPE_CORE_SEND_READY:
1056     if (msize != sizeof (struct SendMessageReady))
1057     {
1058       GNUNET_break (0);
1059       reconnect_later (h);
1060       return;
1061     }
1062     smr = (const struct SendMessageReady *) msg;
1063     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &smr->peer.hashPubKey);
1064     if (pr == NULL)
1065     {
1066       GNUNET_break (0);
1067       reconnect_later (h);
1068       return;
1069     }
1070 #if DEBUG_CORE
1071     LOG (GNUNET_ERROR_TYPE_DEBUG,
1072          "Received notification about transmission readiness to `%s'.\n",
1073          GNUNET_i2s (&smr->peer));
1074 #endif
1075     if (pr->pending_head == NULL)
1076     {
1077       /* request must have been cancelled between the original request
1078        * and the response from core, ignore core's readiness */
1079       break;
1080     }
1081
1082     th = pr->pending_head;
1083     if (ntohs (smr->smr_id) != th->smr_id)
1084     {
1085       /* READY message is for expired or cancelled message,
1086        * ignore! (we should have already sent another request) */
1087       break;
1088     }
1089     if ((pr->prev != NULL) || (pr->next != NULL) || (h->ready_peer_head == pr))
1090     {
1091       /* we should not already be on the ready list... */
1092       GNUNET_break (0);
1093       reconnect_later (h);
1094       return;
1095     }
1096     GNUNET_CONTAINER_DLL_insert (h->ready_peer_head, h->ready_peer_tail, pr);
1097     trigger_next_request (h, GNUNET_NO);
1098     break;
1099   default:
1100     reconnect_later (h);
1101     return;
1102   }
1103   GNUNET_CLIENT_receive (h->client, &main_notify_handler, h,
1104                          GNUNET_TIME_UNIT_FOREVER_REL);
1105 }
1106
1107
1108 /**
1109  * Task executed once we are done transmitting the INIT message.
1110  * Starts our 'receive' loop.
1111  *
1112  * @param cls the 'struct GNUNET_CORE_Handle'
1113  * @param success were we successful
1114  */
1115 static void
1116 init_done_task (void *cls, int success)
1117 {
1118   struct GNUNET_CORE_Handle *h = cls;
1119
1120   if (success == GNUNET_SYSERR)
1121     return;                     /* shutdown */
1122   if (success == GNUNET_NO)
1123   {
1124 #if DEBUG_CORE
1125     LOG (GNUNET_ERROR_TYPE_DEBUG,
1126          "Failed to exchange INIT with core, retrying\n");
1127 #endif
1128     if (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK)
1129       reconnect_later (h);
1130     return;
1131   }
1132   GNUNET_CLIENT_receive (h->client, &main_notify_handler, h,
1133                          GNUNET_TIME_UNIT_FOREVER_REL);
1134 }
1135
1136
1137 /**
1138  * Our current client connection went down.  Clean it up
1139  * and try to reconnect!
1140  *
1141  * @param h our handle to the core service
1142  */
1143 static void
1144 reconnect (struct GNUNET_CORE_Handle *h)
1145 {
1146   struct ControlMessage *cm;
1147   struct InitMessage *init;
1148   uint32_t opt;
1149   uint16_t msize;
1150   uint16_t *ts;
1151   unsigned int hpos;
1152
1153 #if DEBUG_CORE
1154   LOG (GNUNET_ERROR_TYPE_DEBUG, "Reconnecting to CORE service\n");
1155 #endif
1156   GNUNET_assert (h->client == NULL);
1157   GNUNET_assert (h->currently_down == GNUNET_YES);
1158   h->client = GNUNET_CLIENT_connect ("core", h->cfg);
1159   if (h->client == NULL)
1160   {
1161     reconnect_later (h);
1162     return;
1163   }
1164   msize = h->hcnt * sizeof (uint16_t) + sizeof (struct InitMessage);
1165   cm = GNUNET_malloc (sizeof (struct ControlMessage) + msize);
1166   cm->cont = &init_done_task;
1167   cm->cont_cls = h;
1168   init = (struct InitMessage *) &cm[1];
1169   init->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT);
1170   init->header.size = htons (msize);
1171   opt = 0;
1172   if (h->inbound_notify != NULL)
1173   {
1174     if (h->inbound_hdr_only)
1175       opt |= GNUNET_CORE_OPTION_SEND_HDR_INBOUND;
1176     else
1177       opt |= GNUNET_CORE_OPTION_SEND_FULL_INBOUND;
1178   }
1179   if (h->outbound_notify != NULL)
1180   {
1181     if (h->outbound_hdr_only)
1182       opt |= GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND;
1183     else
1184       opt |= GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND;
1185   }
1186   init->options = htonl (opt);
1187   ts = (uint16_t *) & init[1];
1188   for (hpos = 0; hpos < h->hcnt; hpos++)
1189     ts[hpos] = htons (h->handlers[hpos].type);
1190   GNUNET_CONTAINER_DLL_insert (h->control_pending_head, h->control_pending_tail,
1191                                cm);
1192   trigger_next_request (h, GNUNET_YES);
1193 }
1194
1195
1196
1197 /**
1198  * Connect to the core service.  Note that the connection may
1199  * complete (or fail) asynchronously.
1200  *
1201  * @param cfg configuration to use
1202  * @param queue_size size of the per-peer message queue
1203  * @param cls closure for the various callbacks that follow (including handlers in the handlers array)
1204  * @param init callback to call on timeout or once we have successfully
1205  *        connected to the core service; note that timeout is only meaningful if init is not NULL
1206  * @param connects function to call on peer connect, can be NULL
1207  * @param disconnects function to call on peer disconnect / timeout, can be NULL
1208  * @param inbound_notify function to call for all inbound messages, can be NULL
1209  * @param inbound_hdr_only set to GNUNET_YES if inbound_notify will only read the
1210  *                GNUNET_MessageHeader and hence we do not need to give it the full message;
1211  *                can be used to improve efficiency, ignored if inbound_notify is NULLL
1212  * @param outbound_notify function to call for all outbound messages, can be NULL
1213  * @param outbound_hdr_only set to GNUNET_YES if outbound_notify will only read the
1214  *                GNUNET_MessageHeader and hence we do not need to give it the full message
1215  *                can be used to improve efficiency, ignored if outbound_notify is NULLL
1216  * @param handlers callbacks for messages we care about, NULL-terminated
1217  * @return handle to the core service (only useful for disconnect until 'init' is called);
1218  *                NULL on error (in this case, init is never called)
1219  */
1220 struct GNUNET_CORE_Handle *
1221 GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1222                      unsigned int queue_size, void *cls,
1223                      GNUNET_CORE_StartupCallback init,
1224                      GNUNET_CORE_ConnectEventHandler connects,
1225                      GNUNET_CORE_DisconnectEventHandler disconnects,
1226                      GNUNET_CORE_MessageCallback inbound_notify,
1227                      int inbound_hdr_only,
1228                      GNUNET_CORE_MessageCallback outbound_notify,
1229                      int outbound_hdr_only,
1230                      const struct GNUNET_CORE_MessageHandler *handlers)
1231 {
1232   struct GNUNET_CORE_Handle *h;
1233
1234   h = GNUNET_malloc (sizeof (struct GNUNET_CORE_Handle));
1235   h->cfg = cfg;
1236   h->queue_size = queue_size;
1237   h->cls = cls;
1238   h->init = init;
1239   h->connects = connects;
1240   h->disconnects = disconnects;
1241   h->inbound_notify = inbound_notify;
1242   h->outbound_notify = outbound_notify;
1243   h->inbound_hdr_only = inbound_hdr_only;
1244   h->outbound_hdr_only = outbound_hdr_only;
1245   h->handlers = handlers;
1246   h->hcnt = 0;
1247   h->currently_down = GNUNET_YES;
1248   h->peers = GNUNET_CONTAINER_multihashmap_create (128);
1249   h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1250   if (NULL != handlers)
1251     while (handlers[h->hcnt].callback != NULL)
1252       h->hcnt++;
1253   GNUNET_assert (h->hcnt <
1254                  (GNUNET_SERVER_MAX_MESSAGE_SIZE -
1255                   sizeof (struct InitMessage)) / sizeof (uint16_t));
1256 #if DEBUG_CORE
1257   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connecting to CORE service\n");
1258 #endif
1259   reconnect (h);
1260   return h;
1261 }
1262
1263
1264 /**
1265  * Disconnect from the core service.  This function can only
1266  * be called *after* all pending 'GNUNET_CORE_notify_transmit_ready'
1267  * requests have been explicitly canceled.
1268  *
1269  * @param handle connection to core to disconnect
1270  */
1271 void
1272 GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle)
1273 {
1274   struct ControlMessage *cm;
1275
1276 #if DEBUG_CORE
1277   LOG (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from CORE service\n");
1278 #endif
1279   if (handle->cth != NULL)
1280   {
1281     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->cth);
1282     handle->cth = NULL;
1283   }
1284   while (NULL != (cm = handle->control_pending_head))
1285   {
1286     GNUNET_CONTAINER_DLL_remove (handle->control_pending_head,
1287                                  handle->control_pending_tail, cm);
1288     if (cm->th != NULL)
1289       cm->th->cm = NULL;
1290     if (cm->cont != NULL)
1291       cm->cont (cm->cont_cls, GNUNET_SYSERR);
1292     GNUNET_free (cm);
1293   }
1294   if (handle->client != NULL)
1295   {
1296     GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
1297     handle->client = NULL;
1298   }
1299   GNUNET_CONTAINER_multihashmap_iterate (handle->peers,
1300                                          &disconnect_and_free_peer_entry,
1301                                          handle);
1302   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1303   {
1304     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1305     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1306   }
1307   GNUNET_CONTAINER_multihashmap_destroy (handle->peers);
1308   handle->peers = NULL;
1309   GNUNET_break (handle->ready_peer_head == NULL);
1310   GNUNET_free (handle);
1311 }
1312
1313
1314 /**
1315  * Task that calls 'request_next_transmission'.
1316  *
1317  * @param cls the 'struct PeerRecord*'
1318  * @param tc scheduler context
1319  */
1320 static void
1321 run_request_next_transmission (void *cls,
1322                                const struct GNUNET_SCHEDULER_TaskContext *tc)
1323 {
1324   struct PeerRecord *pr = cls;
1325
1326   pr->ntr_task = GNUNET_SCHEDULER_NO_TASK;
1327   request_next_transmission (pr);
1328 }
1329
1330
1331 /**
1332  * Ask the core to call "notify" once it is ready to transmit the
1333  * given number of bytes to the specified "target".    Must only be
1334  * called after a connection to the respective peer has been
1335  * established (and the client has been informed about this).
1336  *
1337  * @param handle connection to core service
1338  * @param cork is corking allowed for this transmission?
1339  * @param priority how important is the message?
1340  * @param maxdelay how long can the message wait?
1341  * @param target who should receive the message,
1342  *        use NULL for this peer (loopback)
1343  * @param notify_size how many bytes of buffer space does notify want?
1344  * @param notify function to call when buffer space is available
1345  * @param notify_cls closure for notify
1346  * @return non-NULL if the notify callback was queued,
1347  *         NULL if we can not even queue the request (insufficient
1348  *         memory); if NULL is returned, "notify" will NOT be called.
1349  */
1350 struct GNUNET_CORE_TransmitHandle *
1351 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle, int cork,
1352                                    uint32_t priority,
1353                                    struct GNUNET_TIME_Relative maxdelay,
1354                                    const struct GNUNET_PeerIdentity *target,
1355                                    size_t notify_size,
1356                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1357                                    void *notify_cls)
1358 {
1359   struct PeerRecord *pr;
1360   struct GNUNET_CORE_TransmitHandle *th;
1361   struct GNUNET_CORE_TransmitHandle *pos;
1362   struct GNUNET_CORE_TransmitHandle *prev;
1363   struct GNUNET_CORE_TransmitHandle *minp;
1364
1365   pr = GNUNET_CONTAINER_multihashmap_get (handle->peers, &target->hashPubKey);
1366   if (NULL == pr)
1367   {
1368     /* attempt to send to peer that is not connected */
1369     LOG (GNUNET_ERROR_TYPE_WARNING,
1370          "Attempting to send to peer `%s' from peer `%s', but not connected!\n",
1371          GNUNET_i2s (target), GNUNET_h2s (&handle->me.hashPubKey));
1372     GNUNET_break (0);
1373     return NULL;
1374   }
1375   GNUNET_assert (notify_size + sizeof (struct SendMessage) <
1376                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
1377   th = GNUNET_malloc (sizeof (struct GNUNET_CORE_TransmitHandle));
1378   th->peer = pr;
1379   GNUNET_assert (NULL != notify);
1380   th->get_message = notify;
1381   th->get_message_cls = notify_cls;
1382   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1383   th->priority = priority;
1384   th->msize = notify_size;
1385   th->cork = cork;
1386   /* bound queue size */
1387   if (pr->queue_size == handle->queue_size)
1388   {
1389     /* find lowest-priority entry, but skip the head of the list */
1390     minp = pr->pending_head->next;
1391     prev = minp;
1392     while (prev != NULL)
1393     {
1394       if (prev->priority < minp->priority)
1395         minp = prev;
1396       prev = prev->next;
1397     }
1398     if (minp == NULL)
1399     {
1400       GNUNET_break (handle->queue_size != 0);
1401       GNUNET_break (pr->queue_size == 1);
1402       GNUNET_free (th);
1403 #if DEBUG_CORE
1404       LOG (GNUNET_ERROR_TYPE_DEBUG,
1405            "Dropping transmission request: cannot drop queue head and limit is one\n");
1406 #endif
1407       return NULL;
1408     }
1409     if (priority <= minp->priority)
1410     {
1411 #if DEBUG_CORE
1412       LOG (GNUNET_ERROR_TYPE_DEBUG,
1413            "Dropping transmission request: priority too low\n");
1414 #endif
1415       GNUNET_free (th);
1416       return NULL;              /* priority too low */
1417     }
1418     GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, minp);
1419     pr->queue_size--;
1420     GNUNET_assert (0 == minp->get_message (minp->get_message_cls, 0, NULL));
1421     GNUNET_free (minp);
1422   }
1423
1424   /* Order entries by deadline, but SKIP 'HEAD' if
1425    * we're in the 'ready_peer_*' DLL */
1426   pos = pr->pending_head;
1427   if ((pr->prev != NULL) || (pr->next != NULL) ||
1428       (pr == handle->ready_peer_head))
1429   {
1430     GNUNET_assert (pos != NULL);
1431     pos = pos->next;            /* skip head */
1432   }
1433
1434   /* insertion sort */
1435   prev = pos;
1436   while ((pos != NULL) && (pos->timeout.abs_value < th->timeout.abs_value))
1437   {
1438     prev = pos;
1439     pos = pos->next;
1440   }
1441   GNUNET_CONTAINER_DLL_insert_after (pr->pending_head, pr->pending_tail, prev,
1442                                      th);
1443   pr->queue_size++;
1444   /* was the request queue previously empty? */
1445 #if DEBUG_CORE
1446   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmission request added to queue\n");
1447 #endif
1448   if ((pr->pending_head == th) && (pr->ntr_task == GNUNET_SCHEDULER_NO_TASK) &&
1449       (pr->next == NULL) && (pr->prev == NULL) &&
1450       (handle->ready_peer_head != pr))
1451     pr->ntr_task =
1452         GNUNET_SCHEDULER_add_now (&run_request_next_transmission, pr);
1453   return th;
1454 }
1455
1456
1457 /**
1458  * Cancel the specified transmission-ready notification.
1459  *
1460  * @param th handle that was returned by "notify_transmit_ready".
1461  */
1462 void
1463 GNUNET_CORE_notify_transmit_ready_cancel (struct GNUNET_CORE_TransmitHandle *th)
1464 {
1465   struct PeerRecord *pr = th->peer;
1466   struct GNUNET_CORE_Handle *h = pr->ch;
1467   int was_head;
1468
1469   was_head = (pr->pending_head == th);
1470   GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, th);
1471   pr->queue_size--;
1472   if (th->cm != NULL)
1473   {
1474     /* we're currently in the control queue, remove */
1475     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
1476                                  h->control_pending_tail, th->cm);
1477     GNUNET_free (th->cm);
1478   }
1479   GNUNET_free (th);
1480   if (was_head)
1481   {
1482     if ((pr->prev != NULL) || (pr->next != NULL) || (pr == h->ready_peer_head))
1483     {
1484       /* the request that was 'approved' by core was
1485        * canceled before it could be transmitted; remove
1486        * us from the 'ready' list */
1487       GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
1488     }
1489     request_next_transmission (pr);
1490   }
1491 }
1492
1493
1494 /* end of core_api.c */