summaryrefslogtreecommitdiffstats
blob: debbe48ff73926139ae591f0efa3fda3baf6799b (plain) (blame)
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
/*
 * Copyright (C) 2012 Texas Instruments
 *
 * 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.
 */

#include <usbhost/usbhost.h>
#include <fuse.h>
#include <MtpStorageInfo.h>
#include <MtpObjectInfo.h>
#include <utils/String8.h>
#include <utils/Vector.h>
#include <utils/KeyedVector.h>
#include <stdio.h>
#include <string.h>
#include <MtpDevice.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/statfs.h>
#include <sys/mman.h>


#undef FUSE_USE_VERSION
#define FUSE_USE_VERSION 25

#ifdef DEBUG
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define DBG(a...) {printf(a);}
#else
#define DBG(a...)
#endif

using namespace android;

MtpDevice* mtp_device			= NULL;
int mtp_device_found 			= 0;
MtpStorageIDList* storageAreaList	= NULL;
KeyedVector<uint32_t, char*> storageEntries;

static struct fuse_operations mtpfuse_oper;
typedef Vector <String8*> PathTokenList;
typedef Vector <MtpObjectInfo*> childList;
KeyedVector<uint32_t, childList*> mtpEntries;
KeyedVector<uint32_t, String8> fileDescriptorTable;

static int usb_device_listed(const char *devname, void* client_data) {
		int fd;
		usb_device* device = usb_device_open(devname);
		if (device == NULL) {
			DBG("Error opening device\n");
			return 0;
		}
		fd = usb_device_get_fd(device);
		if (fd < 0) {
			DBG("Error getting fd\n");
			return 0;
		}

		MtpDevice *mtp = MtpDevice::open(devname, fd);
		if (mtp!= NULL) {
			DBG("MTP device found\n");
			mtp_device_found = 1;
			mtp_device = mtp;
		}
		return 0;
}

static int list_devices () {
	struct usb_host_context* context = usb_host_init();
	usb_host_load(context, usb_device_listed, NULL, NULL, NULL);
	return 0;
}

static int get_storage_id(PathTokenList* tokens) {
	String8* storage = tokens->itemAt(0);
	DBG("Storage %s\n", storage->string());
	if (storage == NULL) {
		return -1;
	}
	for (size_t i = 0;i < storageEntries.size();i++) {
		char* desc = storageEntries.valueAt(i);
		if (strcmp(desc, storage->string()) == 0) {
			return storageEntries.keyAt(i);
		}
	}
	return -1;
}

static int mtpfuse_release (const char *path,
			    struct fuse_file_info *fi) {
	return 0;
}

static PathTokenList* tokenize_path(String8* path) {
	String8* remain = path;
	PathTokenList* tokens = new PathTokenList();
	do {
		String8* token = new String8(remain->walkPath(remain));
		tokens->add(token);
	} while (*remain != "");
	return tokens;
}

static MtpObjectInfo* get_mtp_obj_for_path(const char *path) {
	PathTokenList* tokens;
	MtpObjectInfo* ret = NULL;
	String8* path_str = new String8();
	path_str->setPathName(path);
	tokens = tokenize_path(path_str);
	//Go through mtp entries to get the entries
	int storageId = get_storage_id(tokens);
	if (storageId == -1) {
		DBG("Could not get Storage Id\n");
		tokens->removeItemsAt(0, tokens->size());
		delete tokens;
		delete path_str;
		return NULL;
	}
	int found = 0;
	int index = mtpEntries.indexOfKey(storageId);
	childList *list = mtpEntries.valueAt(index);
	if (list != NULL) {
		found = 1;
	}
	MtpObjectInfo *target = NULL;
	if (tokens->size() > 1) {
		found = 0;
		for (size_t i = 1;i < tokens->size();i++) {
			for (size_t j = 0;j < list->size();j++) {
				if (strcmp(list->itemAt(j)->mName, tokens->itemAt(i)->string()) == 0) {
					uint32_t handle = list->itemAt(j)->mHandle;
					target = list->itemAt(j);
					int indx = mtpEntries.indexOfKey(handle);
					list = NULL;
					list = mtpEntries.valueAt(indx);
					if (i == tokens->size() - 1) {
						found = 1;
					}
					break;
				}
			}
		}
	}

	if (found) {
		ret = target;
	}
	tokens->removeItemsAt(0, tokens->size());
	delete tokens;
	delete path_str;
	return target;
}


static int mtpfuse_open (const char * path, struct fuse_file_info *fi) {
	MtpObjectInfo *obj = get_mtp_obj_for_path(path);
	if (obj == NULL) {
		return -ENOENT;
	}
	fi->fh = (uint64_t)obj->mHandle;
	DBG("Handle is %llu %s\n", fi->fh, obj->mName);
	return 0;
}

static int mtpfuse_readdir (const char * path,
			  void *buf, fuse_fill_dir_t filler,
			  off_t offset, struct fuse_file_info *fi) {
	PathTokenList* tokens;
	filler (buf, ".", NULL, 0);
	filler (buf, "..", NULL, 0);

	if (strcmp(path, "/") == 0) {
		//First get the storages
		for (size_t i = 0;i < storageEntries.size();i++) {
			struct stat st;
			memset (&st, 0, sizeof (st));
			st.st_nlink = 2;
			st.st_ino = storageEntries.keyAt(i);
			st.st_mode = S_IFDIR | 0777;
			char *desc = storageEntries.valueAt(i);
			filler (buf, desc, &st, 0);
		}
		return 0;
	} else {
		String8* path_str = new String8();
		path_str->setPathName(path);
		tokens = tokenize_path(path_str);
		//Go through mtp entries to get the entries
		int storageId = get_storage_id(tokens);
		if (storageId == -1) {
			tokens->removeItemsAt(0, tokens->size());
			delete tokens;
			delete path_str;
			return -ENOENT;
		}
		int found = 0;
		int index = mtpEntries.indexOfKey(storageId);
		childList *list = mtpEntries.valueAt(index);
		if (list != NULL) {
			found = 1;
		}

		if (tokens->size() > 1) {
			found = 0;
			for (size_t i = 1;i < tokens->size();i++) {
				for (size_t j = 0;j < list->size();j++) {
					if (strcmp(list->itemAt(j)->mName, tokens->itemAt(i)->string()) == 0) {
						uint32_t handle = list->itemAt(j)->mHandle;
						int indx = mtpEntries.indexOfKey(handle);
						list = NULL;
						list = mtpEntries.valueAt(indx);
						if (i == tokens->size() - 1) {
							found = 1;
						}
						break;
					}
				}
			}
		}

		if (found) {
			if (list != NULL) {
				childList *leaves = NULL;
				for (size_t i = 0;i < list->size();i++) {
					uint32_t handle = list->itemAt(i)->mHandle;
					int indx = mtpEntries.indexOfKey(handle);
					leaves = mtpEntries.valueAt(indx);
					if (leaves) {
						if (leaves->size() == 0) {
							struct stat st;
							memset (&st, 0, sizeof (st));
							st.st_ino = list->itemAt(i)->mHandle;
							st.st_mode = S_IFREG | 0777;
							filler (buf, list->itemAt(i)->mName, &st, 0);
						}else {
							struct stat st;
							memset (&st, 0, sizeof (st));
							st.st_ino = list->itemAt(i)->mHandle;
							st.st_mode = S_IFDIR | 0777;
							filler (buf, list->itemAt(i)->mName, &st, 0);
						}
					}
				}
			}
		}
		tokens->removeItemsAt(0, tokens->size());
		delete tokens;
		delete path_str;
	}
	return 0;
}


static int mtpfuse_get_mtp_objects(const char * path) {
	//First get the storages
	for (size_t i = 0;i < storageAreaList->size();i++) {
		uint32_t storageId = storageAreaList->itemAt(i);
		//Each storage has handle
		childList *forRoot = new childList;
		mtpEntries.add(storageId, forRoot);
		MtpObjectHandleList* mo_list =
				mtp_device->getObjectHandles(storageId, 0, 0);
		if (mo_list != NULL) {
			//Each mtp object handle is associated with a Vector of child nodes.
			//The object is stored as a KeyedVector which has an associated child Vector
			for (size_t i = 0;i < mo_list->size();i++) {
				MtpObjectInfo* info =  mtp_device->getObjectInfo
							(mo_list->itemAt(i));
				childList *c = new childList;
				mtpEntries.add(info->mHandle, c);
				//Handle to childList
				childList* parent_child_list = NULL;
				int index = -1;
				if (info->mParent != 0) {
					index = mtpEntries.indexOfKey(info->mParent);
				}else {
					index = mtpEntries.indexOfKey(storageId);
				}
				if (index == -1) {
					continue;
				}
				parent_child_list = mtpEntries.valueAt(index);
				if (parent_child_list != NULL) {
					parent_child_list->add(info);
				}else {
					DBG("No handle to parent's list\n");
				}
			}
		}
	}
	return 0;
}

