Librería para enchufes en C.
at main 122 lines 2.2 kB view raw
1#include "lib/log.h" 2#include "lib/enchufe.h" 3#include <pthread.h> 4#include <stdbool.h> 5#include <string.h> 6#define BUF_LEN 0x1000 7#define THREAD_COUNT 5 8 9typedef struct { 10 char* buf; 11 size_t len; 12 size_t cap; 13} DynStr; 14 15void dynstr_append(DynStr* str, char ch) { 16 if (str != NULL) { 17 if (str->len == str->cap) { 18 str-> buf = realloc(str->buf, str->cap * 2); 19 } 20 str->buf[str->len] = ch; 21 } else { 22 try (-1); 23 } 24} 25 26DynStr atods(const char* ch) { 27 size_t l = strlen(ch); 28 return (DynStr){ 29 .buf = (char*)ch, 30 .len = l, 31 .cap = l, 32 }; 33} 34 35DynStr dynstr_init() { 36 DynStr ret = { 37 .buf = (char*)calloc(0xF0, sizeof(char)), 38 .len = 0, 39 .cap = 0xF0, 40 }; 41 return ret; 42} 43 44char dynstr_at(DynStr str, size_t idx) { 45 return (char)str.buf[idx]; 46} 47 48void dynstr_deinit(DynStr* str) { 49 if (str && str->buf) { 50 free(str->buf); 51 str->buf = NULL; 52 } 53} 54 55void dynstr_clear(DynStr* str) { 56 if (str != NULL) { 57 memset(str->buf, 0, str->len); 58 } 59} 60 61void buffer_clear(Buffer* buf) { 62 if (buf != NULL) { 63 memset(buf->buf, 0, buf->len); 64 } 65} 66 67bool dynstr_eq(DynStr a, DynStr b) { 68 return strcmp(a.buf, b.buf) == 0; 69} 70 71void* echo(void* args) { 72 if (args != NULL) { 73 Enchufe enchufe = *(Enchufe*)args; 74 Enchufe cliente = acepta(enchufe); 75 log_info("Accepted client: %d\n", cliente.fd); 76 77 char* data[BUF_LEN]; 78 Buffer buf = { 79 .buf = (Byte*)data, 80 .len = BUF_LEN, 81 }; 82 buffer_clear(&buf); 83 int bytes_read = recibe(cliente, buf); 84 85 DynStr str = dynstr_init(); 86 size_t i = 0; 87 for (; i < bytes_read; ++i) { 88 char ch = (char)buf.buf[i]; 89 if (ch == ' ') { 90 ++i; 91 break; 92 } 93 dynstr_append(&str, ch); 94 } 95 if (dynstr_eq(atods("GET"), str)) { 96 97 } else { 98 } 99 100 desenchufa(cliente); 101 dynstr_deinit(&str); 102 } 103 return NULL; 104} 105 106 107int main() { 108 Enchufe enchufe = enchufa((IPv4){127,0,0,1}, htons(42069)); 109 110 amarra(enchufe); 111 escucha(enchufe, 5); 112 log_info("Listening for a client to connect.\n"); 113 114 pthread_t threads[THREAD_COUNT]; 115 for (size_t i = 0; i < THREAD_COUNT; ++i) 116 pthread_create(&threads[i], NULL, echo, (void*)&enchufe); 117 for (size_t i = 0; i < THREAD_COUNT; ++i) 118 pthread_join(threads[i], NULL); 119 120 desenchufa(enchufe); 121 return 0; 122}