summaryrefslogtreecommitdiff
path: root/src/usbhost/usb-host.c
blob: 1d275d59c6d66427ad3e6ce20f0838d3ccbe4e37 (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
/*
 * deviced
 *
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _GNU_SOURCE

#include <stdio.h>
#include <limits.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <tzplatform_config.h>
#include <libsyscommon/dbus-system.h>
#include <dlfcn.h>

#include "core/log.h"
#include "core/devices.h"
#include "core/device-notifier.h"
#include "core/udev.h"
#include "core/list.h"
#include "core/device-idler.h"
#include "apps/apps.h"
#include "extcon/extcon.h"
#include "display/display-ops.h"
#include "display/core.h"
#include "dd-usbhost.h"
#include "shared/plugin.h"

#define USB_INTERFACE_CLASS     "bInterfaceClass"
#define USB_INTERFACE_SUBCLASS  "bInterfaceSubClass"
#define USB_INTERFACE_PROTOCOL  "bInterfaceProtocol"
#define USB_VENDOR_ID           "idVendor"
#define USB_PRODUCT_ID          "idProduct"
#define USB_MANUFACTURER        "manufacturer"
#define USB_PRODUCT             "product"
#define USB_SERIAL              "serial"

#define USB_HOST_RESULT_SIGNAL	"USBHostResult"

#define SIGNAL_USB_HOST_CHANGED "ChangedDevice"
#define METHOD_GET_CONNECTION_CREDENTIALS "GetConnectionCredentials"

#define ROOTPATH tzplatform_getenv(TZ_SYS_VAR)
#define POLICY_FILENAME "usbhost-policy"

static struct display_plugin *disp_plgn;
static struct display_config *disp_conf;
static struct display_config* (*fp_get_var_display_config)(void);
static bool display_on_usb_conn_changed = true;
static char *POLICY_FILEPATH;

/**
 * Below usb host class is defined by www.usb.org.
 * Please refer to below site.
 * http://www.usb.org/developers/defined_class
 * You can find the detail class codes in linux/usb/ch9.h.
 * Deviced uses kernel defines.
 */
#include <linux/usb/ch9.h>
#define USB_CLASS_ALL   0xffffffff
#define USB_DEVICE_MAJOR 189

/**
 * HID Standard protocol information.
 * Please refer to below site.
 * http://www.usb.org/developers/hidpage/HID1_11.pdf
 * Below protocol only has meaning
 * if the subclass is a boot interface subclass,
 * otherwise it is 0.
 */
enum usbhost_hid_protocol {
	USB_HOST_HID_KEYBOARD = 1,
	USB_HOST_HID_MOUSE    = 2,
};

static dd_list *usbhost_list;

enum policy_value {
	POLICY_NONE,
	POLICY_ALLOW_ALWAYS,
	POLICY_ALLOW_NOW,
	POLICY_DENY_ALWAYS,
	POLICY_DENY_NOW,
};

#define UID_KEY "UnixUserID"
#define PID_KEY "ProcessID"
#define SEC_LABEL_KEY "LinuxSecurityLabel"
#define ENTRY_LINE_SIZE 256

struct user_credentials {
	uint32_t uid;
	uint32_t pid;
	char *sec_label;
};

struct device_desc {
	uint16_t bcdUSB;
	uint8_t bDeviceClass;
	uint8_t bDeviceSubClass;
	uint8_t bDeviceProtocol;
	uint16_t idVendor;
	uint16_t idProduct;
	uint16_t bcdDevice;
};

struct policy_entry {
	struct user_credentials creds;
	union {
		struct usb_device_descriptor device;
		/* for temporary policy */
		char devpath[PATH_MAX];
	};

	enum policy_value value;
};

static inline int is_policy_temporary(struct policy_entry *entry)
{
	return entry->value == POLICY_ALLOW_NOW ||
		entry->value == POLICY_DENY_NOW;
}

static dd_list *access_list;

static struct usbhost_open_request {
	GDBusMethodInvocation *invocation;
	char *path;
	//struct user_credentials cred;
	GDBusCredentials cred;
	struct usb_device_descriptor desc;
	char devpath[PATH_MAX];
} *current_request = NULL;

static void print_usbhost(struct usbhost_device *usbhost)
{
	if (!usbhost)
		return;

	_I("devpath : %s", usbhost->devpath);
	_I("interface baseclass : %#xh", usbhost->baseclass);
	_I("interface subclass : %#xh", usbhost->subclass);
	_I("interface protocol : %#xh", usbhost->protocol);
	_I("vendor id : %#xh", usbhost->vendorid);
	_I("product id : %#xh", usbhost->productid);
	_I("manufacturer : %s", usbhost->manufacturer);
	_I("product : %s", usbhost->product);
	_I("serial : %s", usbhost->serial);
}

static void broadcast_usbhost_signal(enum usbhost_state state,
		struct usbhost_device *usbhost)
{
	int ret;
	GVariant *param;

	if (!usbhost)
		return;

	param = g_variant_new("(isiiiiisss)", state,
										usbhost->devpath,
										usbhost->baseclass,
										usbhost->subclass,
										usbhost->protocol,
										usbhost->vendorid,
										usbhost->productid,
										(usbhost->manufacturer ? usbhost->manufacturer : ""),
										(usbhost->product ? usbhost->product : ""),
										(usbhost->serial ? usbhost->serial : ""));

	ret = dbus_handle_emit_dbus_signal(NULL,
			DEVICED_PATH_USBHOST,
			DEVICED_INTERFACE_USBHOST,
			SIGNAL_USB_HOST_CHANGED,
			param);
	if (ret < 0)
		_E("Failed to send dbus signal(%s)", SIGNAL_USB_HOST_CHANGED);
}

static int add_usbhost_list(struct udev_device *dev, const char *devpath)
{
	struct usbhost_device *usbhost;
	const char *str;
	struct udev_device *parent;

	/* allocate new usbhost device */
	usbhost = calloc(1, sizeof(struct usbhost_device));
	if (!usbhost) {
		_E("Fail to allocate usbhost memory: %d", errno);
		return -errno;
	}

	/* save the devnode */
	snprintf(usbhost->devpath, sizeof(usbhost->devpath),
			"%s", devpath);

	/* get usb interface informations */
	str = udev_device_get_sysattr_value(dev, USB_INTERFACE_CLASS);
	if (str)
		usbhost->baseclass = (int)strtol(str, NULL, 16);
	str = udev_device_get_sysattr_value(dev, USB_INTERFACE_SUBCLASS);
	if (str)
		usbhost->subclass = (int)strtol(str, NULL, 16);
	str = udev_device_get_sysattr_value(dev, USB_INTERFACE_PROTOCOL);
	if (str)
		usbhost->protocol = (int)strtol(str, NULL, 16);

	/* parent has a lot of information about usb_interface */
	parent = udev_device_get_parent(dev);
	if (!parent) {
		_E("Failed to get parent.");
		free(usbhost);
		return -EPERM;
	}

	/* get usb device informations */
	str = udev_device_get_sysattr_value(parent, USB_VENDOR_ID);
	if (str)
		usbhost->vendorid = (int)strtol(str, NULL, 16);
	str = udev_device_get_sysattr_value(parent, USB_PRODUCT_ID);
	if (str)
		usbhost->productid = (int)strtol(str, NULL, 16);
	str = udev_device_get_sysattr_value(parent, USB_MANUFACTURER);
	if (str)
		usbhost->manufacturer = strdup(str);
	str = udev_device_get_sysattr_value(parent, USB_PRODUCT);
	if (str)
		usbhost->product = strdup(str);
	str = udev_device_get_sysattr_value(parent, USB_SERIAL);
	if (str)
		usbhost->serial = strdup(str);

	DD_LIST_APPEND(usbhost_list, usbhost);

	broadcast_usbhost_signal(USB_HOST_ADDED, usbhost);

	if (display_on_usb_conn_changed && disp_plgn->pm_change_internal)
		disp_plgn->pm_change_internal(INTERNAL_LOCK_USB_HOST, LCD_NORMAL);

	/* for debugging */
	_I("USB HOST Added.");
	print_usbhost(usbhost);

	return 0;
}

static int remove_usbhost_list(const char *devpath)
{
	struct usbhost_device *usbhost;
	dd_list *n, *next;

	/* find the matched item */
	DD_LIST_FOREACH_SAFE(usbhost_list, n, next, usbhost) {
		if (!strncmp(usbhost->devpath,
					devpath, sizeof(usbhost->devpath)))
			break;
	}

	if (!usbhost) {
		_E("Failed to find the matched usbhost device.");
		return -ENODEV;
	}

	broadcast_usbhost_signal(USB_HOST_REMOVED, usbhost);

	if (display_on_usb_conn_changed && disp_plgn->pm_change_internal)
		disp_plgn->pm_change_internal(INTERNAL_LOCK_USB_HOST, LCD_NORMAL);

	/* for debugging */
	_I("USB HOST Removed.");
	_I("Devpath=%s", usbhost->devpath);

	DD_LIST_REMOVE(usbhost_list, usbhost);
	free(usbhost->manufacturer);
	free(usbhost->product);
	free(usbhost->serial);
	free(usbhost);

	return 0;
}

static void remove_all_usbhost_list(void)
{
	struct usbhost_device *usbhost;
	dd_list *n, *next;

	DD_LIST_FOREACH_SAFE(usbhost_list, n, next, usbhost) {

		/* for debugging */
		_I("USB HOST Removed.");
		_I("Devpath=%s", usbhost->devpath);

		DD_LIST_REMOVE(usbhost_list, usbhost);
		free(usbhost->manufacturer);
		free(usbhost->product);
		free(usbhost->serial);
		free(usbhost);
	}
}

static void uevent_usbhost_handler(struct udev_device *dev)
{
	const char *subsystem;
	const char *devtype;
	const char *devpath;
	const char *action;
	struct policy_entry *entry;
	dd_list *n, *next;

	/**
	 * Usb host device must have at least one interface.
	 * An interface is matched with a specific usb class.
	 */
	subsystem = udev_device_get_subsystem(dev);
	devtype = udev_device_get_devtype(dev);
	if (!subsystem || !devtype) {
		_E("Failed to get subsystem or devtype.");
		return;
	}

	/* devpath is an unique information among usb host devices */
	devpath = udev_device_get_devpath(dev);
	if (!devpath) {
		_E("Failed to get devpath from udev_device.");
		return;
	}

	action = udev_device_get_action(dev);
	_I("Subsystem=%s devtype=%s action=%s", subsystem, devtype, action);
	/* Policy is valid for entire device, thus we check this devtype here */
	if (strncmp(subsystem, USB_SUBSYSTEM, sizeof(USB_SUBSYSTEM)) == 0 &&
	    strncmp(devtype, USB_DEVICE_DEVTYPE, sizeof(USB_DEVICE_DEVTYPE)) == 0 &&
	    strncmp(action, UDEV_REMOVE, sizeof(UDEV_REMOVE)) == 0) {
		DD_LIST_FOREACH_SAFE(access_list, n, next, entry) {
			if (is_policy_temporary(entry) &&
					strcmp(devpath, entry->devpath) == 0) {
				_I("Removed temporary policy for '%s'", devpath);
				DD_LIST_REMOVE(access_list, entry);
				free(entry->creds.sec_label);
				free(entry);
			}
		}
	}

	/**
	 * if devtype is not matched with usb subsystem
	 * and usb_interface devtype, skip.
	 */
	if (strncmp(subsystem, USB_SUBSYSTEM, sizeof(USB_SUBSYSTEM)) ||
	    strncmp(devtype, USB_INTERFACE_DEVTYPE, sizeof(USB_INTERFACE_DEVTYPE)))
		return;

	if (!strncmp(action, UDEV_ADD, sizeof(UDEV_ADD)))
		add_usbhost_list(dev, devpath);
	else if (!strncmp(action, UDEV_REMOVE, sizeof(UDEV_REMOVE)))
		remove_usbhost_list(devpath);
}

static int usbhost_init_from_udev_enumerate(void)
{
	struct udev *udev;
	struct udev_enumerate *enumerate;
	struct udev_list_entry *list_entry;
	struct udev_device *dev;
	const char *syspath;
	const char *devpath;

	udev = udev_new();
	if (!udev) {
		_E("Failed to create udev library context.");
		return -EPERM;
	}

	/* create a list of the devices in the 'usb' subsystem */
	enumerate = udev_enumerate_new(udev);
	if (!enumerate) {
		_E("Failed to create an enumeration context.");
		return -EPERM;
	}

	udev_enumerate_add_match_subsystem(enumerate, USB_SUBSYSTEM);
	udev_enumerate_add_match_property(enumerate,
			UDEV_DEVTYPE, USB_INTERFACE_DEVTYPE);
	udev_enumerate_scan_devices(enumerate);

	udev_list_entry_foreach(list_entry,
			udev_enumerate_get_list_entry(enumerate)) {
		syspath = udev_list_entry_get_name(list_entry);
		if (!syspath)
			continue;

		dev = udev_device_new_from_syspath(udev_enumerate_get_udev(enumerate),
				syspath);
		if (!dev)
			continue;

		/* devpath is an unique information among usb host devices */
		devpath = udev_device_get_devpath(dev);
		if (!devpath) {
			_E("Failed to get devpath from '%s' device.", syspath);
			continue;
		}

		/* add usbhost list */
		add_usbhost_list(dev, devpath);

		udev_device_unref(dev);
	}

	udev_enumerate_unref(enumerate);
	udev_unref(udev);
	return 0;
}

static GVariant *print_device_list(GDBusConnection *conn,
	const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
	GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
{
	dd_list *elem;
	struct usbhost_device *usbhost;
	int cnt = 0;

	DD_LIST_FOREACH(usbhost_list, elem, usbhost) {
		_I("== [%2d USB HOST DEVICE] ===============", cnt++);
		print_usbhost(usbhost);
	}

	return dbus_handle_new_g_variant_tuple();
}
#define nullstr(x) (x ? x : "")
static GVariant *get_device_list(GDBusConnection *conn,
	const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
	GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
{
	GVariant *gvar = NULL;
	dd_list *elem;
	struct usbhost_device *usbhost;
	int baseclass;
	GVariantBuilder *builder = NULL;
	const char *error = NULL;
	int item_cnt = 0;

	g_variant_get(param, "(i)", &baseclass);

	builder = g_variant_builder_new(G_VARIANT_TYPE("a(siiiiisss)"));
	if (!builder) {
		_E("Failed to alloc memory for g_variant_builder.");
		error = "Failed to alloc memory for g_variant_builder.";
		goto out;
	}

	DD_LIST_FOREACH(usbhost_list, elem, usbhost) {
		if (baseclass != USB_CLASS_ALL && usbhost->baseclass != baseclass)
			continue;

		g_variant_builder_add(builder, "(siiiiisss)",
				nullstr(NULL),
				usbhost->baseclass,
				usbhost->subclass,
				usbhost->protocol,
				usbhost->vendorid,
				usbhost->productid,
				nullstr(usbhost->manufacturer),
				nullstr(usbhost->product),
				nullstr(usbhost->serial));
		++item_cnt;
	}

	if (item_cnt == 0) {
		_E("Not found matched item");
		error = "Not found matched item";
		goto out;
	}

	gvar = g_variant_new("(a(siiiiisss))", builder);

out:
	if (builder)
		g_variant_builder_unref(builder);
	if (!gvar)
		g_dbus_method_invocation_return_error(invocation,
					G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
					"%s", error);
	return gvar;
}

static GVariant *get_device_list_count(GDBusConnection *conn,
	const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
	GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
{
	dd_list *elem;
	struct usbhost_device *usbhost;
	int baseclass;
	int ret = 0;

	g_variant_get(param, "(i)", &baseclass);

	DD_LIST_FOREACH(usbhost_list, elem, usbhost) {
		if (baseclass != USB_CLASS_ALL && usbhost->baseclass != baseclass)
			continue;
		ret++;
	}

	return g_variant_new("(i)", ret);
}

static struct uevent_handler uh = {
	.subsystem = USB_SUBSYSTEM,
	.uevent_func = uevent_usbhost_handler,
};

static const char *policy_value_str(enum policy_value value)
{
	switch (value) {
	case POLICY_ALLOW_ALWAYS:
		return "ALLOW";
	case POLICY_ALLOW_NOW:
		return "ALLOW_NOW";
	case POLICY_DENY_ALWAYS:
		return "DENY";
	case POLICY_DENY_NOW:
		return "DENY_NOW";
	default:
		return "UNKNOWN";
	}
}

static int get_policy_value_from_str(const char *str)
{
	if (strncmp("ALLOW", str, 5) == 0)
		return POLICY_ALLOW_ALWAYS;
	if (strncmp("ALLOW_NOW", str, 5) == 0)
		return POLICY_ALLOW_NOW;
	if (strncmp("DENY", str, 4) == 0)
		return POLICY_DENY_ALWAYS;
	if (strncmp("DENY_NOW", str, 4) == 0)
		return POLICY_DENY_NOW;
	return POLICY_NONE;
}

static inline int marshal_policy_entry(char *buf, int len, struct policy_entry *entry)
{
	if (is_policy_temporary(entry))
		return snprintf(buf, len, "%d %s %s %s\n",
				entry->creds.uid,
				entry->creds.sec_label,
				entry->devpath,
				policy_value_str(entry->value));
	return snprintf(buf, len, "%d %s %04x %02x %02x %02x %04x %04x %04x %s\n",
			entry->creds.uid,
			entry->creds.sec_label,
			entry->device.bcdUSB,
			entry->device.bDeviceClass,
			entry->device.bDeviceSubClass,
			entry->device.bDeviceProtocol,
			entry->device.idVendor,
			entry->device.idProduct,
			entry->device.bcdDevice,
			policy_value_str(entry->value));
}

static GVariant *print_policy(GDBusConnection *conn,
	const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
	GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
{
	char line[ENTRY_LINE_SIZE];
	dd_list *elem;
	struct policy_entry *entry;
	int ret;

	_I("USB access policy:");
	DD_LIST_FOREACH(access_list, elem, entry) {
		ret = marshal_policy_entry(line, ENTRY_LINE_SIZE, entry);
		if (ret < 0)
			break;
		_I("\t%s", line);
	}

	return dbus_handle_new_g_variant_tuple();
}

static int store_policy(void)
{
	int fd;
	dd_list *elem;
	struct policy_entry *entry;
	char line[256];
	int ret;

	fd = open(POLICY_FILEPATH, O_WRONLY | O_CREAT, 0664);
	if (fd < 0) {
		_E("Could not open policy file for writing: %m");
		return -errno;
	}

	DD_LIST_FOREACH(access_list, elem, entry) {
		if (is_policy_temporary(entry))
			continue;

		ret = marshal_policy_entry(line, ENTRY_LINE_SIZE, entry);
		if (ret < 0) {
			_E("Serialization failed: %m");
			goto out;
		}

		ret = write(fd, line, ret);
		if (ret < 0) {
			ret = -errno;
			_E("Error writing policy entry: %m");
			goto out;
		}
	}

	_I("Policy stored in %s", POLICY_FILEPATH);

	ret = 0;

out:
	close(fd);
	return ret;
}

static int read_policy(void)
{
	FILE *fp;
	struct policy_entry *entry;
	char *line = NULL, value_str[256];
	int ret = -1;
	int count = 0;
	size_t len;

	fp = fopen(POLICY_FILEPATH, "r");
	if (!fp) {
		ret = -errno;
		_E("Could not open policy file for reading: %m");
		return ret;
	}

	while ((ret = getline(&line, &len, fp)) != -1) {
		entry = malloc(sizeof(*entry));
		if (!entry) {
			ret = -ENOMEM;
			_E("No memory: %m");
			goto out;
		}

		entry->creds.sec_label = calloc(ENTRY_LINE_SIZE, 1);
		if (!entry->creds.sec_label) {
			_E("No memory: %m");
			free(entry);
			goto out;
		}

		ret = sscanf(line, "%d %255s %04hx %02hhx %02hhx %02hhx %04hx %04hx %04hx %255s\n",
				&entry->creds.uid,
				entry->creds.sec_label,
				&entry->device.bcdUSB,
				&entry->device.bDeviceClass,
				&entry->device.bDeviceSubClass,
				&entry->device.bDeviceProtocol,
				&entry->device.idVendor,
				&entry->device.idProduct,
				&entry->device.bcdDevice,
				value_str);
		if (ret == EOF) {
			_E("Error reading line: %m");
			free(entry->creds.sec_label);
			free(entry);
			goto out;
		}

		entry->value = get_policy_value_from_str(value_str);
		if (entry->value == POLICY_NONE) {
			_E("Invalid policy value=%s", value_str);
			ret = -EINVAL;
			free(entry->creds.sec_label);
			free(entry);
			goto out;
		}

		_I("%04x:%04x : %s", entry->device.idVendor, entry->device.idProduct,
				value_str);

		DD_LIST_APPEND(access_list, entry);
		count++;
	}

	_I("Found %d policy entries.", count);
	ret = 0;

out:
	fclose(fp);
	free(line);

	return ret;
}

static int get_device_desc(const char *filepath, struct usb_device_descriptor *desc, char *devpath)
{
	char *path = NULL;
	const char *rdevpath;
	struct stat st;
	int ret;
	int fd = -1;
	struct udev *udev = NULL;
	struct udev_device *udev_device = NULL;

	ret = stat(filepath, &st);
	if (ret < 0) {
		ret = -errno;
		_E("Could not stat %s: %m", filepath);
		goto out;
	}

	if (!S_ISCHR(st.st_mode) ||
	    major(st.st_rdev) != USB_DEVICE_MAJOR) {
		ret = -EINVAL;
		_E("Not an USB device.");
		goto out;
	}

	udev = udev_new();
	if (!udev) {
		_E("Could not create udev contect.");
		ret =  -ENOMEM;
		goto out;
	}

	udev_device = udev_device_new_from_devnum(udev, 'c', st.st_rdev);
	if (!udev_device) {
		_E("Udev could not find device.");
		ret = -ENOENT;
		goto out;
	}

	rdevpath = udev_device_get_devpath(udev_device);
	if (!rdevpath) {
		_E("Failed to get devpath from udev_device.");
		ret = -errno;
		goto out;
	}
	strncpy(devpath, rdevpath, PATH_MAX);

	ret = asprintf(&path, "/sys/dev/char/%d:%d/descriptors", major(st.st_rdev), minor(st.st_rdev));
	if (ret < 0) {
		ret = -ENOMEM;
		_E("Failed to asprintf.");
		goto out;
	}

	_I("Opening descriptor at '%s'", path);
	fd = open(path, O_RDONLY);
	if (fd < 0) {
		ret = -errno;
		_E("Failed to open '%s': %m", path);
		goto out;
	}

	ret = read(fd, desc, sizeof(*desc));
	if (ret < 0) {
		ret = -errno;
		_E("Failed to read '%s': %m", path);
		goto out;
	}

	ret = 0;

out:
	if (fd >= 0)
		close(fd);
	free(path);

	udev_device_unref(udev_device);
	udev_unref(udev);

	return ret;
}

static void store_idler_cb(void *data)
{
	store_policy();
}

static void destroy_open_request(struct usbhost_open_request *req)
{
	_D("Destroing request structure.");
	free(req->path);
	req->path = NULL;
}

static void finish_opening(struct usbhost_open_request *req, int policy)
{
	int ret;
	int fd = -1;
	const char *err;
	GError *error = NULL;
	GUnixFDList *fd_list;

	if (req->path == NULL)
		return;

	switch (policy) {
	case POLICY_ALLOW_NOW:
	case POLICY_ALLOW_ALWAYS:
		fd = open(req->path, O_RDWR);
		if (fd < 0) {
			ret = -errno;
			err = "org.freedesktop.DBus.Error.Failed";//"org.freedesktop.DBus.Error.Failed";
			_E("Unable to open file(%s): %m", req->path);
		} else
			ret = 0;
		break;
	case POLICY_DENY_NOW:
	case POLICY_DENY_ALWAYS:
		ret = -EACCES;
		err = "org.freedesktop.DBus.Error.AccessDenied";//G_DBUS_ERROR_ACCESS_DENIED;
		break;
	default:
		ret = -EINVAL;
		err = "org.freedesktop.DBus.Error.Failed";
		break;
	}

	if (ret < 0) {
		g_dbus_method_invocation_return_dbus_error(req->invocation, err, "Cannot allocate memory for error message");
		goto out;
	}

	/* send along the stdin in case
		* g_application_command_line_get_stdin_data() is called
		*/
	fd_list = g_unix_fd_list_new();
	if (g_unix_fd_list_append(fd_list, fd, &error) < 0) {
		_E("Failed to append fd in unix fd list: %s\n", error->message);
		g_error_free(error);
		goto out;
	}

	g_dbus_method_invocation_return_value_with_unix_fd_list(req->invocation, g_variant_new("(ih)", ret, 0), fd_list);

	g_object_unref(fd_list);

out:
	destroy_open_request(req);
	if (fd >= 0)
		close(fd);
	_I("Popup destroyed.");
}

static int spawn_popup(struct usbhost_open_request *req)
{
	char pid_str[8];
	int ret;

	if (!req)
		return -EINVAL;

	/* Handle for the previous popup */
	if (current_request) {
		finish_opening(current_request, POLICY_DENY_NOW);
		free(current_request);
		current_request = NULL;
	}

	_I("Launching popup.");

	snprintf(pid_str, sizeof(pid_str), "%d", req->cred.pid);
	ret = launch_system_app(APP_DEFAULT, 4, APP_KEY_TYPE, "usbhost", "_APP_PID_", pid_str);
	if (ret < 0) {
		_E("Could not launch system popup.");
		return ret;
	}

	return ret;
}

static void popup_result_signal_handler(GDBusConnection  *conn,
	const gchar      *sender,
	const gchar      *path,
	const gchar      *iface,
	const gchar      *name,
	GVariant         *param,
	gpointer          data)

{
	int allow = 0, always = 0;
	int ret;
	struct policy_entry *entry;
	int value;
	struct usbhost_open_request *req;

	req = current_request;
	if (!req) {
		_E("req is NULL");
		return;
	}

	if (!g_variant_get_safe(param, "(ii)", &allow, &always)) {
		_E("failed to get params from gvariant. expected:%s, type:%s", "(ii)", g_variant_get_type_string(param));
		free(req);
		return;
	}

	if (allow && always)
		value = POLICY_ALLOW_ALWAYS;
	else if (!allow && always)
		value = POLICY_DENY_ALWAYS;
	else if (allow && !always)
		value = POLICY_ALLOW_NOW;
	else
		value = POLICY_DENY_NOW;

	/* Save the policy */

	entry = calloc(sizeof(*entry), 1);
	if (!entry) {
		_E("No memory.");
		goto out;
	}

	entry->creds.uid = req->cred.uid;
	entry->creds.sec_label = strdup(req->cred.sec_label);
	if (!entry->creds.sec_label) {
		_E("No memory.");
		free(entry);
		goto out;
	}

	switch (value) {
	case POLICY_ALLOW_ALWAYS:
	case POLICY_DENY_ALWAYS:
		entry->device.bcdUSB = le16toh(req->desc.bcdUSB);
		entry->device.bDeviceClass = req->desc.bDeviceClass;
		entry->device.bDeviceSubClass = req->desc.bDeviceSubClass;
		entry->device.bDeviceProtocol = req->desc.bDeviceProtocol;
		entry->device.idVendor = le16toh(req->desc.idVendor);
		entry->device.idProduct = le16toh(req->desc.idProduct);
		entry->device.bcdDevice = le16toh(req->desc.bcdDevice);

		_I("Added policy entry: %d %s %04x %02x %02x %02x %04x %04x %04x %s",
				entry->creds.uid,
				entry->creds.sec_label,
				entry->device.bcdUSB,
				entry->device.bDeviceClass,
				entry->device.bDeviceSubClass,
				entry->device.bDeviceProtocol,
				entry->device.idVendor,
				entry->device.idProduct,
				entry->device.bcdDevice,
				policy_value_str(value));
		break;
	case POLICY_ALLOW_NOW:
	case POLICY_DENY_NOW:
		strncpy(entry->devpath, req->devpath, sizeof(entry->devpath) - 1);
		entry->devpath[sizeof(entry->devpath) - 1] = '\0';
		_I("Added temporary policy entry: %d %s %s %s",
				entry->creds.uid,
				entry->creds.sec_label,
				entry->devpath,
				policy_value_str(value));
		break;
	}

	entry->value = value;
	DD_LIST_APPEND(access_list, entry);

	ret = add_idle_request(store_idler_cb, NULL);
	if (ret < 0) {
		_E("Failed to add store idle request: %d", ret);
		store_idler_cb(NULL);
	}

out:
	finish_opening(req, value);
	free(current_request);
	current_request = NULL;
}

static int get_policy_value(struct usbhost_open_request *req)
{
	int ret;
	dd_list *elem;
	struct policy_entry *entry;

	memset(&req->desc, 0, sizeof(req->desc));

	_I("Requested access from user %d to '%s'.", req->cred.uid, req->path);
	ret = get_device_desc(req->path, &req->desc, req->devpath);
	if (ret < 0) {
		_E("Could not get device descriptor.");
		return ret;
	}

	DD_LIST_FOREACH(access_list, elem, entry) {
		if (entry->creds.uid != req->cred.uid
			|| strncmp(entry->creds.sec_label, req->cred.sec_label, strlen(req->cred.sec_label)) != 0)
			continue;

		if (is_policy_temporary(entry) ? strncmp(entry->devpath, req->devpath, PATH_MAX) :
			(entry->device.bcdUSB && entry->device.bcdUSB != le16toh(req->desc.bcdUSB))
			|| (entry->device.bDeviceClass && entry->device.bDeviceClass != req->desc.bDeviceClass)
			|| (entry->device.bDeviceSubClass && entry->device.bDeviceSubClass != req->desc.bDeviceSubClass)
			|| (entry->device.bDeviceProtocol && entry->device.bDeviceProtocol != req->desc.bDeviceProtocol)
			|| (entry->device.idVendor && entry->device.idVendor != le16toh(req->desc.idVendor))
			|| (entry->device.idProduct && entry->device.idProduct != le16toh(req->desc.idProduct))
			|| (entry->device.bcdDevice && entry->device.bcdDevice != le16toh(req->desc.bcdDevice)))
			continue;

		_I("Found matching policy entry(%s)", policy_value_str(entry->value));

		return entry->value;
	}

	return POLICY_NONE;
}

static void remove_all_access_list(void)
{
	struct policy_entry *entry;
	dd_list *n, *next;

	DD_LIST_FOREACH_SAFE(access_list, n, next, entry) {
		DD_LIST_REMOVE(access_list, entry);
		free(entry->creds.sec_label);
		free(entry);
	}
}

static GVariant *open_device(GDBusConnection *conn,
	const gchar *sender, const gchar *obj_path, const gchar *iface, const gchar *name,
	GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
{
	int ret = 0;
	int policy;
	char *path;
	struct usbhost_open_request *req;

	req = calloc(sizeof(*req), 1);
	if (!req) {
		_E("No memory.");
		g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.DBus.Error.Failed", "no memory");
		return NULL;
	}

	req->invocation = invocation;

	ret = dbus_handle_get_sender_credentials(NULL, sender, &req->cred);
	if (ret < 0) {
		_E("Unable to get credentials for caller: %d", ret);
		goto out;
	}

	g_variant_get(param, "(s)", &path);

	req->path = path;
	policy = get_policy_value(req);
	if (policy < 0) {
		_E("Could not get policy value(%d).", policy);
		ret = -1;
		goto out;
	}

	/* Need to ask user */
	if (policy == POLICY_NONE) {
		ret = spawn_popup(req);
		if (ret < 0) {
			finish_opening(req, POLICY_DENY_NOW);
			free(req->cred.sec_label);
			free(req);
			return NULL;
		}

		current_request = req;
		return NULL;
	}

	/* The policy exists for the app */
	_D("Policy exists.");
	finish_opening(req, policy);
	free(req->cred.sec_label);
	free(req);
	return NULL;

out:
	destroy_open_request(req);
	free(req->cred.sec_label);
	free(req);
	g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.DBus.Error.Failed", "no memory");
	return NULL;
}

static const dbus_method_s dbus_methods[] = {
	{ "PrintDeviceList",   NULL,           NULL, print_device_list }, /* for debugging */
	{ "PrintPolicy",       NULL,           NULL, print_policy }, /* for debugging */
	{ "GetDeviceList",      "i", "a(siiiiisss)", get_device_list },
	{ "GetDeviceListCount", "i",            "i", get_device_list_count },
	{ "OpenDevice",         "s",           "ih", open_device },
	/* Add methods here */
};

static const dbus_interface_u dbus_interface = {
	.oh = NULL,
	.name = DEVICED_INTERFACE_USBHOST,
	.methods = dbus_methods,
	.nr_methods = ARRAY_SIZE(dbus_methods),
};


static int booting_done(void *data)
{
	/**
	 * To search the attched usb host device is not an argent task.
	 * So deviced does not load while booting time.
	 * After booting task is done, it tries to find the attached devices.
	 */
	usbhost_init_from_udev_enumerate();

	/* unregister booting done notifier */
	unregister_notifier(DEVICE_NOTIFIER_BOOTING_DONE, booting_done);

	return 0;
}

static void usbhost_init(void *data)
{
	int ret;

	fp_get_var_display_config = dlsym(disp_plgn->handle, "get_var_display_config");
	if (fp_get_var_display_config) {
		disp_conf = fp_get_var_display_config();
		if (!disp_conf)
			_E("Failed to get display config variable.");
		else
			display_on_usb_conn_changed = disp_conf->display_on_usb_conn_changed;
	} else {
		_E("Failed to obtain address of get_var_display_config, %s.", dlerror());
	}

	/* register usbhost uevent */
	ret = register_kernel_uevent_control(&uh);
	if (ret < 0)
		_E("Failed to register usb uevent: %d", ret);

	/* register usbhost interface and method */
	ret = dbus_handle_add_dbus_object(NULL, DEVICED_PATH_USBHOST, &dbus_interface);
	if (ret < 0)
		_E("Failed to register dbus interface and method: %d", ret);

	/* register notifier */
	register_notifier(DEVICE_NOTIFIER_BOOTING_DONE, booting_done);

	ret = asprintf(&POLICY_FILEPATH, "%s/%s", ROOTPATH, POLICY_FILENAME);
	if (ret < 0) {
		_E("No memory for policy path.");
		return;
	}

	ret = subscribe_dbus_signal(NULL, POPUP_PATH_SYSTEM,
		POPUP_INTERFACE_SYSTEM, USB_HOST_RESULT_SIGNAL,
		popup_result_signal_handler, NULL, NULL);
	if (ret < 0) {
		_E("Could not register popup signal handler.");
		return;
	}

	read_policy();
}

static void usbhost_exit(void *data)
{
	int ret;

	/* unreigset usbhost uevent */
	ret = unregister_kernel_uevent_control(&uh);
	if (ret < 0)
		_E("Failed to unregister usb uevent: %d", ret);

	/* remove all usbhost list */
	remove_all_usbhost_list();

	store_policy();
	remove_all_access_list();

	free(POLICY_FILEPATH);
}

static const struct device_ops usbhost_device_ops = {
	.name	= "usbhost",
	.init	= usbhost_init,
	.exit	= usbhost_exit,
};

DEVICE_OPS_REGISTER(&usbhost_device_ops)

static int extcon_usbhost_state_changed(const char *index, int status)
{
	if (status == USBHOST_DISCONNECTED)
		_I("USB host connector disconnected.");
	else
		_I("USB host connector connected.");

	return 0;
}

static struct extcon_ops extcon_usbhost_ops = {
	.name   = EXTCON_CABLE_USB_HOST,
	.update = extcon_usbhost_state_changed,
};

EXTCON_OPS_REGISTER(extcon_usbhost_ops)

static void __CONSTRUCTOR__ initialize(void)
{
	disp_plgn = get_var_display_plugin();
	if (!disp_plgn)
		_E("Failed to get display plugin variable.");
}