File: DBusService.cpp

package info (click to toggle)
firefox 147.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,683,484 kB
  • sloc: cpp: 7,607,246; javascript: 6,533,185; ansic: 3,775,227; python: 1,415,393; xml: 634,561; asm: 438,951; java: 186,241; sh: 62,752; makefile: 18,079; objc: 13,092; perl: 12,808; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (312 lines) | stat: -rw-r--r-- 11,282 bytes parent folder | download | duplicates (2)
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <gdk/gdk.h>
#include "DBusService.h"
#include "nsAppRunner.h"
#include "mozilla/GUniquePtr.h"
#include "mozilla/WidgetUtils.h"
#include <gio/gio.h>
#include "nsIObserverService.h"
#include "WidgetUtilsGtk.h"
#include "prproces.h"
#include "mozilla/XREAppData.h"
#include "nsPrintfCString.h"

using namespace mozilla;
using namespace mozilla::widget;

DBusService::~DBusService() { StopFreedesktopListener(); }

bool DBusService::Init() { return StartFreedesktopListener(); }

void DBusService::Run() {
  GMainLoop* loop = g_main_loop_new(nullptr, false);
  g_main_loop_run(loop);
  g_main_loop_unref(loop);
}

// Mozilla has old GIO version in build roots
#define G_BUS_NAME_OWNER_FLAGS_DO_NOT_QUEUE GBusNameOwnerFlags(1 << 2)

#define DBUS_BUS_NAME_TEMPLATE "org.mozilla.%s"
#define DBUS_OBJECT_PATH_TEMPLATE "/org/mozilla/%s"

static const char* GetDBusBusName() {
  static const char* name = []() {
    nsAutoCString appName;
    gAppData->GetDBusAppName(appName);
    return ToNewCString(nsPrintfCString(DBUS_BUS_NAME_TEMPLATE,
                                        appName.get()));  // Intentionally leak
  }();
  return name;
}

static const char* GetDBusObjectPath() {
  static const char* path = []() {
    nsAutoCString appName;
    gAppData->GetDBusAppName(appName);
    return ToNewCString(nsPrintfCString(DBUS_OBJECT_PATH_TEMPLATE,
                                        appName.get()));  // Intentionally leak
  }();
  return path;
}

// See
// https://specifications.freedesktop.org/desktop-entry-spec/1.1/ar01s07.html
// for details
static const char* kIntrospectTemplate =
    "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection "
    "1.0//EN\"\n"
    "\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
    "<node>\n"
    "<interface name='org.freedesktop.Application'>\n"
    "<method name='Activate'>\n"
    "  <arg type='a{sv}' name='platform_data' direction='in'/>\n"
    "  </method>\n"
    "  <method name='Open'>\n"
    "  <arg type='as' name='uris' direction='in'/>\n"
    "  <arg type='a{sv}' name='platform_data' direction='in'/>\n"
    "</method>\n"
    "<method name='ActivateAction'>\n"
    "  <arg type='s' name='action_name' direction='in'/>\n"
    "  <arg type='av' name='parameter' direction='in'/>\n"
    "  <arg type='a{sv}' name='platform_data' direction='in'/>\n"
    "</method>\n"
    "</interface>\n"
    "</node>\n";

bool DBusService::LaunchApp(const char* aCommand, const char** aURIList,
                            int aURIListLen) {
  nsAutoCString param(mAppFile);
  if (aCommand) {
    param.Append(" ");
    param.Append(aCommand);
  }
  for (int i = 0; aURIList && i < aURIListLen; i++) {
    param.Append(" ");
    GUniquePtr<char> escUri(g_shell_quote(aURIList[i]));
    param.Append(escUri.get());
  }

  char* argv[] = {strdup("/bin/sh"), strdup("-c"), strdup(param.get()),
                  nullptr};
  int ret =
      PR_CreateProcessDetached("/bin/sh", argv, nullptr, nullptr) != PR_FAILURE;
  for (auto str : argv) {
    free(str);
  }
  return ret;
}

