Make SOUP_SESSION_TIMEOUT also affect async connection
[platform/upstream/libsoup.git] / libsoup / soup-socket.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * soup-socket.c: Socket networking code.
4  *
5  * Copyright (C) 2000-2003, Ximian, Inc.
6  */
7
8 #ifdef HAVE_CONFIG_H
9 #include <config.h>
10 #endif
11
12 #include <stdio.h>
13 #include <errno.h>
14 #include <fcntl.h>
15 #include <signal.h>
16 #include <string.h>
17 #include <unistd.h>
18
19 #include "soup-address.h"
20 #include "soup-socket.h"
21 #include "soup-marshal.h"
22 #include "soup-misc.h"
23 #include "soup-ssl.h"
24
25 #include <sys/time.h>
26 #include <sys/types.h>
27
28 /**
29  * SECTION:soup-socket
30  * @short_description: A network socket
31  *
32  * #SoupSocket is libsoup's TCP socket type. While it is primarily
33  * intended for internal use, #SoupSocket<!-- -->s are exposed in the
34  * API in various places, and some of their methods (eg,
35  * soup_socket_get_remote_address()) may be useful to applications.
36  **/
37
38 G_DEFINE_TYPE (SoupSocket, soup_socket, G_TYPE_OBJECT)
39
40 enum {
41         READABLE,
42         WRITABLE,
43         DISCONNECTED,
44         NEW_CONNECTION,
45         LAST_SIGNAL
46 };
47
48 static guint signals[LAST_SIGNAL] = { 0 };
49
50 enum {
51         PROP_0,
52
53         PROP_LOCAL_ADDRESS,
54         PROP_REMOTE_ADDRESS,
55         PROP_NON_BLOCKING,
56         PROP_IS_SERVER,
57         PROP_SSL_CREDENTIALS,
58         PROP_ASYNC_CONTEXT,
59         PROP_TIMEOUT,
60
61         LAST_PROP
62 };
63
64 typedef struct {
65         int sockfd;
66         SoupAddress *local_addr, *remote_addr;
67         GIOChannel *iochannel;
68
69         guint non_blocking:1;
70         guint is_server:1;
71         guint timed_out:1;
72         gpointer ssl_creds;
73
74         GMainContext   *async_context;
75         GSource        *watch_src;
76         GSource        *read_src, *write_src;
77         GSource        *read_timeout, *write_timeout;
78         GSource        *connect_timeout;
79         GByteArray     *read_buf;
80
81         GMutex *iolock, *addrlock;
82         guint timeout;
83 } SoupSocketPrivate;
84 #define SOUP_SOCKET_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), SOUP_TYPE_SOCKET, SoupSocketPrivate))
85
86 #ifdef HAVE_IPV6
87 #define soup_sockaddr_max sockaddr_in6
88 #else
89 #define soup_sockaddr_max sockaddr_in
90 #endif
91
92 static void set_property (GObject *object, guint prop_id,
93                           const GValue *value, GParamSpec *pspec);
94 static void get_property (GObject *object, guint prop_id,
95                           GValue *value, GParamSpec *pspec);
96
97 #ifdef G_OS_WIN32
98 #define SOUP_IS_SOCKET_ERROR(status) ((status) == SOCKET_ERROR)
99 #define SOUP_IS_INVALID_SOCKET(socket) ((socket) == INVALID_SOCKET)
100 #define SOUP_IS_CONNECT_STATUS_INPROGRESS() (WSAGetLastError () == WSAEWOULDBLOCK)
101 #define SHUT_RDWR SD_BOTH
102 #else
103 #define SOUP_IS_SOCKET_ERROR(status) ((status) == -1)
104 #define SOUP_IS_INVALID_SOCKET(socket) ((socket) < 0)
105 #define SOUP_IS_CONNECT_STATUS_INPROGRESS() (errno == EINPROGRESS)
106 #endif
107
108 static void
109 soup_socket_init (SoupSocket *sock)
110 {
111         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sock);
112
113         priv->sockfd = -1;
114         priv->non_blocking = TRUE;
115         priv->addrlock = g_mutex_new ();
116         priv->iolock = g_mutex_new ();
117         priv->timeout = 0;
118 }
119
120 static void
121 disconnect_internal (SoupSocketPrivate *priv)
122 {
123         g_io_channel_unref (priv->iochannel);
124         priv->iochannel = NULL;
125         priv->sockfd = -1;
126
127         if (priv->read_src) {
128                 g_source_destroy (priv->read_src);
129                 priv->read_src = NULL;
130         }
131         if (priv->write_src) {
132                 g_source_destroy (priv->write_src);
133                 priv->write_src = NULL;
134         }
135         if (priv->read_timeout) {
136                 g_source_destroy (priv->read_timeout);
137                 priv->read_timeout = NULL;
138         }
139         if (priv->write_timeout) {
140                 g_source_destroy (priv->write_timeout);
141                 priv->write_timeout = NULL;
142         }
143 }
144
145 static void
146 finalize (GObject *object)
147 {
148         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (object);
149
150         if (priv->iochannel)
151                 disconnect_internal (priv);
152
153         if (priv->local_addr)
154                 g_object_unref (priv->local_addr);
155         if (priv->remote_addr)
156                 g_object_unref (priv->remote_addr);
157
158         if (priv->watch_src)
159                 g_source_destroy (priv->watch_src);
160         if (priv->connect_timeout)
161                 g_source_destroy (priv->connect_timeout);
162         if (priv->async_context)
163                 g_main_context_unref (priv->async_context);
164
165         if (priv->read_buf)
166                 g_byte_array_free (priv->read_buf, TRUE);
167
168         g_mutex_free (priv->addrlock);
169         g_mutex_free (priv->iolock);
170
171         G_OBJECT_CLASS (soup_socket_parent_class)->finalize (object);
172 }
173
174 static void
175 soup_socket_class_init (SoupSocketClass *socket_class)
176 {
177         GObjectClass *object_class = G_OBJECT_CLASS (socket_class);
178
179 #ifdef SIGPIPE
180         signal (SIGPIPE, SIG_IGN);
181 #endif
182
183         g_type_class_add_private (socket_class, sizeof (SoupSocketPrivate));
184
185         /* virtual method override */
186         object_class->finalize = finalize;
187         object_class->set_property = set_property;
188         object_class->get_property = get_property;
189
190         /* signals */
191
192         /**
193          * SoupSocket::readable:
194          * @sock: the socket
195          *
196          * Emitted when an async socket is readable. See
197          * soup_socket_read(), soup_socket_read_until() and
198          * #SoupSocket:non-blocking.
199          **/
200         signals[READABLE] =
201                 g_signal_new ("readable",
202                               G_OBJECT_CLASS_TYPE (object_class),
203                               G_SIGNAL_RUN_LAST,
204                               G_STRUCT_OFFSET (SoupSocketClass, readable),
205                               NULL, NULL,
206                               soup_marshal_NONE__NONE,
207                               G_TYPE_NONE, 0);
208
209         /**
210          * SoupSocket::writable:
211          * @sock: the socket
212          *
213          * Emitted when an async socket is writable. See
214          * soup_socket_write() and #SoupSocket:non-blocking.
215          **/
216         signals[WRITABLE] =
217                 g_signal_new ("writable",
218                               G_OBJECT_CLASS_TYPE (object_class),
219                               G_SIGNAL_RUN_LAST,
220                               G_STRUCT_OFFSET (SoupSocketClass, writable),
221                               NULL, NULL,
222                               soup_marshal_NONE__NONE,
223                               G_TYPE_NONE, 0);
224
225         /**
226          * SoupSocket::disconnected:
227          * @sock: the socket
228          *
229          * Emitted when the socket is disconnected, for whatever
230          * reason.
231          **/
232         signals[DISCONNECTED] =
233                 g_signal_new ("disconnected",
234                               G_OBJECT_CLASS_TYPE (object_class),
235                               G_SIGNAL_RUN_LAST,
236                               G_STRUCT_OFFSET (SoupSocketClass, disconnected),
237                               NULL, NULL,
238                               soup_marshal_NONE__NONE,
239                               G_TYPE_NONE, 0);
240
241         /**
242          * SoupSocket::new-connection:
243          * @sock: the socket
244          * @new: the new socket
245          *
246          * Emitted when a listening socket (set up with
247          * soup_socket_listen()) receives a new connection.
248          *
249          * You must ref the @new if you want to keep it; otherwise it
250          * will be destroyed after the signal is emitted.
251          **/
252         signals[NEW_CONNECTION] =
253                 g_signal_new ("new_connection",
254                               G_OBJECT_CLASS_TYPE (object_class),
255                               G_SIGNAL_RUN_FIRST,
256                               G_STRUCT_OFFSET (SoupSocketClass, new_connection),
257                               NULL, NULL,
258                               soup_marshal_NONE__OBJECT,
259                               G_TYPE_NONE, 1,
260                               SOUP_TYPE_SOCKET);
261
262         /* properties */
263         /**
264          * SOUP_SOCKET_LOCAL_ADDRESS:
265          *
266          * Alias for the #SoupSocket:local-address property. (Address
267          * of local end of socket.)
268          **/
269         g_object_class_install_property (
270                 object_class, PROP_LOCAL_ADDRESS,
271                 g_param_spec_object (SOUP_SOCKET_LOCAL_ADDRESS,
272                                      "Local address",
273                                      "Address of local end of socket",
274                                      SOUP_TYPE_ADDRESS,
275                                      G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
276         /**
277          * SOUP_SOCKET_REMOTE_ADDRESS:
278          *
279          * Alias for the #SoupSocket:remote-address property. (Address
280          * of remote end of socket.)
281          **/
282         g_object_class_install_property (
283                 object_class, PROP_REMOTE_ADDRESS,
284                 g_param_spec_object (SOUP_SOCKET_REMOTE_ADDRESS,
285                                      "Remote address",
286                                      "Address of remote end of socket",
287                                      SOUP_TYPE_ADDRESS,
288                                      G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
289         /**
290          * SoupSocket:non-blocking:
291          *
292          * Whether or not the socket uses non-blocking I/O.
293          *
294          * #SoupSocket's I/O methods are designed around the idea of
295          * using a single codepath for both synchronous and
296          * asynchronous I/O. If you want to read off a #SoupSocket,
297          * the "correct" way to do it is to call soup_socket_read() or
298          * soup_socket_read_until() repeatedly until you have read
299          * everything you want. If it returns %SOUP_SOCKET_WOULD_BLOCK
300          * at any point, stop reading and wait for it to emit the
301          * #SoupSocket::readable signal. Then go back to the
302          * reading-as-much-as-you-can loop. Likewise, for writing to a
303          * #SoupSocket, you should call soup_socket_write() either
304          * until you have written everything, or it returns
305          * %SOUP_SOCKET_WOULD_BLOCK (in which case you wait for
306          * #SoupSocket::writable and then go back into the loop).
307          *
308          * Code written this way will work correctly with both
309          * blocking and non-blocking sockets; blocking sockets will
310          * simply never return %SOUP_SOCKET_WOULD_BLOCK, and so the
311          * code that handles that case just won't get used for them.
312          **/
313         /**
314          * SOUP_SOCKET_FLAG_NONBLOCKING:
315          *
316          * Alias for the #SoupSocket:non-blocking property. (Whether
317          * or not the socket uses non-blocking I/O.)
318          **/
319         g_object_class_install_property (
320                 object_class, PROP_NON_BLOCKING,
321                 g_param_spec_boolean (SOUP_SOCKET_FLAG_NONBLOCKING,
322                                       "Non-blocking",
323                                       "Whether or not the socket uses non-blocking I/O",
324                                       TRUE,
325                                       G_PARAM_READWRITE));
326         /**
327          * SOUP_SOCKET_IS_SERVER:
328          *
329          * Alias for the #SoupSocket:is-server property. (Whether or
330          * not the socket is a server socket.)
331          **/
332         g_object_class_install_property (
333                 object_class, PROP_IS_SERVER,
334                 g_param_spec_boolean (SOUP_SOCKET_IS_SERVER,
335                                       "Server",
336                                       "Whether or not the socket is a server socket",
337                                       FALSE,
338                                       G_PARAM_READABLE));
339         /**
340          * SOUP_SOCKET_SSL_CREDENTIALS:
341          *
342          * Alias for the #SoupSocket:ssl-credentials property.
343          * (SSL credential information.)
344          **/
345         g_object_class_install_property (
346                 object_class, PROP_SSL_CREDENTIALS,
347                 g_param_spec_pointer (SOUP_SOCKET_SSL_CREDENTIALS,
348                                       "SSL credentials",
349                                       "SSL credential information, passed from the session to the SSL implementation",
350                                       G_PARAM_READWRITE));
351         /**
352          * SOUP_SOCKET_ASYNC_CONTEXT:
353          *
354          * Alias for the #SoupSocket:async-context property. (The
355          * socket's #GMainContext.)
356          **/
357         g_object_class_install_property (
358                 object_class, PROP_ASYNC_CONTEXT,
359                 g_param_spec_pointer (SOUP_SOCKET_ASYNC_CONTEXT,
360                                       "Async GMainContext",
361                                       "The GMainContext to dispatch this socket's async I/O in",
362                                       G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
363
364         /**
365          * SOUP_SOCKET_TIMEOUT:
366          *
367          * Alias for the #SoupSocket:timeout property. (The timeout
368          * in seconds for blocking socket I/O operations.)
369          **/
370         g_object_class_install_property (
371                 object_class, PROP_TIMEOUT,
372                 g_param_spec_uint (SOUP_SOCKET_TIMEOUT,
373                                    "Timeout value",
374                                    "Value in seconds to timeout a blocking I/O",
375                                    0, G_MAXUINT, 0,
376                                    G_PARAM_READWRITE));
377
378 #ifdef G_OS_WIN32
379         /* Make sure WSAStartup() gets called. */
380         soup_address_get_type ();
381 #endif
382 }
383
384
385 static void
386 set_nonblocking (SoupSocketPrivate *priv)
387 {
388 #ifndef G_OS_WIN32
389         int flags;
390 #else
391         u_long val;
392 #endif
393
394         if (priv->sockfd == -1)
395                 return;
396
397 #ifndef G_OS_WIN32
398         flags = fcntl (priv->sockfd, F_GETFL, 0);
399         if (flags != -1) {
400                 if (priv->non_blocking)
401                         flags |= O_NONBLOCK;
402                 else
403                         flags &= ~O_NONBLOCK;
404                 fcntl (priv->sockfd, F_SETFL, flags);
405         }
406 #else
407         val = priv->non_blocking ? 1 : 0;
408         ioctlsocket (priv->sockfd, FIONBIO, &val);
409 #endif
410 }
411
412 static void
413 set_fdflags (SoupSocketPrivate *priv)
414 {
415         int opt;
416 #ifndef G_OS_WIN32
417         struct timeval timeout;
418         int flags;
419 #endif
420
421         if (priv->sockfd == -1)
422                 return;
423
424         set_nonblocking (priv);
425
426 #ifndef G_OS_WIN32
427         flags = fcntl (priv->sockfd, F_GETFD, 0);
428         if (flags != -1) {
429                 flags |= FD_CLOEXEC;
430                 fcntl (priv->sockfd, F_SETFD, flags);
431         }
432 #endif
433
434         opt = 1;
435         setsockopt (priv->sockfd, IPPROTO_TCP,
436                     TCP_NODELAY, (void *) &opt, sizeof (opt));
437         setsockopt (priv->sockfd, SOL_SOCKET,
438                     SO_REUSEADDR, (void *) &opt, sizeof (opt));
439
440 #ifndef G_OS_WIN32
441         timeout.tv_sec = priv->timeout;
442         timeout.tv_usec = 0;
443         setsockopt (priv->sockfd, SOL_SOCKET,
444                     SO_RCVTIMEO, (void *) &timeout, sizeof (timeout));
445
446         timeout.tv_sec = priv->timeout;
447         timeout.tv_usec = 0;
448         setsockopt (priv->sockfd, SOL_SOCKET,
449                     SO_SNDTIMEO, (void *) &timeout, sizeof (timeout));
450 #else
451         if (priv->timeout < G_MAXINT / 1000)
452                 opt = priv->timeout * 1000;
453         else
454                 opt = 0;
455
456         setsockopt (priv->sockfd, SOL_SOCKET,
457                     SO_RCVTIMEO, (void *) &opt, sizeof (opt));
458         
459         setsockopt (priv->sockfd, SOL_SOCKET,
460                     SO_SNDTIMEO, (void *) &opt, sizeof (opt));
461 #endif
462
463 #ifndef G_OS_WIN32
464         priv->iochannel =
465                 g_io_channel_unix_new (priv->sockfd);
466 #else
467         priv->iochannel =
468                 g_io_channel_win32_new_socket (priv->sockfd);
469 #endif
470         g_io_channel_set_close_on_unref (priv->iochannel, TRUE);
471         g_io_channel_set_encoding (priv->iochannel, NULL, NULL);
472         g_io_channel_set_buffered (priv->iochannel, FALSE);
473 }
474
475 static void
476 set_property (GObject *object, guint prop_id,
477               const GValue *value, GParamSpec *pspec)
478 {
479         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (object);
480
481         switch (prop_id) {
482         case PROP_LOCAL_ADDRESS:
483                 priv->local_addr = (SoupAddress *)g_value_dup_object (value);
484                 break;
485         case PROP_REMOTE_ADDRESS:
486                 priv->remote_addr = (SoupAddress *)g_value_dup_object (value);
487                 break;
488         case PROP_NON_BLOCKING:
489                 priv->non_blocking = g_value_get_boolean (value);
490                 set_nonblocking (priv);
491                 break;
492         case PROP_SSL_CREDENTIALS:
493                 priv->ssl_creds = g_value_get_pointer (value);
494                 break;
495         case PROP_ASYNC_CONTEXT:
496                 priv->async_context = g_value_get_pointer (value);
497                 if (priv->async_context)
498                         g_main_context_ref (priv->async_context);
499                 break;
500         case PROP_TIMEOUT:
501                 priv->timeout = g_value_get_uint (value);
502                 break;
503         default:
504                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
505                 break;
506         }
507 }
508
509 static void
510 get_property (GObject *object, guint prop_id,
511               GValue *value, GParamSpec *pspec)
512 {
513         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (object);
514
515         switch (prop_id) {
516         case PROP_LOCAL_ADDRESS:
517                 g_value_set_object (value, soup_socket_get_local_address (SOUP_SOCKET (object)));
518                 break;
519         case PROP_REMOTE_ADDRESS:
520                 g_value_set_object (value, soup_socket_get_remote_address (SOUP_SOCKET (object)));
521                 break;
522         case PROP_NON_BLOCKING:
523                 g_value_set_boolean (value, priv->non_blocking);
524                 break;
525         case PROP_IS_SERVER:
526                 g_value_set_boolean (value, priv->is_server);
527                 break;
528         case PROP_SSL_CREDENTIALS:
529                 g_value_set_pointer (value, priv->ssl_creds);
530                 break;
531         case PROP_ASYNC_CONTEXT:
532                 g_value_set_pointer (value, priv->async_context ? g_main_context_ref (priv->async_context) : NULL);
533                 break;
534         case PROP_TIMEOUT:
535                 g_value_set_uint (value, priv->timeout);
536                 break;
537         default:
538                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
539                 break;
540         }
541 }
542
543
544 /**
545  * soup_socket_new:
546  * @optname1: name of first property to set (or %NULL)
547  * @...: value of @optname1, followed by additional property/value pairs
548  *
549  * Creates a new (disconnected) socket
550  *
551  * Return value: the new socket
552  **/
553 SoupSocket *
554 soup_socket_new (const char *optname1, ...)
555 {
556         SoupSocket *sock;
557         va_list ap;
558
559         va_start (ap, optname1);
560         sock = (SoupSocket *)g_object_new_valist (SOUP_TYPE_SOCKET,
561                                                   optname1, ap);
562         va_end (ap);
563
564         return sock;
565 }
566
567 typedef struct {
568         SoupSocket *sock;
569         GCancellable *cancellable;
570         guint cancel_id;
571         SoupSocketCallback callback;
572         gpointer user_data;
573 } SoupSocketAsyncConnectData;
574
575 static gboolean
576 idle_connect_result (gpointer user_data)
577 {
578         SoupSocketAsyncConnectData *sacd = user_data;
579         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sacd->sock);
580         guint status;
581
582         priv->watch_src = NULL;
583         if (sacd->cancel_id)
584                 g_signal_handler_disconnect (sacd->cancellable, sacd->cancel_id);
585
586         if (priv->sockfd == -1) {
587                 if (g_cancellable_is_cancelled (sacd->cancellable))
588                         status = SOUP_STATUS_CANCELLED;
589                 else
590                         status = SOUP_STATUS_CANT_CONNECT;
591         } else
592                 status = SOUP_STATUS_OK;
593
594         sacd->callback (sacd->sock, status, sacd->user_data);
595         g_slice_free (SoupSocketAsyncConnectData, sacd);
596         return FALSE;
597 }
598
599 static gboolean
600 connect_watch (GIOChannel* iochannel, GIOCondition condition, gpointer data)
601 {
602         SoupSocketAsyncConnectData *sacd = data;
603         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sacd->sock);
604         int error = 0;
605         int len = sizeof (error);
606
607         /* Remove the watch now in case we don't return immediately */
608         g_source_destroy (priv->watch_src);
609         priv->watch_src = NULL;
610         if (priv->connect_timeout) {
611                 g_source_destroy (priv->connect_timeout);
612                 priv->connect_timeout = NULL;
613         }
614
615         if ((condition & ~(G_IO_IN | G_IO_OUT)) ||
616             (getsockopt (priv->sockfd, SOL_SOCKET, SO_ERROR,
617                          (void *)&error, (void *)&len) != 0) ||
618             error)
619                 disconnect_internal (priv);
620
621         return idle_connect_result (sacd);
622 }
623
624 static gboolean
625 connect_timeout (gpointer data)
626 {
627         SoupSocketAsyncConnectData *sacd = data;
628         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sacd->sock);
629
630         /* Remove the watch now in case we don't return immediately */
631         g_source_destroy (priv->watch_src);
632         priv->watch_src = NULL;
633         g_source_destroy (priv->connect_timeout);
634         priv->connect_timeout = NULL;
635
636         disconnect_internal (priv);
637         return idle_connect_result (sacd);
638 }
639
640 static void
641 got_address (SoupAddress *addr, guint status, gpointer user_data)
642 {
643         SoupSocketAsyncConnectData *sacd = user_data;
644
645         if (!SOUP_STATUS_IS_SUCCESSFUL (status)) {
646                 sacd->callback (sacd->sock, status, sacd->user_data);
647                 g_slice_free (SoupSocketAsyncConnectData, sacd);
648                 return;
649         }
650
651         soup_socket_connect_async (sacd->sock, sacd->cancellable,
652                                    sacd->callback, sacd->user_data);
653         g_slice_free (SoupSocketAsyncConnectData, sacd);
654 }
655
656 static void
657 async_cancel (GCancellable *cancellable, gpointer user_data)
658 {
659         SoupSocketAsyncConnectData *sacd = user_data;
660         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sacd->sock);
661
662         if (priv->watch_src)
663                 g_source_destroy (priv->watch_src);
664         disconnect_internal (priv);
665         priv->watch_src = soup_add_completion (priv->async_context,
666                                                idle_connect_result, sacd);
667 }
668
669 static guint
670 socket_connect_internal (SoupSocket *sock)
671 {
672         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sock);
673         struct sockaddr *sa;
674         int len, status;
675
676         sa = soup_address_get_sockaddr (priv->remote_addr, &len);
677         if (!sa)
678                 return SOUP_STATUS_CANT_RESOLVE;
679
680         priv->sockfd = socket (sa->sa_family, SOCK_STREAM, 0);
681         if (SOUP_IS_INVALID_SOCKET (priv->sockfd))
682                 return SOUP_STATUS_CANT_CONNECT;
683         set_fdflags (priv);
684
685         status = connect (priv->sockfd, sa, len);
686
687         if (SOUP_IS_SOCKET_ERROR (status)) {
688                 if (SOUP_IS_CONNECT_STATUS_INPROGRESS ())
689                         return SOUP_STATUS_CONTINUE;
690
691                 disconnect_internal (priv);
692                 return SOUP_STATUS_CANT_CONNECT;
693         } else
694                 return SOUP_STATUS_OK;
695 }
696
697 /**
698  * SoupSocketCallback:
699  * @sock: the #SoupSocket
700  * @status: an HTTP status code indicating success or failure
701  * @user_data: the data passed to soup_socket_connect_async()
702  *
703  * The callback function passed to soup_socket_connect_async().
704  **/
705
706 /**
707  * soup_socket_connect_async:
708  * @sock: a client #SoupSocket (which must not already be connected)
709  * @cancellable: a #GCancellable, or %NULL
710  * @callback: callback to call after connecting
711  * @user_data: data to pass to @callback
712  *
713  * Begins asynchronously connecting to @sock's remote address. The
714  * socket will call @callback when it succeeds or fails (but not
715  * before returning from this function).
716  *
717  * If @cancellable is non-%NULL, it can be used to cancel the
718  * connection. @callback will still be invoked in this case, with a
719  * status of %SOUP_STATUS_CANCELLED.
720  **/
721 void
722 soup_socket_connect_async (SoupSocket *sock, GCancellable *cancellable,
723                            SoupSocketCallback callback, gpointer user_data)
724 {
725         SoupSocketPrivate *priv;
726         SoupSocketAsyncConnectData *sacd;
727         guint status;
728
729         g_return_if_fail (SOUP_IS_SOCKET (sock));
730         priv = SOUP_SOCKET_GET_PRIVATE (sock);
731         g_return_if_fail (priv->remote_addr != NULL);
732
733         sacd = g_slice_new0 (SoupSocketAsyncConnectData);
734         sacd->sock = sock;
735         sacd->cancellable = cancellable;
736         sacd->callback = callback;
737         sacd->user_data = user_data;
738
739         if (!soup_address_get_sockaddr (priv->remote_addr, NULL)) {
740                 soup_address_resolve_async (priv->remote_addr,
741                                             priv->async_context,
742                                             cancellable,
743                                             got_address, sacd);
744                 return;
745         }
746
747         status = socket_connect_internal (sock);
748         if (status == SOUP_STATUS_CONTINUE) {
749                 /* Wait for connect to succeed or fail */
750                 priv->watch_src =
751                         soup_add_io_watch (priv->async_context,
752                                            priv->iochannel,
753                                            G_IO_IN | G_IO_OUT |
754                                            G_IO_PRI | G_IO_ERR |
755                                            G_IO_HUP | G_IO_NVAL,
756                                            connect_watch, sacd);
757                 if (priv->timeout) {
758                         priv->connect_timeout =
759                                 soup_add_timeout (priv->async_context,
760                                                   priv->timeout * 1000,
761                                                   connect_timeout, sacd);
762                 }
763                 if (cancellable) {
764                         sacd->cancel_id =
765                                 g_signal_connect (cancellable, "cancelled",
766                                                   G_CALLBACK (async_cancel),
767                                                   sacd);
768                 }
769         } else {
770                 priv->watch_src = soup_add_completion (priv->async_context,
771                                                        idle_connect_result, sacd);
772         }
773 }
774
775 static void
776 sync_cancel (GCancellable *cancellable, gpointer sock)
777 {
778         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sock);
779
780         shutdown (priv->sockfd, SHUT_RDWR);
781 }
782
783 /**
784  * soup_socket_connect_sync:
785  * @sock: a client #SoupSocket (which must not already be connected)
786  * @cancellable: a #GCancellable, or %NULL
787  *
788  * Attempt to synchronously connect @sock to its remote address.
789  *
790  * If @cancellable is non-%NULL, it can be used to cancel the
791  * connection, in which case soup_socket_connect_sync() will return
792  * %SOUP_STATUS_CANCELLED.
793  *
794  * Return value: a success or failure code.
795  **/
796 guint
797 soup_socket_connect_sync (SoupSocket *sock, GCancellable *cancellable)
798 {
799         SoupSocketPrivate *priv;
800         guint status, cancel_id;
801
802         g_return_val_if_fail (SOUP_IS_SOCKET (sock), SOUP_STATUS_MALFORMED);
803         priv = SOUP_SOCKET_GET_PRIVATE (sock);
804         g_return_val_if_fail (!priv->is_server, SOUP_STATUS_MALFORMED);
805         g_return_val_if_fail (priv->sockfd == -1, SOUP_STATUS_MALFORMED);
806         g_return_val_if_fail (priv->remote_addr != NULL, SOUP_STATUS_MALFORMED);
807
808         if (!soup_address_get_sockaddr (priv->remote_addr, NULL)) {
809                 status = soup_address_resolve_sync (priv->remote_addr,
810                                                     cancellable);
811                 if (!SOUP_STATUS_IS_SUCCESSFUL (status))
812                         return status;
813         }
814
815         if (cancellable) {
816                 cancel_id = g_signal_connect (cancellable, "cancelled",
817                                               G_CALLBACK (sync_cancel), sock);
818         }
819
820         status = socket_connect_internal (sock);
821
822         if (cancellable) {
823                 if (status != SOUP_STATUS_OK &&
824                     g_cancellable_is_cancelled (cancellable)) {
825                         status = SOUP_STATUS_CANCELLED;
826                         disconnect_internal (priv);
827                 }
828                 g_signal_handler_disconnect (cancellable, cancel_id);
829         }
830
831         return status;
832 }
833
834 static gboolean
835 listen_watch (GIOChannel* iochannel, GIOCondition condition, gpointer data)
836 {
837         SoupSocket *sock = data, *new;
838         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sock), *new_priv;
839         struct soup_sockaddr_max sa;
840         int sa_len, sockfd;
841
842         if (condition & (G_IO_HUP | G_IO_ERR)) {
843                 g_source_destroy (priv->watch_src);
844                 priv->watch_src = NULL;
845                 return FALSE;
846         }
847
848         sa_len = sizeof (sa);
849         sockfd = accept (priv->sockfd, (struct sockaddr *)&sa, (void *)&sa_len);
850         if (SOUP_IS_INVALID_SOCKET (sockfd))
851                 return TRUE;
852
853         new = g_object_new (SOUP_TYPE_SOCKET, NULL);
854         new_priv = SOUP_SOCKET_GET_PRIVATE (new);
855         new_priv->sockfd = sockfd;
856         if (priv->async_context)
857                 new_priv->async_context = g_main_context_ref (priv->async_context);
858         new_priv->non_blocking = priv->non_blocking;
859         new_priv->is_server = TRUE;
860         new_priv->ssl_creds = priv->ssl_creds;
861         set_fdflags (new_priv);
862
863         new_priv->remote_addr = soup_address_new_from_sockaddr ((struct sockaddr *)&sa, sa_len);
864
865         if (new_priv->ssl_creds) {
866                 if (!soup_socket_start_ssl (new, NULL)) {
867                         g_object_unref (new);
868                         return TRUE;
869                 }
870         }
871
872         g_signal_emit (sock, signals[NEW_CONNECTION], 0, new);
873         g_object_unref (new);
874
875         return TRUE;
876 }
877
878 /**
879  * soup_socket_listen:
880  * @sock: a server #SoupSocket (which must not already be connected or
881  * listening)
882  *
883  * Makes @sock start listening on its local address. When connections
884  * come in, @sock will emit %new_connection.
885  *
886  * Return value: whether or not @sock is now listening.
887  **/
888 gboolean
889 soup_socket_listen (SoupSocket *sock)
890
891 {
892         SoupSocketPrivate *priv;
893         struct sockaddr *sa;
894         int sa_len;
895
896         g_return_val_if_fail (SOUP_IS_SOCKET (sock), FALSE);
897         priv = SOUP_SOCKET_GET_PRIVATE (sock);
898         g_return_val_if_fail (priv->sockfd == -1, FALSE);
899         g_return_val_if_fail (priv->local_addr != NULL, FALSE);
900
901         priv->is_server = TRUE;
902
903         /* @local_addr may have its port set to 0. So we intentionally
904          * don't store it in priv->local_addr, so that if the
905          * caller calls soup_socket_get_local_address() later, we'll
906          * have to make a new addr by calling getsockname(), which
907          * will have the right port number.
908          */
909         sa = soup_address_get_sockaddr (priv->local_addr, &sa_len);
910         g_return_val_if_fail (sa != NULL, FALSE);
911
912         priv->sockfd = socket (sa->sa_family, SOCK_STREAM, 0);
913         if (SOUP_IS_INVALID_SOCKET (priv->sockfd))
914                 goto cant_listen;
915         set_fdflags (priv);
916
917         /* Bind */
918         if (bind (priv->sockfd, sa, sa_len) != 0)
919                 goto cant_listen;
920         /* Force local_addr to be re-resolved now */
921         g_object_unref (priv->local_addr);
922         priv->local_addr = NULL;
923
924         /* Listen */
925         if (listen (priv->sockfd, 10) != 0)
926                 goto cant_listen;
927
928         priv->watch_src = soup_add_io_watch (priv->async_context,
929                                              priv->iochannel,
930                                              G_IO_IN | G_IO_ERR | G_IO_HUP,
931                                              listen_watch, sock);
932         return TRUE;
933
934  cant_listen:
935         if (priv->iochannel)
936                 disconnect_internal (priv);
937
938         return FALSE;
939 }
940
941 /**
942  * soup_socket_start_ssl:
943  * @sock: the socket
944  * @cancellable: a #GCancellable
945  *
946  * Starts using SSL on @socket.
947  *
948  * Return value: success or failure
949  **/
950 gboolean
951 soup_socket_start_ssl (SoupSocket *sock, GCancellable *cancellable)
952 {
953         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sock);
954
955         return soup_socket_start_proxy_ssl (sock, soup_address_get_name (priv->remote_addr), cancellable);
956 }
957         
958 /**
959  * soup_socket_start_proxy_ssl:
960  * @sock: the socket
961  * @ssl_host: hostname of the SSL server
962  * @cancellable: a #GCancellable
963  *
964  * Starts using SSL on @socket, expecting to find a host named
965  * @ssl_host.
966  *
967  * Return value: success or failure
968  **/
969 gboolean
970 soup_socket_start_proxy_ssl (SoupSocket *sock, const char *ssl_host,
971                              GCancellable *cancellable)
972 {
973         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sock);
974         GIOChannel *ssl_chan;
975         GIOChannel *real_chan;
976
977         real_chan = priv->iochannel;
978         ssl_chan = soup_ssl_wrap_iochannel (
979                 real_chan, priv->non_blocking, priv->is_server ?
980                 SOUP_SSL_TYPE_SERVER : SOUP_SSL_TYPE_CLIENT,
981                 ssl_host, priv->ssl_creds);
982
983         if (!ssl_chan)
984                 return FALSE;
985
986         priv->iochannel = ssl_chan;
987         g_io_channel_unref (real_chan);
988
989         return TRUE;
990 }
991         
992 /**
993  * soup_socket_is_ssl:
994  * @sock: a #SoupSocket
995  *
996  * Tests if @sock is set up to do SSL. Note that this simply means
997  * that the %SOUP_SOCKET_SSL_CREDENTIALS property has been set; it
998  * does not mean that soup_socket_start_ssl() has been called.
999  *
1000  * Return value: %TRUE if @sock has SSL credentials set
1001  **/
1002 gboolean
1003 soup_socket_is_ssl (SoupSocket *sock)
1004 {
1005         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sock);
1006
1007         return priv->ssl_creds != NULL;
1008 }
1009
1010 /**
1011  * soup_socket_disconnect:
1012  * @sock: a #SoupSocket
1013  *
1014  * Disconnects @sock. Any further read or write attempts on it will
1015  * fail.
1016  **/
1017 void
1018 soup_socket_disconnect (SoupSocket *sock)
1019 {
1020         SoupSocketPrivate *priv;
1021         gboolean already_disconnected = FALSE;
1022
1023         g_return_if_fail (SOUP_IS_SOCKET (sock));
1024         priv = SOUP_SOCKET_GET_PRIVATE (sock);
1025
1026         if (g_mutex_trylock (priv->iolock)) {
1027                 if (priv->iochannel)
1028                         disconnect_internal (priv);
1029                 else
1030                         already_disconnected = TRUE;
1031                 g_mutex_unlock (priv->iolock);
1032         } else {
1033                 int sockfd;
1034
1035                 /* Another thread is currently doing IO, so
1036                  * we can't close the iochannel. So just shutdown
1037                  * the file descriptor to force the I/O to fail.
1038                  * (It will actually be closed when the socket is
1039                  * destroyed.)
1040                  */
1041                 sockfd = priv->sockfd;
1042                 priv->sockfd = -1;
1043
1044                 if (sockfd == -1)
1045                         already_disconnected = TRUE;
1046                 else
1047                         shutdown (sockfd, SHUT_RDWR);
1048         }
1049
1050         if (already_disconnected)
1051                 return;
1052
1053         /* Give all readers a chance to notice the connection close */
1054         g_signal_emit (sock, signals[READABLE], 0);
1055
1056         /* FIXME: can't disconnect until all data is read */
1057
1058         /* Then let everyone know we're disconnected */
1059         g_signal_emit (sock, signals[DISCONNECTED], 0);
1060 }
1061
1062 /**
1063  * soup_socket_is_connected:
1064  * @sock: a #SoupSocket
1065  *
1066  * Tests if @sock is connected to another host
1067  *
1068  * Return value: %TRUE or %FALSE.
1069  **/
1070 gboolean
1071 soup_socket_is_connected (SoupSocket *sock)
1072 {
1073         SoupSocketPrivate *priv;
1074
1075         g_return_val_if_fail (SOUP_IS_SOCKET (sock), FALSE);
1076         priv = SOUP_SOCKET_GET_PRIVATE (sock);
1077
1078         return priv->iochannel != NULL;
1079 }
1080
1081 /**
1082  * soup_socket_get_local_address:
1083  * @sock: a #SoupSocket
1084  *
1085  * Returns the #SoupAddress corresponding to the local end of @sock.
1086  *
1087  * Return value: the #SoupAddress
1088  **/
1089 SoupAddress *
1090 soup_socket_get_local_address (SoupSocket *sock)
1091 {
1092         SoupSocketPrivate *priv;
1093
1094         g_return_val_if_fail (SOUP_IS_SOCKET (sock), NULL);
1095         priv = SOUP_SOCKET_GET_PRIVATE (sock);
1096
1097         g_mutex_lock (priv->addrlock);
1098         if (!priv->local_addr) {
1099                 struct soup_sockaddr_max bound_sa;
1100                 int sa_len;
1101
1102                 sa_len = sizeof (bound_sa);
1103                 getsockname (priv->sockfd, (struct sockaddr *)&bound_sa, (void *)&sa_len);
1104                 priv->local_addr = soup_address_new_from_sockaddr ((struct sockaddr *)&bound_sa, sa_len);
1105         }
1106         g_mutex_unlock (priv->addrlock);
1107
1108         return priv->local_addr;
1109 }
1110
1111 /**
1112  * soup_socket_get_remote_address:
1113  * @sock: a #SoupSocket
1114  *
1115  * Returns the #SoupAddress corresponding to the remote end of @sock.
1116  *
1117  * Return value: the #SoupAddress
1118  **/
1119 SoupAddress *
1120 soup_socket_get_remote_address (SoupSocket *sock)
1121 {
1122         SoupSocketPrivate *priv;
1123
1124         g_return_val_if_fail (SOUP_IS_SOCKET (sock), NULL);
1125         priv = SOUP_SOCKET_GET_PRIVATE (sock);
1126
1127         g_mutex_lock (priv->addrlock);
1128         if (!priv->remote_addr) {
1129                 struct soup_sockaddr_max bound_sa;
1130                 int sa_len;
1131
1132                 sa_len = sizeof (bound_sa);
1133                 getpeername (priv->sockfd, (struct sockaddr *)&bound_sa, (void *)&sa_len);
1134                 priv->remote_addr = soup_address_new_from_sockaddr ((struct sockaddr *)&bound_sa, sa_len);
1135         }
1136         g_mutex_unlock (priv->addrlock);
1137
1138         return priv->remote_addr;
1139 }
1140
1141
1142 static gboolean
1143 socket_timeout (gpointer sock)
1144 {
1145         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sock);
1146         gboolean readable = FALSE, writable = FALSE;
1147
1148         priv->timed_out = TRUE;
1149         if (priv->read_timeout) {
1150                 priv->read_timeout = NULL;
1151                 readable = TRUE;
1152         }
1153         if (priv->write_timeout) {
1154                 priv->write_timeout = NULL;
1155                 writable = TRUE;
1156         }
1157
1158         if (readable)
1159                 g_signal_emit (sock, signals[READABLE], 0);
1160         if (writable)
1161                 g_signal_emit (sock, signals[WRITABLE], 0);
1162
1163         return FALSE;
1164 }
1165
1166 static gboolean
1167 socket_read_watch (GIOChannel *chan, GIOCondition cond, gpointer user_data)
1168 {
1169         SoupSocket *sock = user_data;
1170         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sock);
1171
1172         priv->read_src = NULL;
1173         if (priv->read_timeout) {
1174                 g_source_destroy (priv->read_timeout);
1175                 priv->read_timeout = NULL;
1176         }
1177
1178         if (cond & (G_IO_ERR | G_IO_HUP))
1179                 soup_socket_disconnect (sock);
1180         else
1181                 g_signal_emit (sock, signals[READABLE], 0);
1182
1183         return FALSE;
1184 }
1185
1186 static SoupSocketIOStatus
1187 read_from_network (SoupSocket *sock, gpointer buffer, gsize len,
1188                    gsize *nread, GError **error)
1189 {
1190         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sock);
1191         GIOStatus status;
1192         GIOCondition cond = G_IO_IN;
1193         GError *my_err = NULL;
1194
1195         *nread = 0;
1196
1197         if (!priv->iochannel)
1198                 return SOUP_SOCKET_EOF;
1199
1200         if (priv->timed_out)
1201                 return SOUP_SOCKET_ERROR;
1202
1203         status = g_io_channel_read_chars (priv->iochannel,
1204                                           buffer, len, nread, &my_err);
1205         if (my_err) {
1206                 if (my_err->domain == SOUP_SSL_ERROR &&
1207                     my_err->code == SOUP_SSL_ERROR_HANDSHAKE_NEEDS_WRITE)
1208                         cond = G_IO_OUT;
1209                 g_propagate_error (error, my_err);
1210         }
1211
1212         switch (status) {
1213         case G_IO_STATUS_NORMAL:
1214         case G_IO_STATUS_AGAIN:
1215                 if (*nread > 0) {
1216                         g_clear_error (error);
1217                         return SOUP_SOCKET_OK;
1218                 }
1219
1220                 /* If the socket is sync and we get EAGAIN, then it is
1221                  * a socket timeout and should be treated as an error
1222                  * condition.
1223                  */
1224                 if (!priv->non_blocking)
1225                         return SOUP_SOCKET_ERROR;
1226
1227                 if (!priv->read_src) {
1228                         priv->read_src =
1229                                 soup_add_io_watch (priv->async_context,
1230                                                    priv->iochannel,
1231                                                    cond | G_IO_HUP | G_IO_ERR,
1232                                                    socket_read_watch, sock);
1233                         if (priv->timeout) {
1234                                 priv->read_timeout =
1235                                         soup_add_timeout (priv->async_context,
1236                                                           priv->timeout * 1000,
1237                                                           socket_timeout, sock);
1238                         }
1239                 }
1240                 g_clear_error (error);
1241                 return SOUP_SOCKET_WOULD_BLOCK;
1242
1243         case G_IO_STATUS_EOF:
1244                 g_clear_error (error);
1245                 return SOUP_SOCKET_EOF;
1246
1247         default:
1248                 return SOUP_SOCKET_ERROR;
1249         }
1250 }
1251
1252 static SoupSocketIOStatus
1253 read_from_buf (SoupSocket *sock, gpointer buffer, gsize len, gsize *nread)
1254 {
1255         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sock);
1256         GByteArray *read_buf = priv->read_buf;
1257
1258         *nread = MIN (read_buf->len, len);
1259         memcpy (buffer, read_buf->data, *nread);
1260
1261         if (*nread == read_buf->len) {
1262                 g_byte_array_free (read_buf, TRUE);
1263                 priv->read_buf = NULL;
1264         } else {
1265                 memmove (read_buf->data, read_buf->data + *nread, 
1266                          read_buf->len - *nread);
1267                 g_byte_array_set_size (read_buf, read_buf->len - *nread);
1268         }
1269
1270         return SOUP_SOCKET_OK;
1271 }
1272
1273 /**
1274  * SoupSocketIOStatus:
1275  * @SOUP_SOCKET_OK: Success
1276  * @SOUP_SOCKET_WOULD_BLOCK: Cannot read/write any more at this time
1277  * @SOUP_SOCKET_EOF: End of file
1278  * @SOUP_SOCKET_ERROR: Other error
1279  *
1280  * Return value from the #SoupSocket IO methods.
1281  **/
1282
1283 /**
1284  * soup_socket_read:
1285  * @sock: the socket
1286  * @buffer: buffer to read into
1287  * @len: size of @buffer in bytes
1288  * @nread: on return, the number of bytes read into @buffer
1289  * @cancellable: a #GCancellable, or %NULL
1290  * @error: error pointer
1291  *
1292  * Attempts to read up to @len bytes from @sock into @buffer. If some
1293  * data is successfully read, soup_socket_read() will return
1294  * %SOUP_SOCKET_OK, and *@nread will contain the number of bytes
1295  * actually read (which may be less than @len).
1296  *
1297  * If @sock is non-blocking, and no data is available, the return
1298  * value will be %SOUP_SOCKET_WOULD_BLOCK. In this case, the caller
1299  * can connect to the #SoupSocket::readable signal to know when there
1300  * is more data to read. (NB: You MUST read all available data off the
1301  * socket first. #SoupSocket::readable is only emitted after
1302  * soup_socket_read() returns %SOUP_SOCKET_WOULD_BLOCK, and it is only
1303  * emitted once. See the documentation for #SoupSocket:non-blocking.)
1304  *
1305  * Return value: a #SoupSocketIOStatus, as described above (or
1306  * %SOUP_SOCKET_EOF if the socket is no longer connected, or
1307  * %SOUP_SOCKET_ERROR on any other error, in which case @error will
1308  * also be set).
1309  **/
1310 SoupSocketIOStatus
1311 soup_socket_read (SoupSocket *sock, gpointer buffer, gsize len,
1312                   gsize *nread, GCancellable *cancellable, GError **error)
1313 {
1314         SoupSocketPrivate *priv;
1315         SoupSocketIOStatus status;
1316
1317         g_return_val_if_fail (SOUP_IS_SOCKET (sock), SOUP_SOCKET_ERROR);
1318         g_return_val_if_fail (nread != NULL, SOUP_SOCKET_ERROR);
1319
1320         priv = SOUP_SOCKET_GET_PRIVATE (sock);
1321
1322         g_mutex_lock (priv->iolock);
1323         if (priv->read_buf)
1324                 status = read_from_buf (sock, buffer, len, nread);
1325         else
1326                 status = read_from_network (sock, buffer, len, nread, error);
1327         g_mutex_unlock (priv->iolock);
1328
1329         return status;
1330 }
1331
1332 /**
1333  * soup_socket_read_until:
1334  * @sock: the socket
1335  * @buffer: buffer to read into
1336  * @len: size of @buffer in bytes
1337  * @boundary: boundary to read until
1338  * @boundary_len: length of @boundary in bytes
1339  * @nread: on return, the number of bytes read into @buffer
1340  * @got_boundary: on return, whether or not the data in @buffer
1341  * ends with the boundary string
1342  * @cancellable: a #GCancellable, or %NULL
1343  * @error: error pointer
1344  *
1345  * Like soup_socket_read(), but reads no further than the first
1346  * occurrence of @boundary. (If the boundary is found, it will be
1347  * included in the returned data, and *@got_boundary will be set to
1348  * %TRUE.) Any data after the boundary will returned in future reads.
1349  *
1350  * soup_socket_read_until() will almost always return fewer than @len
1351  * bytes: if the boundary is found, then it will only return the bytes
1352  * up until the end of the boundary, and if the boundary is not found,
1353  * then it will leave the last <literal>(boundary_len - 1)</literal>
1354  * bytes in its internal buffer, in case they form the start of the
1355  * boundary string. Thus, @len normally needs to be at least 1 byte
1356  * longer than @boundary_len if you want to make any progress at all.
1357  *
1358  * Return value: as for soup_socket_read()
1359  **/
1360 SoupSocketIOStatus
1361 soup_socket_read_until (SoupSocket *sock, gpointer buffer, gsize len,
1362                         gconstpointer boundary, gsize boundary_len,
1363                         gsize *nread, gboolean *got_boundary,
1364                         GCancellable *cancellable, GError **error)
1365 {
1366         SoupSocketPrivate *priv;
1367         SoupSocketIOStatus status;
1368         GByteArray *read_buf;
1369         guint match_len, prev_len;
1370         guint8 *p, *end;
1371
1372         g_return_val_if_fail (SOUP_IS_SOCKET (sock), SOUP_SOCKET_ERROR);
1373         g_return_val_if_fail (nread != NULL, SOUP_SOCKET_ERROR);
1374         g_return_val_if_fail (len >= boundary_len, SOUP_SOCKET_ERROR);
1375
1376         priv = SOUP_SOCKET_GET_PRIVATE (sock);
1377
1378         g_mutex_lock (priv->iolock);
1379
1380         *got_boundary = FALSE;
1381
1382         if (!priv->read_buf)
1383                 priv->read_buf = g_byte_array_new ();
1384         read_buf = priv->read_buf;
1385
1386         if (read_buf->len < boundary_len) {
1387                 prev_len = read_buf->len;
1388                 g_byte_array_set_size (read_buf, len);
1389                 status = read_from_network (sock,
1390                                             read_buf->data + prev_len,
1391                                             len - prev_len, nread, error);
1392                 read_buf->len = prev_len + *nread;
1393
1394                 if (status != SOUP_SOCKET_OK) {
1395                         g_mutex_unlock (priv->iolock);
1396                         return status;
1397                 }
1398         }
1399
1400         /* Scan for the boundary */
1401         end = read_buf->data + read_buf->len;
1402         for (p = read_buf->data; p <= end - boundary_len; p++) {
1403                 if (!memcmp (p, boundary, boundary_len)) {
1404                         p += boundary_len;
1405                         *got_boundary = TRUE;
1406                         break;
1407                 }
1408         }
1409
1410         /* Return everything up to 'p' (which is either just after the
1411          * boundary, or @boundary_len - 1 bytes before the end of the
1412          * buffer).
1413          */
1414         match_len = p - read_buf->data;
1415         status = read_from_buf (sock, buffer, MIN (len, match_len), nread);
1416
1417         g_mutex_unlock (priv->iolock);
1418         return status;
1419 }
1420
1421 static gboolean
1422 socket_write_watch (GIOChannel *chan, GIOCondition cond, gpointer user_data)
1423 {
1424         SoupSocket *sock = user_data;
1425         SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sock);
1426
1427         priv->write_src = NULL;
1428         if (priv->write_timeout) {
1429                 g_source_destroy (priv->write_timeout);
1430                 priv->write_timeout = NULL;
1431         }
1432
1433         if (cond & (G_IO_ERR | G_IO_HUP))
1434                 soup_socket_disconnect (sock);
1435         else
1436                 g_signal_emit (sock, signals[WRITABLE], 0);
1437
1438         return FALSE;
1439 }
1440
1441 /**
1442  * soup_socket_write:
1443  * @sock: the socket
1444  * @buffer: data to write
1445  * @len: size of @buffer, in bytes
1446  * @nwrote: on return, number of bytes written
1447  * @cancellable: a #GCancellable, or %NULL
1448  * @error: error pointer
1449  *
1450  * Attempts to write @len bytes from @buffer to @sock. If some data is
1451  * successfully written, the return status will be %SOUP_SOCKET_OK,
1452  * and *@nwrote will contain the number of bytes actually written
1453  * (which may be less than @len).
1454  *
1455  * If @sock is non-blocking, and no data could be written right away,
1456  * the return value will be %SOUP_SOCKET_WOULD_BLOCK. In this case,
1457  * the caller can connect to the #SoupSocket::writable signal to know
1458  * when more data can be written. (NB: #SoupSocket::writable is only
1459  * emitted after soup_socket_write() returns %SOUP_SOCKET_WOULD_BLOCK,
1460  * and it is only emitted once. See the documentation for
1461  * #SoupSocket:non-blocking.)
1462  *
1463  * Return value: a #SoupSocketIOStatus, as described above (or
1464  * %SOUP_SOCKET_EOF or %SOUP_SOCKET_ERROR. @error will be set if the
1465  * return value is %SOUP_SOCKET_ERROR.)
1466  **/
1467 SoupSocketIOStatus
1468 soup_socket_write (SoupSocket *sock, gconstpointer buffer,
1469                    gsize len, gsize *nwrote,
1470                    GCancellable *cancellable, GError **error)
1471 {
1472         SoupSocketPrivate *priv;
1473         GIOStatus status;
1474         GIOCondition cond = G_IO_OUT;
1475         GError *my_err = NULL;
1476
1477         g_return_val_if_fail (SOUP_IS_SOCKET (sock), SOUP_SOCKET_ERROR);
1478         g_return_val_if_fail (nwrote != NULL, SOUP_SOCKET_ERROR);
1479
1480         priv = SOUP_SOCKET_GET_PRIVATE (sock);
1481
1482         g_mutex_lock (priv->iolock);
1483
1484         if (!priv->iochannel) {
1485                 g_mutex_unlock (priv->iolock);
1486                 return SOUP_SOCKET_EOF;
1487         }
1488         if (priv->timed_out) {
1489                 g_mutex_unlock (priv->iolock);
1490                 return SOUP_SOCKET_ERROR;
1491         }
1492         if (priv->write_src) {
1493                 g_mutex_unlock (priv->iolock);
1494                 return SOUP_SOCKET_WOULD_BLOCK;
1495         }
1496
1497         status = g_io_channel_write_chars (priv->iochannel,
1498                                            buffer, len, nwrote, &my_err);
1499         if (my_err) {
1500                 if (my_err->domain == SOUP_SSL_ERROR &&
1501                     my_err->code == SOUP_SSL_ERROR_HANDSHAKE_NEEDS_READ)
1502                         cond = G_IO_IN;
1503                 g_propagate_error (error, my_err);
1504         }
1505
1506         /* If the socket is sync and we get EAGAIN, then it is a
1507          * socket timeout and should be treated as an error condition.
1508          */
1509         if (!priv->non_blocking && status == G_IO_STATUS_AGAIN) {
1510                 g_mutex_unlock (priv->iolock);
1511                 return SOUP_SOCKET_ERROR;
1512         }
1513
1514         if (status != G_IO_STATUS_NORMAL && status != G_IO_STATUS_AGAIN) {
1515                 g_mutex_unlock (priv->iolock);
1516                 return SOUP_SOCKET_ERROR;
1517         }
1518
1519         g_clear_error (error);
1520
1521         if (*nwrote) {
1522                 g_mutex_unlock (priv->iolock);
1523                 return SOUP_SOCKET_OK;
1524         }
1525
1526         priv->write_src =
1527                 soup_add_io_watch (priv->async_context,
1528                                    priv->iochannel,
1529                                    cond | G_IO_HUP | G_IO_ERR, 
1530                                    socket_write_watch, sock);
1531         if (priv->timeout) {
1532                 priv->write_timeout = soup_add_timeout (priv->async_context,
1533                                                         priv->timeout * 1000,
1534                                                         socket_timeout, sock);
1535         }
1536
1537         g_mutex_unlock (priv->iolock);
1538         return SOUP_SOCKET_WOULD_BLOCK;
1539 }