Add initial TLS (SSL) support to gio
[platform/upstream/glib.git] / gio / tests / socket-client.c
1 #include <gio/gio.h>
2 #include <gio/gunixsocketaddress.h>
3 #include <glib.h>
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <string.h>
7
8 GMainLoop *loop;
9
10 gboolean verbose = FALSE;
11 gboolean non_blocking = FALSE;
12 gboolean use_udp = FALSE;
13 int cancel_timeout = 0;
14 int read_timeout = 0;
15 gboolean unix_socket = FALSE;
16 gboolean tls = FALSE;
17
18 static GOptionEntry cmd_entries[] = {
19   {"cancel", 'c', 0, G_OPTION_ARG_INT, &cancel_timeout,
20    "Cancel any op after the specified amount of seconds", NULL},
21   {"udp", 'u', 0, G_OPTION_ARG_NONE, &use_udp,
22    "Use udp instead of tcp", NULL},
23   {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
24    "Be verbose", NULL},
25   {"non-blocking", 'n', 0, G_OPTION_ARG_NONE, &non_blocking,
26    "Enable non-blocking i/o", NULL},
27 #ifdef G_OS_UNIX
28   {"unix", 'U', 0, G_OPTION_ARG_NONE, &unix_socket,
29    "Use a unix socket instead of IP", NULL},
30 #endif
31   {"timeout", 't', 0, G_OPTION_ARG_INT, &read_timeout,
32    "Time out reads after the specified number of seconds", NULL},
33   {"tls", 'T', 0, G_OPTION_ARG_NONE, &tls,
34    "Use TLS (SSL)", NULL},
35   {NULL}
36 };
37
38 #include "socket-common.c"
39
40 static gboolean
41 accept_certificate (GTlsClientConnection *conn, GTlsCertificate *cert,
42                     GTlsCertificateFlags errors, gpointer user_data)
43 {
44   g_print ("Certificate would have been rejected ( ");
45   if (errors & G_TLS_CERTIFICATE_UNKNOWN_CA)
46     g_print ("unknown-ca ");
47   if (errors & G_TLS_CERTIFICATE_BAD_IDENTITY)
48     g_print ("bad-identity ");
49   if (errors & G_TLS_CERTIFICATE_NOT_ACTIVATED)
50     g_print ("not-activated ");
51   if (errors & G_TLS_CERTIFICATE_EXPIRED)
52     g_print ("expired ");
53   if (errors & G_TLS_CERTIFICATE_REVOKED)
54     g_print ("revoked ");
55   if (errors & G_TLS_CERTIFICATE_INSECURE)
56     g_print ("insecure ");
57   g_print (") but accepting anyway.\n");
58
59   return TRUE;
60 }
61
62 int
63 main (int argc,
64       char *argv[])
65 {
66   GSocket *socket;
67   GSocketAddress *src_address;
68   GSocketAddress *address;
69   GSocketType socket_type;
70   GSocketFamily socket_family;
71   GError *error = NULL;
72   GOptionContext *context;
73   GCancellable *cancellable;
74   GSocketAddressEnumerator *enumerator;
75   GSocketConnectable *connectable;
76   GIOStream *connection;
77   GInputStream *istream;
78   GOutputStream *ostream;
79
80   g_thread_init (NULL);
81
82   g_type_init ();
83
84   context = g_option_context_new (" <hostname>[:port] - Test GSocket client stuff");
85   g_option_context_add_main_entries (context, cmd_entries, NULL);
86   if (!g_option_context_parse (context, &argc, &argv, &error))
87     {
88       g_printerr ("%s: %s\n", argv[0], error->message);
89       return 1;
90     }
91
92   if (argc != 2)
93     {
94       g_printerr ("%s: %s\n", argv[0], "Need to specify hostname / unix socket name");
95       return 1;
96     }
97
98   if (use_udp && tls)
99     {
100       g_printerr ("DTLS (TLS over UDP) is not supported");
101       return 1;
102     }
103
104   if (cancel_timeout)
105     {
106       cancellable = g_cancellable_new ();
107       g_thread_create (cancel_thread, cancellable, FALSE, NULL);
108     }
109   else
110     {
111       cancellable = NULL;
112     }
113
114   loop = g_main_loop_new (NULL, FALSE);
115
116   if (use_udp)
117     socket_type = G_SOCKET_TYPE_DATAGRAM;
118   else
119     socket_type = G_SOCKET_TYPE_STREAM;
120
121   if (unix_socket)
122     socket_family = G_SOCKET_FAMILY_UNIX;
123   else
124     socket_family = G_SOCKET_FAMILY_IPV4;
125
126   socket = g_socket_new (socket_family, socket_type, 0, &error);
127   if (socket == NULL)
128     {
129       g_printerr ("%s: %s\n", argv[0], error->message);
130       return 1;
131     }
132
133   if (read_timeout)
134     g_socket_set_timeout (socket, read_timeout);
135
136   if (unix_socket)
137     {
138       GSocketAddress *addr;
139
140       addr = socket_address_from_string (argv[1]);
141       if (addr == NULL)
142         {
143           g_printerr ("%s: Could not parse '%s' as unix socket name\n", argv[0], argv[1]);
144           return 1;
145         }
146       connectable = G_SOCKET_CONNECTABLE (addr);
147     }
148   else
149     {
150       connectable = g_network_address_parse (argv[1], 7777, &error);
151       if (connectable == NULL)
152         {
153           g_printerr ("%s: %s\n", argv[0], error->message);
154           return 1;
155         }
156     }
157
158   enumerator = g_socket_connectable_enumerate (connectable);
159   while (TRUE)
160     {
161       address = g_socket_address_enumerator_next (enumerator, cancellable, &error);
162       if (address == NULL)
163         {
164           if (error == NULL)
165             g_printerr ("%s: No more addresses to try\n", argv[0]);
166           else
167             g_printerr ("%s: %s\n", argv[0], error->message);
168           return 1;
169         }
170
171       if (g_socket_connect (socket, address, cancellable, &error))
172         break;
173       g_printerr ("%s: Connection to %s failed: %s, trying next\n", argv[0], socket_address_to_string (address), error->message);
174       g_error_free (error);
175       error = NULL;
176
177       g_object_unref (address);
178     }
179   g_object_unref (enumerator);
180
181   g_print ("Connected to %s\n",
182            socket_address_to_string (address));
183
184   src_address = g_socket_get_local_address (socket, &error);
185   if (!src_address)
186     {
187       g_printerr ("Error getting local address: %s\n",
188                   error->message);
189       return 1;
190     }
191   g_print ("local address: %s\n",
192            socket_address_to_string (src_address));
193   g_object_unref (src_address);
194
195   if (use_udp)
196     connection = NULL;
197   else
198     connection = G_IO_STREAM (g_socket_connection_factory_create_connection (socket));
199
200   if (tls)
201     {
202       GTlsClientConnection *tls_conn;
203
204       tls_conn = g_tls_client_connection_new (connection, connectable, &error);
205       if (!tls_conn)
206         {
207           g_printerr ("Could not create TLS connection: %s\n",
208                       error->message);
209           return 1;
210         }
211
212       g_signal_connect (tls_conn, "accept-certificate",
213                         G_CALLBACK (accept_certificate), NULL);
214
215       if (!g_tls_connection_handshake (G_TLS_CONNECTION (tls_conn),
216                                        cancellable, &error))
217         {
218           g_printerr ("Error during TLS handshake: %s\n",
219                       error->message);
220           return 1;
221         }
222
223       g_object_unref (connection);
224       connection = G_IO_STREAM (tls_conn);
225     }
226   g_object_unref (connectable);
227
228   if (connection)
229     {
230       istream = g_io_stream_get_input_stream (connection);
231       ostream = g_io_stream_get_output_stream (connection);
232     }
233
234   /* TODO: Test non-blocking connect/handshake */
235   if (non_blocking)
236     g_socket_set_blocking (socket, FALSE);
237
238   while (TRUE)
239     {
240       gchar buffer[4096];
241       gssize size;
242       gsize to_send;
243
244       if (fgets (buffer, sizeof buffer, stdin) == NULL)
245         break;
246
247       to_send = strlen (buffer);
248       while (to_send > 0)
249         {
250           if (use_udp)
251             {
252               ensure_socket_condition (socket, G_IO_OUT, cancellable);
253               size = g_socket_send_to (socket, address,
254                                        buffer, to_send,
255                                        cancellable, &error);
256             }
257           else
258             {
259               ensure_connection_condition (connection, G_IO_OUT, cancellable);
260               size = g_output_stream_write (ostream,
261                                             buffer, to_send,
262                                             cancellable, &error);
263             }
264
265           if (size < 0)
266             {
267               if (g_error_matches (error,
268                                    G_IO_ERROR,
269                                    G_IO_ERROR_WOULD_BLOCK))
270                 {
271                   g_print ("socket send would block, handling\n");
272                   g_error_free (error);
273                   error = NULL;
274                   continue;
275                 }
276               else
277                 {
278                   g_printerr ("Error sending to socket: %s\n",
279                               error->message);
280                   return 1;
281                 }
282             }
283
284           g_print ("sent %" G_GSSIZE_FORMAT " bytes of data\n", size);
285
286           if (size == 0)
287             {
288               g_printerr ("Unexpected short write\n");
289               return 1;
290             }
291
292           to_send -= size;
293         }
294
295       if (use_udp)
296         {
297           ensure_socket_condition (socket, G_IO_IN, cancellable);
298           size = g_socket_receive_from (socket, &src_address,
299                                         buffer, sizeof buffer,
300                                         cancellable, &error);
301         }
302       else
303         {
304           ensure_connection_condition (connection, G_IO_IN, cancellable);
305           size = g_input_stream_read (istream,
306                                       buffer, sizeof buffer,
307                                       cancellable, &error);
308         }
309
310       if (size < 0)
311         {
312           g_printerr ("Error receiving from socket: %s\n",
313                       error->message);
314           return 1;
315         }
316
317       if (size == 0)
318         break;
319
320       g_print ("received %" G_GSSIZE_FORMAT " bytes of data", size);
321       if (use_udp)
322         g_print (" from %s", socket_address_to_string (src_address));
323       g_print ("\n");
324
325       if (verbose)
326         g_print ("-------------------------\n"
327                  "%.*s"
328                  "-------------------------\n",
329                  (int)size, buffer);
330
331     }
332
333   g_print ("closing socket\n");
334
335   if (connection)
336     {
337       if (!g_io_stream_close (connection, cancellable, &error))
338         {
339           g_printerr ("Error closing connection: %s\n",
340                       error->message);
341           return 1;
342         }
343       g_object_unref (connection);
344     }
345   else
346     {
347       if (!g_socket_close (socket, &error))
348         {
349           g_printerr ("Error closing master socket: %s\n",
350                       error->message);
351           return 1;
352         }
353     }
354
355   g_object_unref (socket);
356   g_object_unref (address);
357
358   return 0;
359 }