// The Activate method is called when the application is started without
// files to open.
// Open :: (a{sv}) → ()
void DBusService::HandleFreedesktopActivate(GVariant* aParameters,
                                            GDBusMethodInvocation* aReply) {
  if (!LaunchApp(nullptr, nullptr, 0)) {
    g_dbus_method_invocation_return_error(aReply, G_DBUS_ERROR,
                                          G_DBUS_ERROR_FAILED,
                                          "Failed to run target application.");
    return;
  }
  g_dbus_method_invocation_return_value(aReply, nullptr);
}

// The Open method is called when the application is started with files.
// The array of strings is an array of URIs, in UTF-8.
// Open :: (as,a{sv}) → ()
void DBusService::HandleFreedesktopOpen(GVariant* aParameters,
                                        GDBusMethodInvocation* aReply) {
  RefPtr<GVariant> variant =
      dont_AddRef(g_variant_get_child_value(aParameters, 0));
  gsize uriNum = 0;
  GUniquePtr<const char*> uriArray(g_variant_get_strv(variant, &uriNum));
  if (!LaunchApp(nullptr, uriArray.get(), uriNum)) {
    g_dbus_method_invocation_return_error(aReply, G_DBUS_ERROR,
                                          G_DBUS_ERROR_FAILED,
                                          "Failed to run target application.");
    return;
  }
  g_dbus_method_invocation_return_value(aReply, nullptr);
}

