Skip to content

Dhruv-Davda/Http-Server

Repository files navigation

Multi-threaded HTTP Server

A HTTP server implementation using Java socket programming. Handles multiple concurrent clients with threading and supports basic HTTP operations.

Features

Core Functionality

  • Multi-threaded Request Handling: Configurable thread pool with connection queue
  • HTTP/1.1 Protocol Support: Full request parsing and response generation
  • GET Requests: Serve HTML files and download binary files
  • POST Requests: Upload JSON files to the server
  • Connection Management: Keep-alive, timeouts, and connection limits
  • Security Features: Path traversal protection and host validation
  • Comprehensive Logging: Real-time monitoring with timestamps

Supported File Types

  • HTML Files (.html, .htm): Rendered in browser with text/html; charset=utf-8
  • Binary Files (.png, .jpg, .jpeg, .txt): Downloaded as application/octet-stream
  • JSON Uploads: POST requests with application/json content type

Security Measures

  • Path Traversal Protection: Blocks ../, ./, and absolute paths
  • Host Header Validation: Ensures requests are directed to correct server
  • Request Size Limits: Prevents buffer overflow attacks (8KB max)
  • Connection Timeouts: Prevents resource exhaustion (30 seconds)
  • Input Validation: Validates JSON format and file types

Project Structure

project/
├── HttpServer.java          # Main server class
├── ClientHandler.java       # Individual client connection handler
├── HttpRequest.java         # HTTP request representation
├── HttpResponse.java        # HTTP response representation
├── CreateTestImages.java    # Utility to create test images
├── README.md               # This file
└── resources/              # Web resources directory
    ├── index.html          # Main page
    ├── about.html          # About page
    ├── contact.html        # Contact/testing page
    ├── sample.txt          # Sample text file
    ├── logo.png            # Sample PNG image
    ├── photo.jpg           # Sample JPEG image
    └── uploads/            # Directory for POST uploads

Building and Running

Prerequisites

  • Java 8 or higher
  • No external dependencies required

Compilation

javac *.java

Running the Server

Default Configuration

java HttpServer
  • Host: 127.0.0.1 (localhost)
  • Port: 8080
  • Thread Pool Size: 10

Custom Configuration

java HttpServer [port] [host] [threadPoolSize]

Examples:

# Custom port
java HttpServer 9000

# Custom host and port
java HttpServer 9000 0.0.0.0

# Custom host, port, and thread pool size
java HttpServer 9000 0.0.0.0 20

Testing the Server

Basic Functionality Tests

1. HTML File Serving

# Serve main page
curl http://localhost:8080/

# Serve specific HTML files
curl http://localhost:8080/about.html
curl http://localhost:8080/contact.html

2. Binary File Downloads

# Download text file
curl -O http://localhost:8080/sample.txt

# Download PNG image
curl -O http://localhost:8080/logo.png

# Download JPEG image
curl -O http://localhost:8080/photo.jpg

3. JSON File Upload (POST)

curl -X POST http://localhost:8080/upload \
  -H "Content-Type: application/json" \
  -d '{"name": "test", "message": "Hello Server!"}'

Security Tests

Path Traversal Protection

# Should return 403 Forbidden
curl http://localhost:8080/../etc/passwd
curl http://localhost:8080/../../sensitive.txt
curl http://localhost:8080/./././../config

Host Header Validation

# Should return 400 Bad Request (missing Host)
curl -H "Host:" http://localhost:8080/

# Should return 403 Forbidden (wrong Host)
curl -H "Host: evil.com" http://localhost:8080/

Error Handling Tests

Method Not Allowed

# Should return 405 Method Not Allowed
curl -X PUT http://localhost:8080/index.html
curl -X DELETE http://localhost:8080/index.html

File Not Found

# Should return 404 Not Found
curl http://localhost:8080/nonexistent.html
curl http://localhost:8080/missing.png

Unsupported Media Type

# Should return 415 Unsupported Media Type
curl -X POST http://localhost:8080/upload \
  -H "Content-Type: text/plain" \
  -d "This is not JSON"

Configuration Options

Server Parameters

  • Port: Network port to listen on (default: 8080)
  • Host: IP address to bind to (default: 127.0.0.1)
  • Thread Pool Size: Maximum concurrent connections (default: 10)

Connection Settings

  • Connection Timeout: 30 seconds
  • Max Requests per Connection: 100
  • Max Request Size: 8KB
  • Connection Queue Size: 50

File Handling

  • Resources Directory: resources/
  • Uploads Directory: resources/uploads/
  • Supported Extensions: .html, .htm, .png, .jpg, .jpeg, .txt

Performance Features

