Imported Upstream version 2.66.6
[platform/upstream/glib.git] / gio / ghttpproxy.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright (C) 2010 Collabora, Ltd.
4  * Copyright (C) 2014 Red Hat, Inc.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General
17  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  *
19  * Author:  Nicolas Dufresne <nicolas.dufresne@collabora.co.uk>
20  *          Marc-AndrĂ© Lureau <marcandre.lureau@redhat.com>
21  */
22
23 #include "config.h"
24
25 #include "ghttpproxy.h"
26
27 #include <string.h>
28 #include <stdlib.h>
29
30 #include "giomodule.h"
31 #include "giomodule-priv.h"
32 #include "giostream.h"
33 #include "ginputstream.h"
34 #include "glibintl.h"
35 #include "goutputstream.h"
36 #include "gproxy.h"
37 #include "gproxyaddress.h"
38 #include "gsocketconnectable.h"
39 #include "gtask.h"
40 #include "gtlsclientconnection.h"
41 #include "gtlsconnection.h"
42
43
44 struct _GHttpProxy
45 {
46   GObject parent;
47 };
48
49 struct _GHttpProxyClass
50 {
51   GObjectClass parent_class;
52 };
53
54 static void g_http_proxy_iface_init (GProxyInterface *proxy_iface);
55
56 #define g_http_proxy_get_type _g_http_proxy_get_type
57 G_DEFINE_TYPE_WITH_CODE (GHttpProxy, g_http_proxy, G_TYPE_OBJECT,
58                          G_IMPLEMENT_INTERFACE (G_TYPE_PROXY,
59                                                 g_http_proxy_iface_init)
60                          _g_io_modules_ensure_extension_points_registered ();
61                          g_io_extension_point_implement (G_PROXY_EXTENSION_POINT_NAME,
62                                                          g_define_type_id,
63                                                          "http",
64                                                          0))
65
66 static void
67 g_http_proxy_init (GHttpProxy *proxy)
68 {
69 }
70
71 static gchar *
72 create_request (GProxyAddress  *proxy_address,
73                 gboolean       *has_cred,
74                 GError        **error)
75 {
76   const gchar *hostname;
77   gint port;
78   const gchar *username;
79   const gchar *password;
80   GString *request;
81   gchar *ascii_hostname;
82
83   if (has_cred)
84     *has_cred = FALSE;
85
86   hostname = g_proxy_address_get_destination_hostname (proxy_address);
87   ascii_hostname = g_hostname_to_ascii (hostname);
88   if (!ascii_hostname)
89     {
90       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
91                            _("Invalid hostname"));
92       return NULL;
93     }
94   port = g_proxy_address_get_destination_port (proxy_address);
95   username = g_proxy_address_get_username (proxy_address);
96   password = g_proxy_address_get_password (proxy_address);
97
98   request = g_string_new (NULL);
99
100   g_string_append_printf (request,
101                           "CONNECT %s:%i HTTP/1.0\r\n"
102                           "Host: %s:%i\r\n"
103                           "Proxy-Connection: keep-alive\r\n"
104                           "User-Agent: GLib/%i.%i\r\n",
105                           ascii_hostname, port,
106                           ascii_hostname, port,
107                           GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION);
108   g_free (ascii_hostname);
109
110   if (username != NULL && password != NULL)
111     {
112       gchar *cred;
113       gchar *base64_cred;
114
115       if (has_cred)
116         *has_cred = TRUE;
117
118       cred = g_strdup_printf ("%s:%s", username, password);
119       base64_cred = g_base64_encode ((guchar *) cred, strlen (cred));
120       g_free (cred);
121       g_string_append_printf (request,
122                               "Proxy-Authorization: Basic %s\r\n",
123                               base64_cred);
124       g_free (base64_cred);
125     }
126
127   g_string_append (request, "\r\n");
128
129   return g_string_free (request, FALSE);
130 }
131
132 static gboolean
133 check_reply (const gchar  *buffer,
134              gboolean      has_cred,
135              GError      **error)
136 {
137   gint err_code;
138   const gchar *ptr = buffer + 7;
139
140   if (strncmp (buffer, "HTTP/1.", 7) != 0 || (*ptr != '0' && *ptr != '1'))
141     {
142       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
143                            _("Bad HTTP proxy reply"));
144       return FALSE;
145     }
146
147   ptr++;
148   while (*ptr == ' ')
149     ptr++;
150
151   err_code = atoi (ptr);
152
153   if (err_code < 200 || err_code >= 300)
154     {
155       switch (err_code)
156         {
157           case 403:
158             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_NOT_ALLOWED,
159                                  _("HTTP proxy connection not allowed"));
160             break;
161           case 407:
162             if (has_cred)
163               g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_AUTH_FAILED,
164                                    _("HTTP proxy authentication failed"));
165             else
166               g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_NEED_AUTH,
167                                    _("HTTP proxy authentication required"));
168             break;
169           default:
170             g_set_error (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
171                          _("HTTP proxy connection failed: %i"), err_code);
172         }
173
174       return FALSE;
175     }
176
177   return TRUE;
178 }
179
180 #define HTTP_END_MARKER "\r\n\r\n"
181
182 static GIOStream *
183 g_http_proxy_connect (GProxy         *proxy,
184                       GIOStream      *io_stream,
185                       GProxyAddress  *proxy_address,
186                       GCancellable   *cancellable,
187                       GError        **error)
188 {
189   GInputStream *in;
190   GOutputStream *out;
191   gchar *buffer = NULL;
192   gsize buffer_length;
193   gssize bytes_read;
194   gboolean has_cred;
195   GIOStream *tlsconn = NULL;
196
197   if (G_IS_HTTPS_PROXY (proxy))
198     {
199       tlsconn = g_tls_client_connection_new (io_stream,
200                                              G_SOCKET_CONNECTABLE (proxy_address),
201                                              error);
202       if (!tlsconn)
203         goto error;
204
205 #ifdef DEBUG
206       {
207         GTlsCertificateFlags tls_validation_flags = G_TLS_CERTIFICATE_VALIDATE_ALL;
208
209         tls_validation_flags &= ~(G_TLS_CERTIFICATE_UNKNOWN_CA | G_TLS_CERTIFICATE_BAD_IDENTITY);
210         g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (tlsconn),
211                                                       tls_validation_flags);
212       }
213 #endif
214
215       if (!g_tls_connection_handshake (G_TLS_CONNECTION (tlsconn), cancellable, error))
216         goto error;
217
218       io_stream = tlsconn;
219     }
220
221   in = g_io_stream_get_input_stream (io_stream);
222   out = g_io_stream_get_output_stream (io_stream);
223
224   buffer = create_request (proxy_address, &has_cred, error);
225   if (!buffer)
226     goto error;
227   if (!g_output_stream_write_all (out, buffer, strlen (buffer), NULL,
228                                   cancellable, error))
229     goto error;
230
231   g_free (buffer);
232
233   bytes_read = 0;
234   buffer_length = 1024;
235   buffer = g_malloc (buffer_length);
236
237   /* Read byte-by-byte instead of using GDataInputStream
238    * since we do not want to read beyond the end marker
239    */
240   do
241     {
242       gsize nread;
243
244       nread = g_input_stream_read (in, buffer + bytes_read, 1, cancellable, error);
245       if (nread == -1)
246         goto error;
247
248       if (nread == 0)
249         break;
250
251       ++bytes_read;
252
253       if (bytes_read == buffer_length)
254         {
255           buffer_length = 2 * buffer_length;
256           buffer = g_realloc (buffer, buffer_length);
257         }
258
259       *(buffer + bytes_read) = '\0';
260
261       if (g_str_has_suffix (buffer, HTTP_END_MARKER))
262         break;
263     }
264   while (TRUE);
265
266   if (bytes_read == 0)
267     {
268       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
269                            _("HTTP proxy server closed connection unexpectedly."));
270       goto error;
271     }
272
273   if (!check_reply (buffer, has_cred, error))
274     goto error;
275
276   g_free (buffer);
277
278   g_object_ref (io_stream);
279   g_clear_object (&tlsconn);
280
281   return io_stream;
282
283 error:
284   g_clear_object (&tlsconn);
285   g_free (buffer);
286   return NULL;
287 }
288
289 typedef struct
290 {
291   GIOStream *io_stream;
292   GProxyAddress *proxy_address;
293 } ConnectAsyncData;
294
295 static void
296 free_connect_data (ConnectAsyncData *data)
297 {
298   g_object_unref (data->io_stream);
299   g_object_unref (data->proxy_address);
300   g_slice_free (ConnectAsyncData, data);
301 }
302
303 static void
304 connect_thread (GTask        *task,
305                 gpointer      source_object,
306                 gpointer      task_data,
307                 GCancellable *cancellable)
308 {
309   GProxy *proxy = source_object;
310   ConnectAsyncData *data = task_data;
311   GIOStream *res;
312   GError *error = NULL;
313
314   res = g_http_proxy_connect (proxy, data->io_stream, data->proxy_address,
315                               cancellable, &error);
316
317   if (res == NULL)
318     g_task_return_error (task, error);
319   else
320     g_task_return_pointer (task, res, g_object_unref);
321 }
322
323 static void
324 g_http_proxy_connect_async (GProxy              *proxy,
325                             GIOStream           *io_stream,
326                             GProxyAddress       *proxy_address,
327                             GCancellable        *cancellable,
328                             GAsyncReadyCallback  callback,
329                             gpointer             user_data)
330 {
331   ConnectAsyncData *data;
332   GTask *task;
333
334   data = g_slice_new0 (ConnectAsyncData);
335   data->io_stream = g_object_ref (io_stream);
336   data->proxy_address = g_object_ref (proxy_address);
337
338   task = g_task_new (proxy, cancellable, callback, user_data);
339   g_task_set_source_tag (task, g_http_proxy_connect_async);
340   g_task_set_task_data (task, data, (GDestroyNotify) free_connect_data);
341
342   g_task_run_in_thread (task, connect_thread);
343   g_object_unref (task);
344 }
345
346 static GIOStream *
347 g_http_proxy_connect_finish (GProxy        *proxy,
348                              GAsyncResult  *result,
349                              GError       **error)
350 {
351   return g_task_propagate_pointer (G_TASK (result), error);
352 }
353
354 static gboolean
355 g_http_proxy_supports_hostname (GProxy *proxy)
356 {
357   return TRUE;
358 }
359
360 static void
361 g_http_proxy_class_init (GHttpProxyClass *class)
362 {
363 }
364
365 static void
366 g_http_proxy_iface_init (GProxyInterface *proxy_iface)
367 {
368   proxy_iface->connect = g_http_proxy_connect;
369   proxy_iface->connect_async = g_http_proxy_connect_async;
370   proxy_iface->connect_finish = g_http_proxy_connect_finish;
371   proxy_iface->supports_hostname = g_http_proxy_supports_hostname;
372 }
373
374 struct _GHttpsProxy
375 {
376   GHttpProxy parent;
377 };
378
379 struct _GHttpsProxyClass
380 {
381   GHttpProxyClass parent_class;
382 };
383
384 #define g_https_proxy_get_type _g_https_proxy_get_type
385 G_DEFINE_TYPE_WITH_CODE (GHttpsProxy, g_https_proxy, G_TYPE_HTTP_PROXY,
386                          G_IMPLEMENT_INTERFACE (G_TYPE_PROXY,
387                                                 g_http_proxy_iface_init)
388                          _g_io_modules_ensure_extension_points_registered ();
389                          g_io_extension_point_implement (G_PROXY_EXTENSION_POINT_NAME,
390                                                          g_define_type_id,
391                                                          "https",
392                                                          0))
393
394 static void
395 g_https_proxy_init (GHttpsProxy *proxy)
396 {
397 }
398
399 static void
400 g_https_proxy_class_init (GHttpsProxyClass *class)
401 {
402 }