#include "algo_skel.h" #define NAIVE_BUFFER 128 void free_naive(void* app_ctx) { if (app_ctx != NULL) free(app_ctx); } void on_tcp_co(struct evt_core_ctx* ctx, struct evt_core_cat* cat, int fd) { int conn_sock, err; struct sockaddr in_addr; socklen_t in_len; struct epoll_event current_event; in_len = sizeof(in_addr); //while (1) { conn_sock = accept(fd, &in_addr, &in_len); //if (conn_sock == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) break; if (conn_sock == -1) goto co_error; evt_core_add_fd (ctx, "tcp-data", fd); //} return; co_error: perror("Failed to handle new connection"); exit(EXIT_FAILURE); } void on_tcp_data(struct evt_core_ctx* ctx, struct evt_core_cat* cat, int fd) { struct evt_core_cat* udp = g_hash_table_lookup (ctx->catlist, "udp-data"); if (udp == NULL || udp->socklist->len < 1) goto co_error; int udp_fd = g_array_index(udp->socklist, int, 0); char buffer[NAIVE_BUFFER]; int nread, nwrite; nread = read(fd, buffer, sizeof(char) * NAIVE_BUFFER); if (nread == 0) return; //if (nread == -1 && errno == EAGAIN) return; if (nread == -1) goto co_error; nwrite = write(udp_fd, buffer, nread); if (nwrite == -1 && errno == EAGAIN) { printf("Lost data EAGAIN\n"); return; } if (nwrite == -1) goto co_error; if (nread != nwrite) { printf("Lost data not everything has been written\n"); return; } return; co_error: perror("Failed to handle read write for tcp-data"); exit(EXIT_FAILURE); } void on_udp_data(struct evt_core_ctx* ctx, struct evt_core_cat* cat, int fd) { struct evt_core_cat* tcp = g_hash_table_lookup (ctx->catlist, "tcp-data"); if (tcp == NULL || tcp->socklist->len < 1) goto co_error; int tcp_fd = g_array_index(tcp->socklist, int, 0); char buffer[NAIVE_BUFFER]; int nread, nwrite; nread = read(fd, buffer, sizeof(char) * NAIVE_BUFFER); if (nread == 0) return; //if (nread == -1 && errno == EAGAIN) return; if (nread == -1) goto co_error; nwrite = write(tcp_fd, buffer, nread); if (nwrite == -1 && errno == EAGAIN) { printf("Lost data EAGAIN\n"); return; } if (nwrite == -1) goto co_error; if (nread != nwrite) { printf("Lost data not everything has been written\n"); return; } return; co_error: perror("Failed to handle read write for udp-data"); exit(EXIT_FAILURE); } void algo_naive(struct algo_skel* as) { as->on_tcp_data.name = "tcp-data"; as->on_tcp_data.flags = 0; as->on_tcp_data.app_ctx = NULL; as->on_tcp_data.free_app_ctx = free_naive; as->on_tcp_data.cb = on_tcp_data; as->on_tcp_data.socklist = NULL; as->on_tcp_co.name = "tcp-listen"; as->on_tcp_co.flags = 0; as->on_tcp_co.app_ctx = NULL; as->on_tcp_co.free_app_ctx = free_naive; as->on_tcp_co.cb = on_tcp_co; as->on_tcp_co.socklist = NULL; as->on_udp_data.name = "udp-data"; as->on_udp_data.flags = 0; as->on_udp_data.app_ctx = NULL; as->on_udp_data.free_app_ctx = free_naive; as->on_udp_data.cb = on_udp_data; as->on_udp_data.socklist = NULL; /*if (as->on_tcp_data.app_ctx == NULL || as->on_udp_data.app_ctx == NULL) { fprintf(stderr, "Failed to malloc naive_ctx\n"); exit(EXIT_FAILURE); }*/ }