~ted/ubuntu-app-launch/uri-splitting

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
/*
 * Copyright 2013 Canonical Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 3, 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 warranties of
 * MERCHANTABILITY, SATISFACTORY QUALITY, 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, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *     Ted Gould <ted.gould@canonical.com>
 */

#include <gio/gio.h>
#include <nih/alloc.h>
#include <libnih-dbus.h>
#include "libupstart-app-launch/upstart-app-launch.h"
#include "helpers.h"
#include "second-exec-core.h"

/* Globals */
GPid app_pid = 0;
GMainLoop * mainloop = NULL;
guint connections_open = 0;
const gchar * appid = NULL;
const gchar * input_uris = NULL;
GVariant * app_data = NULL;
gchar * dbus_path = NULL;
guint64 unity_starttime = 0;
guint timer = 0;

/* Unity didn't respond in time, continue on */
static gboolean
timer_cb (gpointer user_data)
{
	g_warning("Unity didn't respond in 500ms to resume the app");
	g_main_loop_quit(mainloop);
	return G_SOURCE_REMOVE;
}

/* Lower the connection count and process if it gets to zero */
static void
connection_count_dec (void)
{
	connections_open--;
	if (connections_open == 0) {
		g_debug("Finished finding connections");
		/* Check time here, either we've already heard from
		   Unity and we should send the data to the app (quit) or
		   we should wait some more */
		guint64 timespent = g_get_monotonic_time() - unity_starttime;
		if (timespent > 500 /* ms */ * 1000 /* ms to us */) {
			g_main_loop_quit(mainloop);
		} else {
			g_debug("Timer Set");
			timer = g_timeout_add(500 - (timespent / 1000), timer_cb, NULL);
		}
	}
	return;
}

/* Called when Unity is done unfreezing the application, if we're
   done determining the PID, we can send signals */
static void
unity_resume_cb (GDBusConnection * connection, const gchar * sender, const gchar * path, const gchar * interface, const gchar * signal, GVariant * params, gpointer user_data)
{
	g_debug("Unity Completed Resume");

	if (timer != 0) {
		g_source_remove(timer);
	}

	if (connections_open == 0) {
		g_main_loop_quit(mainloop);
	} else {
		/* Make it look like we started *forever* ago */
		unity_starttime = 0;
	}

	return;
}

/* Turn the input string into something we can send to apps */
static void
parse_uris (void)
{
	if (app_data != NULL) {
		/* Already done */
		return;
	}

	/* TODO: Joining only with space could cause issues with breaking them
	   back out.  We don't have any cases of more than one today.  But, this
	   isn't good.
	   https://bugs.launchpad.net/upstart-app-launch/+bug/1229354
	   */
	GVariant * uris = NULL;
	gchar ** uri_split = g_strsplit(input_uris, " ", 0);
	if (uri_split[0] == NULL) {
		g_free(uri_split);
		uris = g_variant_new_array(G_VARIANT_TYPE_STRING, NULL, 0);
	} else {
		GVariantBuilder builder;
		g_variant_builder_init(&builder, G_VARIANT_TYPE_ARRAY);

		int i;
		for (i = 0; uri_split[i] != NULL; i++) {
			g_variant_builder_add_value(&builder, g_variant_new_take_string(uri_split[i]));
		}
		g_free(uri_split);

		uris = g_variant_builder_end(&builder);
	}

	GVariant * platform = g_variant_new_array(G_VARIANT_TYPE("{sv}"), NULL, 0);

	GVariantBuilder tuple;
	g_variant_builder_init(&tuple, G_VARIANT_TYPE_TUPLE);
	g_variant_builder_add_value(&tuple, uris);
	g_variant_builder_add_value(&tuple, platform);

	app_data = g_variant_builder_end(&tuple);
	g_variant_ref_sink(app_data);

	return;
}

/* Finds us our dbus path to use.  Basically this is the name
   of the application with dots replaced by / and a / tacted on
   the front.  This is recommended here:

   http://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#dbus   
*/
static void
app_id_to_dbus_path (void)
{
	if (dbus_path != NULL) {
		return;
	}

	dbus_path = nih_dbus_path(NULL, "", appid, NULL);
	g_debug("DBus Path: %s", dbus_path);

	return;
}

/* Finish the send and decrement the counter */
static void
send_open_cb (GObject * object, GAsyncResult * res, gpointer user_data)
{
	GError * error = NULL;

	g_dbus_connection_call_finish(G_DBUS_CONNECTION(object), res, &error);

	if (error != NULL) {
		/* Mostly just to free the error, but printing for debugging */
		g_debug("Unable to send Open: %s", error->message);
		g_error_free(error);
	}

	connection_count_dec();
	return;
}

/* Sends the Open message to the connection with the URIs we were given */
static void
contact_app (GDBusConnection * bus, const gchar * dbus_name)
{
	parse_uris();
	app_id_to_dbus_path();

	/* Using the FD.o Application interface */
	g_dbus_connection_call(bus,
		dbus_name,
		dbus_path,
		"org.freedesktop.Application",
		"Open",
		app_data,
		NULL,
		G_DBUS_CALL_FLAGS_NONE,
		-1,
		NULL,
		send_open_cb, NULL);

	g_debug("Sending Open request to: %s", dbus_name);

	return;
}

/* Gets the PID for a connection, and if it matches the one we're looking
   for then it tries to send a message to that connection */
