summaryrefslogtreecommitdiff
path: root/vpn/plugins/openconnect.c
blob: d600e61e4b7db80344720606351c079672303d97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
/*
 *
 *  ConnMan VPN daemon
 *
 *  Copyright (C) 2007-2013  Intel Corporation. All rights reserved.
 *  Copyright (C) 2019  Jolla Ltd. All rights reserved.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <net/if.h>

#include <glib.h>

#define CONNMAN_API_SUBJECT_TO_CHANGE
#include <connman/plugin.h>
#include <connman/log.h>
#include <connman/task.h>
#include <connman/ipconfig.h>
#include <connman/dbus.h>
#include <connman/agent.h>
#include <connman/setting.h>
#include <connman/vpn-dbus.h>

#include "../vpn-provider.h"
#include "../vpn-agent.h"

#include "vpn.h"

#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
#define OC_MAX_READBUF_LEN 128

enum opt_type {
	OPT_STRING	= 0,
	OPT_BOOL	= 1,
};

struct {
	const char	*cm_opt;
	const char	*oc_opt;
	bool		has_value;
	bool		enabled; // Use as task parameter
	enum opt_type	type;
} oc_options[] = {
	{ "OpenConnect.AllowSelfSignedCert", NULL, 1, 0, OPT_BOOL},
	{ "OpenConnect.AuthType", NULL, 1, 0, OPT_STRING},
	{ "OpenConnect.CACert", "--cafile", 1, 1, OPT_STRING},
	{ "OpenConnect.ClientCert", NULL, 1, 0, OPT_STRING},
	{ "OpenConnect.DisableIPv6", "--disable-ipv6", 1, 1, OPT_BOOL},
	{ "OpenConnect.PKCSClientCert", NULL, 1, 0, OPT_STRING},
	{ "OpenConnect.Protocol", "--protocol", 1, 1, OPT_STRING},
	/* --no-cert-check is disabled in openconnect 8.02 */
	{ "OpenConnect.NoCertCheck", "--no-cert-check", 0, 0, OPT_BOOL},
	{ "OpenConnect.NoHTTPKeepalive", "--no-http-keepalive", 1, 1, OPT_BOOL},
	{ "OpenConnect.NoDTLS", "--no-dtls", 1, 1, OPT_BOOL},
	{ "OpenConnect.ServerCert", "--servercert", 1, 1, OPT_STRING},
	{ "OpenConnect.Usergroup", "--usergroup", 1, 1, OPT_STRING},
	{ "OpenConnect.UserPrivateKey", NULL, 1, 0, OPT_STRING},
	{ "VPN.MTU", "--base-mtu", 1, 1, OPT_STRING},
};

enum oc_connect_type {
	OC_CONNECT_COOKIE = 0,
	OC_CONNECT_COOKIE_WITH_USERPASS,
	OC_CONNECT_USERPASS,
	OC_CONNECT_PUBLICKEY,
	OC_CONNECT_PKCS,
};

static const char *connect_types[] = {"cookie", "cookie_with_userpass",
			"userpass", "publickey", "pkcs", NULL};
static const char *protocols[] = { "anyconnect", "nc", "gp", NULL};

struct oc_private_data {
	struct vpn_provider *provider;
	struct connman_task *task;
	char *if_name;
	char *dbus_sender;
	vpn_provider_connect_cb_t cb;
	void *user_data;
	int fd_in;
	int out_ch_id;
	int err_ch_id;
	GIOChannel *out_ch;
	GIOChannel *err_ch;
	enum oc_connect_type connect_type;
	bool interactive;
};

static bool is_valid_protocol(const char* protocol)
{
	if (!protocol || !*protocol)
		return false;

	return g_strv_contains(protocols, protocol);
}

static void oc_connect_done(struct oc_private_data *data, int err)
{
	connman_info("data %p err %d/%s", data, err, strerror(err));

	if (data && data->cb) {
		vpn_provider_connect_cb_t cb = data->cb;
		void *user_data = data->user_data;

		/* Make sure we don't invoke this callback twice */
		data->cb = NULL;
		data->user_data = NULL;
		cb(data->provider, user_data, err);
	}
}

static void close_io_channel(struct oc_private_data *data, GIOChannel *channel)
{
	int id = 0;

	connman_info("data %p channel %p", data, channel);

	if (!data || !channel)
		return;

	if (data->out_ch == channel) {
		id = data->out_ch_id;
		data->out_ch = NULL;
		data->out_ch_id = 0;
	} else if (data->err_ch == channel) {
		id = data->err_ch_id;
		data->err_ch = NULL;
		data->err_ch_id = 0;
	} else {
		return;
	}

	if (id)
		g_source_remove(id);

	g_io_channel_shutdown(channel, FALSE, NULL);
	g_io_channel_unref(channel);
}

static void free_private_data(struct oc_private_data *data)
{
	connman_info("data %p", data);

	if (!data || !data->provider)
		return;

	connman_info("provider %p", data->provider);

	if (vpn_provider_get_plugin_data(data->provider) == data)
		vpn_provider_set_plugin_data(data->provider, NULL);

	vpn_provider_unref(data->provider);

	if (data->fd_in > 0)
		close(data->fd_in);
	data->fd_in = -1;
	close_io_channel(data, data->out_ch);
	close_io_channel(data, data->err_ch);

	g_free(data->dbus_sender);
	g_free(data->if_name);
	g_free(data);
}

static int task_append_config_data(struct vpn_provider *provider,
					struct connman_task *task)
{
	const char *option = NULL;
	int i;

