fix: hostname truncation (#63)

Co-authored-by: javalsai <javalsai@proton.me>
This commit is contained in:
Ar1gin
2025-07-16 17:19:58 +05:00
committed by GitHub
parent 6c99675be7
commit 8fc6bff60f
3 changed files with 32 additions and 20 deletions

View File

@@ -19,6 +19,7 @@ bool read_press_nb(u_char* length, char* out, struct timeval* tv);
bool utf8_iscont(char byte);
size_t utf8len(const char* str);
size_t utf8len_until(const char* str, const char* until);
size_t utf8trunc(char* str, size_t n);
const char* utf8back(const char* str);
const char* utf8seek(const char* str);
const char* utf8seekn(const char* str, size_t n);

View File

@@ -3,6 +3,7 @@
#include <asm-generic/errno.h>
#include <errno.h>
#include <limits.h>
#include <pwd.h>
#include <signal.h>
#include <stdbool.h>
@@ -108,30 +109,22 @@ static char* fmt_time(const char* fmt) {
}
}
char* trunc_gethostname(const size_t MAXSIZE, const char* const ELLIPSIS) {
if (utf8len(ELLIPSIS) > MAXSIZE) return NULL;
size_t alloc_size = MAXSIZE + 1;
char* trunc_gethostname(const size_t MAXLEN, const char* const ELLIPSIS) {
if (utf8len(ELLIPSIS) > MAXLEN) return NULL;
size_t alloc_size = HOST_NAME_MAX + strlen(ELLIPSIS) + 1;
char* buf = malloc(alloc_size);
if (!buf) return NULL;
while (true) {
if (gethostname(buf, alloc_size) == 0) return buf;
if (errno == ENAMETOOLONG) {
buf[alloc_size] = '\0';
if (utf8len(buf) > MAXSIZE - utf8len(ELLIPSIS)) {
strcpy(&buf[MAXSIZE - utf8len(ELLIPSIS)], ELLIPSIS);
return buf;
}
alloc_size *= 2;
char* nbuf = realloc(buf, alloc_size);
if (!nbuf) goto fail;
buf = nbuf;
} else
goto fail;
if(gethostname(buf, alloc_size) != 0) {
free(buf);
return NULL;
}
fail:
free(buf);
return NULL;
if (utf8len(buf) > MAXLEN) {
int end = utf8trunc(buf, MAXLEN - utf8len(ELLIPSIS));
strcpy(&buf[end], ELLIPSIS);
}
return buf;
}
void ui_update_cursor_focus() {

View File

@@ -103,6 +103,24 @@ size_t utf8len_until(const char* str, const char* until) {
return len;
}
size_t utf8trunc(char* str, size_t n) {
size_t bytes = 0;
while (true) {
if(str[bytes] == '\0') break;
if (utf8_iscont(str[bytes])) {
bytes++;
continue;
}
if(n == 0) {
str[bytes] = '\0';
break;
}
bytes++;
n--;
}
return bytes;
}
const char* utf8back(const char* str) {
while (utf8_iscont(*(--str))) {
}