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

4
.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
compile_flags.txt
build/
.clangd

43
Makefile Normal file
View file

@ -0,0 +1,43 @@
CC:=clang
BUILD_DIR:=build
CFLAGS= \
-pthread \
-Wall \
-MMD \
-g
LDFLAGS= \
-lpthread
INCLUDES= \
-Isrc \
-Ilibraries
SRCS= \
libraries/cJSON/cJSON.c \
src/json_rpc.c \
src/main.c
OBJS=$(addprefix $(BUILD_DIR)/,$(addsuffix .o,$(basename $(SRCS))))
DEPS=$(addprefix $(BUILD_DIR)/,$(addsuffix .d,$(basename $(SRCS))))
BIN=$(BUILD_DIR)/bin/pawn_lsp
.PHONY: pawn_lsp clean
pawn_lsp: $(BIN)
$(BIN): $(OBJS)
mkdir -p $(dir $@)
$(CC) $(CFLAGS) $(LDFLAGS) $(INCLUDES) -o $(BIN) $(OBJS)
$(BUILD_DIR)/%.o: %.c
mkdir -p $(dir $@)
$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@
clean:
rm -rf $(BUILD_DIR)
-include $(DEPS)

2936
libraries/cJSON/cJSON.c Normal file

File diff suppressed because it is too large Load diff

285
libraries/cJSON/cJSON.h Normal file
View file

@ -0,0 +1,285 @@
/*
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON__h
#define cJSON__h
#ifdef __cplusplus
extern "C"
{
#endif
#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
#define __WINDOWS__
#endif
#ifdef __WINDOWS__
/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options:
CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
For *nix builds that support visibility attribute, you can define similar behavior by
setting default visibility to hidden by adding
-fvisibility=hidden (for gcc)
or
-xldscope=hidden (for sun cc)
to CFLAGS
then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
*/
#define CJSON_CDECL __cdecl
#define CJSON_STDCALL __stdcall
/* export symbols by default, this is necessary for copy pasting the C and header file */
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_EXPORT_SYMBOLS
#endif
#if defined(CJSON_HIDE_SYMBOLS)
#define CJSON_PUBLIC(type) type CJSON_STDCALL
#elif defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL
#elif defined(CJSON_IMPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL
#endif
#else /* !__WINDOWS__ */
#define CJSON_CDECL
#define CJSON_STDCALL
#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
#else
#define CJSON_PUBLIC(type) type
#endif
#endif
/* project version */
#define CJSON_VERSION_MAJOR 1
#define CJSON_VERSION_MINOR 7
#define CJSON_VERSION_PATCH 9
#include <stddef.h>
/* cJSON Types: */
#define cJSON_Invalid (0)
#define cJSON_False (1 << 0)
#define cJSON_True (1 << 1)
#define cJSON_NULL (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_Raw (1 << 7) /* raw json */
#define cJSON_IsReference 256
#define cJSON_StringIsConst 512
/* The cJSON structure: */
typedef struct cJSON
{
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *next;
struct cJSON *prev;
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
struct cJSON *child;
/* The type of the item, as above. */
int type;
/* The item's string, if type==cJSON_String and type == cJSON_Raw */
char *valuestring;
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
int valueint;
/* The item's number, if type==cJSON_Number */
double valuedouble;
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
char *string;
} cJSON;
typedef struct cJSON_Hooks
{
/* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
void *(CJSON_CDECL *malloc_fn)(size_t sz);
void (CJSON_CDECL *free_fn)(void *ptr);
} cJSON_Hooks;
typedef int cJSON_bool;
/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
* This is to prevent stack overflows. */
#ifndef CJSON_NESTING_LIMIT
#define CJSON_NESTING_LIMIT 1000
#endif
/* returns the version of cJSON as a string */
CJSON_PUBLIC(const char*) cJSON_Version(void);
/* Supply malloc, realloc and free functions to cJSON */
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
/* Render a cJSON entity to text for transfer/storage. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. */
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
/* Delete a cJSON entity and all subentities. */
CJSON_PUBLIC(void) cJSON_Delete(cJSON *c);
/* Returns the number of items in an array (or object). */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
/* Get item "string" from object. Case insensitive. */
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
/* Check if the item is a string and return its valuestring */
CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item);
/* These functions check the type of an item */
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
/* These calls create a cJSON item of the appropriate type. */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
/* raw json */
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
/* Create a string where valuestring references a string so
* it will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
/* Create an object/arrray that only references it's elements so
* they will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
/* These utilities create an Array of count items. */
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count);
/* Append item to the specified array/object. */
CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
* writing to `item->string` */
CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
/* Remove/Detatch items from Arrays/Objects. */
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
/* Update array items. */
CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
need to be released. With recurse!=0, it will duplicate any children connected to the item.
The item->next and ->prev pointers are always zero on return from Duplicate. */
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
CJSON_PUBLIC(void) cJSON_Minify(char *json);
/* Helper functions for creating and adding items to an object at the same time.
* They return the added item or NULL on failure. */
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
/* helper for the cJSON_SetNumberValue macro */
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
/* Macro for iterating over an array or object */
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
CJSON_PUBLIC(void) cJSON_free(void *object);
#ifdef __cplusplus
}
#endif
#endif

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);
}
}