	for (i = 0; i < (int)ARRAY_SIZE(oc_options); i++) {
		if (!oc_options[i].oc_opt || !oc_options[i].enabled)
			continue;

		if (oc_options[i].has_value) {
			option = vpn_provider_get_string(provider,
						oc_options[i].cm_opt);
			if (!option)
				continue;

			/* Add boolean type values only if set as true. */
			if (oc_options[i].type == OPT_BOOL) {
				if (!vpn_provider_get_boolean(provider,
							oc_options[i].cm_opt,
							false))
					continue;

				/* No option is set for boolean type values. */
				option = NULL;
			}

			/* Skip protocol if it is invalid. */
			if (!g_strcmp0(oc_options[i].cm_opt,
						"OpenConnect.Protocol")) {
				if (!is_valid_protocol(option))
					continue;
			}
		}

		/*
		 * Add server certificate fingerprint only when self signed
		 * certificates are explicitly allowed. Using --servercert as
		 * parameter will accept any server with matching fingerprint,
		 * which would disregard the setting of AllowSelfSignedCert.
		 */
		if (!g_strcmp0(oc_options[i].cm_opt,
					"OpenConnect.ServerCert")) {
			if (!vpn_provider_get_boolean(provider,
					"OpenConnect.AllowSelfSignedCert",
					false))
				continue;
		}

		if (connman_task_add_argument(task,
				oc_options[i].oc_opt,
				oc_options[i].has_value ? option : NULL) < 0)
			return -EIO;
	}

	return 0;
}

static int oc_notify(DBusMessage *msg, struct vpn_provider *provider)
{
	DBusMessageIter iter, dict;
	const char *reason, *key, *value;
	char *domain = NULL;
	char *addressv4 = NULL, *addressv6 = NULL;
	char *netmask = NULL, *gateway = NULL;
	unsigned char prefix_len = 0;
	struct connman_ipaddress *ipaddress;
	struct oc_private_data *data;

	connman_info("provider %p", provider);

	data = vpn_provider_get_plugin_data(provider);

	dbus_message_iter_init(msg, &iter);

	dbus_message_iter_get_basic(&iter, &reason);
	dbus_message_iter_next(&iter);

	if (!provider) {
		connman_error("No provider found");
		oc_connect_done(data, ENOENT);
		return VPN_STATE_FAILURE;
	}

	if (strcmp(reason, "connect"))
		return VPN_STATE_DISCONNECT;

	domain = g_strdup(vpn_provider_get_string(provider, "VPN.Domain"));

	dbus_message_iter_recurse(&iter, &dict);

	while (dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_DICT_ENTRY) {
		DBusMessageIter entry;

		dbus_message_iter_recurse(&dict, &entry);
		dbus_message_iter_get_basic(&entry, &key);
		dbus_message_iter_next(&entry);
		dbus_message_iter_get_basic(&entry, &value);

		if (strcmp(key, "CISCO_CSTP_OPTIONS"))
			DBG("%s = %s", key, value);

		if (!strcmp(key, "VPNGATEWAY"))
			gateway = g_strdup(value);

		if (!strcmp(key, "INTERNAL_IP4_ADDRESS"))
			addressv4 = g_strdup(value);

		if (!strcmp(key, "INTERNAL_IP6_ADDRESS")) {
			addressv6 = g_strdup(value);
			prefix_len = 128;
		}

		if (!strcmp(key, "INTERNAL_IP4_NETMASK"))
			netmask = g_strdup(value);

		if (!strcmp(key, "INTERNAL_IP6_NETMASK")) {
			char *sep;

			/* The netmask contains the address and the prefix */
			sep = strchr(value, '/');
			if (sep) {
				unsigned char ip_len = sep - value;

				addressv6 = g_strndup(value, ip_len);
				prefix_len = (unsigned char)
						strtol(sep + 1, NULL, 10);
			}
		}

		if (!strcmp(key, "INTERNAL_IP4_DNS") ||
				!strcmp(key, "INTERNAL_IP6_DNS"))
			vpn_provider_set_nameservers(provider, value);

		if (!strcmp(key, "CISCO_PROXY_PAC"))
			vpn_provider_set_pac(provider, value);

		if (!domain && !strcmp(key, "CISCO_DEF_DOMAIN")) {
			g_free(domain);
			domain = g_strdup(value);
		}

		if (g_str_has_prefix(key, "CISCO_SPLIT_INC") ||
			g_str_has_prefix(key, "CISCO_IPV6_SPLIT_INC"))
			vpn_provider_append_route(provider, key, value);

		dbus_message_iter_next(&dict);
	}

	DBG("%p %p", addressv4, addressv6);

	if (addressv4)
		ipaddress = connman_ipaddress_alloc(AF_INET);
	else if (addressv6)
		ipaddress = connman_ipaddress_alloc(AF_INET6);
	else
		ipaddress = NULL;

	if (!ipaddress) {
		g_free(addressv4);
		g_free(addressv6);
		g_free(netmask);
		g_free(gateway);
		g_free(domain);

		return VPN_STATE_FAILURE;
	}

	if (addressv4)
		connman_ipaddress_set_ipv4(ipaddress, addressv4,
						netmask, gateway);
	else
		connman_ipaddress_set_ipv6(ipaddress, addressv6,
						prefix_len, gateway);
	vpn_provider_set_ipaddress(provider, ipaddress);
	vpn_provider_set_domain(provider, domain);

	g_free(addressv4);
	g_free(addressv6);
	g_free(netmask);
	g_free(gateway);
	g_free(domain);
	connman_ipaddress_free(ipaddress);

	oc_connect_done(data, 0);
	return VPN_STATE_CONNECT;
}

static ssize_t full_write(int fd, const void *buf, size_t len)
{
	ssize_t byte_write;

	while (len) {
		byte_write = write(fd, buf, len);
		if (byte_write < 0) {
			connman_error("failed to write config to openconnect: "
					" %s\n", strerror(errno));
			return byte_write;
		}
		len -= byte_write;
		buf += byte_write;
	}

	return len;
}

static ssize_t write_data(int fd, const char *data)
{
	gchar *buf;
	ssize_t len;

	if (!data || !*data)
		return -1;

	buf = g_strdup_printf("%s\n", data);

	len = full_write(fd, buf, strlen(buf));

	g_free(buf);

	return len;
}

