tools: Add support for WISPr authentication polling
[platform/upstream/connman.git] / tools / wispr.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2010  Intel Corporation. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program 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
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdio.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <signal.h>
32 #include <termios.h>
33
34 #include <gweb/gweb.h>
35
36 #define DEFAULT_URL  "http://www.connman.net/online/status.html"
37
38 static GTimer *timer;
39
40 static GMainLoop *main_loop;
41
42 static void web_debug(const char *str, void *data)
43 {
44         g_print("%s: %s\n", (const char *) data, str);
45 }
46
47 static void sig_term(int sig)
48 {
49         g_main_loop_quit(main_loop);
50 }
51
52 static const char *message_type_to_string(int message_type)
53 {
54         switch (message_type) {
55         case 100:
56                 return "Initial redirect message";
57         case 110:
58                 return "Proxy notification";
59         case 120:
60                 return "Authentication notification";
61         case 130:
62                 return "Logoff notification";
63         case 140:
64                 return "Response to Authentication Poll";
65         case 150:
66                 return "Response to Abort Login";
67         }
68
69         return NULL;
70 }
71
72 static const char *response_code_to_string(int response_code)
73 {
74         switch (response_code) {
75         case 0:
76                 return "No error";
77         case 50:
78                 return "Login succeeded";
79         case 100:
80                 return "Login failed";
81         case 102:
82                 return "RADIUS server error/timeout";
83         case 105:
84                 return "RADIUS server not enabled";
85         case 150:
86                 return "Logoff succeeded";
87         case 151:
88                 return "Login aborted";
89         case 200:
90                 return "Proxy detection/repeat operation";
91         case 201:
92                 return "Authentication pending";
93         case 255:
94                 return "Access gateway internal error";
95         }
96
97         return NULL;
98 }
99
100 struct wispr_msg {
101         gboolean has_error;
102         const char *current_element;
103         int message_type;
104         int response_code;
105         char *login_url;
106         char *abort_login_url;
107         char *logoff_url;
108         char *access_procedure;
109         char *access_location;
110         char *location_name;
111 };
112
113 static inline void wispr_msg_init(struct wispr_msg *msg)
114 {
115         msg->has_error = FALSE;
116         msg->current_element = NULL;
117
118         msg->message_type = -1;
119         msg->response_code = -1;
120
121         g_free(msg->login_url);
122         msg->login_url = NULL;
123
124         g_free(msg->abort_login_url);
125         msg->abort_login_url = NULL;
126
127         g_free(msg->logoff_url);
128         msg->logoff_url = NULL;
129
130         g_free(msg->access_procedure);
131         msg->access_procedure = NULL;
132
133         g_free(msg->access_location);
134         msg->access_location = NULL;
135
136         g_free(msg->location_name);
137         msg->location_name = NULL;
138 }
139
140 struct wispr_session {
141         GWeb *web;
142         GWebParser *parser;
143         guint request;
144         struct wispr_msg msg;
145         char *username;
146         char *password;
147         char *originurl;
148         char *formdata;
149 };
150
151 static gboolean execute_login(gpointer user_data);
152
153 static struct {
154         const char *str;
155         enum {
156                 WISPR_ELEMENT_NONE,
157                 WISPR_ELEMENT_ACCESS_PROCEDURE,
158                 WISPR_ELEMENT_ACCESS_LOCATION,
159                 WISPR_ELEMENT_LOCATION_NAME,
160                 WISPR_ELEMENT_LOGIN_URL,
161                 WISPR_ELEMENT_ABORT_LOGIN_URL,
162                 WISPR_ELEMENT_MESSAGE_TYPE,
163                 WISPR_ELEMENT_RESPONSE_CODE,
164                 WISPR_ELEMENT_NEXT_URL,
165                 WISPR_ELEMENT_DELAY,
166                 WISPR_ELEMENT_REPLY_MESSAGE,
167                 WISPR_ELEMENT_LOGIN_RESULTS_URL,
168                 WISPR_ELEMENT_LOGOFF_URL,
169         } element;
170 } wispr_element_map[] = {
171         { "AccessProcedure",    WISPR_ELEMENT_ACCESS_PROCEDURE  },
172         { "AccessLocation",     WISPR_ELEMENT_ACCESS_LOCATION   },
173         { "LocationName",       WISPR_ELEMENT_LOCATION_NAME     },
174         { "LoginURL",           WISPR_ELEMENT_LOGIN_URL         },
175         { "AbortLoginURL",      WISPR_ELEMENT_ABORT_LOGIN_URL   },
176         { "MessageType",        WISPR_ELEMENT_MESSAGE_TYPE      },
177         { "ResponseCode",       WISPR_ELEMENT_RESPONSE_CODE     },
178         { "NextURL",            WISPR_ELEMENT_NEXT_URL          },
179         { "Delay",              WISPR_ELEMENT_DELAY             },
180         { "ReplyMessage",       WISPR_ELEMENT_REPLY_MESSAGE     },
181         { "LoginResultsURL",    WISPR_ELEMENT_LOGIN_RESULTS_URL },
182         { "LogoffURL",          WISPR_ELEMENT_LOGOFF_URL        },
183         { NULL,                 WISPR_ELEMENT_NONE              },
184 };
185
186 static void start_element_handler(GMarkupParseContext *context,
187                                         const gchar *element_name,
188                                         const gchar **attribute_names,
189                                         const gchar **attribute_values,
190                                         gpointer user_data, GError **error)
191 {
192         struct wispr_msg *msg = user_data;
193
194         msg->current_element = element_name;
195 }
196
197 static void end_element_handler(GMarkupParseContext *context,
198                                         const gchar *element_name,
199                                         gpointer user_data, GError **error)
200 {
201         struct wispr_msg *msg = user_data;
202
203         msg->current_element = NULL;
204 }
205
206 static void text_handler(GMarkupParseContext *context,
207                                         const gchar *text, gsize text_len,
208                                         gpointer user_data, GError **error)
209 {
210         struct wispr_msg *msg = user_data;
211         int i;
212
213         if (msg->current_element == NULL)
214                 return;
215
216         for (i = 0; wispr_element_map[i].str; i++) {
217                 if (g_str_equal(wispr_element_map[i].str,
218                                         msg->current_element) == FALSE)
219                         continue;
220
221                 switch (wispr_element_map[i].element) {
222                 case WISPR_ELEMENT_NONE:
223                 case WISPR_ELEMENT_ACCESS_PROCEDURE:
224                         g_free(msg->access_procedure);
225                         msg->access_procedure = g_strdup(text);
226                         break;
227                 case WISPR_ELEMENT_ACCESS_LOCATION:
228                         g_free(msg->access_location);
229                         msg->access_location = g_strdup(text);
230                         break;
231                 case WISPR_ELEMENT_LOCATION_NAME:
232                         g_free(msg->location_name);
233                         msg->location_name = g_strdup(text);
234                         break;
235                 case WISPR_ELEMENT_LOGIN_URL:
236                         g_free(msg->login_url);
237                         msg->login_url = g_strdup(text);
238                         break;
239                 case WISPR_ELEMENT_ABORT_LOGIN_URL:
240                         g_free(msg->abort_login_url);
241                         msg->abort_login_url = g_strdup(text);
242                         break;
243                 case WISPR_ELEMENT_MESSAGE_TYPE:
244                         msg->message_type = atoi(text);
245                         break;
246                 case WISPR_ELEMENT_RESPONSE_CODE:
247                         msg->response_code = atoi(text);
248                         break;
249                 case WISPR_ELEMENT_NEXT_URL:
250                 case WISPR_ELEMENT_DELAY:
251                 case WISPR_ELEMENT_REPLY_MESSAGE:
252                 case WISPR_ELEMENT_LOGIN_RESULTS_URL:
253                         break;
254                 case WISPR_ELEMENT_LOGOFF_URL:
255                         g_free(msg->logoff_url);
256                         msg->logoff_url = g_strdup(text);
257                         break;
258                 }
259         }
260 }
261
262 static void error_handler(GMarkupParseContext *context,
263                                         GError *error, gpointer user_data)
264 {
265         struct wispr_msg *msg = user_data;
266
267         msg->has_error = TRUE;
268 }
269
270 static const GMarkupParser wispr_parser = {
271         start_element_handler,
272         end_element_handler,
273         text_handler,
274         NULL,
275         error_handler,
276 };
277
278 static void parser_callback(const char *str, gpointer user_data)
279 {
280         struct wispr_session *wispr = user_data;
281         GMarkupParseContext *context;
282         gboolean result;
283
284         //printf("%s\n", str);
285
286         context = g_markup_parse_context_new(&wispr_parser,
287                         G_MARKUP_TREAT_CDATA_AS_TEXT, &wispr->msg, NULL);
288
289         result = g_markup_parse_context_parse(context, str, strlen(str), NULL);
290         if (result == TRUE)
291                 result = g_markup_parse_context_end_parse(context, NULL);
292
293         g_markup_parse_context_free(context);
294 }
295
296 typedef void (*user_input_cb)(const char *value, gpointer user_data);
297
298 struct user_input_data {
299         GString *str;
300         user_input_cb cb;
301         gpointer user_data;
302         gboolean hidden;
303         int fd;
304         struct termios saved_termios;
305 };
306
307 static void user_callback(struct user_input_data *data)
308 {
309         char *value;
310         int len;
311
312         if (data->hidden == TRUE)
313                 len = write(data->fd, "\n", 1);
314
315         tcsetattr(data->fd, TCSADRAIN, &data->saved_termios);
316
317         close(data->fd);
318
319         value = g_string_free(data->str, FALSE);
320
321         if (data->cb)
322                 data->cb(value, data->user_data);
323
324         g_free(value);
325
326         g_free(data);
327 }
328
329 static gboolean keyboard_input(GIOChannel *channel, GIOCondition condition,
330                                                         gpointer user_data)
331 {
332         struct user_input_data *data = user_data;
333         char buf[1];
334         int len;
335
336         len = read(data->fd, buf, 1);
337
338         if (len != 1)
339                 return TRUE;
340
341         if (buf[0] == '\n') {
342                 user_callback(data);
343                 return FALSE;
344         }
345
346         g_string_append_c(data->str, buf[0]);
347
348         if (data->hidden == TRUE)
349                 len = write(data->fd, "*", 1);
350
351         return TRUE;
352 }
353
354 static gboolean user_input(const char *label, gboolean hidden,
355                                 user_input_cb func, gpointer user_data)
356 {
357         struct user_input_data *data;
358         struct termios new_termios;
359         GIOChannel *channel;
360         guint watch;
361         int len;
362
363         data = g_try_new0(struct user_input_data, 1);
364         if (data == NULL)
365                 return FALSE;
366
367         data->str = g_string_sized_new(32);
368         data->cb = func;
369         data->user_data = user_data;
370         data->hidden = hidden;
371
372         data->fd = open("/dev/tty", O_RDWR | O_NOCTTY);
373         if (data->fd < 0)
374                 goto error;
375
376         if (tcgetattr(data->fd, &data->saved_termios) < 0) {
377                 close(data->fd);
378                 goto error;
379         }
380
381         new_termios = data->saved_termios;
382         if (data->hidden == TRUE)
383                 new_termios.c_lflag &= ~(ICANON|ECHO);
384         else
385                 new_termios.c_lflag &= ~ICANON;
386         new_termios.c_cc[VMIN] = 1;
387         new_termios.c_cc[VTIME] = 0;
388
389         tcsetattr(data->fd, TCSADRAIN, &new_termios);
390
391         channel = g_io_channel_unix_new(data->fd);
392         g_io_channel_set_encoding(channel, NULL, NULL);
393         g_io_channel_set_buffered(channel, FALSE);
394         watch = g_io_add_watch(channel, G_IO_IN, keyboard_input, data);
395         g_io_channel_unref(channel);
396
397         if (watch == 0)
398                 goto error;
399
400         len = write(data->fd, label, strlen(label));
401         len = write(data->fd, ": ", 2);
402
403         return TRUE;
404
405 error:
406         g_string_free(data->str, TRUE);
407         g_free(data);
408
409         return FALSE;
410 }
411
412 static void password_callback(const char *value, gpointer user_data)
413 {
414         struct wispr_session *wispr = user_data;
415
416         g_free(wispr->password);
417         wispr->password = g_strdup(value);
418
419         printf("\n");
420
421         execute_login(wispr);
422 }
423
424 static void username_callback(const char *value, gpointer user_data)
425 {
426         struct wispr_session *wispr = user_data;
427
428         g_free(wispr->username);
429         wispr->username = g_strdup(value);
430
431         if (wispr->password == NULL) {
432                 user_input("Password", TRUE, password_callback, wispr);
433                 return;
434         }
435
436         printf("\n");
437
438         execute_login(wispr);
439 }
440
441 static gboolean wispr_input(const guint8 **data, gsize *length,
442                                                 gpointer user_data)
443 {
444         struct wispr_session *wispr = user_data;
445         GString *buf;
446         gsize count;
447
448         buf = g_string_sized_new(100);
449
450         g_string_append(buf, "button=Login&UserName=");
451         g_string_append_uri_escaped(buf, wispr->username, NULL, FALSE);
452         g_string_append(buf, "&Password=");
453         g_string_append_uri_escaped(buf, wispr->password, NULL, FALSE);
454         g_string_append(buf, "&FNAME=0&OriginatingServer=");
455         g_string_append_uri_escaped(buf, wispr->originurl, NULL, FALSE);
456
457         count = buf->len;
458
459         g_free(wispr->formdata);
460         wispr->formdata = g_string_free(buf, FALSE);
461
462         *data = (guint8 *) wispr->formdata;
463         *length = count;
464
465         return FALSE;
466 }
467
468 static gboolean wispr_result(GWebResult *result, gpointer user_data)
469 {
470         struct wispr_session *wispr = user_data;
471         const guint8 *chunk;
472         gsize length;
473         guint16 status;
474         gdouble elapsed;
475
476         g_web_result_get_chunk(result, &chunk, &length);
477
478         if (length > 0) {
479                 //printf("%s\n", (char *) chunk);
480                 g_web_parser_feed_data(wispr->parser, chunk, length);
481                 return TRUE;
482         }
483
484         g_web_parser_end_data(wispr->parser);
485
486         status = g_web_result_get_status(result);
487
488         g_print("status: %03u\n", status);
489
490         elapsed = g_timer_elapsed(timer, NULL);
491
492         g_print("elapse: %f seconds\n", elapsed);
493
494         if (wispr->msg.message_type < 0) {
495                 const char *redirect;
496
497                 if (status != 302)
498                         goto done;
499
500                 if (g_web_result_get_header(result, "Location",
501                                                         &redirect) == FALSE)
502                         goto done;
503
504                 printf("Redirect URL: %s\n", redirect);
505                 printf("\n");
506
507                 wispr->request = g_web_request_get(wispr->web, redirect,
508                                                         wispr_result, wispr);
509
510                 return FALSE;
511         }
512
513         printf("Message type: %s (%d)\n",
514                         message_type_to_string(wispr->msg.message_type),
515                                                 wispr->msg.message_type);
516         printf("Response code: %s (%d)\n",
517                         response_code_to_string(wispr->msg.response_code),
518                                                 wispr->msg.response_code);
519         if (wispr->msg.access_procedure != NULL)
520                 printf("Access procedure: %s\n", wispr->msg.access_procedure);
521         if (wispr->msg.access_location != NULL)
522                 printf("Access location: %s\n", wispr->msg.access_location);
523         if (wispr->msg.location_name != NULL)
524                 printf("Location name: %s\n", wispr->msg.location_name);
525         if (wispr->msg.login_url != NULL)
526                 printf("Login URL: %s\n", wispr->msg.login_url);
527         if (wispr->msg.abort_login_url != NULL)
528                 printf("Abort login URL: %s\n", wispr->msg.abort_login_url);
529         if (wispr->msg.logoff_url != NULL)
530                 printf("Logoff URL: %s\n", wispr->msg.logoff_url);
531         printf("\n");
532
533         if (status == 302 && wispr->msg.message_type == 100) {
534                 if (wispr->username == NULL) {
535                         user_input("Username", FALSE, username_callback, wispr);
536                         return FALSE;
537                 }
538
539                 if (wispr->password == NULL) {
540                         user_input("Password", TRUE, password_callback, wispr);
541                         return FALSE;
542                 }
543
544                 g_idle_add(execute_login, wispr);
545                 return FALSE;
546         } else if (status == 200 && (wispr->msg.message_type == 120 ||
547                                         wispr->msg.message_type == 140)) {
548                 int code = wispr->msg.response_code;
549                 printf("Login process: %s\n",
550                                         code == 50 ? "SUCCESS" : "FAILURE");
551         }
552
553 done:
554         g_main_loop_quit(main_loop);
555
556         return FALSE;
557 }
558
559 static gboolean execute_login(gpointer user_data)
560 {
561         struct wispr_session *wispr = user_data;
562
563         wispr->request = g_web_request_post(wispr->web, wispr->msg.login_url,
564                                         "application/x-www-form-urlencoded",
565                                         wispr_input, wispr_result, wispr);
566
567         wispr_msg_init(&wispr->msg);
568
569         return FALSE;
570 }
571
572 static gboolean option_debug = FALSE;
573 static gchar *option_nameserver = NULL;
574 static gchar *option_username = NULL;
575 static gchar *option_password = NULL;
576 static gchar *option_url = NULL;
577
578 static GOptionEntry options[] = {
579         { "debug", 'd', 0, G_OPTION_ARG_NONE, &option_debug,
580                                         "Enable debug output" },
581         { "nameserver", 'n', 0, G_OPTION_ARG_STRING, &option_nameserver,
582                                         "Specify nameserver", "ADDRESS" },
583         { "username", 'u', 0, G_OPTION_ARG_STRING, &option_username,
584                                         "Specify username", "USERNAME" },
585         { "password", 'p', 0, G_OPTION_ARG_STRING, &option_password,
586                                         "Specify password", "PASSWORD" },
587         { "url", 'U', 0, G_OPTION_ARG_STRING, &option_url,
588                                         "Specify arbitrary request", "URL" },
589         { NULL },
590 };
591
592 int main(int argc, char *argv[])
593 {
594         GOptionContext *context;
595         GError *error = NULL;
596         struct sigaction sa;
597         struct wispr_session wispr;
598         int index = 0;
599
600         context = g_option_context_new(NULL);
601         g_option_context_add_main_entries(context, options, NULL);
602
603         if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
604                 if (error != NULL) {
605                         g_printerr("%s\n", error->message);
606                         g_error_free(error);
607                 } else
608                         g_printerr("An unknown error occurred\n");
609                 return 1;
610         }
611
612         g_option_context_free(context);
613
614         memset(&wispr, 0, sizeof(wispr));
615         wispr_msg_init(&wispr.msg);
616
617         wispr.web = g_web_new(index);
618         if (wispr.web == NULL) {
619                 fprintf(stderr, "Failed to create web service\n");
620                 return 1;
621         }
622
623         if (option_debug == TRUE)
624                 g_web_set_debug(wispr.web, web_debug, "WEB");
625
626         main_loop = g_main_loop_new(NULL, FALSE);
627
628         if (option_nameserver != NULL) {
629                 g_web_add_nameserver(wispr.web, option_nameserver);
630                 g_free(option_nameserver);
631         }
632
633         g_web_set_accept(wispr.web, NULL);
634         g_web_set_user_agent(wispr.web, "SmartClient/%s wispr", VERSION);
635         g_web_set_close_connection(wispr.web, TRUE);
636
637         if (option_url == NULL)
638                 option_url = g_strdup(DEFAULT_URL);
639
640         wispr.username = option_username;
641         wispr.password = option_password;
642         wispr.originurl = option_url;
643
644         timer = g_timer_new();
645
646         wispr.parser = g_web_parser_new("<WISPAccessGatewayParam",
647                                                 "WISPAccessGatewayParam>",
648                                                 parser_callback, &wispr);
649
650         wispr.request = g_web_request_get(wispr.web, option_url,
651                                                         wispr_result, &wispr);
652
653         if (wispr.request == 0) {
654                 fprintf(stderr, "Failed to start request\n");
655                 return 1;
656         }
657
658         memset(&sa, 0, sizeof(sa));
659         sa.sa_handler = sig_term;
660         sigaction(SIGINT, &sa, NULL);
661         sigaction(SIGTERM, &sa, NULL);
662
663         g_main_loop_run(main_loop);
664
665         g_timer_destroy(timer);
666
667         if (wispr.request > 0)
668                 g_web_cancel_request(wispr.web, wispr.request);
669
670         g_web_parser_unref(wispr.parser);
671         g_web_unref(wispr.web);
672
673         g_main_loop_unref(main_loop);
674
675         g_free(wispr.username);
676         g_free(wispr.password);
677         g_free(wispr.originurl);
678
679         return 0;
680 }