PaganOS Luna 0.6.0
PL EN DE
🔒 Repository is read-only – file editing is disabled.

pagan-welcome/pw-util.c main

738 lines Raw ← Back
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
/* pagan-welcome – implementacja konfiguracji i uruchamiania poleceń. */
#define _GNU_SOURCE 1
#include "pw-util.h"

#include <gio/gio.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pty.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>

/* ── Konfiguracja ────────────────────────────────────────────────────────── */
static char *
config_dir(void)
{
    return g_build_filename(g_get_user_config_dir(), "pagan-welcome", NULL);
}

static char *
config_path(void)
{
    char *dir = config_dir();
    char *path = g_build_filename(dir, "config.ini", NULL);
    g_free(dir);
    return path;
}

static char *
env_lang_default(void)
{
    const char *env = g_getenv("LC_ALL");
    if (!env || !*env)
        env = g_getenv("LC_MESSAGES");
    if (!env || !*env)
        env = g_getenv("LANG");
    if (env && g_str_has_prefix(env, "pl"))
        return g_strdup("pl");
    return g_strdup("en");
}

PwConfig *
pw_config_load(void)
{
    PwConfig *cfg = g_new0(PwConfig, 1);
    cfg->lang = env_lang_default();
    cfg->show_on_login = TRUE;

    char *path = config_path();
    GKeyFile *kf = g_key_file_new();
    if (g_key_file_load_from_file(kf, path, G_KEY_FILE_NONE, NULL)) {
        char *lang = g_key_file_get_string(kf, "general", "language", NULL);
        if (lang && (g_strcmp0(lang, "pl") == 0 || g_strcmp0(lang, "en") == 0)) {
            g_free(cfg->lang);
            cfg->lang = lang;
            lang = NULL;
        }
        g_free(lang);
        if (g_key_file_has_key(kf, "general", "show_on_login", NULL))
            cfg->show_on_login = g_key_file_get_boolean(kf, "general",
                                                        "show_on_login", NULL);
    }
    g_key_file_free(kf);
    g_free(path);
    return cfg;
}

void
pw_config_save(const PwConfig *cfg)
{
    GKeyFile *kf = g_key_file_new();
    g_key_file_set_string(kf, "general", "language", cfg->lang);
    g_key_file_set_boolean(kf, "general", "show_on_login", cfg->show_on_login);

    char *dir = config_dir();
    g_mkdir_with_parents(dir, 0755);
    char *path = config_path();
    g_key_file_save_to_file(kf, path, NULL);
    g_free(path);
    g_free(dir);
    g_key_file_free(kf);
}

void
pw_config_free(PwConfig *cfg)
{
    if (!cfg)
        return;
    g_free(cfg->lang);
    g_free(cfg);
}

/* ── Backend ─────────────────────────────────────────────────────────────── */
const char *
pw_backend_path(void)
{
    static char *cached = NULL;
    if (cached)
        return cached;

    const char *env = g_getenv("PAGAN_WELCOME_BACKEND");
    if (env && g_file_test(env, G_FILE_TEST_IS_EXECUTABLE)) {
        cached = g_strdup(env);
        return cached;
    }
    const char *candidates[] = {
        "/usr/bin/pagan-welcome-backend",
        "/usr/lib/pagan-welcome/pagan-welcome-backend.py",
    };
    for (gsize i = 0; i < G_N_ELEMENTS(candidates); i++) {
        if (g_file_test(candidates[i], G_FILE_TEST_EXISTS)) {
            cached = g_strdup(candidates[i]);
            return cached;
        }
    }
    /* Obok pliku wykonywalnego – tryb uruchomienia ze źródeł. */
    char buf[PATH_MAX];
    ssize_t n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
    if (n > 0) {
        buf[n] = '\0';
        char *dir = g_path_get_dirname(buf);
        char *local = g_build_filename(dir, "pagan-welcome-backend.py", NULL);
        char *local2 = g_build_filename(dir, "pagan-welcome-backend", NULL);
        if (g_file_test(local, G_FILE_TEST_EXISTS))
            cached = local;
        else if (g_file_test(local2, G_FILE_TEST_EXISTS))
            cached = local2;
        else
            g_free(local);
        if (!cached)
            g_free(local2);
        g_free(dir);
    }
    if (!cached)
        cached = g_strdup("pagan-welcome-backend");
    return cached;
}