static void oc_died(struct connman_task *task, int exit_code, void *user_data)
{
	struct oc_private_data *data = user_data;

	connman_info("task %p data %p exit_code %d user_data %p", task, data,
				exit_code, user_data);

	if (!data)
		return;

	if (data->provider) {
		connman_agent_cancel(data->provider);

		if (task)
			vpn_died(task, exit_code, data->provider);
	}

	free_private_data(data);
}

static gboolean io_channel_out_cb(GIOChannel *source, GIOCondition condition,
			gpointer user_data)
{
	struct oc_private_data *data;
	char *str;

	data = user_data;

	if (data->out_ch != source)
		return G_SOURCE_REMOVE;

	if ((condition & G_IO_IN) &&
		g_io_channel_read_line(source, &str, NULL, NULL, NULL) ==
							G_IO_STATUS_NORMAL) {

		g_strchomp(str);

		/* Only cookie is printed to stdout */
		vpn_provider_set_string_hide_value(data->provider,
					"OpenConnect.Cookie", str);

		g_free(str);
	} else if (condition & (G_IO_ERR | G_IO_HUP)) {
		connman_info("Out channel termination");
		close_io_channel(data, source);
		return G_SOURCE_REMOVE;
	}

	return G_SOURCE_CONTINUE;
}

static bool strv_contains_prefix(const char *strv[], const char *str)
{
	int i;

	if (!strv || !str || !*str)
		return false;

	for (i = 0; strv[i]; i++) {
		if (g_str_has_prefix(str, strv[i]))
			return true;
	}

	return false;
}

static void clear_provider_credentials(struct vpn_provider *provider)
{
	const char *keys[] = { "OpenConnect.Username",
				"OpenConnect.Password",
				"OpenConnect.PKCSPassword",
				"OpenConnect.Cookie",
				NULL
	};
	int i;

	connman_info("provider %p", provider);

	for (i = 0; keys[i]; i++) {
		if (!vpn_provider_get_string_immutable(provider, keys[i]))
			vpn_provider_set_string_hide_value(provider, keys[i],
						"-");
	}
}

typedef void (* request_input_reply_cb_t) (DBusMessage *reply,
					void *user_data);

static int request_input_credentials(struct oc_private_data *data,
			request_input_reply_cb_t cb);


static void request_input_pkcs_reply(DBusMessage *reply, void *user_data)
{
	struct oc_private_data *data = user_data;
	const char *password = NULL;
	const char *key;
	DBusMessageIter iter, dict;
	int err;

	connman_info("provider %p", data->provider);

	if (!reply)
		goto err;

	err = vpn_agent_check_and_process_reply_error(reply, data->provider,
				data->task, data->cb, data->user_data);
	if (err) {
		/* Ensure cb is called only once */
		data->cb = NULL;
		data->user_data = NULL;
		goto err;
	}

	if (!vpn_agent_check_reply_has_dict(reply))
		goto err;

	dbus_message_iter_init(reply, &iter);
	dbus_message_iter_recurse(&iter, &dict);
	while (dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_DICT_ENTRY) {
		DBusMessageIter entry, value;

		dbus_message_iter_recurse(&dict, &entry);
		if (dbus_message_iter_get_arg_type(&entry) != DBUS_TYPE_STRING)
			break;

		dbus_message_iter_get_basic(&entry, &key);

		if (g_str_equal(key, "OpenConnect.PKCSPassword")) {
			dbus_message_iter_next(&entry);
			if (dbus_message_iter_get_arg_type(&entry)
							!= DBUS_TYPE_VARIANT)
				break;
			dbus_message_iter_recurse(&entry, &value);
			if (dbus_message_iter_get_arg_type(&value)
							!= DBUS_TYPE_STRING)
				break;
			dbus_message_iter_get_basic(&value, &password);
			vpn_provider_set_string_hide_value(data->provider, key,
						password);
		}

		dbus_message_iter_next(&dict);
	}

	if (data->connect_type != OC_CONNECT_PKCS || !password)
		goto err;

	if (write_data(data->fd_in, password) != 0) {
		connman_error("openconnect failed to take PKCS pass phrase on"
					" stdin");
		goto err;
	}

	clear_provider_credentials(data->provider);

	return;
err:
	oc_connect_done(data, EACCES);
}

