Skip to content
Myr

application.c

This file

Path

application.c

476 lines · 14.3 KiB · C

Last changed by

application: fix indentationDaniel Eklöfbefore adoptiondf9368b

History of this file

Take it

1#include "application.h"23#include <stdbool.h>4#include <stdio.h>5#include <stdlib.h>6#include <string.h>7#include <errno.h>8#include <assert.h>910#include <sys/types.h>11#include <sys/stat.h>12#include <unistd.h>13#include <fcntl.h>1415#define LOG_MODULE "application"16#define LOG_ENABLE_DBG 017#include "log.h"18#include "char32.h"19#include "debug.h"20#include "xmalloc.h"2122static void23push_argv(char ***argv, size_t *size, char *arg, size_t *argc)24{25    if (arg != NULL && arg[0] == '%')26        return;2728    if (*argc >= *size) {29        size_t new_size = *size > 0 ? 2 * *size : 10;30        *argv = xreallocarray(*argv, new_size, sizeof(char*));31        *size = new_size;32    }3334    (*argv)[(*argc)++] = arg;35}3637static bool38tokenize_cmdline(char *cmdline, char ***argv)39{40    *argv = NULL;41    size_t argv_size = 0;4243    char *p = cmdline;44    char *search_start = p; /* points to start of current arg */45    char open_quote = 0; /* the current opening quote character, 0 means none open */4647    size_t idx = 0;48    while (*p != '\0') {49        if (*p == '\\') {50            /* lookahead to handle escaped chars51             * only escape if not within single quotes */52            if (open_quote != '\'') {53                /* within double quotes, only \$, \`, \", \\ should be54                 * escaped, others should be literal */55                if ((open_quote != '"' && (*(p + 1) == '\'' || *(p + 1) == ' ')) ||56                    *(p + 1) == '$' ||57                    *(p + 1) == '"' ||58                    *(p + 1) == '`' ||59                    *(p + 1) == '\\')60                {61                    /* essentially delete the (first) backslash */62                    memmove(p, p + 1, strlen(p + 1) + 1);63                }64            }65            /* ignore the other cases */66        } else {67            if (open_quote == 0 && (*p == '\'' || *p == '"')) {68                /*69                 * Open a quote.70                 *71                 * Set search_start (i.e. argument start) to the next72                 * character. Yes, this means the previous argument is73                 * "lost" if it wasn't space separated from the quoted74                 * argument.75                 *76                 * This is ok, because the spec says arguments have to77                 * be quoted in whole. That is, foo"bar" does *not*78                 * translate to the argument 'foobar' - it's invalid.79                 *80                 * Room for improvement: log warning/error message if81                 * the previous character is not a space.82                 */8384                if (search_start != p) {85                    LOG_ERR("command line contains non-specification-compliant "86                            "quoting (arguments must be quoted in whole)");87                    goto err;88                }8990                open_quote = *p;91                search_start = p + 1;92            } else if (*p == open_quote) {93                /*94                 * Close the quote, and create an argument from the95                 * string between the opening and closing quote (as is96                 * - unescaping is done later).97                 *98                 * Note that text following the quote will be treated99                 * as a separate argument, regardless of whether100                 * they're space separated or not.101                 *102                 * Room for improvement: log warning/error message if103                 * the next character is not a space (or the end of104                 * the string).105                 */106                open_quote = 0;107                *p = '\0';108109                push_argv(argv, &argv_size, search_start, &idx);110111                search_start = p + 1;112            } else if (*p == ' ' && open_quote == 0) {113                /* we must not be in an argument right now114                 * check if we can close the arg at p (exclusive) */115                if (p > search_start) {116                    *p = '\0';117                    push_argv(argv, &argv_size, search_start, &idx);118                }119                search_start = p + 1;120            }121        }122        p++;123    }124125    if (open_quote != 0) {126        LOG_ERR("unterminated %s quote\n", open_quote == '"' ? "double" : "single");127        goto err;128    }129130    /* edge case: argument terminated by \0 */131    if (p > search_start)132        push_argv(argv, &argv_size, search_start, &idx);133134    push_argv(argv, &argv_size, NULL, &idx);135    return true;136137err:138    free(*argv);139    return false;140}141142bool143application_execute(const struct application *app, const struct prompt *prompt,144                    const char *launch_prefix, const char *xdg_activation_token)145{146    const char32_t *ptext = prompt_text(prompt);147    const size_t c32len = c32tombs(NULL, ptext, 0);148    char cprompt[c32len + 1];149    c32tombs(cprompt, ptext, c32len + 1);150151    const char *execute = app != NULL ? app->exec : cprompt;152    const char *path = app != NULL ? app->path : NULL;153    const char *id = app != NULL ? app->id : NULL;154155    if (execute == NULL) {156        LOG_ERR("%ls: entry has no Exec field", (const wchar_t *)app->title);157        return false;158    }159160    LOG_DBG("exec(%s)", execute);161162    /* Tokenize the command */163    char *unescaped;164    char *execute_dest;165    size_t execute_len = strlen(execute);166    if (launch_prefix != NULL) {167        size_t launch_len = strlen(launch_prefix);168        unescaped = xmalloc(launch_len + execute_len + 2 /* whitespace + null terminator */);169        memcpy(unescaped, launch_prefix, launch_len);170        unescaped[launch_len] = ' ';171        execute_dest = unescaped + launch_len + 1;172173        if (id != NULL) {174            setenv("DESKTOP_ENTRY_ID", id, 1);175            /* Keep FUZZEL_DESKTOP_FILE_ID for backward compatibility */176            setenv("FUZZEL_DESKTOP_FILE_ID", id, 1);177        } else {178            LOG_WARN("No Desktop File ID, not setting DESKTOP_ENTRY_ID");179        }180181        if (app != NULL) {182            if (app->desktop_file_path != NULL) {183                setenv("DESKTOP_ENTRY_PATH", app->desktop_file_path, 1);184            }185186            if (app->action_id != NULL) {187                setenv("DESKTOP_ENTRY_ACTION", app->action_id, 1);188            }189190            if (app->original_name != NULL) {191                char *name_utf8 = ac32tombs(app->original_name);192                setenv("DESKTOP_ENTRY_NAME", name_utf8, 1);193                free(name_utf8);194            }195196            if (app->localized_name != NULL) {197                char *localized_name_utf8 = ac32tombs(app->localized_name);198                setenv("DESKTOP_ENTRY_NAME_L", localized_name_utf8, 1);199                free(localized_name_utf8);200            }201202            if (app->comment != NULL) {203                char *comment_utf8 = ac32tombs(app->comment);204                setenv("DESKTOP_ENTRY_COMMENT", comment_utf8, 1);205                setenv("DESKTOP_ENTRY_COMMENT_L", comment_utf8, 1); /* TODO: distinguish localized */206                free(comment_utf8);207            }208209            if (app->icon.name != NULL) {210                setenv("DESKTOP_ENTRY_ICON", app->icon.name, 1);211            }212213            if (app->original_generic_name != NULL) {214                char *generic_name_utf8 = ac32tombs(app->original_generic_name);215                setenv("DESKTOP_ENTRY_GENERICNAME", generic_name_utf8, 1);216                free(generic_name_utf8);217            }218219            if (app->localized_generic_name != NULL) {220                char *localized_generic_name_utf8 = ac32tombs(app->localized_generic_name);221                setenv("DESKTOP_ENTRY_GENERICNAME_L", localized_generic_name_utf8, 1);222                free(localized_generic_name_utf8);223            }224225            if (app->action_name != NULL) {226                char *action_name_utf8 = ac32tombs(app->action_name);227                setenv("DESKTOP_ENTRY_ACTION_NAME", action_name_utf8, 1);228                free(action_name_utf8);229            }230231            if (app->localized_action_name != NULL) {232                char *localized_action_name_utf8 = ac32tombs(app->localized_action_name);233                setenv("DESKTOP_ENTRY_ACTION_NAME_L", localized_action_name_utf8, 1);234                free(localized_action_name_utf8);235            }236237            if (app->action_id != NULL && app->icon.name != NULL) {238                setenv("DESKTOP_ENTRY_ACTION_ICON", app->icon.name, 1);239            }240        }241    } else {242        unescaped = xmalloc(execute_len + 1);243        execute_dest = unescaped;244    }245246    /* Substitute escape sequences for their literal character values */247    for (size_t i = 0; i <= execute_len /* so null terminator is copied */; i++, execute_dest++) {248        if (execute[i] != '\\') {249            *execute_dest = execute[i];250        } else {251            i++;252            switch(execute[i]) {253            case 's':254                *execute_dest = ' ';255                break;256            case 'n':257                *execute_dest = '\n';258                break;259            case 't':260                *execute_dest = '\t';261                break;262            case 'r':263                *execute_dest = '\r';264                break;265            case ';':266                *execute_dest = ';';267                break;268            case '\\':269                *execute_dest = '\\';270                break;271            default:272                free(unescaped);273                LOG_ERR("invalid escaped exec argument character: %c", execute[i]);274                return false;275            }276        }277    }278279    LOG_INFO("executing %s: \"%s\"", id, unescaped);280281    char **argv;282    if (!tokenize_cmdline(unescaped, &argv)) {283        free(unescaped);284        return false;285    }286287    LOG_DBG("argv:");288    for (size_t i = 0; argv[i] != NULL; i++)289        LOG_DBG("  %zu: \"%s\"", i, argv[i]);290291    xassert(argv != NULL);292    xassert(argv[0] != NULL);293294    int pipe_fds[2];295    if (pipe2(pipe_fds, O_CLOEXEC) == -1) {296        LOG_ERRNO("failed to create pipe");297        free(unescaped);298        free(argv);299        return false;300    }301302    pid_t pid = fork();303    if (pid == -1) {304        close(pipe_fds[0]);305        close(pipe_fds[1]);306307        free(unescaped);308        free(argv);309310        LOG_ERRNO("failed to fork");311        return false;312    }313314    if (pid == 0) {315        /* Child */316317        /* Close read end */318        close(pipe_fds[0]);319320        if (path != NULL) {321            if (chdir(path) == -1)322                LOG_ERRNO("failed to chdir to %s", path);323        }324325        if (xdg_activation_token != NULL) {326            /* Prepare client for xdg activation startup */327            setenv("XDG_ACTIVATION_TOKEN", xdg_activation_token, 1);328            /* And X11 startup notifications */329            setenv("DESKTOP_STARTUP_ID", xdg_activation_token, 1);330        }331332        /* Redirect stdin -> /dev/null */333        int devnull_r = open("/dev/null", O_RDONLY | O_CLOEXEC);334        if (devnull_r == -1)335            goto child_err;336337        if (dup2(devnull_r, STDIN_FILENO) == -1)338            goto child_err;339340        execvp(argv[0], argv);341342    child_err:343        /* Signal error back to parent process */344        (void)!write(pipe_fds[1], &errno, sizeof(errno));345        _exit(1);346    } else {347        /* Parent */348349        free(unescaped);350        free(argv);351352        /* Close write end */353        close(pipe_fds[1]);354355        int _errno;356        static_assert(sizeof(_errno) == sizeof(errno), "errno size mismatch");357358        ssize_t ret = read(pipe_fds[0], &_errno, sizeof(_errno));359        if (ret == -1)360            LOG_ERRNO("failed to read from pipe");361        else if (ret == sizeof(_errno))362            LOG_ERRNO_P("%s: failed to execute", _errno, execute);363        else {364            LOG_DBG("%s: fork+exec succeeded", execute);365        }366367        close(pipe_fds[0]);368        return ret == 0;369    }370}371372struct application_list *373applications_init(void)374{375    struct application_list *ret = xcalloc(1, sizeof(*ret));376377    if (mtx_init(&ret->lock, mtx_plain) != thrd_success) {378        LOG_ERR("failed to instantiate application list mutex");379        free(ret);380        return NULL;381    }382383    return ret;384}385386void387applications_destroy(struct application_list *apps)388{389    if (apps == NULL)390        return;391392    for (size_t i = 0; i < apps->count; i++) {393        struct application *app = apps->v[i];394395        free(app->id);396        free(app->path);397        free(app->exec);398        free(app->app_id);399        free(app->title);400        if (app->render_title != app->title)401            free(app->render_title);402        free(app->title_lowercase);403        free(app->basename);404        free(app->wexec);405        free(app->generic_name);406        free(app->comment);407        free(app->icon.name);408409        /* Free additional metadata fields */410        free(app->desktop_file_path);411        free(app->action_id);412        free(app->original_name);413        free(app->localized_name);414        free(app->action_name);415        free(app->localized_action_name);416        free(app->original_generic_name);417        free(app->localized_generic_name);418419        tll_free_and_free(app->keywords, free);420        tll_free_and_free(app->categories, free);421422        free(app->dmenu_input);423        free(app->dmenu_match_nth);424425        switch (app->icon.type) {426        case ICON_NONE:427            break;428429        case ICON_PNG:430            if (app->icon.png != NULL) {431#if defined(FUZZEL_ENABLE_PNG_LIBPNG)432                free(pixman_image_get_data(app->icon.png));433                pixman_image_unref(app->icon.png);434#endif435            }436            break;437438        case ICON_SVG:439            if (app->icon.svg != NULL) {440#if defined(FUZZEL_ENABLE_SVG_LIBRSVG)441                g_object_unref(app->icon.svg);442#elif defined(FUZZEL_ENABLE_SVG_NANOSVG)443                nsvgDelete(app->icon.svg);444#endif445            }446            break;447        }448449        tll_foreach(app->icon.rasterized, it) {450            struct rasterized *rast = &it->item;451            free(pixman_image_get_data(rast->pix));452            pixman_image_unref(rast->pix);453            tll_remove(app->icon.rasterized, it);454        }455        free(app->icon.path);456457        fcft_text_run_destroy(app->shaped);458        fcft_text_run_destroy(app->shaped_bold);459        free(app);460    }461462    mtx_destroy(&apps->lock);463    free(apps->v);464    free(apps);465}466467void468applications_flush_text_run_cache(struct application_list *apps)469{470    for (size_t i = 0; i < apps->count; i++) {471        fcft_text_run_destroy(apps->v[i]->shaped);472        fcft_text_run_destroy(apps->v[i]->shaped_bold);473        apps->v[i]->shaped = NULL;474        apps->v[i]->shaped_bold = NULL;475    }476}