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