static gboolean io_channel_err_cb(GIOChannel *source, GIOCondition condition,
			gpointer user_data)
{
	struct oc_private_data *data;
	const char *auth_failures[] = {
				/* Login failed */
				"Got HTTP response: HTTP/1.1 401 Unauthorized",
				"Failed to obtain WebVPN cookie",
				/* Cookie not valid */
				"Got inappropriate HTTP CONNECT response: "
						"HTTP/1.1 401 Unauthorized",
				/* Invalid cookie */
				"VPN service unavailable",
				/* Problem with certificates */
				"SSL connection failure",
				"Creating SSL connection failed",
				"SSL connection cancelled",
				NULL
	};
	const char *conn_failures[] = {
				"Failed to connect to",
				"Failed to open HTTPS connection to",
				NULL
	};
	/* Handle both PKCS#12 and PKCS#8 failures */
	const char *pkcs_failures[] = {
				"Failed to decrypt PKCS#12 certificate file",
				"Failed to decrypt PKCS#8 certificate file",
				NULL
	};
	/* Handle both PKCS#12 and PKCS#8 requests */
	const char *pkcs_requests[] = {
				"Enter PKCS#12 pass phrase",
				"Enter PKCS#8 pass phrase",
				NULL
	};
	const char *server_key_hash = "    --servercert";
	char *str;
	bool close = false;
	int err = 0;

	data = user_data;

	if (!data)
		return G_SOURCE_REMOVE;

	if (source && data->err_ch != source)
		return G_SOURCE_REMOVE;

	if ((condition & G_IO_IN)) {
		gsize len;
		int pos;

		if (!data->interactive) {
			if (g_io_channel_read_line(source, &str, &len, NULL,
						NULL) != G_IO_STATUS_NORMAL)
				err = EIO;
			else
				str[len - 1] = '\0';
		} else {
			GIOStatus status;
			str = g_try_new0(char, OC_MAX_READBUF_LEN);
			if (!str)
				return G_SOURCE_REMOVE;

			for (pos = 0; pos < OC_MAX_READBUF_LEN - 1 ; ++pos) {
				status = g_io_channel_read_chars(source,
						str+pos, 1, &len, NULL);

				if (status == G_IO_STATUS_EOF) {
					break;
				} else if (status != G_IO_STATUS_NORMAL) {
					err = EIO;
					break;
				}

				/* Ignore control chars and digits at start */
				if (!pos && (g_ascii_iscntrl(str[pos]) ||
						g_ascii_isdigit(str[pos])))
					--pos;

				/* Read zero length or no more to read */
				if (!len || g_io_channel_get_buffer_condition(
							source) != G_IO_IN ||
							str[pos] == '\n')
					break;
			}

			/*
			 * When self signed certificates are allowed and server
			 * SHA1 fingerprint is printed to stderr there is a
			 * newline char at the end of SHA1 fingerprint.
			 */
			if (str[pos] == '\n')
				str[pos] = '\0';
		}

		connman_info("openconnect: %s", str);

		if (err || !str || !*str) {
			connman_info("error reading from openconnect");
		} else if (g_str_has_prefix(str, server_key_hash)) {
			const char *fingerprint;
			int position;
			bool allow_self_signed;

			allow_self_signed = vpn_provider_get_boolean(
					data->provider,
					"OpenConnect.AllowSelfSignedCert",
					false);

			if (allow_self_signed) {
				position = strlen(server_key_hash) + 1;
				fingerprint = g_strstrip(str + position);

				connman_info("Set server key hash: \"%s\"",
							fingerprint);

				vpn_provider_set_string(data->provider,
						"OpenConnect.ServerCert",
						fingerprint);

				/*
				 * OpenConnect waits for "yes" or "no" as
				 * response to certificate acceptance request.
				 */
				if (write_data(data->fd_in, "yes") != 0)
					connman_error("openconnect: cannot "
						"write answer to certificate "
						"accept request");

			} else {
				connman_warn("Self signed certificate is not "
							" allowed");

				/*
				 * Close IO channel to avoid deadlock as an
				 * answer is expected for the certificate
				 * accept request.
				 */
				close = true;
				err = ECONNREFUSED;
			}
		} else if (strv_contains_prefix(pkcs_failures, str)) {
			connman_warn("PKCS failure: %s", str);
			close = true;
			err = EACCES;
		} else if (strv_contains_prefix(pkcs_requests, str)) {
			connman_info("PKCS file pass phrase request: %s", str);
			err = request_input_credentials(data,
						request_input_pkcs_reply);

			if (err != -EINPROGRESS) {
				err = EACCES;
				close = true;
			} else {
				err = 0;
			}
		} else if (strv_contains_prefix(auth_failures, str)) {
			connman_warn("authentication failed: %s", str);
			err = EACCES;
		} else if (strv_contains_prefix(conn_failures, str)) {
			connman_warn("connection failed: %s", str);
			err = ECONNREFUSED;
		}

		g_free(str);
	} else if (condition & (G_IO_ERR | G_IO_HUP)) {
		connman_info("Err channel termination");
		close = true;
	}

	if (err) {
		switch (err) {
		case EACCES:
			clear_provider_credentials(data->provider);
			break;
		case ECONNREFUSED:
			/*
			 * This will trigger VPN_PROVIDER_ERROR_CONNECT_FAILED
			 * in vpn-provider.c:connect_cb().
			 */
		default:
			break;
		}

		oc_connect_done(data, err);
	}

	if (close) {
		close_io_channel(data, source);
		return G_SOURCE_REMOVE;
	}

	return G_SOURCE_CONTINUE;
}

