1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- #include <stdlib.h>
- #include <time.h>
- #include <uv.h>
- #include "player.h"
- #include "server.h"
- uv_tcp_t* http_server = NULL;
- #define HTTP_HEADER \
- "HTTP/1.1 200 OK\r\n" \
- "Content-Type: text/plain; charset=utf-8\r\n" \
- "X-Content-Type-Options: nosniff\r\n" \
- "Content-Length: %d\r\n\r\n"
- void free_tcp_connection(uv_handle_t* handle) {
- free(handle->data);
- free(handle);
- }
- void free_http_response(uv_write_t* res, int status) {
- (void)status;
- uv_close((uv_handle_t*)res->data, free_tcp_connection);
- free(res);
- }
- void new_http_connection(uv_stream_t* server, int status) {
- if (status < 0) {
- fprintf(stderr, "Connection error: %s\n", uv_strerror(status));
- return;
- }
- uv_loop_t* loop = uv_default_loop();
- uv_tcp_t* tcp_connection = malloc(sizeof(uv_tcp_t));
- uv_tcp_init(loop, tcp_connection);
- if (uv_accept(server, (uv_stream_t*)tcp_connection) != 0) {
- uv_close((uv_handle_t*)tcp_connection, free_tcp_connection);
- return;
- }
- // Get uptime
- int uptime = time(NULL) - start_tms;
- int seconds = uptime % 60;
- int minutes = uptime / 60 % 60;
- int hours = uptime / 3600;
- // Calculate HTTP response length
- int body_length = snprintf(NULL, 0,
- "Server uptime: %02d:%02d:%02d\r\n\r\n"
- "Players online:\r\n",
- hours, minutes, seconds);
- for (int i = 0; i < MAX_PLAYERS; i++) {
- if (players[i].username[0] == '\0') continue;
- body_length += snprintf(NULL, 0,
- "\r\n* %s\r\n"
- "Scene: %s\r\n",
- players[i].username, players[i].scene);
- }
- int header_length = snprintf(NULL, 0, HTTP_HEADER, body_length);
- // Generate the HTTP response
- tcp_connection->data = malloc(header_length + body_length + 1);
- int pos = sprintf(tcp_connection->data, HTTP_HEADER, body_length);
- pos += sprintf(tcp_connection->data + pos,
- "Server uptime: %02d:%02d:%02d\r\n\r\n"
- "Players online:\r\n",
- hours, minutes, seconds);
- for (int i = 0; i < MAX_PLAYERS; i++) {
- if (players[i].username[0] == '\0') continue;
- pos += sprintf(tcp_connection->data + pos,
- "\r\n* %s\r\n"
- "Scene: %s\r\n",
- players[i].username, players[i].scene);
- }
- uv_write_t* res = malloc(sizeof(uv_write_t));
- res->data = tcp_connection;
- uv_buf_t buf = uv_buf_init(tcp_connection->data, header_length + body_length);
- uv_write(res, (uv_stream_t*)tcp_connection, &buf, 1, free_http_response);
- }
|