/* Saved model endpoints: fetching a list from GET {URL}/models (the OpenAI shape: data[].id and
* owned_by), adding one, and the RPC commands (endpoints.h). */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cred.h"
#include "endpoints.h"
#include "http.h"
#include "image.h"
#include "net.h"
#include "provider_http.h"
#include "sqlite3.h"
#include "userdb.h"
#define EP_BODY_CAP (4u << 20)
typedef struct {
char *buf;
size_t len;
int too_big;
} ep_body;
static int ep_on_body(void *ctx, const char *bytes, size_t n) {
ep_body *b = ctx;
char *grown;
if (b->len + n > EP_BODY_CAP) {
b->too_big = 1;
return 1;
}
if (!(grown = realloc(b->buf, b->len + n + 1))) {
return 1;
}
b->buf = grown;
memcpy(b->buf + b->len, bytes, n);
b->len += n;
b->buf[b->len] = '\0';
return 0;
}
/* The list in BODY as [{id, owned_by}] (malloc'd), or NULL when it is not an OpenAI model list. */
static char *ep_list(sqlite3 *db, const char *body) {
sqlite3_stmt *q = NULL;
char *out = NULL;
if (sqlite3_prepare_v2(db,
"SELECT (SELECT json_group_array(json_object('id', json_extract(value, '$.id'),"
" 'owned_by', CASE json_type(value, '$.owned_by') WHEN 'text' THEN json_extract(value, '$.owned_by') END))"
" FROM json_each(?1, '$.data') WHERE json_type(value, '$.id') = 'text')"
" WHERE json_valid(?1) AND json_type(?1, '$.data') = 'array'",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, body, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
out = strdup((const char *)sqlite3_column_text(q, 0));
}
}
sqlite3_finalize(q);
return out;
}
/* A refusal's own words, short: the error message of an OpenAI-style error body, or "". */
static void ep_reason(sqlite3 *db, const char *body, char *out, size_t cap) {
sqlite3_stmt *q = NULL;
out[0] = '\0';
if (body && sqlite3_prepare_v2(db,
"SELECT coalesce(json_extract(?1, '$.error.message'), json_extract(?1, '$.error'),"
" json_extract(?1, '$.message')) WHERE json_valid(?1)",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, body, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) == SQLITE_TEXT) {
(void)snprintf(out, cap, ": %.160s", (const char *)sqlite3_column_text(q, 0));
}
}
sqlite3_finalize(q);
}
int pic_endpoint_refresh(const char *name, int *count, char *err, size_t errcap) {
char base[PIC_ENDPOINT_URL_CAP], url[PIC_ENDPOINT_URL_CAP + 16], key[PIC_CRED_TOKEN_CAP], auth[PIC_CRED_TOKEN_CAP + 32];
char herr[256], reason[200];
const char *headers[3] = {"Accept: application/json", "User-Agent: pic", auth};
size_t nh = 2;
ep_body b = {NULL, 0, 0};
pic_http_resp r;
pic_net *net;
sqlite3 *db = NULL;
char *list = NULL;
int got, rc = -1;
*count = 0;
err[0] = '\0';
if (!pic_endpoint_url(name, base, sizeof base)) {
(void)snprintf(err, errcap, "no endpoint is saved as %s (pic endpoints list)", name);
return -1;
}
if ((got = pic_cred_get(name, "", "", key, sizeof key, err, errcap)) < 0) {
(void)pic_endpoint_note(name, NULL, err);
return -1;
}
auth[0] = '\0';
if (got == 0) {
if (pic_endpoint_basic_user(name, NULL, 0)) {
pic_auth_line(PIC_AUTH_BASIC, key, auth, sizeof auth);
} else {
pic_auth_line(PIC_AUTH_BEARER, key, auth, sizeof auth);
}
nh = 3;
}
(void)snprintf(url, sizeof url, "%s/models", base);
if (!(net = pic_net_new(herr, sizeof herr))) {
(void)snprintf(err, errcap, "%s", herr);
goto done;
}
pic_http_resp_init(&r, ep_on_body, &b);
if (pic_http_get(net, url, headers, nh, &r, 10, 20, herr, sizeof herr) != 0) {
(void)snprintf(err, errcap, "%s: %s", url, herr);
} else if (sqlite3_open(":memory:", &db) != SQLITE_OK) {
(void)snprintf(err, errcap, "out of memory");
} else if (r.status != 200) {
ep_reason(db, b.buf, reason, sizeof reason);
(void)snprintf(err, errcap, "%s answered HTTP %d%s", url, r.status, reason);
if (r.status == 401 && got == 0 && pic_endpoint_basic_user(name, NULL, 0)) {
size_t used = strlen(err);
(void)snprintf(err + used, errcap - used,
" (the endpoint refused its user and password: pic endpoints add %s %s --basic sets them again)", name,
base);
}
} else if (b.too_big || !b.buf || !(list = ep_list(db, b.buf))) {
(void)snprintf(err, errcap, "%s did not answer with a model list (OpenAI's {\"data\":[{\"id\":...}]})", url);
} else if (pic_endpoint_note(name, list, NULL) != 0) {
(void)snprintf(err, errcap, "cannot save the list in ~/.pic/pic.sqlite");
} else {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(db, "SELECT json_array_length(?1)", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, list, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
*count = sqlite3_column_int(q, 0);
}
}
sqlite3_finalize(q);
rc = 0;
}
pic_net_free(net);
done:
if (got == 0) {
pic_cred_scrub(err, key);
}
pic_cred_wipe(key, sizeof key);
pic_cred_wipe(auth, sizeof auth);
if (rc != 0) {
(void)pic_endpoint_note(name, NULL, err);
}
free(list);
free(b.buf);
sqlite3_close(db);
return rc;
}
int pic_endpoint_add(const char *name, const char *url, const char *user, const char *key, int *count, char *err,
size_t errcap) {
char norm[PIC_ENDPOINT_URL_CAP], joined[PIC_CRED_KEY_CAP + 1];
*count = 0;
if (pic_endpoint_name_check(name, err, errcap) != 0 || pic_endpoint_url_check(url, norm, sizeof norm, err, errcap) != 0) {
return -1;
}
if (user && (!key || pic_endpoint_basic_check(user, key, err, errcap) != 0)) {
if (!key) {
(void)snprintf(err, errcap, "the password is empty");
}
return -1;
}
if (user) {
(void)snprintf(joined, sizeof joined, "%s:%s", user, key);
key = joined;
}
if (key && (user ? pic_cred_login_exact(name, key, err, errcap) : pic_cred_login(name, key, err, errcap)) != 0) {
pic_cred_wipe(joined, sizeof joined);
return -1;
}
pic_cred_wipe(joined, sizeof joined);
if (pic_endpoint_save(name, norm, err, errcap) != 0) {
return -1;
}
if (key && pic_endpoint_basic_set(name, user) != 0) {
(void)snprintf(err, errcap, "cannot save the endpoint in ~/.pic/pic.sqlite");
return -1;
}
return pic_endpoint_refresh(name, count, err, errcap) == 0 ? 0 : 1;
}
/* ---- the RPC commands ------------------------------------------------------ */
static int ep_done(pic_rpc_call *c, sqlite3_str *t) {
char *res = sqlite3_str_finish(t);
c->data = res ? strdup(res) : NULL;
sqlite3_free(res);
return c->data ? 0 : -1;
}
static int ep_row(void *ctx, const pic_endpoint *e) {
sqlite3_str *t = ctx;
if (sqlite3_str_length(t) > 14) {
sqlite3_str_appendall(t, ",");
}
sqlite3_str_appendall(t, "{\"name\":");
pic_rpc_quote(t, e->name);
sqlite3_str_appendall(t, ",\"url\":");
pic_rpc_quote(t, e->url);
sqlite3_str_appendf(t, ",\"hasKey\":%s,\"models\":%s,\"fetchedAt\":", pic_cred_stored(e->name) ? "true" : "false",
e->models);
if (e->fetched_ms) {
sqlite3_str_appendf(t, "%lld", e->fetched_ms);
} else {
sqlite3_str_appendall(t, "null");
}
sqlite3_str_appendall(t, ",\"error\":");
if (e->error) {
pic_rpc_quote(t, e->error);
} else {
sqlite3_str_appendall(t, "null");
}
sqlite3_str_appendall(t, "}");
return 0;
}
/* get_endpoints: {"endpoints": [{name, url, hasKey, models: [{id, owned_by}], fetchedAt, error}]}. */
static int ep_get_answer(pic_rpc_call *c) {
sqlite3_str *t = sqlite3_str_new(NULL);
sqlite3_str_appendall(t, "{\"endpoints\":[");
if (pic_endpoints_each(ep_row, t) != 0) {
sqlite3_free(sqlite3_str_finish(t));
(void)snprintf(c->err, sizeof c->err, "cannot read ~/.pic/pic.sqlite");
return -1;
}
sqlite3_str_appendall(t, "]}");
return ep_done(c, t);
}
/* {"name", "count"} after a fetch that worked; an error otherwise. */
static int ep_counted(pic_rpc_call *c, const char *name, int count) {
sqlite3_str *t = sqlite3_str_new(NULL);
sqlite3_str_appendall(t, "{\"name\":");
pic_rpc_quote(t, name);
sqlite3_str_appendf(t, ",\"count\":%d}", count);
return ep_done(c, t);
}
/* add_endpoint name url [key]: saved, then its list fetched. A failed fetch keeps the endpoint
* and answers {"name", "count": 0, "error"}. */
static int ep_add_answer(pic_rpc_call *c) {
char *name = pic_rpc_text(c, "$.name"), *url = pic_rpc_text(c, "$.url"), *key = pic_rpc_text(c, "$.key"),
*user = pic_rpc_text(c, "$.user"), *pass = pic_rpc_text(c, "$.password");
int count = 0, rc = -1, got;
if (!name || !url) {
(void)snprintf(c->err, sizeof c->err, "add_endpoint needs name and url");
} else if (user && *user && !(pass && *pass)) {
(void)snprintf(c->err, sizeof c->err, "add_endpoint with a user needs its password");
} else if ((got = pic_endpoint_add(name, url, user && *user ? user : NULL, user && *user ? pass : key && *key ? key : NULL,
&count, c->err, sizeof c->err)) == 0) {
rc = ep_counted(c, name, count);
} else if (got == 1) {
sqlite3_str *t = sqlite3_str_new(NULL);
sqlite3_str_appendall(t, "{\"name\":");
pic_rpc_quote(t, name);
sqlite3_str_appendall(t, ",\"count\":0,\"error\":");
pic_rpc_quote(t, c->err);
sqlite3_str_appendall(t, "}");
c->err[0] = '\0';
rc = ep_done(c, t);
}
if (key) {
pic_cred_wipe(key, strlen(key));
}
if (pass) {
pic_cred_wipe(pass, strlen(pass));
}
free(name);
free(url);
free(key);
free(user);
free(pass);
return rc;
}
/* remove_endpoint name: {"removed": true|false}; its stored key goes with it. */
static int ep_remove_answer(pic_rpc_call *c) {
char *name = pic_rpc_text(c, "$.name");
int named = name != NULL, r = named ? pic_endpoint_remove(name) : -1;
free(name);
if (r < 0) {
(void)snprintf(c->err, sizeof c->err, named ? "cannot remove the endpoint from ~/.pic/pic.sqlite"
: "remove_endpoint needs name");
return -1;
}
c->data = strdup(r ? "{\"removed\":true}" : "{\"removed\":false}");
return c->data ? 0 : -1;
}
typedef struct {
char **names;
size_t n;
} ep_names;
static int ep_collect(void *ctx, const pic_endpoint *e) {
ep_names *l = ctx;
char **grown = realloc(l->names, (l->n + 1) * sizeof *grown);
if (!grown) {
return 1;
}
l->names = grown;
if ((l->names[l->n] = strdup(e->name))) {
l->n++;
}
return 0;
}
/* refresh_endpoints [name]: each (or that) endpoint's list fetched again; {"endpoints":
* [{name, count, error}]}, error null for each that worked. */
static int ep_refresh_answer(pic_rpc_call *c) {
char *name = pic_rpc_text(c, "$.name");
ep_names l = {NULL, 0};
sqlite3_str *t;
if (name) {
(void)ep_collect(&l, &(pic_endpoint){.name = name});
} else {
(void)pic_endpoints_each(ep_collect, &l);
}
free(name);
t = sqlite3_str_new(NULL);
sqlite3_str_appendall(t, "{\"endpoints\":[");
for (size_t i = 0; i < l.n; i++) {
char err[PIC_ERR_CAP];
int count = 0, rc = pic_endpoint_refresh(l.names[i], &count, err, sizeof err);
sqlite3_str_appendall(t, i ? ",{\"name\":" : "{\"name\":");
pic_rpc_quote(t, l.names[i]);
sqlite3_str_appendf(t, ",\"count\":%d,\"error\":", count);
if (rc == 0) {
sqlite3_str_appendall(t, "null");
} else {
pic_rpc_quote(t, err);
}
sqlite3_str_appendall(t, "}");
free(l.names[i]);
}
free(l.names);
sqlite3_str_appendall(t, "]}");
return ep_done(c, t);
}
#define EP_FLAGS (PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE)
const pic_rpc_command pic_get_endpoints_rpc = {"get_endpoints", "the saved model endpoints and their lists", EP_FLAGS,
ep_get_answer};
const pic_rpc_command pic_add_endpoint_rpc = {"add_endpoint", "save a model endpoint and fetch its list", EP_FLAGS,
ep_add_answer};
const pic_rpc_command pic_remove_endpoint_rpc = {"remove_endpoint", "forget a model endpoint and its key", EP_FLAGS,
ep_remove_answer};
const pic_rpc_command pic_refresh_endpoints_rpc = {"refresh_endpoints", "fetch the endpoints' lists again", EP_FLAGS,
ep_refresh_answer};