static int run_connect(struct oc_private_data *data)
{
	struct vpn_provider *provider;
	struct connman_task *task;
	const char *vpnhost;
	const char *vpncookie = NULL;
	const char *username;
	const char *password = NULL;
	const char *certificate = NULL;
	const char *private_key;
	const char *setting_str;
	bool setting;
	bool use_stdout = false;
	int fd_out = -1;
	int fd_err;
	int err = 0;

	if (!data)
		return -EINVAL;

	provider = data->provider;
	task = data->task;

	connman_info("provider %p task %p", provider, task);

	switch (data->connect_type) {
	case OC_CONNECT_COOKIE:
		vpncookie = vpn_provider_get_string(provider,
					"OpenConnect.Cookie");
		if (!vpncookie || !g_strcmp0(vpncookie, "-")) {
			err = -EACCES;
			goto done;
		}

		connman_task_add_argument(task, "--cookie-on-stdin", NULL);
		break;
	case OC_CONNECT_COOKIE_WITH_USERPASS:
		vpncookie = vpn_provider_get_string(provider,
					"OpenConnect.Cookie");
		/* No cookie set yet, username and password used first */
		if (!vpncookie || !g_strcmp0(vpncookie, "-")) {
			username = vpn_provider_get_string(provider,
						"OpenConnect.Username");
			password = vpn_provider_get_string(provider,
						"OpenConnect.Password");
			if (!username || !password ||
						!g_strcmp0(username, "-") ||
						!g_strcmp0(password, "-")) {
				err = -EACCES;
				goto done;
			}

			connman_task_add_argument(task, "--cookieonly", NULL);
			connman_task_add_argument(task, "--user", username);
			connman_task_add_argument(task, "--passwd-on-stdin",
						NULL);

			/* Use stdout only when cookie is to be read. */
			use_stdout = true;
		} else {
			connman_task_add_argument(task, "--cookie-on-stdin",
						NULL);
		}

		break;
	case OC_CONNECT_USERPASS:
		username = vpn_provider_get_string(provider,
					"OpenConnect.Username");
		password = vpn_provider_get_string(provider,
					"OpenConnect.Password");
		if (!username || !password || !g_strcmp0(username, "-") ||
					!g_strcmp0(password, "-")) {
			err = -EACCES;
			goto done;
		}

		connman_task_add_argument(task, "--user", username);
		connman_task_add_argument(task, "--passwd-on-stdin", NULL);
		break;
	case OC_CONNECT_PUBLICKEY:
		certificate = vpn_provider_get_string(provider,
					"OpenConnect.ClientCert");
		private_key = vpn_provider_get_string(provider,
					"OpenConnect.UserPrivateKey");

		if (!certificate || !private_key) {
			err = -EACCES;
			goto done;
		}

		connman_task_add_argument(task, "--certificate", certificate);
		connman_task_add_argument(task, "--sslkey", private_key);
		break;
	case OC_CONNECT_PKCS:
		certificate = vpn_provider_get_string(provider,
					"OpenConnect.PKCSClientCert");
		if (!certificate) {
			err = -EACCES;
			goto done;
		}

		connman_task_add_argument(task, "--certificate", certificate);

		password = vpn_provider_get_string(data->provider,
					"OpenConnect.PKCSPassword");
		/* Add password only if it is has been set */
		if (!password || !g_strcmp0(password, "-"))
			break;

		connman_task_add_argument(task, "--passwd-on-stdin", NULL);
		break;
	}

	vpnhost = vpn_provider_get_string(provider, "OpenConnect.VPNHost");
	if (!vpnhost || !*vpnhost)
		vpnhost = vpn_provider_get_string(provider, "Host");

	task_append_config_data(provider, task);

	/*
	 * To clarify complex situation, if cookie is expected to be printed
	 * to stdout all other output must go to syslog. But with PKCS all
	 * output must be caught in order to get message about file decryption
	 * error. For this reason, the mode has to be interactive as well.
	 */
	switch (data->connect_type) {
	case OC_CONNECT_COOKIE:
		/* fall through */
	case OC_CONNECT_COOKIE_WITH_USERPASS:
		/* fall through */
	case OC_CONNECT_USERPASS:
		/* fall through */
	case OC_CONNECT_PUBLICKEY:
		connman_task_add_argument(task, "--syslog", NULL);

		setting = vpn_provider_get_boolean(provider,
					"OpenConnect.AllowSelfSignedCert",
					false);
		setting_str = vpn_provider_get_string(provider,
					"OpenConnect.ServerCert");

		/*
		 * Run in interactive mode if self signed certificates are
		 * allowed and there is no set server SHA1 fingerprint.
		 */
		if (setting_str || !setting)
			connman_task_add_argument(task, "--non-inter", NULL);
		else
			data->interactive = true;
		break;
	case OC_CONNECT_PKCS:
		data->interactive = true;
		break;
	}

	connman_task_add_argument(task, "--script", SCRIPTDIR "/vpn-script");

	connman_task_add_argument(task, "--interface", data->if_name);

	connman_task_add_argument(task, (char *)vpnhost, NULL);

	err = connman_task_run(task, oc_died, data, &data->fd_in, use_stdout ?
				&fd_out : NULL, &fd_err);
	if (err < 0) {
		err = -EIO;
		goto done;
	}

	switch (data->connect_type) {
	case OC_CONNECT_COOKIE:
		if (write_data(data->fd_in, vpncookie) != 0) {
			connman_error("openconnect failed to take cookie on "
						"stdin");
			err = -EIO;
		}

		break;
	case OC_CONNECT_USERPASS:
		if (write_data(data->fd_in, password) != 0) {
			connman_error("openconnect failed to take password on "
						"stdin");
			err = -EIO;
		}

		break;
	case OC_CONNECT_COOKIE_WITH_USERPASS:
		if (!vpncookie || !g_strcmp0(vpncookie, "-")) {
			if (write_data(data->fd_in, password) != 0) {
				connman_error("openconnect failed to take "
							"password on stdin");
				err = -EIO;
			}
		} else {
			if (write_data(data->fd_in, vpncookie) != 0) {
				connman_error("openconnect failed to take "
							"cookie on stdin");
				err = -EIO;
			}
		}

		break;
	case OC_CONNECT_PUBLICKEY:
		break;
	case OC_CONNECT_PKCS:
		if (!password || !g_strcmp0(password, "-"))
			break;

		if (write_data(data->fd_in, password) != 0) {
			connman_error("openconnect failed to take PKCS "
						"pass phrase on stdin");
			err = -EIO;
		}

		break;
	}

	if (err) {
		if (fd_out > 0)
			close(fd_out);

		if (fd_err > 0)
			close(fd_err);

		goto done;
	}

	err = -EINPROGRESS;

	if (use_stdout) {
		data->out_ch = g_io_channel_unix_new(fd_out);

		/* Use ASCII encoding only */
		if (g_io_channel_set_encoding(data->out_ch, NULL, NULL) !=
					G_IO_STATUS_NORMAL) {
			close_io_channel(data, data->out_ch);
			err = -EIO;
		} else {
			data->out_ch_id = g_io_add_watch(data->out_ch,
						G_IO_IN | G_IO_ERR | G_IO_HUP,
						(GIOFunc)io_channel_out_cb,
						data);
		}
	}

	data->err_ch = g_io_channel_unix_new(fd_err);

	/* Use ASCII encoding only */
	if (g_io_channel_set_encoding(data->err_ch, NULL, NULL) !=
				G_IO_STATUS_NORMAL) {
		close_io_channel(data, data->err_ch);
		err = -EIO;
	} else {
		data->err_ch_id = g_io_add_watch(data->err_ch,
					G_IO_IN | G_IO_ERR | G_IO_HUP,
					(GIOFunc)io_channel_err_cb, data);
	}

done:
	clear_provider_credentials(data->provider);

	return err;
}

