summaryrefslogtreecommitdiff
path: root/src/bt-obex.c
blob: e9f7432fcda283695b7e2a5c52aec9b1db3bb82b (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
/*
 *
 *  bluez-tools - a set of tools to manage bluetooth devices for linux
 *
 *  Copyright (C) 2010  Alexander Orlenko <zxteam@gmail.com>
 *
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

#include <readline/readline.h>
#include <readline/history.h>

#include <glib.h>

#include "lib/dbus-common.h"
#include "lib/helpers.h"
#include "lib/bluez-api.h"
#include "lib/obexd-api.h"

static GHashTable *server_transfers = NULL;
static GMainLoop *mainloop = NULL;

static void sigterm_handler(int sig)
{
	g_message("%s received", sig == SIGTERM ? "SIGTERM" : "SIGINT");

	if (g_main_loop_is_running(mainloop))
		g_main_loop_quit(mainloop);
}

static void agent_released(OBEXAgent *agent, gpointer data)
{
	g_assert(data != NULL);
	GMainLoop *mainloop = data;

	if (g_main_loop_is_running(mainloop))
		g_main_loop_quit(mainloop);
}

/* OBEXTransfer signals */
static void obextransfer_progress(OBEXTransfer *transfer, gint total, gint transfered, gpointer data)
{
	guint pp = (transfered / (gfloat) total)*100;

	static gboolean update_progress = FALSE;
	if (!update_progress) {
		g_print("[OBEXTransfer] Progress: %3u%%", pp);
		update_progress = TRUE;
	} else {
		g_print("\b\b\b\b%3u%%", pp);
	}

	if (pp == 100) {
		g_print("\n");
		update_progress = FALSE;
	}
}

/* OBEXManager signals */
static void obexmanager_session_created(OBEXManager *manager, const gchar *session_path, gpointer data)
{
	g_print("[OBEXManager] FTP session opened\n");
}

static void obexmanager_session_removed(OBEXManager *manager, const gchar *session_path, gpointer data)
{
	g_print("[OBEXManager] FTP session closed\n", session_path);
}

static void obexmanager_transfer_started(OBEXManager *manager, const gchar *transfer_path, gpointer data)
{
	g_print("[OBEXManager] Transfer started\n", transfer_path);

	OBEXTransfer *t = g_object_new(OBEXTRANSFER_TYPE, "DBusObjectPath", transfer_path, NULL);
	g_signal_connect(t, "Progress", G_CALLBACK(obextransfer_progress), NULL);
	g_hash_table_insert(server_transfers, transfer_path, t);
}

static void obexmanager_transfer_completed(OBEXManager *manager, const gchar *transfer_path, gboolean success, gpointer data)
{
	OBEXTransfer *t = g_hash_table_lookup(server_transfers, transfer_path);
	if (t) {
		g_print("[OBEXManager] Transfer %s\n", success == TRUE ? "succeeded" : "failed");
		g_object_unref(t);
		g_hash_table_remove(server_transfers, transfer_path);
	} else {
		// Bug ?
	}
}

/* Async callback for SendFiles() */
/*static void send_files_done(gpointer data)
{
	g_assert(data != NULL);
	GMainLoop *mainloop = data;
	g_main_loop_quit(mainloop);
}*/

/* Main arguments */
static gchar *adapter_arg = NULL;
static gboolean server_arg = FALSE;
static gchar *server_path_arg = NULL;
static gboolean opp_arg = FALSE;
static gchar *opp_device_arg = NULL;
static gchar *opp_file_arg = NULL;
static gchar *ftp_arg = NULL;

static GOptionEntry entries[] = {
	{"adapter", 'a', 0, G_OPTION_ARG_STRING, &adapter_arg, "Adapter name or MAC", "<name|mac>"},
	{"server", 's', 0, G_OPTION_ARG_NONE, &server_arg, "Register self at OBEX server", NULL},
	{"opp", 'p', 0, G_OPTION_ARG_NONE, &opp_arg, "Send file to remote device", NULL},
	{"ftp", 'f', 0, G_OPTION_ARG_STRING, &ftp_arg, "Start FTP session with remote device", "<name|mac>"},
	{NULL}
};

int main(int argc, char *argv[])
{
	GError *error = NULL;
	GOptionContext *context;

	g_type_init();
	dbus_init();

	context = g_option_context_new(" - a bluetooth OBEX client/server");
	g_option_context_add_main_entries(context, entries, NULL);
	g_option_context_set_summary(context, "Version "PACKAGE_VERSION);
	g_option_context_set_description(context,
			"Server Options:\n"
			"  -s, --server [<path>]\n"
			"  Register self at OBEX server and use given `path` as OPP save directory\n"
			"  If `path` does not specified - use current directory\n\n"
			"OPP Options:\n"
			"  -p, --opp <name|mac> <file>\n"
			"  Send `file` to remote device using Object Push Profile\n\n"
			//"Report bugs to <"PACKAGE_BUGREPORT">."
			"Project home page <"PACKAGE_URL">."
			);

	if (!g_option_context_parse(context, &argc, &argv, &error)) {
		g_print("%s: %s\n", g_get_prgname(), error->message);
		g_print("Try `%s --help` for more information.\n", g_get_prgname());
		exit(EXIT_FAILURE);
	} else if (!server_arg && !opp_arg && (!ftp_arg || strlen(ftp_arg) == 0)) {
		g_print("%s", g_option_context_get_help(context, FALSE, NULL));
		exit(EXIT_FAILURE);
	} else if (server_arg && argc != 1 && (argc != 2 || strlen(argv[1]) == 0)) {
		g_print("%s: Invalid arguments for --server\n", g_get_prgname());
		g_print("Try `%s --help` for more information.\n", g_get_prgname());
		exit(EXIT_FAILURE);
	} else if (opp_arg && (argc != 3 || strlen(argv[1]) == 0 || strlen(argv[2]) == 0)) {
		g_print("%s: Invalid arguments for --opp\n", g_get_prgname());
		g_print("Try `%s --help` for more information.\n", g_get_prgname());
		exit(EXIT_FAILURE);
	}

	g_option_context_free(context);

	if (!dbus_system_connect(&error)) {
		g_printerr("Couldn't connect to dbus system bus: %s\n", error->message);
		exit(EXIT_FAILURE);
	}

	if (!dbus_session_connect(&error)) {
		g_printerr("Couldn't connect to dbus session bus: %s\n", error->message);
		exit(EXIT_FAILURE);
	}

	/* Check, that bluetooth daemon is running */
	if (!intf_supported(BLUEZ_DBUS_NAME, MANAGER_DBUS_PATH, MANAGER_DBUS_INTERFACE)) {
		g_printerr("%s: BLUEZ service does not found\n", g_get_prgname());
		g_printerr("Did you forget to run bluetoothd?\n");
		exit(EXIT_FAILURE);
	}

	/* Check, that obexd daemon is running */
	if (!intf_supported(OBEXD_DBUS_NAME, OBEXMANAGER_DBUS_PATH, OBEXMANAGER_DBUS_INTERFACE)) {
		g_printerr("%s: OBEXD service does not found\n", g_get_prgname());
		g_printerr("Did you forget to run obexd?\n");
		exit(EXIT_FAILURE);
	}

	if (server_arg) {
		if (argc == 2) {
			server_path_arg = argv[1];
		}

		/* Check that `path` is valid */
		gchar *root_dir = NULL;
		if (server_path_arg == NULL) {
			root_dir = g_get_current_dir();
		} else {
			struct stat buf;
			if (stat(server_path_arg, &buf) != 0) {
				g_printerr("%s: %s\n", g_get_prgname(), strerror(errno));
				exit(EXIT_FAILURE);
			}
			if (!S_ISDIR(buf.st_mode)) {
				g_printerr("%s: Invalid directory: %s\n", g_get_prgname(), server_path_arg);
				exit(EXIT_FAILURE);
			}
			root_dir = g_strdup(server_path_arg);
		}

		server_transfers = g_hash_table_new(g_str_hash, g_str_equal);

		OBEXManager *manager = g_object_new(OBEXMANAGER_TYPE, NULL);
		g_signal_connect(manager, "SessionCreated", G_CALLBACK(obexmanager_session_created), NULL);
		g_signal_connect(manager, "SessionRemoved", G_CALLBACK(obexmanager_session_removed), NULL);
		g_signal_connect(manager, "TransferStarted", G_CALLBACK(obexmanager_transfer_started), NULL);
		g_signal_connect(manager, "TransferCompleted", G_CALLBACK(obexmanager_transfer_completed), NULL);

		OBEXAgent *agent = g_object_new(OBEXAGENT_TYPE, "RootFolder", root_dir, NULL);

		g_free(root_dir);

		obexmanager_register_agent(manager, OBEXAGENT_DBUS_PATH, &error);
		exit_if_error(error);

		mainloop = g_main_loop_new(NULL, FALSE);

		/* Add SIGTERM && SIGINT handlers */
		struct sigaction sa;
		memset(&sa, 0, sizeof(sa));
		sa.sa_handler = sigterm_handler;
		sigaction(SIGTERM, &sa, NULL);
		sigaction(SIGINT, &sa, NULL);

		g_main_loop_run(mainloop);

		/* Waiting for connections... */

		g_main_loop_unref(mainloop);

		/* Stop active transfers */
		GHashTableIter iter;
		gpointer key, value;
		g_hash_table_iter_init(&iter, server_transfers);
		while (g_hash_table_iter_next(&iter, &key, &value)) {
			OBEXTransfer *t = OBEXTRANSFER(value);
			obextransfer_cancel(t, NULL);
			g_object_unref(t);
			g_hash_table_iter_remove(&iter);
		}
		g_hash_table_unref(server_transfers);

		obexmanager_unregister_agent(manager, OBEXAGENT_DBUS_PATH, &error);
		g_object_unref(agent);
		g_object_unref(manager);
	} else if (opp_arg) {
		opp_device_arg = argv[1];
		opp_file_arg = argv[2];

		/* Check that `file` is valid and readable */
		{
			struct stat buf;
			if (stat(opp_file_arg, &buf) != 0) {
				g_printerr("%s: %s\n", g_get_prgname(), strerror(errno));
				exit(EXIT_FAILURE);
			}
			if (!S_ISREG(buf.st_mode)) {
				g_printerr("%s: Invalid file: %s\n", g_get_prgname(), opp_file_arg);
				exit(EXIT_FAILURE);
			}
		}
		gchar * files_to_send[] = {NULL, NULL};
		if (!g_path_is_absolute(opp_file_arg)) {
			gchar *current_dir = g_get_current_dir();
			files_to_send[0] = g_build_filename(current_dir, opp_file_arg, NULL);
			g_free(current_dir);
		} else {
			files_to_send[0] = g_strdup(opp_file_arg);
		}

		/* Get source address (address of adapter) */
		Adapter *adapter = find_adapter(adapter_arg, &error);
		exit_if_error(error);
		gchar *src_address = g_strdup(adapter_get_address(adapter));

		/* Get destination address (address of remote device) */
		Device *device = find_device(adapter, opp_device_arg, &error);
		if (error && g_strcmp0(dbus_g_error_get_name(error), "org.bluez.Error.DoesNotExist") != 0)
			exit_if_error(error);
		gchar *dst_address = g_strdup(device == NULL ? opp_device_arg : device_get_address(device));

		g_object_unref(device);
		g_object_unref(adapter);

		/* Build arguments */
		GHashTable *device_dict = g_hash_table_new(g_str_hash, g_str_equal);
		GValue source = {0};
		GValue destination = {0};
		g_value_init(&source, G_TYPE_STRING);
		g_value_init(&destination, G_TYPE_STRING);
		g_value_set_string(&source, src_address);
		g_value_set_string(&destination, dst_address);
		g_hash_table_insert(device_dict, "Source", &source);
		g_hash_table_insert(device_dict, "Destination", &destination);

		mainloop = g_main_loop_new(NULL, FALSE);

		OBEXClient *client = g_object_new(OBEXCLIENT_TYPE, NULL);

		OBEXAgent *agent = g_object_new(OBEXAGENT_TYPE, NULL);
		g_signal_connect(agent, "AgentReleased", G_CALLBACK(agent_released), mainloop);

		/* Sending file(s) */
		obexclient_send_files(client, device_dict, files_to_send, OBEXAGENT_DBUS_PATH, &error);
		exit_if_error(error);

		/* Add SIGTERM && SIGINT handlers */
		struct sigaction sa;
		memset(&sa, 0, sizeof(sa));
		sa.sa_handler = sigterm_handler;
		sigaction(SIGTERM, &sa, NULL);
		sigaction(SIGINT, &sa, NULL);

		g_main_loop_run(mainloop);

		/* Sending files process here ?? */

		g_main_loop_unref(mainloop);

		g_object_unref(agent);
		g_object_unref(client);

		g_value_unset(&source);
		g_value_unset(&destination);
		g_hash_table_unref(device_dict);

		g_free(src_address);
		g_free(dst_address);
		g_free(files_to_send[0]);
		files_to_send[0] = NULL;
	} else if (ftp_arg) {
		/* Get source address (address of adapter) */
		Adapter *adapter = find_adapter(adapter_arg, &error);
		exit_if_error(error);
		gchar *src_address = g_strdup(adapter_get_address(adapter));

		/* Get destination address (address of remote device) */
		Device *device = find_device(adapter, ftp_arg, &error);
		exit_if_error(error);
		gchar *dst_address = g_strdup(device == NULL ? ftp_arg : device_get_address(device));

		g_object_unref(device);
		g_object_unref(adapter);

		/* Build arguments */
		GHashTable *device_dict = g_hash_table_new(g_str_hash, g_str_equal);
		GValue source = {0};
		GValue destination = {0};
		GValue target = {0};
		g_value_init(&source, G_TYPE_STRING);
		g_value_init(&destination, G_TYPE_STRING);
		g_value_init(&target, G_TYPE_STRING);
		g_value_set_string(&source, src_address);
		g_value_set_string(&destination, dst_address);
		g_value_set_string(&target, "FTP");
		g_hash_table_insert(device_dict, "Source", &source);
		g_hash_table_insert(device_dict, "Destination", &destination);
		g_hash_table_insert(device_dict, "Target", &target);

		OBEXClient *client = g_object_new(OBEXCLIENT_TYPE, NULL);
		OBEXAgent *agent = g_object_new(OBEXAGENT_TYPE, NULL);

		/* Create FTP session */
		gchar *session_path = obexclient_create_session(client, device_dict, &error);
		exit_if_error(error);

		OBEXClientFileTransfer *ftp_session = g_object_new(OBEXCLIENT_FILE_TRANSFER_TYPE, "DBusObjectPath", session_path, NULL);
		g_free(session_path);

		g_print("FTP session opened\n");

		while (TRUE) {
			gchar *cmd = readline("> ");
			if (cmd == NULL || strlen(cmd) == 0) {
				continue;
			} else {
				add_history(cmd);
			}

			gint f_argc;
			gchar **f_argv;
			/* Parsing command line */
			if (!g_shell_parse_argv(cmd, &f_argc, &f_argv, &error)) {
				g_print("%s\n", error->message);
				g_error_free(error);
				error = NULL;
			}

			/* Execute commands */
			if (g_strcmp0(f_argv[0], "cd") == 0) {
				if (f_argc != 2 || strlen(f_argv[1]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_change_folder(ftp_session, f_argv[1], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "mkdir") == 0) {
				if (f_argc != 2 || strlen(f_argv[1]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_create_folder(ftp_session, f_argv[1], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "ls") == 0) {
				if (f_argc != 1) {
					g_print("invalid arguments\n");
				} else {
					GPtrArray *folders = obexclient_file_transfer_list_folder(ftp_session, &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					} else {
						for (int i = 0; i < folders->len; i++) {
							GHashTable *el = g_ptr_array_index(folders, i);
							g_print("%s\n", g_value_get_string(g_hash_table_lookup(el, "Name")));
						}
						//g_ptr_array_unref(folders);

						/*obexclient_remove_session(client, obexclient_file_transfer_get_dbus_object_path(ftp_session), &error);
						exit_if_error(error);
						g_object_unref(ftp_session);
						session_path = obexclient_create_session(client, device_dict, &error);
						exit_if_error(error);
						ftp_session = g_object_new(OBEXCLIENT_FILE_TRANSFER_TYPE, "DBusObjectPath", session_path, NULL);
						g_free(session_path);*/
					}
				}
			} else if (g_strcmp0(f_argv[0], "get") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_get_file(ftp_session, f_argv[1], f_argv[2], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "put") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_put_file(ftp_session, f_argv[1], f_argv[2], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "cp") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_copy_file(ftp_session, f_argv[1], f_argv[2], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "mv") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_move_file(ftp_session, f_argv[1], f_argv[2], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "rm") == 0) {
				if (f_argc != 2 || strlen(f_argv[1]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_delete(ftp_session, f_argv[1], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "help") == 0) {

			} else if (g_strcmp0(f_argv[0], "exit") == 0 || g_strcmp0(f_argv[0], "quit") == 0) {
				obexclient_remove_session(client, obexclient_file_transfer_get_dbus_object_path(ftp_session), &error);
				exit_if_error(error);
				
				g_strfreev(f_argv);
				g_free(cmd);
				break;
			} else {
				g_print("invalid command\n");
			}

			g_strfreev(f_argv);
			g_free(cmd);
		}
	}

	dbus_disconnect();

	exit(EXIT_SUCCESS);
}