const char *
pw_pag_path(void)
{
    static char *cached = NULL;
    if (cached)
        return cached;
    if (g_file_test("/usr/bin/pag", G_FILE_TEST_EXISTS))
        cached = g_strdup("/usr/bin/pag");
    else
        cached = g_strdup("pag");
    return cached;
}

/* ── Uruchamianie poleceń ────────────────────────────────────────────────── */
typedef struct {
    PwLineFunc func;
    char *line;
    gpointer data;
} LineMsg;

static gboolean
line_idle(gpointer p)
{
    LineMsg *m = p;
    m->func(m->line, m->data);
    g_free(m->line);
    g_free(m);
    return G_SOURCE_REMOVE;
}

typedef struct {
    PwDoneFunc func;
    int status;
    gpointer data;
} DoneMsg;

static gboolean
done_idle(gpointer p)
{
    DoneMsg *m = p;
    m->func(m->status, m->data);
    g_free(m);
    return G_SOURCE_REMOVE;
}

typedef struct {
    char **argv;
    char *input;
    PwLineFunc on_line;
    PwDoneFunc on_done;
    gpointer data;
} Job;

static void
job_emit_line(Job *j, const char *line)
{
    if (!j->on_line)
        return;
    LineMsg *m = g_new0(LineMsg, 1);
    m->func = j->on_line;
    m->line = g_strdup(line);
    m->data = j->data;
    g_idle_add(line_idle, m);
}

static void
job_finish(Job *j, int status)
{
    if (j->on_done) {
        DoneMsg *m = g_new0(DoneMsg, 1);
        m->func = j->on_done;
        m->status = status;
        m->data = j->data;
        g_idle_add(done_idle, m);
    }
}

static gpointer
job_thread(gpointer p)
{
    Job *j = p;
    GError *err = NULL;
    GSubprocessFlags flags = G_SUBPROCESS_FLAGS_STDOUT_PIPE |
                             G_SUBPROCESS_FLAGS_STDERR_MERGE;
    if (j->input)
        flags |= G_SUBPROCESS_FLAGS_STDIN_PIPE;

    GSubprocess *proc = g_subprocess_newv((const gchar * const *) j->argv,
                                          flags, &err);
    if (!proc) {
        job_emit_line(j, err ? err->message : "błąd uruchomienia");
        g_clear_error(&err);
        job_finish(j, 127);
        goto out;
    }

    if (j->input) {
        GOutputStream *in = g_subprocess_get_stdin_pipe(proc);
        gsize written = 0;
        g_output_stream_write_all(in, j->input, strlen(j->input), &written,
                                  NULL, NULL);
        g_output_stream_close(in, NULL, NULL);
    }

    GInputStream *out = g_subprocess_get_stdout_pipe(proc);
    GDataInputStream *dis = g_data_input_stream_new(out);
    char *line;
    while ((line = g_data_input_stream_read_line(dis, NULL, NULL, NULL)) != NULL) {
        job_emit_line(j, line);
        g_free(line);
    }
    g_object_unref(dis);
    g_subprocess_wait(proc, NULL, NULL);

    int status = -1;
    if (g_subprocess_get_if_exited(proc))
        status = g_subprocess_get_exit_status(proc);
    g_object_unref(proc);
    job_finish(j, status);

out:
    g_strfreev(j->argv);
    g_free(j->input);
    g_free(j);
    return NULL;
}

void
pw_spawn(const char *const argv[], const char *input, PwLineFunc on_line,
         PwDoneFunc on_done, gpointer data)
{
    Job *j = g_new0(Job, 1);
    /* argv jako NULL-zakończona kopia. */
    gsize n = 0;
    while (argv[n])
        n++;
    j->argv = g_new0(char *, n + 1);
    for (gsize i = 0; i < n; i++)
        j->argv[i] = g_strdup(argv[i]);
    j->input = input ? g_strdup(input) : NULL;
    j->on_line = on_line;
    j->on_done = on_done;
    j->data = data;
    g_thread_unref(g_thread_new("pw-spawn", job_thread, j));
}

void
pw_backend(const char *const args[], PwLineFunc on_line, PwDoneFunc on_done,
           gpointer data)
{
    gsize n = 0;
    while (args[n])
        n++;
    char **argv = g_new0(char *, n + 2);
    argv[0] = g_strdup(pw_backend_path());
    for (gsize i = 0; i < n; i++)
        argv[i + 1] = g_strdup(args[i]);
    pw_spawn((const char *const *) argv, NULL, on_line, on_done, data);
    g_strfreev(argv);
}

