-fixing #2332, plus some minor refactoring
[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   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connecting to CORE service after delay\n");
371   reconnect (h);
372 }
373
374
375 /**
376  * Notify clients about disconnect and free
377  * the entry for connected peer.
378  *
379  * @param cls the 'struct GNUNET_CORE_Handle*'
380  * @param key the peer identity (not used)
381  * @param value the 'struct PeerRecord' to free.
382  * @return GNUNET_YES (continue)
383  */
384 static int
385 disconnect_and_free_peer_entry (void *cls, const GNUNET_HashCode * key,
386                                 void *value)
387 {
388   struct GNUNET_CORE_Handle *h = cls;
389   struct GNUNET_CORE_TransmitHandle *th;
390   struct PeerRecord *pr = value;
391
392   if (pr->timeout_task != GNUNET_SCHEDULER_NO_TASK)
393   {
394     GNUNET_SCHEDULER_cancel (pr->timeout_task);
395     pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
396   }
397   if (pr->ntr_task != GNUNET_SCHEDULER_NO_TASK)
398   {
399     GNUNET_SCHEDULER_cancel (pr->ntr_task);
400     pr->ntr_task = GNUNET_SCHEDULER_NO_TASK;
401   }
402   if ((pr->prev != NULL) || (pr->next != NULL) || (h->ready_peer_head == pr))
403     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
404   if (h->disconnects != NULL)
405     h->disconnects (h->cls, &pr->peer);
406   /* all requests should have been cancelled, clean up anyway, just in case */
407   GNUNET_break (pr->queue_size == 0);
408   while (NULL != (th = pr->pending_head))
409   {
410     GNUNET_break (0);
411     GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, th);
412     pr->queue_size--;
413     if (th->cm != NULL)
414       th->cm->th = NULL;
415     GNUNET_free (th);
416   }
417   /* done with 'voluntary' cleanups, now on to normal freeing */
418   GNUNET_assert (GNUNET_YES ==
419                  GNUNET_CONTAINER_multihashmap_remove (h->peers, key, pr));
420   GNUNET_assert (pr->pending_head == NULL);
421   GNUNET_assert (pr->pending_tail == NULL);
422   GNUNET_assert (pr->ch == h);
423   GNUNET_assert (pr->queue_size == 0);
424   GNUNET_assert (pr->timeout_task == GNUNET_SCHEDULER_NO_TASK);
425   GNUNET_assert (pr->ntr_task == GNUNET_SCHEDULER_NO_TASK);
426   GNUNET_free (pr);
427   return GNUNET_YES;
428 }
429
430
431 /**
432  * Close down any existing connection to the CORE service and
433  * try re-establishing it later.
434  *
435  * @param h our handle
436  */
437 static void
438 reconnect_later (struct GNUNET_CORE_Handle *h)
439 {
440   struct ControlMessage *cm;
441   struct PeerRecord *pr;
442
443   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
444   if (NULL != h->cth)
445   {
446     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
447     h->cth = NULL;
448   }
449   if (h->client != NULL)
450   {
451     GNUNET_CLIENT_disconnect (h->client);
452     h->client = NULL;
453   }
454   h->currently_down = GNUNET_YES;
455   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
456   h->reconnect_task =
457       GNUNET_SCHEDULER_add_delayed (h->retry_backoff, &reconnect_task, h);
458   while (NULL != (cm = h->control_pending_head))
459   {
460     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
461                                  h->control_pending_tail, cm);
462     if (cm->th != NULL)
463       cm->th->cm = NULL;
464     if (cm->cont != NULL)
465       cm->cont (cm->cont_cls, GNUNET_NO);
466     GNUNET_free (cm);
467   }
468   GNUNET_CONTAINER_multihashmap_iterate (h->peers,
469                                          &disconnect_and_free_peer_entry, h);
470   while (NULL != (pr = h->ready_peer_head))
471     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
472   GNUNET_assert (h->control_pending_head == NULL);
473   h->retry_backoff =
474       GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS, h->retry_backoff);
475   h->retry_backoff = GNUNET_TIME_relative_multiply (h->retry_backoff, 2);
476 }
477
478
479 /**
480  * Check the list of pending requests, send the next
481  * one to the core.
482  *
483  * @param h core handle
484  * @param ignore_currently_down transmit message even if not initialized?
485  */
486 static void
487 trigger_next_request (struct GNUNET_CORE_Handle *h, int ignore_currently_down);
488
489
490 /**
491  * The given request hit its timeout.  Remove from the
492  * doubly-linked list and call the respective continuation.
493  *
494  * @param cls the transmit handle of the request that timed out
495  * @param tc context, can be NULL (!)
496  */
497 static void
498 transmission_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
499
500
501 /**
502  * Send a control message to the peer asking for transmission
503  * of the message in the given peer record.
504  *
505  * @param pr peer to request transmission to
506  */
507 static void
508 request_next_transmission (struct PeerRecord *pr)
509 {
510   struct GNUNET_CORE_Handle *h = pr->ch;
511   struct ControlMessage *cm;
512   struct SendMessageRequest *smr;
513   struct GNUNET_CORE_TransmitHandle *th;
514
515   if (pr->timeout_task != GNUNET_SCHEDULER_NO_TASK)
516   {
517     GNUNET_SCHEDULER_cancel (pr->timeout_task);
518     pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
519   }
520   if (NULL == (th = pr->pending_head))
521   {
522     trigger_next_request (h, GNUNET_NO);
523     return;
524   }
525   if (th->cm != NULL)
526     return;                     /* already done */
527   GNUNET_assert (pr->prev == NULL);
528   GNUNET_assert (pr->next == NULL);
529   pr->timeout_task =
530       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
531                                     (th->timeout), &transmission_timeout, pr);
532   cm = GNUNET_malloc (sizeof (struct ControlMessage) +
533                       sizeof (struct SendMessageRequest));
534   th->cm = cm;
535   cm->th = th;
536   smr = (struct SendMessageRequest *) &cm[1];
537   smr->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST);
538   smr->header.size = htons (sizeof (struct SendMessageRequest));
539   smr->priority = htonl (th->priority);
540   smr->deadline = GNUNET_TIME_absolute_hton (th->timeout);
541   smr->peer = pr->peer;
542   smr->queue_size = htonl (pr->queue_size);
543   smr->size = htons (th->msize);
544   smr->smr_id = htons (th->smr_id = pr->smr_id_gen++);
545   GNUNET_CONTAINER_DLL_insert_tail (h->control_pending_head,
546                                     h->control_pending_tail, cm);
547   LOG (GNUNET_ERROR_TYPE_DEBUG,
548        "Adding SEND REQUEST for peer `%s' to message queue\n",
549        GNUNET_i2s (&pr->peer));
550   trigger_next_request (h, GNUNET_NO);
551 }
552
553
554 /**
555  * The given request hit its timeout.  Remove from the
556  * doubly-linked list and call the respective continuation.
557  *
558  * @param cls the transmit handle of the request that timed out
559  * @param tc context, can be NULL (!)
560  */
561 static void
562 transmission_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
563 {
564   struct PeerRecord *pr = cls;
565   struct GNUNET_CORE_Handle *h = pr->ch;
566   struct GNUNET_CORE_TransmitHandle *th;
567
568   pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
569   th = pr->pending_head;
570   GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, th);
571   pr->queue_size--;
572   if ((pr->prev != NULL) || (pr->next != NULL) || (pr == h->ready_peer_head))
573   {
574     /* the request that was 'approved' by core was
575      * canceled before it could be transmitted; remove
576      * us from the 'ready' list */
577     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
578   }
579   if (NULL != th->cm)
580   {
581      /* we're currently in the control queue, remove */
582     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
583                                  h->control_pending_tail, th->cm);
584     GNUNET_free (th->cm);
585   }
586   LOG (GNUNET_ERROR_TYPE_DEBUG,
587        "Signalling timeout of request for transmission to CORE service\n");
588   request_next_transmission (pr);
589   GNUNET_assert (0 == th->get_message (th->get_message_cls, 0, NULL));
590   GNUNET_free (th);
591 }
592
593
594 /**
595  * Transmit the next message to the core service.
596  */
597 static size_t
598 transmit_message (void *cls, size_t size, void *buf)
599 {
600   struct GNUNET_CORE_Handle *h = cls;
601   struct ControlMessage *cm;
602   struct GNUNET_CORE_TransmitHandle *th;
603   struct PeerRecord *pr;
604   struct SendMessage *sm;
605   const struct GNUNET_MessageHeader *hdr;
606   uint16_t msize;
607   size_t ret;
608
609   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
610   h->cth = NULL;
611   if (buf == NULL)
612   {
613     LOG (GNUNET_ERROR_TYPE_DEBUG,
614          "Transmission failed, initiating reconnect\n");
615     reconnect_later (h);
616     return 0;
617   }
618   /* first check for control messages */
619   if (NULL != (cm = h->control_pending_head))
620   {
621     hdr = (const struct GNUNET_MessageHeader *) &cm[1];
622     msize = ntohs (hdr->size);
623     if (size < msize)
624     {
625       trigger_next_request (h, GNUNET_NO);
626       return 0;
627     }
628     LOG (GNUNET_ERROR_TYPE_DEBUG,
629          "Transmitting control message with %u bytes of type %u to core.\n",
630          (unsigned int) msize, (unsigned int) ntohs (hdr->type));
631     memcpy (buf, hdr, msize);
632     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
633                                  h->control_pending_tail, cm);
634     if (cm->th != NULL)
635       cm->th->cm = NULL;
636     if (NULL != cm->cont)
637       cm->cont (cm->cont_cls, GNUNET_OK);
638     GNUNET_free (cm);
639     trigger_next_request (h, GNUNET_NO);
640     return msize;
641   }
642   /* now check for 'ready' P2P messages */
643   if (NULL != (pr = h->ready_peer_head))
644   {
645     GNUNET_assert (pr->pending_head != NULL);
646     th = pr->pending_head;
647     if (size < th->msize + sizeof (struct SendMessage))
648     {
649       trigger_next_request (h, GNUNET_NO);
650       return 0;
651     }
652     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
653     GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, th);
654     pr->queue_size--;
655     if (pr->timeout_task != GNUNET_SCHEDULER_NO_TASK)
656     {
657       GNUNET_SCHEDULER_cancel (pr->timeout_task);
658       pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
659     }
660     LOG (GNUNET_ERROR_TYPE_DEBUG,
661          "Transmitting SEND request to `%s' with %u bytes.\n",
662          GNUNET_i2s (&pr->peer), (unsigned int) th->msize);
663     sm = (struct SendMessage *) buf;
664     sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND);
665     sm->priority = htonl (th->priority);
666     sm->deadline = GNUNET_TIME_absolute_hton (th->timeout);
667     sm->peer = pr->peer;
668     sm->cork = htonl ((uint32_t) th->cork);
669     sm->reserved = htonl (0);
670     ret =
671         th->get_message (th->get_message_cls,
672                          size - sizeof (struct SendMessage), &sm[1]);
673
674     LOG (GNUNET_ERROR_TYPE_DEBUG,
675          "Transmitting SEND request to `%s' yielded %u bytes.\n",
676          GNUNET_i2s (&pr->peer), ret);
677     GNUNET_free (th);
678     if (0 == ret)
679     {
680       LOG (GNUNET_ERROR_TYPE_DEBUG,
681            "Size of clients message to peer %s is 0!\n",
682            GNUNET_i2s (&pr->peer));
683       /* client decided to send nothing! */
684       request_next_transmission (pr);
685       return 0;
686     }
687     LOG (GNUNET_ERROR_TYPE_DEBUG,
688          "Produced SEND message to core with %u bytes payload\n",
689          (unsigned int) ret);
690     GNUNET_assert (ret >= sizeof (struct GNUNET_MessageHeader));
691     if (ret + sizeof (struct SendMessage) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
692     {
693       GNUNET_break (0);
694       request_next_transmission (pr);
695       return 0;
696     }
697     ret += sizeof (struct SendMessage);
698     sm->header.size = htons (ret);
699     GNUNET_assert (ret <= size);
700     request_next_transmission (pr);
701     return ret;
702   }
703   return 0;
704 }
705
706
707 /**
708  * Check the list of pending requests, send the next
709  * one to the core.
710  *
711  * @param h core handle
712  * @param ignore_currently_down transmit message even if not initialized?
713  */
714 static void
715 trigger_next_request (struct GNUNET_CORE_Handle *h, int ignore_currently_down)
716 {
717   uint16_t msize;
718
719   if ((GNUNET_YES == h->currently_down) && (ignore_currently_down == GNUNET_NO))
720   {
721     LOG (GNUNET_ERROR_TYPE_DEBUG,
722          "Core connection down, not processing queue\n");
723     return;
724   }
725   if (NULL != h->cth)
726   {
727     LOG (GNUNET_ERROR_TYPE_DEBUG, "Request pending, not processing queue\n");
728     return;
729   }
730   if (h->control_pending_head != NULL)
731     msize =
732         ntohs (((struct GNUNET_MessageHeader *) &h->
733                 control_pending_head[1])->size);
734   else if (h->ready_peer_head != NULL)
735     msize =
736         h->ready_peer_head->pending_head->msize + sizeof (struct SendMessage);
737   else
738   {
739     LOG (GNUNET_ERROR_TYPE_DEBUG,
740          "Request queue empty, not processing queue\n");
741     return;                     /* no pending message */
742   }
743   h->cth =
744       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
745                                            GNUNET_TIME_UNIT_FOREVER_REL,
746                                            GNUNET_NO, &transmit_message, h);
747 }
748
749
750 /**
751  * Handler for notification messages received from the core.
752  *
753  * @param cls our "struct GNUNET_CORE_Handle"
754  * @param msg the message received from the core service
755  */
756 static void
757 main_notify_handler (void *cls, const struct GNUNET_MessageHeader *msg)
758 {
759   struct GNUNET_CORE_Handle *h = cls;
760   const struct InitReplyMessage *m;
761   const struct ConnectNotifyMessage *cnm;
762   const struct DisconnectNotifyMessage *dnm;
763   const struct NotifyTrafficMessage *ntm;
764   const struct GNUNET_MessageHeader *em;
765   const struct SendMessageReady *smr;
766   const struct GNUNET_CORE_MessageHandler *mh;
767   const struct GNUNET_ATS_Information *ats;
768   GNUNET_CORE_StartupCallback init;
769   struct PeerRecord *pr;
770   struct GNUNET_CORE_TransmitHandle *th;
771   unsigned int hpos;
772   int trigger;
773   uint16_t msize;
774   uint16_t et;
775   uint32_t ats_count;
776
777   if (NULL == msg)
778   {
779     LOG (GNUNET_ERROR_TYPE_INFO,
780          _
781          ("Client was disconnected from core service, trying to reconnect.\n"));
782     reconnect_later (h);
783     return;
784   }
785   msize = ntohs (msg->size);
786   LOG (GNUNET_ERROR_TYPE_DEBUG,
787        "Processing message of type %u and size %u from core service\n",
788        ntohs (msg->type), msize);
789   switch (ntohs (msg->type))
790   {
791   case GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY:
792     if (ntohs (msg->size) != sizeof (struct InitReplyMessage))
793     {
794       GNUNET_break (0);
795       reconnect_later (h);
796       return;
797     }
798     m = (const struct InitReplyMessage *) msg;
799     GNUNET_break (0 == ntohl (m->reserved));
800     /* start our message processing loop */
801     if (GNUNET_YES == h->currently_down)
802     {
803       h->currently_down = GNUNET_NO;
804       trigger_next_request (h, GNUNET_NO);
805     }
806     h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
807     h->me = m->my_identity;
808     if (NULL != (init = h->init))
809     {
810       /* mark so we don't call init on reconnect */
811       h->init = NULL;
812       LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to core service of peer `%s'.\n",
813            GNUNET_i2s (&h->me));
814       init (h->cls, h, &h->me);
815     }
816     else
817     {
818       LOG (GNUNET_ERROR_TYPE_DEBUG,
819            "Successfully reconnected to core service.\n");
820     }
821     /* fake 'connect to self' */
822     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &h->me.hashPubKey);
823     GNUNET_assert (NULL == pr);
824     pr = GNUNET_malloc (sizeof (struct PeerRecord));
825     pr->peer = h->me;
826     pr->ch = h;
827     GNUNET_assert (GNUNET_YES ==
828                    GNUNET_CONTAINER_multihashmap_put (h->peers,
829                                                       &h->me.hashPubKey, pr,
830                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
831     if (NULL != h->connects)
832       h->connects (h->cls, &h->me, NULL, 0);
833     break;
834   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT:
835     if (msize < sizeof (struct ConnectNotifyMessage))
836     {
837       GNUNET_break (0);
838       reconnect_later (h);
839       return;
840     }
841     cnm = (const struct ConnectNotifyMessage *) msg;
842     ats_count = ntohl (cnm->ats_count);
843     if (msize !=
844         sizeof (struct ConnectNotifyMessage) +
845         ats_count * sizeof (struct GNUNET_ATS_Information))
846     {
847       GNUNET_break (0);
848       reconnect_later (h);
849       return;
850     }
851     LOG (GNUNET_ERROR_TYPE_DEBUG,
852          "Received notification about connection from `%s'.\n",
853          GNUNET_i2s (&cnm->peer));
854     if (0 == memcmp (&h->me, &cnm->peer, sizeof (struct GNUNET_PeerIdentity)))
855     {
856       /* connect to self!? */
857       GNUNET_break (0);
858       return;
859     }
860     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &cnm->peer.hashPubKey);
861     if (NULL != pr)
862     {
863       GNUNET_break (0);
864       reconnect_later (h);
865       return;
866     }
867     pr = GNUNET_malloc (sizeof (struct PeerRecord));
868     pr->peer = cnm->peer;
869     pr->ch = h;
870     GNUNET_assert (GNUNET_YES ==
871                    GNUNET_CONTAINER_multihashmap_put (h->peers,
872                                                       &cnm->peer.hashPubKey, pr,
873                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
874     ats = (const struct GNUNET_ATS_Information *) &cnm[1];
875     if (NULL != h->connects)
876       h->connects (h->cls, &cnm->peer, ats, ats_count);
877     break;
878   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT:
879     if (msize != sizeof (struct DisconnectNotifyMessage))
880     {
881       GNUNET_break (0);
882       reconnect_later (h);
883       return;
884     }
885     dnm = (const struct DisconnectNotifyMessage *) msg;
886     if (0 == memcmp (&h->me, &dnm->peer, sizeof (struct GNUNET_PeerIdentity)))
887     {
888       /* connection to self!? */
889       GNUNET_break (0);
890       return;
891     }
892     GNUNET_break (0 == ntohl (dnm->reserved));
893     LOG (GNUNET_ERROR_TYPE_DEBUG,
894          "Received notification about disconnect from `%s'.\n",
895          GNUNET_i2s (&dnm->peer));
896     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &dnm->peer.hashPubKey);
897     if (NULL == pr)
898     {
899       GNUNET_break (0);
900       reconnect_later (h);
901       return;
902     }
903     trigger = ((pr->prev != NULL) || (pr->next != NULL) ||
904                (h->ready_peer_head == pr));
905     disconnect_and_free_peer_entry (h, &dnm->peer.hashPubKey, pr);
906     if (trigger)
907       trigger_next_request (h, GNUNET_NO);
908     break;
909   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND:
910     if (msize < sizeof (struct NotifyTrafficMessage))
911     {
912       GNUNET_break (0);
913       reconnect_later (h);
914       return;
915     }
916     ntm = (const struct NotifyTrafficMessage *) msg;
917     ats_count = ntohl (ntm->ats_count);
918     if ((msize <
919          sizeof (struct NotifyTrafficMessage) +
920          ats_count * sizeof (struct GNUNET_ATS_Information) +
921          sizeof (struct GNUNET_MessageHeader)) )
922     {
923       GNUNET_break (0);
924       reconnect_later (h);
925       return;
926     }
927     ats = (const struct GNUNET_ATS_Information*) &ntm[1];
928     em = (const struct GNUNET_MessageHeader *) &ats[ats_count];
929     LOG (GNUNET_ERROR_TYPE_DEBUG,
930          "Received message of type %u and size %u from peer `%4s'\n",
931          ntohs (em->type), ntohs (em->size), GNUNET_i2s (&ntm->peer));
932     if ((GNUNET_NO == h->inbound_hdr_only) &&
933         (msize !=
934          ntohs (em->size) + sizeof (struct NotifyTrafficMessage) +
935          +ats_count * sizeof (struct GNUNET_ATS_Information)))
936     {
937       GNUNET_break (0);
938       reconnect_later (h);
939       return;
940     }
941     et = ntohs (em->type);
942     for (hpos = 0; hpos < h->hcnt; hpos++)
943     {
944       mh = &h->handlers[hpos];
945       if (mh->type != et)
946         continue;
947       if ((mh->expected_size != ntohs (em->size)) && (mh->expected_size != 0))
948       {
949         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
950                     "Unexpected message size %u for message of type %u from peer `%4s'\n",
951                     htons (em->size), mh->type, GNUNET_i2s (&ntm->peer));
952         GNUNET_break_op (0);
953         continue;
954       }
955       pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &ntm->peer.hashPubKey);
956       if (NULL == pr)
957       {
958         GNUNET_break (0);
959         reconnect_later (h);
960         return;
961       }
962       if (GNUNET_OK !=
963           h->handlers[hpos].callback (h->cls, &ntm->peer, em, ats,
964                                       ats_count))
965       {
966         /* error in processing, do not process other messages! */
967         break;
968       }
969     }
970     if (NULL != h->inbound_notify)
971       h->inbound_notify (h->cls, &ntm->peer, em, ats, ats_count);
972     break;
973   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND:
974     if (msize < sizeof (struct NotifyTrafficMessage))
975     {
976       GNUNET_break (0);
977       reconnect_later (h);
978       return;
979     }
980     ntm = (const struct NotifyTrafficMessage *) msg;
981     if (0 == memcmp (&h->me, &ntm->peer, sizeof (struct GNUNET_PeerIdentity)))
982     {
983       /* self-change!? */
984       GNUNET_break (0);
985       return;
986     }
987     ats_count = ntohl (ntm->ats_count);
988     if ((msize <
989          sizeof (struct NotifyTrafficMessage) +
990          ats_count * sizeof (struct GNUNET_ATS_Information) +
991          sizeof (struct GNUNET_MessageHeader)) )
992     {
993       GNUNET_break (0);
994       reconnect_later (h);
995       return;
996     }
997     ats = (const struct GNUNET_ATS_Information*) &ntm[1];    
998     em = (const struct GNUNET_MessageHeader *) &ats[ats_count];
999     LOG (GNUNET_ERROR_TYPE_DEBUG,
1000          "Received notification about transmission to `%s'.\n",
1001          GNUNET_i2s (&ntm->peer));
1002     if ((GNUNET_NO == h->outbound_hdr_only) &&
1003         (msize !=
1004          ntohs (em->size) + sizeof (struct NotifyTrafficMessage) +
1005          ats_count * sizeof (struct GNUNET_ATS_Information)))
1006     {
1007       GNUNET_break (0);
1008       reconnect_later (h);
1009       return;
1010     }
1011     if (NULL == h->outbound_notify)
1012     {
1013       GNUNET_break (0);
1014       break;
1015     }
1016     h->outbound_notify (h->cls, &ntm->peer, em, ats, ats_count);
1017     break;
1018   case GNUNET_MESSAGE_TYPE_CORE_SEND_READY:
1019     if (msize != sizeof (struct SendMessageReady))
1020     {
1021       GNUNET_break (0);
1022       reconnect_later (h);
1023       return;
1024     }
1025     smr = (const struct SendMessageReady *) msg;
1026     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &smr->peer.hashPubKey);
1027     if (NULL == pr)
1028     {
1029       GNUNET_break (0);
1030       reconnect_later (h);
1031       return;
1032     }
1033     LOG (GNUNET_ERROR_TYPE_DEBUG,
1034          "Received notification about transmission readiness to `%s'.\n",
1035          GNUNET_i2s (&smr->peer));
1036     if (NULL == pr->pending_head)
1037     {
1038       /* request must have been cancelled between the original request
1039        * and the response from core, ignore core's readiness */
1040       break;
1041     }
1042
1043     th = pr->pending_head;
1044     if (ntohs (smr->smr_id) != th->smr_id)
1045     {
1046       /* READY message is for expired or cancelled message,
1047        * ignore! (we should have already sent another request) */
1048       break;
1049     }
1050     if ((NULL != pr->prev) || (NULL != pr->next) || (h->ready_peer_head == pr))
1051     {
1052       /* we should not already be on the ready list... */
1053       GNUNET_break (0);
1054       reconnect_later (h);
1055       return;
1056     }
1057     GNUNET_CONTAINER_DLL_insert (h->ready_peer_head, h->ready_peer_tail, pr);
1058     trigger_next_request (h, GNUNET_NO);
1059     break;
1060   default:
1061     reconnect_later (h);
1062     return;
1063   }
1064   GNUNET_CLIENT_receive (h->client, &main_notify_handler, h,
1065                          GNUNET_TIME_UNIT_FOREVER_REL);
1066 }
1067
1068
1069 /**
1070  * Task executed once we are done transmitting the INIT message.
1071  * Starts our 'receive' loop.
1072  *
1073  * @param cls the 'struct GNUNET_CORE_Handle'
1074  * @param success were we successful
1075  */
1076 static void
1077 init_done_task (void *cls, int success)
1078 {
1079   struct GNUNET_CORE_Handle *h = cls;
1080
1081   if (GNUNET_SYSERR == success)
1082     return;                     /* shutdown */
1083   if (GNUNET_NO == success)
1084   {
1085     LOG (GNUNET_ERROR_TYPE_DEBUG,
1086          "Failed to exchange INIT with core, retrying\n");
1087     if (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK)
1088       reconnect_later (h);
1089     return;
1090   }
1091   GNUNET_CLIENT_receive (h->client, &main_notify_handler, h,
1092                          GNUNET_TIME_UNIT_FOREVER_REL);
1093 }
1094
1095
1096 /**
1097  * Our current client connection went down.  Clean it up
1098  * and try to reconnect!
1099  *
1100  * @param h our handle to the core service
1101  */
1102 static void
1103 reconnect (struct GNUNET_CORE_Handle *h)
1104 {
1105   struct ControlMessage *cm;
1106   struct InitMessage *init;
1107   uint32_t opt;
1108   uint16_t msize;
1109   uint16_t *ts;
1110   unsigned int hpos;
1111
1112   GNUNET_assert (NULL == h->client);
1113   GNUNET_assert (h->currently_down == GNUNET_YES);
1114   h->client = GNUNET_CLIENT_connect ("core", h->cfg);
1115   if (NULL == h->client)
1116   {
1117     reconnect_later (h);
1118     return;
1119   }
1120   msize = h->hcnt * sizeof (uint16_t) + sizeof (struct InitMessage);
1121   cm = GNUNET_malloc (sizeof (struct ControlMessage) + msize);
1122   cm->cont = &init_done_task;
1123   cm->cont_cls = h;
1124   init = (struct InitMessage *) &cm[1];
1125   init->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT);
1126   init->header.size = htons (msize);
1127   opt = 0;
1128   if (h->inbound_notify != NULL)
1129   {
1130     if (h->inbound_hdr_only)
1131       opt |= GNUNET_CORE_OPTION_SEND_HDR_INBOUND;
1132     else
1133       opt |= GNUNET_CORE_OPTION_SEND_FULL_INBOUND;
1134   }
1135   if (h->outbound_notify != NULL)
1136   {
1137     if (h->outbound_hdr_only)
1138       opt |= GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND;
1139     else
1140       opt |= GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND;
1141   }
1142   LOG (GNUNET_ERROR_TYPE_INFO, 
1143        "(Re)connecting to CORE service, monitoring messages of type %u\n",
1144        opt);
1145
1146   init->options = htonl (opt);
1147   ts = (uint16_t *) & init[1];
1148   for (hpos = 0; hpos < h->hcnt; hpos++)
1149     ts[hpos] = htons (h->handlers[hpos].type);
1150   GNUNET_CONTAINER_DLL_insert (h->control_pending_head, h->control_pending_tail,
1151                                cm);
1152   trigger_next_request (h, GNUNET_YES);
1153 }
1154
1155
1156
1157 /**
1158  * Connect to the core service.  Note that the connection may
1159  * complete (or fail) asynchronously.
1160  *
1161  * @param cfg configuration to use
1162  * @param queue_size size of the per-peer message queue
1163  * @param cls closure for the various callbacks that follow (including handlers in the handlers array)
1164  * @param init callback to call once we have successfully
1165  *        connected to the core service
1166  * @param connects function to call on peer connect, can be NULL
1167  * @param disconnects function to call on peer disconnect / timeout, can be NULL
1168  * @param inbound_notify function to call for all inbound messages, can be NULL
1169  * @param inbound_hdr_only set to GNUNET_YES if inbound_notify will only read the
1170  *                GNUNET_MessageHeader and hence we do not need to give it the full message;
1171  *                can be used to improve efficiency, ignored if inbound_notify is NULLL
1172  * @param outbound_notify function to call for all outbound messages, can be NULL
1173  * @param outbound_hdr_only set to GNUNET_YES if outbound_notify will only read the
1174  *                GNUNET_MessageHeader and hence we do not need to give it the full message
1175  *                can be used to improve efficiency, ignored if outbound_notify is NULLL
1176  * @param handlers callbacks for messages we care about, NULL-terminated
1177  * @return handle to the core service (only useful for disconnect until 'init' is called);
1178  *                NULL on error (in this case, init is never called)
1179  */
1180 struct GNUNET_CORE_Handle *
1181 GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1182                      unsigned int queue_size, void *cls,
1183                      GNUNET_CORE_StartupCallback init,
1184                      GNUNET_CORE_ConnectEventHandler connects,
1185                      GNUNET_CORE_DisconnectEventHandler disconnects,
1186                      GNUNET_CORE_MessageCallback inbound_notify,
1187                      int inbound_hdr_only,
1188                      GNUNET_CORE_MessageCallback outbound_notify,
1189                      int outbound_hdr_only,
1190                      const struct GNUNET_CORE_MessageHandler *handlers)
1191 {
1192   struct GNUNET_CORE_Handle *h;
1193
1194   h = GNUNET_malloc (sizeof (struct GNUNET_CORE_Handle));
1195   h->cfg = cfg;
1196   h->queue_size = queue_size;
1197   h->cls = cls;
1198   h->init = init;
1199   h->connects = connects;
1200   h->disconnects = disconnects;
1201   h->inbound_notify = inbound_notify;
1202   h->outbound_notify = outbound_notify;
1203   h->inbound_hdr_only = inbound_hdr_only;
1204   h->outbound_hdr_only = outbound_hdr_only;
1205   h->handlers = handlers;
1206   h->hcnt = 0;
1207   h->currently_down = GNUNET_YES;
1208   h->peers = GNUNET_CONTAINER_multihashmap_create (128);
1209   h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1210   if (NULL != handlers)
1211     while (handlers[h->hcnt].callback != NULL)
1212       h->hcnt++;
1213   GNUNET_assert (h->hcnt <
1214                  (GNUNET_SERVER_MAX_MESSAGE_SIZE -
1215                   sizeof (struct InitMessage)) / sizeof (uint16_t));
1216   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connecting to CORE service\n");
1217   reconnect (h);
1218   return h;
1219 }
1220
1221
1222 /**
1223  * Disconnect from the core service.  This function can only
1224  * be called *after* all pending 'GNUNET_CORE_notify_transmit_ready'
1225  * requests have been explicitly canceled.
1226  *
1227  * @param handle connection to core to disconnect
1228  */
1229 void
1230 GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle)
1231 {
1232   struct ControlMessage *cm;
1233
1234   LOG (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from CORE service\n");
1235   if (NULL != handle->cth)
1236   {
1237     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->cth);
1238     handle->cth = NULL;
1239   }
1240   while (NULL != (cm = handle->control_pending_head))
1241   {
1242     GNUNET_CONTAINER_DLL_remove (handle->control_pending_head,
1243                                  handle->control_pending_tail, cm);
1244     if (NULL != cm->th)
1245       cm->th->cm = NULL;
1246     if (NULL != cm->cont)
1247       cm->cont (cm->cont_cls, GNUNET_SYSERR);
1248     GNUNET_free (cm);
1249   }
1250   if (NULL != handle->client)
1251   {
1252     GNUNET_CLIENT_disconnect (handle->client);
1253     handle->client = NULL;
1254   }
1255   GNUNET_CONTAINER_multihashmap_iterate (handle->peers,
1256                                          &disconnect_and_free_peer_entry,
1257                                          handle);
1258   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1259   {
1260     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1261     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1262   }
1263   GNUNET_CONTAINER_multihashmap_destroy (handle->peers);
1264   handle->peers = NULL;
1265   GNUNET_break (handle->ready_peer_head == NULL);
1266   GNUNET_free (handle);
1267 }
1268
1269
1270 /**
1271  * Task that calls 'request_next_transmission'.
1272  *
1273  * @param cls the 'struct PeerRecord*'
1274  * @param tc scheduler context
1275  */
1276 static void
1277 run_request_next_transmission (void *cls,
1278                                const struct GNUNET_SCHEDULER_TaskContext *tc)
1279 {
1280   struct PeerRecord *pr = cls;
1281
1282   pr->ntr_task = GNUNET_SCHEDULER_NO_TASK;
1283   request_next_transmission (pr);
1284 }
1285
1286
1287 /**
1288  * Ask the core to call "notify" once it is ready to transmit the
1289  * given number of bytes to the specified "target".    Must only be
1290  * called after a connection to the respective peer has been
1291  * established (and the client has been informed about this).
1292  *
1293  * @param handle connection to core service
1294  * @param cork is corking allowed for this transmission?
1295  * @param priority how important is the message?
1296  * @param maxdelay how long can the message wait?
1297  * @param target who should receive the message, never NULL (can be this peer's identity for loopback)
1298  * @param notify_size how many bytes of buffer space does notify want?
1299  * @param notify function to call when buffer space is available
1300  * @param notify_cls closure for notify
1301  * @return non-NULL if the notify callback was queued,
1302  *         NULL if we can not even queue the request (insufficient
1303  *         memory); if NULL is returned, "notify" will NOT be called.
1304  */
1305 struct GNUNET_CORE_TransmitHandle *
1306 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle, int cork,
1307                                    uint32_t priority,
1308                                    struct GNUNET_TIME_Relative maxdelay,
1309                                    const struct GNUNET_PeerIdentity *target,
1310                                    size_t notify_size,
1311                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1312                                    void *notify_cls)
1313 {
1314   struct PeerRecord *pr;
1315   struct GNUNET_CORE_TransmitHandle *th;
1316   struct GNUNET_CORE_TransmitHandle *pos;
1317   struct GNUNET_CORE_TransmitHandle *prev;
1318   struct GNUNET_CORE_TransmitHandle *minp;
1319
1320   pr = GNUNET_CONTAINER_multihashmap_get (handle->peers, &target->hashPubKey);
1321   if (NULL == pr)
1322   {
1323     /* attempt to send to peer that is not connected */
1324     LOG (GNUNET_ERROR_TYPE_WARNING,
1325          "Attempting to send to peer `%s' from peer `%s', but not connected!\n",
1326          GNUNET_i2s (target), GNUNET_h2s (&handle->me.hashPubKey));
1327     GNUNET_break (0);
1328     return NULL;
1329   }
1330   GNUNET_assert (notify_size + sizeof (struct SendMessage) <
1331                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
1332   th = GNUNET_malloc (sizeof (struct GNUNET_CORE_TransmitHandle));
1333   th->peer = pr;
1334   GNUNET_assert (NULL != notify);
1335   th->get_message = notify;
1336   th->get_message_cls = notify_cls;
1337   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1338   th->priority = priority;
1339   th->msize = notify_size;
1340   th->cork = cork;
1341   /* bound queue size */
1342   if (pr->queue_size == handle->queue_size)
1343   {
1344     /* find lowest-priority entry, but skip the head of the list */
1345     minp = pr->pending_head->next;
1346     prev = minp;
1347     while (prev != NULL)
1348     {
1349       if (prev->priority < minp->priority)
1350         minp = prev;
1351       prev = prev->next;
1352     }
1353     if (minp == NULL)
1354     {
1355       GNUNET_break (handle->queue_size != 0);
1356       GNUNET_break (pr->queue_size == 1);
1357       GNUNET_free (th);
1358       LOG (GNUNET_ERROR_TYPE_DEBUG,
1359            "Dropping transmission request: cannot drop queue head and limit is one\n");
1360       return NULL;
1361     }
1362     if (priority <= minp->priority)
1363     {
1364       LOG (GNUNET_ERROR_TYPE_DEBUG,
1365            "Dropping transmission request: priority too low\n");
1366       GNUNET_free (th);
1367       return NULL;              /* priority too low */
1368     }
1369     GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, minp);
1370     pr->queue_size--;
1371     GNUNET_assert (0 == minp->get_message (minp->get_message_cls, 0, NULL));
1372     GNUNET_free (minp);
1373   }
1374
1375   /* Order entries by deadline, but SKIP 'HEAD' (as we may have transmitted
1376    * that request already or might even already be approved to transmit that
1377    * message to core) */
1378   pos = pr->pending_head;
1379   if (pos != NULL)
1380     pos = pos->next;            /* skip head */
1381
1382   /* insertion sort */
1383   prev = pos;
1384   while ((NULL != pos) && (pos->timeout.abs_value < th->timeout.abs_value))
1385   {
1386     prev = pos;
1387     pos = pos->next;
1388   }
1389   GNUNET_CONTAINER_DLL_insert_after (pr->pending_head, pr->pending_tail, prev,
1390                                      th);
1391   pr->queue_size++;
1392   /* was the request queue previously empty? */
1393   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmission request added to queue\n");
1394   if ((pr->pending_head == th) && (pr->ntr_task == GNUNET_SCHEDULER_NO_TASK) &&
1395       (pr->next == NULL) && (pr->prev == NULL) &&
1396       (handle->ready_peer_head != pr))
1397     pr->ntr_task =
1398         GNUNET_SCHEDULER_add_now (&run_request_next_transmission, pr);
1399   return th;
1400 }
1401
1402
1403 /**
1404  * Cancel the specified transmission-ready notification.
1405  *
1406  * @param th handle that was returned by "notify_transmit_ready".
1407  */
1408 void
1409 GNUNET_CORE_notify_transmit_ready_cancel (struct GNUNET_CORE_TransmitHandle *th)
1410 {
1411   struct PeerRecord *pr = th->peer;
1412   struct GNUNET_CORE_Handle *h = pr->ch;
1413   int was_head;
1414
1415   was_head = (pr->pending_head == th);
1416   GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, th);
1417   pr->queue_size--;
1418   if (NULL != th->cm)
1419   {
1420     /* we're currently in the control queue, remove */
1421     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
1422                                  h->control_pending_tail, th->cm);
1423     GNUNET_free (th->cm);
1424   }
1425   GNUNET_free (th);
1426   if (was_head)
1427   {
1428     if ((NULL != pr->prev) || (NULL != pr->next) || (pr == h->ready_peer_head))
1429     {
1430       /* the request that was 'approved' by core was
1431        * canceled before it could be transmitted; remove
1432        * us from the 'ready' list */
1433       GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
1434     }
1435     request_next_transmission (pr);
1436   }
1437 }
1438
1439
1440 /* end of core_api.c */