2.91 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[PATH_MAX];
186    int len;
187    struct stat sbuf;
188
189    path_env = getenv("PATH");
190    if (!prog || !path_env)
191        return NULL;
192
193    path_env = strdup(path_env);
194    if (!path_env)
195        return NULL;
196    path = path_env;
197
198    while ((dir = strsep(&path, ":")) != NULL) {
199        /* empty entries as ./ instead of / */
200        if (*dir == '\0')
201            dir = ".";
202
203        /* strip trailing / */
204        len = strlen(dir);
205        while (len > 0 && dir[len-1] == '/')
206            dir[--len] = '\0';
207
208        len = snprintf(filename, sizeof(filename), "%s/%s", dir, prog);
209        if (len > 0 && len < (int) sizeof(filename) &&
210            (stat(filename, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
211            access(filename, X_OK) == 0) {
212            free(path_env);
213            return strdup(filename);
214        }
215    }
216
217    free(path_env);
218    return NULL;
219}
220
221
222int strip_media(const char *fn)
223/* strips EXIF data from a file */
224{
225    int ret = 0;
226
227    const xs_val *v = xs_dict_get(srv_config, "strip_exif");
228
229    if (xs_type(v) == XSTYPE_TRUE) {
230        /* Heuristic: find 'user/' in the path to make it relative */
231        /* This works for ~/user/..., /var/snac/user/..., etc. */
232        const char *r_fn = strstr(fn, "user/");
233        
234        if (r_fn == NULL) {
235            /* Fallback: try to strip ~/ if present */
236            if (strncmp(fn, "~/", 2) == 0)
237                r_fn = fn + 2;
238            else
239                r_fn = fn;
240        }
241
242        xs *l_fn = xs_tolower_i(xs_dup(r_fn));
243
244        /* check image extensions */
245        if (xs_endswith(l_fn, ".jpg") || xs_endswith(l_fn, ".jpeg") ||
246            xs_endswith(l_fn, ".png") || xs_endswith(l_fn, ".webp") ||
247            xs_endswith(l_fn, ".heic") || xs_endswith(l_fn, ".heif") ||
248            xs_endswith(l_fn, ".avif") || xs_endswith(l_fn, ".tiff") ||
249            xs_endswith(l_fn, ".gif")  || xs_endswith(l_fn, ".bmp")) {
250
251            const char *mp = xs_dict_get(srv_config, "mogrify_path");
252
253            pid_t pid = fork();
254            if (pid == -1) {
255                srv_log(xs_fmt("strip_media: cannot fork()"));
256                return -1;
257            } else if (pid == 0) {
258                chdir(srv_basedir);
259                execl(mp, "-auto-orient", "-strip", r_fn, (char*) NULL);
260                _exit(1);
261            }
262
263            if (waitpid(pid, &ret, 0) == -1) {
264                srv_log(xs_fmt("strip_media: cannot waitpid()"));
265                return -1;
266            }
267
268            if (ret != 0)
269                srv_log(xs_fmt("strip_media: error stripping %s %d", r_fn, ret));
270            else
271                srv_debug(1, xs_fmt("strip_media: stripped %s", r_fn));
272        }
273        else
274        /* check video extensions */
275        if (xs_endswith(l_fn, ".mp4") || xs_endswith(l_fn, ".m4v") ||
276            xs_endswith(l_fn, ".mov") || xs_endswith(l_fn, ".webm") ||
277            xs_endswith(l_fn, ".mkv") || xs_endswith(l_fn, ".avi")) {
278
279            const char *fp = xs_dict_get(srv_config, "ffmpeg_path");
280
281            /* ffmpeg cannot modify in-place, so we need a temp file */
282            /* we must preserve valid extension for ffmpeg to guess the format */
283            const char *ext = strrchr(r_fn, '.');
284            if (ext == NULL) ext = "";
285            xs *tmp_fn = xs_fmt("%s.tmp%s", r_fn, ext);
286
287            pid_t pid = fork();
288            if (pid == -1) {
289                srv_log(xs_fmt("strip_media: cannot fork()"));
290                return -1;
291            } else if (pid == 0) {
292                chdir(srv_basedir);
293                /* -map_metadata -1 strips all global metadata */
294                /* -c copy copies input streams without re-encoding */
295                execl(fp, "-y", "-i", r_fn, "-map_metadata", "-1", "-c", "copy", tmp_fn, (char*) NULL);
296                _exit(1);
297            }
298
299            if (waitpid(pid, &ret, 0) == -1) {
300                srv_log(xs_fmt("strip_media: cannot waitpid()"));
301                return -1;
302            }
303
304            if (ret != 0) {
305                srv_log(xs_fmt("strip_media: error stripping %s %d", r_fn, ret));
306
307                /* try to cleanup, just in case */
308                /* unlink needs full path too if we are not in basedir */
309                xs *full_tmp_fn = xs_fmt("%s/%s", srv_basedir, tmp_fn);
310                unlink(full_tmp_fn);
311            }
312            else {
313                /* rename tmp file to original */
314                /* use full path for source because it was created relative to basedir */
315                xs *full_tmp_fn = xs_fmt("%s/%s", srv_basedir, tmp_fn);
316                
317                if (rename(full_tmp_fn, fn) == 0)
318                    srv_debug(1, xs_fmt("strip_media: stripped %s", fn));
319                else
320                    srv_log(xs_fmt("strip_media: error renaming %s to %s", full_tmp_fn, fn));
321            }
322        }
323    }
324
325    return ret;
326}
327
328
329int check_strip_tool(void)
330/* check if strip_exif tools do exist and fix their absolute path */
331{
332    const xs_val *v = xs_dict_get(srv_config, "strip_exif");
333    /* skip if unless strip_exif; return non-error */
334    if (xs_type(v) != XSTYPE_TRUE)
335        return 1;
336
337    int ret = 1;
338    const char *progs[] = { "ffmpeg", "mogrify" };
339
340    for (int i = 0; i < (int)(sizeof(progs) / sizeof(progs[0])); i++) {
341        xs_str *key = xs_fmt("%s_path", progs[i]);
342
343        const char *val = xs_dict_get(srv_config, key);
344        if (val == NULL) {
345            val = findprog(progs[i]);
346            if (val != NULL)
347                srv_debug(1, xs_fmt("check_strip_tool: found %s in PATH at %s", progs[i], val));
348        }
349
350        if (val == NULL) {
351            srv_log(xs_fmt("check_strip_tool: %s not found in PATH", progs[i]));
352            ret = 0;
353        } else if (access(val, X_OK) != 0) {
354            srv_log(xs_fmt("check_strip_tool: %s '%s' is not executable", progs[i], val));
355            ret = 0;
356        } else {
357            srv_config = xs_dict_set(srv_config, key, val);
358        }
359
360        xs_free(key);
361    }
362
363    return ret;
364}