/* * Copyright (c) 2018 Markus Hennecke * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include #include #include #include #include #include #include #include #include "../db.h" #include "../util.h" enum key { KEY_FROM, KEY_UNTIL, KEY_DEVICE, KEY__MAX }; static const struct kvalid keys[KEY__MAX] = { { validate_timestamp, "from" }, { validate_timestamp, "until" }, { kvalid_string, "device" }, }; enum pg { PG_DATA, PG_STATISTICS, PG_LATEST, PG_ERRORS, PG__MAX }; static const char *pages[PG__MAX] = { "data", "statistics", "latest", "errors", }; static bool (*query_funcs[PG__MAX])(struct kreq *r, char **, const char *, const char *) = { db_get_data_json, db_get_statistics_data_json, db_get_latest_json, NULL, }; int main(void) { struct kreq r; enum kcgi_err er; tzset(); if ((pledge("cpath getpw stdio proc wpath rpath dns inet", NULL)) == (-1)) err(EXIT_FAILURE, "pledge"); er = khttp_parse(&r, keys, KEY__MAX, pages, PG__MAX, PG_DATA); if (KCGI_OK != er) return EXIT_FAILURE; /* * Accept GET... */ if (KMETHOD_OPTIONS == r.method) { khttp_head(&r, kresps[KRESP_ALLOW], "OPTIONS GET"); response(&r, KHTTP_200, r.mime, NULL); } else if (KMETHOD_GET == r.method) { char *json = NULL; const char *from = parameter(&r, KEY_FROM); const char *until = parameter(&r, KEY_UNTIL); const char *device = parameter(&r, KEY_DEVICE); switch (r.page) { case PG_DATA: case PG_STATISTICS: case PG_LATEST: if (r.fieldnmap[KEY_FROM] == NULL && r.fieldnmap[KEY_UNTIL] == NULL && query_funcs[r.page](&r, &json, from, until)) response(&r, KHTTP_200, KMIME_APP_JSON, json); else response(&r, KHTTP_503, KMIME_TEXT_PLAIN, NULL); break; case PG_ERRORS: if (r.fieldnmap[KEY_DEVICE] == NULL && db_get_errors_json(&r, &json, device)) response(&r, KHTTP_200, KMIME_APP_JSON, json); else response(&r, KHTTP_503, KMIME_TEXT_PLAIN, NULL); break; default: response(&r, KHTTP_503, KMIME_TEXT_PLAIN, "0 internal error"); break; } } else { response(&r, KHTTP_404, r.mime, "0 page not found"); } khttp_free(&r); return EXIT_SUCCESS; }