static void
get_pid_cb (GObject * object, GAsyncResult * res, gpointer user_data)
{
	gchar * dbus_name = (gchar *)user_data;
	GError * error = NULL;
	GVariant * vpid = NULL;

	vpid = g_dbus_connection_call_finish(G_DBUS_CONNECTION(object), res, &error);

	if (error != NULL) {
		g_warning("Unable to query PID for dbus name '%s': %s", dbus_name, error->message);
		g_error_free(error);
		g_free(dbus_name);

		/* Lowering the connection count, this one is terminal, even if in error */
		connection_count_dec();
		return;
	}

	guint pid = 0;
	g_variant_get(vpid, "(u)", &pid);
	g_variant_unref(vpid);

	if (pid == app_pid) {
		/* Trying to send a message to the connection */
		contact_app(G_DBUS_CONNECTION(object), dbus_name);
	} else {
		/* See if we can quit now */
		connection_count_dec();
	}

	g_free(dbus_name);

	return;
}

/* Starts to look for the PID and the connections for that PID */
void
find_appid_pid (GDBusConnection * session)
{
	GError * error = NULL;

	/* List all the connections on dbus.  This sucks that we have to do
	   this, but in the future we should add DBus API to do this lookup
	   instead of having to do it with a bunch of requests */
	GVariant * listnames = g_dbus_connection_call_sync(session,
		"org.freedesktop.DBus",
		"/",
		"org.freedesktop.DBus",
		"ListNames",
		NULL,
		G_VARIANT_TYPE("(as)"),
		G_DBUS_CALL_FLAGS_NONE,
		-1,
		NULL,
		&error);

	if (error != NULL) {
		g_warning("Unable to get list of names from DBus: %s", error->message);
		g_error_free(error);
		return;
	}

	/* Next figure out what we're looking for (and if there is something to look for) */
	/* NOTE: We're getting the PID *after* the list of connections so
	   that some new process can't come in, be the same PID as it's
	   connection will not be in teh list we just got. */
	app_pid = upstart_app_launch_get_primary_pid(appid);
	if (app_pid == 0) {
		g_warning("Unable to find pid for app id '%s'", appid);
		return;
	}

	/* Get the names */
	GVariant * names = g_variant_get_child_value(listnames, 0);
	GVariantIter iter;
	g_variant_iter_init(&iter, names);
	gchar * name = NULL;

	while (g_variant_iter_loop(&iter, "s", &name)) {
		/* We only want to ask each connection once, this makes that so */
		if (!g_dbus_is_unique_name(name)) {
			continue;
		}

		/* Get the PIDs */
		g_dbus_connection_call(session,
			"org.freedesktop.DBus",
			"/",
			"org.freedesktop.DBus",
			"GetConnectionUnixProcessID",
			g_variant_new("(s)", name),
			G_VARIANT_TYPE("(u)"),
			G_DBUS_CALL_FLAGS_NONE,
			-1,
			NULL,
			get_pid_cb, g_strdup(name));

		connections_open++;
	}

	g_variant_unref(names);
	g_variant_unref(listnames);

	return;
}

gboolean
second_exec (const gchar * app_id, const gchar * appuris)
{
	appid = app_id;
	input_uris = appuris;

	/* DBus tell us! */
	GError * error = NULL;
	GDBusConnection * session = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error);
	if (error != NULL) {
		g_error("Unable to get session bus");
		g_error_free(error);
		return FALSE;
	}

	/* Allocate main loop */
	mainloop = g_main_loop_new(NULL, FALSE);

	/* Set up listening for the unfrozen signal from Unity */
	g_dbus_connection_signal_subscribe(session,
		NULL, /* sender */
		"com.canonical.UpstartAppLaunch", /* interface */
		"UnityResumeResponse", /* signal */
		"/", /* path */
		appid, /* arg0 */
		G_DBUS_SIGNAL_FLAGS_NONE,
		unity_resume_cb, mainloop,
		NULL); /* user data destroy */

	/* Send unfreeze to to Unity */
	g_dbus_connection_emit_signal(session,
		NULL, /* destination */
		"/", /* path */
		"com.canonical.UpstartAppLaunch", /* interface */
		"UnityResumeRequest", /* signal */
		g_variant_new("(s)", appid),
		&error);

	/* Now we start a race, we try to get to the point of knowing who
	   to send things to, and Unity is unfrezing it.  When both are
	   done we can send something to the app */
	unity_starttime = g_get_monotonic_time();

	if (error != NULL) {
		/* On error let's not wait for Unity */
		g_warning("Unable to signal Unity: %s", error->message);
		g_error_free(error);
		error = NULL;
		unity_starttime = 0;
	}

	/* If we've got something to give out, start looking for how */
	if (input_uris != NULL) {
		find_appid_pid(session);
	}

	/* Loop and wait for everything to align */
	if (connections_open > 0 || unity_starttime > 0) {
		g_main_loop_run(mainloop);
	}
	g_debug("Finishing main loop");

	/* Now that we're done sending the info to the app, we can ask
	   Unity to focus the application. */
	g_dbus_connection_emit_signal(session,
		NULL, /* destination */
		"/", /* path */
		"com.canonical.UpstartAppLaunch", /* interface */
		"UnityFocusRequest", /* signal */
		g_variant_new("(s)", appid),
		&error);

	if (error != NULL) {
		g_warning("Unable to request focus to Unity: %s", error->message);
		g_error_free(error);
		error = NULL;
	}

	/* Make sure the signal hits the bus */
	g_dbus_connection_flush_sync(session, NULL, NULL);

	/* Clean up */
	if (app_data != NULL) {
		g_variant_unref(app_data);
		app_data = NULL;
	}

	g_main_loop_unref(mainloop);
	g_object_unref(session);

	if (dbus_path != NULL) {
		nih_free(dbus_path);
		dbus_path = NULL;
	}

	return TRUE;
}