Skip to content
Myr

application.c

This file

Path

application.c

397 lines · 11.2 KiB · C

Last changed by

application: exec: error out on non-spec compliant quoting (#585)Daniel Eklöfbefore adoptiondb3385d

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 "xmalloc.h"2021static void22push_argv(char ***argv, size_t *size, char *arg, size_t *argc)23{24    if (arg != NULL && arg[0] == '%')25        return;2627    if (*argc >= *size) {28        size_t new_size = *size > 0 ? 2 * *size : 10;29        *argv = xreallocarray(*argv, new_size, sizeof(char*));30        *size = new_size;31    }3233    (*argv)[(*argc)++] = arg;34}3536static bool37tokenize_cmdline(char *cmdline, char ***argv)38{39    *argv = NULL;40    size_t argv_size = 0;4142    char *p = cmdline;43    char *search_start = p; /* points to start of current arg */44    char open_quote = 0; /* the current opening quote character, 0 means none open */4546    size_t idx = 0;47    while (*p != '\0') {48        if (*p == '\\') {49            /* lookahead to handle escaped chars50             * only escape if not within single quotes */51            if (open_quote != '\'') {52                /* within double quotes, only \$, \`, \", \\ should be53                 * escaped, others should be literal */54                if ((open_quote != '"' && (*(p + 1) == '\'' || *(p + 1) == ' ')) ||55                    *(p + 1) == '$' ||56                    *(p + 1) == '"' ||57                    *(p + 1) == '`' ||58                    *(p + 1) == '\\')59                {60                    /* essentially delete the (first) backslash */61                    memmove(p, p + 1, strlen(p + 1) + 1);62                }63            }64            /* ignore the other cases */65        } else {66            if (open_quote == 0 && (*p == '\'' || *p == '"')) {67                /*68                 * Open a quote.69                 *70                 * Set search_start (i.e. argument start) to the next71                 * character. Yes, this means the previous argument is72                 * "lost" if it wasn't space separated from the quoted73                 * argument.74                 *75                 * This is ok, because the spec says arguments have to76                 * be quoted in whole. That is, foo"bar" does *not*77                 * translate to the argument 'foobar' - it's invalid.78                 *79                 * Room for improvement: log warning/error message if80                 * the previous character is not a space.81                 */8283                if (search_start != p) {84                    LOG_ERR("command line contains non-specification-compliant "85                            "quoting (arguments must be quoted in whole)");86                    goto err;87                }8889                open_quote = *p;90                search_start = p + 1;91            } else if (*p == open_quote) {92                /*93                 * Close the quote, and create an argument from the94                 * string between the opening and closing quote (as is95                 * - unescaping is done later).96                 *97                 * Note that text following the quote will be treated98                 * as a separate argument, regardless of whether99                 * they're space separated or not.100                 *101                 * Room for improvement: log warning/error message if102                 * the next character is not a space (or the end of103                 * the string).104                 */105                open_quote = 0;106                *p = '\0';107108                push_argv(argv, &argv_size, search_start, &idx);109110                search_start = p + 1;111            } else if (*p == ' ' && open_quote == 0) {112                /* we must not be in an argument right now113                 * check if we can close the arg at p (exclusive) */114                if (p > search_start) {115                    *p = '\0';116                    push_argv(argv, &argv_size, search_start, &idx);117                }118                search_start = p + 1;119            }120        }121        p++;122    }123124    if (open_quote != 0) {125        LOG_ERR("unterminated %s quote\n", open_quote == '"' ? "double" : "single");126        goto err;127    }128129    /* edge case: argument terminated by \0 */130    if (p > search_start)131        push_argv(argv, &argv_size, search_start, &idx);132133    push_argv(argv, &argv_size, NULL, &idx);134    return true;135136err:137    free(*argv);138    return false;139}140141bool142application_execute(const struct application *app, const struct prompt *prompt,143                    const char *launch_prefix, const char *xdg_activation_token)144{145    const char32_t *ptext = prompt_text(prompt);146    const size_t c32len = c32tombs(NULL, ptext, 0);147    char cprompt[c32len + 1];148    c32tombs(cprompt, ptext, c32len + 1);149150    const char *execute = app != NULL ? app->exec : cprompt;151    const char *path = app != NULL ? app->path : NULL;152    const char *id = app != NULL ? app->id : NULL;153154    if (execute == NULL) {155        LOG_ERR("%ls: entry has no Exec field", (const wchar_t *)app->title);156        return false;157    }158159    LOG_DBG("exec(%s)", execute);160161    /* Tokenize the command */162    char *unescaped;163    char *execute_dest;164    size_t execute_len = strlen(execute);165    if (launch_prefix != NULL) {166      size_t launch_len = strlen(launch_prefix);167      unescaped = xmalloc(launch_len + execute_len + 2 /* whitespace + null terminator */);168      memcpy(unescaped, launch_prefix, launch_len);169      unescaped[launch_len] = ' ';170      execute_dest = unescaped + launch_len + 1;171      if (id != NULL) {172          setenv("FUZZEL_DESKTOP_FILE_ID", id, 1);173      } else {174          LOG_WARN("No Desktop File ID, not setting FUZZEL_DESKTOP_FILE_ID");175      }176    } else {177      unescaped = xmalloc(execute_len + 1);178      execute_dest = unescaped;179    }180181    /* Substitute escape sequences for their literal character values */182    for (size_t i = 0; i <= execute_len /* so null terminator is copied */; i++, execute_dest++) {183      if (execute[i] != '\\') {184        *execute_dest = execute[i];185      } else {186        i++;187        switch(execute[i]) {188          case 's':189            *execute_dest = ' ';190            break;191          case 'n':192            *execute_dest = '\n';193            break;194          case 't':195            *execute_dest = '\t';196            break;197          case 'r':198            *execute_dest = '\r';199            break;200          case ';':201            *execute_dest = ';';202            break;203          case '\\':204            *execute_dest = '\\';205            break;206          default:207            free(unescaped);208            LOG_ERR("invalid escaped exec argument character: %c", execute[i]);209            return false;210        }211      }212    }213214    LOG_INFO("executing %s: \"%s\"", id, unescaped);215216    char **argv;217    if (!tokenize_cmdline(unescaped, &argv)) {218        free(unescaped);219        return false;220    }221222    LOG_DBG("argv:");223    for (size_t i = 0; argv[i] != NULL; i++)224        LOG_DBG("  %zu: \"%s\"", i, argv[i]);225226    int pipe_fds[2];227    if (pipe2(pipe_fds, O_CLOEXEC) == -1) {228        LOG_ERRNO("failed to create pipe");229        free(unescaped);230        free(argv);231        return false;232    }233234    pid_t pid = fork();235    if (pid == -1) {236        close(pipe_fds[0]);237        close(pipe_fds[1]);238239        free(unescaped);240        free(argv);241242        LOG_ERRNO("failed to fork");243        return false;244    }245246    if (pid == 0) {247        /* Child */248249        /* Close read end */250        close(pipe_fds[0]);251252        if (path != NULL) {253            if (chdir(path) == -1)254                LOG_ERRNO("failed to chdir to %s", path);255        }256257        if (xdg_activation_token != NULL) {258            /* Prepare client for xdg activation startup */259            setenv("XDG_ACTIVATION_TOKEN", xdg_activation_token, 1);260            /* And X11 startup notifications */261            setenv("DESKTOP_STARTUP_ID", xdg_activation_token, 1);262        }263264        /* Redirect stdin -> /dev/null */265        int devnull_r = open("/dev/null", O_RDONLY | O_CLOEXEC);266        if (devnull_r == -1)267            goto child_err;268269        if (dup2(devnull_r, STDIN_FILENO) == -1)270            goto child_err;271272        execvp(argv[0], argv);273274    child_err:275        /* Signal error back to parent process */276        (void)!write(pipe_fds[1], &errno, sizeof(errno));277        _exit(1);278    } else {279        /* Parent */280281        free(unescaped);282        free(argv);283284        /* Close write end */285        close(pipe_fds[1]);286287        int _errno;288        static_assert(sizeof(_errno) == sizeof(errno), "errno size mismatch");289290        ssize_t ret = read(pipe_fds[0], &_errno, sizeof(_errno));291        if (ret == -1)292            LOG_ERRNO("failed to read from pipe");293        else if (ret == sizeof(_errno))294            LOG_ERRNO_P("%s: failed to execute", _errno, execute);295        else {296            LOG_DBG("%s: fork+exec succeeded", execute);297        }298299        close(pipe_fds[0]);300        return ret == 0;301    }302}303304struct application_list *305applications_init(void)306{307    struct application_list *ret = xcalloc(1, sizeof(*ret));308309    if (mtx_init(&ret->lock, mtx_plain) != thrd_success) {310        LOG_ERR("failed to instantiate application list mutex");311        free(ret);312        return NULL;313    }314315    return ret;316}317318void319applications_destroy(struct application_list *apps)320{321    if (apps == NULL)322        return;323324    for (size_t i = 0; i < apps->count; i++) {325        struct application *app = apps->v[i];326327        free(app->id);328        free(app->path);329        free(app->exec);330        free(app->app_id);331        free(app->title);332        if (app->render_title != app->title)333            free(app->render_title);334        free(app->title_lowercase);335        free(app->basename);336        free(app->wexec);337        free(app->generic_name);338        free(app->comment);339        free(app->icon.name);340341        tll_free_and_free(app->keywords, free);342        tll_free_and_free(app->categories, free);343344        free(app->dmenu_input);345346        switch (app->icon.type) {347        case ICON_NONE:348            break;349350        case ICON_PNG:351            if (app->icon.png != NULL) {352#if defined(FUZZEL_ENABLE_PNG_LIBPNG)353                free(pixman_image_get_data(app->icon.png));354                pixman_image_unref(app->icon.png);355#endif356            }357            break;358359        case ICON_SVG:360            if (app->icon.svg != NULL) {361#if defined(FUZZEL_ENABLE_SVG_LIBRSVG)362                g_object_unref(app->icon.svg);363#elif defined(FUZZEL_ENABLE_SVG_NANOSVG)364                nsvgDelete(app->icon.svg);365#endif366            }367            break;368        }369370        tll_foreach(app->icon.rasterized, it) {371            struct rasterized *rast = &it->item;372            free(pixman_image_get_data(rast->pix));373            pixman_image_unref(rast->pix);374            tll_remove(app->icon.rasterized, it);375        }376        free(app->icon.path);377378        fcft_text_run_destroy(app->shaped);379        fcft_text_run_destroy(app->shaped_bold);380        free(app);381    }382383    mtx_destroy(&apps->lock);384    free(apps->v);385    free(apps);386}387388void389applications_flush_text_run_cache(struct application_list *apps)390{391    for (size_t i = 0; i < apps->count; i++) {392        fcft_text_run_destroy(apps->v[i]->shaped);393        fcft_text_run_destroy(apps->v[i]->shaped_bold);394        apps->v[i]->shaped = NULL;395        apps->v[i]->shaped_bold = NULL;396    }397}