/*
* c8-sync: keeps this PC's settings in step with the cont8nuum account.
*
* The compositor starts it for the session, over a private connection
* like PC settings', so it sees the settings (cont8nuum-settings-v1) and
* can change them the way PC settings does: applied at once, saved in
* config.ini with its comments kept.
*
* Each synced section of config.ini is one item on the account's server
* (c8-online, /api/v1/settings/config.SECTION): its keys as key=value
* lines, sorted. Per item we keep the "base": what it was when this PC
* and the server last agreed, and the server's revision of that. A
* change on one side since the base goes to the other; with changes on
* both, they are merged key by key, and a key changed on both takes the
* server's value.
*
* The Start and lock screen pictures Photos sets (background.h) go too,
* whole, as picture.start and picture.lock: a JPEG each, shrunk to fit
* the server's limit on the way up. One changed on both sides takes the
* server's; one removed on one side goes from the other, unless the
* other has a new one meanwhile. What comes down is decoded here (JPEG
* only) and encoded again before Start or the lock screen sees it.
*
* The token and the API's address come from c8-accounts
* (GetAccessToken("sync")); with no account, or the service turned off
* in PC settings, this waits. curl does the talking, as elsewhere.
*
* The main thread has the Wayland connection and the bus; a worker does
* the rounds, blocking as it goes, and hands changes to make back to the
* main thread.
*/
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <gio/gio.h>
#include <glib.h>
#include <glib-unix.h>
#include <glib/gstdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <wayland-client.h>
#include "../accounts/curl.h"
#include "background.h"
#include "json.h"
#include "cont8nuum-settings-v1-client-protocol.h"
#define POLL_S 300 // how often to ask the server what changed
#define SETTLE_MS 2000 // after a change here, wait for the rest of it
#define SERVICE "sync"
#define ITEM_MAX (256 * 1024) // a server too old to say its limits
#define PICTURE_GET_MAX (16 * 1024 * 1024)
#define PICTURE_MAX_SIDE 16384
#define PICTURE_QUALITY "92"
/* What is synced. Not power (a laptop and a desktop differ), not the
* displays, and from [general] not what depends on what is installed. */
static const struct {
const char *section;
const char *skip[4];
} synced[] = {
{ "appearance" },
{ "general", { "autostart", "terminal", "xwayland" } },
{ "notifications" },
{ "keyboard" },
{ "touchpad" },
{ "mouse" },
{ "bindings" },
};
static const struct {
const char *item;
enum c8_background which;
} pictures[] = {
{ "picture.start", C8_BACKGROUND_START },
{ "picture.lock", C8_BACKGROUND_LOCK },
};
struct entry {
char *section, *key, *value;
};
static struct {
struct wl_display *display;
struct c8_settings_manager_v1 *manager;
struct c8_settings_v1 *settings;
GPtrArray *incoming; // the series being received
GMutex lock;
GCond cond;
GPtrArray *snapshot; // the last whole series; NULL before the first
bool kicked; // something changed: do a round soon
GDBusConnection *bus;
int poll_s;
} s;
static void entry_free(gpointer data) {
struct entry *e = data;
g_free(e->section);
g_free(e->key);
g_free(e->value);
g_free(e);
}
static void kick(void) {
g_mutex_lock(&s.lock);
s.kicked = true;
g_cond_signal(&s.cond);
g_mutex_unlock(&s.lock);
}
/* The settings, from the compositor */
static void handle_entry(void *data, struct c8_settings_v1 *settings,
const char *section, const char *key, const char *value) {
struct entry *e = g_new0(struct entry, 1);
e->section = g_strdup(section);
e->key = g_strdup(key);
e->value = g_strdup(value);
g_ptr_array_add(s.incoming, e);
}
static void handle_done(void *data, struct c8_settings_v1 *settings) {
g_mutex_lock(&s.lock);
if (s.snapshot) {
g_ptr_array_unref(s.snapshot);
}
s.snapshot = s.incoming;
g_mutex_unlock(&s.lock);
s.incoming = g_ptr_array_new_with_free_func(entry_free);
kick();
}
static void handle_failed(void *data, struct c8_settings_v1 *settings,
const char *section, const char *key, const char *reason) {
g_message("[%s] %s from the account wasn't taken: %s", section, key,
reason);
}
static const struct c8_settings_v1_listener settings_listener = {
.entry = handle_entry,
.done = handle_done,
.failed = handle_failed,
};
static void registry_global(void *data, struct wl_registry *registry,
uint32_t name, const char *interface, uint32_t version) {
if (strcmp(interface, c8_settings_manager_v1_interface.name) == 0) {
s.manager = wl_registry_bind(registry, name,
&c8_settings_manager_v1_interface, 1);
}
}
static void registry_global_remove(void *data, struct wl_registry *registry,
uint32_t name) {
}
static const struct wl_registry_listener registry_listener = {
.global = registry_global,
.global_remove = registry_global_remove,
};
static gboolean display_ready(gint fd, GIOCondition condition, gpointer data) {
/* The compositor going away ends the session, and us */
if ((condition & (G_IO_HUP | G_IO_ERR)) ||
wl_display_dispatch(s.display) < 0) {
exit(0);
}
wl_display_flush(s.display);
return G_SOURCE_CONTINUE;
}
/* A section as its item: "key=value\n" lines, sorted, so two that say
* the same are the same text */
static int by_string(gconstpointer a, gconstpointer b) {
return strcmp(*(const char *const *)a, *(const char *const *)b);
}
static char *body_of(GHashTable *map) {
GPtrArray *keys = g_ptr_array_new();
GHashTableIter it;
gpointer key;
g_hash_table_iter_init(&it, map);
while (g_hash_table_iter_next(&it, &key, NULL)) {
g_ptr_array_add(keys, key);
}
g_ptr_array_sort(keys, by_string);
GString *out = g_string_new(NULL);
for (guint i = 0; i < keys->len; i++) {
g_string_append_printf(out, "%s=%s\n", (char *)keys->pdata[i],
(char *)g_hash_table_lookup(map, keys->pdata[i]));
}
g_ptr_array_unref(keys);
return g_string_free(out, FALSE);
}
static GHashTable *map_of(const char *body) {
GHashTable *map = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
g_free);
char **lines = g_strsplit(body ? body : "", "\n", -1);
for (char **l = lines; *l; l++) {
char *eq = strchr(*l, '=');
if (eq && eq != *l) {
g_hash_table_replace(map, g_strndup(*l, eq - *l),
g_strdup(eq + 1));
}
}
g_strfreev(lines);
return map;
}
static bool skipped(int which, const char *key) {
for (int i = 0; i < 4 && synced[which].skip[i]; i++) {
if (strcmp(synced[which].skip[i], key) == 0) {
return true;
}
}
return false;
}
/* What isn't synced, either way. The server's text is no more trusted
* than a stranger's: the keys this PC keeps to itself, and any key
* binding that runs a command (it would run whatever the account, or
* whoever got into it, says, at the next press of a key). Those stay
* each PC's own. */
static bool refused(int which, const char *key, const char *value) {
if (skipped(which, key) || strchr(key, '=') || strpbrk(key, "\r\n[]#") ||
strpbrk(value, "\r\n")) {
return true;
}
if (strcmp(synced[which].section, "bindings") == 0) {
const char *v = value + strspn(value, " \t");
size_t word = strcspn(v, " \t");
return word == 4 && strncmp(v, "exec", 4) == 0;
}
return false;
}
/* The server's side of a section, without what it may not set */
static GHashTable *remote_map(const char *body, int which) {
GHashTable *map = map_of(body);
GHashTableIter it;
gpointer key, value;
g_hash_table_iter_init(&it, map);
while (g_hash_table_iter_next(&it, &key, &value)) {
if (refused(which, key, value)) {
g_hash_table_iter_remove(&it);
}
}
return map;
}
/* The section as it is here now */
static GHashTable *local_map(GPtrArray *snapshot, int which) {
GHashTable *map = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
g_free);
for (guint i = 0; i < snapshot->len; i++) {
struct entry *e = snapshot->pdata[i];
/* No newlines: one would look like another key to the next PC */
if (strcmp(e->section, synced[which].section) == 0 &&
!refused(which, e->key, e->value)) {
g_hash_table_replace(map, g_strdup(e->key), g_strdup(e->value));
}
}
return map;
}
/* Key by key: what only one side changed since the base wins; changed
* on both, the server's. NULL is "not there". */
static GHashTable *merge(GHashTable *base, GHashTable *local,
GHashTable *remote) {
GHashTable *out = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
g_free);
GHashTable *sides[] = { local, remote };
for (int side = 0; side < 2; side++) {
GHashTableIter it;
gpointer key;
g_hash_table_iter_init(&it, sides[side]);
while (g_hash_table_iter_next(&it, &key, NULL)) {
const char *b = g_hash_table_lookup(base, key);
const char *l = g_hash_table_lookup(local, key);
const char *r = g_hash_table_lookup(remote, key);
const char *take = g_strcmp0(r, b) == 0 ? l : r;
if (take) {
g_hash_table_replace(out, g_strdup(key), g_strdup(take));
}
}
}
return out;
}
/* Changing settings here: on the main thread, where the connection is */
struct change {
char *section;
GPtrArray *ops; // key, value (NULL: remove), …
};
static gboolean apply_change(gpointer data) {
struct change *c = data;
for (guint i = 0; i + 1 < c->ops->len; i += 2) {
const char *key = c->ops->pdata[i], *value = c->ops->pdata[i + 1];
if (value) {
c8_settings_v1_set(s.settings, c->section, key, value);
} else {
c8_settings_v1_remove(s.settings, c->section, key);
}
}
c8_settings_v1_commit(s.settings);
wl_display_flush(s.display);
g_ptr_array_unref(c->ops);
g_free(c->section);
g_free(c);
return G_SOURCE_REMOVE;
}
/* Makes the section here what `want` says, where it differs */
static void apply(int which, GHashTable *local, GHashTable *want) {
struct change *c = g_new0(struct change, 1);
c->section = g_strdup(synced[which].section);
c->ops = g_ptr_array_new_with_free_func(g_free);
GHashTableIter it;
gpointer key, value;
g_hash_table_iter_init(&it, want);
while (g_hash_table_iter_next(&it, &key, &value)) {
if (g_strcmp0(g_hash_table_lookup(local, key), value) != 0) {
g_ptr_array_add(c->ops, g_strdup(key));
g_ptr_array_add(c->ops, g_strdup(value));
}
}
g_hash_table_iter_init(&it, local);
while (g_hash_table_iter_next(&it, &key, NULL)) {
if (!g_hash_table_contains(want, key)) {
g_ptr_array_add(c->ops, g_strdup(key));
g_ptr_array_add(c->ops, NULL);
}
}
g_main_context_invoke(NULL, apply_change, c);
}
/* The server, through curl */
/* One request. `match`: an If-Match revision, 0 for "only if new", -1
* for neither. Returns the status (0: the server wasn't reached), the
* answer in *out and the item's revision (X-C8-Rev) in *rev. A picture
* goes up from the file `upload` and comes down into `download` (*out is
* then empty). */
static int request_files(const char *method, const char *url,
const char *token, gint64 match, const char *body, const char *upload,
const char *download, char **out, gint64 *rev) {
GString *conf = g_string_new(NULL);
cfg(conf, "url", url);
cfg(conf, "request", method);
char *h = g_strconcat("Authorization: Bearer ", token, NULL);
cfg(conf, "header", h);
g_free(h);
if (match > 0) {
h = g_strdup_printf("If-Match: \"%" G_GINT64_FORMAT "\"", match);
cfg(conf, "header", h);
g_free(h);
} else if (match == 0) {
cfg(conf, "header", "If-None-Match: *");
}
if (body) {
cfg(conf, "header", "Content-Type: text/plain; charset=utf-8");
cfg(conf, "data-binary", body);
}
if (upload) {
cfg(conf, "header", "Content-Type: image/jpeg");
char *at = g_strconcat("@", upload, NULL);
cfg(conf, "data-binary", at);
g_free(at);
}
if (download) {
cfg(conf, "output", download);
char *max = g_strdup_printf("%d", PICTURE_GET_MAX);
cfg(conf, "max-filesize", max);
g_free(max);
}
/* The request goes in on stdin, so the token isn't in anyone's ps */
const char *argv[] = { "curl", "-s", "--proto",
plain_http_ok(url) ? "=https,http" : "=https",
"--max-time", "30", "-A", "c8-sync/0.1 (cont8nuum)",
"-w", "\n%header{x-c8-rev} %{http_code}", "--config", "-", NULL };
int status = 0;
*out = NULL;
if (rev) {
*rev = 0;
}
GSubprocess *proc = g_subprocess_newv(argv, G_SUBPROCESS_FLAGS_STDIN_PIPE |
G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_SILENCE,
NULL);
char *text = NULL;
if (proc && g_subprocess_communicate_utf8(proc, conf->str, NULL, &text,
NULL, NULL) && text) {
/* The last line is ours: "REV STATUS" */
char *last = strrchr(text, '\n');
if (last) {
char *space = strrchr(last, ' ');
if (space) {
status = atoi(space + 1);
if (rev) {
*rev = g_ascii_strtoll(last + 1, NULL, 10);
}
}
*last = '\0';
*out = g_strdup(text);
}
}
g_free(text);
g_clear_object(&proc);
memset(conf->str, 0, conf->len);
g_string_free(conf, TRUE);
return status;
}
static int request(const char *method, const char *url, const char *token,
gint64 match, const char *body, char **out, gint64 *rev) {
return request_files(method, url, token, match, body, NULL, NULL, out,
rev);
}
/* A token from c8-accounts; `rejected` is one the server just refused.
* NULL when there is no account to sync with (or it needs signing in:
* PC settings says so). */
static char *get_token(const char *rejected, char **account, char **api) {
GError *error = NULL;
GVariant *r = g_dbus_connection_call_sync(s.bus, "org.cont8nuum.Accounts",
"/org/cont8nuum/Accounts", "org.cont8nuum.Accounts1", "GetAccessToken",
g_variant_new("(ss)", SERVICE, rejected ? rejected : ""),
G_VARIANT_TYPE("(sss)"), G_DBUS_CALL_FLAGS_NONE, 60000, NULL, &error);
if (r == NULL) {
char *name = g_dbus_error_get_remote_error(error);
if (name == NULL || !(g_str_has_suffix(name, ".NoAccount") ||
g_str_has_suffix(name, ".SignInNeeded"))) {
g_message("No token: %s", error->message);
}
g_free(name);
g_error_free(error);
return NULL;
}
char *token;
g_variant_get(r, "(sss)", account, &token, api);
g_variant_unref(r);
return token;
}
/* What this PC and the server last agreed on, per account:
* ~/.local/share/cont8nuum/sync/ACCOUNT.ini, a group per item with its
* `rev` and `base` */
static char *state_path(const char *account) {
char *file = g_strconcat(account, ".ini", NULL);
char *path = g_build_filename(g_get_user_data_dir(), "cont8nuum", "sync",
file, NULL);
g_free(file);
return path;
}
static void state_save(GKeyFile *state, const char *account) {
char *path = state_path(account);
char *dir = g_path_get_dirname(path);
g_mkdir_with_parents(dir, 0700);
g_key_file_save_to_file(state, path, NULL);
g_free(dir);
g_free(path);
}
/* One item. Returns whether the state changed. */
static bool sync_item(int which, GPtrArray *snapshot, GKeyFile *state,
const char *api, const char *token, gint64 remote_rev) {
const char *section = synced[which].section;
char *name = g_strconcat("config.", section, NULL);
char *url = g_strconcat(api, "/api/v1/settings/", name, NULL);
char *base_text = g_key_file_get_string(state, name, "base", NULL);
gint64 base_rev = g_key_file_get_int64(state, name, "rev", NULL);
GHashTable *local = local_map(snapshot, which);
char *local_text = body_of(local);
char *answer = NULL, *agreed = NULL;
gint64 rev = 0;
int status;
if (base_text && remote_rev == base_rev) {
/* Nobody else touched it: ours goes up, if it changed */
if (strcmp(local_text, base_text) != 0) {
status = request("PUT", url, token, base_rev, local_text, &answer,
&rev);
if (status == 200 || status == 201) {
g_message("Sent [%s] to the account", section);
agreed = g_strdup(local_text);
}
if (status == 412) {
kick(); // someone was quicker: merge, soon
}
}
} else if (remote_rev == 0) {
/* Not on the server (yet, or any more) */
if (local_text[0]) {
status = request("PUT", url, token, 0, local_text, &answer, &rev);
if (status == 200 || status == 201) {
g_message("Sent [%s] to the account", section);
agreed = g_strdup(local_text);
}
}
} else {
/* It changed there, or this PC is new to it: merge */
status = request("GET", url, token, -1, NULL, &answer, &rev);
if (status == 200 && rev > 0) {
GHashTable *base = remote_map(base_text, which);
GHashTable *remote = remote_map(answer, which);
GHashTable *merged = merge(base, local, remote);
char *merged_text = body_of(merged);
char *remote_text = body_of(remote);
bool ok = true;
if (strcmp(merged_text, remote_text) != 0) {
gint64 got = rev;
g_free(answer);
status = request("PUT", url, token, got, merged_text, &answer,
&rev);
ok = status == 200 || status == 201;
}
if (ok) {
if (strcmp(merged_text, local_text) != 0) {
g_message("Took [%s] from the account", section);
apply(which, local, merged);
}
agreed = g_strdup(merged_text);
}
g_free(merged_text);
g_free(remote_text);
g_hash_table_unref(merged);
g_hash_table_unref(remote);
g_hash_table_unref(base);
}
}
if (agreed && rev > 0) {
g_key_file_set_string(state, name, "base", agreed);
g_key_file_set_int64(state, name, "rev", rev);
}
bool changed = agreed != NULL && rev > 0;
g_free(agreed);
g_free(answer);
g_free(local_text);
g_hash_table_unref(local);
g_free(base_text);
g_free(url);
g_free(name);
return changed;
}
/* The pictures */
static char *sync_dir(void) {
return g_build_filename(g_get_user_data_dir(), "cont8nuum", "sync", NULL);
}
/* What's there now, to compare with what was agreed: "" for none */
static char *file_hash(const char *path) {
char *data;
gsize len;
if (!g_file_get_contents(path, &data, &len, NULL)) {
return g_strdup("");
}
char *hash = g_compute_checksum_for_data(G_CHECKSUM_SHA256,
(const guchar *)data, len);
g_free(data);
return hash;
}
/* The file to send: the picture itself if it fits, else a smaller copy
* in `tmp`. NULL if no size fits. Local files are ours (written by
* Photos through glycin, or below), so gdk-pixbuf may read them. */
static char *fitting(const char *path, gint64 max, const char *tmp) {
GStatBuf st;
if (g_stat(path, &st) != 0) {
return NULL;
}
if (st.st_size <= max) {
return g_strdup(path);
}
GdkPixbuf *pb = gdk_pixbuf_new_from_file(path, NULL);
if (pb == NULL) {
return NULL;
}
static const int sides[] = { 2560, 1920, 1600, 1280, 960, 640 };
int w = gdk_pixbuf_get_width(pb), h = gdk_pixbuf_get_height(pb);
char *done = NULL;
for (size_t i = 0; i < G_N_ELEMENTS(sides) && done == NULL; i++) {
double k = MIN(1.0, (double)sides[i] / MAX(w, h));
GdkPixbuf *small = gdk_pixbuf_scale_simple(pb, MAX(1, (int)(w * k)),
MAX(1, (int)(h * k)), GDK_INTERP_HYPER);
char *buf = NULL;
gsize len = 0;
if (small && gdk_pixbuf_save_to_buffer(small, &buf, &len, "jpeg",
NULL, "quality", "85", NULL) && (gint64)len <= max &&
g_file_set_contents(tmp, buf, len, NULL)) {
done = g_strdup(tmp);
}
g_free(buf);
g_clear_object(&small);
}
g_object_unref(pb);
return done;
}
/* What came down is the server's, so not trusted: a JPEG only (the
* loader is chosen by us, not by sniffing), not too big, decoded here and
* written out again, so the shell and the login screen only ever read
* what gdk-pixbuf encoded. */
static bool take_picture(const char *got, const char *path) {
char *data;
gsize len;
if (!g_file_get_contents(got, &data, &len, NULL)) {
return false;
}
bool ok = false;
int w = 0, h = 0;
GdkPixbufFormat *f = gdk_pixbuf_get_file_info(got, &w, &h);
char *format = f ? gdk_pixbuf_format_get_name(f) : NULL;
if (len >= 3 && (guchar)data[0] == 0xff && (guchar)data[1] == 0xd8 &&
(guchar)data[2] == 0xff && g_strcmp0(format, "jpeg") == 0 &&
w > 0 && h > 0 && w <= PICTURE_MAX_SIDE && h <= PICTURE_MAX_SIDE) {
GdkPixbufLoader *loader = gdk_pixbuf_loader_new_with_type("jpeg",
NULL);
if (loader && gdk_pixbuf_loader_write(loader, (const guchar *)data,
len, NULL) && gdk_pixbuf_loader_close(loader, NULL)) {
GdkPixbuf *pb = gdk_pixbuf_loader_get_pixbuf(loader);
char *buf = NULL;
gsize blen = 0;
if (pb && gdk_pixbuf_save_to_buffer(pb, &buf, &blen, "jpeg", NULL,
"quality", PICTURE_QUALITY, NULL)) {
char *dir = g_path_get_dirname(path);
g_mkdir_with_parents(dir, 0700);
g_free(dir);
ok = g_file_set_contents(path, buf, blen, NULL);
}
g_free(buf);
}
g_clear_object(&loader);
}
g_free(format);
g_free(data);
return ok;
}
/* One picture. Returns whether the state changed. */
static bool sync_picture(int which, GKeyFile *state, const char *api,
const char *token, gint64 remote_rev, gint64 max) {
const char *name = pictures[which].item;
char *url = g_strconcat(api, "/api/v1/settings/", name, NULL);
char *path = c8_background_path(pictures[which].which);
char *local = file_hash(path);
bool has_base = g_key_file_has_group(state, name);
char *base = g_key_file_get_string(state, name, "hash", NULL);
gint64 base_rev = g_key_file_get_int64(state, name, "rev", NULL);
if (base == NULL) {
base = g_strdup("");
}
char *dir = sync_dir();
g_mkdir_with_parents(dir, 0700);
char *up = g_build_filename(dir, "picture-up.jpg", NULL);
char *down = g_build_filename(dir, "picture-down.jpg", NULL);
char *answer = NULL, *agreed = NULL;
gint64 rev = 0;
int status;
bool changed_here = strcmp(local, base) != 0;
if (has_base && remote_rev == base_rev && !changed_here) {
/* Nothing to do */
} else if ((has_base && remote_rev == base_rev) ||
(remote_rev == 0 && (changed_here || !has_base))) {
/* Ours goes: changed here only, or there's none there (a new one
* here beats one removed there) */
if (local[0]) {
char *file = fitting(path, max, up);
if (file) {
status = request_files("PUT", url, token,
remote_rev > 0 ? remote_rev : 0, NULL, file, NULL,
&answer, &rev);
if (status == 200 || status == 201) {
g_message("Sent %s to the account", name);
agreed = g_strdup(local);
} else if (status == 412) {
kick();
} else if (status != 0) {
g_message("%s: the account's server said %d", name, status);
}
} else {
g_message("%s: no size of it fits the account", name);
}
g_free(file);
} else if (remote_rev > 0) {
status = request("DELETE", url, token, remote_rev, NULL, &answer,
NULL);
if (status == 200 || status == 404) {
g_message("Took %s off the account", name);
agreed = g_strdup("");
} else if (status == 412) {
kick();
}
} else {
agreed = g_strdup(""); // none on either side
}
} else if (remote_rev == 0) {
/* Removed there, unchanged here: it goes here too */
g_unlink(path);
g_message("Removed %s, as the account did", name);
agreed = g_strdup("");
} else {
/* Changed there (or this PC is new to it): the server's wins */
status = request_files("GET", url, token, -1, NULL, NULL, down,
&answer, &rev);
if (status == 200 && rev > 0 && take_picture(down, path)) {
g_message("Took %s from the account", name);
agreed = file_hash(path);
} else if (status == 200) {
g_message("%s from the account isn't a picture we take", name);
}
}
bool changed = false;
if (agreed) {
g_key_file_set_string(state, name, "hash", agreed);
g_key_file_set_int64(state, name, "rev", agreed[0] ? rev : 0);
changed = true;
}
g_unlink(up);
g_unlink(down);
g_free(agreed);
g_free(answer);
g_free(up);
g_free(down);
g_free(dir);
g_free(base);
g_free(local);
g_free(path);
g_free(url);
return changed;
}
static void sync_round(void) {
g_mutex_lock(&s.lock);
GPtrArray *snapshot = s.snapshot ? g_ptr_array_ref(s.snapshot) : NULL;
g_mutex_unlock(&s.lock);
if (snapshot == NULL) {
return;
}
char *account = NULL, *api = NULL, *list = NULL;
char *token = get_token(NULL, &account, &api);
if (token == NULL) {
g_ptr_array_unref(snapshot);
return;
}
char *url = g_strconcat(api, "/api/v1/settings", NULL);
int status = request("GET", url, token, -1, NULL, &list, NULL);
if (status == 401) {
/* Run out early, or revoked: c8-accounts refreshes it or says
* that signing in is needed */
char *fresh = get_token(token, &account, &api);
g_free(token);
token = fresh;
g_free(list);
list = NULL;
status = token ? request("GET", url, token, -1, NULL, &list, NULL) : 0;
}
struct json *json = status == 200 ? json_parse(list) : NULL;
if (json) {
GKeyFile *state = g_key_file_new();
char *path = state_path(account);
g_key_file_load_from_file(state, path, G_KEY_FILE_NONE, NULL);
g_free(path);
bool changed = false;
/* The account pages name the PC */
char *device = g_key_file_get_string(state, "sync", "device", NULL);
if (g_strcmp0(device, g_get_host_name()) != 0) {
char *durl = g_strconcat(api, "/api/v1/device", NULL);
GString *body = g_string_new("{\"name\": \"");
for (const char *p = g_get_host_name(); *p; p++) {
if (*p != '"' && *p != '\\' && (guchar)*p >= 0x20) {
g_string_append_c(body, *p);
}
}
g_string_append(body, "\"}");
char *answer = NULL;
if (request("PUT", durl, token, -1, body->str, &answer, NULL) == 200) {
g_key_file_set_string(state, "sync", "device",
g_get_host_name());
changed = true;
}
g_free(answer);
g_string_free(body, TRUE);
g_free(durl);
}
g_free(device);
struct json *items = json_get(json, "items");
for (int i = 0; i < (int)G_N_ELEMENTS(synced); i++) {
char *name = g_strconcat("config.", synced[i].section, NULL);
gint64 rev = 0;
for (int j = 0; j < json_length(items); j++) {
struct json *item = json_at(items, j);
if (g_strcmp0(json_str(json_get(item, "name"), NULL),
name) == 0) {
rev = (gint64)json_num(json_get(item, "rev"), 0);
}
}
g_free(name);
changed |= sync_item(i, snapshot, state, api, token, rev);
}
struct json *limits = json_get(json, "limits");
gint64 max = (gint64)json_num(json_get(limits, "picture_max_bytes"),
json_num(json_get(limits, "item_max_bytes"), ITEM_MAX));
for (int i = 0; i < (int)G_N_ELEMENTS(pictures); i++) {
gint64 rev = 0;
for (int j = 0; j < json_length(items); j++) {
struct json *item = json_at(items, j);
if (g_strcmp0(json_str(json_get(item, "name"), NULL),
pictures[i].item) == 0) {
rev = (gint64)json_num(json_get(item, "rev"), 0);
}
}
changed |= sync_picture(i, state, api, token, rev, max);
}
if (changed) {
state_save(state, account);
}
g_key_file_unref(state);
json_free(json);
} else if (status != 0 && token) {
g_message("The account's server said %d", status);
}
if (token) {
memset(token, 0, strlen(token));
}
g_free(token);
g_free(list);
g_free(url);
g_free(account);
g_free(api);
g_ptr_array_unref(snapshot);
}
static gpointer worker(gpointer data) {
for (;;) {
g_mutex_lock(&s.lock);
gint64 until = g_get_monotonic_time() +
s.poll_s * G_TIME_SPAN_SECOND;
while (!s.kicked && g_cond_wait_until(&s.cond, &s.lock, until)) {
}
bool kicked = s.kicked;
g_mutex_unlock(&s.lock);
if (kicked) {
/* A change is often several (a commit, the accounts page) */
g_usleep(SETTLE_MS * 1000);
}
g_mutex_lock(&s.lock);
s.kicked = false;
g_mutex_unlock(&s.lock);
sync_round();
}
return NULL;
}
/* An account came or went, or the service was turned on or off */
static void accounts_changed(GDBusConnection *bus, const char *sender,
const char *path, const char *interface, const char *signal,
GVariant *parameters, gpointer data) {
kick();
}
/* Photos set a picture, or PC settings removed one */
static void pictures_changed(GFileMonitor *m, GFile *file, GFile *other,
GFileMonitorEvent event, gpointer data) {
if (event == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT ||
event == G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED) {
return;
}
for (size_t i = 0; i < G_N_ELEMENTS(pictures); i++) {
const char *name = c8_background_name(pictures[i].which);
char *a = g_file_get_basename(file);
char *b = other ? g_file_get_basename(other) : NULL;
bool ours = strcmp(a, name) == 0 || g_strcmp0(b, name) == 0;
g_free(a);
g_free(b);
if (ours) {
kick();
return;
}
}
}
int main(int argc, char *argv[]) {
s.display = wl_display_connect(NULL);
if (s.display == NULL) {
g_printerr("c8-sync: started by c8, not by hand\n");
return 1;
}
g_mutex_init(&s.lock);
g_cond_init(&s.cond);
s.incoming = g_ptr_array_new_with_free_func(entry_free);
struct wl_registry *registry = wl_display_get_registry(s.display);
wl_registry_add_listener(registry, ®istry_listener, NULL);
wl_display_roundtrip(s.display);
if (s.manager == NULL) {
g_printerr("c8-sync: started by c8, not by hand\n");
return 1;
}
s.settings = c8_settings_manager_v1_get_settings(s.manager);
c8_settings_v1_add_listener(s.settings, &settings_listener, NULL);
wl_display_roundtrip(s.display);
s.bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL);
if (s.bus == NULL) {
g_printerr("c8-sync: no session bus\n");
return 1;
}
g_dbus_connection_signal_subscribe(s.bus, "org.cont8nuum.Accounts",
"org.cont8nuum.Accounts1", "Changed", "/org/cont8nuum/Accounts", NULL,
G_DBUS_SIGNAL_FLAGS_NONE, accounts_changed, NULL, NULL);
const char *poll = g_getenv("C8_SYNC_POLL"); // seconds, for trying it
s.poll_s = poll && atoi(poll) > 0 ? atoi(poll) : POLL_S;
g_unix_fd_add(wl_display_get_fd(s.display), G_IO_IN | G_IO_HUP | G_IO_ERR,
display_ready, NULL);
char *pdir = c8_background_dir();
g_mkdir_with_parents(pdir, 0700);
GFile *pf = g_file_new_for_path(pdir);
GFileMonitor *pm = g_file_monitor_directory(pf, G_FILE_MONITOR_WATCH_MOVES,
NULL, NULL); // kept for good
if (pm) {
g_signal_connect(pm, "changed", G_CALLBACK(pictures_changed), NULL);
}
g_object_unref(pf);
g_free(pdir);
g_thread_new("sync", worker, NULL);
g_main_loop_run(g_main_loop_new(NULL, FALSE));
return 0;
}