Thread Pool Management

  • Configurable Size: Default 10 threads, customizable via command line
  • Connection Queue: Queues connections when thread pool is saturated
  • Load Balancing: Distributes connections across available threads
  • Resource Monitoring: Logs thread pool status and connection counts

Connection Optimization

  • Keep-Alive Support: Maintains connections for multiple requests
  • Connection Limits: Prevents resource exhaustion
  • Timeout Management: Closes idle connections automatically
  • Binary Streaming: Efficient transfer of large files

Logging and Monitoring

  • Real-time Logging: Timestamped logs for all operations
  • Connection Tracking: Logs client connections and request details
  • Security Logging: Records security violations and blocked requests
  • Performance Metrics: Thread pool status and connection statistics

Security Implementation

Path Traversal Protection

// Blocks patterns like ../, ./, //, etc.
private static final Pattern PATH_TRAVERSAL_PATTERN = 
    Pattern.compile(".*\\.\\..*|.*//.*|.*\\./.*");

Host Header Validation

// Ensures requests are directed to correct server
public boolean isValidHost(String hostHeader, String serverHost, int serverPort) {
    // Validates against server configuration
}

Input Validation

  • JSON Validation: Checks for valid JSON format in POST requests
  • File Type Validation: Restricts file types to supported extensions
  • Request Size Limits: Prevents buffer overflow attacks
  • Header Validation: Ensures required headers are present

HTTP Response Examples

Successful HTML Response (200 OK)

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 1234
Date: Thu, 15 Mar 2024 10:30:00 GMT
Server: Multi-threaded HTTP Server
Connection: keep-alive
Keep-Alive: timeout=30, max=100

<!DOCTYPE html>...

Binary File Response (200 OK)

HTTP/1.1 200 OK
Content-Type: application/octet-stream
Content-Length: 5842
Content-Disposition: attachment; filename="logo.png"
Date: Thu, 15 Mar 2024 10:30:00 GMT
Server: Multi-threaded HTTP Server
Connection: keep-alive

[binary data]

POST Success Response (201 Created)

HTTP/1.1 201 Created
Content-Type: application/json
Content-Length: 156
Date: Thu, 15 Mar 2024 10:30:00 GMT
Server: Multi-threaded HTTP Server
Connection: keep-alive

{
  "status": "success",
  "message": "File created successfully",
  "filepath": "/uploads/upload_20240315_103000_a7b9c2d1.json"
}

Troubleshooting

Common Issues

Port Already in Use

# Error: Address already in use
# Solution: Use a different port
java HttpServer 9000

Permission Denied

# Error: Permission denied
# Solution: Use a port above 1024 or run with sudo
java HttpServer 8080

File Not Found

# Error: resources directory not found
# Solution: Ensure you're running from the project directory
ls resources/  # Should show the resources directory

Debug Mode

The server provides comprehensive logging. Check the console output for:

  • Connection details
  • Request parsing
  • Security violations
  • Thread pool status
  • Error messages

Performance Considerations

Thread Pool Sizing

  • Low Load: 5-10 threads sufficient
  • Medium Load: 10-20 threads recommended
  • High Load: 20+ threads with monitoring

File Transfer Optimization

  • Small Files: Direct memory transfer
  • Large Files: Streaming with appropriate buffer sizes
  • Binary Files: Preserved data integrity

Connection Management

  • Keep-Alive: Reduces connection overhead
  • Timeouts: Prevents resource leaks
  • Limits: Prevents resource exhaustion

Contributing

This project demonstrates advanced networking concepts and HTTP protocol implementation. Key areas for extension:

  1. HTTPS Support: Add SSL/TLS encryption
  2. Caching: Implement HTTP caching headers
  3. Compression: Add gzip compression support
  4. Authentication: Implement basic authentication
  5. Rate Limiting: Add request rate limiting
  6. Metrics: Enhanced performance monitoring

License

This project is created for educational purposes to demonstrate HTTP server implementation using Java socket programming.

Assignment Requirements Compliance

This implementation fulfills all assignment requirements:

Server Configuration: Command-line arguments for port, host, and thread pool size
Socket Implementation: TCP sockets with proper lifecycle management
Multi-threading: Thread pool with connection queue and synchronization
HTTP Request Handling: Full parsing of GET/POST requests with headers
GET Implementation: HTML serving and binary file downloads
POST Implementation: JSON file uploads with validation
Security Requirements: Path traversal protection and host validation
Connection Management: Keep-alive, timeouts, and connection limits
HTTP Response Format: Proper status codes and headers
Logging Requirements: Comprehensive timestamped logging

The server is production-ready and demonstrates advanced networking and concurrent programming concepts.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors