summaryrefslogtreecommitdiffstats
path: root/toolkit/crashreporter/client/crashreporter_gtk_common.cpp
blob: d4bed0209c07e4b0f778f0868aafbc95b162a2f0 (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
/* -*- 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 "crashreporter.h"

#include <unistd.h>
#include <dlfcn.h>
#include <errno.h>
#include <glib.h>
#include <gtk/gtk.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <gdk/gdkkeysyms.h>

#include <algorithm>
#include <string>
#include <vector>

#include "common/linux/http_upload.h"
#include "crashreporter.h"
#include "crashreporter_gtk_common.h"

#ifndef GDK_KEY_Escape
#  define GDK_KEY_Escape GDK_Escape
#endif

using std::string;
using std::vector;

using namespace CrashReporter;

GtkWidget* gWindow = 0;
GtkWidget* gSubmitReportCheck = 0;
GtkWidget* gIncludeURLCheck = 0;
GtkWidget* gThrobber = 0;
GtkWidget* gProgressLabel = 0;
GtkWidget* gCloseButton = 0;
GtkWidget* gRestartButton = 0;

bool gInitialized = false;
bool gDidTrySend = false;
StringTable gFiles;
Json::Value gQueryParameters;
string gHttpProxy;
string gAuth;
string gCACertificateFile;
string gSendURL;
string gURLParameter;
vector<string> gRestartArgs;
GThread* gSendThreadID;

// From crashreporter_linux.cpp
void SendReport();
void DisableGUIAndSendReport();
void TryInitGnome();
void UpdateSubmit();

static bool RestartApplication() {
  char** argv = reinterpret_cast<char**>(
      malloc(sizeof(char*) * (gRestartArgs.size() + 1)));

  if (!argv) return false;

  unsigned int i;
  for (i = 0; i < gRestartArgs.size(); i++) {
    argv[i] = (char*)gRestartArgs[i].c_str();
  }
  argv[i] = 0;

  pid_t pid = fork();
  if (pid == -1) {
    free(argv);
    return false;
  } else if (pid == 0) {
    (void)execv(argv[0], argv);
    _exit(1);
  }

  free(argv);

  return true;
}

// Quit the app, used as a timeout callback
gboolean CloseApp(gpointer data) {
  if (!gAutoSubmit) {
    gtk_main_quit();
  }
  g_thread_join(gSendThreadID);
  return FALSE;
}

static gboolean ReportCompleted(gpointer success) {
  gtk_widget_hide(gThrobber);
  string str =
      success ? gStrings[ST_REPORTSUBMITSUCCESS] : gStrings[ST_SUBMITFAILED];
  gtk_label_set_text(GTK_LABEL(gProgressLabel), str.c_str());
  g_timeout_add(5000, CloseApp, 0);
  return FALSE;
}

#define HTTP_PROXY_DIR "/system/http_proxy"

void LoadProxyinfo() {
  class GConfClient;
  typedef GConfClient* (*_gconf_default_fn)();
  typedef gboolean (*_gconf_bool_fn)(GConfClient*, const gchar*, GError**);
  typedef gint (*_gconf_int_fn)(GConfClient*, const gchar*, GError**);
  typedef gchar* (*_gconf_string_fn)(GConfClient*, const gchar*, GError**);

  if (getenv("http_proxy"))
    return;  // libcurl can use the value from the environment

  static void* gconfLib = dlopen("libgconf-2.so.4", RTLD_LAZY);
  if (!gconfLib) return;

  _gconf_default_fn gconf_client_get_default =
      (_gconf_default_fn)dlsym(gconfLib, "gconf_client_get_default");
  _gconf_bool_fn gconf_client_get_bool =
      (_gconf_bool_fn)dlsym(gconfLib, "gconf_client_get_bool");
  _gconf_int_fn gconf_client_get_int =
      (_gconf_int_fn)dlsym(gconfLib, "gconf_client_get_int");
  _gconf_string_fn gconf_client_get_string =
      (_gconf_string_fn)dlsym(gconfLib, "gconf_client_get_string");

  if (!(gconf_client_get_default && gconf_client_get_bool &&
        gconf_client_get_int && gconf_client_get_string)) {
    dlclose(gconfLib);
    return;
  }

  GConfClient* conf = gconf_client_get_default();

  if (gconf_client_get_bool(conf, HTTP_PROXY_DIR "/use_http_proxy", nullptr)) {
    gint port;
    gchar *host = nullptr, *httpproxy = nullptr;

    host = gconf_client_get_string(conf, HTTP_PROXY_DIR "/host", nullptr);
    port = gconf_client_get_int(conf, HTTP_PROXY_DIR "/port", nullptr);

    if (port && host && *host != '\0') {
      httpproxy = g_strdup_printf("http://%s:%d/", host, port);
      gHttpProxy = httpproxy;
    }

    g_free(host);
    g_free(httpproxy);

    if (gconf_client_get_bool(conf, HTTP_PROXY_DIR "/use_authentication",
                              nullptr)) {
      gchar *user, *password, *auth = nullptr;

      user = gconf_client_get_string(
          conf, HTTP_PROXY_DIR "/authentication_user", nullptr);
      password = gconf_client_get_string(
          conf, HTTP_PROXY_DIR "/authentication_password", nullptr);

      if (user && password) {
        auth = g_strdup_printf("%s:%s", user, password);
        gAuth = auth;
      }

      g_free(user);
      g_free(password);
      g_free(auth);
    }
  }

  g_object_unref(conf);

  // Don't dlclose gconfLib as libORBit-2 uses atexit().
}

gpointer SendThread(gpointer args) {
  Json::StreamWriterBuilder builder;
  builder["indentation"] = "";
  string parameters(writeString(builder, gQueryParameters));

  string response, error;
  long response_code;

  bool success = google_breakpad::HTTPUpload::SendRequest(
      gSendURL, parameters, gFiles, gHttpProxy, gAuth, gCACertificateFile,
      &response, &response_code, &error);
  if (success) {
    LogMessage("Crash report submitted successfully");
  } else {
    LogMessage("Crash report submission failed: " + error);
  }

  SendCompleted(success, response);

  if (!gAutoSubmit) {
    // Apparently glib is threadsafe, and will schedule this
    // on the main thread, see:
    // http://library.gnome.org/devel/gtk-faq/stable/x499.html
    g_idle_add(ReportCompleted, (gpointer)success);
  }

  return nullptr;
}

gboolean WindowDeleted(GtkWidget* window, GdkEvent* event, gpointer userData) {
  SaveSettings();
  gtk_main_quit();
  return TRUE;
}

gboolean check_escape(GtkWidget* window, GdkEventKey* event,
                      gpointer userData) {
  if (event->keyval == GDK_KEY_Escape) {
    gtk_main_quit();
    return TRUE;
  }
  return FALSE;
}

static void MaybeSubmitReport() {
  if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(gSubmitReportCheck))) {
    gDidTrySend = true;
    DisableGUIAndSendReport();
  } else {
    gtk_main_quit();
  }
}

void CloseClicked(GtkButton* button, gpointer userData) {
  SaveSettings();
  MaybeSubmitReport();
}

void RestartClicked(GtkButton* button, gpointer userData) {
  SaveSettings();
  RestartApplication();
  MaybeSubmitReport();
}

static void UpdateURL() {
  if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(gIncludeURLCheck))) {
    gQueryParameters["URL"] = gURLParameter;
  } else {
    gQueryParameters.removeMember("URL");
  }
}

void SubmitReportChecked(GtkButton* sender, gpointer userData) {
  UpdateSubmit();
}

void IncludeURLClicked(GtkButton* sender, gpointer userData) { UpdateURL(); }

/* === Crashreporter UI Functions === */

bool UIInit() {
  // breakpad probably left us with blocked signals, unblock them here
  sigset_t signals, old;
  sigfillset(&signals);
  sigprocmask(SIG_UNBLOCK, &signals, &old);

  // tell glib we're going to use threads
  g_thread_init(nullptr);

  if (gtk_init_check(&gArgc, &gArgv)) {
    gInitialized = true;

    if (gStrings.find("isRTL") != gStrings.end() && gStrings["isRTL"] == "yes")
      gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL);

    return true;
  }

  return false;
}