/* ── Uprawnienia root ────────────────────────────────────────────────────── */
gboolean
pw_is_root(void)
{
    return geteuid() == 0;
}

gboolean
pw_have(const char *cmd)
{
    if (!cmd || !*cmd)
        return FALSE;
    if (g_path_is_absolute(cmd))
        return g_file_test(cmd, G_FILE_TEST_IS_EXECUTABLE);
    char *found = g_find_program_in_path(cmd);
    gboolean ok = (found != NULL);
    g_free(found);
    return ok;
}

static gboolean
polkit_agent_running(void)
{
    /* Wynik zapamiętujemy – agent polkit nie pojawia się w trakcie sesji, a
     * pgrep w pętli spawnowałby kilka procesów przy każdej akcji. */
    static int cached = -1;
    if (cached >= 0)
        return cached == 1;

    static const char *names[] = {
        "polkit-gnome-authentication-agent-1", "xfce-polkit",
        "polkit-kde-authentication-agent-1", "mate-polkit",
        "lxpolkit", "polkit-mate-authentication-agent-1",
    };
    cached = 0;
    for (gsize i = 0; i < G_N_ELEMENTS(names); i++) {
        const char *argv[] = {"pgrep", "-x", names[i], NULL};
        char *out = pw_run_capture(argv);
        gboolean found = out && *out;
        g_free(out);
        if (found) {
            cached = 1;
            break;
        }
    }
    return cached == 1;
}

gboolean
pw_privileged_needs_password(void)
{
    if (pw_is_root())
        return FALSE;
    if (pw_have("pkexec") && polkit_agent_running())
        return FALSE;
    return TRUE;
}

char **
pw_privileged_argv(const char *const cmd[])
{
    GPtrArray *arr = g_ptr_array_new();
    if (pw_is_root()) {
        /* bez prefiksu */
    } else if (pw_have("pkexec") && polkit_agent_running()) {
        g_ptr_array_add(arr, g_strdup("pkexec"));
    } else if (pw_have("sudo")) {
        g_ptr_array_add(arr, g_strdup("sudo"));
        g_ptr_array_add(arr, g_strdup("-S"));
    }
    for (gsize i = 0; cmd[i]; i++)
        g_ptr_array_add(arr, g_strdup(cmd[i]));
    g_ptr_array_add(arr, NULL);
    return (char **) g_ptr_array_free(arr, FALSE);
}

/* ── Pomocnicze ──────────────────────────────────────────────────────────── */
char *
pw_run_capture(const char *const argv[])
{
    char *out = NULL;
    GError *err = NULL;
    if (!g_spawn_sync(NULL, (char **) argv, NULL,
                      G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL,
                      &out, NULL, NULL, &err)) {
        g_clear_error(&err);
        return NULL;
    }
    if (out) {
        g_strstrip(out); /* modyfikuje w miejscu */
        return out;
    }
    return NULL;
}

gboolean
pw_is_live(void)
{
    char *cmdline = NULL;
    if (g_file_get_contents("/proc/cmdline", &cmdline, NULL, NULL)) {
        gboolean live = (strstr(cmdline, "pagan.live") != NULL);
        if (!live) {
            /* samotne "live" jako osobny parametr */
            char **parts = g_strsplit_set(cmdline, " \t\n", -1);
            for (gsize i = 0; parts[i]; i++) {
                if (g_strcmp0(parts[i], "live") == 0) {
                    live = TRUE;
                    break;
                }
            }
            g_strfreev(parts);
        }
        g_free(cmdline);
        if (live)
            return TRUE;
    }
    if (g_file_test("/run/live", G_FILE_TEST_IS_DIR) ||
        g_file_test("/lib/live/mount", G_FILE_TEST_IS_DIR) ||
        g_file_test("/live/root", G_FILE_TEST_IS_DIR))
        return TRUE;
    char *mounts = NULL;
    if (g_file_get_contents("/proc/mounts", &mounts, NULL, NULL)) {
        gboolean overlay = (strstr(mounts, " / overlay ") != NULL);
        g_free(mounts);
        if (overlay)
            return TRUE;
    }
    return FALSE;
}

