eeabebdf760b050492b49cf6a957f7a4bffbe580
[oweals/gnunet.git] / src / util / connection.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009-2013 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 util/connection.c
23  * @brief  TCP connection management
24  * @author Christian Grothoff
25  *
26  * This code is rather complex.  Only modify it if you
27  * 1) Have a NEW testcase showing that the new code
28  *    is needed and correct
29  * 2) All EXISTING testcases pass with the new code
30  * These rules should apply in general, but for this
31  * module they are VERY, VERY important.
32  */
33 #include "platform.h"
34 #include "gnunet_util_lib.h"
35 #include "gnunet_resolver_service.h"
36
37
38 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
39
40 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
41
42
43 /**
44  * Transmission handle.  There can only be one for each connection.
45  */
46 struct GNUNET_CONNECTION_TransmitHandle
47 {
48
49   /**
50    * Function to call if the send buffer has notify_size
51    * bytes available.
52    */
53   GNUNET_CONNECTION_TransmitReadyNotify notify_ready;
54
55   /**
56    * Closure for notify_ready.
57    */
58   void *notify_ready_cls;
59
60   /**
61    * Our connection handle.
62    */
63   struct GNUNET_CONNECTION_Handle *connection;
64
65   /**
66    * Timeout for receiving (in absolute time).
67    */
68   struct GNUNET_TIME_Absolute transmit_timeout;
69
70   /**
71    * Task called on timeout.
72    */
73   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
74
75   /**
76    * At what number of bytes available in the
77    * write buffer should the notify method be called?
78    */
79   size_t notify_size;
80
81 };
82
83
84 /**
85  * During connect, we try multiple possible IP addresses
86  * to find out which one might work.
87  */
88 struct AddressProbe
89 {
90
91   /**
92    * This is a linked list.
93    */
94   struct AddressProbe *next;
95
96   /**
97    * This is a doubly-linked list.
98    */
99   struct AddressProbe *prev;
100
101   /**
102    * The address; do not free (allocated at the end of this struct).
103    */
104   const struct sockaddr *addr;
105
106   /**
107    * Underlying OS's socket.
108    */
109   struct GNUNET_NETWORK_Handle *sock;
110
111   /**
112    * Connection for which we are probing.
113    */
114   struct GNUNET_CONNECTION_Handle *connection;
115
116   /**
117    * Lenth of addr.
118    */
119   socklen_t addrlen;
120
121   /**
122    * Task waiting for the connection to finish connecting.
123    */
124   GNUNET_SCHEDULER_TaskIdentifier task;
125 };
126
127
128 /**
129  * @brief handle for a network connection
130  */
131 struct GNUNET_CONNECTION_Handle
132 {
133
134   /**
135    * Configuration to use.
136    */
137   const struct GNUNET_CONFIGURATION_Handle *cfg;
138
139   /**
140    * Linked list of sockets we are currently trying out
141    * (during connect).
142    */
143   struct AddressProbe *ap_head;
144
145   /**
146    * Linked list of sockets we are currently trying out
147    * (during connect).
148    */
149   struct AddressProbe *ap_tail;
150
151   /**
152    * Network address of the other end-point, may be NULL.
153    */
154   struct sockaddr *addr;
155
156   /**
157    * Pointer to the hostname if connection was
158    * created using DNS lookup, otherwise NULL.
159    */
160   char *hostname;
161
162   /**
163    * Underlying OS's socket, set to NULL after fatal errors.
164    */
165   struct GNUNET_NETWORK_Handle *sock;
166
167   /**
168    * Function to call on data received, NULL if no receive is pending.
169    */
170   GNUNET_CONNECTION_Receiver receiver;
171
172   /**
173    * Closure for receiver.
174    */
175   void *receiver_cls;
176
177   /**
178    * Pointer to our write buffer.
179    */
180   char *write_buffer;
181
182   /**
183    * Current size of our write buffer.
184    */
185   size_t write_buffer_size;
186
187   /**
188    * Current write-offset in write buffer (where
189    * would we write next).
190    */
191   size_t write_buffer_off;
192
193   /**
194    * Current read-offset in write buffer (how many
195    * bytes have already been sent).
196    */
197   size_t write_buffer_pos;
198
199   /**
200    * Length of addr.
201    */
202   socklen_t addrlen;
203
204   /**
205    * Read task that we may need to wait for.
206    */
207   GNUNET_SCHEDULER_TaskIdentifier read_task;
208
209   /**
210    * Write task that we may need to wait for.
211    */
212   GNUNET_SCHEDULER_TaskIdentifier write_task;
213
214   /**
215    * Handle to a pending DNS lookup request.
216    */
217   struct GNUNET_RESOLVER_RequestHandle *dns_active;
218
219   /**
220    * The handle we return for GNUNET_CONNECTION_notify_transmit_ready.
221    */
222   struct GNUNET_CONNECTION_TransmitHandle nth;
223
224   /**
225    * Timeout for receiving (in absolute time).
226    */
227   struct GNUNET_TIME_Absolute receive_timeout;
228
229   /**
230    * Maximum number of bytes to read (for receiving).
231    */
232   size_t max;
233
234   /**
235    * Port to connect to.
236    */
237   uint16_t port;
238
239   /**
240    * When shutdown, do not ever actually close the socket, but
241    * free resources.  Only should ever be set if using program
242    * termination as a signal (because only then will the leaked
243    * socket be freed!)
244    */
245   int8_t persist;
246
247   /**
248    * Usually 0.  Set to 1 if this handle is in used and should
249    * 'GNUNET_CONNECTION_destroy' be called right now, the action needs
250    * to be deferred by setting it to -1.
251    */
252   int8_t destroy_later;
253
254 };
255
256
257 /**
258  * Set the persist option on this connection handle.  Indicates
259  * that the underlying socket or fd should never really be closed.
260  * Used for indicating process death.
261  *
262  * @param connection the connection to set persistent
263  */
264 void
265 GNUNET_CONNECTION_persist_ (struct GNUNET_CONNECTION_Handle *connection)
266 {
267   connection->persist = GNUNET_YES;
268 }
269
270
271 /**
272  * Disable the "CORK" feature for communication with the given connection,
273  * forcing the OS to immediately flush the buffer on transmission
274  * instead of potentially buffering multiple messages.  Essentially
275  * reduces the OS send buffers to zero.
276  * Used to make sure that the last messages sent through the connection
277  * reach the other side before the process is terminated.
278  *
279  * @param connection the connection to make flushing and blocking
280  * @return GNUNET_OK on success
281  */
282 int
283 GNUNET_CONNECTION_disable_corking (struct GNUNET_CONNECTION_Handle *connection)
284 {
285   return GNUNET_NETWORK_socket_disable_corking (connection->sock);
286 }
287
288
289 /**
290  * Create a connection handle by boxing an existing OS socket.  The OS
291  * socket should henceforth be no longer used directly.
292  * GNUNET_connection_destroy will close it.
293  *
294  * @param osSocket existing socket to box
295  * @return the boxed connection handle
296  */
297 struct GNUNET_CONNECTION_Handle *
298 GNUNET_CONNECTION_create_from_existing (struct GNUNET_NETWORK_Handle *osSocket)
299 {
300   struct GNUNET_CONNECTION_Handle *connection;
301
302   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
303   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
304   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
305   connection->sock = osSocket;
306   return connection;
307 }
308
309
310 /**
311  * Create a connection handle by accepting on a listen socket.  This
312  * function may block if the listen socket has no connection ready.
313  *
314  * @param access function to use to check if access is allowed
315  * @param access_cls closure for access
316  * @param lsock listen socket
317  * @return the connection handle, NULL on error
318  */
319 struct GNUNET_CONNECTION_Handle *
320 GNUNET_CONNECTION_create_from_accept (GNUNET_CONNECTION_AccessCheck access,
321                                       void *access_cls,
322                                       struct GNUNET_NETWORK_Handle *lsock)
323 {
324   struct GNUNET_CONNECTION_Handle *connection;
325   char addr[128];
326   socklen_t addrlen;
327   struct GNUNET_NETWORK_Handle *sock;
328   int aret;
329   struct sockaddr_in *v4;
330   struct sockaddr_in6 *v6;
331   struct sockaddr *sa;
332   void *uaddr;
333   struct GNUNET_CONNECTION_Credentials *gcp;
334   struct GNUNET_CONNECTION_Credentials gc;
335 #ifdef SO_PEERCRED
336   struct ucred uc;
337   socklen_t olen;
338 #endif
339
340   addrlen = sizeof (addr);
341   sock =
342       GNUNET_NETWORK_socket_accept (lsock, (struct sockaddr *) &addr, &addrlen);
343   if (NULL == sock)
344   {
345     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "accept");
346     return NULL;
347   }
348   if ((addrlen > sizeof (addr)) || (addrlen < sizeof (sa_family_t)))
349   {
350     GNUNET_break (0);
351     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
352     return NULL;
353   }
354
355   sa = (struct sockaddr *) addr;
356   v6 = (struct sockaddr_in6 *) addr;
357   if ((AF_INET6 == sa->sa_family) && (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)))
358   {
359     /* convert to V4 address */
360     v4 = GNUNET_new (struct sockaddr_in);
361     memset (v4, 0, sizeof (struct sockaddr_in));
362     v4->sin_family = AF_INET;
363 #if HAVE_SOCKADDR_IN_SIN_LEN
364     v4->sin_len = (u_char) sizeof (struct sockaddr_in);
365 #endif
366     memcpy (&v4->sin_addr,
367             &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
368                                        sizeof (struct in_addr)],
369             sizeof (struct in_addr));
370     v4->sin_port = v6->sin6_port;
371     uaddr = v4;
372     addrlen = sizeof (struct sockaddr_in);
373   }
374   else
375   {
376     uaddr = GNUNET_malloc (addrlen);
377     memcpy (uaddr, addr, addrlen);
378   }
379   gcp = NULL;
380   gc.uid = 0;
381   gc.gid = 0;
382   if (AF_UNIX == sa->sa_family)
383   {
384 #if HAVE_GETPEEREID
385     /* most BSDs */
386     if (0 == getpeereid (GNUNET_NETWORK_get_fd (sock), &gc.uid, &gc.gid))
387       gcp = &gc;
388 #else
389 #ifdef SO_PEERCRED
390     /* largely traditional GNU/Linux */
391     olen = sizeof (uc);
392     if ((0 ==
393          getsockopt (GNUNET_NETWORK_get_fd (sock), SOL_SOCKET, SO_PEERCRED, &uc,
394                      &olen)) && (olen == sizeof (uc)))
395     {
396       gc.uid = uc.uid;
397       gc.gid = uc.gid;
398       gcp = &gc;
399     }
400 #else
401 #if HAVE_GETPEERUCRED
402     /* this is for Solaris 10 */
403     ucred_t *uc;
404
405     uc = NULL;
406     if (0 == getpeerucred (GNUNET_NETWORK_get_fd (sock), &uc))
407     {
408       gc.uid = ucred_geteuid (uc);
409       gc.gid = ucred_getegid (uc);
410       gcp = &gc;
411     }
412     ucred_free (uc);
413 #endif
414 #endif
415 #endif
416   }
417
418   if ((NULL != access) &&
419       (GNUNET_YES != (aret = access (access_cls, gcp, uaddr, addrlen))))
420   {
421     if (GNUNET_NO == aret)
422       LOG (GNUNET_ERROR_TYPE_INFO, _("Access denied to `%s'\n"),
423            GNUNET_a2s (uaddr, addrlen));
424     GNUNET_break (GNUNET_OK ==
425                   GNUNET_NETWORK_socket_shutdown (sock, SHUT_RDWR));
426     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
427     GNUNET_free (uaddr);
428     return NULL;
429   }
430   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
431   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
432   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
433   connection->addr = uaddr;
434   connection->addrlen = addrlen;
435   connection->sock = sock;
436   LOG (GNUNET_ERROR_TYPE_INFO,
437        _("Accepting connection from `%s': %p\n"),
438        GNUNET_a2s (uaddr, addrlen), connection);
439   return connection;
440 }
441
442
443 /**
444  * Obtain the network address of the other party.
445  *
446  * @param connection the client to get the address for
447  * @param addr where to store the address
448  * @param addrlen where to store the length of the address
449  * @return GNUNET_OK on success
450  */
451 int
452 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
453                                void **addr, size_t * addrlen)
454 {
455   if ((NULL == connection->addr) || (0 == connection->addrlen))
456     return GNUNET_NO;
457   *addr = GNUNET_malloc (connection->addrlen);
458   memcpy (*addr, connection->addr, connection->addrlen);
459   *addrlen = connection->addrlen;
460   return GNUNET_OK;
461 }
462
463
464 /**
465  * Tell the receiver callback that we had an IO error.
466  *
467  * @param connection connection to signal error
468  * @param errcode error code to send
469  */
470 static void
471 signal_receive_error (struct GNUNET_CONNECTION_Handle *connection, int errcode)
472 {
473   GNUNET_CONNECTION_Receiver receiver;
474
475   LOG (GNUNET_ERROR_TYPE_DEBUG,
476        "Receive encounters error (%s), connection closed (%p)\n",
477        STRERROR (errcode),
478        connection);
479   GNUNET_assert (NULL != (receiver = connection->receiver));
480   connection->receiver = NULL;
481   receiver (connection->receiver_cls, NULL, 0, connection->addr, connection->addrlen, errcode);
482 }
483
484
485 /**
486  * Tell the receiver callback that a timeout was reached.
487  *
488  * @param connection connection to signal for
489  */
490 static void
491 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
492 {
493   GNUNET_CONNECTION_Receiver receiver;
494
495   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection signals timeout to receiver (%p)!\n",
496        connection);
497   GNUNET_assert (NULL != (receiver = connection->receiver));
498   connection->receiver = NULL;
499   receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
500 }
501
502
503 /**
504  * We failed to transmit data to the service, signal the error.
505  *
506  * @param connection handle that had trouble
507  * @param ecode error code (errno)
508  */
509 static void
510 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
511                        int ecode)
512 {
513   GNUNET_CONNECTION_TransmitReadyNotify notify;
514
515   LOG (GNUNET_ERROR_TYPE_DEBUG,
516        "Transmission encounterd error (%s), connection closed (%p)\n",
517        STRERROR (ecode),
518        connection);
519   if (NULL != connection->sock)
520   {
521     GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR);
522     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
523     connection->sock = NULL;
524     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
525   }
526   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
527   {
528     /* send errors trigger read errors... */
529     GNUNET_SCHEDULER_cancel (connection->read_task);
530     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
531     signal_receive_timeout (connection);
532     return;
533   }
534   if (NULL == connection->nth.notify_ready)
535     return;                     /* nobody to tell about it */
536   notify = connection->nth.notify_ready;
537   connection->nth.notify_ready = NULL;
538   notify (connection->nth.notify_ready_cls, 0, NULL);
539 }
540
541
542 /**
543  * We've failed for good to establish a connection (timeout or
544  * no more addresses to try).
545  *
546  * @param connection the connection we tried to establish
547  */
548 static void
549 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
550 {
551   LOG (GNUNET_ERROR_TYPE_INFO,
552        _("Failed to establish TCP connection to `%s:%u', no further addresses to try.\n"),
553        connection->hostname, connection->port);
554   GNUNET_break (NULL == connection->ap_head);
555   GNUNET_break (NULL == connection->ap_tail);
556   GNUNET_break (GNUNET_NO == connection->dns_active);
557   GNUNET_break (NULL == connection->sock);
558   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
559
560   /* signal errors for jobs that used to wait on the connection */
561   connection->destroy_later = 1;
562   if (NULL != connection->receiver)
563     signal_receive_error (connection, ECONNREFUSED);
564   if (NULL != connection->nth.notify_ready)
565   {
566     GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
567     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
568     connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
569     signal_transmit_error (connection, ECONNREFUSED);
570   }
571   if (-1 == connection->destroy_later)
572   {
573     /* do it now */
574     connection->destroy_later = 0;
575     GNUNET_CONNECTION_destroy (connection);
576     return;
577   }
578   connection->destroy_later = 0;
579 }
580
581
582 /**
583  * We are ready to transmit (or got a timeout).
584  *
585  * @param cls our connection handle
586  * @param tc task context describing why we are here
587  */
588 static void
589 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
590
591
592 /**
593  * This function is called once we either timeout or have data ready
594  * to read.
595  *
596  * @param cls connection to read from
597  * @param tc scheduler context
598  */
599 static void
600 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
601
602
603 /**
604  * We've succeeded in establishing a connection.
605  *
606  * @param connection the connection we tried to establish
607  */
608 static void
609 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
610 {
611   LOG (GNUNET_ERROR_TYPE_DEBUG,
612        "Connection to `%s' succeeded! (%p)\n",
613        GNUNET_a2s (connection->addr, connection->addrlen), connection);
614   /* trigger jobs that waited for the connection */
615   if (NULL != connection->receiver)
616   {
617     LOG (GNUNET_ERROR_TYPE_DEBUG,
618          "Connection succeeded, starting with receiving data (%p)\n",
619          connection);
620     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->read_task);
621     connection->read_task =
622       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
623                                      (connection->receive_timeout), connection->sock,
624                                      &receive_ready, connection);
625   }
626   if (NULL != connection->nth.notify_ready)
627   {
628     LOG (GNUNET_ERROR_TYPE_DEBUG,
629          "Connection succeeded, starting with sending data (%p)\n",
630          connection);
631     GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
632     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
633     connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
634     GNUNET_assert (connection->write_task == GNUNET_SCHEDULER_NO_TASK);
635     connection->write_task =
636         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
637                                         (connection->nth.transmit_timeout), connection->sock,
638                                         &transmit_ready, connection);
639   }
640 }
641
642
643 /**
644  * Scheduler let us know that we're either ready to write on the
645  * socket OR connect timed out.  Do the right thing.
646  *
647  * @param cls the "struct AddressProbe*" with the address that we are probing
648  * @param tc success or failure info about the connect attempt.
649  */
650 static void
651 connect_probe_continuation (void *cls,
652                             const struct GNUNET_SCHEDULER_TaskContext *tc)
653 {
654   struct AddressProbe *ap = cls;
655   struct GNUNET_CONNECTION_Handle *connection = ap->connection;
656   struct AddressProbe *pos;
657   int error;
658   socklen_t len;
659
660   GNUNET_assert (NULL != ap->sock);
661   GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, ap);
662   len = sizeof (error);
663   errno = 0;
664   error = 0;
665   if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
666       (GNUNET_OK !=
667        GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR, &error,
668                                          &len)) || (0 != error))
669   {
670     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
671     GNUNET_free (ap);
672     if ((NULL == connection->ap_head) && (GNUNET_NO == connection->dns_active))
673       connect_fail_continuation (connection);
674     return;
675   }
676   GNUNET_assert (NULL == connection->sock);
677   connection->sock = ap->sock;
678   GNUNET_assert (NULL == connection->addr);
679   connection->addr = GNUNET_malloc (ap->addrlen);
680   memcpy (connection->addr, ap->addr, ap->addrlen);
681   connection->addrlen = ap->addrlen;
682   GNUNET_free (ap);
683   /* cancel all other attempts */
684   while (NULL != (pos = connection->ap_head))
685   {
686     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
687     GNUNET_SCHEDULER_cancel (pos->task);
688     GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
689     GNUNET_free (pos);
690   }
691   connect_success_continuation (connection);
692 }
693
694
695 /**
696  * Try to establish a connection given the specified address.
697  * This function is called by the resolver once we have a DNS reply.
698  *
699  * @param cls our "struct GNUNET_CONNECTION_Handle *"
700  * @param addr address to try, NULL for "last call"
701  * @param addrlen length of addr
702  */
703 static void
704 try_connect_using_address (void *cls, const struct sockaddr *addr,
705                            socklen_t addrlen)
706 {
707   struct GNUNET_CONNECTION_Handle *connection = cls;
708   struct AddressProbe *ap;
709   struct GNUNET_TIME_Relative delay;
710
711   if (NULL == addr)
712   {
713     connection->dns_active = NULL;
714     if ((NULL == connection->ap_head) && (NULL == connection->sock))
715       connect_fail_continuation (connection);
716     return;
717   }
718   if (NULL != connection->sock)
719     return;                     /* already connected */
720   GNUNET_assert (NULL == connection->addr);
721   /* try to connect */
722   LOG (GNUNET_ERROR_TYPE_DEBUG,
723        "Trying to connect using address `%s:%u/%s:%u'\n", connection->hostname, connection->port,
724        GNUNET_a2s (addr, addrlen), connection->port);
725   ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
726   ap->addr = (const struct sockaddr *) &ap[1];
727   memcpy (&ap[1], addr, addrlen);
728   ap->addrlen = addrlen;
729   ap->connection = connection;
730
731   switch (ap->addr->sa_family)
732   {
733   case AF_INET:
734     ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
735     break;
736   case AF_INET6:
737     ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
738     break;
739   default:
740     GNUNET_break (0);
741     GNUNET_free (ap);
742     return;                     /* not supported by us */
743   }
744   ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
745   if (NULL == ap->sock)
746   {
747     GNUNET_free (ap);
748     return;                     /* not supported by OS */
749   }
750   LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
751        GNUNET_a2s (ap->addr, ap->addrlen), connection);
752   if ((GNUNET_OK !=
753        GNUNET_NETWORK_socket_connect (ap->sock, ap->addr, ap->addrlen)) &&
754       (EINPROGRESS != errno))
755   {
756     /* maybe refused / unsupported address, try next */
757     LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
758     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
759     GNUNET_free (ap);
760     return;
761   }
762   GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
763   delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
764   if (NULL != connection->nth.notify_ready)
765     delay =
766         GNUNET_TIME_relative_min (delay,
767                                   GNUNET_TIME_absolute_get_remaining (connection->
768                                                                       nth.transmit_timeout));
769   if (NULL != connection->receiver)
770     delay =
771         GNUNET_TIME_relative_min (delay,
772                                   GNUNET_TIME_absolute_get_remaining
773                                   (connection->receive_timeout));
774   ap->task =
775       GNUNET_SCHEDULER_add_write_net (delay, ap->sock,
776                                       &connect_probe_continuation, ap);
777 }
778
779
780 /**
781  * Create a connection handle by (asynchronously) connecting to a host.
782  * This function returns immediately, even if the connection has not
783  * yet been established.  This function only creates TCP connections.
784  *
785  * @param cfg configuration to use
786  * @param hostname name of the host to connect to
787  * @param port port to connect to
788  * @return the connection handle
789  */
790 struct GNUNET_CONNECTION_Handle *
791 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle
792                                        *cfg, const char *hostname,
793                                        uint16_t port)
794 {
795   struct GNUNET_CONNECTION_Handle *connection;
796
797   GNUNET_assert (0 < strlen (hostname));        /* sanity check */
798   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
799   connection->cfg = cfg;
800   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
801   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
802   connection->port = port;
803   connection->hostname = GNUNET_strdup (hostname);
804   connection->dns_active =
805       GNUNET_RESOLVER_ip_get (connection->hostname, AF_UNSPEC,
806                               GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
807                               &try_connect_using_address, connection);
808   return connection;
809 }
810
811
812 /**
813  * Create a connection handle by connecting to a UNIX domain service.
814  * This function returns immediately, even if the connection has not
815  * yet been established.  This function only creates UNIX connections.
816  *
817  * @param cfg configuration to use
818  * @param unixpath path to connect to
819  * @return the connection handle, NULL on systems without UNIX support
820  */
821 struct GNUNET_CONNECTION_Handle *
822 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct
823                                                    GNUNET_CONFIGURATION_Handle
824                                                    *cfg, const char *unixpath)
825 {
826 #ifdef AF_UNIX
827   struct GNUNET_CONNECTION_Handle *connection;
828   struct sockaddr_un *un;
829
830   GNUNET_assert (0 < strlen (unixpath));        /* sanity check */
831   un = GNUNET_new (struct sockaddr_un);
832   un->sun_family = AF_UNIX;
833   strncpy(un->sun_path, unixpath, sizeof(un->sun_path) - 1);
834 #if HAVE_SOCKADDR_IN_SIN_LEN
835   un->sun_len = (u_char) sizeof (struct sockaddr_un);
836 #endif
837   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
838   connection->cfg = cfg;
839   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
840   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
841   connection->port = 0;
842   connection->hostname = NULL;
843   connection->addr = (struct sockaddr *) un;
844   connection->addrlen = sizeof (struct sockaddr_un);
845   connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
846   if (NULL == connection->sock)
847   {
848     GNUNET_free (connection->addr);
849     GNUNET_free (connection->write_buffer);
850     GNUNET_free (connection);
851     return NULL;
852   }
853   if ( (GNUNET_OK !=
854         GNUNET_NETWORK_socket_connect (connection->sock, connection->addr, connection->addrlen)) &&
855        (EINPROGRESS != errno) )
856   {
857     /* Just return; we expect everything to work eventually so don't fail HARD */
858     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
859     connection->sock = NULL;
860     return connection;
861   }
862   connect_success_continuation (connection);
863   return connection;
864 #else
865   return NULL;
866 #endif
867 }
868
869
870 /**
871  * Create a connection handle by (asynchronously) connecting to a host.
872  * This function returns immediately, even if the connection has not
873  * yet been established.  This function only creates TCP connections.
874  *
875  * @param af_family address family to use
876  * @param serv_addr server address
877  * @param addrlen length of server address
878  * @return the connection handle
879  */
880 struct GNUNET_CONNECTION_Handle *
881 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
882                                         const struct sockaddr *serv_addr,
883                                         socklen_t addrlen)
884 {
885   struct GNUNET_NETWORK_Handle *s;
886   struct GNUNET_CONNECTION_Handle *connection;
887
888   s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
889   if (NULL == s)
890   {
891     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
892     return NULL;
893   }
894   if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
895       (EINPROGRESS != errno))
896   {
897     /* maybe refused / unsupported address, try next */
898     LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
899     LOG (GNUNET_ERROR_TYPE_INFO, _("Attempt to connect to `%s' failed\n"),
900          GNUNET_a2s (serv_addr, addrlen));
901     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
902     return NULL;
903   }
904   connection = GNUNET_CONNECTION_create_from_existing (s);
905   connection->addr = GNUNET_malloc (addrlen);
906   memcpy (connection->addr, serv_addr, addrlen);
907   connection->addrlen = addrlen;
908   LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
909        GNUNET_a2s (serv_addr, addrlen), connection);
910   return connection;
911 }
912
913
914 /**
915  * Check if connection is valid (no fatal errors have happened so far).
916  * Note that a connection that is still trying to connect is considered
917  * valid.
918  *
919  * @param connection connection to check
920  * @return GNUNET_YES if valid, GNUNET_NO otherwise
921  */
922 int
923 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
924 {
925   if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
926     return GNUNET_YES;          /* still trying to connect */
927   return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
928 }
929
930
931 /**
932  * Close the connection and free associated resources.  There must
933  * not be any pending requests for reading or writing to the
934  * connection at this time.
935  *
936  * @param connection connection to destroy
937  */
938 void
939 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
940 {
941   struct AddressProbe *pos;
942
943   if (0 != connection->destroy_later)
944   {
945     connection->destroy_later = -1;
946     return;
947   }
948   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down connection (%p)\n", connection);
949   GNUNET_assert (NULL == connection->nth.notify_ready);
950   GNUNET_assert (NULL == connection->receiver);
951   if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
952   {
953     GNUNET_SCHEDULER_cancel (connection->write_task);
954     connection->write_task = GNUNET_SCHEDULER_NO_TASK;
955     connection->write_buffer_off = 0;
956   }
957   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
958   {
959     GNUNET_SCHEDULER_cancel (connection->read_task);
960     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
961   }
962   if (GNUNET_SCHEDULER_NO_TASK != connection->nth.timeout_task)
963   {
964     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
965     connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
966   }
967   connection->nth.notify_ready = NULL;
968   if (NULL != connection->dns_active)
969   {
970     GNUNET_RESOLVER_request_cancel (connection->dns_active);
971     connection->dns_active = NULL;
972   }
973   while (NULL != (pos = connection->ap_head))
974   {
975     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
976     GNUNET_SCHEDULER_cancel (pos->task);
977     GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
978     GNUNET_free (pos);
979   }
980   if ( (NULL != connection->sock) &&
981        (GNUNET_YES != connection->persist) )
982   {
983     if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR)) &&
984         (ENOTCONN != errno) &&
985         (ECONNRESET != errno) )
986       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "shutdown");
987   }
988   if (NULL != connection->sock)
989   {
990     if (GNUNET_YES != connection->persist)
991       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
992     else
993     {
994       GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
995                                                                    * leak the socket in this special case) ... */
996     }
997   }
998   GNUNET_free_non_null (connection->addr);
999   GNUNET_free_non_null (connection->hostname);
1000   GNUNET_free (connection->write_buffer);
1001   GNUNET_free (connection);
1002 }
1003
1004
1005 /**
1006  * This function is called once we either timeout
1007  * or have data ready to read.
1008  *
1009  * @param cls connection to read from
1010  * @param tc scheduler context
1011  */
1012 static void
1013 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1014 {
1015   struct GNUNET_CONNECTION_Handle *connection = cls;
1016   char buffer[connection->max];
1017   ssize_t ret;
1018   GNUNET_CONNECTION_Receiver receiver;
1019
1020   connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1021   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1022   {
1023     /* ignore shutdown request, go again immediately */
1024     connection->read_task =
1025         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1026                                        (connection->receive_timeout), connection->sock,
1027                                        &receive_ready, connection);
1028     return;
1029   }
1030   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1031   {
1032     LOG (GNUNET_ERROR_TYPE_DEBUG,
1033          "Receive from `%s' encounters error: timeout (%s, %p)\n",
1034          GNUNET_a2s (connection->addr, connection->addrlen),
1035          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout), GNUNET_YES),
1036          connection);
1037     signal_receive_timeout (connection);
1038     return;
1039   }
1040   if (NULL == connection->sock)
1041   {
1042     /* connect failed for good */
1043     signal_receive_error (connection, ECONNREFUSED);
1044     return;
1045   }
1046   GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1047 RETRY:
1048   ret = GNUNET_NETWORK_socket_recv (connection->sock, buffer, connection->max);
1049   if (-1 == ret)
1050   {
1051     if (EINTR == errno)
1052       goto RETRY;
1053     signal_receive_error (connection, errno);
1054     return;
1055   }
1056   LOG (GNUNET_ERROR_TYPE_DEBUG,
1057        "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1058        connection->max, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1059   GNUNET_assert (NULL != (receiver = connection->receiver));
1060   connection->receiver = NULL;
1061   receiver (connection->receiver_cls, buffer, ret, connection->addr, connection->addrlen, 0);
1062 }
1063
1064
1065 /**
1066  * Receive data from the given connection.  Note that this function will
1067  * call "receiver" asynchronously using the scheduler.  It will
1068  * "immediately" return.  Note that there MUST only be one active
1069  * receive call per connection at any given point in time (so do not
1070  * call receive again until the receiver callback has been invoked).
1071  *
1072  * @param connection connection handle
1073  * @param max maximum number of bytes to read
1074  * @param timeout maximum amount of time to wait
1075  * @param receiver function to call with received data
1076  * @param receiver_cls closure for receiver
1077  */
1078 void
1079 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection, size_t max,
1080                            struct GNUNET_TIME_Relative timeout,
1081                            GNUNET_CONNECTION_Receiver receiver,
1082                            void *receiver_cls)
1083 {
1084   GNUNET_assert ((GNUNET_SCHEDULER_NO_TASK == connection->read_task) &&
1085                  (NULL == connection->receiver));
1086   GNUNET_assert (NULL != receiver);
1087   connection->receiver = receiver;
1088   connection->receiver_cls = receiver_cls;
1089   connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1090   connection->max = max;
1091   if (NULL != connection->sock)
1092   {
1093     connection->read_task =
1094       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1095                                      (connection->receive_timeout), connection->sock,
1096                                      &receive_ready, connection);
1097     return;
1098   }
1099   if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1100   {
1101     connection->receiver = NULL;
1102     receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1103     return;
1104   }
1105 }
1106
1107
1108 /**
1109  * Cancel receive job on the given connection.  Note that the
1110  * receiver callback must not have been called yet in order
1111  * for the cancellation to be valid.
1112  *
1113  * @param connection connection handle
1114  * @return closure of the original receiver callback closure
1115  */
1116 void *
1117 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1118 {
1119   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
1120   {
1121     GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1122     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1123   }
1124   connection->receiver = NULL;
1125   return connection->receiver_cls;
1126 }
1127
1128
1129 /**
1130  * Try to call the transmit notify method (check if we do
1131  * have enough space available first)!
1132  *
1133  * @param connection connection for which we should do this processing
1134  * @return GNUNET_YES if we were able to call notify
1135  */
1136 static int
1137 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1138 {
1139   size_t used;
1140   size_t avail;
1141   size_t size;
1142   GNUNET_CONNECTION_TransmitReadyNotify notify;
1143
1144   LOG (GNUNET_ERROR_TYPE_DEBUG, "process_notify is running\n");
1145
1146   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1147   if (NULL == (notify = connection->nth.notify_ready))
1148   {
1149     LOG (GNUNET_ERROR_TYPE_DEBUG, "Noone to notify\n");
1150     return GNUNET_NO;
1151   }
1152   used = connection->write_buffer_off - connection->write_buffer_pos;
1153   avail = connection->write_buffer_size - used;
1154   size = connection->nth.notify_size;
1155   if (size > avail)
1156   {
1157     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not enough buffer\n");
1158     return GNUNET_NO;
1159   }
1160   connection->nth.notify_ready = NULL;
1161   if (connection->write_buffer_size - connection->write_buffer_off < size)
1162   {
1163     /* need to compact */
1164     memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1165              used);
1166     connection->write_buffer_off -= connection->write_buffer_pos;
1167     connection->write_buffer_pos = 0;
1168   }
1169   avail = connection->write_buffer_size - connection->write_buffer_off;
1170   GNUNET_assert (avail >= size);
1171   size =
1172       notify (connection->nth.notify_ready_cls, avail,
1173               &connection->write_buffer[connection->write_buffer_off]);
1174   GNUNET_assert (size <= avail);
1175   if (0 != size)
1176     connection->write_buffer_off += size;
1177   return GNUNET_YES;
1178 }
1179
1180
1181 /**
1182  * Task invoked by the scheduler when a call to transmit
1183  * is timing out (we never got enough buffer space to call
1184  * the callback function before the specified timeout
1185  * expired).
1186  *
1187  * This task notifies the client about the timeout.
1188  *
1189  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1190  * @param tc scheduler context
1191  */
1192 static void
1193 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1194 {
1195   struct GNUNET_CONNECTION_Handle *connection = cls;
1196   GNUNET_CONNECTION_TransmitReadyNotify notify;
1197
1198   connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1199   LOG (GNUNET_ERROR_TYPE_DEBUG,
1200        "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1201        connection->hostname,
1202        connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1203   notify = connection->nth.notify_ready;
1204   GNUNET_assert (NULL != notify);
1205   connection->nth.notify_ready = NULL;
1206   notify (connection->nth.notify_ready_cls, 0, NULL);
1207 }
1208
1209
1210 /**
1211  * Task invoked by the scheduler when we failed to connect
1212  * at the time of being asked to transmit.
1213  *
1214  * This task notifies the client about the error.
1215  *
1216  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1217  * @param tc scheduler context
1218  */
1219 static void
1220 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1221 {
1222   struct GNUNET_CONNECTION_Handle *connection = cls;
1223   GNUNET_CONNECTION_TransmitReadyNotify notify;
1224
1225   LOG (GNUNET_ERROR_TYPE_DEBUG,
1226        "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1227        connection->nth.notify_size, connection->hostname, connection->port, connection);
1228   connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1229   notify = connection->nth.notify_ready;
1230   connection->nth.notify_ready = NULL;
1231   notify (connection->nth.notify_ready_cls, 0, NULL);
1232 }
1233
1234
1235 /**
1236  * We are ready to transmit (or got a timeout).
1237  *
1238  * @param cls our connection handle
1239  * @param tc task context describing why we are here
1240  */
1241 static void
1242 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1243 {
1244   struct GNUNET_CONNECTION_Handle *connection = cls;
1245   GNUNET_CONNECTION_TransmitReadyNotify notify;
1246   ssize_t ret;
1247   size_t have;
1248
1249   LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", connection);
1250   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != connection->write_task);
1251   connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1252   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1253   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1254   {
1255     if (NULL != connection->sock)
1256       goto SCHEDULE_WRITE;      /* ignore shutdown, go again immediately */
1257     LOG (GNUNET_ERROR_TYPE_DEBUG,
1258          "Transmit to `%s' fails, shutdown happened (%p).\n",
1259          GNUNET_a2s (connection->addr, connection->addrlen), connection);
1260     notify = connection->nth.notify_ready;
1261     if (NULL != notify)
1262     {
1263       connection->nth.notify_ready = NULL;
1264       notify (connection->nth.notify_ready_cls, 0, NULL);
1265     }
1266     return;
1267   }
1268   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1269   {
1270     LOG (GNUNET_ERROR_TYPE_DEBUG,
1271          "Transmit to `%s' fails, time out reached (%p).\n",
1272          GNUNET_a2s (connection->addr, connection->addrlen), connection);
1273     notify = connection->nth.notify_ready;
1274     GNUNET_assert (NULL != notify);
1275     connection->nth.notify_ready = NULL;
1276     notify (connection->nth.notify_ready_cls, 0, NULL);
1277     return;
1278   }
1279   GNUNET_assert (NULL != connection->sock);
1280   if (NULL == tc->write_ready)
1281   {
1282     /* special circumstances (in particular, PREREQ_DONE after
1283      * connect): not yet ready to write, but no "fatal" error either.
1284      * Hence retry.  */
1285     goto SCHEDULE_WRITE;
1286   }
1287   if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1288   {
1289     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1290     /* special circumstances (in particular, shutdown): not yet ready
1291      * to write, but no "fatal" error either.  Hence retry.  */
1292     goto SCHEDULE_WRITE;
1293   }
1294   GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1295   if ((NULL != connection->nth.notify_ready) &&
1296       (connection->write_buffer_size < connection->nth.notify_size))
1297   {
1298     connection->write_buffer =
1299         GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1300     connection->write_buffer_size = connection->nth.notify_size;
1301   }
1302   process_notify (connection);
1303   have = connection->write_buffer_off - connection->write_buffer_pos;
1304   if (0 == have)
1305   {
1306     /* no data ready for writing, terminate write loop */
1307     return;
1308   }
1309   GNUNET_assert (have <= connection->write_buffer_size);
1310   GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1311   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1312 RETRY:
1313   ret =
1314       GNUNET_NETWORK_socket_send (connection->sock,
1315                                   &connection->write_buffer[connection->write_buffer_pos],
1316                                   have);
1317   if (-1 == ret)
1318   {
1319     if (EINTR == errno)
1320       goto RETRY;
1321     if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1322     {
1323       GNUNET_SCHEDULER_cancel (connection->write_task);
1324       connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1325     }
1326     signal_transmit_error (connection, errno);
1327     return;
1328   }
1329   LOG (GNUNET_ERROR_TYPE_DEBUG,
1330        "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1331        (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1332   connection->write_buffer_pos += ret;
1333   if (connection->write_buffer_pos == connection->write_buffer_off)
1334   {
1335     /* transmitted all pending data */
1336     connection->write_buffer_pos = 0;
1337     connection->write_buffer_off = 0;
1338   }
1339   if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1340     return;                     /* all data sent! */
1341   /* not done writing, schedule more */
1342 SCHEDULE_WRITE:
1343   LOG (GNUNET_ERROR_TYPE_DEBUG,
1344        "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1345   have = connection->write_buffer_off - connection->write_buffer_pos;
1346   GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1347   if (GNUNET_SCHEDULER_NO_TASK == connection->write_task)
1348     connection->write_task =
1349         GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1350                                          NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1351                                         GNUNET_TIME_absolute_get_remaining
1352                                         (connection->nth.transmit_timeout),
1353                                         connection->sock, &transmit_ready, connection);
1354 }
1355
1356
1357 /**
1358  * Ask the connection to call us once the specified number of bytes
1359  * are free in the transmission buffer.  May call the notify
1360  * method immediately if enough space is available.
1361  *
1362  * @param connection connection
1363  * @param size number of bytes to send
1364  * @param timeout after how long should we give up (and call
1365  *        notify with buf NULL and size 0)?
1366  * @param notify function to call
1367  * @param notify_cls closure for notify
1368  * @return non-NULL if the notify callback was queued,
1369  *         NULL if we are already going to notify someone else (busy)
1370  */
1371 struct GNUNET_CONNECTION_TransmitHandle *
1372 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1373                                          size_t size,
1374                                          struct GNUNET_TIME_Relative timeout,
1375                                          GNUNET_CONNECTION_TransmitReadyNotify
1376                                          notify, void *notify_cls)
1377 {
1378   if (NULL != connection->nth.notify_ready)
1379   {
1380     GNUNET_assert (0);
1381     return NULL;
1382   }
1383   GNUNET_assert (NULL != notify);
1384   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1385   GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1386   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1387   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1388   connection->nth.notify_ready = notify;
1389   connection->nth.notify_ready_cls = notify_cls;
1390   connection->nth.connection = connection;
1391   connection->nth.notify_size = size;
1392   connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1393   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1394   if ((NULL == connection->sock) &&
1395       (NULL == connection->ap_head) &&
1396       (NULL == connection->dns_active))
1397   {
1398     if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1399       GNUNET_SCHEDULER_cancel (connection->write_task);
1400     connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error, connection);
1401     return &connection->nth;
1402   }
1403   if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1404     return &connection->nth; /* previous transmission still in progress */
1405   if (NULL != connection->sock)
1406   {
1407     /* connected, try to transmit now */
1408     LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmission (%p).\n", connection);
1409     connection->write_task =
1410         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1411                                         (connection->nth.transmit_timeout),
1412                                         connection->sock, &transmit_ready, connection);
1413     return &connection->nth;
1414   }
1415   /* not yet connected, wait for connection */
1416   LOG (GNUNET_ERROR_TYPE_DEBUG,
1417        "Need to wait to schedule transmission for connection, adding timeout task (%p).\n", connection);
1418   connection->nth.timeout_task =
1419     GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, connection);
1420   return &connection->nth;
1421 }
1422
1423
1424 /**
1425  * Cancel the specified transmission-ready notification.
1426  *
1427  * @param th notification to cancel
1428  */
1429 void
1430 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1431                                                 GNUNET_CONNECTION_TransmitHandle
1432                                                 *th)
1433 {
1434   GNUNET_assert (NULL != th->notify_ready);
1435   th->notify_ready = NULL;
1436   if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
1437   {
1438     GNUNET_SCHEDULER_cancel (th->timeout_task);
1439     th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1440   }
1441   if (GNUNET_SCHEDULER_NO_TASK != th->connection->write_task)
1442   {
1443     GNUNET_SCHEDULER_cancel (th->connection->write_task);
1444     th->connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1445   }
1446 }
1447
1448 /* end of connection.c */