First build with JSON RPC parsing

No responses or real functionality implemented
This commit is contained in:
Aaron Cook 2026-05-19 09:26:43 -05:00
commit fcc15f5b68
9 changed files with 3910 additions and 0 deletions

378
src/json_rpc.c Normal file
View file

@ -0,0 +1,378 @@
#include <fcntl.h>
#include <sched.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include "cJSON/cJSON.h"
#include "log.h"
#include "json_rpc.h"
static void _service_request(json_rpc_t *jrpc);
static void _generic_error_response(json_rpc_t *jrpc, json_rpc_request_t *req);
static size_t _read_bytes(int fd, void *buf, size_t sz, int timeout_ms);
static size_t _read_until(int fd, void *buf, size_t sz, char c, int timeout_ms);
int
json_rpc_init(json_rpc_t *jrpc, int infd, int outfd)
{
int fl = fcntl(infd, F_GETFL);
if (fl < 0) {
return (-1);
}
fcntl(infd, F_SETFL, fl | O_NONBLOCK);
memset(jrpc, 0, sizeof(*jrpc));
jrpc->infd = infd;
jrpc->outfd = outfd;
jrpc->bufsz = 1024*1024; /* 1MB */
jrpc->buf = malloc(jrpc->bufsz);
if (!jrpc->buf) {
log_error("Failed to allocate request buffer\r\b");
return (-1);
}
return (0);
}
int
json_rpc_add_method(json_rpc_t *jrpc, const char *method,
int (*callback)(json_rpc_request_t *req, cJSON **response, void *arg),
void *arg)
{
return (-1);
}
void
json_rpc_run(json_rpc_t *jrpc)
{
log_info("Started server\r\n");
while (1) {
fd_set fds;
struct timeval tv = {
.tv_sec = 1,
.tv_usec = 10000, /* 10 ms */
};
FD_ZERO(&fds);
FD_SET(jrpc->infd, &fds);
if (select(1, &fds, NULL, NULL, &tv) > 0) {
_service_request(jrpc);
}
if (jrpc->cancelled) {
log_info("Cancelled\r\n");
break;
}
sched_yield();
}
free(jrpc->buf);
for (size_t i = 0; i < jrpc->method_cnt; i++) {
free(jrpc->methods[i].method);
}
free(jrpc->methods);
}
void
json_rpc_cancel(json_rpc_t *jrpc)
{
jrpc->cancelled = 1;
}
static void
_service_request(json_rpc_t *jrpc)
{
char *buf = jrpc->buf;
char *len_str;
char *content;
size_t p = 0;
size_t ret;
long content_len;
json_rpc_request_t request;
/* read Content-Length: ...\r\n */
ret = _read_bytes(jrpc->infd, &buf[p], 16, 1000);
if ((ret != 16) || (memcmp(&buf[p], "Content-Length: ", 16))) {
log_error("Failed to read request header\r\n");
return;
}
p += ret;
len_str = &buf[p];
ret = _read_until(jrpc->infd, &buf[p], jrpc->bufsz - p, '\n', 1000);
p += ret;
if ((ret == 0) || (buf[p-1] != '\n')) {
log_error("Failed to read content length value\r\n");
return;
}
content_len = strtol(len_str, NULL, 10);
if (content_len < 0) {
log_warn("Invalid content length %ld\r\n", content_len);
return;
}
if (content_len > (jrpc->bufsz - p - 3)) {
log_warn("Content too long (%ld)\r\n", content_len);
return;
}
/* Read empty CRLF */
ret = _read_bytes(jrpc->infd, &buf[p], 2, 1000);
if (ret != 2) {
log_error("Failed to read blank line\r\n");
return;
}
p += ret;
content = &buf[p];
ret = _read_bytes(jrpc->infd, &buf[p], content_len, 1000);
if (ret != content_len) {
log_error("Failed to read all of content, exp %ld, got %ld\r\n",
content_len, ret);
return;
}
p += ret;
buf[p] = '\0';
/* JSON parsing */
request.request = cJSON_Parse(content);
if ((!request.request) || (!cJSON_IsObject(request.request))) {
log_error("Failed to parse request %s\r\n", buf);
return;
}
{
char *req_pretty = cJSON_Print(request.request);
if (req_pretty) {
log_info("|<<| %s\r\n", req_pretty);
free(req_pretty);
}
}
request.id = cJSON_GetObjectItem(request.request, "id");
if ((!request.id) ||
((!cJSON_IsNumber(request.id)) && (!cJSON_IsString(request.id)))) {
log_error("Invalid ID format\r\n");
return;
}
request.method = cJSON_GetObjectItem(request.request, "method");
if ((!request.method) || (!cJSON_IsString(request.method))) {
log_error("Invalid method format\r\n");
return;
}
request.params = cJSON_GetObjectItem(request.request, "params");
if (request.params) {
if ((!cJSON_IsArray(request.params)) && (!cJSON_IsObject(request.params))) {
log_error("Invalid params format\r\n");
return;
}
}
{
json_rpc_method_t *method = NULL;
for (size_t i = 0; i < jrpc->method_cnt; i++) {
if (!strcmp(jrpc->methods[i].method, request.method->valuestring)) {
method = &jrpc->methods[i];
break;
}
}
if (!method) {
log_warn("No handler for method \"%s\"\r\n", request.method->valuestring);
_generic_error_response(jrpc, &request);
} else {
/* TODO */
}
}
cJSON_Delete(request.request);
}
static void
_generic_error_response(json_rpc_t *jrpc, json_rpc_request_t *req)
{
cJSON *resp = cJSON_CreateObject();
cJSON *err_obj;
cJSON *val;
if (!resp) {
return;
}
if (cJSON_IsNumber(req->id)) {
val = cJSON_AddNumberToObject(resp, "id", req->id->valuedouble);
} else {
val = cJSON_AddStringToObject(resp, "id", req->id->valuestring);
}
if (!val) {
cJSON_Delete(resp);
return;
}
err_obj = cJSON_AddObjectToObject(resp, "error");
if (!err_obj) {
cJSON_Delete(resp);
return;
}
val = cJSON_AddNumberToObject(err_obj, "code", -32803);
if (!val) {
cJSON_Delete(resp);
return;
}
val = cJSON_AddStringToObject(err_obj, "message", "Not implemented");
if (!val) {
cJSON_Delete(resp);
return;
}
{
char *resp_str = cJSON_PrintUnformatted(resp);
size_t resp_str_len;
if (!resp_str) {
cJSON_Delete(resp);
return;
}
resp_str_len = strlen(resp_str);
dprintf(jrpc->outfd, "Content-Length: %ld\r\n", resp_str_len);
write(jrpc->outfd, resp_str, resp_str_len);
free(resp_str);
resp_str = cJSON_Print(resp);
if (resp_str) {
log_info(">> %s\r\n", resp_str);
free(resp_str);
}
}
cJSON_Delete(resp);
}
static size_t
_read_bytes(int fd, void *buf, size_t sz, int timeout_ms)
{
char *b = buf;
fd_set fds;
size_t ret = 0;
struct timespec start;
if (clock_gettime(CLOCK_MONOTONIC, &start)) {
return (ret);
}
while (ret < sz) {
struct timespec now;
int elapsed_ms;
struct timeval tv = {
.tv_sec = timeout_ms / 1000,
.tv_usec = (timeout_ms % 1000) * 1000,
};
FD_ZERO(&fds);
FD_SET(fd, &fds);
if (select(1, &fds, NULL, NULL, &tv) > 0) {
ssize_t tmp = read(fd, &b[ret], (sz - ret));
if (tmp <= 0) {
goto _read_bytes_ret;
}
ret += tmp;
}
if (clock_gettime(CLOCK_MONOTONIC, &now)) {
return (ret);
}
if (now.tv_nsec < start.tv_nsec) {
now.tv_nsec += 1000000000;
now.tv_sec -= 1;
}
elapsed_ms = (((now.tv_sec - start.tv_sec) * 1000) +
((now.tv_nsec - start.tv_nsec + 500000) / 1000000));
if (elapsed_ms > timeout_ms) {
goto _read_bytes_ret;
}
}
_read_bytes_ret:
return (ret);
}
static size_t
_read_until(int fd, void *buf, size_t sz, char c, int timeout_ms)
{
char *b = buf;
fd_set fds;
size_t ret = 0;
struct timespec start;
if (clock_gettime(CLOCK_MONOTONIC, &start)) {
return (ret);
}
while (ret < sz) {
struct timespec now;
int elapsed_ms;
struct timeval tv = {
.tv_sec = timeout_ms / 1000,
.tv_usec = (timeout_ms % 1000) * 1000,
};
FD_ZERO(&fds);
FD_SET(fd, &fds);
if (select(1, &fds, NULL, NULL, &tv) > 0) {
ssize_t tmp = read(fd, &b[ret], 1);
if (tmp <= 0) {
goto _read_until_ret;
}
ret += tmp;
if (b[ret-tmp] == c) {
goto _read_until_ret;
}
}
if (clock_gettime(CLOCK_MONOTONIC, &now)) {
goto _read_until_ret;
}
if (now.tv_nsec < start.tv_nsec) {
now.tv_nsec += 1000000000;
now.tv_sec -= 1;
}
elapsed_ms = (((now.tv_sec - start.tv_sec) * 1000) +
((now.tv_nsec - start.tv_nsec + 500000) / 1000000));
if (elapsed_ms > timeout_ms) {
goto _read_until_ret;
}
}
_read_until_ret:
return (ret);
}

65
src/json_rpc.h Normal file
View file

@ -0,0 +1,65 @@
#ifndef _JSON_RPC_H_
#define _JSON_RPC_H_
#include <pthread.h>
#include <stdint.h>
#include "cJSON/cJSON.h"
typedef struct json_rpc_request_struct {
/** Base request structure, guaranteed to be an object */
cJSON *request;
/** Reference to the value of the ID field, guaranteed to be a string or number */
cJSON *id;
/** Reference to the value of the method field, guaranteed to be a string */
cJSON *method;
/** Optional reference to the value of the params field, guaranteed to be an
* object or array if not NULL */
cJSON *params;
} json_rpc_request_t;
typedef struct json_rpc_method_struct {
/** "method" field to match on */
char *method;
/** User arg to pass into callback */
void *arg;
/** Callback to handle the method - 0 return indicates to send back a
* successful result, non-zero will treat the response object as a response
* error object */
int (*callback)(json_rpc_request_t *req, cJSON **response, void *arg);
} json_rpc_method_t;
typedef struct json_rpc_struct {
/** Socket to read requests from */
int infd;
/** Socket to write responses to */
int outfd;
/** List of methods added */
json_rpc_method_t *methods;
/** Number of methods added */
size_t method_cnt;
/** Main server thread */
pthread_t thread;
/** Allocated buffer for reading requests */
void *buf;
/** Size of the reqeust buffer */
size_t bufsz;
/** Cancelled by an interrupt */
volatile int cancelled;
} json_rpc_t;
int json_rpc_init(json_rpc_t *jrpc, int infd, int outfd);
int json_rpc_add_method(json_rpc_t *jrpc, const char *method,
int (*callback)(json_rpc_request_t *req, cJSON **response, void *arg),
void *arg);
void json_rpc_run(json_rpc_t *jrpc);
void json_rpc_cancel(json_rpc_t *jrpc);
#endif /* _JSON_RPC_H_ */