static void request_input_append(DBusMessageIter *iter,
		const char *str_type, const char *str, void *user_data)
{
	const char *string;

	connman_dbus_dict_append_basic(iter, "Type",
				DBUS_TYPE_STRING, &str_type);
	connman_dbus_dict_append_basic(iter, "Requirement",
				DBUS_TYPE_STRING, &str);

	if (!user_data)
		return;

	string = user_data;
	connman_dbus_dict_append_basic(iter, "Value", DBUS_TYPE_STRING,
				&string);
}

static void request_input_append_informational(DBusMessageIter *iter,
		void *user_data)
{
	request_input_append(iter, "string", "informational", user_data);
}

static void request_input_append_mandatory(DBusMessageIter *iter,
		void *user_data)
{
	request_input_append(iter, "string", "mandatory", user_data);
}

static void request_input_append_optional(DBusMessageIter *iter,
		void *user_data)
{
	request_input_append(iter, "string", "optional", user_data);
}

static void request_input_append_password(DBusMessageIter *iter,
		void *user_data)
{
	request_input_append(iter, "password", "mandatory", user_data);
}

static void request_input_append_to_dict(struct vpn_provider *provider,
			DBusMessageIter *dict,
			connman_dbus_append_cb_t function_cb, const char *key)
{
	const char *str;
	bool immutable = false;

	if (!provider || !dict || !function_cb || !key)
		return;

	str = vpn_provider_get_string(provider, key);
	/* Ignore empty informational content */
	if (!str && function_cb == request_input_append_informational)
		return;

	/* If value is "-", it is cleared by VPN agent */
	if (!g_strcmp0(str, "-"))
		str = NULL;

	if (str)
		immutable = vpn_provider_get_string_immutable(provider, key);

	if (immutable) {
		/* Hide immutable password types */
		if (function_cb == request_input_append_password)
			str = "********";

		/* Send immutable as informational */
		function_cb = request_input_append_informational;
	}

	connman_dbus_dict_append_dict(dict, key, function_cb,
				str ? (void *)str : NULL);
}

static void request_input_credentials_reply(DBusMessage *reply, void *user_data)
{
	struct oc_private_data *data = user_data;
	const char *cookie = NULL;
	const char *servercert = NULL;
	const char *vpnhost = NULL;
	const char *username = NULL;
	const char *password = NULL;
	const char *pkcspassword = NULL;
	const char *key;
	DBusMessageIter iter, dict;
	int err;

	connman_info("provider %p", data->provider);

	if (!reply)
		goto err;

	err = vpn_agent_check_and_process_reply_error(reply, data->provider,
				data->task, data->cb, data->user_data);
	if (err) {
		/* Ensure cb is called only once */
		data->cb = NULL;
		data->user_data = NULL;
		goto out;
	}

	if (!vpn_agent_check_reply_has_dict(reply))
		goto err;

	dbus_message_iter_init(reply, &iter);
	dbus_message_iter_recurse(&iter, &dict);
	while (dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_DICT_ENTRY) {
		DBusMessageIter entry, value;

		dbus_message_iter_recurse(&dict, &entry);
		if (dbus_message_iter_get_arg_type(&entry) != DBUS_TYPE_STRING)
			break;

		dbus_message_iter_get_basic(&entry, &key);

		if (g_str_equal(key, "OpenConnect.Cookie")) {
			dbus_message_iter_next(&entry);
			if (dbus_message_iter_get_arg_type(&entry)
							!= DBUS_TYPE_VARIANT)
				break;
			dbus_message_iter_recurse(&entry, &value);
			if (dbus_message_iter_get_arg_type(&value)
							!= DBUS_TYPE_STRING)
				break;
			dbus_message_iter_get_basic(&value, &cookie);
			vpn_provider_set_string_hide_value(data->provider,
					key, cookie);
		} else if (g_str_equal(key, "OpenConnect.ServerCert")) {
			dbus_message_iter_next(&entry);
			if (dbus_message_iter_get_arg_type(&entry)
							!= DBUS_TYPE_VARIANT)
				break;
			dbus_message_iter_recurse(&entry, &value);
			if (dbus_message_iter_get_arg_type(&value)
							!= DBUS_TYPE_STRING)
				break;
			dbus_message_iter_get_basic(&value, &servercert);
			vpn_provider_set_string(data->provider, key,
					servercert);

		} else if (g_str_equal(key, "OpenConnect.VPNHost")) {
			dbus_message_iter_next(&entry);
			if (dbus_message_iter_get_arg_type(&entry)
							!= DBUS_TYPE_VARIANT)
				break;
			dbus_message_iter_recurse(&entry, &value);
			if (dbus_message_iter_get_arg_type(&value)
							!= DBUS_TYPE_STRING)
				break;
			dbus_message_iter_get_basic(&value, &vpnhost);
			vpn_provider_set_string(data->provider, key, vpnhost);
		} else if (g_str_equal(key, "Username")) {
			dbus_message_iter_next(&entry);
			if (dbus_message_iter_get_arg_type(&entry)
							!= DBUS_TYPE_VARIANT)
				break;
			dbus_message_iter_recurse(&entry, &value);
			if (dbus_message_iter_get_arg_type(&value)
							!= DBUS_TYPE_STRING)
				break;
			dbus_message_iter_get_basic(&value, &username);
			vpn_provider_set_string_hide_value(data->provider,
					"OpenConnect.Username", username);
		} else if (g_str_equal(key, "Password")) {
			dbus_message_iter_next(&entry);
			if (dbus_message_iter_get_arg_type(&entry)
							!= DBUS_TYPE_VARIANT)
				break;
			dbus_message_iter_recurse(&entry, &value);
			if (dbus_message_iter_get_arg_type(&value)
							!= DBUS_TYPE_STRING)
				break;
			dbus_message_iter_get_basic(&value, &password);
			vpn_provider_set_string_hide_value(data->provider,
					"OpenConnect.Password", password);
		} else if (g_str_equal(key, "OpenConnect.PKCSPassword")) {
			dbus_message_iter_next(&entry);
			if (dbus_message_iter_get_arg_type(&entry)
							!= DBUS_TYPE_VARIANT)
				break;
			dbus_message_iter_recurse(&entry, &value);
			if (dbus_message_iter_get_arg_type(&value)
							!= DBUS_TYPE_STRING)
				break;
			dbus_message_iter_get_basic(&value, &pkcspassword);
			vpn_provider_set_string_hide_value(data->provider, key,
						pkcspassword);
		}

		dbus_message_iter_next(&dict);
	}

	switch (data->connect_type) {
	case OC_CONNECT_COOKIE:
		if (!cookie)
			goto err;

		break;
	case OC_CONNECT_USERPASS:
		/* fall through */
	case OC_CONNECT_COOKIE_WITH_USERPASS:
		if (!username || !password)
			goto err;

		break;
	case OC_CONNECT_PUBLICKEY:
		break; // This should not be reached.
	case OC_CONNECT_PKCS:
		if (!pkcspassword)
			goto err;

		break;
	}

	err = run_connect(data);
	if (err != -EINPROGRESS)
		goto err;

	return;

err:
	oc_connect_done(data, EACCES);

out:
	free_private_data(data);
}

