#include "lib/log.h" #include "lib/enchufe.h" #include #include #include #define BUF_LEN 0x1000 #define THREAD_COUNT 5 typedef struct { char* buf; size_t len; size_t cap; } DynStr; void dynstr_append(DynStr* str, char ch) { if (str != NULL) { if (str->len == str->cap) { str-> buf = realloc(str->buf, str->cap * 2); } str->buf[str->len] = ch; } else { try (-1); } } DynStr atods(const char* ch) { size_t l = strlen(ch); return (DynStr){ .buf = (char*)ch, .len = l, .cap = l, }; } DynStr dynstr_init() { DynStr ret = { .buf = (char*)calloc(0xF0, sizeof(char)), .len = 0, .cap = 0xF0, }; return ret; } char dynstr_at(DynStr str, size_t idx) { return (char)str.buf[idx]; } void dynstr_deinit(DynStr* str) { if (str && str->buf) { free(str->buf); str->buf = NULL; } } void dynstr_clear(DynStr* str) { if (str != NULL) { memset(str->buf, 0, str->len); } } void buffer_clear(Buffer* buf) { if (buf != NULL) { memset(buf->buf, 0, buf->len); } } bool dynstr_eq(DynStr a, DynStr b) { return strcmp(a.buf, b.buf) == 0; } void* echo(void* args) { if (args != NULL) { Enchufe enchufe = *(Enchufe*)args; Enchufe cliente = acepta(enchufe); log_info("Accepted client: %d\n", cliente.fd); char* data[BUF_LEN]; Buffer buf = { .buf = (Byte*)data, .len = BUF_LEN, }; buffer_clear(&buf); int bytes_read = recibe(cliente, buf); DynStr str = dynstr_init(); size_t i = 0; for (; i < bytes_read; ++i) { char ch = (char)buf.buf[i]; if (ch == ' ') { ++i; break; } dynstr_append(&str, ch); } if (dynstr_eq(atods("GET"), str)) { } else { } desenchufa(cliente); dynstr_deinit(&str); } return NULL; } int main() { Enchufe enchufe = enchufa((IPv4){127,0,0,1}, htons(42069)); amarra(enchufe); escucha(enchufe, 5); log_info("Listening for a client to connect.\n"); pthread_t threads[THREAD_COUNT]; for (size_t i = 0; i < THREAD_COUNT; ++i) pthread_create(&threads[i], NULL, echo, (void*)&enchufe); for (size_t i = 0; i < THREAD_COUNT; ++i) pthread_join(threads[i], NULL); desenchufa(enchufe); return 0; }