// httpd.cpp - Lightweight HTTP Server for AGI Frontend (C++) #include #include #include #include #include #include #include #include constexpr int PORT = 8080; constexpr int BUFFER_SIZE = 4096; const char *HTTP_200 = "HTTP/1.1 200 OK\r\n"; const char *HTTP_404 = "HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\n\r\nNot Found"; const char *CONTENT_HTML = "Content-Type: text/html\r\n"; void send_file(int client_fd, const char *filepath) { int fd = open(filepath, O_RDONLY); if (fd < 0) { write(client_fd, HTTP_404, strlen(HTTP_404)); return; } struct stat st; fstat(fd, &st); char header[512]; snprintf(header, sizeof(header), "%s%sContent-Length: %ld\r\n\r\n", HTTP_200, CONTENT_HTML, st.st_size); write(client_fd, header, strlen(header)); char buf[BUFFER_SIZE]; ssize_t n; while ((n = read(fd, buf, sizeof(buf))) > 0) { write(client_fd, buf, n); } close(fd); } void handle_request(int client_fd) { char buffer[BUFFER_SIZE]; ssize_t bytes_read = read(client_fd, buffer, sizeof(buffer) - 1); if (bytes_read <= 0) { close(client_fd); return; } buffer[bytes_read] = '\0'; /* Parse request line */ char method[16], path[256]; sscanf(buffer, "%s %s", method, path); std::cout << "[" << method << "] " << path << std::endl; /* Route requests */ if (strcmp(path, "/") == 0 || strcmp(path, "/index.html") == 0) { send_file(client_fd, "frontend/index.html"); } else { write(client_fd, HTTP_404, strlen(HTTP_404)); } close(client_fd); } int main() { int server_fd, client_fd; struct sockaddr_in addr; server_fd = socket(AF_INET, SOCK_STREAM, 0); if (server_fd < 0) { perror("socket"); return 1; } int opt = 1; setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(PORT); if (bind(server_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { perror("bind"); close(server_fd); return 1; } if (listen(server_fd, 10) < 0) { perror("listen"); close(server_fd); return 1; } std::cout << "🧠 AGI Frontend Server running on http://localhost:" << PORT << std::endl; std::cout << " Serving: frontend/index.html\n" << std::endl; while (1) { client_fd = accept(server_fd, NULL, NULL); if (client_fd < 0) { perror("accept"); continue; } handle_request(client_fd); } close(server_fd); return 0; }