/* Porównaj dwa segmenty wersji: liczbowo gdy oba liczbowe, inaczej tekstowo. */
static int
seg_cmp(const char *a, const char *b)
{
    gboolean na = (*a != '\0');
    gboolean nb = (*b != '\0');
    for (const char *p = a; *p; p++)
        if (!g_ascii_isdigit(*p)) { na = FALSE; break; }
    for (const char *p = b; *p; p++)
        if (!g_ascii_isdigit(*p)) { nb = FALSE; break; }
    if (na && nb) {
        long va = strtol(a, NULL, 10);
        long vb = strtol(b, NULL, 10);
        return (va < vb) ? -1 : (va > vb) ? 1 : 0;
    }
    return g_strcmp0(a, b);
}

int
pw_version_cmp(const char *a, const char *b)
{
    char **sa = g_strsplit_set(a ? a : "", "._+~-", -1);
    char **sb = g_strsplit_set(b ? b : "", "._+~-", -1);
    int result = 0;
    for (gsize i = 0; sa[i] || sb[i]; i++) {
        const char *x = sa[i] ? sa[i] : "";
        const char *y = sb[i] ? sb[i] : "";
        int c = seg_cmp(x, y);
        if (c != 0) {
            result = c;
            break;
        }
    }
    g_strfreev(sa);
    g_strfreev(sb);
    return result;
}

char *
pw_format_size(guint64 bytes)
{
    static const char *units[] = {"B", "KB", "MB", "GB", "TB"};
    double v = (double) bytes;
    int u = 0;
    while (v >= 1024.0 && u < 4) {
        v /= 1024.0;
        u++;
    }
    if (u == 0)
        return g_strdup_printf("%" G_GUINT64_FORMAT " %s", bytes, units[u]);
    return g_strdup_printf("%.1f %s", v, units[u]);
}

/* ── Terminal (pseudo-tty) ───────────────────────────────────────────────── */
struct PwPty {
    int master;
    pid_t pid;
    gboolean alive;
    GMutex lock;
    gint refs;
    PwLineFunc on_line;
    PwDoneFunc on_done;
    gpointer data;
};

/* Usuń sekwencje ANSI (kolory, sterowanie kursorem) – GtkTextView nie renderuje
 * escape'ów, więc surowe „\x1b[32m” zaśmiecałoby log. Zostawiamy czysty tekst. */
static char *
strip_ansi(const char *in)
{
    GString *out = g_string_new(NULL);
    const unsigned char *p = (const unsigned char *) in;
    while (*p) {
        if (*p == 0x1b) {
            p++;
            if (*p == '[') {                 /* CSI: ESC [ ... litera @-~ */
                p++;
                while (*p >= 0x20 && *p <= 0x3f)
                    p++;
                if (*p >= 0x40 && *p <= 0x7e)
                    p++;
            } else if (*p == ']') {          /* OSC: ESC ] ... BEL/ST */
                p++;
                while (*p && *p != 0x07 && *p != 0x1b)
                    p++;
                if (*p == 0x07)
                    p++;
                else if (*p == 0x1b)
                    p++;
            } else if (*p) {
                p++;                         /* pojedynczy ESC x */
            }
            continue;
        }
        if (*p == '\r') {                    /* powrót karetki – pomijamy */
            p++;
            continue;
        }
        g_string_append_c(out, (char) *p);
        p++;
    }
    return g_string_free(out, FALSE);
}

static void
pty_unref(PwPty *pty)
{
    if (!pty)
        return;
    if (g_atomic_int_dec_and_test(&pty->refs)) {
        g_mutex_clear(&pty->lock);
        g_free(pty);
    }
}

static void
pty_emit_line(PwPty *pty, const char *line)
{
    if (!pty->on_line)
        return;
    LineMsg *m = g_new0(LineMsg, 1);
    m->func = pty->on_line;
    m->line = g_strdup(line);
    m->data = pty->data;
    g_idle_add(line_idle, m);
}

static void
pty_emit_done(PwPty *pty, int status)
{
    if (!pty->on_done)
        return;
    DoneMsg *m = g_new0(DoneMsg, 1);
    m->func = pty->on_done;
    m->status = status;
    m->data = pty->data;
    g_idle_add(done_idle, m);
}

