modular-worm/plugins/7_fs.c

82 lines
2.5 KiB
C

#include <string.h>
#include <stdio.h>
#include "api.h"
#include "error_codes.h"
#include "7_fs.h"
api_plugin_t version = {.id = 7, .flag = 0, .major = 1, .minor = 0};
/* the fct has access to the variable "data" which contains the arguments */
#define P7_DECLARE_IMPLEMENTATION(name, result, fct) \
static void p7_##name(api_msg_t *msg, p7_data_send_t *data) { \
fct; \
api_send_message(msg->plugin, &result, sizeof(result), 1); \
return; \
}
P7_DECLARE_IMPLEMENTATION(fclose, result,
printf("fclose(%p);\n", (char *)data->p1); \
int result = fclose(data->p1); \
)
P7_DECLARE_IMPLEMENTATION(fopen, result,
printf("fopen(\"%s\", \"%s\");\n", (char *)data->p1, (char *)data->p2); \
FILE* result = fopen(data->p1, data->p2); \
)
typedef struct {
char *name;
void (*fct)(api_msg_t*, p7_data_send_t*);
} p7_call_t;
static p7_call_t p7_calls[] = {
{"fopen", &p7_fopen},
{"fclose", &p7_fclose},
};
/*
This function tries to match the function requested with the existing implementation.
It calls it when the function p7_XXX is found (where the match is XXX).
@param msg the msg received with the plugin which sent the message
@param data the msg->content casted to p7_data_send_t
*/
static int p7_execute(api_msg_t *msg, p7_data_send_t *data) {
for (size_t i = 0; i < sizeof(p7_calls) / sizeof(p7_call_t); i++) {
p7_call_t current_call = p7_calls[i];
if (strncmp(data->function, current_call.name, strlen(current_call.name)) == 0) {
printf("\"%s\" matched\n", current_call.name);
current_call.fct(msg, data);
return SUCCESS;
}
}
printf("Nothing matched with \"%s\"\n", data->function);
return ERR_NOT_FOUND;
}
/*
Receive the request sent (for example a FOPEN) and tries to match the function
*/
static int p7_handle_request() {
api_msg_t msg;
msg.plugin = (api_plugin_t){0, 0, 0, 0};
int res;
if ((res = API_RECEIVE_MESSAGE(&msg.plugin, msg)) == 0) {
p7_data_send_t *data = (p7_data_send_t *)msg.content;
return p7_execute(&msg, data);
}
else {
printf("Nothing to receive %i\n", res);
return ERR_UNKNOWN;
}
}
void run_instant() {
printf("Received an instant request\n");
p7_handle_request();
}
void run() {
/* p7_handle_request(0); */
}