static int mtpfuse_getattr (const char * path, struct stat *stbuf) {
	PathTokenList* tokens;

	memset (stbuf, 0, sizeof (struct stat));

	struct fuse_context *fc;
	fc = fuse_get_context();
	stbuf->st_uid = fc->uid;
	stbuf->st_gid = fc->gid;

	if (strcmp(path, "/") == 0) {
		stbuf->st_mode = S_IFDIR | 0777;
		stbuf->st_nlink = 2;
		return 0;

	} else {
		String8* path_str = new String8();
		path_str->setPathName(path);
		tokens = tokenize_path(path_str);
		//Go through mtp entries to get the entries
		int storageId = get_storage_id(tokens);
		if (storageId == -1) {
			tokens->removeItemsAt(0, tokens->size());
			delete tokens;
			delete path_str;
			return -ENOENT;
		}
		int found = 0;
		int index = mtpEntries.indexOfKey(storageId);
		childList *list = mtpEntries.valueAt(index);
		if (list != NULL) {
			found = 1;
		}
		MtpObjectInfo *target = NULL;
		if (tokens->size() > 1) {
			found = 0;
			for (size_t i = 1;i < tokens->size();i++) {
				for (size_t j = 0;j < list->size();j++) {
					if (strcmp(list->itemAt(j)->mName, tokens->itemAt(i)->string()) == 0) {
						uint32_t handle = list->itemAt(j)->mHandle;
						target = list->itemAt(j);
						int indx = mtpEntries.indexOfKey(handle);
						list = NULL;
						list = mtpEntries.valueAt(indx);
						if (i == tokens->size() - 1) {
							found = 1;
						}
						break;
					}
				}
			}
		}
		if (found) {
			if (list != NULL) {
				//If an object has no child nodes, assume it to be a directory
				if (list->size() == 0) {
					DBG("File\n");
					stbuf->st_ino = target->mHandle;
					stbuf->st_size = target->mCompressedSize;
					stbuf->st_blocks = (target->mCompressedSize / 512) +
						(target->mCompressedSize % 512 > 0 ? 1 : 0);
					stbuf->st_nlink = 1;
					stbuf->st_mode = S_IFREG | 0777;
					stbuf->st_uid = 1000;
					stbuf->st_gid = 1015;
					stbuf->st_mtime = target->mDateModified;
					stbuf->st_ctime = target->mDateModified;
					stbuf->st_atime = target->mDateModified;
				}else {
					DBG("Directory\n");
					if (target != NULL)
						stbuf->st_ino = target->mHandle;
					stbuf->st_mode = S_IFDIR | 0777;
					stbuf->st_nlink = 2;
					stbuf->st_uid = 1000;
					stbuf->st_gid = 1015;
				}
			}
		}
		tokens->removeItemsAt(0, tokens->size());
		delete tokens;
		delete path_str;
	}
	return 0;
}

bool read_callback (void* data, int offset, int length, void* clientData) {
	//DBG("Received read callback %d %d\n", offset, length);
	memcpy((char *)clientData + offset, data, length);
	return true;
}

static int mtpfuse_read (const char * path, char * buf,
		       			  size_t size, off_t offset,
		                  struct fuse_file_info *fi) {
	int ret;
	MtpObjectHandle h = (MtpObjectHandle)fi->fh;
	bool status = mtp_device->readObject(h, read_callback, size, offset, buf);
	if (status == false) {
		ret = 0;
	}else {
		ret = size;
	}
	return ret;
}

static void start_media_scanner() {
	const char* cmd =
	"am broadcast -a android.intent.action.MEDIA_MOUNTED -d file:///mnt/shell/emulated/0";
	system(cmd);
}

void mtpfuse_destroy (void *) {
	//Release mtp entries
	for (size_t i = 0;i < mtpEntries.size();i++) {
		childList* list = mtpEntries.valueAt(i);
		list->clear();
	}
	mtpEntries.clear();
	mtp_device->close();
	storageEntries.clear();
	start_media_scanner();
}

void * mtpfuse_init (struct fuse_conn_info *conn) {
	return 0;
}

int main(int argc, char* argv[]) {
	int fuse_stat;

	/*Create the mount directory, if it doesn't exist*/
	struct stat st;
	if (stat(argv[1], &st) != 0) {
		if (mkdir(argv[1], S_IRWXU) != 0 && errno != EEXIST) {
			printf("Could not create mount point %d\n", errno);
			exit(0);
		}
	}

	list_devices();
	if (mtp_device_found && mtp_device != NULL) {
		storageAreaList = mtp_device->getStorageIDs();
		if (storageAreaList == NULL) {
			return 0;
		}

		if (storageAreaList->size() == 0) {
			printf("No storages found\n");
			return 0;
		}
		printf("Found %d storage(s)\n", storageAreaList->size());
		for (size_t i = 0;i < storageAreaList->size();i++) {
			MtpStorageInfo* storageInfo = mtp_device->getStorageInfo(storageAreaList->itemAt(i));
			printf("Desc: %s\n", storageInfo->mStorageDescription);
			storageEntries.add(storageAreaList->itemAt(i), storageInfo->mStorageDescription);
		}
		mtpfuse_get_mtp_objects("/");
		mtpfuse_oper.readdir = mtpfuse_readdir;
		mtpfuse_oper.release = mtpfuse_release;
		mtpfuse_oper.getattr = mtpfuse_getattr;
		mtpfuse_oper.open = mtpfuse_open;
		mtpfuse_oper.read = mtpfuse_read;
		mtpfuse_oper.destroy = mtpfuse_destroy;
		//Mount fuse
		DBG("Setting up FUSE\n");
		fuse_stat = fuse_main(argc, argv, &mtpfuse_oper);
		return fuse_stat;
	}
	return 0;
}