// The ActivateAction method is called when Desktop Actions are activated.
// The action-name parameter is the name of the action.
// ActivateAction :: (s,av,a{sv}) → ()
void DBusService::HandleFreedesktopActivateAction(
    GVariant* aParameters, GDBusMethodInvocation* aReply) {
  const char* actionName;

  // aParameters is "(s,av,a{sv})" type
  RefPtr<GVariant> r = dont_AddRef(g_variant_get_child_value(aParameters, 0));
  if (!(actionName = g_variant_get_string(r, nullptr))) {
    g_dbus_method_invocation_return_error(
        aReply, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Wrong params!");
    return;
  }

  // TODO: Read av params and pass them to LaunchApp?

  // actionName matches desktop action defined in .desktop file.
  // We implement it for .desktop file shipped by flatpak
  // (taskcluster/docker/firefox-flatpak/org.mozilla.firefox.desktop)
  bool ret = false;
  if (!strcmp(actionName, "new-window")) {
    ret = LaunchApp(nullptr, nullptr, 0);
  } else if (!strcmp(actionName, "new-private-window")) {
    ret = LaunchApp("--private-window", nullptr, 0);
  } else if (!strcmp(actionName, "profile-manager-window")) {
    ret = LaunchApp("--ProfileManager", nullptr, 0);
  }
  if (!ret) {
    g_dbus_method_invocation_return_error(aReply, G_DBUS_ERROR,
                                          G_DBUS_ERROR_FAILED,
                                          "Failed to run target application.");
    return;
  }
  g_dbus_method_invocation_return_value(aReply, nullptr);
}

static void HandleMethodCall(GDBusConnection* aConnection, const gchar* aSender,
                             const gchar* aObjectPath,
                             const gchar* aInterfaceName,
                             const gchar* aMethodName, GVariant* aParameters,
                             GDBusMethodInvocation* aInvocation,
                             gpointer aUserData) {
  MOZ_ASSERT(aUserData);
  MOZ_ASSERT(NS_IsMainThread());

  if (strcmp("org.freedesktop.Application", aInterfaceName) != 0) {
    g_warning("DBusService: HandleMethodCall() wrong interface name %s",
              aInterfaceName);
    return;
  }
  if (strcmp("Activate", aMethodName) == 0) {
    static_cast<DBusService*>(aUserData)->HandleFreedesktopActivate(
        aParameters, aInvocation);
  } else if (strcmp("Open", aMethodName) == 0) {
    static_cast<DBusService*>(aUserData)->HandleFreedesktopOpen(aParameters,
                                                                aInvocation);
  } else if (strcmp("ActivateAction", aMethodName) == 0) {
    static_cast<DBusService*>(aUserData)->HandleFreedesktopActivateAction(
        aParameters, aInvocation);
  } else {
    g_warning("DBusService: HandleMethodCall() wrong method %s", aMethodName);
  }
}

static GVariant* HandleGetProperty(GDBusConnection* aConnection,
                                   const gchar* aSender,
                                   const gchar* aObjectPath,
                                   const gchar* aInterfaceName,
                                   const gchar* aPropertyName, GError** aError,
                                   gpointer aUserData) {
  MOZ_ASSERT(aUserData);
  MOZ_ASSERT(NS_IsMainThread());
  g_set_error(aError, G_IO_ERROR, G_IO_ERROR_FAILED,
              "%s:%s setting is not supported", aInterfaceName, aPropertyName);
  return nullptr;
}

static gboolean HandleSetProperty(GDBusConnection* aConnection,
                                  const gchar* aSender,
                                  const gchar* aObjectPath,
                                  const gchar* aInterfaceName,
                                  const gchar* aPropertyName, GVariant* aValue,
                                  GError** aError, gpointer aUserData) {
  MOZ_ASSERT(aUserData);
  MOZ_ASSERT(NS_IsMainThread());
  g_set_error(aError, G_IO_ERROR, G_IO_ERROR_FAILED,
              "%s:%s setting is not supported", aInterfaceName, aPropertyName);
  return false;
}

static const GDBusInterfaceVTable gInterfaceVTable = {
    HandleMethodCall, HandleGetProperty, HandleSetProperty};

void DBusService::OnBusAcquired(GDBusConnection* aConnection) {
  GUniquePtr<GError> error;
  mIntrospectionData = dont_AddRef(g_dbus_node_info_new_for_xml(
      kIntrospectTemplate, getter_Transfers(error)));
  if (!mIntrospectionData) {
    g_warning("DBusService: g_dbus_node_info_new_for_xml() failed! %s",
              error->message);
    return;
  }

  mRegistrationId = g_dbus_connection_register_object(
      aConnection, GetDBusObjectPath(), mIntrospectionData->interfaces[0],
      &gInterfaceVTable, this,  /* user_data */
      nullptr,                  /* user_data_free_func */
      getter_Transfers(error)); /* GError** */

  if (mRegistrationId == 0) {
    g_warning(
        "DBusService: g_dbus_connection_register_object() "
        "failed! %s",
        error->message);
    return;
  }
}

void DBusService::OnNameAcquired(GDBusConnection* aConnection) {
  mConnection = aConnection;
}

void DBusService::OnNameLost(GDBusConnection* aConnection) {
  mConnection = nullptr;
  if (!mRegistrationId) {
    return;
  }
  if (g_dbus_connection_unregister_object(aConnection, mRegistrationId)) {
    mRegistrationId = 0;
  }
}

bool DBusService::StartFreedesktopListener() {
  if (mDBusID) {
    // We're already connected so we don't need to reconnect
    return false;
  }

  mDBusID = g_bus_own_name(
      // if org.mozilla.Firefox is taken it means we're already running
      // so use G_BUS_NAME_OWNER_FLAGS_DO_NOT_QUEUE and quit.
      G_BUS_TYPE_SESSION, GetDBusBusName(), G_BUS_NAME_OWNER_FLAGS_DO_NOT_QUEUE,
      [](GDBusConnection* aConnection, const gchar*,
         gpointer aUserData) -> void {
        static_cast<DBusService*>(aUserData)->OnBusAcquired(aConnection);
      },
      [](GDBusConnection* aConnection, const gchar*,
         gpointer aUserData) -> void {
        static_cast<DBusService*>(aUserData)->OnNameAcquired(aConnection);
      },
      [](GDBusConnection* aConnection, const gchar*,
         gpointer aUserData) -> void {
        static_cast<DBusService*>(aUserData)->OnNameLost(aConnection);
      },
      this, nullptr);

  if (!mDBusID) {
    g_warning("DBusService: g_bus_own_name() failed!");
    return false;
  }

  return true;
}

void DBusService::StopFreedesktopListener() {
  OnNameLost(mConnection);
  if (mDBusID) {
    g_bus_unown_name(mDBusID);
    mDBusID = 0;
  }
  mIntrospectionData = nullptr;
}