static gpointer
pty_thread(gpointer p)
{
    PwPty *pty = p;
    GString *buf = g_string_new(NULL);
    char chunk[4096];
    ssize_t n;

    while ((n = read(pty->master, chunk, sizeof(chunk))) > 0) {
        for (ssize_t i = 0; i < n; i++) {
            if (chunk[i] == '\n') {
                char *clean = strip_ansi(buf->str);
                pty_emit_line(pty, clean);
                g_free(clean);
                g_string_truncate(buf, 0);
            } else {
                g_string_append_c(buf, chunk[i]);
            }
        }
    }
    if (buf->len) {
        char *clean = strip_ansi(buf->str);
        if (*clean)
            pty_emit_line(pty, clean);
        g_free(clean);
    }
    g_string_free(buf, TRUE);

    int status = -1;
    int st = 0;
    if (waitpid(pty->pid, &st, 0) == pty->pid) {
        if (WIFEXITED(st))
            status = WEXITSTATUS(st);
        else if (WIFSIGNALED(st))
            status = 128 + WTERMSIG(st);
    }

    g_mutex_lock(&pty->lock);
    pty->alive = FALSE;
    if (pty->master >= 0) {
        close(pty->master);
        pty->master = -1;
    }
    g_mutex_unlock(&pty->lock);

    pty_emit_done(pty, status);
    pty_unref(pty); /* zwolnij referencję wątku */
    return NULL;
}

PwPty *
pw_pty_spawn(const char *const argv[], const char *initial_input,
             PwLineFunc on_line, PwDoneFunc on_done, gpointer data)
{
    if (!argv || !argv[0])
        return NULL;

    PwPty *pty = g_new0(PwPty, 1);
    pty->master = -1;
    pty->refs = 1;
    g_mutex_init(&pty->lock);
    pty->on_line = on_line;
    pty->on_done = on_done;
    pty->data = data;

    /* Głęboka kopia argv przed forkiem – po forku wolno wywoływać wyłącznie
     * funkcje bezpieczne dla sygnałów, więc nie alokujemy po stronie dziecka. */
    gsize argc = 0;
    while (argv[argc])
        argc++;
    char **child_argv = g_new0(char *, argc + 1);
    for (gsize i = 0; i < argc; i++)
        child_argv[i] = g_strdup(argv[i]);

    int master = -1;
    pid_t pid = forkpty(&master, NULL, NULL, NULL);
    if (pid < 0) {
        g_strfreev(child_argv);
        g_mutex_clear(&pty->lock);
        g_free(pty);
        return NULL;
    }
    if (pid == 0) {
        /* Dziecko: forkpty dał już nową sesję z PTY jako terminalem. */
        setenv("TERM", "xterm-256color", 1);
        setenv("COLORTERM", "truecolor", 1);
        execvp(child_argv[0], child_argv);
        _exit(127);
    }
    g_strfreev(child_argv);

    pty->master = master;
    pty->pid = pid;
    pty->alive = TRUE;

    /* Wstępne wejście (np. hasło do `sudo -S`). Echo na PTY wyłączamy PRZED
     * zapisem, żeby hasło nie zostało odbite do logu terminala. */
    if (initial_input && *initial_input) {
        struct termios tio;
        if (tcgetattr(master, &tio) == 0) {
            tio.c_lflag &= ~ECHO;
            tcsetattr(master, TCSANOW, &tio);
        }
        ssize_t w = write(master, initial_input, strlen(initial_input));
        (void) w;
    }

    g_atomic_int_inc(&pty->refs); /* referencja wątku czytającego */
    g_thread_unref(g_thread_new("pw-pty", pty_thread, pty));
    return pty;
}

void
pw_pty_write(PwPty *pty, const char *data)
{
    if (!pty || !data)
        return;
    g_mutex_lock(&pty->lock);
    if (pty->alive && pty->master >= 0) {
        ssize_t w = write(pty->master, data, strlen(data));
        (void) w;
    }
    g_mutex_unlock(&pty->lock);
}

void
pw_pty_cancel(PwPty *pty)
{
    if (!pty)
        return;
    g_mutex_lock(&pty->lock);
    gboolean alive = pty->alive;
    pid_t pid = pty->pid;
    g_mutex_unlock(&pty->lock);
    if (!alive)
        return;
    /* forkpty tworzy nową sesję, więc -pid to cała grupa procesów polecenia. */
    kill(-pid, SIGTERM);
    kill(pid, SIGTERM);
}

gboolean
pw_pty_alive(PwPty *pty)
{
    if (!pty)
        return FALSE;
    g_mutex_lock(&pty->lock);
    gboolean alive = pty->alive;
    g_mutex_unlock(&pty->lock);
    return alive;
}

void
pw_pty_free(PwPty *pty)
{
    if (!pty)
        return;
    g_mutex_lock(&pty->lock);
    if (pty->alive) {
        kill(-pty->pid, SIGTERM);
        kill(pty->pid, SIGTERM);
    }
    g_mutex_unlock(&pty->lock);
    pty_unref(pty);
}