#include "system.h"
#include "meshlink_internal.h"
+#include "protocol.h"
+#include "xalloc.h"
static const char *errstr[] = {
[MESHLINK_OK] = "No error",
return errstr[errno];
}
+static meshlink_handle_t *meshlink_setup(meshlink_handle_t *mesh) {
+ return mesh;
+}
+
meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
- return NULL;
+ if(!confbase || !*confbase) {
+ fprintf(stderr, "No confbase given!\n");
+ return NULL;
+ }
+
+ if(!name || !*name) {
+ fprintf(stderr, "No name given!\n");
+ return NULL;
+ }
+
+ if(!check_id(name)) {
+ fprintf(stderr, "Invalid name given!\n");
+ return NULL;
+ }
+
+ meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
+ mesh->confbase = xstrdup(confbase);
+ mesh->name = xstrdup(name);
+
+ char filename[PATH_MAX];
+ snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
+
+ FILE *f = fopen(filename, "r");
+
+ if(!f && errno == ENOENT)
+ return meshlink_setup(mesh);
+
+ if(!f) {
+ fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
+ return meshlink_close(mesh), NULL;
+ }
+
+ char buf[1024] = "";
+ if(!fgets(buf, sizeof buf, f)) {
+ fprintf(stderr, "Could not read line from %s: %s\n", filename, strerror(errno));
+ fclose(f);
+ return meshlink_close(mesh), NULL;
+ }
+
+ fclose(f);
+
+ size_t len = strlen(buf);
+ if(len && buf[len - 1] == '\n')
+ buf[--len] = 0;
+ if(len && buf[len - 1] == '\r')
+ buf[--len] = 0;
+
+ if(strncmp(buf, "Name = ", 7) || !check_id(buf + 7)) {
+ fprintf(stderr, "Could not read Name from %s\n", filename);
+ return meshlink_close(mesh), NULL;
+ }
+
+ if(strcmp(buf + 7, name)) {
+ fprintf(stderr, "Name in %s is %s, not the same as %s\n", filename, buf + 7, name);
+ free(mesh->name);
+ mesh->name = xstrdup(buf + 7);
+ }
+
+ snprintf(filename, sizeof filename, "%s" SLASH "ed25519_key.priv", mesh->confbase);
+ f = fopen(filename, "r");
+ if(!f) {
+ fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
+ return meshlink_close(mesh), NULL;
+ }
+
+ mesh->self->ecdsa = ecdsa_read_pem_private_key(f);
+ fclose(f);
+
+ if(!mesh->self->ecdsa) {
+ fprintf(stderr, "Could not read keypair!\n");
+ return meshlink_close(mesh), NULL;
+ }
+
+ return mesh;
}
bool meshlink_start(meshlink_handle_t *mesh) {