void UIShowDefaultUI() {
  GtkWidget* errorDialog = gtk_message_dialog_new(
      nullptr, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s",
      gStrings[ST_CRASHREPORTERDEFAULT].c_str());

  gtk_window_set_title(GTK_WINDOW(errorDialog),
                       gStrings[ST_CRASHREPORTERTITLE].c_str());
  gtk_dialog_run(GTK_DIALOG(errorDialog));
}

void UIError_impl(const string& message) {
  if (!gInitialized) {
    // Didn't initialize, this is the best we can do
    printf("Error: %s\n", message.c_str());
    return;
  }

  GtkWidget* errorDialog =
      gtk_message_dialog_new(nullptr, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR,
                             GTK_BUTTONS_CLOSE, "%s", message.c_str());

  gtk_window_set_title(GTK_WINDOW(errorDialog),
                       gStrings[ST_CRASHREPORTERTITLE].c_str());
  gtk_dialog_run(GTK_DIALOG(errorDialog));
}

bool UIGetIniPath(string& path) {
  path = gArgv[0];
  path.append(".ini");

  return true;
}

/*
 * Settings are stored in ~/.vendor/product, or
 * ~/.product if vendor is empty.
 */
bool UIGetSettingsPath(const string& vendor, const string& product,
                       string& settingsPath) {
  char* home = getenv("HOME");

  if (!home) return false;

  settingsPath = home;
  settingsPath += "/.";
  if (!vendor.empty()) {
    string lc_vendor;
    std::transform(vendor.begin(), vendor.end(), back_inserter(lc_vendor),
                   (int (*)(int))std::tolower);
    settingsPath += lc_vendor + "/";
  }
  string lc_product;
  std::transform(product.begin(), product.end(), back_inserter(lc_product),
                 (int (*)(int))std::tolower);
  settingsPath += lc_product + "/Crash Reports";
  return true;
}

bool UIMoveFile(const string& file, const string& newfile) {
  if (!rename(file.c_str(), newfile.c_str())) return true;
  if (errno != EXDEV) return false;

  // use system /bin/mv instead, time to fork
  pid_t pID = vfork();
  if (pID < 0) {
    // Failed to fork
    return false;
  }
  if (pID == 0) {
    char* const args[4] = {const_cast<char*>("mv"), strdup(file.c_str()),
                           strdup(newfile.c_str()), 0};
    if (args[1] && args[2]) execve("/bin/mv", args, 0);
    free(args[1]);
    free(args[2]);
    exit(-1);
  }
  int status;
  waitpid(pID, &status, 0);
  return UIFileExists(newfile);
}