Change the User-Agent field to Tizen
[platform/upstream/connman.git] / vpn / vpn-provider.c
1 /*
2  *
3  *  ConnMan VPN daemon
4  *
5  *  Copyright (C) 2012-2013  Intel Corporation. All rights reserved.
6  *  Copyright (C) 2019-2021  Jolla Ltd. All rights reserved.
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License version 2 as
10  *  published by the Free Software Foundation.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  *
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26
27 /*
28  * One hour difference in seconds between connections for checking whether to
29  * treat the authentication error as a real error or as a result of rapid
30  * transport change.
31  */
32 #define CONNECT_OK_DIFF         ((time_t)60*60)
33 #define AUTH_ERROR_LIMIT_DEFAULT        1
34
35 #define STATE_INTERVAL_DEFAULT          0
36
37 #define CONNMAN_STATE_ONLINE            "online"
38 #define CONNMAN_STATE_OFFLINE           "offline"
39 #define CONNMAN_STATE_READY             "ready"
40 #define CONNMAN_STATE_IDLE              "idle"
41
42 #include <errno.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <stdlib.h>
46 #include <gdbus.h>
47 #include <connman/log.h>
48 #include <gweb/gresolv.h>
49 #include <netdb.h>
50 #include <time.h>
51
52 #include "../src/connman.h"
53 #include "connman/agent.h"
54 #include "connman/vpn-dbus.h"
55 #include "vpn-provider.h"
56 #include "vpn.h"
57 #include "plugins/vpn.h"
58
59 static DBusConnection *connection;
60 static GHashTable *provider_hash;
61 static GSList *driver_list;
62 static int configuration_count;
63
64 struct vpn_route {
65         int family;
66         char *network;
67         char *netmask;
68         char *gateway;
69 };
70
71 struct vpn_setting {
72         bool hide_value;
73         bool immutable;
74         char *value;
75 };
76
77 struct vpn_provider {
78         int refcount;
79         int index;
80         int fd;
81         enum vpn_provider_state state;
82         char *path;
83         char *identifier;
84         char *name;
85         char *type;
86         char *host;
87         char *domain;
88         int family;
89         bool do_split_routing;
90         GHashTable *routes;
91         struct vpn_provider_driver *driver;
92         void *driver_data;
93         GHashTable *setting_strings;
94         GHashTable *user_routes;
95         GSList *user_networks;
96         GResolv *resolv;
97         char **host_ip;
98         struct vpn_ipconfig *ipconfig_ipv4;
99         struct vpn_ipconfig *ipconfig_ipv6;
100         char **nameservers;
101         guint notify_id;
102         char *config_file;
103         char *config_entry;
104         bool immutable;
105         struct connman_ipaddress *prev_ipv4_addr;
106         struct connman_ipaddress *prev_ipv6_addr;
107         void *plugin_data;
108         unsigned int do_connect_timeout;
109         unsigned int auth_error_counter;
110         unsigned int conn_error_counter;
111         unsigned int signal_watch;
112         unsigned int auth_error_limit;
113         time_t previous_connect_time;
114 };
115
116 struct vpn_provider_connect_data {
117         DBusConnection *conn;
118         DBusMessage *msg;
119         struct vpn_provider *provider;
120 };
121
122 static unsigned int get_connman_state_timeout;
123
124 static guint connman_signal_watch;
125 static guint connman_service_watch;
126
127 static bool connman_online;
128 static bool state_query_completed;
129
130 static void append_properties(DBusMessageIter *iter,
131                                 struct vpn_provider *provider);
132 static int vpn_provider_save(struct vpn_provider *provider);
133
134 static void get_connman_state(void);
135
136 static void set_state(const char *new_state)
137 {
138         if (!new_state || !*new_state)
139                 return;
140
141         DBG("old state %s new state %s",
142                                 connman_online ?
143                                 CONNMAN_STATE_ONLINE "/" CONNMAN_STATE_READY :
144                                 CONNMAN_STATE_OFFLINE "/" CONNMAN_STATE_IDLE,
145                                 new_state);
146
147         /* States "online" and "ready" mean connman is online */
148         if (!g_ascii_strcasecmp(new_state, CONNMAN_STATE_ONLINE) ||
149                         !g_ascii_strcasecmp(new_state, CONNMAN_STATE_READY))
150                 connman_online = true;
151         /* Everything else means connman is offline */
152         else
153                 connman_online = false;
154
155         DBG("set state %s connman_online=%s ", new_state,
156                                 connman_online ? "true" : "false");
157 }
158
159 static void free_route(gpointer data)
160 {
161         struct vpn_route *route = data;
162
163         g_free(route->network);
164         g_free(route->netmask);
165         g_free(route->gateway);
166
167         g_free(route);
168 }
169
170 static void free_setting(gpointer data)
171 {
172         struct vpn_setting *setting = data;
173
174         g_free(setting->value);
175         g_free(setting);
176 }
177
178 static void append_route(DBusMessageIter *iter, void *user_data)
179 {
180         struct vpn_route *route = user_data;
181         DBusMessageIter item;
182         int family = 0;
183
184         connman_dbus_dict_open(iter, &item);
185
186         if (!route)
187                 goto empty_dict;
188
189         if (route->family == AF_INET)
190                 family = 4;
191         else if (route->family == AF_INET6)
192                 family = 6;
193
194         if (family != 0)
195                 connman_dbus_dict_append_basic(&item, "ProtocolFamily",
196                                         DBUS_TYPE_INT32, &family);
197
198         if (route->network)
199                 connman_dbus_dict_append_basic(&item, "Network",
200                                         DBUS_TYPE_STRING, &route->network);
201
202         if (route->netmask)
203                 connman_dbus_dict_append_basic(&item, "Netmask",
204                                         DBUS_TYPE_STRING, &route->netmask);
205
206         if (route->gateway)
207                 connman_dbus_dict_append_basic(&item, "Gateway",
208                                         DBUS_TYPE_STRING, &route->gateway);
209
210 empty_dict:
211         connman_dbus_dict_close(iter, &item);
212 }
213
214 static void append_routes(DBusMessageIter *iter, void *user_data)
215 {
216         GHashTable *routes = user_data;
217         GHashTableIter hash;
218         gpointer value, key;
219
220         if (!routes) {
221                 append_route(iter, NULL);
222                 return;
223         }
224
225         g_hash_table_iter_init(&hash, routes);
226
227         while (g_hash_table_iter_next(&hash, &key, &value)) {
228                 DBusMessageIter dict;
229
230                 dbus_message_iter_open_container(iter, DBUS_TYPE_STRUCT, NULL,
231                                                 &dict);
232                 append_route(&dict, value);
233                 dbus_message_iter_close_container(iter, &dict);
234         }
235 }
236
237 static void send_routes(struct vpn_provider *provider, GHashTable *routes,
238                         const char *name)
239 {
240         connman_dbus_property_changed_array(provider->path,
241                                         VPN_CONNECTION_INTERFACE,
242                                         name,
243                                         DBUS_TYPE_DICT_ENTRY,
244                                         append_routes,
245                                         routes);
246 }
247
248 static int provider_routes_changed(struct vpn_provider *provider)
249 {
250         DBG("provider %p", provider);
251
252         send_routes(provider, provider->routes, "ServerRoutes");
253
254         return 0;
255 }
256
257 /*
258  * Sort vpn_route struct based on (similarly to the route key in hash table):
259  * 1) IP protocol number
260  * 2) Network addresses
261  * 3) Netmask addresses
262  * 4) Gateway addresses
263  */
264 static gint compare_route(gconstpointer a, gconstpointer b)
265 {
266         const struct vpn_route *route_a = a;
267         const struct vpn_route *route_b = b;
268         int difference;
269
270         /* If IP families differ, prefer IPv6 over IPv4 */
271         if (route_a->family != route_b->family) {
272                 if (route_a->family < route_b->family)
273                         return -1;
274
275                 if (route_a->family > route_b->family)
276                         return 1;
277         }
278
279         /* If networks differ, return  */
280         if ((difference = g_strcmp0(route_a->network, route_b->network)))
281                 return difference;
282
283         /* If netmasks differ, return. */
284         if ((difference = g_strcmp0(route_a->netmask, route_b->netmask)))
285                 return difference;
286
287         return g_strcmp0(route_a->gateway, route_b->gateway);
288 }
289
290 static GSList *read_route_dict(GSList *routes, DBusMessageIter *dicts)
291 {
292         DBusMessageIter dict, value, entry;
293         const char *network, *netmask, *gateway;
294         struct vpn_route *route;
295         int family, type;
296         const char *key;
297
298         dbus_message_iter_recurse(dicts, &entry);
299
300         network = netmask = gateway = NULL;
301         family = PF_UNSPEC;
302
303         while (dbus_message_iter_get_arg_type(&entry) == DBUS_TYPE_DICT_ENTRY) {
304
305                 dbus_message_iter_recurse(&entry, &dict);
306                 dbus_message_iter_get_basic(&dict, &key);
307
308                 dbus_message_iter_next(&dict);
309                 dbus_message_iter_recurse(&dict, &value);
310
311                 type = dbus_message_iter_get_arg_type(&value);
312
313                 switch (type) {
314                 case DBUS_TYPE_INT32:
315                         if (g_str_equal(key, "ProtocolFamily"))
316                                 dbus_message_iter_get_basic(&value, &family);
317                         break;
318
319                 case DBUS_TYPE_STRING:
320                         if (g_str_equal(key, "Network"))
321                                 dbus_message_iter_get_basic(&value, &network);
322                         else if (g_str_equal(key, "Netmask"))
323                                 dbus_message_iter_get_basic(&value, &netmask);
324                         else if (g_str_equal(key, "Gateway"))
325                                 dbus_message_iter_get_basic(&value, &gateway);
326                         break;
327                 }
328
329                 dbus_message_iter_next(&entry);
330         }
331
332         DBG("family %d network %s netmask %s gateway %s", family,
333                 network, netmask, gateway);
334
335         if (!network || !netmask) {
336                 DBG("Ignoring route as network/netmask is missing");
337                 return routes;
338         }
339
340         route = g_try_new(struct vpn_route, 1);
341         if (!route) {
342                 g_slist_free_full(routes, free_route);
343                 return NULL;
344         }
345
346         if (family == PF_UNSPEC) {
347                 family = connman_inet_check_ipaddress(network);
348                 if (family < 0) {
349                         DBG("Cannot get address family of %s (%d/%s)", network,
350                                 family, gai_strerror(family));
351
352                         g_free(route);
353                         return routes;
354                 }
355         } else {
356                 switch (family) {
357                 case '4':
358                 case 4:
359                         family = AF_INET;
360                         break;
361                 case '6':
362                 case 6:
363                         family = AF_INET6;
364                         break;
365                 default:
366                         family = PF_UNSPEC;
367                         break;
368                 }
369         }
370
371         route->family = family;
372         route->network = g_strdup(network);
373         route->netmask = g_strdup(netmask);
374         route->gateway = g_strdup(gateway);
375
376         routes = g_slist_insert_sorted(routes, route, compare_route);
377         return routes;
378 }
379
380 static GSList *get_user_networks(DBusMessageIter *array)
381 {
382         DBusMessageIter entry;
383         GSList *list = NULL;
384
385         while (dbus_message_iter_get_arg_type(array) == DBUS_TYPE_ARRAY) {
386
387                 dbus_message_iter_recurse(array, &entry);
388
389                 while (dbus_message_iter_get_arg_type(&entry) ==
390                                                         DBUS_TYPE_STRUCT) {
391                         DBusMessageIter dicts;
392
393                         dbus_message_iter_recurse(&entry, &dicts);
394
395                         while (dbus_message_iter_get_arg_type(&dicts) ==
396                                                         DBUS_TYPE_ARRAY) {
397
398                                 list = read_route_dict(list, &dicts);
399                                 dbus_message_iter_next(&dicts);
400                         }
401
402                         dbus_message_iter_next(&entry);
403                 }
404
405                 dbus_message_iter_next(array);
406         }
407
408         return list;
409 }
410
411 static void set_user_networks(struct vpn_provider *provider, GSList *networks)
412 {
413         GSList *list;
414
415         for (list = networks; list; list = g_slist_next(list)) {
416                 struct vpn_route *route = list->data;
417
418                 if (__vpn_provider_append_user_route(provider,
419                                         route->family, route->network,
420                                         route->netmask, route->gateway) != 0)
421                         break;
422         }
423 }
424
425 static void del_routes(struct vpn_provider *provider)
426 {
427         GHashTableIter hash;
428
429         g_hash_table_iter_init(&hash, provider->user_routes);
430         g_hash_table_remove_all(provider->user_routes);
431         g_slist_free_full(provider->user_networks, free_route);
432         provider->user_networks = NULL;
433 }
434
435 static void send_value(const char *path, const char *key, const char *value)
436 {
437         const char *empty = "";
438         const char *str;
439
440         if (value)
441                 str = value;
442         else
443                 str = empty;
444
445         connman_dbus_property_changed_basic(path,
446                                         VPN_CONNECTION_INTERFACE,
447                                         key,
448                                         DBUS_TYPE_STRING,
449                                         &str);
450 }
451
452 static void send_value_boolean(const char *path, const char *key,
453                                                         dbus_bool_t value)
454 {
455         connman_dbus_property_changed_basic(path,
456                                         VPN_CONNECTION_INTERFACE,
457                                         key,
458                                         DBUS_TYPE_BOOLEAN,
459                                         &value);
460 }
461
462 static gboolean provider_send_changed(gpointer data)
463 {
464         struct vpn_provider *provider = data;
465
466         provider_routes_changed(provider);
467
468         provider->notify_id = 0;
469
470         return FALSE;
471 }
472
473 static void provider_schedule_changed(struct vpn_provider *provider)
474 {
475         if (provider->notify_id != 0)
476                 g_source_remove(provider->notify_id);
477
478         provider->notify_id = g_timeout_add(100, provider_send_changed,
479                                                                 provider);
480 }
481
482 static DBusMessage *get_properties(DBusConnection *conn,
483                                         DBusMessage *msg, void *data)
484 {
485         struct vpn_provider *provider = data;
486         DBusMessage *reply;
487         DBusMessageIter array;
488
489         DBG("provider %p", provider);
490
491         reply = dbus_message_new_method_return(msg);
492         if (!reply)
493                 return NULL;
494
495         dbus_message_iter_init_append(reply, &array);
496
497         append_properties(&array, provider);
498
499         return reply;
500 }
501
502 /* True when lists are equal, false otherwise */
503 static bool compare_network_lists(GSList *a, GSList *b)
504 {
505         struct vpn_route *route_a, *route_b;
506         GSList *iter_a, *iter_b;
507
508         if (!a && !b)
509                 return true;
510
511         /*
512          * If either of lists is NULL or the lists are of different size, the
513          * lists are not equal.
514          */
515         if ((!a || !b) || (g_slist_length(a) != g_slist_length(b)))
516                 return false;
517
518         /* Routes are in sorted list so items can be compared in order. */
519         for (iter_a = a, iter_b = b; iter_a && iter_b;
520                                 iter_a = iter_a->next, iter_b = iter_b->next) {
521
522                 route_a = iter_a->data;
523                 route_b = iter_b->data;
524
525                 if (compare_route(route_a, route_b))
526                         return false;
527         }
528
529         return true;
530 }
531
532 static const char *bool2str(bool value)
533 {
534         return value ? "true" : "false";
535 }
536
537 static int set_provider_property(struct vpn_provider *provider,
538                         const char *name, DBusMessageIter *value, int type)
539 {
540         int err = 0;
541
542         DBG("provider %p", provider);
543
544         if (!provider || !name || !value)
545                 return -EINVAL;
546
547         if (g_str_equal(name, "UserRoutes")) {
548                 GSList *networks;
549
550                 if (type != DBUS_TYPE_ARRAY)
551                         return -EINVAL;
552
553                 networks = get_user_networks(value);
554
555                 if (compare_network_lists(provider->user_networks, networks)) {
556                         g_slist_free_full(networks, free_route);
557                         return -EALREADY;
558                 }
559
560                 del_routes(provider);
561                 provider->user_networks = networks;
562                 set_user_networks(provider, provider->user_networks);
563                 send_routes(provider, provider->user_routes, "UserRoutes");
564         } else if (g_str_equal(name, "SplitRouting")) {
565                 dbus_bool_t split_routing;
566
567                 if (type != DBUS_TYPE_BOOLEAN)
568                         return -EINVAL;
569
570                 dbus_message_iter_get_basic(value, &split_routing);
571
572                 DBG("property %s value %s ", name, bool2str(split_routing));
573                 vpn_provider_set_boolean(provider, name, split_routing, false);
574         } else {
575                 const char *str;
576
577                 if (type != DBUS_TYPE_STRING)
578                         return -EINVAL;
579
580                 dbus_message_iter_get_basic(value, &str);
581
582                 DBG("property %s value %s", name, str);
583
584                 /* Empty string clears the value, similar to ClearProperty. */
585                 err = vpn_provider_set_string(provider, name,
586                                         *str ? str : NULL);
587         }
588
589         return err;
590 }
591
592 static GString *append_to_gstring(GString *str, const char *value)
593 {
594         if (!str)
595                 return g_string_new(value);
596
597         g_string_append_printf(str, ",%s", value);
598
599         return str;
600 }
601
602 static DBusMessage *set_properties(DBusMessageIter *iter, DBusMessage *msg,
603                                                                 void *data)
604 {
605         struct vpn_provider *provider = data;
606         DBusMessageIter dict;
607         const char *key;
608         bool change = false;
609         GString *invalid = NULL;
610         GString *denied = NULL;
611         int type;
612         int err;
613
614         for (dbus_message_iter_recurse(iter, &dict);
615                                 dbus_message_iter_get_arg_type(&dict) ==
616                                 DBUS_TYPE_DICT_ENTRY;
617                                 dbus_message_iter_next(&dict)) {
618                 DBusMessageIter entry, value;
619
620                 dbus_message_iter_recurse(&dict, &entry);
621                 /*
622                  * Ignore invalid types in order to process all values in the
623                  * dict. If there is an invalid type in between the dict there
624                  * may already be changes on some values and breaking out here
625                  *  would have the provider in an inconsistent state, leaving
626                  * the rest, potentially correct property values untouched.
627                  */
628                 if (dbus_message_iter_get_arg_type(&entry) != DBUS_TYPE_STRING)
629                         continue;
630
631                 dbus_message_iter_get_basic(&entry, &key);
632
633                 DBG("key %s", key);
634
635                 dbus_message_iter_next(&entry);
636                 /* Ignore and report back all non variant types. */
637                 if (dbus_message_iter_get_arg_type(&entry)
638                                         != DBUS_TYPE_VARIANT) {
639                         invalid = append_to_gstring(invalid, key);
640                         continue;
641                 }
642
643                 dbus_message_iter_recurse(&entry, &value);
644
645                 type = dbus_message_iter_get_arg_type(&value);
646                 switch (type) {
647                 case DBUS_TYPE_STRING:
648                 case DBUS_TYPE_ARRAY:
649                 case DBUS_TYPE_BOOLEAN:
650                         break;
651                 default:
652                         /* Ignore and report back all invalid property types */
653                         invalid = append_to_gstring(invalid, key);
654                         continue;
655                 }
656
657                 err = set_provider_property(provider, key, &value, type);
658                 switch (err) {
659                 case 0:
660                         change = true;
661                         break;
662                 case -EINVAL:
663                         invalid = append_to_gstring(invalid, key);
664                         break;
665                 case -EPERM:
666                         denied = append_to_gstring(denied, key);
667                         break;
668                 }
669         }
670
671         if (change)
672                 vpn_provider_save(provider);
673
674         if (invalid || denied) {
675                 DBusMessage *error;
676                 char *invalid_str = g_string_free(invalid, FALSE);
677                 char *denied_str = g_string_free(denied, FALSE);
678
679                 /*
680                  * If there are both invalid and denied properties report
681                  * back invalid arguments. Add also the failed properties to
682                  * the error message.
683                  */
684                 error = g_dbus_create_error(msg, (invalid ?
685                                 CONNMAN_ERROR_INTERFACE ".InvalidProperty" :
686                                 CONNMAN_ERROR_INTERFACE ".PermissionDenied"),
687                                 "%s %s%s%s", (invalid ? "Invalid properties" :
688                                 "Permission denied"),
689                                 (invalid ? invalid_str : ""),
690                                 (invalid && denied ? "," : ""),
691                                 (denied ? denied_str : ""));
692
693                 g_free(invalid_str);
694                 g_free(denied_str);
695
696                 return error;
697         }
698
699         return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
700 }
701
702 static DBusMessage *set_property(DBusConnection *conn, DBusMessage *msg,
703                                                                 void *data)
704 {
705         struct vpn_provider *provider = data;
706         DBusMessageIter iter, value;
707         const char *name;
708         int type;
709         int err;
710
711         DBG("conn %p", conn);
712
713         if (provider->immutable)
714                 return __connman_error_not_supported(msg);
715
716         if (!dbus_message_iter_init(msg, &iter))
717                 return __connman_error_invalid_arguments(msg);
718
719         if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
720                 return __connman_error_invalid_arguments(msg);
721
722         dbus_message_iter_get_basic(&iter, &name);
723         dbus_message_iter_next(&iter);
724
725         if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
726                 return __connman_error_invalid_arguments(msg);
727
728         dbus_message_iter_recurse(&iter, &value);
729
730         type = dbus_message_iter_get_arg_type(&value);
731         if (type == DBUS_TYPE_ARRAY && g_str_equal(name, "Properties"))
732                 return set_properties(&value, msg, data);
733
734         err = set_provider_property(provider, name, &value, type);
735         switch (err) {
736         case 0:
737                 vpn_provider_save(provider);
738                 break;
739         case -EALREADY:
740                 break;
741         case -EINVAL:
742                 return __connman_error_invalid_property(msg);
743         default:
744                 return __connman_error_failed(msg, -err);
745         }
746
747         return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
748 }
749
750 static DBusMessage *clear_property(DBusConnection *conn, DBusMessage *msg,
751                                                                 void *data)
752 {
753         struct vpn_provider *provider = data;
754         const char *name;
755         bool change = false;
756         int err;
757
758         DBG("conn %p", conn);
759
760         if (provider->immutable)
761                 return __connman_error_not_supported(msg);
762
763         dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &name,
764                                                         DBUS_TYPE_INVALID);
765
766         if (g_str_equal(name, "UserRoutes")) {
767                 /*
768                  * If either user_routes or user_networks has any entries
769                  * there is a change that is to be written to settings file.
770                  */
771                 if (g_hash_table_size(provider->user_routes) ||
772                                 provider->user_networks)
773                         change = true;
774
775                 del_routes(provider);
776
777                 send_routes(provider, provider->user_routes, name);
778         } else if (vpn_provider_get_string(provider, name)) {
779                 err = vpn_provider_set_string(provider, name, NULL);
780                 switch (err) {
781                 case 0:
782                         change = true;
783                         /* fall through */
784                 case -EALREADY:
785                         break;
786                 case -EINVAL:
787                         return __connman_error_invalid_property(msg);
788                 default:
789                         return __connman_error_failed(msg, -err);
790                 }
791         } else {
792                 return __connman_error_invalid_property(msg);
793         }
794
795         if (change)
796                 vpn_provider_save(provider);
797
798         return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
799 }
800
801 static gboolean do_connect_timeout_function(gpointer data)
802 {
803         struct vpn_provider_connect_data *cdata = data;
804         struct vpn_provider *provider = cdata->provider;
805         int err;
806
807         DBG("");
808
809         /* Keep in main loop if connman is not online. */
810         if (!connman_online)
811                 return G_SOURCE_CONTINUE;
812
813         provider->do_connect_timeout = 0;
814         err = __vpn_provider_connect(provider, cdata->msg);
815
816         if (err < 0 && err != -EINPROGRESS) {
817                 g_dbus_send_message(cdata->conn,
818                                 __connman_error_failed(cdata->msg, -err));
819                 cdata->msg = NULL;
820         }
821
822         return G_SOURCE_REMOVE;
823 }
824
825 static void do_connect_timeout_free(gpointer data)
826 {
827         struct vpn_provider_connect_data *cdata = data;
828
829         if (cdata->msg)
830                 g_dbus_send_message(cdata->conn,
831                                 __connman_error_operation_aborted(cdata->msg));
832
833         dbus_connection_unref(cdata->conn);
834         g_free(data);
835 }
836
837 static void do_connect_later(struct vpn_provider *provider,
838                                         DBusConnection *conn, DBusMessage *msg)
839 {
840         struct vpn_provider_connect_data *cdata =
841                                 g_new0(struct vpn_provider_connect_data, 1);
842
843         cdata->conn = dbus_connection_ref(conn);
844         cdata->msg = dbus_message_ref(msg);
845         cdata->provider = provider;
846
847         if (provider->do_connect_timeout)
848                 g_source_remove(provider->do_connect_timeout);
849
850         provider->do_connect_timeout =
851                         g_timeout_add_seconds_full(G_PRIORITY_DEFAULT, 1,
852                                         do_connect_timeout_function, cdata,
853                                         do_connect_timeout_free);
854 }
855
856 static DBusMessage *do_connect(DBusConnection *conn, DBusMessage *msg,
857                                                                 void *data)
858 {
859         struct vpn_provider *provider = data;
860         int err;
861
862         DBG("conn %p provider %p", conn, provider);
863
864         if (!connman_online) {
865                 if (state_query_completed) {
866                         DBG("%s not started - ConnMan not online/ready",
867                                 provider->identifier);
868                         return __connman_error_failed(msg, ENOLINK);
869                 }
870
871                 DBG("%s start delayed - ConnMan state not queried",
872                         provider->identifier);
873                 do_connect_later(provider, conn, msg);
874                 return NULL;
875         }
876
877         /* Cancel delayed connection if connmand is online. */
878         if (provider->do_connect_timeout) {
879                 g_source_remove(provider->do_connect_timeout);
880                 provider->do_connect_timeout = 0;
881         }
882
883         err = __vpn_provider_connect(provider, msg);
884         if (err < 0 && err != -EINPROGRESS)
885                 return __connman_error_failed(msg, -err);
886
887         return NULL;
888 }
889
890 static DBusMessage *do_connect2(DBusConnection *conn, DBusMessage *msg,
891                                                                 void *data)
892 {
893         return do_connect(conn, msg, data);
894 }
895
896 static DBusMessage *do_disconnect(DBusConnection *conn, DBusMessage *msg,
897                                                                 void *data)
898 {
899         struct vpn_provider *provider = data;
900         int err;
901
902         DBG("conn %p provider %p", conn, provider);
903
904         err = __vpn_provider_disconnect(provider);
905         if (err < 0 && err != -EINPROGRESS)
906                 return __connman_error_failed(msg, -err);
907
908         return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
909 }
910
911 static const GDBusMethodTable connection_methods[] = {
912         { GDBUS_METHOD("GetProperties",
913                         NULL, GDBUS_ARGS({ "properties", "a{sv}" }),
914                         get_properties) },
915         { GDBUS_METHOD("SetProperty",
916                         GDBUS_ARGS({ "name", "s" }, { "value", "v" }),
917                         NULL, set_property) },
918         { GDBUS_METHOD("ClearProperty",
919                         GDBUS_ARGS({ "name", "s" }), NULL,
920                         clear_property) },
921         { GDBUS_ASYNC_METHOD("Connect", NULL, NULL, do_connect) },
922         { GDBUS_ASYNC_METHOD("Connect2",
923                         GDBUS_ARGS({ "dbus_sender", "s" }),
924                         NULL, do_connect2) },
925         { GDBUS_METHOD("Disconnect", NULL, NULL, do_disconnect) },
926         { },
927 };
928
929 static const GDBusSignalTable connection_signals[] = {
930         { GDBUS_SIGNAL("PropertyChanged",
931                         GDBUS_ARGS({ "name", "s" }, { "value", "v" })) },
932         { },
933 };
934
935 static void resolv_result(GResolvResultStatus status,
936                                         char **results, gpointer user_data)
937 {
938         struct vpn_provider *provider = user_data;
939
940         DBG("status %d", status);
941
942         if (status == G_RESOLV_RESULT_STATUS_SUCCESS && results &&
943                                                 g_strv_length(results) > 0)
944                 provider->host_ip = g_strdupv(results);
945
946         vpn_provider_unref(provider);
947
948         /* Remove the resolver here so that it will not be left
949          * hanging around and cause double free in unregister_provider()
950          */
951         g_resolv_unref(provider->resolv);
952         provider->resolv = NULL;
953 }
954
955 static void provider_resolv_host_addr(struct vpn_provider *provider)
956 {
957         if (!provider->host)
958                 return;
959
960         if (connman_inet_check_ipaddress(provider->host) > 0)
961                 return;
962
963         if (provider->host_ip)
964                 return;
965
966         /*
967          * If the hostname is not numeric, try to resolv it. We do not wait
968          * the result as it might take some time. We will get the result
969          * before VPN will feed routes to us because VPN client will need
970          * the IP address also before VPN connection can be established.
971          */
972         provider->resolv = g_resolv_new(0);
973         if (!provider->resolv) {
974                 DBG("Cannot resolv %s", provider->host);
975                 return;
976         }
977
978         DBG("Trying to resolv %s", provider->host);
979
980         vpn_provider_ref(provider);
981
982         g_resolv_lookup_hostname(provider->resolv, provider->host,
983                                 resolv_result, provider);
984 }
985
986 void __vpn_provider_append_properties(struct vpn_provider *provider,
987                                                         DBusMessageIter *iter)
988 {
989         dbus_bool_t split_routing;
990
991         if (provider->host)
992                 connman_dbus_dict_append_basic(iter, "Host",
993                                         DBUS_TYPE_STRING, &provider->host);
994
995         if (provider->domain)
996                 connman_dbus_dict_append_basic(iter, "Domain",
997                                         DBUS_TYPE_STRING, &provider->domain);
998
999         if (provider->type)
1000                 connman_dbus_dict_append_basic(iter, "Type", DBUS_TYPE_STRING,
1001                                                  &provider->type);
1002
1003         split_routing = provider->do_split_routing;
1004         connman_dbus_dict_append_basic(iter, "SplitRouting", DBUS_TYPE_BOOLEAN,
1005                                                         &split_routing);
1006 }
1007
1008 int __vpn_provider_append_user_route(struct vpn_provider *provider,
1009                                 int family, const char *network,
1010                                 const char *netmask, const char *gateway)
1011 {
1012         struct vpn_route *route;
1013         char *key = g_strdup_printf("%d/%s/%s/%s", family, network,
1014                                 netmask, gateway ? gateway : "");
1015
1016         DBG("family %d network %s netmask %s gw %s", family, network,
1017                                                         netmask, gateway);
1018
1019         route = g_hash_table_lookup(provider->user_routes, key);
1020         if (!route) {
1021                 route = g_try_new0(struct vpn_route, 1);
1022                 if (!route) {
1023                         connman_error("out of memory");
1024                         return -ENOMEM;
1025                 }
1026
1027                 route->family = family;
1028                 route->network = g_strdup(network);
1029                 route->netmask = g_strdup(netmask);
1030                 route->gateway = g_strdup(gateway);
1031
1032                 g_hash_table_replace(provider->user_routes, key, route);
1033         } else
1034                 g_free(key);
1035
1036         return 0;
1037 }
1038
1039 static struct vpn_route *get_route(char *route_str)
1040 {
1041         char **elems = g_strsplit(route_str, "/", 0);
1042         char *network, *netmask, *gateway, *family_str;
1043         int family = PF_UNSPEC;
1044         struct vpn_route *route = NULL;
1045
1046         if (!elems)
1047                 return NULL;
1048
1049         family_str = elems[0];
1050
1051         network = elems[1];
1052         if (!network || network[0] == '\0')
1053                 goto out;
1054
1055         netmask = elems[2];
1056         if (!netmask || netmask[0] == '\0')
1057                 goto out;
1058
1059         gateway = elems[3];
1060
1061         route = g_try_new0(struct vpn_route, 1);
1062         if (!route)
1063                 goto out;
1064
1065         if (family_str[0] == '\0' || atoi(family_str) == 0) {
1066                 family = PF_UNSPEC;
1067         } else {
1068                 switch (family_str[0]) {
1069                 case '4':
1070                         family = AF_INET;
1071                         break;
1072                 case '6':
1073                         family = AF_INET6;
1074                         break;
1075                 }
1076         }
1077
1078         if (g_strrstr(network, ":")) {
1079                 if (family != PF_UNSPEC && family != AF_INET6)
1080                         DBG("You have IPv6 address but you have non IPv6 route");
1081         } else if (g_strrstr(network, ".")) {
1082                 if (family != PF_UNSPEC && family != AF_INET)
1083                         DBG("You have IPv4 address but you have non IPv4 route");
1084
1085                 if (!g_strrstr(netmask, ".")) {
1086                         /* We have netmask length */
1087                         in_addr_t addr;
1088                         struct in_addr netmask_in;
1089                         unsigned char prefix_len = 32;
1090                         char *ptr;
1091                         long int value = strtol(netmask, &ptr, 10);
1092
1093                         if (ptr != netmask && *ptr == '\0' && value <= 32)
1094                                 prefix_len = value;
1095
1096                         addr = 0xffffffff << (32 - prefix_len);
1097                         netmask_in.s_addr = htonl(addr);
1098                         netmask = inet_ntoa(netmask_in);
1099
1100                         DBG("network %s netmask %s", network, netmask);
1101                 }
1102         }
1103
1104         if (family == PF_UNSPEC) {
1105                 family = connman_inet_check_ipaddress(network);
1106                 if (family < 0 || family == PF_UNSPEC)
1107                         goto out;
1108         }
1109
1110         route->family = family;
1111         route->network = g_strdup(network);
1112         route->netmask = g_strdup(netmask);
1113         route->gateway = g_strdup(gateway);
1114
1115 out:
1116         g_strfreev(elems);
1117         return route;
1118 }
1119
1120 static GSList *get_routes(gchar **networks)
1121 {
1122         struct vpn_route *route;
1123         GSList *routes = NULL;
1124         int i;
1125
1126         for (i = 0; networks[i]; i++) {
1127                 route = get_route(networks[i]);
1128                 if (route)
1129                         routes = g_slist_prepend(routes, route);
1130         }
1131
1132         return routes;
1133 }
1134
1135 static int provider_load_from_keyfile(struct vpn_provider *provider,
1136                 GKeyFile *keyfile)
1137 {
1138         gsize idx;
1139         gchar **settings;
1140         gchar *key, *value;
1141         gsize length, num_user_networks;
1142         gchar **networks = NULL;
1143
1144         settings = g_key_file_get_keys(keyfile, provider->identifier, &length,
1145                                 NULL);
1146         if (!settings) {
1147                 g_key_file_free(keyfile);
1148                 return -ENOENT;
1149         }
1150
1151         for (idx = 0; idx < length; idx++) {
1152                 key = settings[idx];
1153                 if (!key)
1154                         continue;
1155
1156                 if (g_str_equal(key, "Networks")) {
1157                         networks = __vpn_config_get_string_list(keyfile,
1158                                                 provider->identifier,key,
1159                                                 &num_user_networks, NULL);
1160                         provider->user_networks = get_routes(networks);
1161                 } else {
1162                         value = __vpn_config_get_string(keyfile,
1163                                                 provider->identifier, key,
1164                                                 NULL);
1165
1166                         vpn_provider_set_string(provider, key, value);
1167                         g_free(value);
1168                 }
1169         }
1170
1171         g_strfreev(settings);
1172         g_strfreev(networks);
1173
1174         if (provider->user_networks)
1175                 set_user_networks(provider, provider->user_networks);
1176
1177         return 0;
1178 }
1179
1180
1181 static int vpn_provider_load(struct vpn_provider *provider)
1182 {
1183         GKeyFile *keyfile;
1184
1185         DBG("provider %p", provider);
1186
1187         keyfile = __connman_storage_load_provider(provider->identifier);
1188         if (!keyfile)
1189                 return -ENOENT;
1190
1191         provider_load_from_keyfile(provider, keyfile);
1192
1193         g_key_file_free(keyfile);
1194         return 0;
1195 }
1196
1197 static gchar **create_network_list(GSList *networks, gsize *count)
1198 {
1199         GSList *list;
1200         gchar **result = NULL;
1201         gchar **prev_result;
1202         unsigned int num_elems = 0;
1203
1204         for (list = networks; list; list = g_slist_next(list)) {
1205                 struct vpn_route *route = list->data;
1206                 int family;
1207
1208                 prev_result = result;
1209                 result = g_try_realloc(result,
1210                                 (num_elems + 1) * sizeof(gchar *));
1211                 if (!result) {
1212                         g_free(prev_result);
1213                         return NULL;
1214                 }
1215
1216                 switch (route->family) {
1217                 case AF_INET:
1218                         family = 4;
1219                         break;
1220                 case AF_INET6:
1221                         family = 6;
1222                         break;
1223                 default:
1224                         family = 0;
1225                         break;
1226                 }
1227
1228                 result[num_elems] = g_strdup_printf("%d/%s/%s/%s",
1229                                 family, route->network, route->netmask,
1230                                 !route->gateway ? "" : route->gateway);
1231
1232                 num_elems++;
1233         }
1234
1235         prev_result = result;
1236         result = g_try_realloc(result, (num_elems + 1) * sizeof(gchar *));
1237         if (!result) {
1238                 g_free(prev_result);
1239                 return NULL;
1240         }
1241
1242         result[num_elems] = NULL;
1243         *count = num_elems;
1244         return result;
1245 }
1246
1247 static void reset_error_counters(struct vpn_provider *provider)
1248 {
1249         if (!provider)
1250                 return;
1251
1252         DBG("provider %p", provider);
1253
1254         provider->auth_error_counter = provider->conn_error_counter = 0;
1255 }
1256
1257 static int vpn_provider_save(struct vpn_provider *provider)
1258 {
1259         GKeyFile *keyfile;
1260         const char *value;
1261
1262         DBG("provider %p immutable %s", provider,
1263                                         provider->immutable ? "yes" : "no");
1264
1265         reset_error_counters(provider);
1266
1267         if (provider->state == VPN_PROVIDER_STATE_FAILURE)
1268                 vpn_provider_set_state(provider, VPN_PROVIDER_STATE_IDLE);
1269
1270         if (provider->immutable) {
1271                 /*
1272                  * Do not save providers that are provisioned via .config
1273                  * file.
1274                  */
1275                 return -EPERM;
1276         }
1277
1278         keyfile = g_key_file_new();
1279         if (!keyfile)
1280                 return -ENOMEM;
1281
1282         g_key_file_set_string(keyfile, provider->identifier,
1283                         "Name", provider->name);
1284         g_key_file_set_string(keyfile, provider->identifier,
1285                         "Type", provider->type);
1286         g_key_file_set_string(keyfile, provider->identifier,
1287                         "Host", provider->host);
1288         g_key_file_set_string(keyfile, provider->identifier,
1289                         "VPN.Domain", provider->domain);
1290
1291         value = vpn_provider_get_string(provider, "AuthErrorLimit");
1292         if (value)
1293                 g_key_file_set_string(keyfile, provider->identifier,
1294                                                 "AuthErrorLimit", value);
1295
1296         if (provider->user_networks) {
1297                 gchar **networks;
1298                 gsize network_count;
1299
1300                 networks = create_network_list(provider->user_networks,
1301                                                         &network_count);
1302                 if (networks) {
1303                         g_key_file_set_string_list(keyfile,
1304                                                 provider->identifier,
1305                                                 "Networks",
1306                                                 (const gchar ** const)networks,
1307                                                 network_count);
1308                         g_strfreev(networks);
1309                 }
1310         }
1311
1312         if (provider->config_file && strlen(provider->config_file) > 0)
1313                 g_key_file_set_string(keyfile, provider->identifier,
1314                                 "Config.file", provider->config_file);
1315
1316         if (provider->config_entry &&
1317                                         strlen(provider->config_entry) > 0)
1318                 g_key_file_set_string(keyfile, provider->identifier,
1319                                 "Config.ident", provider->config_entry);
1320
1321         if (provider->driver && provider->driver->save)
1322                 provider->driver->save(provider, keyfile);
1323
1324         __connman_storage_save_provider(keyfile, provider->identifier);
1325         g_key_file_free(keyfile);
1326
1327         return 0;
1328 }
1329
1330 struct vpn_provider *__vpn_provider_lookup(const char *identifier)
1331 {
1332         struct vpn_provider *provider = NULL;
1333
1334         provider = g_hash_table_lookup(provider_hash, identifier);
1335
1336         return provider;
1337 }
1338
1339 static bool match_driver(struct vpn_provider *provider,
1340                                 struct vpn_provider_driver *driver)
1341 {
1342         if (g_strcmp0(driver->name, provider->type) == 0)
1343                 return true;
1344
1345         return false;
1346 }
1347
1348 static int provider_probe(struct vpn_provider *provider)
1349 {
1350         GSList *list;
1351
1352         DBG("provider %p driver %p name %s", provider, provider->driver,
1353                                                 provider->name);
1354
1355         if (provider->driver)
1356                 return -EALREADY;
1357
1358         for (list = driver_list; list; list = list->next) {
1359                 struct vpn_provider_driver *driver = list->data;
1360
1361                 if (!match_driver(provider, driver))
1362                         continue;
1363
1364                 DBG("driver %p name %s", driver, driver->name);
1365
1366                 if (driver->probe && driver->probe(provider) == 0) {
1367                         provider->driver = driver;
1368                         break;
1369                 }
1370         }
1371
1372         if (!provider->driver)
1373                 return -ENODEV;
1374
1375         return 0;
1376 }
1377
1378 static void provider_remove(struct vpn_provider *provider)
1379 {
1380         if (provider->driver) {
1381                 provider->driver->remove(provider);
1382                 provider->driver = NULL;
1383         }
1384 }
1385
1386 static int provider_register(struct vpn_provider *provider)
1387 {
1388         return provider_probe(provider);
1389 }
1390
1391 static void provider_unregister(struct vpn_provider *provider)
1392 {
1393         provider_remove(provider);
1394 }
1395
1396 struct vpn_provider *
1397 vpn_provider_ref_debug(struct vpn_provider *provider,
1398                         const char *file, int line, const char *caller)
1399 {
1400         DBG("%p ref %d by %s:%d:%s()", provider, provider->refcount + 1,
1401                 file, line, caller);
1402
1403         __sync_fetch_and_add(&provider->refcount, 1);
1404
1405         return provider;
1406 }
1407
1408 static void provider_destruct(struct vpn_provider *provider)
1409 {
1410         DBG("provider %p", provider);
1411
1412         if (provider->do_connect_timeout)
1413                 g_source_remove(provider->do_connect_timeout);
1414
1415         if (provider->notify_id != 0)
1416                 g_source_remove(provider->notify_id);
1417
1418         g_free(provider->name);
1419         g_free(provider->type);
1420         g_free(provider->host);
1421         g_free(provider->domain);
1422         g_free(provider->identifier);
1423         g_free(provider->path);
1424         g_slist_free_full(provider->user_networks, free_route);
1425         g_strfreev(provider->nameservers);
1426         g_hash_table_destroy(provider->routes);
1427         g_hash_table_destroy(provider->user_routes);
1428         g_hash_table_destroy(provider->setting_strings);
1429         if (provider->resolv) {
1430                 g_resolv_unref(provider->resolv);
1431                 provider->resolv = NULL;
1432         }
1433         __vpn_ipconfig_unref(provider->ipconfig_ipv4);
1434         __vpn_ipconfig_unref(provider->ipconfig_ipv6);
1435
1436         g_strfreev(provider->host_ip);
1437         g_free(provider->config_file);
1438         g_free(provider->config_entry);
1439         connman_ipaddress_free(provider->prev_ipv4_addr);
1440         connman_ipaddress_free(provider->prev_ipv6_addr);
1441         g_free(provider);
1442 }
1443
1444 void vpn_provider_unref_debug(struct vpn_provider *provider,
1445                                 const char *file, int line, const char *caller)
1446 {
1447         DBG("%p ref %d by %s:%d:%s()", provider, provider->refcount - 1,
1448                 file, line, caller);
1449
1450         if (__sync_fetch_and_sub(&provider->refcount, 1) != 1)
1451                 return;
1452
1453         provider_remove(provider);
1454
1455         provider_destruct(provider);
1456 }
1457
1458 static void configuration_count_add(void)
1459 {
1460         DBG("count %d", configuration_count + 1);
1461
1462         __sync_fetch_and_add(&configuration_count, 1);
1463 }
1464
1465 static void configuration_count_del(void)
1466 {
1467         DBG("count %d", configuration_count - 1);
1468
1469         if (__sync_fetch_and_sub(&configuration_count, 1) != 1)
1470                 return;
1471 }
1472
1473 int __vpn_provider_disconnect(struct vpn_provider *provider)
1474 {
1475         int err;
1476
1477         DBG("provider %p", provider);
1478
1479         if (provider->driver && provider->driver->disconnect)
1480                 err = provider->driver->disconnect(provider);
1481         else
1482                 return -EOPNOTSUPP;
1483
1484         if (err == -EINPROGRESS)
1485                 vpn_provider_set_state(provider, VPN_PROVIDER_STATE_CONNECT);
1486
1487         return err;
1488 }
1489
1490 static void connect_cb(struct vpn_provider *provider, void *user_data,
1491                                                                 int error)
1492 {
1493         DBusMessage *pending = user_data;
1494
1495         DBG("provider %p user %p error %d", provider, user_data, error);
1496
1497         if (error != 0) {
1498                 DBusMessage *reply = __connman_error_failed(pending, error);
1499                 if (reply)
1500                         g_dbus_send_message(connection, reply);
1501
1502                 switch (error) {
1503                 case EACCES:
1504                         vpn_provider_indicate_error(provider,
1505                                                 VPN_PROVIDER_ERROR_AUTH_FAILED);
1506                         break;
1507                 case ENOENT:
1508                         /*
1509                          * No reply, disconnect called by connmand because of
1510                          * connection timeout.
1511                          */
1512                         break;
1513                 case ENOMSG:
1514                         /* fall through */
1515                 case ETIMEDOUT:
1516                         /* No reply or timed out -> cancel the agent request */
1517                         connman_agent_cancel(provider);
1518                         vpn_provider_indicate_error(provider,
1519                                                 VPN_PROVIDER_ERROR_UNKNOWN);
1520                         break;
1521                 case ECANCELED:
1522                         /* fall through */
1523                 case ECONNABORTED:
1524                         /*
1525                          * This can be called in other situations than when
1526                          * VPN agent error checker is called. In such case
1527                          * react to both ECONNABORTED and ECANCELED as if the
1528                          * connection was called to terminate and do full
1529                          * disconnect -> idle cycle when being connected or
1530                          * ready. Setting the state also using the driver
1531                          * callback (vpn_set_state()) ensures that the driver is
1532                          * being disconnected as well and eventually the vpn
1533                          * process gets killed and vpn_died() is called to make
1534                          * the provider back to idle state.
1535                          */
1536                         if (provider->state == VPN_PROVIDER_STATE_CONNECT ||
1537                                                 provider->state ==
1538                                                 VPN_PROVIDER_STATE_READY) {
1539                                 if (provider->driver->set_state)
1540                                         provider->driver->set_state(provider,
1541                                                 VPN_PROVIDER_STATE_DISCONNECT);
1542
1543                                 vpn_provider_set_state(provider,
1544                                                 VPN_PROVIDER_STATE_DISCONNECT);
1545                         }
1546                         break;
1547                 default:
1548                         vpn_provider_indicate_error(provider,
1549                                         VPN_PROVIDER_ERROR_CONNECT_FAILED);
1550                         vpn_provider_set_state(provider,
1551                                         VPN_PROVIDER_STATE_FAILURE);
1552                 }
1553         } else {
1554                 reset_error_counters(provider);
1555                 g_dbus_send_reply(connection, pending, DBUS_TYPE_INVALID);
1556         }
1557
1558         dbus_message_unref(pending);
1559 }
1560
1561 int __vpn_provider_connect(struct vpn_provider *provider, DBusMessage *msg)
1562 {
1563         DBusMessage *reply;
1564         int err;
1565
1566         DBG("provider %p state %d", provider, provider->state);
1567
1568         switch (provider->state) {
1569         /*
1570          * When previous connection has failed change state to idle and let
1571          * the connmand to process this information as well. Return -EINPROGRESS
1572          * to indicate that transition is in progress and next connection
1573          * attempt will continue as normal.
1574          */
1575         case VPN_PROVIDER_STATE_FAILURE:
1576                 if (provider->driver && provider->driver->set_state)
1577                         provider->driver->set_state(provider,
1578                                                 VPN_PROVIDER_STATE_IDLE);
1579
1580                 vpn_provider_set_state(provider, VPN_PROVIDER_STATE_IDLE);
1581                 /* fall through */
1582         /*
1583          * If re-using a provider and it is being disconnected let it finish
1584          * the disconnect process in order to let vpn.c:vpn_died() to get
1585          * processed and everything cleaned up. Otherwise the reference
1586          * counters are not decreased properly causing the previous interface
1587          * being left up and its routes will remain in routing table. Return
1588          * -EINPROGRESS to indicate that transition is in progress.
1589          */
1590         case VPN_PROVIDER_STATE_DISCONNECT:
1591                 /*
1592                  * Failure transition or disconnecting does not yield a
1593                  * message to be sent. Send in progress message to avoid
1594                  * D-Bus LimitsExceeded error message.
1595                  */
1596                 reply = __connman_error_in_progress(msg);
1597                 if (reply)
1598                         g_dbus_send_message(connection, reply);
1599
1600                 return -EINPROGRESS;
1601         case VPN_PROVIDER_STATE_UNKNOWN:
1602         case VPN_PROVIDER_STATE_IDLE:
1603         case VPN_PROVIDER_STATE_CONNECT:
1604         case VPN_PROVIDER_STATE_READY:
1605                 break;
1606         }
1607
1608         if (provider->driver && provider->driver->connect) {
1609                 const char *dbus_sender = dbus_message_get_sender(msg);
1610
1611                 dbus_message_ref(msg);
1612
1613                 if (dbus_message_has_signature(msg,
1614                                                 DBUS_TYPE_STRING_AS_STRING)) {
1615                         const char *sender = NULL;
1616
1617                         dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING,
1618                                         &sender, DBUS_TYPE_INVALID);
1619                         if (sender && sender[0])
1620                                 dbus_sender = sender;
1621                 }
1622
1623                 err = provider->driver->connect(provider, connect_cb,
1624                                                 dbus_sender, msg);
1625         } else
1626                 return -EOPNOTSUPP;
1627
1628         if (err == -EINPROGRESS)
1629                 vpn_provider_set_state(provider, VPN_PROVIDER_STATE_CONNECT);
1630
1631         return err;
1632 }
1633
1634 static void connection_removed_signal(struct vpn_provider *provider)
1635 {
1636         DBusMessage *signal;
1637         DBusMessageIter iter;
1638
1639         signal = dbus_message_new_signal(VPN_MANAGER_PATH,
1640                         VPN_MANAGER_INTERFACE, "ConnectionRemoved");
1641         if (!signal)
1642                 return;
1643
1644         dbus_message_iter_init_append(signal, &iter);
1645         dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH,
1646                                                         &provider->path);
1647         dbus_connection_send(connection, signal, NULL);
1648         dbus_message_unref(signal);
1649 }
1650
1651 static char *get_ident(const char *path)
1652 {
1653         char *pos;
1654
1655         if (*path != '/')
1656                 return NULL;
1657
1658         pos = strrchr(path, '/');
1659         if (!pos)
1660                 return NULL;
1661
1662         return pos + 1;
1663 }
1664
1665 int __vpn_provider_remove(const char *path)
1666 {
1667         struct vpn_provider *provider;
1668         char *ident;
1669
1670         DBG("path %s", path);
1671
1672         ident = get_ident(path);
1673
1674         provider = __vpn_provider_lookup(ident);
1675         if (provider)
1676                 return __vpn_provider_delete(provider);
1677
1678         return -ENXIO;
1679 }
1680
1681 int __vpn_provider_delete(struct vpn_provider *provider)
1682 {
1683         DBG("Deleting VPN %s", provider->identifier);
1684
1685         connection_removed_signal(provider);
1686
1687         provider_unregister(provider);
1688
1689         __connman_storage_remove_provider(provider->identifier);
1690
1691         g_hash_table_remove(provider_hash, provider->identifier);
1692
1693         return 0;
1694 }
1695
1696 static void append_ipv4(DBusMessageIter *iter, void *user_data)
1697 {
1698         struct vpn_provider *provider = user_data;
1699         const char *address, *gateway, *peer;
1700
1701         address = __vpn_ipconfig_get_local(provider->ipconfig_ipv4);
1702         if (address) {
1703                 in_addr_t addr;
1704                 struct in_addr netmask;
1705                 char *mask;
1706                 int prefixlen;
1707
1708                 prefixlen = __vpn_ipconfig_get_prefixlen(
1709                                                 provider->ipconfig_ipv4);
1710
1711                 addr = 0xffffffff << (32 - prefixlen);
1712                 netmask.s_addr = htonl(addr);
1713                 mask = inet_ntoa(netmask);
1714
1715                 connman_dbus_dict_append_basic(iter, "Address",
1716                                                 DBUS_TYPE_STRING, &address);
1717
1718                 connman_dbus_dict_append_basic(iter, "Netmask",
1719                                                 DBUS_TYPE_STRING, &mask);
1720         }
1721
1722         gateway = __vpn_ipconfig_get_gateway(provider->ipconfig_ipv4);
1723         if (gateway)
1724                 connman_dbus_dict_append_basic(iter, "Gateway",
1725                                                 DBUS_TYPE_STRING, &gateway);
1726
1727         peer = __vpn_ipconfig_get_peer(provider->ipconfig_ipv4);
1728         if (peer)
1729                 connman_dbus_dict_append_basic(iter, "Peer",
1730                                                 DBUS_TYPE_STRING, &peer);
1731 }
1732
1733 static void append_ipv6(DBusMessageIter *iter, void *user_data)
1734 {
1735         struct vpn_provider *provider = user_data;
1736         const char *address, *gateway, *peer;
1737
1738         address = __vpn_ipconfig_get_local(provider->ipconfig_ipv6);
1739         if (address) {
1740                 unsigned char prefixlen;
1741
1742                 connman_dbus_dict_append_basic(iter, "Address",
1743                                                 DBUS_TYPE_STRING, &address);
1744
1745                 prefixlen = __vpn_ipconfig_get_prefixlen(
1746                                                 provider->ipconfig_ipv6);
1747
1748                 connman_dbus_dict_append_basic(iter, "PrefixLength",
1749                                                 DBUS_TYPE_BYTE, &prefixlen);
1750         }
1751
1752         gateway = __vpn_ipconfig_get_gateway(provider->ipconfig_ipv6);
1753         if (gateway)
1754                 connman_dbus_dict_append_basic(iter, "Gateway",
1755                                                 DBUS_TYPE_STRING, &gateway);
1756
1757         peer = __vpn_ipconfig_get_peer(provider->ipconfig_ipv6);
1758         if (peer)
1759                 connman_dbus_dict_append_basic(iter, "Peer",
1760                                                 DBUS_TYPE_STRING, &peer);
1761 }
1762
1763 static const char *state2string(enum vpn_provider_state state)
1764 {
1765         switch (state) {
1766         case VPN_PROVIDER_STATE_UNKNOWN:
1767                 break;
1768         case VPN_PROVIDER_STATE_IDLE:
1769                 return "idle";
1770         case VPN_PROVIDER_STATE_CONNECT:
1771                 return "configuration";
1772         case VPN_PROVIDER_STATE_READY:
1773                 return "ready";
1774         case VPN_PROVIDER_STATE_DISCONNECT:
1775                 return "disconnect";
1776         case VPN_PROVIDER_STATE_FAILURE:
1777                 return "failure";
1778         }
1779
1780         return NULL;
1781 }
1782
1783 static void append_nameservers(DBusMessageIter *iter, char **servers)
1784 {
1785         int i;
1786
1787         DBG("%p", servers);
1788
1789         for (i = 0; servers[i]; i++) {
1790                 DBG("servers[%d] %s", i, servers[i]);
1791                 dbus_message_iter_append_basic(iter,
1792                                         DBUS_TYPE_STRING, &servers[i]);
1793         }
1794 }
1795
1796 static void append_dns(DBusMessageIter *iter, void *user_data)
1797 {
1798         struct vpn_provider *provider = user_data;
1799
1800         if (provider->nameservers)
1801                 append_nameservers(iter, provider->nameservers);
1802 }
1803
1804 static time_t get_uptime(void)
1805 {
1806         struct timespec t = { 0 };
1807
1808         if (clock_gettime(CLOCK_BOOTTIME, &t) == -1) {
1809                 connman_warn("clock_gettime() error %d, uptime failed", errno);
1810                 return 0;
1811         }
1812
1813         return t.tv_sec;
1814 }
1815
1816 static int provider_indicate_state(struct vpn_provider *provider,
1817                                 enum vpn_provider_state state)
1818 {
1819         const char *str;
1820         enum vpn_provider_state old_state;
1821
1822         str = state2string(state);
1823         DBG("provider %p state %s/%d", provider, str, state);
1824         if (!str)
1825                 return -EINVAL;
1826
1827         old_state = provider->state;
1828         provider->state = state;
1829
1830         if (state == VPN_PROVIDER_STATE_READY) {
1831                 provider->previous_connect_time = get_uptime();
1832
1833                 connman_dbus_property_changed_basic(provider->path,
1834                                         VPN_CONNECTION_INTERFACE, "Index",
1835                                         DBUS_TYPE_INT32, &provider->index);
1836
1837                 if (provider->family == AF_INET)
1838                         connman_dbus_property_changed_dict(provider->path,
1839                                         VPN_CONNECTION_INTERFACE, "IPv4",
1840                                         append_ipv4, provider);
1841                 else if (provider->family == AF_INET6)
1842                         connman_dbus_property_changed_dict(provider->path,
1843                                         VPN_CONNECTION_INTERFACE, "IPv6",
1844                                         append_ipv6, provider);
1845
1846                 connman_dbus_property_changed_array(provider->path,
1847                                                 VPN_CONNECTION_INTERFACE,
1848                                                 "Nameservers",
1849                                                 DBUS_TYPE_STRING,
1850                                                 append_dns, provider);
1851
1852                 if (provider->domain)
1853                         connman_dbus_property_changed_basic(provider->path,
1854                                                 VPN_CONNECTION_INTERFACE,
1855                                                 "Domain",
1856                                                 DBUS_TYPE_STRING,
1857                                                 &provider->domain);
1858         }
1859
1860         if (old_state != state)
1861                 connman_dbus_property_changed_basic(provider->path,
1862                                         VPN_CONNECTION_INTERFACE, "State",
1863                                         DBUS_TYPE_STRING, &str);
1864
1865         return 0;
1866 }
1867
1868 static void append_state(DBusMessageIter *iter,
1869                                         struct vpn_provider *provider)
1870 {
1871         char *str;
1872
1873         switch (provider->state) {
1874         case VPN_PROVIDER_STATE_UNKNOWN:
1875         case VPN_PROVIDER_STATE_IDLE:
1876                 str = "idle";
1877                 break;
1878         case VPN_PROVIDER_STATE_CONNECT:
1879                 str = "configuration";
1880                 break;
1881         case VPN_PROVIDER_STATE_READY:
1882                 str = "ready";
1883                 break;
1884         case VPN_PROVIDER_STATE_DISCONNECT:
1885                 str = "disconnect";
1886                 break;
1887         case VPN_PROVIDER_STATE_FAILURE:
1888                 str = "failure";
1889                 break;
1890         }
1891
1892         connman_dbus_dict_append_basic(iter, "State",
1893                                 DBUS_TYPE_STRING, &str);
1894 }
1895
1896 static void append_properties(DBusMessageIter *iter,
1897                                         struct vpn_provider *provider)
1898 {
1899         DBusMessageIter dict;
1900         GHashTableIter hash;
1901         gpointer value, key;
1902         dbus_bool_t immutable;
1903         dbus_bool_t split_routing;
1904
1905         connman_dbus_dict_open(iter, &dict);
1906
1907         append_state(&dict, provider);
1908
1909         if (provider->type)
1910                 connman_dbus_dict_append_basic(&dict, "Type",
1911                                         DBUS_TYPE_STRING, &provider->type);
1912
1913         if (provider->name)
1914                 connman_dbus_dict_append_basic(&dict, "Name",
1915                                         DBUS_TYPE_STRING, &provider->name);
1916
1917         if (provider->host)
1918                 connman_dbus_dict_append_basic(&dict, "Host",
1919                                         DBUS_TYPE_STRING, &provider->host);
1920         if (provider->index >= 0)
1921                 connman_dbus_dict_append_basic(&dict, "Index",
1922                                         DBUS_TYPE_INT32, &provider->index);
1923         if (provider->domain)
1924                 connman_dbus_dict_append_basic(&dict, "Domain",
1925                                         DBUS_TYPE_STRING, &provider->domain);
1926
1927         immutable = provider->immutable;
1928         connman_dbus_dict_append_basic(&dict, "Immutable", DBUS_TYPE_BOOLEAN,
1929                                         &immutable);
1930
1931         split_routing = provider->do_split_routing;
1932         connman_dbus_dict_append_basic(&dict, "SplitRouting",
1933                                         DBUS_TYPE_BOOLEAN, &split_routing);
1934
1935         if (provider->family == AF_INET)
1936                 connman_dbus_dict_append_dict(&dict, "IPv4", append_ipv4,
1937                                                 provider);
1938         else if (provider->family == AF_INET6)
1939                 connman_dbus_dict_append_dict(&dict, "IPv6", append_ipv6,
1940                                                 provider);
1941
1942         connman_dbus_dict_append_array(&dict, "Nameservers",
1943                                 DBUS_TYPE_STRING, append_dns, provider);
1944
1945         connman_dbus_dict_append_array(&dict, "UserRoutes",
1946                                 DBUS_TYPE_DICT_ENTRY, append_routes,
1947                                 provider->user_routes);
1948
1949         connman_dbus_dict_append_array(&dict, "ServerRoutes",
1950                                 DBUS_TYPE_DICT_ENTRY, append_routes,
1951                                 provider->routes);
1952
1953         if (provider->setting_strings) {
1954                 g_hash_table_iter_init(&hash, provider->setting_strings);
1955
1956                 while (g_hash_table_iter_next(&hash, &key, &value)) {
1957                         struct vpn_setting *setting = value;
1958
1959                         if (!setting->hide_value && setting->value)
1960                                 connman_dbus_dict_append_basic(&dict, key,
1961                                                         DBUS_TYPE_STRING,
1962                                                         &setting->value);
1963                 }
1964         }
1965
1966         connman_dbus_dict_close(iter, &dict);
1967 }
1968
1969 static void connection_added_signal(struct vpn_provider *provider)
1970 {
1971         DBusMessage *signal;
1972         DBusMessageIter iter;
1973
1974         signal = dbus_message_new_signal(VPN_MANAGER_PATH,
1975                         VPN_MANAGER_INTERFACE, "ConnectionAdded");
1976         if (!signal)
1977                 return;
1978
1979         dbus_message_iter_init_append(signal, &iter);
1980         dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH,
1981                                                         &provider->path);
1982         append_properties(&iter, provider);
1983
1984         dbus_connection_send(connection, signal, NULL);
1985         dbus_message_unref(signal);
1986 }
1987
1988 static int set_connected(struct vpn_provider *provider,
1989                                         bool connected)
1990 {
1991         struct vpn_ipconfig *ipconfig;
1992
1993         DBG("provider %p id %s connected %d", provider,
1994                                         provider->identifier, connected);
1995
1996         if (connected) {
1997                 if (provider->family == AF_INET6)
1998                         ipconfig = provider->ipconfig_ipv6;
1999                 else
2000                         ipconfig = provider->ipconfig_ipv4;
2001
2002                 __vpn_ipconfig_address_add(ipconfig, provider->family);
2003
2004                 provider_indicate_state(provider,
2005                                         VPN_PROVIDER_STATE_READY);
2006         } else {
2007                 provider_indicate_state(provider,
2008                                         VPN_PROVIDER_STATE_DISCONNECT);
2009
2010                 provider_indicate_state(provider,
2011                                         VPN_PROVIDER_STATE_IDLE);
2012         }
2013
2014         return 0;
2015 }
2016
2017 int vpn_provider_set_state(struct vpn_provider *provider,
2018                                         enum vpn_provider_state state)
2019 {
2020         if (!provider)
2021                 return -EINVAL;
2022
2023         switch (state) {
2024         case VPN_PROVIDER_STATE_UNKNOWN:
2025                 return -EINVAL;
2026         case VPN_PROVIDER_STATE_IDLE:
2027                 return set_connected(provider, false);
2028         case VPN_PROVIDER_STATE_CONNECT:
2029                 return provider_indicate_state(provider, state);
2030         case VPN_PROVIDER_STATE_READY:
2031                 return set_connected(provider, true);
2032         case VPN_PROVIDER_STATE_DISCONNECT:
2033                 return provider_indicate_state(provider, state);
2034         case VPN_PROVIDER_STATE_FAILURE:
2035                 return provider_indicate_state(provider, state);
2036         }
2037         return -EINVAL;
2038 }
2039
2040 void vpn_provider_add_error(struct vpn_provider *provider,
2041                         enum vpn_provider_error error)
2042 {
2043         switch (error) {
2044         case VPN_PROVIDER_ERROR_UNKNOWN:
2045                 provider->previous_connect_time = 0;
2046                 break;
2047         case VPN_PROVIDER_ERROR_CONNECT_FAILED:
2048                 provider->previous_connect_time = 0;
2049                 ++provider->conn_error_counter;
2050                 break;
2051         case VPN_PROVIDER_ERROR_LOGIN_FAILED:
2052         case VPN_PROVIDER_ERROR_AUTH_FAILED:
2053                 ++provider->auth_error_counter;
2054                 break;
2055         }
2056
2057         DBG("%p connect errors %d auth errors %d", provider,
2058                                                 provider->conn_error_counter,
2059                                                 provider->auth_error_counter);
2060 }
2061
2062 int vpn_provider_indicate_error(struct vpn_provider *provider,
2063                                         enum vpn_provider_error error)
2064 {
2065         DBG("provider %p id %s error %d", provider, provider->identifier,
2066                                                                         error);
2067
2068         /*
2069          * Ignore adding of errors when the VPN is idle or not set. Calls may
2070          * happen in a case when networks are rapidly changed and the call to
2071          * vpn_died() is done before executing the connect_cb() from the
2072          * plugin. Then vpn.c:vpn_died() executes the plugin specific died()
2073          * function which may free the plugin private data, containing also
2074          * the callback which hasn't yet been called. As a result the provider
2075          * might already been reset to idle state when the callback is executed
2076          * resulting in unnecessary reset of the previous successful connect
2077          * timer and adding of an error for already disconnected VPN.
2078          */
2079         if (provider->state == VPN_PROVIDER_STATE_IDLE ||
2080                                 provider->state == VPN_PROVIDER_STATE_UNKNOWN)
2081                 return 0;
2082
2083         vpn_provider_set_state(provider, VPN_PROVIDER_STATE_FAILURE);
2084
2085         vpn_provider_add_error(provider, error);
2086
2087         if (provider->driver && provider->driver->set_state)
2088                 provider->driver->set_state(provider, provider->state);
2089
2090         return 0;
2091 }
2092
2093 static gboolean provider_property_changed(DBusConnection *conn,
2094                                         DBusMessage *message, void *user_data)
2095 {
2096         DBusMessageIter iter;
2097         DBusMessageIter value;
2098         struct vpn_provider *provider = user_data;
2099         const char *key;
2100
2101         if (!dbus_message_iter_init(message, &iter))
2102                 return TRUE;
2103
2104         dbus_message_iter_get_basic(&iter, &key);
2105
2106         dbus_message_iter_next(&iter);
2107         dbus_message_iter_recurse(&iter, &value);
2108
2109         DBG("provider %p key %s", provider, key);
2110
2111         if (g_str_equal(key, "SplitRouting")) {
2112                 dbus_bool_t split_routing;
2113
2114                 if (dbus_message_iter_get_arg_type(&value) !=
2115                                                         DBUS_TYPE_BOOLEAN)
2116                         goto out;
2117
2118                 dbus_message_iter_get_basic(&value, &split_routing);
2119
2120                 DBG("property %s value %s", key, bool2str(split_routing));
2121
2122                 /*
2123                  * Even though this is coming from connmand, signal the value
2124                  * for other components listening to the changes via VPN API
2125                  * only. provider.c will skip setting the same value in order
2126                  * to avoid signaling loop. This is needed for ensuring that
2127                  * all components using VPN API will be informed about the
2128                  * correct status of SplitRouting. Especially when loading the
2129                  * services after a crash, for instance.
2130                  */
2131                 vpn_provider_set_boolean(provider, "SplitRouting",
2132                                         split_routing, true);
2133         }
2134
2135 out:
2136         return TRUE;
2137 }
2138
2139 static int connection_unregister(struct vpn_provider *provider)
2140 {
2141         DBG("provider %p path %s", provider, provider->path);
2142
2143         if (provider->signal_watch) {
2144                 g_dbus_remove_watch(connection, provider->signal_watch);
2145                 provider->signal_watch = 0;
2146         }
2147
2148         if (!provider->path)
2149                 return -EALREADY;
2150
2151         g_dbus_unregister_interface(connection, provider->path,
2152                                 VPN_CONNECTION_INTERFACE);
2153
2154         g_free(provider->path);
2155         provider->path = NULL;
2156
2157         return 0;
2158 }
2159
2160 static int connection_register(struct vpn_provider *provider)
2161 {
2162         char *connmand_vpn_path;
2163
2164         DBG("provider %p path %s", provider, provider->path);
2165
2166         if (provider->path)
2167                 return -EALREADY;
2168
2169         provider->path = g_strdup_printf("%s/connection/%s", VPN_PATH,
2170                                                 provider->identifier);
2171
2172         g_dbus_register_interface(connection, provider->path,
2173                                 VPN_CONNECTION_INTERFACE,
2174                                 connection_methods, connection_signals,
2175                                 NULL, provider, NULL);
2176
2177         connmand_vpn_path = g_strdup_printf("%s/service/vpn_%s", CONNMAN_PATH,
2178                                                 provider->identifier);
2179
2180         provider->signal_watch = g_dbus_add_signal_watch(connection,
2181                                         CONNMAN_SERVICE, connmand_vpn_path,
2182                                         CONNMAN_SERVICE_INTERFACE,
2183                                         PROPERTY_CHANGED,
2184                                         provider_property_changed,
2185                                         provider, NULL);
2186
2187         g_free(connmand_vpn_path);
2188
2189         return 0;
2190 }
2191
2192 static void unregister_provider(gpointer data)
2193 {
2194         struct vpn_provider *provider = data;
2195
2196         configuration_count_del();
2197
2198         connection_unregister(provider);
2199
2200         /* If the provider has any DNS resolver queries pending,
2201          * they need to be cleared here because the unref will not
2202          * be able to do that (because the provider_resolv_host_addr()
2203          * has increased the ref count by 1). This is quite rare as
2204          * normally the resolving either returns a value or has a
2205          * timeout which clears the memory. Typically resolv_result() will
2206          * unref the provider but in this case that call has not yet
2207          * happened.
2208          */
2209         if (provider->resolv)
2210                 vpn_provider_unref(provider);
2211
2212         vpn_provider_unref(provider);
2213 }
2214
2215 static void provider_initialize(struct vpn_provider *provider)
2216 {
2217         DBG("provider %p", provider);
2218
2219         provider->index = 0;
2220         provider->fd = -1;
2221         provider->name = NULL;
2222         provider->type = NULL;
2223         provider->domain = NULL;
2224         provider->identifier = NULL;
2225         provider->immutable = false;
2226         provider->do_split_routing = false;
2227         provider->user_networks = NULL;
2228         provider->routes = g_hash_table_new_full(g_direct_hash, g_direct_equal,
2229                                         NULL, free_route);
2230         provider->user_routes = g_hash_table_new_full(g_str_hash, g_str_equal,
2231                                         g_free, free_route);
2232         provider->setting_strings = g_hash_table_new_full(g_str_hash,
2233                                         g_str_equal, g_free, free_setting);
2234         provider->auth_error_limit = AUTH_ERROR_LIMIT_DEFAULT;
2235 }
2236
2237 static struct vpn_provider *vpn_provider_new(void)
2238 {
2239         struct vpn_provider *provider;
2240
2241         provider = g_try_new0(struct vpn_provider, 1);
2242         if (!provider)
2243                 return NULL;
2244
2245         provider->refcount = 1;
2246
2247         DBG("provider %p", provider);
2248         provider_initialize(provider);
2249
2250         return provider;
2251 }
2252
2253 static struct vpn_provider *vpn_provider_get(const char *identifier)
2254 {
2255         struct vpn_provider *provider;
2256
2257         provider = g_hash_table_lookup(provider_hash, identifier);
2258         if (provider)
2259                 return provider;
2260
2261         provider = vpn_provider_new();
2262         if (!provider)
2263                 return NULL;
2264
2265         DBG("provider %p", provider);
2266
2267         provider->identifier = g_strdup(identifier);
2268
2269         g_hash_table_insert(provider_hash, provider->identifier, provider);
2270
2271         configuration_count_add();
2272
2273         return provider;
2274 }
2275
2276 static void vpn_provider_put(const char *identifier)
2277 {
2278         configuration_count_del();
2279
2280         g_hash_table_remove(provider_hash, identifier);
2281 }
2282
2283 static void provider_dbus_ident(char *ident)
2284 {
2285         int i, len = strlen(ident);
2286
2287         for (i = 0; i < len; i++) {
2288                 if (ident[i] >= '0' && ident[i] <= '9')
2289                         continue;
2290                 if (ident[i] >= 'a' && ident[i] <= 'z')
2291                         continue;
2292                 if (ident[i] >= 'A' && ident[i] <= 'Z')
2293                         continue;
2294                 ident[i] = '_';
2295         }
2296 }
2297
2298 static struct vpn_provider *provider_create_from_keyfile(GKeyFile *keyfile,
2299                 const char *ident)
2300 {
2301         struct vpn_provider *provider;
2302
2303         if (!keyfile || !ident)
2304                 return NULL;
2305
2306         provider = __vpn_provider_lookup(ident);
2307         if (!provider) {
2308                 provider = vpn_provider_get(ident);
2309                 if (!provider) {
2310                         DBG("can not create provider");
2311                         return NULL;
2312                 }
2313
2314                 provider_load_from_keyfile(provider, keyfile);
2315
2316                 if (!provider->name || !provider->host ||
2317                                 !provider->domain) {
2318                         DBG("cannot get name, host or domain");
2319                         vpn_provider_unref(provider);
2320                         return NULL;
2321                 }
2322
2323                 if (!provider_register(provider)) {
2324                         connection_register(provider);
2325                         connection_added_signal(provider);
2326                 }
2327         }
2328
2329         return provider;
2330 }
2331
2332 static void provider_create_all_from_type(const char *provider_type)
2333 {
2334         unsigned int i;
2335         char **providers;
2336         char *id, *type;
2337         GKeyFile *keyfile;
2338
2339         DBG("provider type %s", provider_type);
2340
2341         providers = __connman_storage_get_providers();
2342
2343         if (!providers)
2344                 return;
2345
2346         for (i = 0; providers[i]; i += 1) {
2347
2348                 if (strncmp(providers[i], "provider_", 9) != 0)
2349                         continue;
2350
2351                 id = providers[i] + 9;
2352                 keyfile = __connman_storage_load_provider(id);
2353
2354                 if (!keyfile)
2355                         continue;
2356
2357                 type = __vpn_config_get_string(keyfile, id, "Type", NULL);
2358
2359                 DBG("keyfile %p id %s type %s", keyfile, id, type);
2360
2361                 if (strcmp(provider_type, type) != 0) {
2362                         g_free(type);
2363                         g_key_file_free(keyfile);
2364                         continue;
2365                 }
2366
2367                 if (!provider_create_from_keyfile(keyfile, id))
2368                         DBG("could not create provider");
2369
2370                 g_free(type);
2371                 g_key_file_free(keyfile);
2372         }
2373         g_strfreev(providers);
2374 }
2375
2376 #if !defined TIZEN_EXT
2377 char *__vpn_provider_create_identifier(const char *host, const char *domain)
2378 {
2379         char *ident;
2380
2381         if (domain)
2382                 ident = g_strdup_printf("%s_%s", host, domain);
2383         else
2384                 ident = g_strdup_printf("%s", host);
2385
2386         provider_dbus_ident(ident);
2387
2388         return ident;
2389 }
2390 #else
2391 char *__vpn_provider_create_identifier(const char *host, const char *domain, const char *name)
2392 {
2393         char *ident;
2394
2395         if (domain)
2396                 ident = g_strdup_printf("%s_%s_%s", host, domain, name);
2397         else
2398                 ident = g_strdup_printf("%s_%s", host, name);
2399         if (!ident)
2400                 return NULL;
2401
2402         provider_dbus_ident(ident);
2403
2404         return ident;
2405 }
2406 #endif
2407
2408 int __vpn_provider_create(DBusMessage *msg)
2409 {
2410         struct vpn_provider *provider;
2411         DBusMessageIter iter, array;
2412         const char *type = NULL, *name = NULL;
2413         const char *host = NULL, *domain = NULL;
2414         GSList *networks = NULL;
2415         char *ident;
2416         int err;
2417         dbus_bool_t split_routing = false;
2418
2419         dbus_message_iter_init(msg, &iter);
2420         dbus_message_iter_recurse(&iter, &array);
2421
2422         while (dbus_message_iter_get_arg_type(&array) == DBUS_TYPE_DICT_ENTRY) {
2423                 DBusMessageIter entry, value;
2424                 const char *key;
2425
2426                 dbus_message_iter_recurse(&array, &entry);
2427                 dbus_message_iter_get_basic(&entry, &key);
2428
2429                 dbus_message_iter_next(&entry);
2430                 dbus_message_iter_recurse(&entry, &value);
2431
2432                 switch (dbus_message_iter_get_arg_type(&value)) {
2433                 case DBUS_TYPE_STRING:
2434                         if (g_str_equal(key, "Type"))
2435                                 dbus_message_iter_get_basic(&value, &type);
2436                         else if (g_str_equal(key, "Name"))
2437                                 dbus_message_iter_get_basic(&value, &name);
2438                         else if (g_str_equal(key, "Host"))
2439                                 dbus_message_iter_get_basic(&value, &host);
2440                         else if (g_str_equal(key, "VPN.Domain") ||
2441                                         g_str_equal(key, "Domain"))
2442                                 dbus_message_iter_get_basic(&value, &domain);
2443                         break;
2444                 case DBUS_TYPE_BOOLEAN:
2445                         if (g_str_equal(key, "SplitRouting"))
2446                                 dbus_message_iter_get_basic(&value,
2447                                                         &split_routing);
2448                         break;
2449                 case DBUS_TYPE_ARRAY:
2450                         if (g_str_equal(key, "UserRoutes"))
2451                                 networks = get_user_networks(&value);
2452                         break;
2453                 }
2454
2455                 dbus_message_iter_next(&array);
2456         }
2457
2458         if (!host)
2459                 return -EINVAL;
2460
2461         DBG("Type %s name %s networks %p", type, name, networks);
2462
2463         if (!type || !name)
2464                 return -EOPNOTSUPP;
2465
2466 #if !defined TIZEN_EXT
2467         ident = __vpn_provider_create_identifier(host, domain);
2468 #else
2469         ident = __vpn_provider_create_identifier(host, domain, name);
2470 #endif
2471         DBG("ident %s", ident);
2472
2473         provider = __vpn_provider_lookup(ident);
2474         if (!provider) {
2475                 provider = vpn_provider_get(ident);
2476                 if (!provider) {
2477                         DBG("can not create provider");
2478                         g_free(ident);
2479                         return -EOPNOTSUPP;
2480                 }
2481
2482                 provider->host = g_strdup(host);
2483                 provider->domain = g_strdup(domain);
2484                 provider->name = g_strdup(name);
2485                 provider->type = g_strdup(type);
2486                 provider->do_split_routing = split_routing;
2487
2488                 if (provider_register(provider) == 0)
2489                         vpn_provider_load(provider);
2490
2491                 provider_resolv_host_addr(provider);
2492         }
2493
2494         if (networks) {
2495                 g_slist_free_full(provider->user_networks, free_route);
2496                 provider->user_networks = networks;
2497                 set_user_networks(provider, provider->user_networks);
2498         }
2499
2500         dbus_message_iter_init(msg, &iter);
2501         dbus_message_iter_recurse(&iter, &array);
2502
2503         while (dbus_message_iter_get_arg_type(&array) == DBUS_TYPE_DICT_ENTRY) {
2504                 DBusMessageIter entry, value;
2505                 const char *key, *str;
2506
2507                 dbus_message_iter_recurse(&array, &entry);
2508                 dbus_message_iter_get_basic(&entry, &key);
2509
2510                 dbus_message_iter_next(&entry);
2511                 dbus_message_iter_recurse(&entry, &value);
2512
2513                 switch (dbus_message_iter_get_arg_type(&value)) {
2514                 case DBUS_TYPE_STRING:
2515                         dbus_message_iter_get_basic(&value, &str);
2516                         vpn_provider_set_string(provider, key, str);
2517                         break;
2518                 }
2519
2520                 dbus_message_iter_next(&array);
2521         }
2522
2523         g_free(ident);
2524
2525         vpn_provider_save(provider);
2526
2527         err = provider_register(provider);
2528         if (err != 0 && err != -EALREADY)
2529                 return err;
2530
2531         connection_register(provider);
2532
2533         DBG("provider %p index %d path %s", provider, provider->index,
2534                                                         provider->path);
2535
2536         g_dbus_send_reply(connection, msg,
2537                                 DBUS_TYPE_OBJECT_PATH, &provider->path,
2538                                 DBUS_TYPE_INVALID);
2539
2540         connection_added_signal(provider);
2541
2542         return 0;
2543 }
2544
2545 static const char *get_string(GHashTable *settings, const char *key)
2546 {
2547         DBG("settings %p key %s", settings, key);
2548
2549         return g_hash_table_lookup(settings, key);
2550 }
2551
2552 static GSList *parse_user_networks(const char *network_str)
2553 {
2554         GSList *networks = NULL;
2555         char **elems;
2556         int i = 0;
2557
2558         if (!network_str)
2559                 return NULL;
2560
2561         elems = g_strsplit(network_str, ",", 0);
2562         if (!elems)
2563                 return NULL;
2564
2565         while (elems[i]) {
2566                 struct vpn_route *vpn_route;
2567                 char *network, *netmask, *gateway;
2568                 int family;
2569                 char **route;
2570
2571                 route = g_strsplit(elems[i], "/", 0);
2572                 if (!route)
2573                         goto next;
2574
2575                 network = route[0];
2576                 if (!network || network[0] == '\0')
2577                         goto next;
2578
2579                 family = connman_inet_check_ipaddress(network);
2580                 if (family < 0) {
2581                         DBG("Cannot get address family of %s (%d/%s)", network,
2582                                 family, gai_strerror(family));
2583
2584                         goto next;
2585                 }
2586
2587                 switch (family) {
2588                 case AF_INET:
2589                         break;
2590                 case AF_INET6:
2591                         break;
2592                 default:
2593                         DBG("Unsupported address family %d", family);
2594                         goto next;
2595                 }
2596
2597                 netmask = route[1];
2598                 if (!netmask || netmask[0] == '\0')
2599                         goto next;
2600
2601                 gateway = route[2];
2602
2603                 vpn_route = g_try_new0(struct vpn_route, 1);
2604                 if (!vpn_route) {
2605                         g_strfreev(route);
2606                         break;
2607                 }
2608
2609                 vpn_route->family = family;
2610                 vpn_route->network = g_strdup(network);
2611                 vpn_route->netmask = g_strdup(netmask);
2612                 vpn_route->gateway = g_strdup(gateway);
2613
2614                 DBG("route %s/%s%s%s", network, netmask,
2615                         gateway ? " via " : "", gateway ? gateway : "");
2616
2617                 networks = g_slist_prepend(networks, vpn_route);
2618
2619         next:
2620                 g_strfreev(route);
2621                 i++;
2622         }
2623
2624         g_strfreev(elems);
2625
2626         return g_slist_reverse(networks);
2627 }
2628
2629 int __vpn_provider_create_from_config(GHashTable *settings,
2630                                 const char *config_ident,
2631                                 const char *config_entry)
2632 {
2633         struct vpn_provider *provider;
2634         const char *type, *name, *host, *domain, *networks_str;
2635         GSList *networks;
2636         char *ident = NULL;
2637         GHashTableIter hash;
2638         gpointer value, key;
2639         int err;
2640
2641         type = get_string(settings, "Type");
2642         name = get_string(settings, "Name");
2643         host = get_string(settings, "Host");
2644         domain = get_string(settings, "Domain");
2645         networks_str = get_string(settings, "Networks");
2646         networks = parse_user_networks(networks_str);
2647
2648         if (!host) {
2649                 err = -EINVAL;
2650                 goto fail;
2651         }
2652
2653         DBG("type %s name %s networks %s", type, name, networks_str);
2654
2655         if (!type || !name) {
2656                 err = -EOPNOTSUPP;
2657                 goto fail;
2658         }
2659
2660 #if !defined TIZEN_EXT
2661         ident = __vpn_provider_create_identifier(host, domain);
2662 #else
2663         ident = __vpn_provider_create_identifier(host, domain, name);
2664 #endif
2665         DBG("ident %s", ident);
2666
2667         provider = __vpn_provider_lookup(ident);
2668         if (!provider) {
2669                 provider = vpn_provider_get(ident);
2670                 if (!provider) {
2671                         DBG("can not create provider");
2672                         err = -EOPNOTSUPP;
2673                         goto fail;
2674                 }
2675
2676                 provider->host = g_strdup(host);
2677                 provider->domain = g_strdup(domain);
2678                 provider->name = g_strdup(name);
2679                 provider->type = g_ascii_strdown(type, -1);
2680
2681                 provider->config_file = g_strdup(config_ident);
2682                 provider->config_entry = g_strdup(config_entry);
2683
2684                 provider_resolv_host_addr(provider);
2685         }
2686
2687         if (networks) {
2688                 g_slist_free_full(provider->user_networks, free_route);
2689                 provider->user_networks = networks;
2690                 set_user_networks(provider, provider->user_networks);
2691         }
2692
2693         g_hash_table_iter_init(&hash, settings);
2694
2695         while (g_hash_table_iter_next(&hash, &key, &value))
2696                 __vpn_provider_set_string_immutable(provider, key, value);
2697
2698         provider->immutable = true;
2699
2700         vpn_provider_save(provider);
2701
2702         err = provider_register(provider);
2703         if (err != 0 && err != -EALREADY)
2704                 goto fail;
2705
2706         connection_register(provider);
2707
2708         DBG("provider %p index %d path %s", provider, provider->index,
2709                                                         provider->path);
2710
2711         connection_added_signal(provider);
2712
2713         g_free(ident);
2714
2715         return 0;
2716
2717 fail:
2718         vpn_provider_put(ident);
2719         g_free(ident);
2720         g_slist_free_full(networks, free_route);
2721
2722         return err;
2723 }
2724
2725 static void append_connection_structs(DBusMessageIter *iter, void *user_data)
2726 {
2727         DBusMessageIter entry;
2728         GHashTableIter hash;
2729         gpointer value, key;
2730
2731         g_hash_table_iter_init(&hash, provider_hash);
2732
2733         while (g_hash_table_iter_next(&hash, &key, &value)) {
2734                 struct vpn_provider *provider = value;
2735
2736 #if defined TIZEN_EXT
2737                 DBG("provider %p", provider);
2738 #else
2739                 DBG("path %s", provider->path);
2740 #endif
2741
2742                 if (!provider->identifier)
2743                         continue;
2744
2745                 dbus_message_iter_open_container(iter, DBUS_TYPE_STRUCT,
2746                                 NULL, &entry);
2747                 dbus_message_iter_append_basic(&entry, DBUS_TYPE_OBJECT_PATH,
2748                                 &provider->path);
2749                 append_properties(&entry, provider);
2750                 dbus_message_iter_close_container(iter, &entry);
2751         }
2752 }
2753
2754 DBusMessage *__vpn_provider_get_connections(DBusMessage *msg)
2755 {
2756         DBusMessage *reply;
2757
2758         DBG("");
2759
2760         reply = dbus_message_new_method_return(msg);
2761         if (!reply)
2762                 return NULL;
2763
2764         __connman_dbus_append_objpath_dict_array(reply,
2765                         append_connection_structs, NULL);
2766
2767         return reply;
2768 }
2769
2770 const char *vpn_provider_get_ident(struct vpn_provider *provider)
2771 {
2772         if (!provider)
2773                 return NULL;
2774
2775         return provider->identifier;
2776 }
2777
2778 static int set_string(struct vpn_provider *provider,
2779                         const char *key, const char *value,
2780                         bool hide_value, bool immutable)
2781 {
2782         DBG("provider %p key %s immutable %s value %s", provider, key,
2783                 immutable ? "yes" : "no",
2784                 hide_value ? "<not printed>" : value);
2785
2786         if (g_str_equal(key, "Type")) {
2787                 if (!g_strcmp0(provider->type, value))
2788                         return -EALREADY;
2789
2790                 g_free(provider->type);
2791                 provider->type = g_ascii_strdown(value, -1);
2792                 send_value(provider->path, "Type", provider->type);
2793         } else if (g_str_equal(key, "Name")) {
2794                 if (!g_strcmp0(provider->name, value))
2795                         return -EALREADY;
2796
2797                 g_free(provider->name);
2798                 provider->name = g_strdup(value);
2799                 send_value(provider->path, "Name", provider->name);
2800         } else if (g_str_equal(key, "Host")) {
2801                 if (!g_strcmp0(provider->host, value))
2802                         return -EALREADY;
2803
2804                 g_free(provider->host);
2805                 provider->host = g_strdup(value);
2806                 send_value(provider->path, "Host", provider->host);
2807         } else if (g_str_equal(key, "VPN.Domain") ||
2808                         g_str_equal(key, "Domain")) {
2809                 if (!g_strcmp0(provider->domain, value))
2810                         return -EALREADY;
2811
2812                 g_free(provider->domain);
2813                 provider->domain = g_strdup(value);
2814                 send_value(provider->path, "Domain", provider->domain);
2815         } else if (g_str_equal(key, "SplitRouting")) {
2816                 connman_warn("VPN SplitRouting value attempted to set as "
2817                                         "string, is boolean");
2818                 return -EINVAL;
2819         } else {
2820                 struct vpn_setting *setting;
2821                 bool replace = true;
2822
2823                 setting = g_hash_table_lookup(provider->setting_strings, key);
2824                 if (setting) {
2825                         if (!immutable && setting->immutable) {
2826                                 DBG("Trying to set immutable variable %s", key);
2827                                 return -EPERM;
2828                         } else if (!g_strcmp0(setting->value, value)) {
2829                                 return -EALREADY;
2830                         }
2831
2832                         g_free(setting->value);
2833                         replace = false;
2834                 } else {
2835                         setting = g_try_new0(struct vpn_setting, 1);
2836                         if (!setting)
2837                                 return -ENOMEM;
2838                 }
2839
2840                 setting->value = g_strdup(value);
2841                 setting->hide_value = hide_value;
2842
2843                 if (immutable)
2844                         setting->immutable = true;
2845
2846                 if (!hide_value)
2847                         send_value(provider->path, key, setting->value);
2848
2849                 if (replace)
2850                         g_hash_table_replace(provider->setting_strings,
2851                                                 g_strdup(key), setting);
2852         }
2853
2854         return 0;
2855 }
2856
2857 int vpn_provider_set_string(struct vpn_provider *provider,
2858                                         const char *key, const char *value)
2859 {
2860         return set_string(provider, key, value, false, false);
2861 }
2862
2863 int vpn_provider_set_string_hide_value(struct vpn_provider *provider,
2864                                         const char *key, const char *value)
2865 {
2866         return set_string(provider, key, value, true, false);
2867 }
2868
2869 int __vpn_provider_set_string_immutable(struct vpn_provider *provider,
2870                                         const char *key, const char *value)
2871 {
2872         return set_string(provider, key, value, false, true);
2873 }
2874
2875 const char *vpn_provider_get_string(struct vpn_provider *provider,
2876                                                         const char *key)
2877 {
2878         struct vpn_setting *setting;
2879
2880         DBG("provider %p key %s", provider, key);
2881
2882         if (g_str_equal(key, "Type"))
2883                 return provider->type;
2884         else if (g_str_equal(key, "Name"))
2885                 return provider->name;
2886         else if (g_str_equal(key, "Host"))
2887                 return provider->host;
2888         else if (g_str_equal(key, "HostIP")) {
2889                 if (!provider->host_ip ||
2890                                 !provider->host_ip[0])
2891                         return provider->host;
2892                 else
2893                         return provider->host_ip[0];
2894         } else if (g_str_equal(key, "VPN.Domain") ||
2895                         g_str_equal(key, "Domain"))
2896                 return provider->domain;
2897
2898         setting = g_hash_table_lookup(provider->setting_strings, key);
2899         if (!setting)
2900                 return NULL;
2901
2902         return setting->value;
2903 }
2904
2905 int vpn_provider_set_boolean(struct vpn_provider *provider, const char *key,
2906                                                 bool value, bool force_change)
2907 {
2908         DBG("provider %p key %s", provider, key);
2909
2910         if (g_str_equal(key, "SplitRouting")) {
2911                 if (provider->do_split_routing == value && !force_change)
2912                         return -EALREADY;
2913
2914                 DBG("SplitRouting set to %s", bool2str(value));
2915
2916                 provider->do_split_routing = value;
2917                 send_value_boolean(provider->path, key,
2918                                         provider->do_split_routing);
2919         }
2920
2921         return 0;
2922 }
2923
2924 bool vpn_provider_get_boolean(struct vpn_provider *provider, const char *key,
2925                                                         bool default_value)
2926 {
2927         struct vpn_setting *setting;
2928
2929         connman_info("provider %p key %s", provider, key);
2930
2931         setting = g_hash_table_lookup(provider->setting_strings, key);
2932         if (!setting || !setting->value)
2933                 return default_value;
2934
2935         if (!g_strcmp0(setting->value, "true"))
2936                 return true;
2937
2938         if (!g_strcmp0(setting->value, "false"))
2939                 return false;
2940
2941         return default_value;
2942 }
2943
2944 bool vpn_provider_get_string_immutable(struct vpn_provider *provider,
2945                                                         const char *key)
2946 {
2947         struct vpn_setting *setting;
2948
2949         /* These values can be changed if the provider is not immutable */
2950         if (g_str_equal(key, "Type")) {
2951                 return provider->immutable;
2952         } else if (g_str_equal(key, "Name")) {
2953                 return provider->immutable;
2954         } else if (g_str_equal(key, "Host")) {
2955                 return provider->immutable;
2956         } else if (g_str_equal(key, "HostIP")) {
2957                 return provider->immutable;
2958         } else if (g_str_equal(key, "VPN.Domain") ||
2959                         g_str_equal(key, "Domain")) {
2960                 return provider->immutable;
2961         }
2962
2963         setting = g_hash_table_lookup(provider->setting_strings, key);
2964         if (!setting)
2965                 return true; /* Not found, regard as immutable - no changes */
2966
2967         return setting->immutable;
2968 }
2969
2970 bool vpn_provider_setting_key_exists(struct vpn_provider *provider,
2971                                                         const char *key)
2972 {
2973         return g_hash_table_contains(provider->setting_strings, key);
2974 }
2975
2976 void vpn_provider_set_auth_error_limit(struct vpn_provider *provider,
2977                                                         unsigned int limit)
2978 {
2979         if (!provider)
2980                 return;
2981
2982         provider->auth_error_limit = limit;
2983 }
2984
2985 bool __vpn_provider_check_routes(struct vpn_provider *provider)
2986 {
2987         if (!provider)
2988                 return false;
2989
2990         if (provider->user_routes &&
2991                         g_hash_table_size(provider->user_routes) > 0)
2992                 return true;
2993
2994         if (provider->routes &&
2995                         g_hash_table_size(provider->routes) > 0)
2996                 return true;
2997
2998         return false;
2999 }
3000
3001 void *vpn_provider_get_data(struct vpn_provider *provider)
3002 {
3003         return provider->driver_data;
3004 }
3005
3006 void vpn_provider_set_data(struct vpn_provider *provider, void *data)
3007 {
3008         provider->driver_data = data;
3009 }
3010
3011 void *vpn_provider_get_plugin_data(struct vpn_provider *provider)
3012 {
3013 #if defined TIZEN_EXT
3014         if (!provider)
3015                 return NULL;
3016 #endif
3017         return provider->plugin_data;
3018 }
3019
3020 void vpn_provider_set_plugin_data(struct vpn_provider *provider, void *data)
3021 {
3022         provider->plugin_data = data;
3023 }
3024
3025 void vpn_provider_set_index(struct vpn_provider *provider, int index)
3026 {
3027         DBG("index %d provider %p", index, provider);
3028
3029         if (!provider->ipconfig_ipv4) {
3030                 provider->ipconfig_ipv4 = __vpn_ipconfig_create(index,
3031                                                                 AF_INET);
3032                 if (!provider->ipconfig_ipv4) {
3033                         DBG("Couldn't create ipconfig for IPv4");
3034                         goto done;
3035                 }
3036         }
3037
3038         __vpn_ipconfig_set_index(provider->ipconfig_ipv4, index);
3039
3040         if (!provider->ipconfig_ipv6) {
3041                 provider->ipconfig_ipv6 = __vpn_ipconfig_create(index,
3042                                                                 AF_INET6);
3043                 if (!provider->ipconfig_ipv6) {
3044                         DBG("Couldn't create ipconfig for IPv6");
3045                         goto done;
3046                 }
3047         }
3048
3049         __vpn_ipconfig_set_index(provider->ipconfig_ipv6, index);
3050
3051 done:
3052         provider->index = index;
3053 }
3054
3055 int vpn_provider_get_index(struct vpn_provider *provider)
3056 {
3057         return provider->index;
3058 }
3059
3060 int vpn_provider_set_ipaddress(struct vpn_provider *provider,
3061                                         struct connman_ipaddress *ipaddress)
3062 {
3063         struct vpn_ipconfig *ipconfig = NULL;
3064
3065         switch (ipaddress->family) {
3066         case AF_INET:
3067                 ipconfig = provider->ipconfig_ipv4;
3068                 break;
3069         case AF_INET6:
3070                 ipconfig = provider->ipconfig_ipv6;
3071                 break;
3072         default:
3073                 break;
3074         }
3075
3076         DBG("provider %p state %d ipconfig %p family %d", provider,
3077                 provider->state, ipconfig, ipaddress->family);
3078
3079         if (!ipconfig)
3080                 return -EINVAL;
3081
3082         provider->family = ipaddress->family;
3083
3084         if (provider->state == VPN_PROVIDER_STATE_CONNECT ||
3085                         provider->state == VPN_PROVIDER_STATE_READY) {
3086                 struct connman_ipaddress *addr =
3087                                         __vpn_ipconfig_get_address(ipconfig);
3088
3089                 /*
3090                  * Remember the old address so that we can remove it in notify
3091                  * function in plugins/vpn.c if we ever restart
3092                  */
3093                 if (ipaddress->family == AF_INET6) {
3094                         connman_ipaddress_free(provider->prev_ipv6_addr);
3095                         provider->prev_ipv6_addr =
3096                                                 connman_ipaddress_copy(addr);
3097                 } else {
3098                         connman_ipaddress_free(provider->prev_ipv4_addr);
3099                         provider->prev_ipv4_addr =
3100                                                 connman_ipaddress_copy(addr);
3101                 }
3102         }
3103
3104         if (ipaddress->local) {
3105                 __vpn_ipconfig_set_local(ipconfig, ipaddress->local);
3106                 __vpn_ipconfig_set_peer(ipconfig, ipaddress->peer);
3107                 __vpn_ipconfig_set_broadcast(ipconfig, ipaddress->broadcast);
3108                 __vpn_ipconfig_set_gateway(ipconfig, ipaddress->gateway);
3109                 __vpn_ipconfig_set_prefixlen(ipconfig, ipaddress->prefixlen);
3110         }
3111
3112         return 0;
3113 }
3114
3115 int vpn_provider_set_pac(struct vpn_provider *provider,
3116                                 const char *pac)
3117 {
3118         DBG("provider %p pac %s", provider, pac);
3119
3120         return 0;
3121 }
3122
3123
3124 int vpn_provider_set_domain(struct vpn_provider *provider,
3125                                         const char *domain)
3126 {
3127         DBG("provider %p domain %s", provider, domain);
3128
3129         g_free(provider->domain);
3130         provider->domain = g_strdup(domain);
3131
3132         return 0;
3133 }
3134
3135 int vpn_provider_set_nameservers(struct vpn_provider *provider,
3136                                         const char *nameservers)
3137 {
3138         DBG("provider %p nameservers %s", provider, nameservers);
3139
3140         g_strfreev(provider->nameservers);
3141         provider->nameservers = NULL;
3142
3143         if (!nameservers)
3144                 return 0;
3145
3146         provider->nameservers = g_strsplit_set(nameservers, ", ", 0);
3147
3148         return 0;
3149 }
3150
3151 static int route_env_parse(struct vpn_provider *provider, const char *key,
3152                                 int *family, unsigned long *idx,
3153                                 enum vpn_provider_route_type *type)
3154 {
3155         if (!provider)
3156                 return -EINVAL;
3157
3158         DBG("name %s", provider->name);
3159
3160         if (provider->driver && provider->driver->route_env_parse)
3161                 return provider->driver->route_env_parse(provider, key, family, idx,
3162                                 type);
3163
3164         return 0;
3165 }
3166
3167 int vpn_provider_append_route(struct vpn_provider *provider,
3168                                         const char *key, const char *value)
3169 {
3170         struct vpn_route *route;
3171         int ret, family = 0;
3172         unsigned long idx = 0;
3173         enum vpn_provider_route_type type = VPN_PROVIDER_ROUTE_TYPE_NONE;
3174
3175         DBG("key %s value %s", key, value);
3176
3177         ret = route_env_parse(provider, key, &family, &idx, &type);
3178         if (ret < 0)
3179                 return ret;
3180
3181         DBG("idx %lu family %d type %d", idx, family, type);
3182
3183         route = g_hash_table_lookup(provider->routes, GINT_TO_POINTER(idx));
3184         if (!route) {
3185                 route = g_try_new0(struct vpn_route, 1);
3186                 if (!route) {
3187                         connman_error("out of memory");
3188                         return -ENOMEM;
3189                 }
3190
3191                 route->family = family;
3192
3193                 g_hash_table_replace(provider->routes, GINT_TO_POINTER(idx),
3194                                                 route);
3195         }
3196
3197         switch (type) {
3198         case VPN_PROVIDER_ROUTE_TYPE_NONE:
3199                 break;
3200         case VPN_PROVIDER_ROUTE_TYPE_MASK:
3201                 route->netmask = g_strdup(value);
3202                 break;
3203         case VPN_PROVIDER_ROUTE_TYPE_ADDR:
3204                 route->network = g_strdup(value);
3205                 break;
3206         case VPN_PROVIDER_ROUTE_TYPE_GW:
3207                 route->gateway = g_strdup(value);
3208                 break;
3209         }
3210
3211         if (route->netmask && route->gateway && route->network)
3212                 provider_schedule_changed(provider);
3213
3214         return 0;
3215 }
3216
3217 const char *vpn_provider_get_driver_name(struct vpn_provider *provider)
3218 {
3219         if (!provider->driver)
3220                 return NULL;
3221
3222         return provider->driver->name;
3223 }
3224
3225 const char *vpn_provider_get_save_group(struct vpn_provider *provider)
3226 {
3227         return provider->identifier;
3228 }
3229
3230 static gint compare_priority(gconstpointer a, gconstpointer b)
3231 {
3232         return 0;
3233 }
3234
3235 static void clean_provider(gpointer key, gpointer value, gpointer user_data)
3236 {
3237         struct vpn_provider *provider = value;
3238
3239         if (provider->driver && provider->driver->remove)
3240                 provider->driver->remove(provider);
3241
3242         connection_unregister(provider);
3243 }
3244
3245 int vpn_provider_driver_register(struct vpn_provider_driver *driver)
3246 {
3247         DBG("driver %p name %s", driver, driver->name);
3248
3249         driver_list = g_slist_insert_sorted(driver_list, driver,
3250                                                         compare_priority);
3251         provider_create_all_from_type(driver->name);
3252         return 0;
3253 }
3254
3255 void vpn_provider_driver_unregister(struct vpn_provider_driver *driver)
3256 {
3257         GHashTableIter iter;
3258         gpointer value, key;
3259
3260         DBG("driver %p name %s", driver, driver->name);
3261
3262         driver_list = g_slist_remove(driver_list, driver);
3263
3264         g_hash_table_iter_init(&iter, provider_hash);
3265         while (g_hash_table_iter_next(&iter, &key, &value)) {
3266                 struct vpn_provider *provider = value;
3267
3268                 if (provider && provider->driver &&
3269                                 g_strcmp0(provider->driver->name,
3270                                                         driver->name) == 0) {
3271                         /*
3272                          * Cancel VPN agent request to avoid segfault at
3273                          * shutdown as the callback, if set can point to a
3274                          * function in the plugin that is to be removed.
3275                          */
3276                         connman_agent_cancel(provider);
3277                         provider->driver = NULL;
3278                 }
3279         }
3280 }
3281
3282 const char *vpn_provider_get_name(struct vpn_provider *provider)
3283 {
3284         return provider->name;
3285 }
3286
3287 const char *vpn_provider_get_host(struct vpn_provider *provider)
3288 {
3289         return provider->host;
3290 }
3291
3292 const char *vpn_provider_get_path(struct vpn_provider *provider)
3293 {
3294         return provider->path;
3295 }
3296
3297 /*
3298  * This crude heuristic is meant to mitigate an issue with certain VPN
3299  * providers that allow only one authentication per account at a time. These
3300  * providers require the VPN client shuts down cleanly by sending an exit
3301  * notification. In many cases this is not possible as the transport may
3302  * already be gone and there is no route to the VPN server. In such case server
3303  * may return authentication error to indicate that an other client is active
3304  * and reserves the slot.
3305  *
3306  * By allowing the VPN client to try again with the following conditons the
3307  * unnecessary credential resets done by VPN agent can be avoided. VPN client
3308  * is allowed to retry if 1) there was a successful connection to the server
3309  * within the specified CONNECT_OK_DIFF time and 2) the provider specific
3310  * limit for auth errors is not reached the unnecessary credential resets in
3311  * this case are avoided.
3312  *
3313  * This feature is controlled by the provider specific value for
3314  * "AuthErrorLimit". Setting the value to 0 feature is disabled. User defined
3315  * value is preferred if set, otherwise plugin default set with
3316  * vpn_provider_set_auth_error_limit() is used, which defaults to
3317  * AUTH_ERROR_LIMIT_DEFAULT.
3318  */
3319 static bool ignore_authentication_errors(struct vpn_provider *provider)
3320 {
3321         const char *val;
3322         unsigned int limit;
3323         time_t uptime;
3324         time_t diff;
3325
3326         val = vpn_provider_get_string(provider, "AuthErrorLimit");
3327         if (val)
3328                 limit = g_ascii_strtoull(val, NULL, 10);
3329         else
3330                 limit = provider->auth_error_limit;
3331
3332         if (!limit || !provider->previous_connect_time) {
3333                 DBG("%p errors %u %s", provider, provider->auth_error_counter,
3334                                         !limit ?
3335                                         "disabled by 0 limit" :
3336                                         "no previous ok conn");
3337                 return false;
3338         }
3339
3340         uptime = get_uptime();
3341         diff = uptime - provider->previous_connect_time;
3342
3343         DBG("%p errors %u limit %u uptime %jd time diff %jd", provider,
3344                                 provider->auth_error_counter, limit,
3345                                 (intmax_t)uptime, (intmax_t)diff);
3346
3347         if (diff <= CONNECT_OK_DIFF && provider->auth_error_counter <= limit) {
3348                 DBG("ignore auth errors");
3349                 return true;
3350         }
3351
3352         return false;
3353 }
3354
3355 unsigned int vpn_provider_get_authentication_errors(
3356                                                 struct vpn_provider *provider)
3357 {
3358         if (ignore_authentication_errors(provider))
3359                 return 0;
3360
3361         return provider->auth_error_counter;
3362 }
3363
3364 unsigned int vpn_provider_get_connection_errors(
3365                                                 struct vpn_provider *provider)
3366 {
3367         return provider->conn_error_counter;
3368 }
3369
3370 void vpn_provider_change_address(struct vpn_provider *provider)
3371 {
3372         switch (provider->family) {
3373         case AF_INET:
3374                 connman_inet_set_address(provider->index,
3375                         __vpn_ipconfig_get_address(provider->ipconfig_ipv4));
3376                 break;
3377         case AF_INET6:
3378                 connman_inet_set_ipv6_address(provider->index,
3379                         __vpn_ipconfig_get_address(provider->ipconfig_ipv6));
3380                 break;
3381         default:
3382                 break;
3383         }
3384 }
3385
3386 void vpn_provider_clear_address(struct vpn_provider *provider, int family)
3387 {
3388         const char *address;
3389         unsigned char len;
3390
3391         DBG("provider %p family %d ipv4 %p ipv6 %p", provider, family,
3392                 provider->prev_ipv4_addr, provider->prev_ipv6_addr);
3393
3394         switch (family) {
3395         case AF_INET:
3396                 if (provider->prev_ipv4_addr) {
3397                         connman_ipaddress_get_ip(provider->prev_ipv4_addr,
3398                                                 &address, &len);
3399
3400                         DBG("ipv4 %s/%d", address, len);
3401
3402                         connman_inet_clear_address(provider->index,
3403                                         provider->prev_ipv4_addr);
3404                         connman_ipaddress_free(provider->prev_ipv4_addr);
3405                         provider->prev_ipv4_addr = NULL;
3406                 }
3407                 break;
3408         case AF_INET6:
3409                 if (provider->prev_ipv6_addr) {
3410                         connman_ipaddress_get_ip(provider->prev_ipv6_addr,
3411                                                 &address, &len);
3412
3413                         DBG("ipv6 %s/%d", address, len);
3414
3415                         connman_inet_clear_ipv6_address(provider->index,
3416                                                 provider->prev_ipv6_addr);
3417
3418                         connman_ipaddress_free(provider->prev_ipv6_addr);
3419                         provider->prev_ipv6_addr = NULL;
3420                 }
3421                 break;
3422         default:
3423                 break;
3424         }
3425 }
3426
3427 static int agent_probe(struct connman_agent *agent)
3428 {
3429         DBG("agent %p", agent);
3430         return 0;
3431 }
3432
3433 static void agent_remove(struct connman_agent *agent)
3434 {
3435         DBG("agent %p", agent);
3436 }
3437
3438 static struct connman_agent_driver agent_driver = {
3439         .name           = "vpn",
3440         .interface      = VPN_AGENT_INTERFACE,
3441         .probe          = agent_probe,
3442         .remove         = agent_remove,
3443 };
3444
3445 static void remove_unprovisioned_providers(void)
3446 {
3447         gchar **providers;
3448         GKeyFile *keyfile, *configkeyfile;
3449         char *file, *section;
3450         int i = 0;
3451
3452         providers = __connman_storage_get_providers();
3453         if (!providers)
3454                 return;
3455
3456         for (; providers[i]; i++) {
3457                 char *group = providers[i] + sizeof("provider_") - 1;
3458                 file = section = NULL;
3459                 keyfile = configkeyfile = NULL;
3460
3461                 keyfile = __connman_storage_load_provider(group);
3462                 if (!keyfile)
3463                         continue;
3464
3465                 file = __vpn_config_get_string(keyfile, group,
3466                                         "Config.file", NULL);
3467                 if (!file)
3468                         goto next;
3469
3470                 section = __vpn_config_get_string(keyfile, group,
3471                                         "Config.ident", NULL);
3472                 if (!section)
3473                         goto next;
3474
3475                 configkeyfile = __connman_storage_load_provider_config(file);
3476                 if (!configkeyfile) {
3477                         /*
3478                          * Config file is missing, remove the provisioned
3479                          * service.
3480                          */
3481                         __connman_storage_remove_provider(group);
3482                         goto next;
3483                 }
3484
3485                 if (!g_key_file_has_group(configkeyfile, section))
3486                         /*
3487                          * Config section is missing, remove the provisioned
3488                          * service.
3489                          */
3490                         __connman_storage_remove_provider(group);
3491
3492         next:
3493                 if (keyfile)
3494                         g_key_file_free(keyfile);
3495
3496                 if (configkeyfile)
3497                         g_key_file_free(configkeyfile);
3498
3499                 g_free(section);
3500                 g_free(file);
3501         }
3502
3503         g_strfreev(providers);
3504 }
3505
3506 static gboolean connman_property_changed(DBusConnection *conn,
3507                                 DBusMessage *message,
3508                                 void *user_data)
3509 {
3510         DBusMessageIter iter, value;
3511         const char *key;
3512         const char *signature = DBUS_TYPE_STRING_AS_STRING
3513                                 DBUS_TYPE_VARIANT_AS_STRING;
3514
3515         if (!dbus_message_has_signature(message, signature)) {
3516                 connman_error("vpn connman property signature \"%s\" "
3517                                 "does not match expected \"%s\"",
3518                         dbus_message_get_signature(message),
3519                         signature);
3520                 return TRUE;
3521         }
3522
3523         if (!dbus_message_iter_init(message, &iter))
3524                 return TRUE;
3525
3526         dbus_message_iter_get_basic(&iter, &key);
3527
3528         dbus_message_iter_next(&iter);
3529         dbus_message_iter_recurse(&iter, &value);
3530
3531         DBG("key %s", key);
3532
3533         if (g_str_equal(key, "State")) {
3534                 const char *str;
3535
3536                 if (dbus_message_iter_get_arg_type(&value) != DBUS_TYPE_STRING)
3537                         return TRUE;
3538
3539                 dbus_message_iter_get_basic(&value, &str);
3540                 set_state(str);
3541         }
3542
3543         return TRUE;
3544 }
3545
3546 static void get_connman_state_reply(DBusPendingCall *call, void *user_data)
3547 {
3548         DBusMessage *reply = NULL;
3549         DBusError error;
3550         DBusMessageIter iter, array, dict, value;
3551
3552         const char *signature = DBUS_TYPE_ARRAY_AS_STRING
3553                                 DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
3554                                 DBUS_TYPE_STRING_AS_STRING
3555                                 DBUS_TYPE_VARIANT_AS_STRING
3556                                 DBUS_DICT_ENTRY_END_CHAR_AS_STRING;
3557
3558         const char *key;
3559         const char *str;
3560
3561         DBG("");
3562
3563         if (!dbus_pending_call_get_completed(call))
3564                 goto done;
3565
3566         reply = dbus_pending_call_steal_reply(call);
3567
3568         dbus_error_init(&error);
3569
3570         if (dbus_set_error_from_message(&error, reply)) {
3571                 connman_error("%s", error.message);
3572
3573                 /*
3574                  * In case of timeout re-add the state function to main
3575                  * event loop.
3576                  */
3577                 if (g_ascii_strcasecmp(error.name, DBUS_ERROR_TIMEOUT) == 0) {
3578                         DBG("D-Bus timeout, re-add get_connman_state()");
3579                         get_connman_state();
3580                 } else {
3581                         dbus_error_free(&error);
3582                         goto done;
3583                 }
3584         }
3585
3586         if (!dbus_message_has_signature(reply, signature)) {
3587                 connman_error("vpnd signature \"%s\" does not match "
3588                                 "expected \"%s\"",
3589                         dbus_message_get_signature(reply),
3590                         signature);
3591
3592                 goto done;
3593         }
3594
3595         if (!dbus_message_iter_init(reply, &array))
3596                 goto done;
3597
3598         dbus_message_iter_recurse(&array, &dict);
3599
3600         while (dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_DICT_ENTRY) {
3601                 dbus_message_iter_recurse(&dict, &iter);
3602
3603                 dbus_message_iter_get_basic(&iter, &key);
3604
3605                 dbus_message_iter_next(&iter);
3606                 dbus_message_iter_recurse(&iter, &value);
3607
3608                 if (g_ascii_strcasecmp(key, "State") == 0 &&
3609                                 dbus_message_iter_get_arg_type(&value) ==
3610                                                 DBUS_TYPE_STRING) {
3611                         dbus_message_iter_get_basic(&value, &str);
3612
3613                         DBG("Got initial state %s", str);
3614
3615                         set_state(str);
3616
3617                         /* No need to process further */
3618                         break;
3619                 }
3620
3621                 dbus_message_iter_next(&dict);
3622         }
3623
3624         state_query_completed = true;
3625
3626 done:
3627         if (reply)
3628                 dbus_message_unref(reply);
3629
3630         if (call)
3631                 dbus_pending_call_unref(call);
3632 }
3633
3634 static gboolean run_get_connman_state(gpointer user_data)
3635 {
3636         const char *path = "/";
3637         const char *method = "GetProperties";
3638         gboolean rval = FALSE;
3639
3640         DBusMessage *msg = NULL;
3641         DBusPendingCall *call = NULL;
3642
3643         DBG("");
3644
3645         msg = dbus_message_new_method_call(CONNMAN_SERVICE, path,
3646                                         CONNMAN_MANAGER_INTERFACE, method);
3647         if (!msg)
3648                 goto out;
3649
3650         rval = g_dbus_send_message_with_reply(connection, msg, &call, -1);
3651         if (!rval) {
3652                 connman_error("Cannot call %s on %s", method,
3653                                                 CONNMAN_MANAGER_INTERFACE);
3654                 goto out;
3655         }
3656
3657         if (!call) {
3658                 connman_error("set pending call failed");
3659                 rval = FALSE;
3660                 goto out;
3661         }
3662
3663         if (!dbus_pending_call_set_notify(call, get_connman_state_reply,
3664                                                                 NULL, NULL)) {
3665                 connman_error("set notify to pending call failed");
3666
3667                 if (call)
3668                         dbus_pending_call_unref(call);
3669
3670                 rval = FALSE;
3671         }
3672
3673 out:
3674         if (msg)
3675                 dbus_message_unref(msg);
3676
3677         /* In case sending was success, unset timeout function id */
3678         if (rval) {
3679                 DBG("unsetting get_connman_state_timeout id");
3680                 get_connman_state_timeout = 0;
3681         }
3682
3683         /* Return FALSE in case of success to remove from main event loop */
3684         return !rval;
3685 }
3686
3687 static void get_connman_state(void)
3688 {
3689         if (get_connman_state_timeout)
3690                 return;
3691
3692         get_connman_state_timeout = g_timeout_add(STATE_INTERVAL_DEFAULT,
3693                                                 run_get_connman_state, NULL);
3694 }
3695
3696 static void connman_service_watch_connected(DBusConnection *conn,
3697                                 void *user_data)
3698 {
3699         DBG("");
3700
3701         get_connman_state();
3702 }
3703
3704 static void connman_service_watch_disconnected(DBusConnection *conn,
3705                                 void *user_data)
3706 {
3707         DBG("");
3708
3709         set_state(CONNMAN_STATE_IDLE);
3710
3711         /* Set state query variable to initial state */
3712         state_query_completed = false;
3713 }
3714
3715 int __vpn_provider_init(void)
3716 {
3717         int err;
3718
3719         DBG("");
3720
3721         err = connman_agent_driver_register(&agent_driver);
3722         if (err < 0) {
3723                 connman_error("Cannot register agent driver for %s",
3724                                                 agent_driver.name);
3725                 return err;
3726         }
3727
3728         connection = connman_dbus_get_connection();
3729
3730         remove_unprovisioned_providers();
3731
3732         provider_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
3733                                                 NULL, unregister_provider);
3734
3735         connman_service_watch = g_dbus_add_service_watch(connection,
3736                                         CONNMAN_SERVICE,
3737                                         connman_service_watch_connected,
3738                                         connman_service_watch_disconnected,
3739                                         NULL, NULL);
3740
3741         connman_signal_watch = g_dbus_add_signal_watch(connection,
3742                                         CONNMAN_SERVICE, NULL,
3743                                         CONNMAN_MANAGER_INTERFACE,
3744                                         PROPERTY_CHANGED,
3745                                         connman_property_changed,
3746                                         NULL, NULL);
3747
3748         return 0;
3749 }
3750
3751 void __vpn_provider_cleanup(void)
3752 {
3753         DBG("");
3754
3755         connman_agent_driver_unregister(&agent_driver);
3756
3757         g_hash_table_foreach(provider_hash, clean_provider, NULL);
3758
3759         g_hash_table_destroy(provider_hash);
3760         provider_hash = NULL;
3761
3762         if (get_connman_state_timeout) {
3763                 if (!g_source_remove(get_connman_state_timeout))
3764                         connman_error("connman state timeout not removed");
3765         }
3766
3767         g_dbus_remove_watch(connection, connman_service_watch);
3768         g_dbus_remove_watch(connection, connman_signal_watch);
3769
3770         dbus_connection_unref(connection);
3771 }