static int request_input_credentials(struct oc_private_data *data,
			request_input_reply_cb_t cb)
{
	DBusMessage *message;
	const char *path;
	const char *agent_sender;
	const char *agent_path;
	const char *username;
	DBusMessageIter iter;
	DBusMessageIter dict;
	int err;
	void *agent;

	if (!data || !cb)
		return -ESRCH;

	connman_info("provider %p", data->provider);

	agent = connman_agent_get_info(data->dbus_sender,
				&agent_sender, &agent_path);
	if (!data->provider || !agent || !agent_path)
		return -ESRCH;

	message = dbus_message_new_method_call(agent_sender, agent_path,
					VPN_AGENT_INTERFACE,
					"RequestInput");
	if (!message)
		return -ENOMEM;

	dbus_message_iter_init_append(message, &iter);

	path = vpn_provider_get_path(data->provider);
	dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &path);

	connman_dbus_dict_open(&iter, &dict);

	request_input_append_to_dict(data->provider, &dict,
				request_input_append_informational,
				"OpenConnect.CACert");

	/*
	 * For backwards compatibility add OpenConnect.ServerCert and
	 * OpenConnect.VPNHost as madnatory only in the default authentication
	 * mode. Otherwise. add the fields as informational. These should be
	 * set in provider settings and not to be queried with every connection
	 * attempt.
	 */
	request_input_append_to_dict(data->provider, &dict,
				data->connect_type == OC_CONNECT_COOKIE ?
				request_input_append_optional :
				request_input_append_informational,
				"OpenConnect.ServerCert");

	request_input_append_to_dict(data->provider, &dict,
				data->connect_type == OC_CONNECT_COOKIE ?
				request_input_append_optional :
				request_input_append_informational,
				"OpenConnect.VPNHost");

	if (vpn_provider_get_authentication_errors(data->provider))
		vpn_agent_append_auth_failure(&dict, data->provider, NULL);

	switch (data->connect_type) {
	case OC_CONNECT_COOKIE:
		request_input_append_to_dict(data->provider, &dict,
					request_input_append_mandatory,
					"OpenConnect.Cookie");
		break;
	/*
	 * The authentication is done with username and password to get the
	 * cookie for connection.
	 */
	case OC_CONNECT_COOKIE_WITH_USERPASS:
		/* fallthrough */
	case OC_CONNECT_USERPASS:
		username = vpn_provider_get_string(data->provider,
					"OpenConnect.Username");
		vpn_agent_append_user_info(&dict, data->provider, username);
		break;
	case OC_CONNECT_PUBLICKEY:
		return -EINVAL;
	case OC_CONNECT_PKCS:
		request_input_append_to_dict(data->provider, &dict,
				request_input_append_informational,
				"OpenConnect.PKCSClientCert");

		request_input_append_to_dict(data->provider, &dict,
					request_input_append_password,
					"OpenConnect.PKCSPassword");
		break;
	}

	vpn_agent_append_host_and_name(&dict, data->provider);

	connman_dbus_dict_close(&iter, &dict);

	err = connman_agent_queue_message(data->provider, message,
			connman_timeout_input_request(), cb, data, agent);

	dbus_message_unref(message);

	if (err < 0 && err != -EBUSY) {
		connman_error("cannot send agent request, error: %d", err);
		return err;
	}

	return -EINPROGRESS;
}

static enum oc_connect_type get_authentication_type(
			struct vpn_provider *provider)
{
	const char *auth;
	enum oc_connect_type type;

	auth = vpn_provider_get_string(provider, "OpenConnect.AuthType");
	if (!auth)
		goto out;

	for (type = 0; connect_types[type]; type++) {
		if (!g_strcmp0(auth, connect_types[type])) {
			connman_info("auth type %d/%s", type,
						connect_types[type]);
			return type;
		}
	}

out:
	/* Default to cookie */
	return OC_CONNECT_COOKIE;
}

