main snac.c
  1/* snac - A simple, minimalistic ActivityPub instance */
  2/* copyright (c) 2022 - 2026 grunfink et al. / MIT license */
  3
  4#ifndef XS_IMPLEMENTATION
  5#define XS_IMPLEMENTATION
  6#endif
  7
  8#include "xs.h"
  9#include "xs_hex.h"
 10#include "xs_io.h"
 11#include "xs_unicode_tbl.h"
 12#include "xs_unicode.h"
 13#include "xs_json.h"
 14#include "xs_curl.h"
 15#include "xs_bearssl.h"
 16#include "xs_socket.h"
 17#include "xs_unix_socket.h"
 18#include "xs_url.h"
 19#include "xs_http.h"
 20#include "xs_httpd.h"
 21#include "xs_mime.h"
 22#include "xs_regex.h"
 23#include "xs_set.h"
 24#include "xs_time.h"
 25#include "xs_glob.h"
 26#include "xs_random.h"
 27#include "xs_match.h"
 28#include "xs_fcgi.h"
 29#include "xs_html.h"
 30#include "xs_po.h"
 31#include "xs_webmention.h"
 32#include "xs_list_tools.h"
 33
 34#include "snac.h"
 35
 36#include <sys/time.h>
 37#include <sys/stat.h>
 38#include <sys/wait.h>
 39#include <limits.h>
 40#include <stdio.h>
 41#include <stdlib.h>
 42#include <unistd.h>
 43
 44xs_str *srv_basedir = NULL;
 45xs_dict *srv_config = NULL;
 46xs_str *srv_baseurl = NULL;
 47xs_str *srv_proxy_token_seed = NULL;
 48xs_dict *srv_langs = NULL;
 49const char *months[12] = {0};
 50
 51int dbglevel = 0;
 52
 53
 54int mkdirx(const char *pathname)
 55/* creates a directory with special permissions */
 56{
 57    int ret;
 58
 59    if ((ret = mkdir(pathname, DIR_PERM)) != -1) {
 60        /* try to the set the setgid bit, to allow system users
 61           to create files in these directories using the
 62           command-line tool. This may fail in some restricted
 63           environments, but it's of no use there anyway */
 64        chmod(pathname, DIR_PERM_ADD);
 65    }
 66
 67    return ret;
 68}
 69
 70
 71xs_str *tid(int offset)
 72/* returns a time-based Id */
 73{
 74    struct timeval tv;
 75
 76    gettimeofday(&tv, NULL);
 77
 78    return xs_fmt("%010ld.%06ld", (long)tv.tv_sec + (long)offset, (long)tv.tv_usec);
 79}
 80
 81
 82double ftime(void)
 83/* returns the UNIX time as a float */
 84{
 85    xs *ntid = tid(0);
 86
 87    return atof(ntid);
 88}
 89
 90
 91int validate_uid(const char *uid)
 92/* returns if uid is a valid identifier */
 93{
 94    if (!uid || *uid == '\0')
 95        return 0;
 96
 97    while (*uid) {
 98        if (!(isalnum((int)*uid) || *uid == '_'))
 99            return 0;
100
101        uid++;
102    }
103
104    return 1;
105}
106
107
108void srv_log(xs_str *str)
109/* logs a debug message */
110{
111    if (xs_str_in(str, srv_basedir) != -1) {
112        /* replace basedir with ~ */
113        str = xs_replace_i(str, srv_basedir, "~");
114    }
115
116    xs *tm = xs_str_localtime(0, "%H:%M:%S");
117    fprintf(stderr, "%s %s\n", tm, str);
118
119    /* if the ~/log/ folder exists, also write to a file there */
120    xs *dt = xs_str_localtime(0, "%Y-%m-%d");
121    xs *lf = xs_fmt("%s/log/%s.log", srv_basedir, dt);
122    FILE *f;
123    if ((f = fopen(lf, "a")) != NULL) {
124        fprintf(f, "%s %s\n", tm, str);
125        fclose(f);
126    }
127
128    xs_free(str);
129}
130
131
132void snac_log(const snac *snac, xs_str *str)
133/* prints a user debugging information */
134{
135    xs *o_str = str;
136    xs_str *msg = xs_fmt("[%s] %s", snac->uid, o_str);
137
138    if (xs_str_in(msg, snac->basedir) != -1) {
139        /* replace long basedir references with ~ */
140        msg = xs_replace_i(msg, snac->basedir, "~");
141    }
142
143    srv_log(msg);
144}
145
146
147xs_str *hash_password(const char *uid, const char *passwd, const char *nonce)
148/* hashes a password */
149{
150    xs *d_nonce = NULL;
151    xs *combi;
152    xs *hash;
153
154    if (nonce == NULL) {
155        unsigned int r;
156        xs_rnd_buf(&r, sizeof(r));
157        d_nonce = xs_fmt("%08x", r);
158        nonce = d_nonce;
159    }
160
161    combi = xs_fmt("%s:%s:%s", nonce, uid, passwd);
162    hash  = xs_sha1_hex(combi, strlen(combi));
163
164    return xs_fmt("%s:%s", nonce, hash);
165}
166
167
168int check_password(const char *uid, const char *passwd, const char *hash)
169/* checks a password */
170{
171    int ret = 0;
172    xs *spl = xs_split_n(hash, ":", 1);
173
174    if (xs_list_len(spl) == 2) {
175        xs *n_hash = hash_password(uid, passwd, xs_list_get(spl, 0));
176
177        ret = (strcmp(hash, n_hash) == 0);
178    }
179
180    return ret;
181}
182
183
184char* findprog(const char *prog)
185/* find a prog in PATH and return the first match */
186{
187    char *path_env, *path, *dir, *filename;
188    int len;
189    size_t filename_sz;
190    struct stat sbuf;
191
192    path_env = getenv("PATH");
193    if (!prog || !path_env)
194        return NULL;
195
196    path_env = strdup(path_env);
197    if (!path_env)
198        return NULL;
199    path = path_env;
200
201    filename_sz = strlen(path) + strlen(prog) + 2;
202    filename = xs_realloc(NULL, filename_sz);
203
204    while ((dir = strsep(&path, ":")) != NULL) {
205        /* empty entries as ./ instead of / */
206        if (*dir == '\0')
207            dir = ".";
208
209        /* strip trailing / */
210        len = strlen(dir);
211        while (len > 0 && dir[len-1] == '/')
212            dir[--len] = '\0';
213
214        len = snprintf(filename, filename_sz, "%s/%s", dir, prog);
215        if (len > 0 && len < (int) filename_sz &&
216            (stat(filename, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
217            access(filename, X_OK) == 0) {
218            free(path_env);
219            return filename;
220        }
221    }
222
223    free(path_env);
224    xs_free(filename);
225    return NULL;
226}
227
228
229int strip_media(const char *fn)
230/* strips EXIF data from a file */
231{
232    int ret = 0;
233
234    const xs_val *v = xs_dict_get(srv_config, "strip_exif");
235
236    if (xs_type(v) == XSTYPE_TRUE) {
237        /* Heuristic: find 'user/' in the path to make it relative */
238        /* This works for ~/user/..., /var/snac/user/..., etc. */
239        const char *r_fn = strstr(fn, "user/");
240
241        if (r_fn == NULL) {
242            /* Fallback: try to strip ~/ if present */
243            if (strncmp(fn, "~/", 2) == 0)
244                r_fn = fn + 2;
245            else
246                r_fn = fn;
247        }
248
249        xs *l_fn = xs_tolower_i(xs_dup(r_fn));
250
251        /* check image extensions */
252        if (xs_endswith(l_fn, ".jpg") || xs_endswith(l_fn, ".jpeg") ||
253            xs_endswith(l_fn, ".png") || xs_endswith(l_fn, ".webp") ||
254            xs_endswith(l_fn, ".heic") || xs_endswith(l_fn, ".heif") ||
255            xs_endswith(l_fn, ".avif") || xs_endswith(l_fn, ".tiff") ||
256            xs_endswith(l_fn, ".gif")  || xs_endswith(l_fn, ".bmp")) {
257
258            const char *mp = xs_dict_get(srv_config, "mogrify_path");
259
260            pid_t pid = fork();
261            if (pid == -1) {
262                srv_log(xs_fmt("strip_media: cannot fork()"));
263                return -1;
264            } else if (pid == 0) {
265                chdir(srv_basedir);
266                execl(mp, "-auto-orient", "-strip", r_fn, (char*) NULL);
267                _exit(1);
268            }
269
270            if (waitpid(pid, &ret, 0) == -1) {
271                srv_log(xs_fmt("strip_media: cannot waitpid()"));
272                return -1;
273            }
274
275            if (ret != 0)
276                srv_log(xs_fmt("strip_media: error stripping %s %d", r_fn, ret));
277            else
278                srv_debug(1, xs_fmt("strip_media: stripped %s", r_fn));
279        }
280        else
281        /* check video extensions */
282        if (xs_endswith(l_fn, ".mp4") || xs_endswith(l_fn, ".m4v") ||
283            xs_endswith(l_fn, ".mov") || xs_endswith(l_fn, ".webm") ||
284            xs_endswith(l_fn, ".mkv") || xs_endswith(l_fn, ".avi")) {
285
286            const char *fp = xs_dict_get(srv_config, "ffmpeg_path");
287
288            /* ffmpeg cannot modify in-place, so we need a temp file */
289            /* we must preserve valid extension for ffmpeg to guess the format */
290            const char *ext = strrchr(r_fn, '.');
291            if (ext == NULL) ext = "";
292            xs *tmp_fn = xs_fmt("%s.tmp%s", r_fn, ext);
293
294            pid_t pid = fork();
295            if (pid == -1) {
296                srv_log(xs_fmt("strip_media: cannot fork()"));
297                return -1;
298            } else if (pid == 0) {
299                chdir(srv_basedir);
300                /* -map_metadata -1 strips all global metadata */
301                /* -c copy copies input streams without re-encoding */
302                execl(fp, "-y", "-i", r_fn, "-map_metadata", "-1", "-c", "copy", tmp_fn, (char*) NULL);
303                _exit(1);
304            }
305
306            if (waitpid(pid, &ret, 0) == -1) {
307                srv_log(xs_fmt("strip_media: cannot waitpid()"));
308                return -1;
309            }
310
311            if (ret != 0) {
312                srv_log(xs_fmt("strip_media: error stripping %s %d", r_fn, ret));
313
314                /* try to cleanup, just in case */
315                /* unlink needs full path too if we are not in basedir */
316                xs *full_tmp_fn = xs_fmt("%s/%s", srv_basedir, tmp_fn);
317                unlink(full_tmp_fn);
318            }
319            else {
320                /* rename tmp file to original */
321                /* use full path for source because it was created relative to basedir */
322                xs *full_tmp_fn = xs_fmt("%s/%s", srv_basedir, tmp_fn);
323
324                if (rename(full_tmp_fn, fn) == 0)
325                    srv_debug(1, xs_fmt("strip_media: stripped %s", fn));
326                else
327                    srv_log(xs_fmt("strip_media: error renaming %s to %s", full_tmp_fn, fn));
328            }
329        }
330    }
331
332    return ret;
333}
334
335
336int check_strip_tool(void)
337/* check if strip_exif tools do exist and fix their absolute path */
338{
339    const xs_val *v = xs_dict_get(srv_config, "strip_exif");
340    /* skip if unless strip_exif; return non-error */
341    if (xs_type(v) != XSTYPE_TRUE)
342        return 1;
343
344    int ret = 1;
345    const char *progs[] = { "ffmpeg", "mogrify" };
346
347    for (int i = 0; i < (int)(sizeof(progs) / sizeof(progs[0])); i++) {
348        xs_str *key = xs_fmt("%s_path", progs[i]);
349
350        const char *val = xs_dict_get(srv_config, key);
351        if (val == NULL) {
352            val = findprog(progs[i]);
353            if (val != NULL)
354                srv_debug(1, xs_fmt("check_strip_tool: found %s in PATH at %s", progs[i], val));
355        }
356
357        if (val == NULL) {
358            srv_log(xs_fmt("check_strip_tool: %s not found in PATH", progs[i]));
359            ret = 0;
360        } else if (access(val, X_OK) != 0) {
361            srv_log(xs_fmt("check_strip_tool: %s '%s' is not executable", progs[i], val));
362            ret = 0;
363        } else {
364            srv_config = xs_dict_set(srv_config, key, val);
365        }
366
367        xs_free(key);
368    }
369
370    return ret;
371}