mastoapi.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. /* snac - A simple, minimalistic ActivityPub instance */
  2. /* copyright (c) 2022 - 2023 grunfink / MIT license */
  3. #include "xs.h"
  4. #include "xs_encdec.h"
  5. #include "xs_openssl.h"
  6. #include "xs_json.h"
  7. #include "xs_io.h"
  8. #include "xs_time.h"
  9. #include "snac.h"
  10. static xs_str *random_str(void)
  11. /* just what is says in the tin */
  12. {
  13. unsigned int data[4] = {0};
  14. FILE *f;
  15. if ((f = fopen("/dev/random", "r")) != NULL) {
  16. fread(data, sizeof(data), 1, f);
  17. fclose(f);
  18. }
  19. else {
  20. data[0] = random() % 0xffffffff;
  21. data[1] = random() % 0xffffffff;
  22. data[2] = random() % 0xffffffff;
  23. data[3] = random() % 0xffffffff;
  24. }
  25. return xs_hex_enc((char *)data, sizeof(data));
  26. }
  27. int app_add(const char *id, const xs_dict *app)
  28. /* stores an app */
  29. {
  30. int status = 201;
  31. xs *fn = xs_fmt("%s/app/", srv_basedir);
  32. FILE *f;
  33. mkdirx(fn);
  34. fn = xs_str_cat(fn, id);
  35. fn = xs_str_cat(fn, ".json");
  36. if ((f = fopen(fn, "w")) != NULL) {
  37. xs *j = xs_json_dumps_pp(app, 4);
  38. fwrite(j, strlen(j), 1, f);
  39. fclose(f);
  40. }
  41. else
  42. status = 500;
  43. return status;
  44. }
  45. xs_dict *app_get(const char *id)
  46. /* gets an app */
  47. {
  48. xs *fn = xs_fmt("%s/app/%s.json", srv_basedir, id);
  49. xs_dict *app = NULL;
  50. FILE *f;
  51. if ((f = fopen(fn, "r")) != NULL) {
  52. xs *j = xs_readall(f);
  53. fclose(f);
  54. app = xs_json_loads(j);
  55. }
  56. return app;
  57. }
  58. int token_add(const char *id, const xs_dict *token)
  59. /* stores a token */
  60. {
  61. int status = 201;
  62. xs *fn = xs_fmt("%s/token/", srv_basedir);
  63. FILE *f;
  64. mkdirx(fn);
  65. fn = xs_str_cat(fn, id);
  66. fn = xs_str_cat(fn, ".json");
  67. if ((f = fopen(fn, "w")) != NULL) {
  68. xs *j = xs_json_dumps_pp(token, 4);
  69. fwrite(j, strlen(j), 1, f);
  70. fclose(f);
  71. }
  72. else
  73. status = 500;
  74. return status;
  75. }
  76. xs_dict *token_get(const char *id)
  77. /* gets a token */
  78. {
  79. xs *fn = xs_fmt("%s/token/%s.json", srv_basedir, id);
  80. xs_dict *token = NULL;
  81. FILE *f;
  82. if ((f = fopen(fn, "r")) != NULL) {
  83. xs *j = xs_readall(f);
  84. fclose(f);
  85. token = xs_json_loads(j);
  86. }
  87. return token;
  88. }
  89. int token_del(const char *id)
  90. /* deletes a token */
  91. {
  92. xs *fn = xs_fmt("%s/token/%s.json", srv_basedir, id);
  93. return unlink(fn);
  94. }
  95. const char *login_page = ""
  96. "<!DOCTYPE html>\n"
  97. "<body><h1>%s OAuth identify</h1>\n"
  98. "<div style=\"background-color: red; color: white\">%s</div>\n"
  99. "<form method=\"post\" action=\"https:/" "/%s/oauth/x-snac-login\">\n"
  100. "<p>Login: <input type=\"text\" name=\"login\"></p>\n"
  101. "<p>Password: <input type=\"password\" name=\"passwd\"></p>\n"
  102. "<input type=\"hidden\" name=\"redir\" value=\"%s\">\n"
  103. "<input type=\"hidden\" name=\"cid\" value=\"%s\">\n"
  104. "<input type=\"submit\" value=\"OK\">\n"
  105. "</form><p>%s</p></body>\n"
  106. "";
  107. int oauth_get_handler(const xs_dict *req, const char *q_path,
  108. char **body, int *b_size, char **ctype)
  109. {
  110. if (!xs_startswith(q_path, "/oauth/"))
  111. return 0;
  112. {
  113. xs *j = xs_json_dumps_pp(req, 4);
  114. printf("oauth get:\n%s\n", j);
  115. }
  116. int status = 404;
  117. xs_dict *msg = xs_dict_get(req, "q_vars");
  118. xs *cmd = xs_replace(q_path, "/oauth", "");
  119. srv_debug(0, xs_fmt("oauth_get_handler %s", q_path));
  120. if (strcmp(cmd, "/authorize") == 0) {
  121. const char *cid = xs_dict_get(msg, "client_id");
  122. const char *ruri = xs_dict_get(msg, "redirect_uri");
  123. const char *rtype = xs_dict_get(msg, "response_type");
  124. status = 400;
  125. if (cid && ruri && rtype && strcmp(rtype, "code") == 0) {
  126. xs *app = app_get(cid);
  127. if (app != NULL) {
  128. const char *host = xs_dict_get(srv_config, "host");
  129. *body = xs_fmt(login_page, host, "", host, ruri, cid, USER_AGENT);
  130. *ctype = "text/html";
  131. status = 200;
  132. srv_debug(0, xs_fmt("oauth authorize: generating login page"));
  133. }
  134. else
  135. srv_debug(0, xs_fmt("oauth authorize: bad client_id %s", cid));
  136. }
  137. else
  138. srv_debug(0, xs_fmt("oauth authorize: invalid or unset arguments"));
  139. }
  140. return status;
  141. }
  142. int oauth_post_handler(const xs_dict *req, const char *q_path,
  143. const char *payload, int p_size,
  144. char **body, int *b_size, char **ctype)
  145. {
  146. if (!xs_startswith(q_path, "/oauth/"))
  147. return 0;
  148. {
  149. xs *j = xs_json_dumps_pp(req, 4);
  150. printf("oauth post:\n%s\n", j);
  151. }
  152. int status = 404;
  153. xs_dict *msg = xs_dict_get(req, "p_vars");
  154. xs *cmd = xs_replace(q_path, "/oauth", "");
  155. srv_debug(0, xs_fmt("oauth_post_handler %s", q_path));
  156. if (strcmp(cmd, "/x-snac-login") == 0) {
  157. const char *login = xs_dict_get(msg, "login");
  158. const char *passwd = xs_dict_get(msg, "passwd");
  159. const char *redir = xs_dict_get(msg, "redir");
  160. const char *cid = xs_dict_get(msg, "cid");
  161. const char *host = xs_dict_get(srv_config, "host");
  162. /* by default, generate another login form with an error */
  163. *body = xs_fmt(login_page, host, "LOGIN INCORRECT", host, redir, cid, USER_AGENT);
  164. *ctype = "text/html";
  165. status = 200;
  166. if (login && passwd && redir && cid) {
  167. snac snac;
  168. if (user_open(&snac, login)) {
  169. /* check the login + password */
  170. if (check_password(login, passwd,
  171. xs_dict_get(snac.config, "passwd"))) {
  172. /* success! redirect to the desired uri */
  173. xs *code = random_str();
  174. xs_free(*body);
  175. *body = xs_fmt("%s?code=%s", redir, code);
  176. status = 303;
  177. srv_debug(0, xs_fmt("oauth x-snac-login: success, redirect to %s", *body));
  178. /* assign the login to the app */
  179. xs *app = app_get(cid);
  180. if (app != NULL) {
  181. app = xs_dict_set(app, "uid", login);
  182. app = xs_dict_set(app, "code", code);
  183. app_add(cid, app);
  184. }
  185. else
  186. srv_log(xs_fmt("oauth x-snac-login: error getting app %s", cid));
  187. }
  188. else
  189. srv_debug(0, xs_fmt("oauth x-snac-login: login '%s' incorrect", login));
  190. user_free(&snac);
  191. }
  192. else
  193. srv_debug(0, xs_fmt("oauth x-snac-login: bad user '%s'", login));
  194. }
  195. else
  196. srv_debug(0, xs_fmt("oauth x-snac-login: invalid or unset arguments"));
  197. }
  198. else
  199. if (strcmp(cmd, "/token") == 0) {
  200. const char *gtype = xs_dict_get(msg, "grant_type");
  201. const char *code = xs_dict_get(msg, "code");
  202. const char *cid = xs_dict_get(msg, "client_id");
  203. const char *csec = xs_dict_get(msg, "client_secret");
  204. const char *ruri = xs_dict_get(msg, "redirect_uri");
  205. if (gtype && code && cid && csec && ruri) {
  206. xs *app = app_get(cid);
  207. if (app == NULL) {
  208. status = 401;
  209. srv_log(xs_fmt("oauth token: invalid app %s", cid));
  210. }
  211. else
  212. if (strcmp(csec, xs_dict_get(app, "client_secret")) != 0) {
  213. status = 401;
  214. srv_log(xs_fmt("oauth token: invalid client_secret for app %s", cid));
  215. }
  216. else {
  217. xs *rsp = xs_dict_new();
  218. xs *cat = xs_number_new(time(NULL));
  219. xs *tokid = random_str();
  220. rsp = xs_dict_append(rsp, "access_token", tokid);
  221. rsp = xs_dict_append(rsp, "token_type", "Bearer");
  222. rsp = xs_dict_append(rsp, "created_at", cat);
  223. *body = xs_json_dumps_pp(rsp, 4);
  224. *ctype = "application/json";
  225. status = 200;
  226. const char *uid = xs_dict_get(app, "uid");
  227. srv_debug(0, xs_fmt("oauth token: "
  228. "successful login for %s, new token %s", uid, tokid));
  229. xs *token = xs_dict_new();
  230. token = xs_dict_append(token, "token", tokid);
  231. token = xs_dict_append(token, "client_id", cid);
  232. token = xs_dict_append(token, "client_secret", csec);
  233. token = xs_dict_append(token, "uid", uid);
  234. token = xs_dict_append(token, "code", code);
  235. token_add(tokid, token);
  236. }
  237. }
  238. else {
  239. srv_debug(0, xs_fmt("oauth token: invalid or unset arguments"));
  240. status = 400;
  241. }
  242. }
  243. else
  244. if (strcmp(cmd, "/revoke") == 0) {
  245. const char *cid = xs_dict_get(msg, "client_id");
  246. const char *csec = xs_dict_get(msg, "client_secret");
  247. const char *tokid = xs_dict_get(msg, "token");
  248. if (cid && csec && tokid) {
  249. xs *token = token_get(tokid);
  250. *body = xs_str_new("{}");
  251. *ctype = "application/json";
  252. if (token == NULL || strcmp(csec, xs_dict_get(token, "client_secret")) != 0) {
  253. srv_debug(0, xs_fmt("oauth revoke: bad secret for token %s", tokid));
  254. status = 403;
  255. }
  256. else {
  257. token_del(tokid);
  258. srv_debug(0, xs_fmt("oauth revoke: revoked token %s", tokid));
  259. status = 200;
  260. }
  261. }
  262. else {
  263. srv_debug(0, xs_fmt("oauth revoke: invalid or unset arguments"));
  264. status = 403;
  265. }
  266. }
  267. return status;
  268. }
  269. int mastoapi_get_handler(const xs_dict *req, const char *q_path,
  270. char **body, int *b_size, char **ctype)
  271. {
  272. if (!xs_startswith(q_path, "/api/v1/"))
  273. return 0;
  274. srv_debug(0, xs_fmt("mastoapi_get_handler %s", q_path));
  275. {
  276. xs *j = xs_json_dumps_pp(req, 4);
  277. printf("mastoapi get:\n%s\n", j);
  278. }
  279. int status = 404;
  280. xs_dict *args = xs_dict_get(req, "q_vars");
  281. xs *cmd = xs_replace(q_path, "/api/v1", "");
  282. char *v;
  283. snac snac = {0};
  284. int logged_in = 0;
  285. /* if there is an authorization field, try to validate it */
  286. if (!xs_is_null(v = xs_dict_get(req, "authorization")) && xs_startswith(v, "Bearer ")) {
  287. xs *tokid = xs_replace(v, "Bearer ", "");
  288. xs *token = token_get(tokid);
  289. if (token != NULL) {
  290. const char *uid = xs_dict_get(token, "uid");
  291. if (!xs_is_null(uid) && user_open(&snac, uid)) {
  292. logged_in = 1;
  293. srv_debug(0, xs_fmt("mastoapi auth: valid token for user %s", uid));
  294. }
  295. else
  296. srv_log(xs_fmt("mastoapi auth: corrupted token %s", tokid));
  297. }
  298. else
  299. srv_log(xs_fmt("mastoapi auth: invalid token %s", tokid));
  300. }
  301. if (strcmp(cmd, "/accounts/verify_credentials") == 0) {
  302. if (logged_in) {
  303. xs *acct = xs_dict_new();
  304. acct = xs_dict_append(acct, "id", xs_dict_get(snac.config, "uid"));
  305. acct = xs_dict_append(acct, "username", xs_dict_get(snac.config, "uid"));
  306. acct = xs_dict_append(acct, "acct", xs_dict_get(snac.config, "uid"));
  307. acct = xs_dict_append(acct, "display_name", xs_dict_get(snac.config, "name"));
  308. acct = xs_dict_append(acct, "created_at", xs_dict_get(snac.config, "published"));
  309. acct = xs_dict_append(acct, "note", xs_dict_get(snac.config, "bio"));
  310. acct = xs_dict_append(acct, "url", snac.actor);
  311. xs *avatar = NULL;
  312. char *av = xs_dict_get(snac.config, "avatar");
  313. if (xs_is_null(av) || *av == '\0')
  314. avatar = xs_fmt("%s/susie.png", srv_baseurl);
  315. else
  316. avatar = xs_dup(av);
  317. acct = xs_dict_append(acct, "avatar", avatar);
  318. *body = xs_json_dumps_pp(acct, 4);
  319. *ctype = "application/json";
  320. status = 200;
  321. }
  322. else {
  323. status = 422; // "Unprocessable entity" (no login)
  324. }
  325. }
  326. else
  327. if (strcmp(cmd, "/timelines/home") == 0) {
  328. /* the private timeline */
  329. if (logged_in) {
  330. const char *max_id = xs_dict_get(args, "max_id");
  331. // const char *since_id = xs_dict_get(args, "since_id");
  332. // const char *min_id = xs_dict_get(args, "min_id");
  333. const char *limit_s = xs_dict_get(args, "limit");
  334. int limit = 20;
  335. int cnt = 0;
  336. if (!xs_is_null(limit_s))
  337. limit = atoi(limit_s);
  338. xs *timeline = timeline_list(&snac, "private", 0, XS_ALL);
  339. xs *out = xs_list_new();
  340. xs_list *p = timeline;
  341. xs_str *v;
  342. while (xs_list_iter(&p, &v) && cnt < limit) {
  343. xs *msg = NULL;
  344. /* only return entries older that max_id */
  345. if (max_id) {
  346. if (strcmp(v, max_id) == 0)
  347. max_id = NULL;
  348. continue;
  349. }
  350. /* get the entry */
  351. if (!valid_status(timeline_get_by_md5(&snac, v, &msg)))
  352. continue;
  353. /* discard not-Notes */
  354. if (strcmp(xs_dict_get(msg, "type"), "Note") != 0)
  355. continue;
  356. xs *actor = NULL;
  357. actor_get(&snac, xs_dict_get(msg, "attributedTo"), &actor);
  358. /* if the author is not here, discard */
  359. if (actor == NULL)
  360. continue;
  361. xs *acct = xs_dict_new();
  362. const char *display_name = xs_dict_get(actor, "name");
  363. if (xs_is_null(display_name) || *display_name == '\0')
  364. display_name = xs_dict_get(actor, "preferredUsername");
  365. const char *id = xs_dict_get(actor, "id");
  366. xs *acct_md5 = xs_md5_hex(id, strlen(id));
  367. acct = xs_dict_append(acct, "id", acct_md5);
  368. acct = xs_dict_append(acct, "username", xs_dict_get(actor, "preferredUsername"));
  369. acct = xs_dict_append(acct, "acct", xs_dict_get(actor, "preferredUsername"));
  370. acct = xs_dict_append(acct, "display_name", display_name);
  371. acct = xs_dict_append(acct, "created_at", xs_dict_get(actor, "published"));
  372. acct = xs_dict_append(acct, "note", xs_dict_get(actor, "summary"));
  373. acct = xs_dict_append(acct, "url", id);
  374. xs *avatar = NULL;
  375. xs_dict *av = xs_dict_get(actor, "icon");
  376. if (xs_type(av) == XSTYPE_DICT)
  377. avatar = xs_dup(xs_dict_get(av, "url"));
  378. else
  379. avatar = xs_fmt("%s/susie.png", srv_baseurl);
  380. acct = xs_dict_append(acct, "avatar", avatar);
  381. xs *f = xs_val_new(XSTYPE_FALSE);
  382. xs *t = xs_val_new(XSTYPE_TRUE);
  383. xs *n = xs_val_new(XSTYPE_NULL);
  384. xs *el = xs_list_new();
  385. xs *idx = NULL;
  386. xs *ixc = NULL;
  387. char *tmp;
  388. id = xs_dict_get(msg, "id");
  389. xs *st = xs_dict_new();
  390. st = xs_dict_append(st, "id", v);
  391. st = xs_dict_append(st, "uri", id);
  392. st = xs_dict_append(st, "created_at", xs_dict_get(msg, "published"));
  393. st = xs_dict_append(st, "account", acct);
  394. st = xs_dict_append(st, "content", xs_dict_get(msg, "content"));
  395. st = xs_dict_append(st, "visibility", "public");
  396. tmp = xs_dict_get(msg, "sensitive");
  397. if (xs_is_null(tmp))
  398. tmp = f;
  399. st = xs_dict_append(st, "sensitive", tmp);
  400. tmp = xs_dict_get(msg, "summary");
  401. if (xs_is_null(tmp))
  402. tmp = "";
  403. st = xs_dict_append(st, "spoiler_text", tmp);
  404. st = xs_dict_append(st, "media_attachments", el);
  405. st = xs_dict_append(st, "mentions", el);
  406. st = xs_dict_append(st, "tags", el);
  407. st = xs_dict_append(st, "emojis", el);
  408. xs_free(idx);
  409. xs_free(ixc);
  410. idx = object_likes(id);
  411. ixc = xs_number_new(xs_list_len(idx));
  412. st = xs_dict_append(st, "favourites_count", ixc);
  413. st = xs_dict_append(st, "favourited",
  414. xs_list_in(idx, snac.md5) != -1 ? t : f);
  415. xs_free(idx);
  416. xs_free(ixc);
  417. idx = object_announces(id);
  418. ixc = xs_number_new(xs_list_len(idx));
  419. st = xs_dict_append(st, "reblogs_count", ixc);
  420. st = xs_dict_append(st, "reblogged",
  421. xs_list_in(idx, snac.md5) != -1 ? t : f);
  422. xs_free(idx);
  423. xs_free(ixc);
  424. idx = object_children(id);
  425. ixc = xs_number_new(xs_list_len(idx));
  426. st = xs_dict_append(st, "replies_count", ixc);
  427. st = xs_dict_append(st, "url", id);
  428. st = xs_dict_append(st, "in_reply_to_id", n);
  429. st = xs_dict_append(st, "in_reply_to_account_id", n);
  430. st = xs_dict_append(st, "reblog", n);
  431. st = xs_dict_append(st, "poll", n);
  432. st = xs_dict_append(st, "card", n);
  433. st = xs_dict_append(st, "language", n);
  434. tmp = xs_dict_get(msg, "sourceContent");
  435. if (xs_is_null(tmp))
  436. tmp = "";
  437. st = xs_dict_append(st, "text", tmp);
  438. tmp = xs_dict_get(msg, "updated");
  439. if (xs_is_null(tmp))
  440. tmp = n;
  441. st = xs_dict_append(st, "edited_at", tmp);
  442. out = xs_list_append(out, st);
  443. cnt++;
  444. }
  445. *body = xs_json_dumps_pp(out, 4);
  446. *ctype = "application/json";
  447. status = 200;
  448. }
  449. else {
  450. status = 401; // unauthorized
  451. }
  452. }
  453. else
  454. if (strcmp(cmd, "/timelines/public") == 0) {
  455. /* the public timeline */
  456. }
  457. /* user cleanup */
  458. if (logged_in)
  459. user_free(&snac);
  460. return status;
  461. }
  462. int mastoapi_post_handler(const xs_dict *req, const char *q_path,
  463. const char *payload, int p_size,
  464. char **body, int *b_size, char **ctype)
  465. {
  466. if (!xs_startswith(q_path, "/api/v1/"))
  467. return 0;
  468. srv_debug(0, xs_fmt("mastoapi_post_handler %s", q_path));
  469. {
  470. xs *j = xs_json_dumps_pp(req, 4);
  471. printf("mastoapi post:\n%s\n", j);
  472. }
  473. int status = 404;
  474. xs *msg = NULL;
  475. char *i_ctype = xs_dict_get(req, "content-type");
  476. if (xs_startswith(i_ctype, "application/json"))
  477. msg = xs_json_loads(payload);
  478. else
  479. msg = xs_dup(xs_dict_get(req, "p_vars"));
  480. if (msg == NULL)
  481. return 400;
  482. {
  483. xs *j = xs_json_dumps_pp(msg, 4);
  484. printf("%s\n", j);
  485. }
  486. xs *cmd = xs_replace(q_path, "/api/v1", "");
  487. if (strcmp(cmd, "/apps") == 0) {
  488. const char *name = xs_dict_get(msg, "client_name");
  489. const char *ruri = xs_dict_get(msg, "redirect_uris");
  490. const char *scope = xs_dict_get(msg, "scope");
  491. if (xs_type(ruri) == XSTYPE_LIST)
  492. ruri = xs_dict_get(ruri, 0);
  493. if (name && ruri) {
  494. xs *app = xs_dict_new();
  495. xs *id = xs_replace_i(tid(0), ".", "");
  496. xs *cid = random_str();
  497. xs *csec = random_str();
  498. xs *vkey = random_str();
  499. app = xs_dict_append(app, "name", name);
  500. app = xs_dict_append(app, "redirect_uri", ruri);
  501. app = xs_dict_append(app, "client_id", cid);
  502. app = xs_dict_append(app, "client_secret", csec);
  503. app = xs_dict_append(app, "vapid_key", vkey);
  504. app = xs_dict_append(app, "id", id);
  505. *body = xs_json_dumps_pp(app, 4);
  506. *ctype = "application/json";
  507. status = 200;
  508. app = xs_dict_append(app, "code", "");
  509. if (scope)
  510. app = xs_dict_append(app, "scope", scope);
  511. app_add(cid, app);
  512. srv_debug(0, xs_fmt("mastoapi apps: new app %s", cid));
  513. }
  514. }
  515. return status;
  516. }