static int oc_connect(struct vpn_provider *provider,
			struct connman_task *task, const char *if_name,
			vpn_provider_connect_cb_t cb,
			const char *dbus_sender, void *user_data)
{
	struct oc_private_data *data;
	const char *vpncookie;
	const char *certificate;
	const char *username;
	const char *password;
	const char *private_key;
	int err;

	connman_info("provider %p task %p", provider, task);

	data = g_try_new0(struct oc_private_data, 1);
	if (!data)
		return -ENOMEM;

	vpn_provider_set_plugin_data(provider, data);
	data->provider = vpn_provider_ref(provider);
	data->task = task;
	data->if_name = g_strdup(if_name);
	data->dbus_sender = g_strdup(dbus_sender);
	data->cb = cb;
	data->user_data = user_data;
	data->connect_type = get_authentication_type(provider);

	switch (data->connect_type) {
	case OC_CONNECT_COOKIE:
		vpncookie = vpn_provider_get_string(provider,
					"OpenConnect.Cookie");
		if (!vpncookie || !g_strcmp0(vpncookie, "-"))
			goto request_input;

		break;
	case OC_CONNECT_USERPASS:
		username = vpn_provider_get_string(provider,
					"OpenConnect.Username");
		password = vpn_provider_get_string(provider,
					"OpenConnect.Password");
		if (!username || !password || !g_strcmp0(username, "-") ||
					!g_strcmp0(password, "-"))
			goto request_input;

		break;
	case OC_CONNECT_COOKIE_WITH_USERPASS:
		vpncookie = vpn_provider_get_string(provider,
					"OpenConnect.Cookie");
		/* Username and password must be set if cookie is missing */
		if (!vpncookie) {
			username = vpn_provider_get_string(provider,
						"OpenConnect.Username");
			password = vpn_provider_get_string(provider,
						"OpenConnect.Password");

			if (!username || !password ||
						!g_strcmp0(username, "-") ||
						!g_strcmp0(password, "-"))
				goto request_input;
		} else if (!g_strcmp0(vpncookie, "-")) {
			goto request_input;
		}

		break;
	case OC_CONNECT_PUBLICKEY:
		certificate = vpn_provider_get_string(provider,
				"OpenConnect.ClientCert");
		private_key = vpn_provider_get_string(provider,
				"OpenConnect.UserPrivateKey");

		if (!certificate || !private_key) {
			connman_warn("missing certificate and/or private key");
			oc_connect_done(data, EACCES);
			free_private_data(data);
			return -EACCES;
		}

		break;
	case OC_CONNECT_PKCS:
		certificate = vpn_provider_get_string(provider,
					"OpenConnect.PKCSClientCert");
		if (!certificate) {
			connman_warn("missing PKCS certificate");
			oc_connect_done(data, EACCES);
			free_private_data(data);
			return -EACCES;
		}

		break;
	}

	return run_connect(data);

request_input:
	err = request_input_credentials(data, request_input_credentials_reply);
	if (err != -EINPROGRESS) {
		oc_connect_done(data, err);
		vpn_provider_indicate_error(data->provider,
					VPN_PROVIDER_ERROR_LOGIN_FAILED);
		free_private_data(data);
	}

	return err;
}

static void oc_disconnect(struct vpn_provider *provider)
{
	connman_info("provider %p", provider);

	if (!provider)
		return;

	/*
	* OpenConnect may be disconnect by timeout in connmand before running
	* the openconnect process. In such case it is important to cancel the
	* agent request to avoid having multiple ones visible.
	*/
	connman_agent_cancel(provider);
}

static int oc_save(struct vpn_provider *provider, GKeyFile *keyfile)
{
	const char *save_group;
	const char *option;
	int i;

	save_group = vpn_provider_get_save_group(provider);

	for (i = 0; i < (int)ARRAY_SIZE(oc_options); i++) {
		if (strncmp(oc_options[i].cm_opt, "OpenConnect.", 12) == 0) {
			option = vpn_provider_get_string(provider,
							oc_options[i].cm_opt);
			if (!option)
				continue;

			g_key_file_set_string(keyfile, save_group,
					oc_options[i].cm_opt, option);
		}
	}

	return 0;
}

static int oc_error_code(struct vpn_provider *provider, int exit_code)
{
	connman_info("%d", exit_code);

	/* OpenConnect process return values are ambiguous in definition
	 * https://github.com/openconnect/openconnect/blob/master/main.c#L1693
	 * and it is safer not to rely on them. Login error cannot be
	 * differentiated from connection errors, e.g., when self signed
	 * certificate is rejected by user setting.
	 */

	switch (exit_code) {
	case 2:
		/* Cookie has failed */
		clear_provider_credentials(provider);
		return VPN_PROVIDER_ERROR_LOGIN_FAILED;
	case 1:
		/* fall through */
	default:
		return VPN_PROVIDER_ERROR_UNKNOWN;
	}
}

static int oc_route_env_parse(struct vpn_provider *provider, const char *key,
		int *family, unsigned long *idx, enum vpn_provider_route_type *type)
{
	char *end;
	const char *start;

	if (g_str_has_prefix(key, "CISCO_SPLIT_INC_")) {
		*family = AF_INET;
		start = key + strlen("CISCO_SPLIT_INC_");
	} else if (g_str_has_prefix(key, "CISCO_IPV6_SPLIT_INC_")) {
		*family = AF_INET6;
		start = key + strlen("CISCO_IPV6_SPLIT_INC_");
	} else
		return -EINVAL;

	*idx = g_ascii_strtoull(start, &end, 10);

	if (strncmp(end, "_ADDR", 5) == 0)
		*type = VPN_PROVIDER_ROUTE_TYPE_ADDR;
	else if (strncmp(end, "_MASK", 5) == 0)
		*type = VPN_PROVIDER_ROUTE_TYPE_MASK;
	else if (strncmp(end, "_MASKLEN", 8) == 0 && *family == AF_INET6)
		*type = VPN_PROVIDER_ROUTE_TYPE_MASK;
	else
		return -EINVAL;

	return 0;
}

static struct vpn_driver vpn_driver = {
	.notify         = oc_notify,
	.connect	= oc_connect,
	.disconnect	= oc_disconnect,
	.error_code	= oc_error_code,
	.save		= oc_save,
	.route_env_parse = oc_route_env_parse,
};

static int openconnect_init(void)
{
	return vpn_register("openconnect", &vpn_driver, OPENCONNECT);
}

static void openconnect_exit(void)
{
	vpn_unregister("openconnect");
}

CONNMAN_PLUGIN_DEFINE(openconnect, "OpenConnect VPN plugin", VERSION,
	CONNMAN_PLUGIN_PRIORITY_DEFAULT, openconnect_init, openconnect_exit)