chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
1134 files changed
+433629
No files matched your search
@@ -0,0 +1,662 @@
|
||||
/*
|
||||
* cli-parser.h
|
||||
* Copyright (C) 2025 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
*
|
||||
* Distributed under terms of the GPL3 license.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Python.h>
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <errno.h>
|
||||
#include "../iqsort.h"
|
||||
|
||||
#ifndef RAII_PyObject
|
||||
static inline void
|
||||
cleanup_decref2(PyObject **p) {
|
||||
Py_CLEAR(*p);
|
||||
}
|
||||
#define RAII_PyObject(name, initializer) __attribute__((cleanup(cleanup_decref2))) PyObject *name = initializer
|
||||
|
||||
#undef MAX
|
||||
#define MAX(x, y) \
|
||||
__extension__({ \
|
||||
const __typeof__(x) __a__ = (x); \
|
||||
const __typeof__(y) __b__ = (y); \
|
||||
__a__ > __b__ ? __a__ : __b__; \
|
||||
})
|
||||
#endif
|
||||
|
||||
typedef enum CLIValueType { CLI_VALUE_STRING, CLI_VALUE_BOOL, CLI_VALUE_INT, CLI_VALUE_FLOAT, CLI_VALUE_LIST, CLI_VALUE_CHOICE } CLIValueType;
|
||||
typedef struct CLIValue {
|
||||
CLIValueType type;
|
||||
long long intval;
|
||||
double floatval;
|
||||
bool boolval;
|
||||
const char *strval;
|
||||
struct {
|
||||
const char **items;
|
||||
size_t count, capacity;
|
||||
} listval;
|
||||
} CLIValue;
|
||||
|
||||
#define NAME cli_hash
|
||||
#define KEY_TY const char *
|
||||
#define VAL_TY CLIValue
|
||||
#include "../kitty-verstable.h"
|
||||
#define value_map_for_loop(x) vt_create_for_loop(cli_hash_itr, itr, x)
|
||||
|
||||
#define NAME alias_hash
|
||||
#define KEY_TY const char *
|
||||
#define VAL_TY const char *
|
||||
#include "../kitty-verstable.h"
|
||||
#define alias_map_for_loop(x) vt_create_for_loop(alias_hash_itr, itr, x)
|
||||
|
||||
typedef struct FlagSpec {
|
||||
CLIValue defval;
|
||||
const char *dest;
|
||||
} FlagSpec;
|
||||
|
||||
#define NAME flag_hash
|
||||
#define KEY_TY const char *
|
||||
#define VAL_TY FlagSpec
|
||||
#include "../kitty-verstable.h"
|
||||
#define flag_map_for_loop(x) vt_create_for_loop(flag_hash_itr, itr, x)
|
||||
|
||||
|
||||
typedef struct CLISpec {
|
||||
cli_hash value_map;
|
||||
alias_hash alias_map;
|
||||
flag_hash flag_map, disabled_map;
|
||||
char **argv;
|
||||
int argc; // leftover args
|
||||
char **original_argv;
|
||||
int original_argc; // original args
|
||||
const char *errmsg;
|
||||
struct {
|
||||
struct {
|
||||
char *buf;
|
||||
size_t capacity, used;
|
||||
} *items;
|
||||
size_t count, capacity;
|
||||
} blocks;
|
||||
} CLISpec;
|
||||
|
||||
static void
|
||||
out_of_memory(int line) {
|
||||
fprintf(stderr, "Out of memory at %s:%d\n", __FILE__, line);
|
||||
exit(1);
|
||||
}
|
||||
#define OOM out_of_memory(__LINE__)
|
||||
|
||||
static void *
|
||||
alloc_for_cli(CLISpec *spec, size_t sz) {
|
||||
sz++;
|
||||
if (!spec->blocks.capacity) {
|
||||
spec->blocks.capacity = 8;
|
||||
spec->blocks.items = calloc(spec->blocks.capacity, sizeof(spec->blocks.items[0]));
|
||||
if (!spec->blocks.items) return NULL;
|
||||
spec->blocks.count = 1;
|
||||
}
|
||||
#define block spec->blocks.items[spec->blocks.count - 1]
|
||||
if (block.used + sz >= block.capacity) {
|
||||
if (block.capacity) { // need new block
|
||||
spec->blocks.count++;
|
||||
if (spec->blocks.count >= spec->blocks.capacity) {
|
||||
spec->blocks.capacity *= 2;
|
||||
spec->blocks.items = realloc(spec->blocks.items, spec->blocks.capacity * sizeof(spec->blocks.items[0]));
|
||||
if (!spec->blocks.items) return NULL;
|
||||
}
|
||||
}
|
||||
block.capacity = MAX(sz, 8192u);
|
||||
block.buf = malloc(block.capacity);
|
||||
if (!block.buf) return NULL;
|
||||
block.used = 0;
|
||||
}
|
||||
char *ans = block.buf + block.used;
|
||||
ans[sz - 1] = 0;
|
||||
block.used += sz;
|
||||
// keep returned memory regions aligned to size of pointer
|
||||
size_t extra = sz % sizeof(void *);
|
||||
if (extra) block.used += sizeof(void *) - extra;
|
||||
return ans;
|
||||
#undef block
|
||||
}
|
||||
|
||||
#define set_err(fmt, ...) \
|
||||
{ \
|
||||
int sz = snprintf(NULL, 0, fmt, __VA_ARGS__); \
|
||||
char *buf = alloc_for_cli(spec, sz + 4); \
|
||||
if (!buf) OOM; \
|
||||
snprintf(buf, sz + 4, fmt, __VA_ARGS__); \
|
||||
spec->errmsg = buf; \
|
||||
}
|
||||
|
||||
static ssize_t
|
||||
levenshtein_distance(size_t *cache, const char *a, const char *b) {
|
||||
if (a == b) return 0;
|
||||
const size_t length = strlen(a);
|
||||
const size_t bLength = strlen(b);
|
||||
if (length == 0) return bLength;
|
||||
if (bLength == 0) return length;
|
||||
size_t index = 0, bIndex = 0, distance = 0, bDistance = 0, result = 0;
|
||||
char code = 0;
|
||||
|
||||
// initialize the vector.
|
||||
while (index < length) {
|
||||
cache[index] = index + 1;
|
||||
index++;
|
||||
}
|
||||
|
||||
while (bIndex < bLength) {
|
||||
code = b[bIndex];
|
||||
result = distance = bIndex++;
|
||||
index = SIZE_MAX;
|
||||
|
||||
while (++index < length) {
|
||||
bDistance = code == a[index] ? distance : distance + 1;
|
||||
distance = cache[index];
|
||||
|
||||
cache[index] = result = distance > result ? bDistance > result ? result + 1 : bDistance : bDistance > distance ? distance + 1 : bDistance;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static bool
|
||||
add_to_listval(CLISpec *spec, CLIValue *v, const char *val) {
|
||||
if (v->listval.count + 1 >= v->listval.capacity) {
|
||||
size_t cap = MAX(64u, v->listval.capacity * 2u);
|
||||
char **new = alloc_for_cli(spec, cap * sizeof(v->listval.items[0]));
|
||||
if (!new) return false;
|
||||
v->listval.capacity = cap;
|
||||
if (v->listval.count) memcpy(new, v->listval.items, sizeof(new[0]) * v->listval.count);
|
||||
v->listval.items = (void *)new;
|
||||
}
|
||||
v->listval.items[v->listval.count++] = val;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
use_ansi_escape_codes(void) {
|
||||
static bool checked = false, ans;
|
||||
if (!checked) {
|
||||
ans = isatty(STDERR_FILENO);
|
||||
checked = true;
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
|
||||
static const char *
|
||||
formatted_text(CLISpec *spec, const char *start_code, const char *text, const char *end_code) {
|
||||
if (!use_ansi_escape_codes()) return text;
|
||||
static const char *fmt = "\x1b[%sm%s\x1b[%sm";
|
||||
int sz = snprintf(NULL, 0, fmt, start_code, text, end_code);
|
||||
char *ans = alloc_for_cli(spec, sz + 1);
|
||||
snprintf(ans, sz + 1, fmt, start_code, text, end_code);
|
||||
return ans;
|
||||
}
|
||||
|
||||
#define red_text(text) formatted_text(spec, "91", text, "39")
|
||||
#define yellow_text(text) formatted_text(spec, "93", text, "39")
|
||||
#define green_text(text) formatted_text(spec, "32", text, "39")
|
||||
#define italic_text(text) formatted_text(spec, "3", text, "23")
|
||||
|
||||
typedef struct similiar_alias {
|
||||
const char *alias;
|
||||
ssize_t distance;
|
||||
} similiar_alias;
|
||||
|
||||
static const char *
|
||||
dest_for_alias(CLISpec *spec, const char *alias) {
|
||||
alias_hash_itr itr = vt_get(&spec->alias_map, alias);
|
||||
if (vt_is_end(itr)) {
|
||||
const char *match_key = NULL, *match_val = NULL;
|
||||
size_t total = 0;
|
||||
alias_hash matches;
|
||||
vt_init(&matches);
|
||||
alias_map_for_loop(&spec->alias_map) {
|
||||
if (strstr(itr.data->key, alias) == itr.data->key) {
|
||||
total += strlen(itr.data->key) + 8;
|
||||
if (!match_key) {
|
||||
match_key = itr.data->key;
|
||||
match_val = itr.data->val;
|
||||
}
|
||||
if (vt_is_end(vt_insert(&matches, itr.data->val, itr.data->key))) OOM;
|
||||
}
|
||||
}
|
||||
if (match_key) {
|
||||
if (vt_size(&matches) == 1) {
|
||||
vt_cleanup(&matches);
|
||||
return match_val;
|
||||
}
|
||||
total += 256 + total;
|
||||
char *buf = alloc_for_cli(spec, total);
|
||||
if (!buf) OOM;
|
||||
int n = snprintf(buf, total, "The flag %s is ambiguous. Possible matches:", yellow_text(alias));
|
||||
alias_map_for_loop(&matches) {
|
||||
if ((ssize_t)total > n) n += snprintf(buf + n, total - n, " %s,", itr.data->val);
|
||||
}
|
||||
vt_cleanup(&matches);
|
||||
buf[n - 1] = '.';
|
||||
spec->errmsg = buf;
|
||||
return NULL;
|
||||
}
|
||||
size_t *cache = alloc_for_cli(spec, sizeof(size_t) * strlen(alias));
|
||||
size_t num_aliases = vt_size(&spec->alias_map);
|
||||
similiar_alias *candidates = alloc_for_cli(spec, sizeof(similiar_alias) * num_aliases);
|
||||
size_t num_candidates = 0;
|
||||
alias_map_for_loop(&spec->alias_map) {
|
||||
const char *q = itr.data->key;
|
||||
ssize_t d = levenshtein_distance(cache, alias, q);
|
||||
if (d < 0) break;
|
||||
if (d < 3) candidates[num_candidates++] = (similiar_alias){.alias = q, .distance = d};
|
||||
}
|
||||
if (num_candidates) {
|
||||
#define lt(a, b) (a->distance < b->distance)
|
||||
QSORT(similiar_alias, candidates, num_candidates, lt);
|
||||
set_err("Unknown flag: %s. Did you mean: %s?", red_text(alias), green_text(candidates[0].alias));
|
||||
return NULL;
|
||||
#undef lt
|
||||
}
|
||||
set_err("Unknown flag: %s use --help.", red_text(alias));
|
||||
return NULL;
|
||||
}
|
||||
return itr.data->val;
|
||||
}
|
||||
|
||||
static bool
|
||||
is_alias_bool(CLISpec *spec, const char *alias, const char **dest_out) {
|
||||
*dest_out = dest_for_alias(spec, alias);
|
||||
if (!*dest_out) return false;
|
||||
flag_hash_itr itr = vt_get(&spec->flag_map, *dest_out);
|
||||
return itr.data->val.defval.type == CLI_VALUE_BOOL;
|
||||
}
|
||||
|
||||
static void
|
||||
add_list_value(CLISpec *spec, const char *dest, const char *val) {
|
||||
cli_hash_itr itr = vt_get_or_insert(&spec->value_map, dest, (CLIValue){.type = CLI_VALUE_LIST});
|
||||
if (vt_is_end(itr)) OOM;
|
||||
CLIValue v = itr.data->val;
|
||||
if (!add_to_listval(spec, &v, val)) OOM;
|
||||
if (vt_is_end(vt_insert(&spec->value_map, dest, v))) OOM;
|
||||
}
|
||||
|
||||
static bool
|
||||
process_cli_arg(CLISpec *spec, const char *alias, const char *payload, const char *dest) {
|
||||
if (!dest) dest = dest_for_alias(spec, alias);
|
||||
if (!dest) return false;
|
||||
flag_hash_itr itr = vt_get(&spec->flag_map, dest);
|
||||
const FlagSpec *flag = &itr.data->val;
|
||||
CLIValue val = {.type = flag->defval.type};
|
||||
#define streq(q) (strcmp(payload, #q) == 0)
|
||||
switch (val.type) {
|
||||
case CLI_VALUE_STRING: val.strval = payload; break;
|
||||
case CLI_VALUE_BOOL:
|
||||
if (payload) {
|
||||
if (streq(y) || streq(yes) || streq(true)) val.boolval = true;
|
||||
else if (streq(n) || streq(no) || streq(false)) val.boolval = false;
|
||||
else {
|
||||
set_err(
|
||||
"%s is an invalid value for %s. Valid values are: %s, %s, %s, %s, %s and %s.",
|
||||
red_text(payload[0] ? payload : "<empty>"),
|
||||
green_text(alias),
|
||||
italic_text("y"),
|
||||
italic_text("yes"),
|
||||
italic_text("true"),
|
||||
italic_text("n"),
|
||||
italic_text("no"),
|
||||
italic_text("false"));
|
||||
return false;
|
||||
}
|
||||
} else val.boolval = !flag->defval.boolval;
|
||||
break;
|
||||
case CLI_VALUE_CHOICE:
|
||||
val.strval = NULL;
|
||||
for (size_t c = 0; c < flag->defval.listval.count; c++) {
|
||||
if (strcmp(payload, flag->defval.listval.items[c]) == 0) {
|
||||
val.strval = payload;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!val.strval) {
|
||||
size_t bufsz = 0;
|
||||
for (size_t c = 0; c < flag->defval.listval.count; c++) bufsz += strlen(flag->defval.listval.items[c]) + 8;
|
||||
bufsz += 256 + strlen(alias) + strlen(payload) + bufsz;
|
||||
char *buf = alloc_for_cli(spec, bufsz);
|
||||
int n = snprintf(buf, bufsz, "%s is an invalid value for %s. Valid values are:", red_text(payload[0] ? payload : "<empty>"), green_text(alias));
|
||||
for (size_t c = 0; c < flag->defval.listval.count; c++)
|
||||
if ((ssize_t)bufsz > n) n += snprintf(buf + n, bufsz - n, " %s,", italic_text(flag->defval.listval.items[c]));
|
||||
buf[n - 1] = '.';
|
||||
spec->errmsg = buf;
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case CLI_VALUE_INT:
|
||||
errno = 0;
|
||||
val.intval = strtoll(payload, NULL, 10);
|
||||
if (errno) {
|
||||
set_err("%s is an invalid value for %s, it must be an integer number.", red_text(payload), green_text(alias));
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case CLI_VALUE_FLOAT:
|
||||
errno = 0;
|
||||
val.floatval = strtod(payload, NULL);
|
||||
if (errno) {
|
||||
set_err("%s is an invalid value for %s, it must be a number.", red_text(payload), green_text(alias));
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case CLI_VALUE_LIST: add_list_value(spec, flag->dest, payload); return true;
|
||||
}
|
||||
if (vt_is_end(vt_insert(&spec->value_map, flag->dest, val))) OOM;
|
||||
return true;
|
||||
#undef streq
|
||||
}
|
||||
|
||||
static void
|
||||
alloc_cli_spec(CLISpec *spec) {
|
||||
vt_init(&spec->value_map);
|
||||
vt_init(&spec->alias_map);
|
||||
vt_init(&spec->flag_map);
|
||||
vt_init(&spec->disabled_map);
|
||||
}
|
||||
|
||||
static void
|
||||
dealloc_cli_spec(void *v) {
|
||||
CLISpec *spec = v;
|
||||
for (size_t i = 0; i < spec->blocks.count; i++) free(spec->blocks.items[i].buf);
|
||||
free(spec->blocks.items);
|
||||
vt_cleanup(&spec->value_map);
|
||||
vt_cleanup(&spec->alias_map);
|
||||
vt_cleanup(&spec->flag_map);
|
||||
vt_cleanup(&spec->disabled_map);
|
||||
}
|
||||
|
||||
#define RAII_CLISpec(name) \
|
||||
__attribute__((cleanup(dealloc_cli_spec))) CLISpec name = {0}; \
|
||||
alloc_cli_spec(&name)
|
||||
|
||||
static bool
|
||||
parse_cli_loop(CLISpec *spec, bool save_original_argv, int argc, char **argv) {
|
||||
enum { NORMAL, EXPECTING_ARG } state = NORMAL;
|
||||
spec->argc = 0;
|
||||
spec->argv = NULL;
|
||||
spec->errmsg = NULL;
|
||||
spec->original_argc = argc;
|
||||
spec->original_argv = NULL;
|
||||
if (save_original_argv) {
|
||||
char **copy = alloc_for_cli(spec, sizeof(char *) * (argc + 1));
|
||||
if (!copy) OOM;
|
||||
copy[argc] = NULL;
|
||||
for (int i = 0; i < argc; i++) {
|
||||
size_t len = strlen(argv[i]);
|
||||
copy[i] = alloc_for_cli(spec, len);
|
||||
if (!copy[i]) OOM;
|
||||
memcpy(copy[i], argv[i], len);
|
||||
}
|
||||
spec->original_argv = argv;
|
||||
argv = copy;
|
||||
}
|
||||
char flag[3] = {'-', 0, 0};
|
||||
const char *current_option = NULL;
|
||||
const char *dest_for_current_arg = NULL;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
char *arg = argv[i];
|
||||
switch (state) {
|
||||
case NORMAL: {
|
||||
if (arg[0] == '-') {
|
||||
const bool is_long_opt = arg[1] == '-';
|
||||
if (is_long_opt && arg[2] == 0) {
|
||||
spec->argc = argc - i - 1;
|
||||
if (spec->argc > 0) spec->argv = argv + i + 1;
|
||||
return true;
|
||||
}
|
||||
char *has_equal = strchr(arg, '=');
|
||||
const char *payload = NULL;
|
||||
if (has_equal) {
|
||||
*has_equal = 0;
|
||||
payload = has_equal + 1;
|
||||
}
|
||||
if (is_long_opt) {
|
||||
if (is_alias_bool(spec, arg, &dest_for_current_arg)) {
|
||||
if (!process_cli_arg(spec, arg, payload, dest_for_current_arg)) return false;
|
||||
} else {
|
||||
if (spec->errmsg) return false;
|
||||
if (has_equal) {
|
||||
if (!process_cli_arg(spec, arg, payload, dest_for_current_arg)) return false;
|
||||
} else {
|
||||
state = EXPECTING_ARG;
|
||||
current_option = arg;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const char *letter = arg + 1; *letter; letter++) {
|
||||
flag[1] = *letter;
|
||||
if (letter[1]) {
|
||||
if (!process_cli_arg(spec, flag, NULL, NULL)) return false;
|
||||
} else {
|
||||
if (is_alias_bool(spec, flag, &dest_for_current_arg) || payload) {
|
||||
if (!process_cli_arg(spec, flag, payload, dest_for_current_arg)) return false;
|
||||
} else {
|
||||
if (spec->errmsg) return false;
|
||||
state = EXPECTING_ARG;
|
||||
current_option = flag;
|
||||
}
|
||||
if (spec->errmsg) return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
spec->argc = argc - i;
|
||||
if (spec->argc > 0) spec->argv = argv + i;
|
||||
return true;
|
||||
}
|
||||
} break;
|
||||
case EXPECTING_ARG: {
|
||||
if (current_option && !process_cli_arg(spec, current_option, arg, NULL)) return false;
|
||||
current_option = NULL;
|
||||
state = NORMAL;
|
||||
} break;
|
||||
}
|
||||
}
|
||||
if (state == EXPECTING_ARG) set_err("The %s flag must be followed by an argument.", yellow_text(current_option ? current_option : ""));
|
||||
return spec->errmsg != NULL;
|
||||
}
|
||||
|
||||
#ifdef FOR_LAUNCHER
|
||||
static void
|
||||
output_argv(const char *name, int argc, char **argv) {
|
||||
printf("%s:", name);
|
||||
for (int i = 0; i < argc; i++) printf("\x1e%s", argv[i]);
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
static void
|
||||
output_values_for_testing(CLISpec *spec) {
|
||||
value_map_for_loop(&spec->value_map) {
|
||||
CLIValue v = itr.data->val;
|
||||
switch (v.type) {
|
||||
case CLI_VALUE_STRING:
|
||||
case CLI_VALUE_CHOICE: printf("%s: %s", itr.data->key, v.strval ? v.strval : ""); break;
|
||||
case CLI_VALUE_BOOL: printf("%s: %d", itr.data->key, v.boolval); break;
|
||||
case CLI_VALUE_INT: printf("%s: %lld", itr.data->key, v.intval); break;
|
||||
case CLI_VALUE_FLOAT: printf("%s: %f", itr.data->key, v.floatval); break;
|
||||
case CLI_VALUE_LIST: output_argv(itr.data->key, v.listval.count, (char **)v.listval.items); break;
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
output_for_testing(CLISpec *spec) {
|
||||
output_argv("original_argv", spec->original_argc, spec->original_argv);
|
||||
output_argv("argv", spec->argc, spec->argv);
|
||||
output_values_for_testing(spec);
|
||||
}
|
||||
|
||||
static CLIValue
|
||||
get_cli_val(CLISpec *spec, const char *name) {
|
||||
cli_hash_itr itr = vt_get(&spec->value_map, name);
|
||||
if (vt_is_end(itr)) {
|
||||
flag_hash_itr itr = vt_get(&spec->flag_map, name);
|
||||
if (vt_is_end(itr)) return (CLIValue){0};
|
||||
return itr.data->val.defval;
|
||||
}
|
||||
return itr.data->val;
|
||||
}
|
||||
|
||||
static bool
|
||||
get_bool_cli_val(CLISpec *spec, const char *name) {
|
||||
return get_cli_val(spec, name).boolval;
|
||||
}
|
||||
|
||||
static const char *
|
||||
get_string_cli_val(CLISpec *spec, const char *name) {
|
||||
return get_cli_val(spec, name).strval;
|
||||
}
|
||||
#endif
|
||||
|
||||
static bool
|
||||
clival_as_python(const CLIValue *v, PyObject *is_seen, const char *dest, PyObject *ans) {
|
||||
#define S(fv) \
|
||||
{ \
|
||||
RAII_PyObject(temp, Py_BuildValue("NO", fv, is_seen)); \
|
||||
if (!temp) return false; \
|
||||
if (PyDict_SetItemString(ans, dest, temp) != 0) return false; \
|
||||
}
|
||||
switch (v->type) {
|
||||
case CLI_VALUE_BOOL: S(PyBool_FromLong((long)v->boolval)); break;
|
||||
case CLI_VALUE_STRING:
|
||||
if (v->strval) {
|
||||
S(PyUnicode_FromString(v->strval));
|
||||
} else {
|
||||
S(Py_NewRef(Py_None));
|
||||
}
|
||||
break;
|
||||
case CLI_VALUE_CHOICE: S(PyUnicode_FromString(v->strval)); break;
|
||||
case CLI_VALUE_INT: S(PyLong_FromLongLong(v->intval)); break;
|
||||
case CLI_VALUE_FLOAT: S(PyFloat_FromDouble(v->floatval)); break;
|
||||
case CLI_VALUE_LIST: {
|
||||
RAII_PyObject(l, PyList_New(v->listval.count));
|
||||
if (!l) return false;
|
||||
for (size_t i = 0; i < v->listval.count; i++) {
|
||||
PyObject *x = PyUnicode_FromString(v->listval.items[i]);
|
||||
if (!x) return false;
|
||||
PyList_SET_ITEM(l, i, x);
|
||||
}
|
||||
S(Py_NewRef(l));
|
||||
} break;
|
||||
}
|
||||
#undef S
|
||||
return true;
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
cli_parse_result_as_python(CLISpec *spec) {
|
||||
if (PyErr_Occurred()) return NULL;
|
||||
if (spec->errmsg) {
|
||||
PyErr_SetString(PyExc_ValueError, spec->errmsg);
|
||||
return NULL;
|
||||
}
|
||||
RAII_PyObject(ans, PyDict_New());
|
||||
if (!ans) return NULL;
|
||||
flag_map_for_loop(&spec->flag_map) {
|
||||
const FlagSpec *flag = &itr.data->val;
|
||||
cli_hash_itr i = vt_get(&spec->value_map, flag->dest);
|
||||
PyObject *is_seen = vt_is_end(i) ? Py_False : Py_True;
|
||||
const CLIValue *v = is_seen == Py_True ? &i.data->val : &flag->defval;
|
||||
if (!clival_as_python(v, is_seen, flag->dest, ans)) return NULL;
|
||||
}
|
||||
flag_map_for_loop(&spec->disabled_map) {
|
||||
const FlagSpec *flag = &itr.data->val;
|
||||
if (!clival_as_python(&flag->defval, Py_False, flag->dest, ans)) return NULL;
|
||||
}
|
||||
RAII_PyObject(leftover_args, PyList_New(spec->argc));
|
||||
if (!leftover_args) return NULL;
|
||||
for (int i = 0; i < spec->argc; i++) {
|
||||
PyObject *t = PyUnicode_FromString(spec->argv[i]);
|
||||
if (!t) return NULL;
|
||||
PyList_SET_ITEM(leftover_args, i, t);
|
||||
}
|
||||
return Py_BuildValue("OO", ans, leftover_args);
|
||||
}
|
||||
|
||||
#ifndef FOR_LAUNCHER
|
||||
static PyObject *
|
||||
parse_cli_from_python_spec(PyObject *self, PyObject *args) {
|
||||
(void)self;
|
||||
PyObject *pyargs, *names_map, *defval_map;
|
||||
if (!PyArg_ParseTuple(args, "O!O!O!", &PyList_Type, &pyargs, &PyDict_Type, &names_map, &PyDict_Type, &defval_map)) return NULL;
|
||||
int argc = PyList_GET_SIZE(pyargs);
|
||||
RAII_CLISpec(spec);
|
||||
char **argv = alloc_for_cli(&spec, sizeof(char *) * (argc + 2));
|
||||
if (!argv) return PyErr_NoMemory();
|
||||
argv[0] = "parse_cli_from_python_spec";
|
||||
for (int i = 0; i < argc; i++) {
|
||||
Py_ssize_t sz;
|
||||
const char *src = PyUnicode_AsUTF8AndSize(PyList_GET_ITEM(pyargs, i), &sz);
|
||||
argv[i + 1] = alloc_for_cli(&spec, sz);
|
||||
if (!argv[i + 1]) return PyErr_NoMemory();
|
||||
memcpy(argv[i + 1], src, sz);
|
||||
}
|
||||
argv[++argc] = 0;
|
||||
PyObject *key = NULL, *optdef = NULL;
|
||||
Py_ssize_t pos = 0;
|
||||
while (PyDict_Next(names_map, &pos, &key, &optdef)) {
|
||||
FlagSpec flag = {.dest = PyUnicode_AsUTF8(key)};
|
||||
RAII_PyObject(pytype, PyObject_GetAttrString(optdef, "type"));
|
||||
if (!pytype) return NULL;
|
||||
const char *type = PyUnicode_AsUTF8(pytype);
|
||||
PyObject *defval = PyDict_GetItemWithError(defval_map, key);
|
||||
if (!defval && PyErr_Occurred()) return NULL;
|
||||
RAII_PyObject(pyaliases, PyObject_GetAttrString(optdef, "aliases"));
|
||||
if (!pyaliases) return NULL;
|
||||
for (int a = 0; a < PyTuple_GET_SIZE(pyaliases); a++) {
|
||||
const char *alias = PyUnicode_AsUTF8(PyTuple_GET_ITEM(pyaliases, a));
|
||||
if (vt_is_end(vt_insert(&spec.alias_map, alias, flag.dest))) return PyErr_NoMemory();
|
||||
}
|
||||
if (strstr(type, "bool-") == type) {
|
||||
flag.defval.type = CLI_VALUE_BOOL;
|
||||
flag.defval.boolval = PyObject_IsTrue(defval);
|
||||
} else if (strcmp(type, "int") == 0) {
|
||||
flag.defval.type = CLI_VALUE_INT;
|
||||
flag.defval.intval = PyLong_AsLongLong(defval);
|
||||
} else if (strcmp(type, "float") == 0) {
|
||||
flag.defval.type = CLI_VALUE_FLOAT;
|
||||
flag.defval.floatval = PyFloat_AsDouble(defval);
|
||||
} else if (strcmp(type, "list") == 0) {
|
||||
flag.defval.type = CLI_VALUE_LIST;
|
||||
if (PyObject_IsTrue(defval)) {
|
||||
for (ssize_t l = 0; l < PyList_GET_SIZE(defval); l++) add_to_listval(&spec, &flag.defval, PyUnicode_AsUTF8(PyList_GET_ITEM(defval, l)));
|
||||
}
|
||||
} else if (strcmp(type, "choices") == 0) {
|
||||
flag.defval.type = CLI_VALUE_CHOICE;
|
||||
flag.defval.strval = PyUnicode_AsUTF8(defval);
|
||||
RAII_PyObject(pyc, PyObject_GetAttrString(optdef, "choices"));
|
||||
if (!pyc) return NULL;
|
||||
flag.defval.listval.items = alloc_for_cli(&spec, PyTuple_GET_SIZE(pyc) * sizeof(char *));
|
||||
if (!flag.defval.listval.items) return PyErr_NoMemory();
|
||||
flag.defval.listval.count = PyTuple_GET_SIZE(pyc);
|
||||
flag.defval.listval.capacity = PyTuple_GET_SIZE(pyc);
|
||||
for (size_t n = 0; n < flag.defval.listval.count; n++) {
|
||||
flag.defval.listval.items[n] = PyUnicode_AsUTF8(PyTuple_GET_ITEM(pyc, n));
|
||||
if (!flag.defval.listval.items[n]) return NULL;
|
||||
}
|
||||
} else {
|
||||
flag.defval.type = CLI_VALUE_STRING;
|
||||
flag.defval.strval = PyUnicode_Check(defval) ? PyUnicode_AsUTF8(defval) : NULL;
|
||||
}
|
||||
if (vt_is_end(vt_insert(&spec.flag_map, flag.dest, flag))) return PyErr_NoMemory();
|
||||
}
|
||||
if (PyErr_Occurred()) return NULL;
|
||||
parse_cli_loop(&spec, false, argc, argv);
|
||||
PyObject *ans = cli_parse_result_as_python(&spec);
|
||||
return ans;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* cmdline.c
|
||||
* Copyright (C) 2025 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
*
|
||||
* Distributed under terms of the GPL3 license.
|
||||
*/
|
||||
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include "shlex.h"
|
||||
#include "utils.h"
|
||||
#include "launcher.h"
|
||||
#ifdef __APPLE__
|
||||
#include <os/log.h>
|
||||
#endif
|
||||
|
||||
bool
|
||||
append_arg_to_argv_array(argv_array *a, const char *arg) {
|
||||
if (a->count + 2 > a->capacity) {
|
||||
size_t cap = a->capacity * 2;
|
||||
if (!cap) cap = 256;
|
||||
void *m = realloc(a->argv, cap * sizeof(a->argv[0]));
|
||||
if (!m) return false;
|
||||
a->argv = m;
|
||||
a->capacity = cap;
|
||||
a->needs_free = true;
|
||||
}
|
||||
// arg points into the process's original argv which persists for the lifetime
|
||||
// of the process and is never modified through this pointer.
|
||||
a->argv[a->count++] = (char *)arg;
|
||||
a->argv[a->count] = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
void
|
||||
free_argv_array(argv_array *a) {
|
||||
if (a && a->needs_free) {
|
||||
free(a->buf);
|
||||
free(a->argv);
|
||||
*a = (argv_array){0};
|
||||
}
|
||||
}
|
||||
|
||||
static bool
|
||||
add_to_argv(argv_array *a, const char *arg, size_t sz) {
|
||||
if (a->count + 2 > a->capacity) {
|
||||
size_t cap = a->capacity * 2;
|
||||
if (!cap) cap = 256;
|
||||
void *m = realloc(a->argv, cap * sizeof(a->argv[0]));
|
||||
if (!m) return false;
|
||||
a->argv = m;
|
||||
a->argv[a->count] = 0;
|
||||
a->capacity = cap;
|
||||
a->needs_free = true;
|
||||
}
|
||||
memcpy(a->buf + a->pos, arg, sz);
|
||||
a->argv[a->count++] = a->buf + a->pos;
|
||||
a->argv[a->count] = 0;
|
||||
a->pos += sz;
|
||||
a->buf[a->pos++] = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
get_argv_from(const char *filename, const char *argv0, argv_array *final_ans) {
|
||||
(void)get_config_dir;
|
||||
if (!filename || !filename[0]) return true;
|
||||
size_t src_sz;
|
||||
char *src = read_full_file(filename, &src_sz);
|
||||
if (!src) {
|
||||
if (errno == ENOENT || errno == ENOTDIR) return true;
|
||||
#ifdef __APPLE__
|
||||
int saved = errno;
|
||||
os_log_error(OS_LOG_DEFAULT, "Failed to read from %{public}s with error: %{darwin.errno}d", filename, errno);
|
||||
errno = saved;
|
||||
#endif
|
||||
fprintf(stderr, "Failed to read from %s ", filename);
|
||||
perror("with error");
|
||||
return true;
|
||||
}
|
||||
ShlexState s = {0};
|
||||
argv_array ans = {0};
|
||||
bool ok = false;
|
||||
ans.buf = malloc(src_sz + strlen(argv0) + 64);
|
||||
if (!ans.buf) goto oom;
|
||||
ans.needs_free = true;
|
||||
if (!add_to_argv(&ans, argv0, strlen(argv0))) goto oom;
|
||||
if (!alloc_shlex_state(&s, src, src_sz, false)) goto oom;
|
||||
bool keep_going = true;
|
||||
while (keep_going) {
|
||||
ssize_t q = next_word(&s);
|
||||
switch (q) {
|
||||
case -1: fprintf(stderr, "Failed to parse %s with error: %s\n", filename, s.err); goto end;
|
||||
case -2: keep_going = false; break;
|
||||
default:
|
||||
if (ans.count == 1 && strcmp(s.buf, "kitty") == 0) continue;
|
||||
if (!add_to_argv(&ans, s.buf, q)) goto oom;
|
||||
break;
|
||||
}
|
||||
}
|
||||
ok = true;
|
||||
oom:
|
||||
if (!ok) {
|
||||
errno = ENOMEM;
|
||||
fprintf(stderr, "Failed to read from %s ", filename);
|
||||
perror("with error");
|
||||
}
|
||||
end:
|
||||
free(src);
|
||||
dealloc_shlex_state(&s);
|
||||
if (ok) *final_ans = ans;
|
||||
else free_argv_array(final_ans);
|
||||
return ok;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* launcher.h
|
||||
* Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
*
|
||||
* Distributed under terms of the GPL3 license.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
|
||||
typedef struct CLIOptions {
|
||||
const char *session, *instance_group;
|
||||
bool wait_for_single_instance_window_close;
|
||||
int open_url_count;
|
||||
char **open_urls;
|
||||
} CLIOptions;
|
||||
|
||||
|
||||
typedef struct argv_array {
|
||||
char **argv, *buf;
|
||||
size_t capacity, count, pos;
|
||||
bool needs_free;
|
||||
} argv_array;
|
||||
|
||||
|
||||
void single_instance_main(int argc, char *argv[], const CLIOptions *opts);
|
||||
bool get_argv_from(const char *filename, const char *argv0, argv_array *ans);
|
||||
bool append_arg_to_argv_array(argv_array *a, const char *arg);
|
||||
void free_argv_array(argv_array *a);
|
||||
@@ -0,0 +1,651 @@
|
||||
/*
|
||||
* launcher.c
|
||||
* Copyright (C) 2017 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
*
|
||||
* Distributed under terms of the GPL3 license.
|
||||
*/
|
||||
|
||||
#define PY_SSIZE_T_CLEAN
|
||||
#include <Python.h>
|
||||
|
||||
#include <libgen.h>
|
||||
#ifdef __APPLE__
|
||||
#include <mach-o/dyld.h>
|
||||
#include <sys/syslimits.h>
|
||||
#include <sys/stat.h>
|
||||
#include <os/log.h>
|
||||
#else
|
||||
#include <limits.h>
|
||||
#endif
|
||||
#include "launcher.h"
|
||||
#include "utils.h"
|
||||
#define FOR_LAUNCHER
|
||||
#include "cli-parser-data_generated.h"
|
||||
|
||||
#ifndef KITTY_LIB_PATH
|
||||
#define KITTY_LIB_PATH "../.."
|
||||
#endif
|
||||
#ifndef KITTY_LIB_DIR_NAME
|
||||
#define KITTY_LIB_DIR_NAME "lib"
|
||||
#endif
|
||||
|
||||
static void
|
||||
cleanup_free(void *p) {
|
||||
free(*(void **)p);
|
||||
}
|
||||
#define RAII_ALLOC(type, name, initializer) __attribute__((cleanup(cleanup_free))) type *name = initializer
|
||||
|
||||
static bool being_tested = false;
|
||||
|
||||
#ifndef __FreeBSD__
|
||||
static bool
|
||||
safe_realpath(const char *src, char *buf, size_t buf_sz) {
|
||||
RAII_ALLOC(char, ans, realpath(src, NULL));
|
||||
if (ans == NULL) return false;
|
||||
safe_snprintf(buf, buf_sz, "%s", ans);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
typedef struct {
|
||||
const char *exe, *exe_dir, *lc_ctype, *lib_dir, *config_dir;
|
||||
CLISpec *cli_spec;
|
||||
bool launched_by_launch_services, is_quick_access_terminal;
|
||||
} RunData;
|
||||
|
||||
static bool
|
||||
set_kitty_run_data(RunData *run_data, bool from_source, wchar_t *extensions_dir) {
|
||||
PyObject *ans = PyDict_New();
|
||||
if (!ans) {
|
||||
PyErr_Print();
|
||||
return false;
|
||||
}
|
||||
PyObject *exe_dir = PyUnicode_DecodeFSDefaultAndSize(run_data->exe_dir, strlen(run_data->exe_dir));
|
||||
if (exe_dir == NULL) {
|
||||
fprintf(stderr, "Fatal error: cannot decode exe_dir: %s\n", run_data->exe_dir);
|
||||
PyErr_Print();
|
||||
Py_CLEAR(ans);
|
||||
return false;
|
||||
}
|
||||
#define S(key, val) \
|
||||
{ \
|
||||
if (!val) { \
|
||||
PyErr_Print(); \
|
||||
Py_CLEAR(ans); \
|
||||
return false; \
|
||||
} \
|
||||
int ret = PyDict_SetItemString(ans, #key, val); \
|
||||
Py_CLEAR(val); \
|
||||
if (ret != 0) { \
|
||||
PyErr_Print(); \
|
||||
Py_CLEAR(ans); \
|
||||
return false; \
|
||||
} \
|
||||
}
|
||||
S(bundle_exe_dir, exe_dir);
|
||||
if (from_source) {
|
||||
PyObject *one = Py_True;
|
||||
Py_INCREF(one);
|
||||
S(from_source, one);
|
||||
}
|
||||
if (run_data->lc_ctype) {
|
||||
PyObject *ctype = PyUnicode_DecodeLocaleAndSize(run_data->lc_ctype, strlen(run_data->lc_ctype), NULL);
|
||||
S(lc_ctype_before_python, ctype);
|
||||
}
|
||||
if (extensions_dir) {
|
||||
PyObject *ed = PyUnicode_FromWideChar(extensions_dir, -1);
|
||||
S(extensions_dir, ed);
|
||||
}
|
||||
PyObject *lbls = run_data->launched_by_launch_services ? Py_True : Py_False;
|
||||
Py_INCREF(lbls);
|
||||
S(launched_by_launch_services, lbls);
|
||||
lbls = run_data->is_quick_access_terminal ? Py_True : Py_False;
|
||||
Py_INCREF(lbls);
|
||||
S(is_quick_access_terminal_app, lbls);
|
||||
|
||||
char buf[PATH_MAX + 1];
|
||||
if (run_data->config_dir == NULL) {
|
||||
if (get_config_dir(buf, sizeof(buf))) run_data->config_dir = buf;
|
||||
}
|
||||
if (run_data->config_dir) {
|
||||
PyObject *cdir = PyUnicode_DecodeFSDefaultAndSize(run_data->config_dir, strlen(run_data->config_dir));
|
||||
if (!cdir) {
|
||||
PyErr_Print();
|
||||
return false;
|
||||
}
|
||||
S(config_dir, cdir);
|
||||
}
|
||||
PyObject *cli_flags = cli_parse_result_as_python(run_data->cli_spec);
|
||||
if (!cli_flags) {
|
||||
if (PyErr_Occurred()) PyErr_Print();
|
||||
return false;
|
||||
}
|
||||
S(cli_flags, cli_flags);
|
||||
|
||||
#undef S
|
||||
int ret = PySys_SetObject("kitty_run_data", ans);
|
||||
Py_CLEAR(ans);
|
||||
if (ret != 0) {
|
||||
PyErr_Print();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
#ifdef FOR_BUNDLE
|
||||
#include <bypy-freeze.h>
|
||||
|
||||
static void
|
||||
canonicalize_path_wide(const char *srcpath, wchar_t *dest, size_t sz) {
|
||||
char buf[sz + 1];
|
||||
lexical_absolute_path(srcpath, buf, sz);
|
||||
buf[sz] = 0;
|
||||
mbstowcs(dest, buf, sz - 1);
|
||||
dest[sz - 1] = 0;
|
||||
}
|
||||
|
||||
static int
|
||||
run_embedded(RunData *run_data) {
|
||||
bypy_pre_initialize_interpreter(false);
|
||||
char extensions_dir_full[PATH_MAX + 1] = {0}, python_home_full[PATH_MAX + 1] = {0};
|
||||
#ifdef __APPLE__
|
||||
const char *python_relpath = "../Resources/Python/lib";
|
||||
#else
|
||||
const char *python_relpath = "../" KITTY_LIB_DIR_NAME;
|
||||
#endif
|
||||
safe_snprintf(extensions_dir_full, PATH_MAX, "%s/%s/kitty-extensions", run_data->exe_dir, python_relpath);
|
||||
wchar_t extensions_dir[PATH_MAX];
|
||||
canonicalize_path_wide(extensions_dir_full, extensions_dir, PATH_MAX);
|
||||
safe_snprintf(python_home_full, PATH_MAX, "%s/%s/python%s", run_data->exe_dir, python_relpath, PYVER);
|
||||
wchar_t python_home[PATH_MAX];
|
||||
canonicalize_path_wide(python_home_full, python_home, PATH_MAX);
|
||||
bypy_initialize_interpreter(L"kitty", python_home, L"kitty_main", extensions_dir, run_data->cli_spec->original_argc, run_data->cli_spec->original_argv);
|
||||
if (!set_kitty_run_data(run_data, false, extensions_dir)) return 1;
|
||||
set_sys_bool("frozen", true);
|
||||
return bypy_run_interpreter();
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
static int
|
||||
run_embedded(RunData *run_data) {
|
||||
bool from_source = false;
|
||||
#ifdef FROM_SOURCE
|
||||
from_source = true;
|
||||
#endif
|
||||
PyStatus status;
|
||||
PyPreConfig preconfig;
|
||||
PyPreConfig_InitPythonConfig(&preconfig);
|
||||
preconfig.utf8_mode = 1;
|
||||
preconfig.coerce_c_locale = 1;
|
||||
#ifdef SET_PYTHON_HOME
|
||||
preconfig.isolated = 1;
|
||||
#endif
|
||||
status = Py_PreInitialize(&preconfig);
|
||||
if (PyStatus_Exception(status)) goto fail;
|
||||
PyConfig config;
|
||||
PyConfig_InitPythonConfig(&config);
|
||||
config.parse_argv = 0;
|
||||
config.optimization_level = 2;
|
||||
status = PyConfig_SetBytesArgv(&config, run_data->cli_spec->original_argc, run_data->cli_spec->original_argv);
|
||||
if (PyStatus_Exception(status)) goto fail;
|
||||
status = PyConfig_SetBytesString(&config, &config.executable, run_data->exe);
|
||||
if (PyStatus_Exception(status)) goto fail;
|
||||
status = PyConfig_SetBytesString(&config, &config.run_filename, run_data->lib_dir);
|
||||
if (PyStatus_Exception(status)) goto fail;
|
||||
#ifdef SET_PYTHON_HOME
|
||||
#ifndef __APPLE__
|
||||
char pyhome[256];
|
||||
safe_snprintf(pyhome, sizeof(pyhome), "%s/%s", run_data->lib_dir, SET_PYTHON_HOME);
|
||||
status = PyConfig_SetBytesString(&config, &config.home, pyhome);
|
||||
if (PyStatus_Exception(status)) goto fail;
|
||||
#endif
|
||||
config.isolated = 1;
|
||||
#endif
|
||||
status = Py_InitializeFromConfig(&config);
|
||||
if (PyStatus_Exception(status)) goto fail;
|
||||
PyConfig_Clear(&config);
|
||||
if (!set_kitty_run_data(run_data, from_source, NULL)) return 1;
|
||||
PySys_SetObject("frozen", Py_False);
|
||||
return Py_RunMain();
|
||||
fail:
|
||||
PyConfig_Clear(&config);
|
||||
if (PyStatus_IsExit(status)) return status.exitcode;
|
||||
single_instance_main(-1, NULL, NULL);
|
||||
Py_ExitStatusException(status);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
// read_exe_path() {{{
|
||||
#ifdef __APPLE__
|
||||
static bool
|
||||
read_exe_path(char *exe, size_t buf_sz) {
|
||||
(void)buf_sz;
|
||||
uint32_t size = PATH_MAX;
|
||||
char apple[PATH_MAX + 1] = {0};
|
||||
if (_NSGetExecutablePath(apple, &size) != 0) {
|
||||
fprintf(stderr, "Failed to get path to executable\n");
|
||||
return false;
|
||||
}
|
||||
if (!safe_realpath(apple, exe, buf_sz)) {
|
||||
fprintf(stderr, "realpath() failed on the executable's path\n");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#elif defined(__FreeBSD__)
|
||||
#include <sys/param.h>
|
||||
#include <sys/sysctl.h>
|
||||
|
||||
static bool
|
||||
read_exe_path(char *exe, size_t buf_sz) {
|
||||
int name[] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
|
||||
size_t length = buf_sz;
|
||||
int error = sysctl(name, 4, exe, &length, NULL, 0);
|
||||
if (error < 0 || length <= 1) {
|
||||
fprintf(stderr, "failed to get path to executable, sysctl() failed\n");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#elif defined(__NetBSD__)
|
||||
|
||||
static bool
|
||||
read_exe_path(char *exe, size_t buf_sz) {
|
||||
if (!safe_realpath("/proc/curproc/exe", exe, buf_sz)) {
|
||||
fprintf(stderr, "Failed to read /proc/curproc/exe\n");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#elif defined(__OpenBSD__)
|
||||
static bool
|
||||
read_exe_path(char *exe, size_t buf_sz) {
|
||||
const char *path = getenv("PATH");
|
||||
if (!path) {
|
||||
fprintf(stderr, "No PATH environment variable set, aborting\n");
|
||||
return false;
|
||||
}
|
||||
char buf[PATH_MAX + 1] = {0};
|
||||
strncpy(buf, path, PATH_MAX);
|
||||
char *token = strtok(buf, ":");
|
||||
while (token != NULL) {
|
||||
char q[PATH_MAX + 1] = {0};
|
||||
safe_snprintf(q, PATH_MAX, "%s/kitty", token);
|
||||
if (safe_realpath(q, exe, buf_sz)) return true;
|
||||
token = strtok(NULL, ":");
|
||||
}
|
||||
fprintf(stderr, "kitty not found in PATH aborting\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
static bool
|
||||
read_exe_path(char *exe, size_t buf_sz) {
|
||||
if (!safe_realpath("/proc/self/exe", exe, buf_sz)) {
|
||||
fprintf(stderr, "Failed to read /proc/self/exe\n");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#endif // }}}
|
||||
|
||||
static bool
|
||||
is_valid_fd(int fd) {
|
||||
// This is copied from the python source code as we need the exact same semantics
|
||||
// to prevent python from giving us None for sys.stdout and friends.
|
||||
#if defined(F_GETFD) && (defined(__linux__) || defined(__APPLE__) || defined(__wasm__))
|
||||
return fcntl(fd, F_GETFD) >= 0;
|
||||
#elif defined(__linux__)
|
||||
int fd2 = dup(fd);
|
||||
if (fd2 >= 0) { close(fd2); }
|
||||
return (fd2 >= 0);
|
||||
#else
|
||||
struct stat st;
|
||||
return (fstat(fd, &st) == 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
static bool
|
||||
reopen_to_null(const char *mode, FILE *stream) {
|
||||
errno = 0;
|
||||
while (true) {
|
||||
if (freopen("/dev/null", mode, stream) != NULL) return true;
|
||||
if (errno == EINTR) continue;
|
||||
perror("Failed to re-open STDIO handle to /dev/null");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static bool
|
||||
ensure_working_stdio(void) {
|
||||
#define C(which, mode) \
|
||||
{ \
|
||||
int fd = fileno(which); \
|
||||
if (fd < 0) { \
|
||||
if (!reopen_to_null(mode, which)) return false; \
|
||||
} else if (!is_valid_fd(fd)) { \
|
||||
close(fd); \
|
||||
if (!reopen_to_null(mode, which)) return false; \
|
||||
} \
|
||||
}
|
||||
C(stdin, "r") C(stdout, "w") C(stderr, "w") return true;
|
||||
#undef C
|
||||
}
|
||||
|
||||
static bool
|
||||
is_wrapped_kitten(const char *arg) {
|
||||
char buf[64];
|
||||
safe_snprintf(buf, sizeof(buf) - 1, " %s ", arg);
|
||||
return strstr(" " WRAPPED_KITTENS " ", buf);
|
||||
}
|
||||
|
||||
static void
|
||||
exec_kitten(int argc, char *argv[], char *exe_dir) {
|
||||
char exe[PATH_MAX + 1] = {0};
|
||||
safe_snprintf(exe, PATH_MAX, "%s/kitten", exe_dir);
|
||||
argv[0] = "kitten";
|
||||
if (being_tested) {
|
||||
printf("kitten_exe: %s\n", exe);
|
||||
output_argv("argv", argc, argv);
|
||||
exit(0);
|
||||
}
|
||||
errno = 0;
|
||||
execv(exe, argv);
|
||||
fprintf(stderr, "Failed to execute kitten (%s) with error: %s\n", exe, strerror(errno));
|
||||
exit(1);
|
||||
}
|
||||
|
||||
static bool
|
||||
parse_and_check_kitty_cli(CLISpec *cli_spec, int argc, char **argv) {
|
||||
parse_cli_for_kitty(cli_spec, argc, argv);
|
||||
if (cli_spec->errmsg) {
|
||||
fprintf(stderr, "%s\n", cli_spec->errmsg);
|
||||
#ifdef __APPLE__
|
||||
os_log_error(OS_LOG_DEFAULT, "%{public}s", cli_spec->errmsg);
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
parse_and_check_panel_kitten_cli(CLISpec *cli_spec, int argc, char **argv) {
|
||||
parse_cli_for_panel_kitten(cli_spec, argc, argv);
|
||||
if (cli_spec->errmsg) {
|
||||
fprintf(stderr, "%s\n", cli_spec->errmsg);
|
||||
#ifdef __APPLE__
|
||||
os_log_error(OS_LOG_DEFAULT, "%{public}s", cli_spec->errmsg);
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static int
|
||||
offset_for_plus_subcommand(int argc, char **argv, const char *name) {
|
||||
int offset = 0;
|
||||
#define arg_eq(num, what) (strcmp(argv[num], what) == 0)
|
||||
if (argc > 1 && argv[1][0] == '+' && strcmp(argv[1] + 1, name) == 0) {
|
||||
offset = 1;
|
||||
} else if (argc > 2 && arg_eq(1, "+") && arg_eq(2, name)) {
|
||||
offset = 2;
|
||||
}
|
||||
#undef arg_eq
|
||||
return offset;
|
||||
}
|
||||
|
||||
static void
|
||||
handle_fast_commandline(CLISpec *cli_spec, const char *instance_group_prefix) {
|
||||
CLIOptions opts = {0};
|
||||
RAII_CLISpec(subcommand_cli_spec);
|
||||
#define swap_cli_spec \
|
||||
subcommand_cli_spec.original_argc = cli_spec->original_argc; \
|
||||
subcommand_cli_spec.original_argv = cli_spec->original_argv; \
|
||||
cli_spec = &subcommand_cli_spec;
|
||||
if (instance_group_prefix == NULL) {
|
||||
// Look for +open
|
||||
int offset = offset_for_plus_subcommand(cli_spec->original_argc, cli_spec->original_argv, "open");
|
||||
if (offset) {
|
||||
if (!parse_and_check_kitty_cli(&subcommand_cli_spec, cli_spec->original_argc - offset, cli_spec->original_argv + offset)) exit(1);
|
||||
swap_cli_spec;
|
||||
opts.open_url_count = cli_spec->argc;
|
||||
opts.open_urls = cli_spec->argv;
|
||||
}
|
||||
} else {
|
||||
parse_and_check_panel_kitten_cli(&subcommand_cli_spec, cli_spec->original_argc, cli_spec->original_argv);
|
||||
swap_cli_spec;
|
||||
}
|
||||
if (get_bool_cli_val(cli_spec, "help")) return;
|
||||
if (get_bool_cli_val(cli_spec, "version")) {
|
||||
if (isatty(STDOUT_FILENO)) {
|
||||
printf("\x1b[3mkitty\x1b[23m \x1b[32m%s\x1b[39m created by \x1b[1;34mKovid Goyal\x1b[22;39m\n", KITTY_VERSION);
|
||||
} else {
|
||||
printf("kitty %s created by Kovid Goyal\n", KITTY_VERSION);
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
opts.session = get_string_cli_val(cli_spec, "session");
|
||||
#ifdef __APPLE__
|
||||
char pid_str[32];
|
||||
snprintf(pid_str, sizeof(pid_str), "%d", getpid());
|
||||
const char *ekfd = getenv("KITTY_EXEC_FOR_DETACH");
|
||||
bool is_exec_for_detach = ekfd && strcmp(getenv("KITTY_EXEC_FOR_DETACH"), pid_str) == 0;
|
||||
if (is_exec_for_detach) unsetenv("KITTY_EXEC_FOR_DETACH");
|
||||
#else
|
||||
bool is_exec_for_detach = false;
|
||||
#endif
|
||||
if (get_bool_cli_val(cli_spec, "detach") && !is_exec_for_detach) {
|
||||
const char *detached_log = get_string_cli_val(cli_spec, "detached_log");
|
||||
if (being_tested) {
|
||||
printf("detach: true\n");
|
||||
printf("detached_log: %s\n", detached_log ? detached_log : "");
|
||||
printf("session: %s\n", opts.session ? opts.session : "");
|
||||
exit(0);
|
||||
} else {
|
||||
int fds[2] = {0};
|
||||
if (pipe(fds) == -1) {
|
||||
perror("failed to create a pipe");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
#define reopen_or_fail(path, mode, which) \
|
||||
{ \
|
||||
errno = 0; \
|
||||
if (freopen(path, mode, which) == NULL) { \
|
||||
int s = errno; \
|
||||
fprintf(stderr, "Failed to redirect %s to %s with error: ", #which, path); \
|
||||
errno = s; \
|
||||
perror(NULL); \
|
||||
exit(1); \
|
||||
} \
|
||||
setlinebuf(which); \
|
||||
}
|
||||
if (!(opts.session && ((opts.session[0] == '-' && opts.session[1] == 0) || strcmp(opts.session, "/dev/stdin") == 0)))
|
||||
reopen_or_fail("/dev/null", "rb", stdin);
|
||||
if (!detached_log || !detached_log[0]) detached_log = "/dev/null";
|
||||
reopen_or_fail(detached_log, "ab", stdout);
|
||||
reopen_or_fail(detached_log, "ab", stderr);
|
||||
#undef reopen_or_fail
|
||||
if (fork() != 0) {
|
||||
// wait until child has done setsid() before exiting so that it doesnt get a SIGHUP,
|
||||
// see: https://github.com/kovidgoyal/kitty/issues/8680
|
||||
char buf[4];
|
||||
errno = 0;
|
||||
while (close(fds[1]) != 0 && errno == EINTR);
|
||||
errno = 0;
|
||||
while (read(fds[0], buf, sizeof(buf)) == -1 && errno == EINTR);
|
||||
exit(0);
|
||||
}
|
||||
errno = 0;
|
||||
while (close(fds[0]) != 0 && errno == EINTR);
|
||||
setsid();
|
||||
errno = 0;
|
||||
while (close(fds[1]) != 0 && errno == EINTR);
|
||||
#ifdef __APPLE__
|
||||
// fork() without exec() is unsafe on macOS. It used to work since
|
||||
// in this case we havent yet loaded any major Cocoa libraries but
|
||||
// in Tahoe 26.2 Apple broke that as well. So now just exec() on --detach
|
||||
snprintf(pid_str, sizeof(pid_str), "%d", getpid());
|
||||
setenv("KITTY_EXEC_FOR_DETACH", pid_str, 1);
|
||||
char exe_path[PATH_MAX] = {0};
|
||||
read_exe_path(exe_path, PATH_MAX);
|
||||
execv(exe_path, cli_spec->original_argv);
|
||||
fprintf(stderr, "Failed to execv() for --detach with exe_path: %s\n", exe_path);
|
||||
exit(1);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
unsetenv("KITTY_SI_DATA");
|
||||
if (get_bool_cli_val(cli_spec, "single_instance")) {
|
||||
char igbuf[256];
|
||||
opts.wait_for_single_instance_window_close = get_bool_cli_val(cli_spec, "wait_for_single_instance_window_close");
|
||||
opts.instance_group = get_string_cli_val(cli_spec, "instance_group");
|
||||
if (instance_group_prefix && instance_group_prefix[0]) {
|
||||
opts.instance_group = get_string_cli_val(cli_spec, "instance_group");
|
||||
if (opts.instance_group && opts.instance_group[0]) {
|
||||
safe_snprintf(igbuf, sizeof(igbuf), "%s-%s", instance_group_prefix, opts.instance_group ? opts.instance_group : "");
|
||||
opts.instance_group = igbuf;
|
||||
} else {
|
||||
opts.instance_group = instance_group_prefix;
|
||||
}
|
||||
}
|
||||
if (being_tested) {
|
||||
output_argv("argv", cli_spec->original_argc, cli_spec->original_argv);
|
||||
output_argv("open_urls", opts.open_url_count, opts.open_urls);
|
||||
output_values_for_testing(cli_spec);
|
||||
printf("single_instance: 1\n");
|
||||
printf("instance_group: %s\n", opts.instance_group ? opts.instance_group : "");
|
||||
printf("session: %s\n", opts.session ? opts.session : "");
|
||||
exit(0);
|
||||
} else {
|
||||
single_instance_main(cli_spec->original_argc, cli_spec->original_argv, &opts);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static bool
|
||||
delegate_to_kitten_if_possible(int argc, char **argv, char *exe_dir) {
|
||||
if (argc > 1 && argv[1][0] == '@') exec_kitten(argc, argv, exe_dir);
|
||||
int offset = offset_for_plus_subcommand(argc, argv, "kitten");
|
||||
if (offset && argc > offset + 1) {
|
||||
const char *kitten = argv[offset + 1];
|
||||
if (is_wrapped_kitten(kitten)) exec_kitten(argc - offset, argv + offset, exe_dir);
|
||||
if (strcmp(kitten, "panel") == 0) {
|
||||
offset++;
|
||||
CLISpec t = {.original_argv = argv + offset, .original_argc = argc - offset};
|
||||
handle_fast_commandline(&t, "panel");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool
|
||||
endswith(const char *str, const char *suffix) {
|
||||
size_t strLen = strlen(str);
|
||||
size_t suffixLen = strlen(suffix);
|
||||
if (suffixLen > strLen) return false;
|
||||
return strcmp(str + strLen - suffixLen, suffix) == 0;
|
||||
}
|
||||
|
||||
static void
|
||||
output_test_data(RunData *rd) {
|
||||
printf("launched_by_launch_services: %d\n", rd->launched_by_launch_services);
|
||||
printf("is_quick_access_terminal: %d\n", rd->is_quick_access_terminal);
|
||||
char buf[PATH_MAX + 1];
|
||||
if (rd->config_dir == NULL) {
|
||||
if (get_config_dir(buf, sizeof(buf))) rd->config_dir = buf;
|
||||
}
|
||||
printf("config_dir: %s\n", rd->config_dir ? rd->config_dir : "");
|
||||
output_for_testing(rd->cli_spec);
|
||||
}
|
||||
|
||||
int
|
||||
main(int argc_, char *argv_[], char *envp[]) {
|
||||
if (argc_ < 1 || !argv_) {
|
||||
fprintf(stderr, "Invalid argc/argv\n");
|
||||
return 1;
|
||||
}
|
||||
if (argc_ > 1 && strcmp(argv_[1], "+testing-launcher-code") == 0) {
|
||||
being_tested = true;
|
||||
memmove(argv_ + 1, argv_ + 2, (--argc_ - 1) * sizeof(argv_[0]));
|
||||
}
|
||||
if (!ensure_working_stdio()) return 1;
|
||||
char exe[PATH_MAX + 1] = {0};
|
||||
if (!read_exe_path(exe, sizeof(exe))) return 1;
|
||||
char exe_dir_buf[PATH_MAX + 1] = {0};
|
||||
strncpy(exe_dir_buf, exe, sizeof(exe_dir_buf));
|
||||
char *exe_dir = dirname(exe_dir_buf);
|
||||
|
||||
RAII_ALLOC(const char, lc_ctype, NULL);
|
||||
bool launched_by_launch_services = false;
|
||||
const char *config_dir = NULL;
|
||||
bool is_quick_access_terminal = false;
|
||||
argv_array argva = {.argv = argv_, .count = argc_};
|
||||
#ifdef __APPLE__
|
||||
lc_ctype = getenv("LC_CTYPE");
|
||||
if (lc_ctype) lc_ctype = strdup(lc_ctype);
|
||||
char abuf[PATH_MAX + 1];
|
||||
is_quick_access_terminal = endswith(exe, "/kitty-quick-access");
|
||||
if (getenv("KITTY_LAUNCHED_BY_LAUNCH_SERVICES")) {
|
||||
launched_by_launch_services = true;
|
||||
unsetenv("KITTY_LAUNCHED_BY_LAUNCH_SERVICES");
|
||||
if (!get_config_dir(abuf, sizeof(abuf))) abuf[0] = 0;
|
||||
config_dir = abuf;
|
||||
if (launched_by_launch_services && config_dir[0]) {
|
||||
char cbuf[PATH_MAX];
|
||||
safe_snprintf(cbuf, sizeof(cbuf), "%s/macos-launch-services-cmdline", config_dir);
|
||||
int orig_argc = argc_;
|
||||
char **orig_argv = argv_;
|
||||
if (!get_argv_from(cbuf, argva.argv[0], &argva)) exit(1);
|
||||
// If the file was loaded (argva replaced), append any extra args passed via open --args
|
||||
if (argva.needs_free) {
|
||||
for (int i = 1; i < orig_argc; i++) {
|
||||
// Skip Apple-internal process serial number args (-psn_*)
|
||||
if (strncmp(orig_argv[i], "-psn_", sizeof("-psn_") - 1) == 0) continue;
|
||||
if (!append_arg_to_argv_array(&argva, orig_argv[i])) {
|
||||
fprintf(stderr, "Out of memory while processing launch services args\n");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
(void)endswith;
|
||||
#endif
|
||||
(void)read_full_file;
|
||||
RAII_CLISpec(cli_spec);
|
||||
bool handle_fast_commandline_called = delegate_to_kitten_if_possible(argva.count, argva.argv, exe_dir);
|
||||
bool ok = parse_and_check_kitty_cli(&cli_spec, argva.count, argva.argv);
|
||||
if (!ok) return 1;
|
||||
if (!handle_fast_commandline_called) handle_fast_commandline(&cli_spec, NULL);
|
||||
int ret = 0;
|
||||
char lib[PATH_MAX + 1] = {0};
|
||||
if (KITTY_LIB_PATH[0] == '/') {
|
||||
safe_snprintf(lib, PATH_MAX, "%s", KITTY_LIB_PATH);
|
||||
} else {
|
||||
safe_snprintf(lib, PATH_MAX, "%s/%s", exe_dir, KITTY_LIB_PATH);
|
||||
}
|
||||
RunData run_data = {
|
||||
.exe = exe,
|
||||
.exe_dir = exe_dir,
|
||||
.lib_dir = lib,
|
||||
.cli_spec = &cli_spec,
|
||||
.lc_ctype = lc_ctype,
|
||||
.launched_by_launch_services = launched_by_launch_services,
|
||||
.config_dir = config_dir,
|
||||
.is_quick_access_terminal = is_quick_access_terminal,
|
||||
};
|
||||
if (being_tested) output_test_data(&run_data);
|
||||
else ret = run_embedded(&run_data);
|
||||
free_argv_array(&argva);
|
||||
single_instance_main(-1, NULL, NULL);
|
||||
if (!being_tested) Py_FinalizeEx();
|
||||
return ret;
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
/*
|
||||
* shlex.h
|
||||
* Copyright (C) 2025 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
*
|
||||
* Distributed under terms of the GPL3 license.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef enum { NORMAL, WORD, STRING_WITHOUT_ESCAPES, STRING_WITH_ESCAPES, ANSI_C_QUOTED } ShlexEnum;
|
||||
|
||||
typedef struct {
|
||||
const char *src;
|
||||
bool support_ansi_c_quoting, allow_empty;
|
||||
char *buf;
|
||||
size_t src_sz, src_pos, word_start, buf_pos;
|
||||
ShlexEnum state;
|
||||
const char *err;
|
||||
} ShlexState;
|
||||
|
||||
|
||||
static bool
|
||||
alloc_shlex_state(ShlexState *s, const char *src, size_t src_sz, bool support_ansi_c_quoting) {
|
||||
*s = (ShlexState){
|
||||
// for NULL termination and some safety we add 16 bytes
|
||||
.src = src,
|
||||
.src_sz = src_sz,
|
||||
.support_ansi_c_quoting = support_ansi_c_quoting,
|
||||
.buf = malloc(16 + src_sz)};
|
||||
return s->buf != NULL;
|
||||
}
|
||||
|
||||
static void
|
||||
dealloc_shlex_state(ShlexState *s) {
|
||||
free(s->buf);
|
||||
s->buf = NULL;
|
||||
*s = (ShlexState){0};
|
||||
}
|
||||
#define WHITESPACE \
|
||||
' ' : case '\n': \
|
||||
case '\t': \
|
||||
case '\r'
|
||||
#define STRING_WITH_ESCAPES_DELIM '"'
|
||||
#define STRING_WITHOUT_ESCAPES_DELIM '\''
|
||||
#define ESCAPE_CHAR '\\'
|
||||
|
||||
static void
|
||||
start_word(ShlexState *self) {
|
||||
self->word_start = self->src_pos - 1;
|
||||
self->buf_pos = 0;
|
||||
}
|
||||
|
||||
static void
|
||||
write_ch(ShlexState *self, char ch) {
|
||||
self->buf[self->buf_pos++] = ch;
|
||||
}
|
||||
|
||||
static unsigned
|
||||
encode_utf8(unsigned long ch, char *dest) {
|
||||
if (ch < 0x80) { // only lower 7 bits can be 1
|
||||
dest[0] = (char)ch; // 0xxxxxxx
|
||||
return 1;
|
||||
}
|
||||
if (ch < 0x800) { // only lower 11 bits can be 1
|
||||
dest[0] = (ch >> 6) | 0xC0; // 110xxxxx
|
||||
dest[1] = (ch & 0x3F) | 0x80; // 10xxxxxx
|
||||
return 2;
|
||||
}
|
||||
if (ch < 0x10000) { // only lower 16 bits can be 1
|
||||
dest[0] = (ch >> 12) | 0xE0; // 1110xxxx
|
||||
dest[1] = ((ch >> 6) & 0x3F) | 0x80; // 10xxxxxx
|
||||
dest[2] = (ch & 0x3F) | 0x80; // 10xxxxxx
|
||||
return 3;
|
||||
}
|
||||
if (ch < 0x110000) { // only lower 21 bits can be 1
|
||||
dest[0] = (ch >> 18) | 0xF0; // 11110xxx
|
||||
dest[1] = ((ch >> 12) & 0x3F) | 0x80; // 10xxxxxx
|
||||
dest[2] = ((ch >> 6) & 0x3F) | 0x80; // 10xxxxxx
|
||||
dest[3] = (ch & 0x3F) | 0x80; // 10xxxxxx
|
||||
return 4;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
write_unich(ShlexState *self, unsigned long ch) {
|
||||
self->buf_pos += encode_utf8(ch, self->buf + self->buf_pos);
|
||||
}
|
||||
|
||||
|
||||
static size_t
|
||||
get_word(ShlexState *self) {
|
||||
size_t ans = self->buf_pos;
|
||||
self->buf_pos = 0;
|
||||
self->buf[ans] = 0;
|
||||
self->allow_empty = false;
|
||||
return ans;
|
||||
}
|
||||
|
||||
static char
|
||||
read_ch(ShlexState *self) {
|
||||
return self->src[self->src_pos++];
|
||||
}
|
||||
|
||||
static bool
|
||||
write_escape_ch(ShlexState *self) {
|
||||
if (self->src_pos < self->src_sz) {
|
||||
char nch = read_ch(self);
|
||||
write_ch(self, nch);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool
|
||||
write_control_ch(ShlexState *self) {
|
||||
if (self->src_pos >= self->src_sz) {
|
||||
self->err = "Trailing \\c escape at end of input data";
|
||||
return false;
|
||||
}
|
||||
char ch = read_ch(self);
|
||||
write_ch(self, ch & 0x1f);
|
||||
return true;
|
||||
}
|
||||
|
||||
static void
|
||||
read_valid_digits(ShlexState *self, int max, char *output, bool (*is_valid)(char ch)) {
|
||||
for (int i = 0; i < max && self->src_pos < self->src_sz; i++, output++) {
|
||||
char ch = read_ch(self);
|
||||
if (!is_valid(ch)) {
|
||||
self->src_pos--;
|
||||
break;
|
||||
}
|
||||
*output = ch;
|
||||
}
|
||||
}
|
||||
|
||||
static bool
|
||||
is_octal_digit(char ch) {
|
||||
return '0' <= ch && ch <= '7';
|
||||
}
|
||||
|
||||
static bool
|
||||
is_hex_digit(char ch) {
|
||||
return ('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F');
|
||||
}
|
||||
|
||||
static void
|
||||
write_octal_ch(ShlexState *self, char ch) {
|
||||
char chars[4] = {ch, 0, 0, 0};
|
||||
read_valid_digits(self, 2, chars + 1, is_octal_digit);
|
||||
write_unich(self, strtol(chars, NULL, 8));
|
||||
}
|
||||
|
||||
static bool
|
||||
write_unicode_ch(ShlexState *self, int max) {
|
||||
char chars[16] = {0};
|
||||
read_valid_digits(self, max, chars, is_hex_digit);
|
||||
if (!chars[0]) {
|
||||
self->err = "Trailing unicode escape at end of input data";
|
||||
return false;
|
||||
}
|
||||
write_unich(self, strtol(chars, NULL, 16));
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
write_ansi_escape_ch(ShlexState *self) {
|
||||
if (self->src_pos >= self->src_sz) {
|
||||
self->err = "Trailing backslash at end of input data";
|
||||
return false;
|
||||
}
|
||||
char ch = read_ch(self);
|
||||
switch (ch) {
|
||||
case 'a': write_ch(self, '\a'); return true;
|
||||
case 'b': write_ch(self, '\b'); return true;
|
||||
case 'e':
|
||||
case 'E': write_ch(self, 0x1b); return true;
|
||||
case 'f': write_ch(self, '\f'); return true;
|
||||
case 'n': write_ch(self, '\n'); return true;
|
||||
case 'r': write_ch(self, '\r'); return true;
|
||||
case 't': write_ch(self, '\t'); return true;
|
||||
case 'v': write_ch(self, '\v'); return true;
|
||||
case '\\': write_ch(self, '\\'); return true;
|
||||
case '\'': write_ch(self, '\''); return true;
|
||||
case '\"': write_ch(self, '\"'); return true;
|
||||
case '\?': write_ch(self, '\?'); return true;
|
||||
|
||||
case 'c': return write_control_ch(self);
|
||||
case 'x': return write_unicode_ch(self, 2);
|
||||
case 'u': return write_unicode_ch(self, 4);
|
||||
case 'U': return write_unicode_ch(self, 8);
|
||||
case '0':
|
||||
case '1':
|
||||
case '2':
|
||||
case '3':
|
||||
case '4':
|
||||
case '5':
|
||||
case '6':
|
||||
case '7': write_octal_ch(self, ch); return true;
|
||||
default: write_ch(self, ch); return true;
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
set_state(ShlexState *self, ShlexEnum s) {
|
||||
self->state = s;
|
||||
}
|
||||
|
||||
static ssize_t
|
||||
next_word(ShlexState *self) {
|
||||
#define write_escaped_or_fail() \
|
||||
if (!write_escape_ch(self)) { \
|
||||
self->err = "Trailing backslash at end of input data"; \
|
||||
return -1; \
|
||||
}
|
||||
char prev_word_ch = 0;
|
||||
while (self->src_pos < self->src_sz) {
|
||||
char ch = read_ch(self);
|
||||
switch (self->state) {
|
||||
case NORMAL:
|
||||
switch (ch) {
|
||||
case WHITESPACE: break;
|
||||
case STRING_WITH_ESCAPES_DELIM:
|
||||
set_state(self, STRING_WITH_ESCAPES);
|
||||
start_word(self);
|
||||
break;
|
||||
case STRING_WITHOUT_ESCAPES_DELIM:
|
||||
set_state(self, STRING_WITHOUT_ESCAPES);
|
||||
start_word(self);
|
||||
break;
|
||||
case ESCAPE_CHAR:
|
||||
start_word(self);
|
||||
write_escaped_or_fail();
|
||||
set_state(self, WORD);
|
||||
break;
|
||||
default:
|
||||
set_state(self, WORD);
|
||||
start_word(self);
|
||||
write_ch(self, ch);
|
||||
prev_word_ch = ch;
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case WORD:
|
||||
switch (ch) {
|
||||
case WHITESPACE:
|
||||
prev_word_ch = 0;
|
||||
set_state(self, NORMAL);
|
||||
if (self->buf_pos || self->allow_empty) return get_word(self);
|
||||
break;
|
||||
case STRING_WITH_ESCAPES_DELIM:
|
||||
prev_word_ch = 0;
|
||||
set_state(self, STRING_WITH_ESCAPES);
|
||||
break;
|
||||
case STRING_WITHOUT_ESCAPES_DELIM:
|
||||
// prev_word_ch is only '$' if the immediately preceding
|
||||
// character written to buf was an unquoted, unescaped '$'
|
||||
if (self->support_ansi_c_quoting && prev_word_ch == '$' && self->buf_pos > 0) {
|
||||
self->buf_pos--;
|
||||
set_state(self, ANSI_C_QUOTED);
|
||||
} else set_state(self, STRING_WITHOUT_ESCAPES);
|
||||
prev_word_ch = 0;
|
||||
break;
|
||||
case ESCAPE_CHAR:
|
||||
prev_word_ch = 0;
|
||||
write_escaped_or_fail();
|
||||
break;
|
||||
default:
|
||||
write_ch(self, ch);
|
||||
prev_word_ch = ch;
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case STRING_WITHOUT_ESCAPES:
|
||||
switch (ch) {
|
||||
case STRING_WITHOUT_ESCAPES_DELIM:
|
||||
set_state(self, WORD);
|
||||
self->allow_empty = true;
|
||||
break;
|
||||
default: write_ch(self, ch); break;
|
||||
}
|
||||
break;
|
||||
case STRING_WITH_ESCAPES:
|
||||
switch (ch) {
|
||||
case STRING_WITH_ESCAPES_DELIM:
|
||||
set_state(self, WORD);
|
||||
self->allow_empty = true;
|
||||
break;
|
||||
case ESCAPE_CHAR: write_escaped_or_fail(); break;
|
||||
default: write_ch(self, ch); break;
|
||||
}
|
||||
break;
|
||||
case ANSI_C_QUOTED:
|
||||
switch (ch) {
|
||||
case STRING_WITHOUT_ESCAPES_DELIM:
|
||||
set_state(self, WORD);
|
||||
self->allow_empty = true;
|
||||
break;
|
||||
case ESCAPE_CHAR:
|
||||
if (!write_ansi_escape_ch(self)) return -1;
|
||||
break;
|
||||
default: write_ch(self, ch); break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
switch (self->state) {
|
||||
case WORD:
|
||||
self->state = NORMAL;
|
||||
if (self->buf_pos || self->allow_empty) return get_word(self);
|
||||
break;
|
||||
case STRING_WITH_ESCAPES:
|
||||
case STRING_WITHOUT_ESCAPES:
|
||||
case ANSI_C_QUOTED:
|
||||
self->err = "Unterminated string at the end of input";
|
||||
self->state = NORMAL;
|
||||
return -1;
|
||||
case NORMAL: break;
|
||||
}
|
||||
return -2;
|
||||
#undef write_escaped_or_fail
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
/*
|
||||
* single-instance.c
|
||||
* Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
*
|
||||
* Distributed under terms of the GPL3 license.
|
||||
*/
|
||||
|
||||
// We rely on data-types.h including Python.h which defines _DARWIN_C_SOURCE
|
||||
// which we need for _CS_DARWIN_USER_CACHE_DIR
|
||||
#include "../data-types.h"
|
||||
|
||||
#include "launcher.h"
|
||||
#include "../safe-wrappers.h"
|
||||
#include <stdbool.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include <pwd.h>
|
||||
#include <sys/types.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#define CHARSETS_STORAGE static inline
|
||||
#define NO_SINGLE_BYTE_CHARSETS
|
||||
#include "../charsets.c"
|
||||
|
||||
#define fail_on_errno(msg) \
|
||||
{ \
|
||||
perror(msg); \
|
||||
do_exit(1); \
|
||||
}
|
||||
|
||||
void
|
||||
log_error(const char *fmt, ...) {
|
||||
va_list ar;
|
||||
va_start(ar, fmt);
|
||||
vfprintf(stderr, fmt, ar);
|
||||
va_end(ar);
|
||||
}
|
||||
|
||||
typedef struct cleanup_data {
|
||||
int fd1, fd2;
|
||||
bool close_fd1, close_fd2;
|
||||
char path1[sizeof(struct sockaddr_un) + 16], path2[sizeof(struct sockaddr_un) + 16];
|
||||
} cleanup_data;
|
||||
|
||||
struct {
|
||||
cleanup_data si, notify;
|
||||
} cleanup_entries = {0};
|
||||
|
||||
static void
|
||||
do_cleanup(cleanup_data *d) {
|
||||
if (d->path1[0]) unlink(d->path1);
|
||||
if (d->path2[0]) unlink(d->path2);
|
||||
if (d->close_fd1) safe_close(d->fd1, __FILE__, __LINE__);
|
||||
if (d->close_fd2) safe_close(d->fd2, __FILE__, __LINE__);
|
||||
}
|
||||
|
||||
static void
|
||||
cleanup(void) {
|
||||
do_cleanup(&cleanup_entries.notify);
|
||||
do_cleanup(&cleanup_entries.si);
|
||||
}
|
||||
|
||||
static void
|
||||
do_exit(int code) {
|
||||
cleanup();
|
||||
exit(code);
|
||||
}
|
||||
|
||||
|
||||
#ifndef __APPLE__
|
||||
static bool
|
||||
is_ok_tmpdir(const char *x) {
|
||||
if (!x || !x[0]) return false;
|
||||
char path[2048];
|
||||
snprintf(path, sizeof(path), "%s/kitty-si-test-tmpdir-XXXXXXXXXXXX", x);
|
||||
int fd = safe_mkstemp(path);
|
||||
if (fd > -1) {
|
||||
safe_close(fd, __FILE__, __LINE__);
|
||||
unlink(path);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
static void
|
||||
get_socket_dir(char *output, size_t output_capacity) {
|
||||
#define ret_if_ok(x) \
|
||||
if (is_ok_tmpdir(x)) { \
|
||||
if (snprintf(output, output_capacity, "%s", x) < output_capacity - 1) \
|
||||
; \
|
||||
return; \
|
||||
}
|
||||
#ifdef __APPLE__
|
||||
if (confstr(_CS_DARWIN_USER_CACHE_DIR, output, output_capacity)) return;
|
||||
snprintf(output, output_capacity, "%s", "/Library/Caches");
|
||||
#else
|
||||
#define test_env(x) \
|
||||
{ \
|
||||
const char *e = getenv(#x); \
|
||||
ret_if_ok(e); \
|
||||
}
|
||||
test_env(XDG_RUNTIME_DIR);
|
||||
test_env(TMPDIR);
|
||||
test_env(TEMP);
|
||||
test_env(TMP);
|
||||
|
||||
ret_if_ok("/tmp");
|
||||
ret_if_ok("/var/tmp");
|
||||
ret_if_ok("/usr/tmp");
|
||||
|
||||
test_env(HOME);
|
||||
|
||||
const char *home = getpwuid(geteuid())->pw_dir;
|
||||
ret_if_ok(home);
|
||||
|
||||
if (getcwd(output, output_capacity)) return;
|
||||
snprintf(output, output_capacity, "%s", ".");
|
||||
#undef test_env
|
||||
#endif
|
||||
}
|
||||
|
||||
static void
|
||||
set_single_instance_socket(int fd) {
|
||||
if (listen(fd, 5) != 0) fail_on_errno("Failed to listen on single instance socket");
|
||||
char buf[256];
|
||||
snprintf(buf, sizeof(buf), "%d", fd);
|
||||
setenv("KITTY_SI_DATA", buf, 1);
|
||||
}
|
||||
|
||||
typedef struct membuf {
|
||||
char *data;
|
||||
size_t used, capacity;
|
||||
} membuf;
|
||||
|
||||
static void
|
||||
write_to_membuf(membuf *m, void *data, size_t sz) {
|
||||
ensure_space_for(m, data, char, m->used + sz, capacity, 8192, false);
|
||||
memcpy(m->data + m->used, data, sz);
|
||||
m->used += sz;
|
||||
}
|
||||
|
||||
static void
|
||||
write_escaped_char(membuf *m, char ch) {
|
||||
char buf[8];
|
||||
int n = snprintf(buf, sizeof(buf), "\\u%04x", ch);
|
||||
write_to_membuf(m, buf, n);
|
||||
}
|
||||
|
||||
static void
|
||||
write_json_string(membuf *m, const char *src, size_t src_len) {
|
||||
ensure_space_for(m, data, char, m->used + 2 + 8 * src_len, capacity, 8192, false);
|
||||
m->data[m->used++] = '"';
|
||||
uint32_t codep = 0;
|
||||
UTF8State state = 0, prev = UTF8_ACCEPT;
|
||||
for (size_t i = 0; i < src_len; i++) {
|
||||
switch (decode_utf8(&state, &codep, src[i])) {
|
||||
case UTF8_ACCEPT:
|
||||
switch (codep) {
|
||||
case '"': write_to_membuf(m, "\\\"", 2); break;
|
||||
case '\\': write_to_membuf(m, "\\\\", 2); break;
|
||||
case '\t': write_to_membuf(m, "\\t", 2); break;
|
||||
case '\n': write_to_membuf(m, "\\n", 2); break;
|
||||
case '\r':
|
||||
write_to_membuf(m, "\\r", 2);
|
||||
break;
|
||||
START_ALLOW_CASE_RANGE
|
||||
case 0 ... 8:
|
||||
case 11:
|
||||
case 12:
|
||||
case 14 ... 31:
|
||||
write_escaped_char(m, codep);
|
||||
break;
|
||||
END_ALLOW_CASE_RANGE
|
||||
default: m->used += encode_utf8(codep, m->data + m->used);
|
||||
}
|
||||
break;
|
||||
case UTF8_REJECT:
|
||||
state = UTF8_ACCEPT;
|
||||
if (prev != UTF8_ACCEPT && i > 0) i--;
|
||||
break;
|
||||
}
|
||||
prev = state;
|
||||
}
|
||||
m->data[m->used++] = '"';
|
||||
}
|
||||
|
||||
static void
|
||||
write_json_string_array(membuf *m, int argc, char *argv[]) {
|
||||
write_to_membuf(m, "[", 1);
|
||||
for (int i = 0; i < argc; i++) {
|
||||
if (i) write_to_membuf(m, ",", 1);
|
||||
write_json_string(m, argv[i], strlen(argv[i]));
|
||||
}
|
||||
write_to_membuf(m, "]", 1);
|
||||
}
|
||||
|
||||
static void
|
||||
read_till_eof(FILE *f, membuf *m) {
|
||||
while (!feof(f)) {
|
||||
ensure_space_for(m, data, char, m->used + 8192, capacity, 4 * 8192, false);
|
||||
m->used += fread(m->data, 1, m->capacity - m->used, f);
|
||||
if (ferror(f)) {
|
||||
fclose(f);
|
||||
fail_on_errno("Failed to read from session file");
|
||||
}
|
||||
}
|
||||
// ensure NULL termination
|
||||
write_to_membuf(m, "\0", 1);
|
||||
m->used--;
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
|
||||
static bool
|
||||
bind_unix_socket(int s, const char *basename, struct sockaddr_un *addr, cleanup_data *cleanup) {
|
||||
addr->sun_family = AF_UNIX;
|
||||
const size_t blen = strlen(basename);
|
||||
// First try abstract socket
|
||||
addr->sun_path[0] = 0;
|
||||
memcpy(addr->sun_path + 1, basename, blen + 1);
|
||||
if (safe_bind(s, (struct sockaddr *)addr, sizeof(sa_family_t) + 1 + blen) > -1) return true;
|
||||
if (errno != ENOENT) return false;
|
||||
// Try an actual filesystem file
|
||||
get_socket_dir(addr->sun_path, sizeof(addr->sun_path) - blen - 2);
|
||||
size_t dlen = strlen(addr->sun_path);
|
||||
while (dlen && addr->sun_path[dlen - 1] == '/') dlen--;
|
||||
if (snprintf(addr->sun_path + dlen, sizeof(addr->sun_path) - dlen, "/%s", basename) < blen + 1) {
|
||||
fprintf(stderr, "Socket directory has path too long for single instance socket file %s\n", addr->sun_path);
|
||||
do_exit(1);
|
||||
}
|
||||
// First lock the socket file using a separate lock file
|
||||
char lock_file_path[sizeof(addr->sun_path) + 16];
|
||||
snprintf(lock_file_path, sizeof(lock_file_path), "%s.lock", addr->sun_path);
|
||||
int fd = safe_open(lock_file_path, O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR);
|
||||
if (fd == -1) return false;
|
||||
cleanup->close_fd2 = true;
|
||||
cleanup->fd2 = fd;
|
||||
snprintf(cleanup->path2, sizeof(cleanup->path2), "%s", lock_file_path);
|
||||
if (safe_lockf(fd, F_TLOCK, 0) != 0) {
|
||||
int saved_errno = errno;
|
||||
safe_close(fd, __FILE__, __LINE__);
|
||||
cleanup->close_fd2 = false;
|
||||
errno = saved_errno;
|
||||
if (errno == EAGAIN || errno == EACCES) errno = EADDRINUSE; // client
|
||||
return false;
|
||||
}
|
||||
// First unlink the socket file and then try to bind it.
|
||||
if (unlink(addr->sun_path) != 0 && errno != ENOENT) return false;
|
||||
// Create the socket file accessible only to us, as a defense in depth
|
||||
// measure, the peer uid is checked at both ends of the connection as well.
|
||||
mode_t old_umask = umask(S_IRWXG | S_IRWXO);
|
||||
bool bound = safe_bind(s, (struct sockaddr *)addr, sizeof(*addr)) > -1;
|
||||
int saved_errno = errno;
|
||||
umask(old_umask);
|
||||
errno = saved_errno;
|
||||
if (bound) {
|
||||
snprintf(cleanup->path1, sizeof(cleanup->path1), "%s", addr->sun_path);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Verify that the process at the other end of the specified connected socket
|
||||
// is running as the same user as us. Needed because on Linux abstract UNIX
|
||||
// sockets are accessible to every process on the system.
|
||||
static bool
|
||||
peer_is_same_user(int fd) {
|
||||
uid_t peer_uid;
|
||||
gid_t peer_gid;
|
||||
if (!get_peer_credentials(fd, &peer_uid, &peer_gid)) {
|
||||
fprintf(stderr, "Failed to get the credentials of the process at the other end of the socket with error: %s\n", strerror(errno));
|
||||
return false;
|
||||
}
|
||||
if (peer_uid != geteuid()) {
|
||||
fprintf(stderr, "Refusing to talk to a process running as the user with uid: %d rather than our uid: %d\n", (int)peer_uid, (int)geteuid());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static int
|
||||
create_unix_socket(void) {
|
||||
int s = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (s < 0) fail_on_errno("Failed to create single instance socket object");
|
||||
int flags;
|
||||
if ((flags = fcntl(s, F_GETFD)) == -1) fail_on_errno("Failed to get fcntl flags for single instance socket");
|
||||
if (fcntl(s, F_SETFD, flags | FD_CLOEXEC) == -1) fail_on_errno("Failed to set single instance socket to CLOEXEC");
|
||||
return s;
|
||||
}
|
||||
|
||||
extern char **environ;
|
||||
|
||||
static void
|
||||
talk_to_instance(int s, struct sockaddr_un *server_addr, int argc, char *argv[], const CLIOptions *opts) {
|
||||
cleanup_entries.si.path2[0] = 0;
|
||||
cleanup_entries.si.path1[0] = 0;
|
||||
membuf session_data = {0};
|
||||
char *session_path = NULL;
|
||||
if (opts->session && opts->session[0]) {
|
||||
if (strcmp(opts->session, "none") == 0) {
|
||||
session_data.data = "none";
|
||||
session_data.used = 4;
|
||||
} else if (strcmp(opts->session, "-") == 0) {
|
||||
read_till_eof(stdin, &session_data);
|
||||
session_path = malloc(PATH_MAX + 8);
|
||||
if (!session_path) fail_on_errno("Failed to alloc space for session_path");
|
||||
if (getcwd(session_path, PATH_MAX + 1) == NULL) fail_on_errno("Failed to getcwd()");
|
||||
char *p = session_path + strlen(session_path);
|
||||
*(p++) = '/';
|
||||
*(p++) = '-';
|
||||
*p = 0;
|
||||
} else {
|
||||
FILE *f = safe_fopen(opts->session, "r");
|
||||
if (f == NULL) fail_on_errno("Failed to open session file for reading");
|
||||
read_till_eof(f, &session_data);
|
||||
session_path = realpath(opts->session, NULL);
|
||||
if (session_path == NULL) fail_on_errno("Failed to call realpath() on session file");
|
||||
}
|
||||
}
|
||||
membuf output = {0};
|
||||
#define w(literal) write_to_membuf(&output, literal, sizeof(literal) - 1)
|
||||
w("{\"cmd\":\"new_instance\",\"session_data\":");
|
||||
if (session_data.used) write_json_string(&output, session_data.data, session_data.used);
|
||||
else write_json_string(&output, "", 0);
|
||||
w(",\"session_arg\":");
|
||||
if (opts->session && opts->session[0]) write_json_string(&output, opts->session, strlen(opts->session));
|
||||
else write_json_string(&output, "", 0);
|
||||
w(",\"session_path\":");
|
||||
if (session_path && session_path[0]) write_json_string(&output, session_path, strlen(session_path));
|
||||
else write_json_string(&output, "", 0);
|
||||
free(session_path);
|
||||
w(",\"args\":");
|
||||
write_json_string_array(&output, argc, argv);
|
||||
char cwd[4096];
|
||||
if (!getcwd(cwd, sizeof(cwd))) fail_on_errno("Failed to get cwd");
|
||||
w(",\"cwd\":");
|
||||
write_json_string(&output, cwd, strlen(cwd));
|
||||
w(",\"environ\":{");
|
||||
char **e = environ;
|
||||
for (; *e; e++) {
|
||||
const char *eq = strchr(*e, '=');
|
||||
if (eq) {
|
||||
if (e != environ) write_to_membuf(&output, ",", 1);
|
||||
write_json_string(&output, *e, eq - *e);
|
||||
w(":");
|
||||
write_json_string(&output, eq + 1, strlen(eq + 1));
|
||||
}
|
||||
}
|
||||
w("}");
|
||||
|
||||
w(",\"cmdline_args_for_open\":");
|
||||
if (opts->open_url_count) write_json_string_array(&output, opts->open_url_count, opts->open_urls);
|
||||
else w("[]");
|
||||
|
||||
w(",\"notify_on_os_window_death\":");
|
||||
int notify_socket = -1;
|
||||
if (opts->wait_for_single_instance_window_close) {
|
||||
notify_socket = create_unix_socket();
|
||||
cleanup_entries.notify.fd1 = notify_socket;
|
||||
cleanup_entries.notify.close_fd1 = true;
|
||||
struct sockaddr_un server_addr;
|
||||
char addr[128];
|
||||
snprintf(addr, sizeof(addr), "kitty-os-window-close-notify-%d-%d", getpid(), geteuid());
|
||||
if (!bind_unix_socket(notify_socket, addr, &server_addr, &cleanup_entries.notify)) fail_on_errno("Failed to bind notification socket");
|
||||
size_t len = strlen(server_addr.sun_path);
|
||||
if (len == 0) len = 1 + strlen(server_addr.sun_path + 1);
|
||||
if (listen(notify_socket, 5) != 0) fail_on_errno("Failed to listen on notify socket");
|
||||
write_json_string(&output, server_addr.sun_path, len);
|
||||
} else w("null");
|
||||
|
||||
w("}");
|
||||
#undef w
|
||||
size_t addr_len = sizeof(sa_family_t);
|
||||
if (!server_addr->sun_path[0]) addr_len += 1 + strlen(server_addr->sun_path + 1);
|
||||
else addr_len = sizeof(*server_addr);
|
||||
if (safe_connect(s, (struct sockaddr *)server_addr, addr_len) != 0) { fail_on_errno("Failed to connect to single instance socket"); }
|
||||
// Check the identity of the listening process before sending it our
|
||||
// environment, cwd and session data.
|
||||
if (!peer_is_same_user(s)) do_exit(1);
|
||||
if (safe_write_all(s, output.data, output.used) != 0) fail_on_errno("Failed to write message to single instance socket");
|
||||
shutdown(s, SHUT_RDWR);
|
||||
safe_close(s, __FILE__, __LINE__);
|
||||
cleanup_entries.si.close_fd1 = false;
|
||||
if (notify_socket > -1) {
|
||||
while (true) {
|
||||
int fd = safe_accept(notify_socket, NULL, NULL);
|
||||
if (fd < 0) fail_on_errno("Failed to accept connection on notify socket");
|
||||
// Ignore connections from processes not running as us, they cannot
|
||||
// tell us anything about the death of our OS Window.
|
||||
if (!peer_is_same_user(fd)) {
|
||||
shutdown(fd, SHUT_RDWR);
|
||||
safe_close(fd, __FILE__, __LINE__);
|
||||
continue;
|
||||
}
|
||||
char rbuf;
|
||||
while (true) {
|
||||
ssize_t n = recv(fd, &rbuf, 1, 0);
|
||||
if (n < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) continue;
|
||||
break;
|
||||
}
|
||||
shutdown(fd, SHUT_RDWR);
|
||||
safe_close(fd, __FILE__, __LINE__);
|
||||
break;
|
||||
}
|
||||
shutdown(notify_socket, SHUT_RDWR);
|
||||
safe_close(notify_socket, __FILE__, __LINE__);
|
||||
cleanup_entries.notify.close_fd1 = false;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
single_instance_main(int argc, char *argv[], const CLIOptions *opts) {
|
||||
if (argc == -1) {
|
||||
cleanup();
|
||||
return;
|
||||
}
|
||||
struct sockaddr_un server_addr;
|
||||
char addr_buf[sizeof(server_addr.sun_path) - 1];
|
||||
if (opts->instance_group) snprintf(addr_buf, sizeof(addr_buf), "kitty-ipc-%d-%s", geteuid(), opts->instance_group);
|
||||
else snprintf(addr_buf, sizeof(addr_buf), "kitty-ipc-%d", geteuid());
|
||||
|
||||
int s = create_unix_socket();
|
||||
cleanup_entries.si.fd1 = s;
|
||||
cleanup_entries.si.close_fd1 = true;
|
||||
if (!bind_unix_socket(s, addr_buf, &server_addr, &cleanup_entries.si)) {
|
||||
if (errno == EADDRINUSE) {
|
||||
talk_to_instance(s, &server_addr, argc, argv, opts);
|
||||
do_exit(0);
|
||||
} else fail_on_errno("Failed to bind single instance socket");
|
||||
} else set_single_instance_socket(s);
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
/*
|
||||
* utils.h
|
||||
* Copyright (C) 2025 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
*
|
||||
* Distributed under terms of the GPL3 license.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
#include <pwd.h>
|
||||
#include <unistd.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <limits.h>
|
||||
#include <errno.h>
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
|
||||
|
||||
static const char *home = NULL;
|
||||
|
||||
static void
|
||||
ensure_home_path(void) {
|
||||
if (home) return;
|
||||
home = getenv("HOME");
|
||||
if (!home || !home[0]) {
|
||||
struct passwd *pw = getpwuid(geteuid());
|
||||
if (pw) home = pw->pw_dir;
|
||||
}
|
||||
if (!home || !home[0]) {
|
||||
fprintf(stderr, "Fatal error: Cannot determine home directory\n");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
#define safe_snprintf(buf, sz, fmt, ...) \
|
||||
{ \
|
||||
int n = snprintf(buf, sz, fmt, __VA_ARGS__); \
|
||||
if (n < 0 || (size_t)n >= sz) { \
|
||||
fprintf(stderr, "Out of buffer space calling sprintf for format: %s at line: %d\n", fmt, __LINE__); \
|
||||
exit(1); \
|
||||
} \
|
||||
}
|
||||
|
||||
static const char *
|
||||
home_path_for(const char *username) {
|
||||
struct passwd *pw = getpwnam(username);
|
||||
if (pw) return pw->pw_dir;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void
|
||||
expand_tilde(const char *path, char *ans, size_t ans_sz) {
|
||||
if (path[0] != '~') {
|
||||
safe_snprintf(ans, ans_sz, "%s", path);
|
||||
return;
|
||||
}
|
||||
const char *prefix = NULL, *sep = "";
|
||||
if (path[1] == '/' || path[1] == '\0') {
|
||||
// If the path is "~" or "~/something", get the current user's home directory
|
||||
ensure_home_path();
|
||||
prefix = home;
|
||||
} else {
|
||||
// If the path is "~user/something", get the specified user's home directory
|
||||
char *slash = (char *)strchr(path, '/'); // path is temporarily modified here and then restored
|
||||
if (slash) {
|
||||
*slash = 0;
|
||||
prefix = home_path_for(path + 1);
|
||||
*slash = '/';
|
||||
} else prefix = home_path_for(path + 1);
|
||||
if (prefix) path = slash ? slash - 1 : "a";
|
||||
else {
|
||||
prefix = "";
|
||||
path--;
|
||||
}
|
||||
}
|
||||
// Construct the expanded path
|
||||
safe_snprintf(ans, ans_sz, "%s%s%s", prefix, sep, path + 1);
|
||||
}
|
||||
|
||||
static size_t
|
||||
clean_path(char *path) {
|
||||
char *write_ptr = path;
|
||||
char *read_ptr = path;
|
||||
while (*read_ptr) {
|
||||
if (read_ptr[0] != '/') {
|
||||
*write_ptr++ = *read_ptr++;
|
||||
continue;
|
||||
}
|
||||
// we have /
|
||||
if (read_ptr[1] == '/') {
|
||||
read_ptr++;
|
||||
continue;
|
||||
} // skip one slash of double slash
|
||||
if (read_ptr[1] != '.') {
|
||||
*write_ptr++ = *read_ptr++;
|
||||
continue;
|
||||
}
|
||||
// we have /.
|
||||
if (read_ptr[2] == '/' || !read_ptr[2]) {
|
||||
read_ptr += 2;
|
||||
continue;
|
||||
} // skip /./
|
||||
if (read_ptr[2] != '.') {
|
||||
*write_ptr++ = *read_ptr++;
|
||||
continue;
|
||||
}
|
||||
// we have /..
|
||||
if (read_ptr[3] == '/' || !read_ptr[3]) {
|
||||
read_ptr += 3;
|
||||
while (write_ptr > path) {
|
||||
write_ptr--;
|
||||
if (*write_ptr == '/') break;
|
||||
}
|
||||
} else *write_ptr++ = *read_ptr++;
|
||||
}
|
||||
// remove trailing slashes
|
||||
while (write_ptr > path + 1 && *(write_ptr - 1) == '/') write_ptr--;
|
||||
// Null-terminate the normalized path
|
||||
*write_ptr++ = '\0';
|
||||
return write_ptr - path - 1;
|
||||
}
|
||||
|
||||
static size_t
|
||||
lexical_absolute_path(const char *relative, char *output, size_t outsz) {
|
||||
size_t rlen = strlen(relative);
|
||||
char *limit = output + outsz;
|
||||
char *write_ptr = output; // Points to the location to write normalized characters
|
||||
#define _ensure_space(n) \
|
||||
if (write_ptr + n + 1 >= limit) { \
|
||||
fprintf(stderr, "Out of buffer space making absolute path for: %s with cwd: %s\n", relative, output); \
|
||||
exit(1); \
|
||||
}
|
||||
if (relative[0] != '/') {
|
||||
if (!getcwd(output, outsz)) {
|
||||
perror("Getting the current working directory failed with error");
|
||||
exit(1);
|
||||
}
|
||||
size_t cwdlen = strlen(output);
|
||||
write_ptr = output + cwdlen;
|
||||
_ensure_space(cwdlen + rlen + 2);
|
||||
if (rlen && cwdlen && *(write_ptr - 1) != '/') *(write_ptr++) = '/';
|
||||
} else {
|
||||
_ensure_space(rlen + 2);
|
||||
}
|
||||
#undef _ensure_space
|
||||
// Append the relative path
|
||||
memcpy(write_ptr, relative, rlen);
|
||||
*(write_ptr + rlen) = 0;
|
||||
size_t ans = clean_path(output);
|
||||
// Ensure the path is not empty
|
||||
if (output[0] == '\0') {
|
||||
output[0] = '/';
|
||||
output[1] = 0;
|
||||
ans = 1;
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
|
||||
static bool
|
||||
makedirs_cleaned(char *path, int mode, struct stat *buffer) {
|
||||
if (stat(path, buffer) == 0) {
|
||||
if (S_ISDIR(buffer->st_mode)) return true;
|
||||
errno = ENOTDIR;
|
||||
return false;
|
||||
}
|
||||
if (errno == ENOTDIR) return false;
|
||||
char *p = strrchr(path, '/');
|
||||
if (p && p > path) {
|
||||
p[0] = 0;
|
||||
bool parent_created = makedirs_cleaned(path, mode, buffer);
|
||||
p[0] = '/';
|
||||
if (!parent_created) return false;
|
||||
}
|
||||
// Now parent exists
|
||||
return mkdir(path, mode) == 0;
|
||||
}
|
||||
|
||||
static bool
|
||||
makedirs(const char *path, int mode) {
|
||||
struct stat buffer;
|
||||
char pbuf[PATH_MAX];
|
||||
lexical_absolute_path(path, pbuf, sizeof(pbuf));
|
||||
return makedirs_cleaned(pbuf, mode, &buffer);
|
||||
}
|
||||
|
||||
static bool
|
||||
is_dir_ok_for_config(char *q) {
|
||||
size_t len = strlen(q);
|
||||
memcpy(q + len, "/kitty", sizeof("/kitty"));
|
||||
len += sizeof("/kitty") - 1;
|
||||
memcpy(q + len, "/kitty.conf", sizeof("/kitty.conf"));
|
||||
if (access(q, F_OK) != 0) return false;
|
||||
q[len] = 0;
|
||||
return access(q, W_OK) == 0;
|
||||
}
|
||||
|
||||
static bool
|
||||
get_config_dir(char *output, size_t outputsz) {
|
||||
const char *q;
|
||||
char buf1[PATH_MAX], buf2[PATH_MAX];
|
||||
#define expand(x, dest, sz) \
|
||||
{ \
|
||||
expand_tilde(x, buf1, sizeof(buf1)); \
|
||||
lexical_absolute_path(buf1, dest, sz); \
|
||||
}
|
||||
q = getenv("KITTY_CONFIG_DIRECTORY");
|
||||
if (q && q[0]) {
|
||||
expand(q, output, outputsz);
|
||||
return true;
|
||||
}
|
||||
#define check_and_ret(x) \
|
||||
if (x && x[0]) { \
|
||||
expand(x, output, outputsz); \
|
||||
if (is_dir_ok_for_config(output)) return true; \
|
||||
}
|
||||
q = getenv("XDG_CONFIG_HOME");
|
||||
check_and_ret(q);
|
||||
check_and_ret("~/.config");
|
||||
#ifdef __APPLE__
|
||||
check_and_ret("~/Library/Preferences");
|
||||
#endif
|
||||
q = getenv("XDG_CONFIG_DIRS");
|
||||
if (q && q[0]) {
|
||||
safe_snprintf(buf2, sizeof(buf2), "%s", q);
|
||||
char *s, *token = strtok_r(buf2, ":", &s);
|
||||
while (token) {
|
||||
check_and_ret(token);
|
||||
token = strtok_r(NULL, ":", &s);
|
||||
}
|
||||
}
|
||||
q = getenv("XDG_CONFIG_HOME");
|
||||
if (!q || !q[0]) q = "~/.config";
|
||||
expand(q, buf2, sizeof(buf2));
|
||||
safe_snprintf(output, outputsz, "%s/kitty", buf2);
|
||||
if (makedirs(output, 0755)) return true;
|
||||
return false;
|
||||
#undef expand
|
||||
#undef check_and_ret
|
||||
}
|
||||
|
||||
|
||||
static ssize_t
|
||||
safe_read_stream(void *ptr, size_t size, FILE *stream) {
|
||||
errno = 0;
|
||||
ssize_t total = 0, bytes_to_read = size;
|
||||
while (total < bytes_to_read) {
|
||||
size_t n = fread((char *)ptr + total, 1, bytes_to_read - total, stream);
|
||||
if (n > 0) total += n;
|
||||
else {
|
||||
if (!ferror(stream)) break; // eof
|
||||
if (errno != EINTR) return -1;
|
||||
clearerr(stream);
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
static char *
|
||||
read_full_file(const char *filename, size_t *sz) {
|
||||
FILE *file = NULL;
|
||||
errno = EINTR;
|
||||
while (file == NULL && errno == EINTR) file = fopen(filename, "rb");
|
||||
if (!file) return NULL;
|
||||
fseek(file, 0, SEEK_END);
|
||||
unsigned long file_size = ftell(file);
|
||||
rewind(file);
|
||||
char *buffer = (char *)malloc(file_size + 1); // +1 for the null terminator
|
||||
if (!buffer) {
|
||||
errno = EINTR;
|
||||
while (errno == EINTR && fclose(file) != 0);
|
||||
errno = ENOMEM;
|
||||
return NULL;
|
||||
}
|
||||
ssize_t q = safe_read_stream(buffer, file_size, file);
|
||||
int saved = errno;
|
||||
errno = EINTR;
|
||||
while (errno == EINTR && fclose(file) != 0);
|
||||
errno = saved;
|
||||
if (q < 0) {
|
||||
free(buffer);
|
||||
buffer = NULL;
|
||||
if (sz) *sz = 0;
|
||||
} else {
|
||||
if (sz) { *sz = q; }
|
||||
buffer[q] = 0;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
Reference in new issue
Block a user