mirror of
https://github.com/javalsai/lidm.git
synced 2025-08-30 09:58:00 +02:00
fix: hostname truncation (#63)
Co-authored-by: javalsai <javalsai@proton.me>
This commit is contained in:
@@ -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);
|
||||
|
33
src/ui.c
33
src/ui.c
@@ -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() {
|
||||
|
18
src/util.c
18
src/util.c
@@ -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))) {
|
||||
}
|
||||
|
Reference in New Issue
Block a user