48
src/log.h Normal file
View file

@ -0,0 +1,48 @@
#ifndef _PAWN_LSP_LOG_H_
#define _PAWN_LSP_LOG_H_
#include <stdio.h>
#define COL_BLU "\e[38;5;12m\e[1m"
#define COL_GRE "\e[38;5;82m\e[1m"
#define COL_RED "\e[38;5;9m\e[1m"
#define COL_CYA "\e[38;5;50m\e[1m"
#define COL_YEL "\e[38;5;11m\e[1m"
#define COL_ORA "\e[38;5;202m\e[1m"
#define COL_DONE "\e[0m"
extern FILE *logger;
#define log_info(fmt, ...) do { \
const char *__fmt = "[" COL_CYA "INFO " COL_DONE " | %s:%d] " fmt; \
fprintf(stderr, __fmt, __FILE__, __LINE__, ##__VA_ARGS__); \
fflush(stderr); \
if (logger) { \
fprintf(logger, __fmt, __FILE__, __LINE__, ##__VA_ARGS__); \
fflush(logger); \
} \
} while (0)
#define log_warn(fmt, ...) do { \
const char *__fmt = "[" COL_YEL "WARN " COL_DONE " | %s:%d] " fmt; \
fprintf(stderr, __fmt, __FILE__, __LINE__, ##__VA_ARGS__); \
fflush(stderr); \
if (logger) { \
fprintf(logger, __fmt, __FILE__, __LINE__, ##__VA_ARGS__); \
fflush(logger); \
} \
} while (0)
#define log_error(fmt, ...) do { \
const char *__fmt = "[" COL_ORA "ERROR" COL_DONE " | %s:%d] " fmt; \
fprintf(stderr, __fmt, __FILE__, __LINE__, ##__VA_ARGS__); \
fflush(stderr); \
if (logger) { \
fprintf(logger, __fmt, __FILE__, __LINE__, ##__VA_ARGS__); \
fflush(logger); \
} \
} while (0)
#endif /* _PAWN_LSP_LOG_H_ */

90
src/lsp.h Normal file
View file

@ -0,0 +1,90 @@
#ifndef _LSP_H_
#define _LSP_H_
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
/* Ref: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/ */
typedef enum lsp_error_enum {
// Defined by JSON-RPC
LSP_ERR_ParseError = -32700,
LSP_ERR_InvalidRequest = -32600,
LSP_ERR_MethodNotFound = -32601,
LSP_ERR_InvalidParams = -32602,
LSP_ERR_InternalError = -32603,
/**
* This is the start range of JSON-RPC reserved error codes.
* It doesn't denote a real error code. No LSP error codes should
* be defined between the start and end range. For backwards
* compatibility the `ServerNotInitialized` and the `UnknownErrorCode`
* are left in the range.
*
* @since 3.16.0
*/
LSP_ERR_jsonrpcReservedErrorRangeStart = -32099,
/**
* Error code indicating that a server received a notification or
* request before the server received the `initialize` request.
*/
LSP_ERR_ServerNotInitialized = -32002,
LSP_ERR_UnknownErrorCode = -32001,
/**
* This is the end range of JSON-RPC reserved error codes.
* It doesn't denote a real error code.
*
* @since 3.16.0
*/
LSP_ERR_jsonrpcReservedErrorRangeEnd = -32000,
/**
* This is the start range of LSP reserved error codes.
* It doesn't denote a real error code.
*
* @since 3.16.0
*/
LSP_ERR_lspReservedErrorRangeStart = -32899,
/**
* A request failed but it was syntactically correct, e.g the
* method name was known and the parameters were valid. The error
* message should contain human readable information about why
* the request failed.
*
* @since 3.17.0
*/
LSP_ERR_RequestFailed = -32803,
/**
* The server cancelled the request. This error code should
* only be used for requests that explicitly support being
* server cancellable.
*
* @since 3.17.0
*/
LSP_ERR_ServerCancelled = -32802,
/**
* The server detected that the content of a document got
* modified outside normal conditions. A server should
* NOT send this error code if it detects a content change
* in its unprocessed messages. The result even computed
* on an older state might still be useful for the client.
*
* If a client decides that a result is not of any use anymore
* the client should cancel the request.
*/
LSP_ERR_ContentModified = -32801,
/**
* The client has canceled a request and a server has detected
* the cancel.
*/
LSP_ERR_RequestCancelled = -32800,
} lsp_error_e;
#endif /* _LSP_H_ */

61
src/main.c Normal file
View file

@ -0,0 +1,61 @@
#include <signal.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include "log.h"
#include "json_rpc.h"
void sighandler(int signal);
static json_rpc_t jrpc;
FILE *logger = NULL;
int
main(int argc, char **argv)
{
struct termios term_orig;
struct termios term_new;
if (argc < 2) {
fprintf(stderr, "Usage: pawn_lsp <pawncc> [...pawncc options]\r\n");
return (-1);
}
logger = fopen("pawn_lsp.log", "w");
if (signal(SIGINT, sighandler) == SIG_ERR) {
log_error("Failed to intialize signal handling\r\n");
return (-1);
}
tcgetattr(STDIN_FILENO, &term_orig);
memcpy(&term_new, &term_orig, sizeof(term_orig));
term_new.c_lflag &= ~(ICANON | ECHO);
term_new.c_cc[VMIN] = 1;
term_new.c_cc[VTIME] = 0;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &term_new);
if (json_rpc_init(&jrpc, STDIN_FILENO, STDOUT_FILENO)) {
log_error("Failed to initialize server\r\n");
return (-1);
}
json_rpc_run(&jrpc);
if (logger) {
fclose(logger);
}
tcsetattr(STDIN_FILENO, TCSAFLUSH, &term_orig);
return (0);
}
void
sighandler(int signal)
{
if (signal == SIGINT) {
json_rpc_cancel(&jrpc);
}
}