mastoapi.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  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. if (!xs_is_hex(id))
  31. return 500;
  32. int status = 201;
  33. xs *fn = xs_fmt("%s/app/", srv_basedir);
  34. FILE *f;
  35. mkdirx(fn);
  36. fn = xs_str_cat(fn, id);
  37. fn = xs_str_cat(fn, ".json");
  38. if ((f = fopen(fn, "w")) != NULL) {
  39. xs *j = xs_json_dumps_pp(app, 4);
  40. fwrite(j, strlen(j), 1, f);
  41. fclose(f);
  42. }
  43. else
  44. status = 500;
  45. return status;
  46. }
  47. xs_dict *app_get(const char *id)
  48. /* gets an app */
  49. {
  50. if (!xs_is_hex(id))
  51. return NULL;
  52. xs *fn = xs_fmt("%s/app/%s.json", srv_basedir, id);
  53. xs_dict *app = NULL;
  54. FILE *f;
  55. if ((f = fopen(fn, "r")) != NULL) {
  56. xs *j = xs_readall(f);
  57. fclose(f);
  58. app = xs_json_loads(j);
  59. }
  60. return app;
  61. }
  62. int app_del(const char *id)
  63. /* deletes an app */
  64. {
  65. if (!xs_is_hex(id))
  66. return -1;
  67. xs *fn = xs_fmt("%s/app/%s.json", srv_basedir, id);
  68. return unlink(fn);
  69. }
  70. int token_add(const char *id, const xs_dict *token)
  71. /* stores a token */
  72. {
  73. if (!xs_is_hex(id))
  74. return 500;
  75. int status = 201;
  76. xs *fn = xs_fmt("%s/token/", srv_basedir);
  77. FILE *f;
  78. mkdirx(fn);
  79. fn = xs_str_cat(fn, id);
  80. fn = xs_str_cat(fn, ".json");
  81. if ((f = fopen(fn, "w")) != NULL) {
  82. xs *j = xs_json_dumps_pp(token, 4);
  83. fwrite(j, strlen(j), 1, f);
  84. fclose(f);
  85. }
  86. else
  87. status = 500;
  88. return status;
  89. }
  90. xs_dict *token_get(const char *id)
  91. /* gets a token */
  92. {
  93. if (!xs_is_hex(id))
  94. return NULL;
  95. xs *fn = xs_fmt("%s/token/%s.json", srv_basedir, id);
  96. xs_dict *token = NULL;
  97. FILE *f;
  98. if ((f = fopen(fn, "r")) != NULL) {
  99. xs *j = xs_readall(f);
  100. fclose(f);
  101. token = xs_json_loads(j);
  102. }
  103. return token;
  104. }
  105. int token_del(const char *id)
  106. /* deletes a token */
  107. {
  108. if (!xs_is_hex(id))
  109. return -1;
  110. xs *fn = xs_fmt("%s/token/%s.json", srv_basedir, id);
  111. return unlink(fn);
  112. }
  113. const char *login_page = ""
  114. "<!DOCTYPE html>\n"
  115. "<body><h1>%s OAuth identify</h1>\n"
  116. "<div style=\"background-color: red; color: white\">%s</div>\n"
  117. "<form method=\"post\" action=\"https:/" "/%s/oauth/x-snac-login\">\n"
  118. "<p>Login: <input type=\"text\" name=\"login\"></p>\n"
  119. "<p>Password: <input type=\"password\" name=\"passwd\"></p>\n"
  120. "<input type=\"hidden\" name=\"redir\" value=\"%s\">\n"
  121. "<input type=\"hidden\" name=\"cid\" value=\"%s\">\n"
  122. "<input type=\"hidden\" name=\"state\" value=\"%s\">\n"
  123. "<input type=\"submit\" value=\"OK\">\n"
  124. "</form><p>%s</p></body>\n"
  125. "";
  126. int oauth_get_handler(const xs_dict *req, const char *q_path,
  127. char **body, int *b_size, char **ctype)
  128. {
  129. if (!xs_startswith(q_path, "/oauth/"))
  130. return 0;
  131. /* {
  132. xs *j = xs_json_dumps_pp(req, 4);
  133. printf("oauth get:\n%s\n", j);
  134. }*/
  135. int status = 404;
  136. xs_dict *msg = xs_dict_get(req, "q_vars");
  137. xs *cmd = xs_replace(q_path, "/oauth", "");
  138. srv_debug(1, xs_fmt("oauth_get_handler %s", q_path));
  139. if (strcmp(cmd, "/authorize") == 0) {
  140. const char *cid = xs_dict_get(msg, "client_id");
  141. const char *ruri = xs_dict_get(msg, "redirect_uri");
  142. const char *rtype = xs_dict_get(msg, "response_type");
  143. const char *state = xs_dict_get(msg, "state");
  144. status = 400;
  145. if (cid && ruri && rtype && strcmp(rtype, "code") == 0) {
  146. xs *app = app_get(cid);
  147. if (app != NULL) {
  148. const char *host = xs_dict_get(srv_config, "host");
  149. if (xs_is_null(state))
  150. state = "";
  151. *body = xs_fmt(login_page, host, "", host, ruri, cid, state, USER_AGENT);
  152. *ctype = "text/html";
  153. status = 200;
  154. srv_debug(0, xs_fmt("oauth authorize: generating login page"));
  155. }
  156. else
  157. srv_debug(0, xs_fmt("oauth authorize: bad client_id %s", cid));
  158. }
  159. else
  160. srv_debug(0, xs_fmt("oauth authorize: invalid or unset arguments"));
  161. }
  162. return status;
  163. }
  164. int oauth_post_handler(const xs_dict *req, const char *q_path,
  165. const char *payload, int p_size,
  166. char **body, int *b_size, char **ctype)
  167. {
  168. if (!xs_startswith(q_path, "/oauth/"))
  169. return 0;
  170. /* {
  171. xs *j = xs_json_dumps_pp(req, 4);
  172. printf("oauth post:\n%s\n", j);
  173. }*/
  174. int status = 404;
  175. char *i_ctype = xs_dict_get(req, "content-type");
  176. xs *args = NULL;
  177. if (i_ctype && xs_startswith(i_ctype, "application/json"))
  178. args = xs_json_loads(payload);
  179. else
  180. args = xs_dup(xs_dict_get(req, "p_vars"));
  181. xs *cmd = xs_replace(q_path, "/oauth", "");
  182. srv_debug(1, xs_fmt("oauth_post_handler %s", q_path));
  183. if (strcmp(cmd, "/x-snac-login") == 0) {
  184. const char *login = xs_dict_get(args, "login");
  185. const char *passwd = xs_dict_get(args, "passwd");
  186. const char *redir = xs_dict_get(args, "redir");
  187. const char *cid = xs_dict_get(args, "cid");
  188. const char *state = xs_dict_get(args, "state");
  189. const char *host = xs_dict_get(srv_config, "host");
  190. /* by default, generate another login form with an error */
  191. *body = xs_fmt(login_page, host, "LOGIN INCORRECT", host, redir, cid, state, USER_AGENT);
  192. *ctype = "text/html";
  193. status = 200;
  194. if (login && passwd && redir && cid) {
  195. snac snac;
  196. if (user_open(&snac, login)) {
  197. /* check the login + password */
  198. if (check_password(login, passwd,
  199. xs_dict_get(snac.config, "passwd"))) {
  200. /* success! redirect to the desired uri */
  201. xs *code = random_str();
  202. xs_free(*body);
  203. *body = xs_fmt("%s?code=%s", redir, code);
  204. status = 303;
  205. /* if there is a state, add it */
  206. if (!xs_is_null(state) && *state) {
  207. *body = xs_str_cat(*body, "&state=");
  208. *body = xs_str_cat(*body, state);
  209. }
  210. srv_log(xs_fmt("oauth x-snac-login: '%s' success, redirect to %s",
  211. login, *body));
  212. /* assign the login to the app */
  213. xs *app = app_get(cid);
  214. if (app != NULL) {
  215. app = xs_dict_set(app, "uid", login);
  216. app = xs_dict_set(app, "code", code);
  217. app_add(cid, app);
  218. }
  219. else
  220. srv_log(xs_fmt("oauth x-snac-login: error getting app %s", cid));
  221. }
  222. else
  223. srv_debug(1, xs_fmt("oauth x-snac-login: login '%s' incorrect", login));
  224. user_free(&snac);
  225. }
  226. else
  227. srv_debug(1, xs_fmt("oauth x-snac-login: bad user '%s'", login));
  228. }
  229. else
  230. srv_debug(1, xs_fmt("oauth x-snac-login: invalid or unset arguments"));
  231. }
  232. else
  233. if (strcmp(cmd, "/token") == 0) {
  234. const char *gtype = xs_dict_get(args, "grant_type");
  235. const char *code = xs_dict_get(args, "code");
  236. const char *cid = xs_dict_get(args, "client_id");
  237. const char *csec = xs_dict_get(args, "client_secret");
  238. const char *ruri = xs_dict_get(args, "redirect_uri");
  239. const char *scope = xs_dict_get(args, "scope");
  240. xs *wrk = NULL;
  241. /* no client_secret? check if it's inside an authorization header
  242. (AndStatus does it this way) */
  243. if (xs_is_null(csec)) {
  244. const char *auhdr = xs_dict_get(req, "authorization");
  245. if (!xs_is_null(auhdr) && xs_startswith(auhdr, "Basic ")) {
  246. xs *s1 = xs_replace(auhdr, "Basic ", "");
  247. int size;
  248. xs *s2 = xs_base64_dec(s1, &size);
  249. if (!xs_is_null(s2)) {
  250. xs *l1 = xs_split(s2, ":");
  251. if (xs_list_len(l1) == 2) {
  252. wrk = xs_dup(xs_list_get(l1, 1));
  253. csec = wrk;
  254. }
  255. }
  256. }
  257. }
  258. if (gtype && code && cid && csec && ruri) {
  259. xs *app = app_get(cid);
  260. if (app == NULL) {
  261. status = 401;
  262. srv_log(xs_fmt("oauth token: invalid app %s", cid));
  263. }
  264. else
  265. if (strcmp(csec, xs_dict_get(app, "client_secret")) != 0) {
  266. status = 401;
  267. srv_log(xs_fmt("oauth token: invalid client_secret for app %s", cid));
  268. }
  269. else {
  270. xs *rsp = xs_dict_new();
  271. xs *cat = xs_number_new(time(NULL));
  272. xs *tokid = random_str();
  273. rsp = xs_dict_append(rsp, "access_token", tokid);
  274. rsp = xs_dict_append(rsp, "token_type", "Bearer");
  275. rsp = xs_dict_append(rsp, "created_at", cat);
  276. if (!xs_is_null(scope))
  277. rsp = xs_dict_append(rsp, "scope", scope);
  278. *body = xs_json_dumps_pp(rsp, 4);
  279. *ctype = "application/json";
  280. status = 200;
  281. const char *uid = xs_dict_get(app, "uid");
  282. srv_debug(0, xs_fmt("oauth token: "
  283. "successful login for %s, new token %s", uid, tokid));
  284. xs *token = xs_dict_new();
  285. token = xs_dict_append(token, "token", tokid);
  286. token = xs_dict_append(token, "client_id", cid);
  287. token = xs_dict_append(token, "client_secret", csec);
  288. token = xs_dict_append(token, "uid", uid);
  289. token = xs_dict_append(token, "code", code);
  290. token_add(tokid, token);
  291. }
  292. }
  293. else {
  294. srv_debug(0, xs_fmt("oauth token: invalid or unset arguments"));
  295. status = 400;
  296. }
  297. }
  298. else
  299. if (strcmp(cmd, "/revoke") == 0) {
  300. const char *cid = xs_dict_get(args, "client_id");
  301. const char *csec = xs_dict_get(args, "client_secret");
  302. const char *tokid = xs_dict_get(args, "token");
  303. if (cid && csec && tokid) {
  304. xs *token = token_get(tokid);
  305. *body = xs_str_new("{}");
  306. *ctype = "application/json";
  307. if (token == NULL || strcmp(csec, xs_dict_get(token, "client_secret")) != 0) {
  308. srv_debug(1, xs_fmt("oauth revoke: bad secret for token %s", tokid));
  309. status = 403;
  310. }
  311. else {
  312. token_del(tokid);
  313. srv_debug(0, xs_fmt("oauth revoke: revoked token %s", tokid));
  314. status = 200;
  315. /* also delete the app, as it serves no purpose from now on */
  316. app_del(cid);
  317. }
  318. }
  319. else {
  320. srv_debug(0, xs_fmt("oauth revoke: invalid or unset arguments"));
  321. status = 403;
  322. }
  323. }
  324. return status;
  325. }
  326. xs_str *mastoapi_id(const xs_dict *msg)
  327. /* returns a somewhat Mastodon-compatible status id */
  328. {
  329. const char *id = xs_dict_get(msg, "id");
  330. xs *md5 = xs_md5_hex(id, strlen(id));
  331. return xs_fmt("%10.0f%s", object_ctime_by_md5(md5), md5);
  332. }
  333. #define MID_TO_MD5(id) (id + 10)
  334. xs_dict *mastoapi_account(const xs_dict *actor)
  335. /* converts an ActivityPub actor to a Mastodon account */
  336. {
  337. xs_dict *acct = xs_dict_new();
  338. const char *display_name = xs_dict_get(actor, "name");
  339. if (xs_is_null(display_name) || *display_name == '\0')
  340. display_name = xs_dict_get(actor, "preferredUsername");
  341. const char *id = xs_dict_get(actor, "id");
  342. const char *pub = xs_dict_get(actor, "published");
  343. xs *acct_md5 = xs_md5_hex(id, strlen(id));
  344. acct = xs_dict_append(acct, "id", acct_md5);
  345. acct = xs_dict_append(acct, "username", xs_dict_get(actor, "preferredUsername"));
  346. acct = xs_dict_append(acct, "acct", xs_dict_get(actor, "preferredUsername"));
  347. acct = xs_dict_append(acct, "display_name", display_name);
  348. if (pub)
  349. acct = xs_dict_append(acct, "created_at", pub);
  350. else {
  351. /* unset created_at crashes Tusky, so lie like a mf */
  352. xs *date = xs_str_utctime(0, "%Y-%m-%dT%H:%M:%SZ");
  353. acct = xs_dict_append(acct, "created_at", date);
  354. }
  355. acct = xs_dict_append(acct, "note", xs_dict_get(actor, "summary"));
  356. acct = xs_dict_append(acct, "url", id);
  357. xs *avatar = NULL;
  358. xs_dict *av = xs_dict_get(actor, "icon");
  359. if (xs_type(av) == XSTYPE_DICT)
  360. avatar = xs_dup(xs_dict_get(av, "url"));
  361. else
  362. avatar = xs_fmt("%s/susie.png", srv_baseurl);
  363. acct = xs_dict_append(acct, "avatar", avatar);
  364. return acct;
  365. }
  366. xs_dict *mastoapi_status(snac *snac, const xs_dict *msg)
  367. /* converts an ActivityPub note to a Mastodon status */
  368. {
  369. xs *actor = NULL;
  370. actor_get(snac, xs_dict_get(msg, "attributedTo"), &actor);
  371. /* if the author is not here, discard */
  372. if (actor == NULL)
  373. return NULL;
  374. xs *acct = mastoapi_account(actor);
  375. /** shave the yak converting an ActivityPub Note to a Mastodon status **/
  376. xs *f = xs_val_new(XSTYPE_FALSE);
  377. xs *t = xs_val_new(XSTYPE_TRUE);
  378. xs *n = xs_val_new(XSTYPE_NULL);
  379. xs *el = xs_list_new();
  380. xs *idx = NULL;
  381. xs *ixc = NULL;
  382. char *tmp;
  383. char *id = xs_dict_get(msg, "id");
  384. xs *mid = mastoapi_id(msg);
  385. xs_dict *st = xs_dict_new();
  386. st = xs_dict_append(st, "id", mid);
  387. st = xs_dict_append(st, "uri", id);
  388. st = xs_dict_append(st, "url", id);
  389. st = xs_dict_append(st, "created_at", xs_dict_get(msg, "published"));
  390. st = xs_dict_append(st, "account", acct);
  391. st = xs_dict_append(st, "content", xs_dict_get(msg, "content"));
  392. st = xs_dict_append(st, "visibility",
  393. is_msg_public(snac, msg) ? "public" : "private");
  394. tmp = xs_dict_get(msg, "sensitive");
  395. if (xs_is_null(tmp))
  396. tmp = f;
  397. st = xs_dict_append(st, "sensitive", tmp);
  398. tmp = xs_dict_get(msg, "summary");
  399. if (xs_is_null(tmp))
  400. tmp = "";
  401. st = xs_dict_append(st, "spoiler_text", tmp);
  402. /* create the list of attachments */
  403. xs *matt = xs_list_new();
  404. xs_list *att = xs_dict_get(msg, "attachment");
  405. xs_str *aobj;
  406. while (xs_list_iter(&att, &aobj)) {
  407. const char *mtype = xs_dict_get(aobj, "mediaType");
  408. if (!xs_is_null(mtype) && xs_startswith(mtype, "image/")) {
  409. xs *matteid = xs_fmt("%s_%d", id, xs_list_len(matt));
  410. xs *matte = xs_dict_new();
  411. matte = xs_dict_append(matte, "id", matteid);
  412. matte = xs_dict_append(matte, "type", "image");
  413. matte = xs_dict_append(matte, "url", xs_dict_get(aobj, "url"));
  414. matte = xs_dict_append(matte, "preview_url", xs_dict_get(aobj, "url"));
  415. matte = xs_dict_append(matte, "remote_url", xs_dict_get(aobj, "url"));
  416. const char *name = xs_dict_get(aobj, "name");
  417. if (xs_is_null(name))
  418. name = "";
  419. matte = xs_dict_append(matte, "description", name);
  420. matt = xs_list_append(matt, matte);
  421. }
  422. }
  423. st = xs_dict_append(st, "media_attachments", matt);
  424. st = xs_dict_append(st, "mentions", el);
  425. st = xs_dict_append(st, "tags", el);
  426. st = xs_dict_append(st, "emojis", el);
  427. xs_free(idx);
  428. xs_free(ixc);
  429. idx = object_likes(id);
  430. ixc = xs_number_new(xs_list_len(idx));
  431. st = xs_dict_append(st, "favourites_count", ixc);
  432. st = xs_dict_append(st, "favourited",
  433. xs_list_in(idx, snac->md5) != -1 ? t : f);
  434. xs_free(idx);
  435. xs_free(ixc);
  436. idx = object_announces(id);
  437. ixc = xs_number_new(xs_list_len(idx));
  438. st = xs_dict_append(st, "reblogs_count", ixc);
  439. st = xs_dict_append(st, "reblogged",
  440. xs_list_in(idx, snac->md5) != -1 ? t : f);
  441. xs_free(idx);
  442. xs_free(ixc);
  443. idx = object_children(id);
  444. ixc = xs_number_new(xs_list_len(idx));
  445. st = xs_dict_append(st, "replies_count", ixc);
  446. /* default in_reply_to values */
  447. st = xs_dict_append(st, "in_reply_to_id", n);
  448. st = xs_dict_append(st, "in_reply_to_account_id", n);
  449. tmp = xs_dict_get(msg, "inReplyTo");
  450. if (!xs_is_null(tmp)) {
  451. xs *irto = NULL;
  452. if (valid_status(object_get(tmp, &irto))) {
  453. xs *irt_mid = mastoapi_id(irto);
  454. st = xs_dict_set(st, "in_reply_to_id", irt_mid);
  455. char *at = NULL;
  456. if (!xs_is_null(at = xs_dict_get(irto, "attributedTo"))) {
  457. xs *at_md5 = xs_md5_hex(at, strlen(at));
  458. st = xs_dict_set(st, "in_reply_to_account_id", at_md5);
  459. }
  460. }
  461. }
  462. st = xs_dict_append(st, "reblog", n);
  463. st = xs_dict_append(st, "poll", n);
  464. st = xs_dict_append(st, "card", n);
  465. st = xs_dict_append(st, "language", n);
  466. tmp = xs_dict_get(msg, "sourceContent");
  467. if (xs_is_null(tmp))
  468. tmp = "";
  469. st = xs_dict_append(st, "text", tmp);
  470. tmp = xs_dict_get(msg, "updated");
  471. if (xs_is_null(tmp))
  472. tmp = n;
  473. st = xs_dict_append(st, "edited_at", tmp);
  474. return st;
  475. }
  476. int process_auth_token(snac *snac, const xs_dict *req)
  477. /* processes an authorization token, if there is one */
  478. {
  479. int logged_in = 0;
  480. char *v;
  481. /* if there is an authorization field, try to validate it */
  482. if (!xs_is_null(v = xs_dict_get(req, "authorization")) && xs_startswith(v, "Bearer ")) {
  483. xs *tokid = xs_replace(v, "Bearer ", "");
  484. xs *token = token_get(tokid);
  485. if (token != NULL) {
  486. const char *uid = xs_dict_get(token, "uid");
  487. if (!xs_is_null(uid) && user_open(snac, uid)) {
  488. logged_in = 1;
  489. srv_debug(2, xs_fmt("mastoapi auth: valid token for user %s", uid));
  490. }
  491. else
  492. srv_log(xs_fmt("mastoapi auth: corrupted token %s", tokid));
  493. }
  494. else
  495. srv_log(xs_fmt("mastoapi auth: invalid token %s", tokid));
  496. }
  497. return logged_in;
  498. }
  499. int mastoapi_get_handler(const xs_dict *req, const char *q_path,
  500. char **body, int *b_size, char **ctype)
  501. {
  502. if (!xs_startswith(q_path, "/api/v1/"))
  503. return 0;
  504. srv_debug(1, xs_fmt("mastoapi_get_handler %s", q_path));
  505. /* {
  506. xs *j = xs_json_dumps_pp(req, 4);
  507. printf("mastoapi get:\n%s\n", j);
  508. }*/
  509. int status = 404;
  510. xs_dict *args = xs_dict_get(req, "q_vars");
  511. xs *cmd = xs_replace(q_path, "/api/v1", "");
  512. snac snac1 = {0};
  513. int logged_in = process_auth_token(&snac1, req);
  514. if (strcmp(cmd, "/accounts/verify_credentials") == 0) {
  515. if (logged_in) {
  516. xs *acct = xs_dict_new();
  517. acct = xs_dict_append(acct, "id", xs_dict_get(snac1.config, "uid"));
  518. acct = xs_dict_append(acct, "username", xs_dict_get(snac1.config, "uid"));
  519. acct = xs_dict_append(acct, "acct", xs_dict_get(snac1.config, "uid"));
  520. acct = xs_dict_append(acct, "display_name", xs_dict_get(snac1.config, "name"));
  521. acct = xs_dict_append(acct, "created_at", xs_dict_get(snac1.config, "published"));
  522. acct = xs_dict_append(acct, "note", xs_dict_get(snac1.config, "bio"));
  523. acct = xs_dict_append(acct, "url", snac1.actor);
  524. xs *avatar = NULL;
  525. char *av = xs_dict_get(snac1.config, "avatar");
  526. if (xs_is_null(av) || *av == '\0')
  527. avatar = xs_fmt("%s/susie.png", srv_baseurl);
  528. else
  529. avatar = xs_dup(av);
  530. acct = xs_dict_append(acct, "avatar", avatar);
  531. *body = xs_json_dumps_pp(acct, 4);
  532. *ctype = "application/json";
  533. status = 200;
  534. }
  535. else {
  536. status = 422; // "Unprocessable entity" (no login)
  537. }
  538. }
  539. else
  540. if (strcmp(cmd, "/accounts/relationships") == 0) {
  541. /* find if an account is followed, blocked, etc. */
  542. /* the account to get relationships about is in args "id[]" */
  543. /* dummy by now */
  544. if (logged_in) {
  545. *body = xs_dup("[]");
  546. *ctype = "application/json";
  547. status = 200;
  548. }
  549. }
  550. else
  551. if (xs_startswith(cmd, "/accounts/")) {
  552. /* account-related information */
  553. xs *l = xs_split(cmd, "/");
  554. const char *uid = xs_list_get(l, 2);
  555. const char *opt = xs_list_get(l, 3);
  556. if (uid != NULL) {
  557. snac snac2;
  558. xs *out = NULL;
  559. xs *actor = NULL;
  560. /* is it a local user? */
  561. if (user_open(&snac2, uid)) {
  562. if (opt == NULL) {
  563. /* account information */
  564. actor = msg_actor(&snac2);
  565. out = mastoapi_account(actor);
  566. }
  567. else
  568. if (strcmp(opt, "statuses") == 0) {
  569. /* the public list of posts of a user */
  570. xs *timeline = timeline_simple_list(&snac2, "public", 0, 256);
  571. xs_list *p = timeline;
  572. xs_str *v;
  573. out = xs_list_new();
  574. while (xs_list_iter(&p, &v)) {
  575. xs *msg = NULL;
  576. if (valid_status(timeline_get_by_md5(&snac2, v, &msg))) {
  577. /* add only posts by the author */
  578. if (strcmp(xs_dict_get(msg, "type"), "Note") == 0 &&
  579. xs_startswith(xs_dict_get(msg, "id"), snac2.actor)) {
  580. xs *st = mastoapi_status(&snac2, msg);
  581. out = xs_list_append(out, st);
  582. }
  583. }
  584. }
  585. }
  586. user_free(&snac2);
  587. }
  588. else {
  589. /* try the uid as the md5 of a possibly loaded actor */
  590. if (logged_in && valid_status(object_get_by_md5(uid, &actor))) {
  591. if (opt == NULL) {
  592. /* account information */
  593. out = mastoapi_account(actor);
  594. }
  595. else
  596. if (strcmp(opt, "statuses") == 0) {
  597. /* we don't serve statuses of others; return the empty list */
  598. out = xs_list_new();
  599. }
  600. }
  601. }
  602. if (out != NULL) {
  603. *body = xs_json_dumps_pp(out, 4);
  604. *ctype = "application/json";
  605. status = 200;
  606. }
  607. }
  608. }
  609. else
  610. if (strcmp(cmd, "/timelines/home") == 0) {
  611. /* the private timeline */
  612. if (logged_in) {
  613. const char *max_id = xs_dict_get(args, "max_id");
  614. const char *since_id = xs_dict_get(args, "since_id");
  615. const char *min_id = xs_dict_get(args, "min_id");
  616. const char *limit_s = xs_dict_get(args, "limit");
  617. int limit = 0;
  618. int cnt = 0;
  619. if (!xs_is_null(limit_s))
  620. limit = atoi(limit_s);
  621. if (limit == 0)
  622. limit = 20;
  623. xs *timeline = timeline_simple_list(&snac1, "private", 0, XS_ALL);
  624. xs *out = xs_list_new();
  625. xs_list *p = timeline;
  626. xs_str *v;
  627. while (xs_list_iter(&p, &v) && cnt < limit) {
  628. xs *msg = NULL;
  629. /* only return entries older that max_id */
  630. if (max_id) {
  631. if (strcmp(v, max_id) == 0)
  632. max_id = NULL;
  633. continue;
  634. }
  635. /* only returns entries newer than since_id */
  636. if (since_id) {
  637. if (strcmp(v, since_id) == 0)
  638. break;
  639. }
  640. /* only returns entries newer than min_id */
  641. /* what does really "Return results immediately newer than ID" mean? */
  642. if (min_id) {
  643. if (strcmp(v, min_id) == 0)
  644. break;
  645. }
  646. /* get the entry */
  647. if (!valid_status(timeline_get_by_md5(&snac1, v, &msg)))
  648. continue;
  649. /* discard non-Notes */
  650. if (strcmp(xs_dict_get(msg, "type"), "Note") != 0)
  651. continue;
  652. /* convert the Note into a Mastodon status */
  653. xs *st = mastoapi_status(&snac1, msg);
  654. if (st != NULL)
  655. out = xs_list_append(out, st);
  656. cnt++;
  657. }
  658. *body = xs_json_dumps_pp(out, 4);
  659. *ctype = "application/json";
  660. status = 200;
  661. {
  662. xs *j = xs_json_loads(*body);
  663. if (j == NULL) {
  664. srv_log(xs_fmt("mastoapi timeline: bad JSON"));
  665. srv_archive_error("mastoapi_timeline", "bad JSON", req, *body);
  666. }
  667. }
  668. srv_debug(2, xs_fmt("mastoapi timeline: returned %d entries", xs_list_len(out)));
  669. }
  670. else {
  671. status = 401; // unauthorized
  672. }
  673. }
  674. else
  675. if (strcmp(cmd, "/timelines/public") == 0) {
  676. /* the public timeline (public timelines for all users) */
  677. /* TBD */
  678. *body = xs_dup("[]");
  679. *ctype = "application/json";
  680. status = 200;
  681. }
  682. else
  683. if (strcmp(cmd, "/conversations") == 0) {
  684. /* TBD */
  685. *body = xs_dup("[]");
  686. *ctype = "application/json";
  687. status = 200;
  688. }
  689. else
  690. if (strcmp(cmd, "/notifications") == 0) {
  691. if (logged_in) {
  692. xs *l = notify_list(&snac1, 0);
  693. xs *out = xs_list_new();
  694. xs_list *p = l;
  695. xs_dict *v;
  696. while (xs_list_iter(&p, &v)) {
  697. xs *noti = notify_get(&snac1, v);
  698. if (noti == NULL)
  699. continue;
  700. const char *type = xs_dict_get(noti, "type");
  701. const char *objid = xs_dict_get(noti, "objid");
  702. xs *actor = NULL;
  703. xs *entry = NULL;
  704. if (!valid_status(object_get(xs_dict_get(noti, "actor"), &actor)))
  705. continue;
  706. if (objid != NULL && !valid_status(object_get(objid, &entry)))
  707. continue;
  708. if (is_hidden(&snac1, objid))
  709. continue;
  710. /* convert the type */
  711. if (strcmp(type, "Like") == 0)
  712. type = "favourite";
  713. else
  714. if (strcmp(type, "Announce") == 0)
  715. type = "reblog";
  716. else
  717. if (strcmp(type, "Follow") == 0)
  718. type = "follow";
  719. else
  720. if (strcmp(type, "Create") == 0)
  721. type = "mention";
  722. else
  723. continue;
  724. xs *mn = xs_dict_new();
  725. mn = xs_dict_append(mn, "type", type);
  726. xs *id = xs_replace(xs_dict_get(noti, "id"), ".", "");
  727. mn = xs_dict_append(mn, "id", id);
  728. mn = xs_dict_append(mn, "created_at", xs_dict_get(noti, "date"));
  729. xs *acct = mastoapi_account(actor);
  730. mn = xs_dict_append(mn, "account", acct);
  731. if (strcmp(type, "follow") != 0 && !xs_is_null(objid)) {
  732. xs *st = mastoapi_status(&snac1, entry);
  733. mn = xs_dict_append(mn, "status", st);
  734. }
  735. out = xs_list_append(out, mn);
  736. }
  737. *body = xs_json_dumps_pp(out, 4);
  738. *ctype = "application/json";
  739. status = 200;
  740. }
  741. else
  742. status = 401;
  743. }
  744. else
  745. if (strcmp(cmd, "/filters") == 0) {
  746. /* snac will never have filters */
  747. *body = xs_dup("[]");
  748. *ctype = "application/json";
  749. status = 200;
  750. }
  751. else
  752. if (strcmp(cmd, "/favourites") == 0) {
  753. /* snac will never support a list of favourites */
  754. *body = xs_dup("[]");
  755. *ctype = "application/json";
  756. status = 200;
  757. }
  758. else
  759. if (strcmp(cmd, "/bookmarks") == 0) {
  760. /* snac does not support bookmarks */
  761. *body = xs_dup("[]");
  762. *ctype = "application/json";
  763. status = 200;
  764. }
  765. else
  766. if (strcmp(cmd, "/lists") == 0) {
  767. /* snac does not support lists */
  768. *body = xs_dup("[]");
  769. *ctype = "application/json";
  770. status = 200;
  771. }
  772. else
  773. if (strcmp(cmd, "/scheduled_statuses") == 0) {
  774. /* snac does not scheduled notes */
  775. *body = xs_dup("[]");
  776. *ctype = "application/json";
  777. status = 200;
  778. }
  779. else
  780. if (strcmp(cmd, "/follow_requests") == 0) {
  781. /* snac does not support optional follow confirmations */
  782. *body = xs_dup("[]");
  783. *ctype = "application/json";
  784. status = 200;
  785. }
  786. else
  787. if (strcmp(cmd, "/announcements") == 0) {
  788. /* snac has no announcements (yet?) */
  789. *body = xs_dup("[]");
  790. *ctype = "application/json";
  791. status = 200;
  792. }
  793. else
  794. if (strcmp(cmd, "/custom_emojis") == 0) {
  795. /* are you kidding me? */
  796. *body = xs_dup("[]");
  797. *ctype = "application/json";
  798. status = 200;
  799. }
  800. else
  801. if (strcmp(cmd, "/instance") == 0) {
  802. /* returns an instance object */
  803. xs *ins = xs_dict_new();
  804. const char *host = xs_dict_get(srv_config, "host");
  805. ins = xs_dict_append(ins, "uri", host);
  806. ins = xs_dict_append(ins, "domain", host);
  807. ins = xs_dict_append(ins, "title", host);
  808. ins = xs_dict_append(ins, "version", "4.0.0 (not true; really " USER_AGENT ")");
  809. ins = xs_dict_append(ins, "source_url", "https:/" "/comam.es/what-is-snac");
  810. ins = xs_dict_append(ins, "description", host);
  811. xs *susie = xs_fmt("%s/susie.png", srv_baseurl);
  812. ins = xs_dict_append(ins, "thumbnail", susie);
  813. xs *d2 = xs_dict_new();
  814. d2 = xs_dict_append(d2, "email", "admin@localhost");
  815. ins = xs_dict_append(ins, "contact", d2);
  816. xs *l1 = xs_list_new();
  817. ins = xs_dict_append(ins, "rules", l1);
  818. ins = xs_dict_append(ins, "languages", l1);
  819. *body = xs_json_dumps_pp(ins, 4);
  820. *ctype = "application/json";
  821. status = 200;
  822. }
  823. else
  824. if (xs_startswith(cmd, "/statuses/")) {
  825. /* operations on a status */
  826. xs *l = xs_split(cmd, "/");
  827. const char *id = xs_list_get(l, 2);
  828. const char *op = xs_list_get(l, 3);
  829. if (!xs_is_null(id)) {
  830. xs *msg = NULL;
  831. xs *out = NULL;
  832. /* skip the 'fake' part of the id */
  833. id = MID_TO_MD5(id);
  834. if (valid_status(timeline_get_by_md5(&snac1, id, &msg))) {
  835. if (op == NULL) {
  836. /* return the status itself */
  837. out = mastoapi_status(&snac1, msg);
  838. }
  839. else
  840. if (strcmp(op, "context") == 0) {
  841. /* return ancestors and children */
  842. xs *anc = xs_list_new();
  843. xs *des = xs_list_new();
  844. xs_list *p;
  845. xs_str *v;
  846. char pid[64];
  847. /* build the [grand]parent list, moving up */
  848. strcpy(pid, id);
  849. while (object_parent(pid, pid, sizeof(pid))) {
  850. xs *m2 = NULL;
  851. if (valid_status(timeline_get_by_md5(&snac1, pid, &m2))) {
  852. xs *st = mastoapi_status(&snac1, m2);
  853. anc = xs_list_append(anc, st);
  854. }
  855. else
  856. break;
  857. }
  858. /* build the children list */
  859. xs *children = object_children(xs_dict_get(msg, "id"));
  860. p = children;
  861. while (xs_list_iter(&p, &v)) {
  862. xs *m2 = NULL;
  863. if (valid_status(timeline_get_by_md5(&snac1, v, &m2))) {
  864. xs *st = mastoapi_status(&snac1, m2);
  865. des = xs_list_append(des, st);
  866. }
  867. }
  868. out = xs_dict_new();
  869. out = xs_dict_append(out, "ancestors", anc);
  870. out = xs_dict_append(out, "descendants", des);
  871. }
  872. else
  873. if (strcmp(op, "reblogged_by") == 0 ||
  874. strcmp(op, "favourited_by") == 0) {
  875. /* return the list of people who liked or boosted this */
  876. out = xs_list_new();
  877. xs *l = NULL;
  878. if (op[0] == 'r')
  879. l = object_announces(xs_dict_get(msg, "id"));
  880. else
  881. l = object_likes(xs_dict_get(msg, "id"));
  882. xs_list *p = l;
  883. xs_str *v;
  884. while (xs_list_iter(&p, &v)) {
  885. xs *actor2 = NULL;
  886. if (valid_status(object_get_by_md5(v, &actor2))) {
  887. xs *acct2 = mastoapi_account(actor2);
  888. out = xs_list_append(out, acct2);
  889. }
  890. }
  891. }
  892. }
  893. else
  894. srv_debug(1, xs_fmt("mastoapi status: bad id %s", id));
  895. if (out != NULL) {
  896. *body = xs_json_dumps_pp(out, 4);
  897. *ctype = "application/json";
  898. status = 200;
  899. }
  900. }
  901. }
  902. else
  903. if (strcmp(cmd, "/filters") == 0) {
  904. *body = xs_dup("[]");
  905. *ctype = "application/json";
  906. status = 200;
  907. }
  908. /* user cleanup */
  909. if (logged_in)
  910. user_free(&snac1);
  911. return status;
  912. }
  913. int mastoapi_post_handler(const xs_dict *req, const char *q_path,
  914. const char *payload, int p_size,
  915. char **body, int *b_size, char **ctype)
  916. {
  917. if (!xs_startswith(q_path, "/api/v1/"))
  918. return 0;
  919. srv_debug(1, xs_fmt("mastoapi_post_handler %s", q_path));
  920. /* {
  921. xs *j = xs_json_dumps_pp(req, 4);
  922. printf("mastoapi post:\n%s\n", j);
  923. }*/
  924. int status = 404;
  925. xs *args = NULL;
  926. char *i_ctype = xs_dict_get(req, "content-type");
  927. if (i_ctype && xs_startswith(i_ctype, "application/json"))
  928. args = xs_json_loads(payload);
  929. else
  930. args = xs_dup(xs_dict_get(req, "p_vars"));
  931. if (args == NULL)
  932. return 400;
  933. /* {
  934. xs *j = xs_json_dumps_pp(args, 4);
  935. printf("%s\n", j);
  936. }*/
  937. xs *cmd = xs_replace(q_path, "/api/v1", "");
  938. snac snac = {0};
  939. int logged_in = process_auth_token(&snac, req);
  940. if (strcmp(cmd, "/apps") == 0) {
  941. const char *name = xs_dict_get(args, "client_name");
  942. const char *ruri = xs_dict_get(args, "redirect_uris");
  943. const char *scope = xs_dict_get(args, "scope");
  944. if (xs_type(ruri) == XSTYPE_LIST)
  945. ruri = xs_dict_get(ruri, 0);
  946. if (name && ruri) {
  947. xs *app = xs_dict_new();
  948. xs *id = xs_replace_i(tid(0), ".", "");
  949. xs *cid = random_str();
  950. xs *csec = random_str();
  951. xs *vkey = random_str();
  952. app = xs_dict_append(app, "name", name);
  953. app = xs_dict_append(app, "redirect_uri", ruri);
  954. app = xs_dict_append(app, "client_id", cid);
  955. app = xs_dict_append(app, "client_secret", csec);
  956. app = xs_dict_append(app, "vapid_key", vkey);
  957. app = xs_dict_append(app, "id", id);
  958. *body = xs_json_dumps_pp(app, 4);
  959. *ctype = "application/json";
  960. status = 200;
  961. app = xs_dict_append(app, "code", "");
  962. if (scope)
  963. app = xs_dict_append(app, "scope", scope);
  964. app_add(cid, app);
  965. srv_debug(0, xs_fmt("mastoapi apps: new app %s", cid));
  966. }
  967. }
  968. else
  969. if (strcmp(cmd, "/statuses") == 0) {
  970. if (logged_in) {
  971. /* post a new Note */
  972. /* TBD */
  973. }
  974. else
  975. status = 401;
  976. }
  977. else
  978. if (xs_startswith(cmd, "/statuses")) {
  979. if (logged_in) {
  980. /* operations on a status */
  981. xs *l = xs_split(cmd, "/");
  982. const char *mid = xs_list_get(l, 2);
  983. const char *op = xs_list_get(l, 3);
  984. if (!xs_is_null(mid)) {
  985. xs *msg = NULL;
  986. xs *out = NULL;
  987. /* skip the 'fake' part of the id */
  988. mid = MID_TO_MD5(mid);
  989. if (valid_status(timeline_get_by_md5(&snac, mid, &msg))) {
  990. char *id = xs_dict_get(msg, "id");
  991. if (op == NULL) {
  992. /* no operation (?) */
  993. }
  994. else
  995. if (strcmp(op, "favourite") == 0) {
  996. xs *n_msg = msg_admiration(&snac, id, "Like");
  997. if (n_msg != NULL) {
  998. enqueue_message(&snac, n_msg);
  999. timeline_admire(&snac, xs_dict_get(n_msg, "object"), snac.actor, 1);
  1000. out = mastoapi_status(&snac, msg);
  1001. }
  1002. }
  1003. else
  1004. if (strcmp(op, "unfavourite") == 0) {
  1005. /* snac does not support Undo+Like */
  1006. }
  1007. else
  1008. if (strcmp(op, "reblog") == 0) {
  1009. xs *n_msg = msg_admiration(&snac, id, "Announce");
  1010. if (n_msg != NULL) {
  1011. enqueue_message(&snac, n_msg);
  1012. timeline_admire(&snac, xs_dict_get(n_msg, "object"), snac.actor, 0);
  1013. out = mastoapi_status(&snac, msg);
  1014. }
  1015. }
  1016. else
  1017. if (strcmp(op, "unreblog") == 0) {
  1018. /* snac does not support Undo+Announce */
  1019. }
  1020. else
  1021. if (strcmp(op, "bookmark") == 0) {
  1022. /* snac does not support bookmarks */
  1023. }
  1024. else
  1025. if (strcmp(op, "unbookmark") == 0) {
  1026. /* snac does not support bookmarks */
  1027. }
  1028. else
  1029. if (strcmp(op, "pin") == 0) {
  1030. /* snac does not support pinning */
  1031. }
  1032. else
  1033. if (strcmp(op, "unpin") == 0) {
  1034. /* snac does not support pinning */
  1035. }
  1036. else
  1037. if (strcmp(op, "mute") == 0) {
  1038. /* Mastodon's mute is snac's hide */
  1039. }
  1040. else
  1041. if (strcmp(op, "unmute") == 0) {
  1042. /* Mastodon's unmute is snac's unhide */
  1043. }
  1044. }
  1045. if (out != NULL) {
  1046. *body = xs_json_dumps_pp(out, 4);
  1047. *ctype = "application/json";
  1048. status = 200;
  1049. }
  1050. }
  1051. }
  1052. else
  1053. status = 401;
  1054. }
  1055. else
  1056. if (strcmp(cmd, "/notifications/clear") == 0) {
  1057. if (logged_in) {
  1058. notify_clear(&snac);
  1059. timeline_touch(&snac);
  1060. *body = xs_dup("{}");
  1061. *ctype = "application/json";
  1062. status = 200;
  1063. }
  1064. else
  1065. status = 401;
  1066. }
  1067. /* user cleanup */
  1068. if (logged_in)
  1069. user_free(&snac);
  1070. return status;
  1071. }