v0.1.12 - Successfully integrated websocket client, and program connects to relays and publishes kinds 0 and 10002
This commit is contained in:
@@ -1,541 +0,0 @@
|
||||
/*
|
||||
* Ginxsom Admin WebSocket Server
|
||||
* Handles WebSocket connections for Kind 23456/23457 admin commands
|
||||
* Based on c-relay's WebSocket implementation using libwebsockets
|
||||
*/
|
||||
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <cjson/cJSON.h>
|
||||
#include <sqlite3.h>
|
||||
#include <libwebsockets.h>
|
||||
#include "ginxsom.h"
|
||||
|
||||
// Forward declarations from admin_event.c
|
||||
extern char g_db_path[];
|
||||
extern int nostr_hex_to_bytes(const char* hex, unsigned char* bytes, size_t bytes_len);
|
||||
extern int nostr_nip44_decrypt(const unsigned char* recipient_private_key,
|
||||
const unsigned char* sender_public_key,
|
||||
const char* encrypted_data,
|
||||
char* output,
|
||||
size_t output_size);
|
||||
extern int nostr_nip44_encrypt(const unsigned char* sender_private_key,
|
||||
const unsigned char* recipient_public_key,
|
||||
const char* plaintext,
|
||||
char* output,
|
||||
size_t output_size);
|
||||
extern cJSON* nostr_create_and_sign_event(int kind, const char* content, cJSON* tags,
|
||||
const unsigned char* private_key, time_t created_at);
|
||||
|
||||
// Per-session data for each WebSocket connection
|
||||
struct per_session_data {
|
||||
char admin_pubkey[65];
|
||||
int authenticated;
|
||||
unsigned char pending_response[LWS_PRE + 131072];
|
||||
size_t pending_response_len;
|
||||
};
|
||||
|
||||
// Global WebSocket context
|
||||
static struct lws_context *ws_context = NULL;
|
||||
static volatile int force_exit = 0;
|
||||
|
||||
// Function prototypes
|
||||
static int get_server_privkey(unsigned char* privkey_bytes);
|
||||
static int get_server_pubkey(char* pubkey_hex, size_t size);
|
||||
static int handle_config_query_command(cJSON* response_data);
|
||||
static int process_admin_event(struct lws *wsi, struct per_session_data *pss, const char *json_str);
|
||||
|
||||
/**
|
||||
* WebSocket protocol callback
|
||||
*/
|
||||
static int callback_admin_protocol(struct lws *wsi, enum lws_callback_reasons reason,
|
||||
void *user, void *in, size_t len) {
|
||||
struct per_session_data *pss = (struct per_session_data *)user;
|
||||
|
||||
switch (reason) {
|
||||
case LWS_CALLBACK_ESTABLISHED:
|
||||
fprintf(stderr, "[WebSocket] New connection established\n");
|
||||
fflush(stderr);
|
||||
memset(pss, 0, sizeof(*pss));
|
||||
pss->authenticated = 0;
|
||||
break;
|
||||
|
||||
case LWS_CALLBACK_RECEIVE:
|
||||
fprintf(stderr, "[WebSocket] Received %zu bytes\n", len);
|
||||
fflush(stderr);
|
||||
|
||||
// Null-terminate the received data
|
||||
char *json_str = malloc(len + 1);
|
||||
if (!json_str) {
|
||||
fprintf(stderr, "[WebSocket] Memory allocation failed\n");
|
||||
fflush(stderr);
|
||||
return -1;
|
||||
}
|
||||
memcpy(json_str, in, len);
|
||||
json_str[len] = '\0';
|
||||
|
||||
// Process the admin event
|
||||
int result = process_admin_event(wsi, pss, json_str);
|
||||
free(json_str);
|
||||
|
||||
if (result == 0 && pss->pending_response_len > 0) {
|
||||
// Request callback to send response
|
||||
lws_callback_on_writable(wsi);
|
||||
}
|
||||
break;
|
||||
|
||||
case LWS_CALLBACK_SERVER_WRITEABLE:
|
||||
if (pss->pending_response_len > 0) {
|
||||
fprintf(stderr, "[WebSocket] Sending %zu bytes\n", pss->pending_response_len - LWS_PRE);
|
||||
fflush(stderr);
|
||||
|
||||
int written = lws_write(wsi,
|
||||
&pss->pending_response[LWS_PRE],
|
||||
pss->pending_response_len - LWS_PRE,
|
||||
LWS_WRITE_TEXT);
|
||||
|
||||
if (written < 0) {
|
||||
fprintf(stderr, "[WebSocket] Write failed\n");
|
||||
fflush(stderr);
|
||||
return -1;
|
||||
}
|
||||
|
||||
pss->pending_response_len = 0;
|
||||
}
|
||||
break;
|
||||
|
||||
case LWS_CALLBACK_CLOSED:
|
||||
fprintf(stderr, "[WebSocket] Connection closed\n");
|
||||
fflush(stderr);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* WebSocket protocols
|
||||
*/
|
||||
static struct lws_protocols protocols[] = {
|
||||
{
|
||||
"nostr-admin",
|
||||
callback_admin_protocol,
|
||||
sizeof(struct per_session_data),
|
||||
131072, // rx buffer size
|
||||
0, NULL, 0
|
||||
},
|
||||
{ NULL, NULL, 0, 0, 0, NULL, 0 } // terminator
|
||||
};
|
||||
|
||||
/**
|
||||
* Process Kind 23456 admin event received via WebSocket
|
||||
*/
|
||||
static int process_admin_event(struct lws *wsi __attribute__((unused)), struct per_session_data *pss, const char *json_str) {
|
||||
// Parse event JSON
|
||||
cJSON *event = cJSON_Parse(json_str);
|
||||
if (!event) {
|
||||
fprintf(stderr, "[WebSocket] Invalid JSON\n");
|
||||
fflush(stderr);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Verify it's Kind 23456
|
||||
cJSON *kind_obj = cJSON_GetObjectItem(event, "kind");
|
||||
if (!kind_obj || !cJSON_IsNumber(kind_obj) ||
|
||||
(int)cJSON_GetNumberValue(kind_obj) != 23456) {
|
||||
fprintf(stderr, "[WebSocket] Not a Kind 23456 event\n");
|
||||
fflush(stderr);
|
||||
cJSON_Delete(event);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Get event ID for response correlation
|
||||
cJSON *id_obj = cJSON_GetObjectItem(event, "id");
|
||||
if (!id_obj || !cJSON_IsString(id_obj)) {
|
||||
fprintf(stderr, "[WebSocket] Event missing id\n");
|
||||
fflush(stderr);
|
||||
cJSON_Delete(event);
|
||||
return -1;
|
||||
}
|
||||
const char *request_id = cJSON_GetStringValue(id_obj);
|
||||
|
||||
// Get admin pubkey from event
|
||||
cJSON *pubkey_obj = cJSON_GetObjectItem(event, "pubkey");
|
||||
if (!pubkey_obj || !cJSON_IsString(pubkey_obj)) {
|
||||
fprintf(stderr, "[WebSocket] Event missing pubkey\n");
|
||||
fflush(stderr);
|
||||
cJSON_Delete(event);
|
||||
return -1;
|
||||
}
|
||||
const char *admin_pubkey = cJSON_GetStringValue(pubkey_obj);
|
||||
|
||||
// Verify admin pubkey
|
||||
if (!verify_admin_pubkey(admin_pubkey)) {
|
||||
fprintf(stderr, "[WebSocket] Not authorized as admin: %s\n", admin_pubkey);
|
||||
fflush(stderr);
|
||||
cJSON_Delete(event);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Store admin pubkey in session
|
||||
strncpy(pss->admin_pubkey, admin_pubkey, sizeof(pss->admin_pubkey) - 1);
|
||||
pss->authenticated = 1;
|
||||
|
||||
// Get encrypted content
|
||||
cJSON *content_obj = cJSON_GetObjectItem(event, "content");
|
||||
if (!content_obj || !cJSON_IsString(content_obj)) {
|
||||
fprintf(stderr, "[WebSocket] Event missing content\n");
|
||||
fflush(stderr);
|
||||
cJSON_Delete(event);
|
||||
return -1;
|
||||
}
|
||||
const char *encrypted_content = cJSON_GetStringValue(content_obj);
|
||||
|
||||
// Get server private key for decryption
|
||||
unsigned char server_privkey[32];
|
||||
if (get_server_privkey(server_privkey) != 0) {
|
||||
fprintf(stderr, "[WebSocket] Failed to get server private key\n");
|
||||
fflush(stderr);
|
||||
cJSON_Delete(event);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Convert admin pubkey to bytes
|
||||
unsigned char admin_pubkey_bytes[32];
|
||||
if (nostr_hex_to_bytes(admin_pubkey, admin_pubkey_bytes, 32) != 0) {
|
||||
fprintf(stderr, "[WebSocket] Invalid admin pubkey format\n");
|
||||
fflush(stderr);
|
||||
cJSON_Delete(event);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Decrypt content using NIP-44
|
||||
char decrypted_content[8192];
|
||||
const char *content_to_parse = encrypted_content;
|
||||
|
||||
// Check if content is already plaintext JSON (starts with '[')
|
||||
if (encrypted_content[0] != '[') {
|
||||
int decrypt_result = nostr_nip44_decrypt(
|
||||
server_privkey,
|
||||
admin_pubkey_bytes,
|
||||
encrypted_content,
|
||||
decrypted_content,
|
||||
sizeof(decrypted_content)
|
||||
);
|
||||
|
||||
if (decrypt_result != 0) {
|
||||
fprintf(stderr, "[WebSocket] Failed to decrypt content\n");
|
||||
fflush(stderr);
|
||||
cJSON_Delete(event);
|
||||
return -1;
|
||||
}
|
||||
content_to_parse = decrypted_content;
|
||||
}
|
||||
|
||||
// Parse command array
|
||||
cJSON *command_array = cJSON_Parse(content_to_parse);
|
||||
if (!command_array || !cJSON_IsArray(command_array)) {
|
||||
fprintf(stderr, "[WebSocket] Decrypted content is not a valid command array\n");
|
||||
fflush(stderr);
|
||||
cJSON_Delete(event);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Get command type
|
||||
cJSON *command_type = cJSON_GetArrayItem(command_array, 0);
|
||||
if (!command_type || !cJSON_IsString(command_type)) {
|
||||
fprintf(stderr, "[WebSocket] Invalid command format\n");
|
||||
fflush(stderr);
|
||||
cJSON_Delete(command_array);
|
||||
cJSON_Delete(event);
|
||||
return -1;
|
||||
}
|
||||
|
||||
const char *cmd = cJSON_GetStringValue(command_type);
|
||||
fprintf(stderr, "[WebSocket] Processing command: %s\n", cmd);
|
||||
fflush(stderr);
|
||||
|
||||
// Create response data object
|
||||
cJSON *response_data = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(response_data, "query_type", cmd);
|
||||
cJSON_AddNumberToObject(response_data, "timestamp", (double)time(NULL));
|
||||
|
||||
// Handle command
|
||||
int result = -1;
|
||||
if (strcmp(cmd, "config_query") == 0) {
|
||||
result = handle_config_query_command(response_data);
|
||||
} else {
|
||||
cJSON_AddStringToObject(response_data, "status", "error");
|
||||
cJSON_AddStringToObject(response_data, "error", "Unknown command");
|
||||
}
|
||||
|
||||
cJSON_Delete(command_array);
|
||||
cJSON_Delete(event);
|
||||
|
||||
if (result == 0) {
|
||||
// Get server keys
|
||||
char server_pubkey[65];
|
||||
if (get_server_pubkey(server_pubkey, sizeof(server_pubkey)) != 0) {
|
||||
fprintf(stderr, "[WebSocket] Failed to get server pubkey\n");
|
||||
fflush(stderr);
|
||||
cJSON_Delete(response_data);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Convert response data to JSON string
|
||||
char *response_json = cJSON_PrintUnformatted(response_data);
|
||||
cJSON_Delete(response_data);
|
||||
|
||||
if (!response_json) {
|
||||
fprintf(stderr, "[WebSocket] Failed to serialize response\n");
|
||||
fflush(stderr);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Encrypt response using NIP-44
|
||||
char encrypted_response[131072];
|
||||
int encrypt_result = nostr_nip44_encrypt(
|
||||
server_privkey,
|
||||
admin_pubkey_bytes,
|
||||
response_json,
|
||||
encrypted_response,
|
||||
sizeof(encrypted_response)
|
||||
);
|
||||
|
||||
free(response_json);
|
||||
|
||||
if (encrypt_result != 0) {
|
||||
fprintf(stderr, "[WebSocket] Failed to encrypt response\n");
|
||||
fflush(stderr);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Create Kind 23457 response event
|
||||
cJSON *tags = cJSON_CreateArray();
|
||||
|
||||
// p tag for admin
|
||||
cJSON *p_tag = cJSON_CreateArray();
|
||||
cJSON_AddItemToArray(p_tag, cJSON_CreateString("p"));
|
||||
cJSON_AddItemToArray(p_tag, cJSON_CreateString(admin_pubkey));
|
||||
cJSON_AddItemToArray(tags, p_tag);
|
||||
|
||||
// e tag for request correlation
|
||||
cJSON *e_tag = cJSON_CreateArray();
|
||||
cJSON_AddItemToArray(e_tag, cJSON_CreateString("e"));
|
||||
cJSON_AddItemToArray(e_tag, cJSON_CreateString(request_id));
|
||||
cJSON_AddItemToArray(tags, e_tag);
|
||||
|
||||
// Sign the event
|
||||
cJSON *signed_event = nostr_create_and_sign_event(
|
||||
23457,
|
||||
encrypted_response,
|
||||
tags,
|
||||
server_privkey,
|
||||
time(NULL)
|
||||
);
|
||||
|
||||
if (!signed_event) {
|
||||
fprintf(stderr, "[WebSocket] Failed to sign response event\n");
|
||||
fflush(stderr);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Serialize event to JSON
|
||||
char *event_json = cJSON_PrintUnformatted(signed_event);
|
||||
cJSON_Delete(signed_event);
|
||||
|
||||
if (!event_json) {
|
||||
fprintf(stderr, "[WebSocket] Failed to serialize event\n");
|
||||
fflush(stderr);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Store response in session for sending
|
||||
size_t json_len = strlen(event_json);
|
||||
if (json_len + LWS_PRE < sizeof(pss->pending_response)) {
|
||||
memcpy(&pss->pending_response[LWS_PRE], event_json, json_len);
|
||||
pss->pending_response_len = LWS_PRE + json_len;
|
||||
fprintf(stderr, "[WebSocket] Response prepared (%zu bytes)\n", json_len);
|
||||
fflush(stderr);
|
||||
} else {
|
||||
fprintf(stderr, "[WebSocket] Response too large\n");
|
||||
fflush(stderr);
|
||||
}
|
||||
|
||||
free(event_json);
|
||||
return 0;
|
||||
} else {
|
||||
cJSON_Delete(response_data);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get server private key from database
|
||||
*/
|
||||
static int get_server_privkey(unsigned char* privkey_bytes) {
|
||||
sqlite3 *db;
|
||||
int rc = sqlite3_open_v2(g_db_path, &db, SQLITE_OPEN_READONLY, NULL);
|
||||
if (rc != SQLITE_OK) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
sqlite3_stmt *stmt;
|
||||
const char *sql = "SELECT seckey FROM blossom_seckey LIMIT 1";
|
||||
int result = -1;
|
||||
|
||||
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
|
||||
if (sqlite3_step(stmt) == SQLITE_ROW) {
|
||||
const char *privkey_hex = (const char*)sqlite3_column_text(stmt, 0);
|
||||
if (privkey_hex && nostr_hex_to_bytes(privkey_hex, privkey_bytes, 32) == 0) {
|
||||
result = 0;
|
||||
}
|
||||
}
|
||||
sqlite3_finalize(stmt);
|
||||
}
|
||||
sqlite3_close(db);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get server public key from database
|
||||
*/
|
||||
static int get_server_pubkey(char* pubkey_hex, size_t size) {
|
||||
sqlite3 *db;
|
||||
int rc = sqlite3_open_v2(g_db_path, &db, SQLITE_OPEN_READONLY, NULL);
|
||||
if (rc != SQLITE_OK) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
sqlite3_stmt *stmt;
|
||||
const char *sql = "SELECT value FROM config WHERE key = 'blossom_pubkey'";
|
||||
int result = -1;
|
||||
|
||||
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
|
||||
if (sqlite3_step(stmt) == SQLITE_ROW) {
|
||||
const char *pubkey = (const char*)sqlite3_column_text(stmt, 0);
|
||||
if (pubkey) {
|
||||
strncpy(pubkey_hex, pubkey, size - 1);
|
||||
pubkey_hex[size - 1] = '\0';
|
||||
result = 0;
|
||||
}
|
||||
}
|
||||
sqlite3_finalize(stmt);
|
||||
}
|
||||
sqlite3_close(db);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle config_query command
|
||||
*/
|
||||
static int handle_config_query_command(cJSON* response_data) {
|
||||
sqlite3 *db;
|
||||
int rc = sqlite3_open_v2(g_db_path, &db, SQLITE_OPEN_READONLY, NULL);
|
||||
if (rc != SQLITE_OK) {
|
||||
cJSON_AddStringToObject(response_data, "status", "error");
|
||||
cJSON_AddStringToObject(response_data, "error", "Database error");
|
||||
return -1;
|
||||
}
|
||||
|
||||
cJSON_AddStringToObject(response_data, "status", "success");
|
||||
cJSON *data = cJSON_CreateObject();
|
||||
|
||||
// Query all config settings
|
||||
sqlite3_stmt *stmt;
|
||||
const char *sql = "SELECT key, value FROM config ORDER BY key";
|
||||
|
||||
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
|
||||
while (sqlite3_step(stmt) == SQLITE_ROW) {
|
||||
const char *key = (const char*)sqlite3_column_text(stmt, 0);
|
||||
const char *value = (const char*)sqlite3_column_text(stmt, 1);
|
||||
if (key && value) {
|
||||
cJSON_AddStringToObject(data, key, value);
|
||||
}
|
||||
}
|
||||
sqlite3_finalize(stmt);
|
||||
}
|
||||
|
||||
cJSON_AddItemToObject(response_data, "data", data);
|
||||
sqlite3_close(db);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* WebSocket server thread
|
||||
*/
|
||||
void* admin_websocket_thread(void* arg) {
|
||||
int port = *(int*)arg;
|
||||
|
||||
struct lws_context_creation_info info;
|
||||
memset(&info, 0, sizeof(info));
|
||||
|
||||
info.port = port;
|
||||
info.iface = "127.0.0.1"; // Force IPv4 binding for localhost compatibility
|
||||
info.protocols = protocols;
|
||||
info.gid = -1;
|
||||
info.uid = -1;
|
||||
info.options = LWS_SERVER_OPTION_VALIDATE_UTF8 | LWS_SERVER_OPTION_DISABLE_IPV6;
|
||||
|
||||
fprintf(stderr, "[WebSocket] Starting admin WebSocket server on 127.0.0.1:%d (IPv4 only)\n", port);
|
||||
fflush(stderr);
|
||||
|
||||
ws_context = lws_create_context(&info);
|
||||
if (!ws_context) {
|
||||
fprintf(stderr, "[WebSocket] Failed to create context\n");
|
||||
fflush(stderr);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
fprintf(stderr, "[WebSocket] Server started successfully\n");
|
||||
fflush(stderr);
|
||||
|
||||
// Service loop
|
||||
while (!force_exit) {
|
||||
lws_service(ws_context, 50);
|
||||
}
|
||||
|
||||
lws_context_destroy(ws_context);
|
||||
fprintf(stderr, "[WebSocket] Server stopped\n");
|
||||
fflush(stderr);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start admin WebSocket server
|
||||
*/
|
||||
int start_admin_websocket_server(int port) {
|
||||
static int server_port;
|
||||
server_port = port;
|
||||
|
||||
pthread_t thread;
|
||||
int result = pthread_create(&thread, NULL, admin_websocket_thread, &server_port);
|
||||
if (result != 0) {
|
||||
fprintf(stderr, "[WebSocket] Failed to create thread: %d\n", result);
|
||||
fflush(stderr);
|
||||
return -1;
|
||||
}
|
||||
|
||||
pthread_detach(thread);
|
||||
fprintf(stderr, "[WebSocket] Thread started\n");
|
||||
fflush(stderr);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop admin WebSocket server
|
||||
*/
|
||||
void stop_admin_websocket_server(void) {
|
||||
force_exit = 1;
|
||||
}
|
||||
@@ -10,8 +10,8 @@
|
||||
// Version information (auto-updated by build system)
|
||||
#define VERSION_MAJOR 0
|
||||
#define VERSION_MINOR 1
|
||||
#define VERSION_PATCH 11
|
||||
#define VERSION "v0.1.11"
|
||||
#define VERSION_PATCH 12
|
||||
#define VERSION "v0.1.12"
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
@@ -250,6 +250,16 @@ void send_json_response(int status_code, const char* json_content);
|
||||
// Logging utilities
|
||||
void log_request(const char* method, const char* uri, const char* auth_status, int status_code);
|
||||
|
||||
// Centralized application logging (writes to logs/app/app.log)
|
||||
typedef enum {
|
||||
LOG_DEBUG = 0,
|
||||
LOG_INFO = 1,
|
||||
LOG_WARN = 2,
|
||||
LOG_ERROR = 3
|
||||
} log_level_t;
|
||||
|
||||
void app_log(log_level_t level, const char* format, ...);
|
||||
|
||||
// SHA-256 validation helper (used by multiple BUDs)
|
||||
int validate_sha256_format(const char* sha256);
|
||||
|
||||
@@ -283,10 +293,6 @@ void send_json_response(int status, const char* json_content);
|
||||
void send_json_error(int status, const char* error, const char* message);
|
||||
int parse_query_params(const char* query_string, char params[][256], int max_params);
|
||||
|
||||
// Admin WebSocket server functions
|
||||
int start_admin_websocket_server(int port);
|
||||
void stop_admin_websocket_server(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
177
src/main.c
177
src/main.c
@@ -5,11 +5,13 @@
|
||||
|
||||
#define _GNU_SOURCE
|
||||
#include "ginxsom.h"
|
||||
#include "relay_client.h"
|
||||
#include "../nostr_core_lib/nostr_core/nostr_common.h"
|
||||
#include "../nostr_core_lib/nostr_core/utils.h"
|
||||
#include <getopt.h>
|
||||
#include <curl/curl.h>
|
||||
#include <sqlite3.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -19,7 +21,43 @@
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// Debug macros removed
|
||||
// Centralized logging system (declaration in ginxsom.h)
|
||||
void app_log(log_level_t level, const char *format, ...) {
|
||||
FILE *log_file = fopen("logs/app/app.log", "a");
|
||||
if (!log_file) {
|
||||
return; // Silently fail if we can't open log file
|
||||
}
|
||||
|
||||
// Get timestamp
|
||||
time_t now = time(NULL);
|
||||
struct tm *tm_info = localtime(&now);
|
||||
char timestamp[64];
|
||||
strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", tm_info);
|
||||
|
||||
// Get log level string
|
||||
const char *level_str;
|
||||
switch (level) {
|
||||
case LOG_DEBUG: level_str = "DEBUG"; break;
|
||||
case LOG_INFO: level_str = "INFO"; break;
|
||||
case LOG_WARN: level_str = "WARN"; break;
|
||||
case LOG_ERROR: level_str = "ERROR"; break;
|
||||
default: level_str = "UNKNOWN"; break;
|
||||
}
|
||||
|
||||
// Write log prefix with timestamp, PID, and level
|
||||
fprintf(log_file, "[%s] [PID:%d] [%s] ", timestamp, getpid(), level_str);
|
||||
|
||||
// Write formatted message
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
vfprintf(log_file, format, args);
|
||||
va_end(args);
|
||||
|
||||
// Ensure newline
|
||||
fprintf(log_file, "\n");
|
||||
|
||||
fclose(log_file);
|
||||
}
|
||||
|
||||
#define MAX_SHA256_LEN 65
|
||||
#define MAX_PATH_LEN 4096
|
||||
@@ -196,7 +234,10 @@ int initialize_database(const char *db_path) {
|
||||
" ('admin_enabled', 'true', 'Whether admin API is enabled'),"
|
||||
" ('nip42_require_auth', 'false', 'Enable NIP-42 challenge/response authentication'),"
|
||||
" ('nip42_challenge_timeout', '600', 'NIP-42 challenge timeout in seconds'),"
|
||||
" ('nip42_time_tolerance', '300', 'NIP-42 timestamp tolerance in seconds');";
|
||||
" ('nip42_time_tolerance', '300', 'NIP-42 timestamp tolerance in seconds'),"
|
||||
" ('enable_relay_connect', 'true', 'Enable connection to Nostr relays'),"
|
||||
" ('kind_0_content', '{\"name\":\"Ginxsom Blossom Server\",\"about\":\"A Nostr-enabled Blossom media server\",\"picture\":\"\"}', 'JSON content for Kind 0 profile event'),"
|
||||
" ('kind_10002_tags', '[\"wss://relay.laantungir.net\"]', 'JSON array of relay URLs for Kind 10002');";
|
||||
|
||||
rc = sqlite3_exec(db, insert_config, NULL, NULL, &err_msg);
|
||||
if (rc != SQLITE_OK) {
|
||||
@@ -1830,18 +1871,9 @@ void handle_auth_challenge_request(void) {
|
||||
/////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
// Redirect stderr to log file BEFORE any other operations
|
||||
// This is necessary because spawn-fcgi doesn't preserve stderr redirections
|
||||
FILE *stderr_log = freopen("logs/app/stderr.log", "a", stderr);
|
||||
if (!stderr_log) {
|
||||
// If redirection fails, continue anyway but log to original stderr
|
||||
perror("Warning: Failed to redirect stderr to log file");
|
||||
}
|
||||
|
||||
// Set stderr to unbuffered mode so all fprintf(stderr, ...) calls flush immediately
|
||||
setvbuf(stderr, NULL, _IONBF, 0);
|
||||
|
||||
fprintf(stderr, "DEBUG: main() started\n");
|
||||
// Initialize application logging
|
||||
app_log(LOG_INFO, "=== Ginxsom FastCGI Application Starting ===");
|
||||
app_log(LOG_INFO, "Process ID: %d", getpid());
|
||||
|
||||
// Parse command line arguments
|
||||
int use_test_keys = 0;
|
||||
@@ -1901,17 +1933,16 @@ int main(int argc, char *argv[]) {
|
||||
}
|
||||
}
|
||||
|
||||
fprintf(stderr, "STARTUP: Using storage directory: %s\n", g_storage_dir);
|
||||
app_log(LOG_INFO, "Storage directory: %s", g_storage_dir);
|
||||
|
||||
// CRITICAL: Initialize nostr crypto system BEFORE key operations
|
||||
fprintf(stderr, "STARTUP: Initializing nostr crypto system...\r\n");
|
||||
app_log(LOG_INFO, "Initializing nostr crypto system...");
|
||||
int crypto_init_result = nostr_crypto_init();
|
||||
fprintf(stderr, "CRYPTO INIT RESULT: %d\r\n", crypto_init_result);
|
||||
if (crypto_init_result != 0) {
|
||||
fprintf(stderr, "FATAL ERROR: Failed to initialize nostr crypto system\r\n");
|
||||
app_log(LOG_ERROR, "Failed to initialize nostr crypto system (result: %d)", crypto_init_result);
|
||||
return 1;
|
||||
}
|
||||
fprintf(stderr, "STARTUP: nostr crypto system initialized successfully\r\n");
|
||||
app_log(LOG_INFO, "Nostr crypto system initialized successfully");
|
||||
|
||||
// ========================================================================
|
||||
// DATABASE AND KEY INITIALIZATION - 5 SCENARIOS
|
||||
@@ -1919,12 +1950,12 @@ int main(int argc, char *argv[]) {
|
||||
|
||||
// Scenario 4: Test Mode (--test-keys)
|
||||
if (use_test_keys) {
|
||||
fprintf(stderr, "\n=== SCENARIO 4: TEST MODE ===\n");
|
||||
app_log(LOG_INFO, "=== SCENARIO 4: TEST MODE ===");
|
||||
|
||||
// Load test keys from .test_keys file
|
||||
FILE *keys_file = fopen(".test_keys", "r");
|
||||
if (!keys_file) {
|
||||
fprintf(stderr, "ERROR: Cannot open .test_keys file\n");
|
||||
app_log(LOG_ERROR, "Cannot open .test_keys file");
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -1944,38 +1975,38 @@ int main(int argc, char *argv[]) {
|
||||
if (end && (end - start) == 64) {
|
||||
strncpy(test_server_privkey, start, 64);
|
||||
test_server_privkey[64] = '\0';
|
||||
fprintf(stderr, "TEST MODE: Parsed SERVER_PRIVKEY: %s\n", test_server_privkey);
|
||||
app_log(LOG_DEBUG, "Parsed SERVER_PRIVKEY from .test_keys");
|
||||
} else {
|
||||
fprintf(stderr, "TEST MODE: Failed to parse SERVER_PRIVKEY (length: %ld)\n", end ? (long)(end - start) : -1L);
|
||||
app_log(LOG_ERROR, "Failed to parse SERVER_PRIVKEY (length: %ld)", end ? (long)(end - start) : -1L);
|
||||
}
|
||||
}
|
||||
}
|
||||
fclose(keys_file);
|
||||
|
||||
fprintf(stderr, "TEST MODE: Loaded keys from .test_keys\n");
|
||||
fprintf(stderr, "TEST MODE: Admin pubkey: %s\n", g_admin_pubkey);
|
||||
app_log(LOG_INFO, "Loaded keys from .test_keys");
|
||||
app_log(LOG_INFO, "Admin pubkey: %s", g_admin_pubkey);
|
||||
|
||||
// Derive pubkey from test privkey
|
||||
if (derive_pubkey_from_privkey(test_server_privkey, g_blossom_pubkey) != 0) {
|
||||
fprintf(stderr, "ERROR: Failed to derive pubkey from test privkey\n");
|
||||
app_log(LOG_ERROR, "Failed to derive pubkey from test privkey");
|
||||
return 1;
|
||||
}
|
||||
|
||||
fprintf(stderr, "TEST MODE: Server pubkey: %s\n", g_blossom_pubkey);
|
||||
app_log(LOG_INFO, "Server pubkey: %s", g_blossom_pubkey);
|
||||
|
||||
// Set database path based on test pubkey
|
||||
if (set_db_path_from_pubkey(g_blossom_pubkey) != 0) {
|
||||
fprintf(stderr, "ERROR: Failed to set database path\n");
|
||||
app_log(LOG_ERROR, "Failed to set database path");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Test mode ALWAYS overwrites database for clean testing
|
||||
fprintf(stderr, "TEST MODE: Creating/overwriting database: %s\n", g_db_path);
|
||||
app_log(LOG_INFO, "Creating/overwriting test database: %s", g_db_path);
|
||||
unlink(g_db_path); // Remove if exists
|
||||
|
||||
// Initialize new database
|
||||
if (initialize_database(g_db_path) != 0) {
|
||||
fprintf(stderr, "ERROR: Failed to initialize test database\n");
|
||||
app_log(LOG_ERROR, "Failed to initialize test database");
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -1984,7 +2015,7 @@ int main(int argc, char *argv[]) {
|
||||
g_blossom_seckey[64] = '\0';
|
||||
|
||||
if (store_blossom_private_key(test_server_privkey) != 0) {
|
||||
fprintf(stderr, "ERROR: Failed to store test private key\n");
|
||||
app_log(LOG_ERROR, "Failed to store test private key");
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -2016,12 +2047,12 @@ int main(int argc, char *argv[]) {
|
||||
sqlite3_close(db);
|
||||
}
|
||||
|
||||
fprintf(stderr, "TEST MODE: Database initialized successfully\n");
|
||||
app_log(LOG_INFO, "Test database initialized successfully");
|
||||
}
|
||||
|
||||
// Scenario 3: Keys Specified (--server-privkey)
|
||||
else if (test_server_privkey[0] != '\0') {
|
||||
fprintf(stderr, "\n=== SCENARIO 3: KEYS SPECIFIED ===\n");
|
||||
app_log(LOG_INFO, "=== SCENARIO 3: KEYS SPECIFIED ===");
|
||||
|
||||
// Derive pubkey from provided privkey
|
||||
if (derive_pubkey_from_privkey(test_server_privkey, g_blossom_pubkey) != 0) {
|
||||
@@ -2171,21 +2202,18 @@ int main(int argc, char *argv[]) {
|
||||
// END DATABASE AND KEY INITIALIZATION
|
||||
// ========================================================================
|
||||
|
||||
fprintf(stderr, "\n=== FINAL CONFIGURATION ===\n");
|
||||
fprintf(stderr, "Database path: %s\n", g_db_path);
|
||||
fprintf(stderr, "Storage directory: %s\n", g_storage_dir);
|
||||
fprintf(stderr, "Server pubkey: %s\n", g_blossom_pubkey);
|
||||
app_log(LOG_INFO, "=== FINAL CONFIGURATION ===");
|
||||
app_log(LOG_INFO, "Database path: %s", g_db_path);
|
||||
app_log(LOG_INFO, "Storage directory: %s", g_storage_dir);
|
||||
app_log(LOG_INFO, "Server pubkey: %s", g_blossom_pubkey);
|
||||
if (strlen(g_admin_pubkey) > 0) {
|
||||
fprintf(stderr, "Admin pubkey: %s\n", g_admin_pubkey);
|
||||
app_log(LOG_INFO, "Admin pubkey: %s", g_admin_pubkey);
|
||||
}
|
||||
fprintf(stderr, "===========================\n\n");
|
||||
|
||||
fflush(stderr);
|
||||
app_log(LOG_INFO, "===========================");
|
||||
|
||||
// If --generate-keys was specified, exit after key generation
|
||||
if (g_generate_keys) {
|
||||
fprintf(stderr, "Key generation completed, exiting.\n");
|
||||
fflush(stderr);
|
||||
app_log(LOG_INFO, "Key generation completed, exiting");
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -2206,51 +2234,48 @@ if (!config_loaded /* && !initialize_server_config() */) {
|
||||
}
|
||||
|
||||
// Initialize request validator system
|
||||
fprintf(stderr, "STARTUP: Initializing request validator system...\r\n");
|
||||
app_log(LOG_INFO, "Initializing request validator system...");
|
||||
int validator_init_result =
|
||||
ginxsom_request_validator_init(g_db_path, "ginxsom");
|
||||
fprintf(stderr, "MAIN: validator init return code: %d\r\n",
|
||||
validator_init_result);
|
||||
if (validator_init_result != NOSTR_SUCCESS) {
|
||||
fprintf(stderr,
|
||||
"FATAL ERROR: Failed to initialize request validator system\r\n");
|
||||
app_log(LOG_ERROR, "Failed to initialize request validator system (result: %d)", validator_init_result);
|
||||
return 1;
|
||||
}
|
||||
fprintf(stderr,
|
||||
"STARTUP: Request validator system initialized successfully\r\n");
|
||||
fflush(stderr);
|
||||
app_log(LOG_INFO, "Request validator system initialized successfully");
|
||||
|
||||
// Start WebSocket admin server if enabled
|
||||
sqlite3 *db;
|
||||
sqlite3_stmt *stmt;
|
||||
int rc = sqlite3_open_v2(g_db_path, &db, SQLITE_OPEN_READONLY, NULL);
|
||||
if (rc == SQLITE_OK) {
|
||||
const char *sql = "SELECT value FROM config WHERE key = 'admin_enabled'";
|
||||
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
|
||||
if (rc == SQLITE_OK) {
|
||||
rc = sqlite3_step(stmt);
|
||||
if (rc == SQLITE_ROW) {
|
||||
const char *admin_enabled = (const char *)sqlite3_column_text(stmt, 0);
|
||||
if (admin_enabled && (strcmp(admin_enabled, "true") == 0 || strcmp(admin_enabled, "1") == 0)) {
|
||||
fprintf(stderr, "STARTUP: Starting WebSocket admin server on port 9442...\n");
|
||||
if (start_admin_websocket_server(9442) == 0) {
|
||||
fprintf(stderr, "STARTUP: WebSocket admin server started successfully\n");
|
||||
} else {
|
||||
fprintf(stderr, "WARNING: Failed to start WebSocket admin server\n");
|
||||
}
|
||||
} else {
|
||||
fprintf(stderr, "STARTUP: Admin interface disabled in config\n");
|
||||
}
|
||||
}
|
||||
sqlite3_finalize(stmt);
|
||||
// Initialize relay client system
|
||||
app_log(LOG_INFO, "Initializing relay client system...");
|
||||
int relay_init_result = relay_client_init(g_db_path);
|
||||
if (relay_init_result != 0) {
|
||||
app_log(LOG_WARN, "Failed to initialize relay client system (result: %d)", relay_init_result);
|
||||
app_log(LOG_WARN, "Continuing without relay client functionality");
|
||||
} else {
|
||||
app_log(LOG_INFO, "Relay client system initialized successfully");
|
||||
|
||||
// Start relay connections (this will check enable_relay_connect config)
|
||||
app_log(LOG_INFO, "Starting relay client connections...");
|
||||
int relay_start_result = relay_client_start();
|
||||
if (relay_start_result != 0) {
|
||||
app_log(LOG_WARN, "Failed to start relay client (result: %d)", relay_start_result);
|
||||
app_log(LOG_WARN, "Relay client disabled - check configuration");
|
||||
} else {
|
||||
app_log(LOG_INFO, "Relay client started successfully");
|
||||
}
|
||||
sqlite3_close(db);
|
||||
}
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// THIS IS WHERE THE REQUESTS ENTER THE FastCGI
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
app_log(LOG_INFO, "FastCGI request loop starting - ready to accept requests");
|
||||
|
||||
int first_request = 1;
|
||||
while (FCGI_Accept() >= 0) {
|
||||
// Test stderr capture on first request
|
||||
if (first_request) {
|
||||
fprintf(stderr, "FCGI: First request received - testing nginx stderr capture\n");
|
||||
fflush(stderr);
|
||||
first_request = 0;
|
||||
}
|
||||
const char *request_method = getenv("REQUEST_METHOD");
|
||||
const char *request_uri = getenv("REQUEST_URI");
|
||||
const char *auth_header = getenv("HTTP_AUTHORIZATION");
|
||||
|
||||
784
src/relay_client.c
Normal file
784
src/relay_client.c
Normal file
@@ -0,0 +1,784 @@
|
||||
/*
|
||||
* Ginxsom Relay Client Implementation
|
||||
*
|
||||
* Manages connections to Nostr relays, publishes events, and subscribes to admin commands.
|
||||
*/
|
||||
|
||||
#include "relay_client.h"
|
||||
#include "../nostr_core_lib/nostr_core/nostr_core.h"
|
||||
#include <sqlite3.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <pthread.h>
|
||||
#include <unistd.h>
|
||||
#include <time.h>
|
||||
|
||||
// Forward declare app_log to avoid including ginxsom.h (which has typedef conflicts)
|
||||
typedef enum {
|
||||
LOG_DEBUG = 0,
|
||||
LOG_INFO = 1,
|
||||
LOG_WARN = 2,
|
||||
LOG_ERROR = 3
|
||||
} log_level_t;
|
||||
|
||||
void app_log(log_level_t level, const char* format, ...);
|
||||
|
||||
// Maximum number of relays to connect to
|
||||
#define MAX_RELAYS 10
|
||||
|
||||
// Reconnection settings
|
||||
#define RECONNECT_DELAY_SECONDS 30
|
||||
#define MAX_RECONNECT_ATTEMPTS 5
|
||||
|
||||
// Global state
|
||||
static struct {
|
||||
int enabled;
|
||||
int initialized;
|
||||
int running;
|
||||
char db_path[512];
|
||||
nostr_relay_pool_t* pool;
|
||||
char** relay_urls;
|
||||
int relay_count;
|
||||
nostr_pool_subscription_t* admin_subscription;
|
||||
pthread_t management_thread;
|
||||
pthread_mutex_t state_mutex;
|
||||
} g_relay_state = {0};
|
||||
|
||||
// External globals from main.c
|
||||
extern char g_blossom_seckey[65];
|
||||
extern char g_blossom_pubkey[65];
|
||||
extern char g_admin_pubkey[65];
|
||||
|
||||
// Forward declarations
|
||||
static void *relay_management_thread(void *arg);
|
||||
static int load_config_from_db(void);
|
||||
static int parse_relay_urls(const char *json_array);
|
||||
static int subscribe_to_admin_commands(void);
|
||||
static void on_publish_response(const char* relay_url, const char* event_id, int success, const char* message, void* user_data);
|
||||
static void on_admin_command_event(cJSON* event, const char* relay_url, void* user_data);
|
||||
static void on_admin_subscription_eose(cJSON** events, int event_count, void* user_data);
|
||||
|
||||
// Initialize relay client system
|
||||
int relay_client_init(const char *db_path) {
|
||||
if (g_relay_state.initialized) {
|
||||
app_log(LOG_WARN, "Relay client already initialized");
|
||||
return 0;
|
||||
}
|
||||
|
||||
app_log(LOG_INFO, "Initializing relay client system...");
|
||||
|
||||
// Store database path
|
||||
strncpy(g_relay_state.db_path, db_path, sizeof(g_relay_state.db_path) - 1);
|
||||
|
||||
// Initialize mutex
|
||||
if (pthread_mutex_init(&g_relay_state.state_mutex, NULL) != 0) {
|
||||
app_log(LOG_ERROR, "Failed to initialize relay state mutex");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Load configuration from database
|
||||
if (load_config_from_db() != 0) {
|
||||
app_log(LOG_ERROR, "Failed to load relay configuration from database");
|
||||
pthread_mutex_destroy(&g_relay_state.state_mutex);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Create relay pool if enabled
|
||||
if (g_relay_state.enabled) {
|
||||
// Use default reconnection config (don't free - it's a static structure)
|
||||
nostr_pool_reconnect_config_t* config = nostr_pool_reconnect_config_default();
|
||||
g_relay_state.pool = nostr_relay_pool_create(config);
|
||||
if (!g_relay_state.pool) {
|
||||
app_log(LOG_ERROR, "Failed to create relay pool");
|
||||
pthread_mutex_destroy(&g_relay_state.state_mutex);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Add all relays to pool
|
||||
for (int i = 0; i < g_relay_state.relay_count; i++) {
|
||||
if (nostr_relay_pool_add_relay(g_relay_state.pool, g_relay_state.relay_urls[i]) != NOSTR_SUCCESS) {
|
||||
app_log(LOG_WARN, "Failed to add relay to pool: %s", g_relay_state.relay_urls[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Trigger initial connection attempts by creating a dummy subscription
|
||||
// This forces ensure_relay_connection() to be called for each relay
|
||||
app_log(LOG_INFO, "Initiating relay connections...");
|
||||
cJSON* dummy_filter = cJSON_CreateObject();
|
||||
cJSON* kinds = cJSON_CreateArray();
|
||||
cJSON_AddItemToArray(kinds, cJSON_CreateNumber(0)); // Kind 0 (will match nothing)
|
||||
cJSON_AddItemToObject(dummy_filter, "kinds", kinds);
|
||||
cJSON_AddNumberToObject(dummy_filter, "limit", 0); // Limit 0 = no results
|
||||
|
||||
nostr_pool_subscription_t* dummy_sub = nostr_relay_pool_subscribe(
|
||||
g_relay_state.pool,
|
||||
(const char**)g_relay_state.relay_urls,
|
||||
g_relay_state.relay_count,
|
||||
dummy_filter,
|
||||
NULL, // No event callback
|
||||
NULL, // No EOSE callback
|
||||
NULL, // No user data
|
||||
1, // close_on_eose
|
||||
1, // enable_deduplication
|
||||
NOSTR_POOL_EOSE_FIRST, // result_mode
|
||||
30, // relay_timeout_seconds
|
||||
30 // eose_timeout_seconds
|
||||
);
|
||||
|
||||
cJSON_Delete(dummy_filter);
|
||||
|
||||
// Immediately close the dummy subscription
|
||||
if (dummy_sub) {
|
||||
nostr_pool_subscription_close(dummy_sub);
|
||||
app_log(LOG_INFO, "Connection attempts initiated for %d relays", g_relay_state.relay_count);
|
||||
} else {
|
||||
app_log(LOG_WARN, "Failed to initiate connection attempts");
|
||||
}
|
||||
}
|
||||
|
||||
g_relay_state.initialized = 1;
|
||||
app_log(LOG_INFO, "Relay client initialized (enabled: %d, relays: %d)",
|
||||
g_relay_state.enabled, g_relay_state.relay_count);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Load configuration from database
|
||||
static int load_config_from_db(void) {
|
||||
sqlite3 *db;
|
||||
sqlite3_stmt *stmt;
|
||||
int rc;
|
||||
|
||||
rc = sqlite3_open_v2(g_relay_state.db_path, &db, SQLITE_OPEN_READONLY, NULL);
|
||||
if (rc != SQLITE_OK) {
|
||||
app_log(LOG_ERROR, "Cannot open database: %s", sqlite3_errmsg(db));
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Load enable_relay_connect
|
||||
const char *sql = "SELECT value FROM config WHERE key = ?";
|
||||
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
|
||||
if (rc != SQLITE_OK) {
|
||||
app_log(LOG_ERROR, "Failed to prepare statement: %s", sqlite3_errmsg(db));
|
||||
sqlite3_close(db);
|
||||
return -1;
|
||||
}
|
||||
|
||||
sqlite3_bind_text(stmt, 1, "enable_relay_connect", -1, SQLITE_STATIC);
|
||||
rc = sqlite3_step(stmt);
|
||||
if (rc == SQLITE_ROW) {
|
||||
const char *value = (const char *)sqlite3_column_text(stmt, 0);
|
||||
g_relay_state.enabled = (strcmp(value, "true") == 0 || strcmp(value, "1") == 0);
|
||||
} else {
|
||||
g_relay_state.enabled = 0;
|
||||
}
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
// If not enabled, skip loading relay URLs
|
||||
if (!g_relay_state.enabled) {
|
||||
sqlite3_close(db);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Load kind_10002_tags (relay URLs)
|
||||
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
|
||||
if (rc != SQLITE_OK) {
|
||||
app_log(LOG_ERROR, "Failed to prepare statement: %s", sqlite3_errmsg(db));
|
||||
sqlite3_close(db);
|
||||
return -1;
|
||||
}
|
||||
|
||||
sqlite3_bind_text(stmt, 1, "kind_10002_tags", -1, SQLITE_STATIC);
|
||||
rc = sqlite3_step(stmt);
|
||||
if (rc == SQLITE_ROW) {
|
||||
const char *json_array = (const char *)sqlite3_column_text(stmt, 0);
|
||||
if (parse_relay_urls(json_array) != 0) {
|
||||
app_log(LOG_ERROR, "Failed to parse relay URLs from config");
|
||||
sqlite3_finalize(stmt);
|
||||
sqlite3_close(db);
|
||||
return -1;
|
||||
}
|
||||
} else {
|
||||
app_log(LOG_WARN, "No relay URLs configured in kind_10002_tags");
|
||||
}
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
sqlite3_close(db);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Parse relay URLs from JSON array
|
||||
static int parse_relay_urls(const char *json_array) {
|
||||
cJSON *root = cJSON_Parse(json_array);
|
||||
if (!root || !cJSON_IsArray(root)) {
|
||||
app_log(LOG_ERROR, "Invalid JSON array for relay URLs");
|
||||
if (root) cJSON_Delete(root);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int count = cJSON_GetArraySize(root);
|
||||
if (count > MAX_RELAYS) {
|
||||
app_log(LOG_WARN, "Too many relays configured (%d), limiting to %d", count, MAX_RELAYS);
|
||||
count = MAX_RELAYS;
|
||||
}
|
||||
|
||||
// Allocate relay URLs array
|
||||
g_relay_state.relay_urls = malloc(count * sizeof(char*));
|
||||
if (!g_relay_state.relay_urls) {
|
||||
cJSON_Delete(root);
|
||||
return -1;
|
||||
}
|
||||
|
||||
g_relay_state.relay_count = 0;
|
||||
for (int i = 0; i < count; i++) {
|
||||
cJSON *item = cJSON_GetArrayItem(root, i);
|
||||
if (cJSON_IsString(item) && item->valuestring) {
|
||||
g_relay_state.relay_urls[g_relay_state.relay_count] = strdup(item->valuestring);
|
||||
if (!g_relay_state.relay_urls[g_relay_state.relay_count]) {
|
||||
// Cleanup on failure
|
||||
for (int j = 0; j < g_relay_state.relay_count; j++) {
|
||||
free(g_relay_state.relay_urls[j]);
|
||||
}
|
||||
free(g_relay_state.relay_urls);
|
||||
cJSON_Delete(root);
|
||||
return -1;
|
||||
}
|
||||
g_relay_state.relay_count++;
|
||||
}
|
||||
}
|
||||
|
||||
cJSON_Delete(root);
|
||||
app_log(LOG_INFO, "Parsed %d relay URLs from configuration", g_relay_state.relay_count);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Start relay connections
|
||||
int relay_client_start(void) {
|
||||
if (!g_relay_state.initialized) {
|
||||
app_log(LOG_ERROR, "Relay client not initialized");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!g_relay_state.enabled) {
|
||||
app_log(LOG_INFO, "Relay client disabled in configuration");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (g_relay_state.running) {
|
||||
app_log(LOG_WARN, "Relay client already running");
|
||||
return 0;
|
||||
}
|
||||
|
||||
app_log(LOG_INFO, "Starting relay client...");
|
||||
|
||||
// Start management thread
|
||||
g_relay_state.running = 1;
|
||||
if (pthread_create(&g_relay_state.management_thread, NULL, relay_management_thread, NULL) != 0) {
|
||||
app_log(LOG_ERROR, "Failed to create relay management thread");
|
||||
g_relay_state.running = 0;
|
||||
return -1;
|
||||
}
|
||||
|
||||
app_log(LOG_INFO, "Relay client started successfully");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Relay management thread
|
||||
static void *relay_management_thread(void *arg) {
|
||||
(void)arg;
|
||||
|
||||
app_log(LOG_INFO, "Relay management thread started");
|
||||
|
||||
// Wait for at least one relay to connect (max 30 seconds)
|
||||
int connected = 0;
|
||||
for (int i = 0; i < 30 && !connected; i++) {
|
||||
sleep(1);
|
||||
|
||||
// Poll to process connection attempts
|
||||
nostr_relay_pool_poll(g_relay_state.pool, 100);
|
||||
|
||||
// Check if any relay is connected
|
||||
for (int j = 0; j < g_relay_state.relay_count; j++) {
|
||||
nostr_pool_relay_status_t status = nostr_relay_pool_get_relay_status(
|
||||
g_relay_state.pool,
|
||||
g_relay_state.relay_urls[j]
|
||||
);
|
||||
if (status == NOSTR_POOL_RELAY_CONNECTED) {
|
||||
connected = 1;
|
||||
app_log(LOG_INFO, "Relay connected: %s", g_relay_state.relay_urls[j]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!connected) {
|
||||
app_log(LOG_WARN, "No relays connected after 30 seconds, continuing anyway");
|
||||
}
|
||||
|
||||
// Publish initial events
|
||||
relay_client_publish_kind0();
|
||||
relay_client_publish_kind10002();
|
||||
|
||||
// Subscribe to admin commands
|
||||
subscribe_to_admin_commands();
|
||||
|
||||
// Main loop: poll the relay pool for incoming messages
|
||||
while (g_relay_state.running) {
|
||||
// Poll with 1000ms timeout
|
||||
int events_processed = nostr_relay_pool_poll(g_relay_state.pool, 1000);
|
||||
|
||||
if (events_processed < 0) {
|
||||
app_log(LOG_ERROR, "Error polling relay pool");
|
||||
sleep(1);
|
||||
}
|
||||
// Pool handles all connection management, reconnection, and message processing
|
||||
}
|
||||
|
||||
app_log(LOG_INFO, "Relay management thread stopping");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Stop relay connections
|
||||
void relay_client_stop(void) {
|
||||
if (!g_relay_state.running) {
|
||||
return;
|
||||
}
|
||||
|
||||
app_log(LOG_INFO, "Stopping relay client...");
|
||||
|
||||
g_relay_state.running = 0;
|
||||
|
||||
// Wait for management thread to finish
|
||||
pthread_join(g_relay_state.management_thread, NULL);
|
||||
|
||||
// Close admin subscription
|
||||
if (g_relay_state.admin_subscription) {
|
||||
nostr_pool_subscription_close(g_relay_state.admin_subscription);
|
||||
g_relay_state.admin_subscription = NULL;
|
||||
}
|
||||
|
||||
// Destroy relay pool (automatically disconnects all relays)
|
||||
if (g_relay_state.pool) {
|
||||
nostr_relay_pool_destroy(g_relay_state.pool);
|
||||
g_relay_state.pool = NULL;
|
||||
}
|
||||
|
||||
// Free relay URLs
|
||||
if (g_relay_state.relay_urls) {
|
||||
for (int i = 0; i < g_relay_state.relay_count; i++) {
|
||||
free(g_relay_state.relay_urls[i]);
|
||||
}
|
||||
free(g_relay_state.relay_urls);
|
||||
g_relay_state.relay_urls = NULL;
|
||||
}
|
||||
|
||||
pthread_mutex_destroy(&g_relay_state.state_mutex);
|
||||
|
||||
app_log(LOG_INFO, "Relay client stopped");
|
||||
}
|
||||
|
||||
// Check if relay client is enabled
|
||||
int relay_client_is_enabled(void) {
|
||||
return g_relay_state.enabled;
|
||||
}
|
||||
|
||||
// Publish Kind 0 profile event
|
||||
int relay_client_publish_kind0(void) {
|
||||
if (!g_relay_state.enabled || !g_relay_state.running || !g_relay_state.pool) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
app_log(LOG_INFO, "Publishing Kind 0 profile event...");
|
||||
|
||||
// Load kind_0_content from database
|
||||
sqlite3 *db;
|
||||
sqlite3_stmt *stmt;
|
||||
int rc;
|
||||
|
||||
rc = sqlite3_open_v2(g_relay_state.db_path, &db, SQLITE_OPEN_READONLY, NULL);
|
||||
if (rc != SQLITE_OK) {
|
||||
app_log(LOG_ERROR, "Cannot open database: %s", sqlite3_errmsg(db));
|
||||
return -1;
|
||||
}
|
||||
|
||||
const char *sql = "SELECT value FROM config WHERE key = 'kind_0_content'";
|
||||
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
|
||||
if (rc != SQLITE_OK) {
|
||||
app_log(LOG_ERROR, "Failed to prepare statement: %s", sqlite3_errmsg(db));
|
||||
sqlite3_close(db);
|
||||
return -1;
|
||||
}
|
||||
|
||||
rc = sqlite3_step(stmt);
|
||||
if (rc != SQLITE_ROW) {
|
||||
app_log(LOG_WARN, "No kind_0_content found in config");
|
||||
sqlite3_finalize(stmt);
|
||||
sqlite3_close(db);
|
||||
return -1;
|
||||
}
|
||||
|
||||
const char *content = (const char *)sqlite3_column_text(stmt, 0);
|
||||
|
||||
// Convert private key from hex to bytes
|
||||
unsigned char privkey_bytes[32];
|
||||
if (nostr_hex_to_bytes(g_blossom_seckey, privkey_bytes, 32) != 0) {
|
||||
app_log(LOG_ERROR, "Failed to convert private key from hex");
|
||||
sqlite3_finalize(stmt);
|
||||
sqlite3_close(db);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Create and sign Kind 0 event using nostr_core_lib
|
||||
cJSON* event = nostr_create_and_sign_event(
|
||||
0, // kind
|
||||
content, // content
|
||||
NULL, // tags (empty for Kind 0)
|
||||
privkey_bytes, // private key
|
||||
time(NULL) // created_at
|
||||
);
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
sqlite3_close(db);
|
||||
|
||||
if (!event) {
|
||||
app_log(LOG_ERROR, "Failed to create Kind 0 event");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Publish to all relays using async pool API
|
||||
int result = nostr_relay_pool_publish_async(
|
||||
g_relay_state.pool,
|
||||
(const char**)g_relay_state.relay_urls,
|
||||
g_relay_state.relay_count,
|
||||
event,
|
||||
on_publish_response,
|
||||
(void*)"Kind 0" // user_data to identify event type
|
||||
);
|
||||
|
||||
cJSON_Delete(event);
|
||||
|
||||
if (result == 0) {
|
||||
app_log(LOG_INFO, "Kind 0 profile event publish initiated");
|
||||
return 0;
|
||||
} else {
|
||||
app_log(LOG_ERROR, "Failed to initiate Kind 0 profile event publish");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// Publish Kind 10002 relay list event
|
||||
int relay_client_publish_kind10002(void) {
|
||||
if (!g_relay_state.enabled || !g_relay_state.running || !g_relay_state.pool) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
app_log(LOG_INFO, "Publishing Kind 10002 relay list event...");
|
||||
|
||||
// Build tags array from configured relays
|
||||
cJSON* tags = cJSON_CreateArray();
|
||||
for (int i = 0; i < g_relay_state.relay_count; i++) {
|
||||
cJSON* tag = cJSON_CreateArray();
|
||||
cJSON_AddItemToArray(tag, cJSON_CreateString("r"));
|
||||
cJSON_AddItemToArray(tag, cJSON_CreateString(g_relay_state.relay_urls[i]));
|
||||
cJSON_AddItemToArray(tags, tag);
|
||||
}
|
||||
|
||||
// Convert private key from hex to bytes
|
||||
unsigned char privkey_bytes[32];
|
||||
if (nostr_hex_to_bytes(g_blossom_seckey, privkey_bytes, 32) != 0) {
|
||||
app_log(LOG_ERROR, "Failed to convert private key from hex");
|
||||
cJSON_Delete(tags);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Create and sign Kind 10002 event
|
||||
cJSON* event = nostr_create_and_sign_event(
|
||||
10002, // kind
|
||||
"", // content (empty for Kind 10002)
|
||||
tags, // tags
|
||||
privkey_bytes, // private key
|
||||
time(NULL) // created_at
|
||||
);
|
||||
|
||||
cJSON_Delete(tags);
|
||||
|
||||
if (!event) {
|
||||
app_log(LOG_ERROR, "Failed to create Kind 10002 event");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Publish to all relays using async pool API
|
||||
int result = nostr_relay_pool_publish_async(
|
||||
g_relay_state.pool,
|
||||
(const char**)g_relay_state.relay_urls,
|
||||
g_relay_state.relay_count,
|
||||
event,
|
||||
on_publish_response,
|
||||
(void*)"Kind 10002" // user_data to identify event type
|
||||
);
|
||||
|
||||
cJSON_Delete(event);
|
||||
|
||||
if (result == 0) {
|
||||
app_log(LOG_INFO, "Kind 10002 relay list event publish initiated");
|
||||
return 0;
|
||||
} else {
|
||||
app_log(LOG_ERROR, "Failed to initiate Kind 10002 relay list event publish");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// Send Kind 23457 admin response event
|
||||
int relay_client_send_admin_response(const char *recipient_pubkey, const char *response_content) {
|
||||
if (!g_relay_state.enabled || !g_relay_state.running || !g_relay_state.pool) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!recipient_pubkey || !response_content) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
app_log(LOG_INFO, "Sending Kind 23457 admin response to %s", recipient_pubkey);
|
||||
|
||||
// TODO: Encrypt response_content using NIP-44
|
||||
// For now, use plaintext (stub implementation)
|
||||
const char *encrypted_content = response_content;
|
||||
|
||||
// Build tags array
|
||||
cJSON* tags = cJSON_CreateArray();
|
||||
cJSON* p_tag = cJSON_CreateArray();
|
||||
cJSON_AddItemToArray(p_tag, cJSON_CreateString("p"));
|
||||
cJSON_AddItemToArray(p_tag, cJSON_CreateString(recipient_pubkey));
|
||||
cJSON_AddItemToArray(tags, p_tag);
|
||||
|
||||
// Convert private key from hex to bytes
|
||||
unsigned char privkey_bytes[32];
|
||||
if (nostr_hex_to_bytes(g_blossom_seckey, privkey_bytes, 32) != 0) {
|
||||
app_log(LOG_ERROR, "Failed to convert private key from hex");
|
||||
cJSON_Delete(tags);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Create and sign Kind 23457 event
|
||||
cJSON* event = nostr_create_and_sign_event(
|
||||
23457, // kind
|
||||
encrypted_content, // content
|
||||
tags, // tags
|
||||
privkey_bytes, // private key
|
||||
time(NULL) // created_at
|
||||
);
|
||||
|
||||
cJSON_Delete(tags);
|
||||
|
||||
if (!event) {
|
||||
app_log(LOG_ERROR, "Failed to create Kind 23457 event");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Publish to all relays using async pool API
|
||||
int result = nostr_relay_pool_publish_async(
|
||||
g_relay_state.pool,
|
||||
(const char**)g_relay_state.relay_urls,
|
||||
g_relay_state.relay_count,
|
||||
event,
|
||||
on_publish_response,
|
||||
(void*)"Kind 23457" // user_data to identify event type
|
||||
);
|
||||
|
||||
cJSON_Delete(event);
|
||||
|
||||
if (result == 0) {
|
||||
app_log(LOG_INFO, "Kind 23457 admin response publish initiated");
|
||||
return 0;
|
||||
} else {
|
||||
app_log(LOG_ERROR, "Failed to initiate Kind 23457 admin response publish");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// Callback for publish responses
|
||||
static void on_publish_response(const char* relay_url, const char* event_id, int success, const char* message, void* user_data) {
|
||||
const char* event_type = (const char*)user_data;
|
||||
|
||||
if (success) {
|
||||
app_log(LOG_INFO, "%s event published successfully to %s (ID: %s)",
|
||||
event_type, relay_url, event_id);
|
||||
} else {
|
||||
app_log(LOG_WARN, "%s event rejected by %s: %s",
|
||||
event_type, relay_url, message ? message : "unknown error");
|
||||
}
|
||||
}
|
||||
|
||||
// Callback for received Kind 23456 admin command events
|
||||
static void on_admin_command_event(cJSON* event, const char* relay_url, void* user_data) {
|
||||
(void)user_data;
|
||||
|
||||
app_log(LOG_INFO, "Received Kind 23456 admin command from relay: %s", relay_url);
|
||||
|
||||
// Extract event fields
|
||||
cJSON* kind_json = cJSON_GetObjectItem(event, "kind");
|
||||
cJSON* pubkey_json = cJSON_GetObjectItem(event, "pubkey");
|
||||
cJSON* content_json = cJSON_GetObjectItem(event, "content");
|
||||
cJSON* id_json = cJSON_GetObjectItem(event, "id");
|
||||
|
||||
if (!kind_json || !pubkey_json || !content_json || !id_json) {
|
||||
app_log(LOG_ERROR, "Invalid event structure");
|
||||
return;
|
||||
}
|
||||
|
||||
int kind = cJSON_GetNumberValue(kind_json);
|
||||
const char* sender_pubkey = cJSON_GetStringValue(pubkey_json);
|
||||
const char* encrypted_content = cJSON_GetStringValue(content_json);
|
||||
const char* event_id = cJSON_GetStringValue(id_json);
|
||||
|
||||
if (kind != 23456) {
|
||||
app_log(LOG_WARN, "Unexpected event kind: %d", kind);
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify sender is admin
|
||||
if (strcmp(sender_pubkey, g_admin_pubkey) != 0) {
|
||||
app_log(LOG_WARN, "Ignoring command from non-admin pubkey: %s", sender_pubkey);
|
||||
return;
|
||||
}
|
||||
|
||||
app_log(LOG_INFO, "Processing admin command (event ID: %s)", event_id);
|
||||
|
||||
// TODO: Decrypt content using NIP-44
|
||||
// For now, log the encrypted content
|
||||
app_log(LOG_DEBUG, "Encrypted command content: %s", encrypted_content);
|
||||
|
||||
// TODO: Parse and execute command
|
||||
// TODO: Send response using relay_client_send_admin_response()
|
||||
}
|
||||
|
||||
// Callback for EOSE (End Of Stored Events) - new signature
|
||||
static void on_admin_subscription_eose(cJSON** events, int event_count, void* user_data) {
|
||||
(void)events;
|
||||
(void)event_count;
|
||||
(void)user_data;
|
||||
app_log(LOG_INFO, "Received EOSE for admin command subscription");
|
||||
}
|
||||
|
||||
// Subscribe to admin commands (Kind 23456)
|
||||
static int subscribe_to_admin_commands(void) {
|
||||
if (!g_relay_state.pool) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
app_log(LOG_INFO, "Subscribing to Kind 23456 admin commands...");
|
||||
|
||||
// Create subscription filter for Kind 23456 events addressed to us
|
||||
cJSON* filter = cJSON_CreateObject();
|
||||
cJSON* kinds = cJSON_CreateArray();
|
||||
cJSON_AddItemToArray(kinds, cJSON_CreateNumber(23456));
|
||||
cJSON_AddItemToObject(filter, "kinds", kinds);
|
||||
|
||||
cJSON* p_tags = cJSON_CreateArray();
|
||||
cJSON_AddItemToArray(p_tags, cJSON_CreateString(g_blossom_pubkey));
|
||||
cJSON_AddItemToObject(filter, "#p", p_tags);
|
||||
|
||||
cJSON_AddNumberToObject(filter, "since", (double)time(NULL));
|
||||
|
||||
// Subscribe using pool with new API signature
|
||||
g_relay_state.admin_subscription = nostr_relay_pool_subscribe(
|
||||
g_relay_state.pool,
|
||||
(const char**)g_relay_state.relay_urls,
|
||||
g_relay_state.relay_count,
|
||||
filter,
|
||||
on_admin_command_event,
|
||||
on_admin_subscription_eose,
|
||||
NULL, // user_data
|
||||
0, // close_on_eose (keep subscription open)
|
||||
1, // enable_deduplication
|
||||
NOSTR_POOL_EOSE_FULL_SET, // result_mode
|
||||
30, // relay_timeout_seconds
|
||||
30 // eose_timeout_seconds
|
||||
);
|
||||
|
||||
cJSON_Delete(filter);
|
||||
|
||||
if (!g_relay_state.admin_subscription) {
|
||||
app_log(LOG_ERROR, "Failed to create admin command subscription");
|
||||
return -1;
|
||||
}
|
||||
|
||||
app_log(LOG_INFO, "Successfully subscribed to admin commands");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Get current relay connection status
|
||||
char *relay_client_get_status(void) {
|
||||
if (!g_relay_state.pool) {
|
||||
return strdup("[]");
|
||||
}
|
||||
|
||||
cJSON *root = cJSON_CreateArray();
|
||||
|
||||
pthread_mutex_lock(&g_relay_state.state_mutex);
|
||||
for (int i = 0; i < g_relay_state.relay_count; i++) {
|
||||
cJSON *relay_obj = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(relay_obj, "url", g_relay_state.relay_urls[i]);
|
||||
|
||||
// Get status from pool
|
||||
nostr_pool_relay_status_t status = nostr_relay_pool_get_relay_status(
|
||||
g_relay_state.pool,
|
||||
g_relay_state.relay_urls[i]
|
||||
);
|
||||
|
||||
const char *state_str;
|
||||
switch (status) {
|
||||
case NOSTR_POOL_RELAY_CONNECTED: state_str = "connected"; break;
|
||||
case NOSTR_POOL_RELAY_CONNECTING: state_str = "connecting"; break;
|
||||
case NOSTR_POOL_RELAY_ERROR: state_str = "error"; break;
|
||||
default: state_str = "disconnected"; break;
|
||||
}
|
||||
cJSON_AddStringToObject(relay_obj, "state", state_str);
|
||||
|
||||
// Get statistics from pool
|
||||
const nostr_relay_stats_t* stats = nostr_relay_pool_get_relay_stats(
|
||||
g_relay_state.pool,
|
||||
g_relay_state.relay_urls[i]
|
||||
);
|
||||
|
||||
if (stats) {
|
||||
cJSON_AddNumberToObject(relay_obj, "events_received", stats->events_received);
|
||||
cJSON_AddNumberToObject(relay_obj, "events_published", stats->events_published);
|
||||
cJSON_AddNumberToObject(relay_obj, "connection_attempts", stats->connection_attempts);
|
||||
cJSON_AddNumberToObject(relay_obj, "connection_failures", stats->connection_failures);
|
||||
|
||||
if (stats->query_latency_avg > 0) {
|
||||
cJSON_AddNumberToObject(relay_obj, "query_latency_ms", stats->query_latency_avg);
|
||||
}
|
||||
}
|
||||
|
||||
cJSON_AddItemToArray(root, relay_obj);
|
||||
}
|
||||
pthread_mutex_unlock(&g_relay_state.state_mutex);
|
||||
|
||||
char *json_str = cJSON_PrintUnformatted(root);
|
||||
cJSON_Delete(root);
|
||||
|
||||
return json_str;
|
||||
}
|
||||
|
||||
// Force reconnection to all relays
|
||||
int relay_client_reconnect(void) {
|
||||
if (!g_relay_state.enabled || !g_relay_state.running || !g_relay_state.pool) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
app_log(LOG_INFO, "Forcing reconnection to all relays...");
|
||||
|
||||
// Remove and re-add all relays to force reconnection
|
||||
pthread_mutex_lock(&g_relay_state.state_mutex);
|
||||
for (int i = 0; i < g_relay_state.relay_count; i++) {
|
||||
nostr_relay_pool_remove_relay(g_relay_state.pool, g_relay_state.relay_urls[i]);
|
||||
nostr_relay_pool_add_relay(g_relay_state.pool, g_relay_state.relay_urls[i]);
|
||||
}
|
||||
pthread_mutex_unlock(&g_relay_state.state_mutex);
|
||||
|
||||
app_log(LOG_INFO, "Reconnection initiated for all relays");
|
||||
return 0;
|
||||
}
|
||||
78
src/relay_client.h
Normal file
78
src/relay_client.h
Normal file
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Ginxsom Relay Client - Nostr Relay Connection Manager
|
||||
*
|
||||
* This module enables Ginxsom to act as a Nostr client, connecting to relays
|
||||
* to publish events (Kind 0, Kind 10002) and subscribe to admin commands (Kind 23456).
|
||||
*/
|
||||
|
||||
#ifndef RELAY_CLIENT_H
|
||||
#define RELAY_CLIENT_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <time.h>
|
||||
|
||||
// Connection states for relay tracking
|
||||
typedef enum {
|
||||
RELAY_STATE_DISCONNECTED = 0,
|
||||
RELAY_STATE_CONNECTING = 1,
|
||||
RELAY_STATE_CONNECTED = 2,
|
||||
RELAY_STATE_ERROR = 3
|
||||
} relay_state_t;
|
||||
|
||||
// Relay connection info (in-memory only)
|
||||
typedef struct {
|
||||
char url[256];
|
||||
relay_state_t state;
|
||||
int reconnect_attempts;
|
||||
time_t last_connect_attempt;
|
||||
time_t connected_since;
|
||||
} relay_info_t;
|
||||
|
||||
// Initialize relay client system
|
||||
// Loads configuration from database and prepares for connections
|
||||
// Returns: 0 on success, -1 on error
|
||||
int relay_client_init(const char *db_path);
|
||||
|
||||
// Start relay connections
|
||||
// Connects to all relays specified in kind_10002_tags config
|
||||
// Publishes Kind 0 and Kind 10002 events after successful connection
|
||||
// Returns: 0 on success, -1 on error
|
||||
int relay_client_start(void);
|
||||
|
||||
// Stop relay connections and cleanup
|
||||
// Gracefully disconnects from all relays and stops background thread
|
||||
void relay_client_stop(void);
|
||||
|
||||
// Check if relay client is enabled
|
||||
// Returns: 1 if enabled, 0 if disabled
|
||||
int relay_client_is_enabled(void);
|
||||
|
||||
// Publish Kind 0 profile event to all connected relays
|
||||
// Uses kind_0_content from config database
|
||||
// Returns: 0 on success, -1 on error
|
||||
int relay_client_publish_kind0(void);
|
||||
|
||||
// Publish Kind 10002 relay list event to all connected relays
|
||||
// Uses kind_10002_tags from config database
|
||||
// Returns: 0 on success, -1 on error
|
||||
int relay_client_publish_kind10002(void);
|
||||
|
||||
// Send Kind 23457 admin response event
|
||||
// Encrypts content using NIP-44 and publishes to all connected relays
|
||||
// Parameters:
|
||||
// - recipient_pubkey: Admin's public key (recipient)
|
||||
// - response_content: JSON response content to encrypt
|
||||
// Returns: 0 on success, -1 on error
|
||||
int relay_client_send_admin_response(const char *recipient_pubkey, const char *response_content);
|
||||
|
||||
// Get current relay connection status
|
||||
// Returns JSON string with relay status (caller must free)
|
||||
// Format: [{"url": "wss://...", "state": "connected", "connected_since": 1234567890}, ...]
|
||||
char *relay_client_get_status(void);
|
||||
|
||||
// Force reconnection to all relays
|
||||
// Disconnects and reconnects to all configured relays
|
||||
// Returns: 0 on success, -1 on error
|
||||
int relay_client_reconnect(void);
|
||||
|
||||
#endif // RELAY_CLIENT_H
|
||||
@@ -529,7 +529,7 @@ int nostr_validate_unified_request(const nostr_unified_request_t *request,
|
||||
"VALIDATOR_DEBUG: STEP 10 FAILED - NIP-42 requires request_url and "
|
||||
"challenge (from event tags)\n");
|
||||
result->valid = 0;
|
||||
result->error_code = NOSTR_ERROR_NIP42_NOT_CONFIGURED;
|
||||
result->error_code = NOSTR_ERROR_NIP42_INVALID_CHALLENGE;
|
||||
strcpy(result->reason, "NIP-42 authentication requires request_url and challenge in event tags");
|
||||
cJSON_Delete(event);
|
||||
return NOSTR_SUCCESS;
|
||||
@@ -549,15 +549,12 @@ int nostr_validate_unified_request(const nostr_unified_request_t *request,
|
||||
|
||||
// Map specific NIP-42 error codes to detailed error messages
|
||||
switch (nip42_result) {
|
||||
case NOSTR_ERROR_NIP42_CHALLENGE_NOT_FOUND:
|
||||
strcpy(result->reason, "Challenge not found or has been used. Request a new challenge from /auth endpoint.");
|
||||
case NOSTR_ERROR_NIP42_INVALID_CHALLENGE:
|
||||
strcpy(result->reason, "Challenge not found or invalid. Request a new challenge from /auth endpoint.");
|
||||
break;
|
||||
case NOSTR_ERROR_NIP42_CHALLENGE_EXPIRED:
|
||||
strcpy(result->reason, "Challenge has expired. Request a new challenge from /auth endpoint.");
|
||||
break;
|
||||
case NOSTR_ERROR_NIP42_INVALID_CHALLENGE:
|
||||
strcpy(result->reason, "Invalid challenge format. Challenge must be a valid hex string.");
|
||||
break;
|
||||
case NOSTR_ERROR_NIP42_URL_MISMATCH:
|
||||
strcpy(result->reason, "Relay URL in auth event does not match server. Use 'ginxsom' as relay value.");
|
||||
break;
|
||||
@@ -576,12 +573,6 @@ int nostr_validate_unified_request(const nostr_unified_request_t *request,
|
||||
case NOSTR_ERROR_EVENT_INVALID_TAGS:
|
||||
strcpy(result->reason, "Required tags missing. Auth event must include 'relay' and 'expiration' tags.");
|
||||
break;
|
||||
case NOSTR_ERROR_NIP42_INVALID_RELAY_URL:
|
||||
strcpy(result->reason, "Invalid relay URL in tags. Use 'ginxsom' as the relay identifier.");
|
||||
break;
|
||||
case NOSTR_ERROR_NIP42_NOT_CONFIGURED:
|
||||
strcpy(result->reason, "NIP-42 authentication not properly configured on server.");
|
||||
break;
|
||||
default:
|
||||
snprintf(result->reason, sizeof(result->reason),
|
||||
"NIP-42 authentication failed (error code: %d). Check event structure and signature.",
|
||||
@@ -1907,7 +1898,7 @@ static int validate_challenge(const char *challenge_id) {
|
||||
}
|
||||
|
||||
validator_debug_log("NIP-42: Challenge not found\n");
|
||||
return NOSTR_ERROR_NIP42_CHALLENGE_NOT_FOUND;
|
||||
return NOSTR_ERROR_NIP42_INVALID_CHALLENGE;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user