Skip to content

Commit 12188a0

Browse files
committed
prog: Updated ReadME.md
1 parent 4c3c30a commit 12188a0

1 file changed

Lines changed: 163 additions & 34 deletions

File tree

ReadME.md

Lines changed: 163 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,8 @@
22

33
![Java](https://img.shields.io/badge/language-Java-blue.svg?style=for-the-badge&logo=java)
44
![Maven](https://img.shields.io/badge/build-Maven-red.svg?style=for-the-badge&logo=apache-maven)
5-
![License](https://img.shields.io/badge/license-MIT-green.svg?style=for-the-badge)
65

7-
A multi-threaded HTTP/1.1 server built from scratch using low-level Java socket programming. This
6+
A Multi-threaded HTTP/1.1 server built from scratch using low-level Java socket programming. This
87
project demonstrates a deep understanding of the HTTP protocol, concurrent programming, and network security
98
fundamentals.
109

@@ -18,14 +17,14 @@ fundamentals.
1817
- [Prerequisites](#prerequisites)
1918
- [Installation & Running](#installation--running)
2019
- [Usage & Testing](#usage--testing)
20+
- [Web-Based Test Interface](#web-based-test-interface)
2121
- [Testing with `curl`](#testing-with-curl)
2222
- [Concurrency Testing](#concurrency-testing)
2323
- [Technical Deep Dive](#technical-deep-dive)
2424
- [Thread Pool Architecture](#thread-pool-architecture)
2525
- [Request Handling Pipeline](#request-handling-pipeline)
2626
- [Security Measures](#security-measures)
2727
- [Configuration](#configuration)
28-
- [License](#license)
2928

3029
---
3130

@@ -44,6 +43,7 @@ fundamentals.
4443
request limits.
4544
- **📊 Comprehensive Logging**: Detailed, timestamped logs for all server activities, managed by a dedicated `Logger`
4645
class.
46+
- **🧪 Interactive Test Suite**: Built-in web interface for testing all server endpoints and features.
4747

4848
---
4949

@@ -70,17 +70,19 @@ Http_server/
7070
│ │ │ │ └── Logger.java # Centralized logging utility
7171
│ │ │ ├── server/
7272
│ │ │ │ └── Server.java # Main server loop and thread pool management
73-
│ │ │ └── Main.java # Application entry point
73+
│ │ │ └── Main.java # Application entry point
7474
│ │ └── resources/
7575
│ │ ├── uploads/ # Directory for POST uploads
76-
│ │ ├── about.html
77-
│ │ ├── contact.html
78-
│ │ ├── index.html
79-
│ │ ├── logo.png
80-
│ │ ├── photo.jpg
81-
│ │ └── sample.txt
76+
│ │ ├── about.html # Sample HTML page
77+
│ │ ├── contact.html # Sample HTML page
78+
│ │ ├── index.html # Default home page
79+
│ │ ├── test.html # Interactive test suite
80+
│ │ ├── logo.png # Sample PNG image
81+
│ │ ├── photo.jpg # Sample JPEG image
82+
│ │ └── sample.txt # Sample text file
8283
│ └── test/
8384
│ └── test_server.ps1 # PowerShell test script
85+
├── logs/ # Server logs directory
8486
└── README.md
8587
```
8688

@@ -111,21 +113,51 @@ Http_server/
111113
3. **Run the server:**
112114
- To run with default settings (`127.0.0.1:8080`, 10 threads):
113115
```sh
114-
java -jar http_server.jar
116+
java -cp target/myartifactid-0.0-SNAPSHOT.jar Main
115117
```
116118
- To run with custom settings (e.g., port 8000, any host, 20 threads):
117119
```sh
118-
java -jar http_server.jar 8000 0.0.0.0 20
120+
java -cp target/myartifactid-0.0-SNAPSHOT.jar Main 8000 0.0.0.0 20
119121
```
120122

121123
---
122124

123125
## Usage & Testing
124126

125-
Once the server is running, you can interact with it using a browser, `curl`, or the provided test script.
127+
Once the server is running, you can interact with it using multiple methods.
128+
129+
### Web-Based Test Interface
130+
131+
The easiest way to test all server features is through the built-in web interface:
132+
133+
1. **Start the server:**
134+
```sh
135+
java -cp target/myartifactid-0.0-SNAPSHOT.jar Main
136+
```
137+
138+
2. **Open your browser and navigate to:**
139+
```
140+
http://127.0.0.1:8080/test.html
141+
```
142+
143+
3. **Interactive Test Suite Features:**
144+
- ✅ **GET Requests**: Test HTML pages, image downloads, and text files
145+
- ✅ **POST Requests**: Upload JSON data with editable text areas
146+
- ❌ **Error Cases**: Test 404, 405, 415, and 400 error responses
147+
- 🔒 **Security Tests**: Verify path traversal protection
148+
- 📊 **Live Response Display**: View status codes, headers, and response bodies in real-time
149+
150+
The test interface provides a beautiful, user-friendly way to verify that all server features are working correctly.
126151
127152
### Testing with `curl`
128153
154+
For command-line testing, you can use `curl`:
155+
156+
- **Get HTML page:**
157+
```sh
158+
curl -v http://localhost:8080/index.html
159+
```
160+
129161
- **Download a binary file:**
130162
```sh
131163
curl -v http://localhost:8080/logo.png --output downloaded_logo.png
@@ -139,14 +171,26 @@ Once the server is running, you can interact with it using a browser, `curl`, or
139171
-d '{"message": "Testing POST request"}'
140172
```
141173

174+
- **Test path traversal protection:**
175+
```sh
176+
curl -v http://localhost:8080/../etc/passwd
177+
```
178+
179+
- **Test unsupported method:**
180+
```sh
181+
curl -v -X PUT http://localhost:8080/index.html
182+
```
183+
142184
### Concurrency Testing
143185

144-
Use a tool like Apache Bench (`ab`) to simulate concurrent connections.
186+
Use Apache Bench (`ab`) to simulate concurrent connections and test server performance:
145187

146188
```sh
147-
ab -n 100 -c 10 http://localhost:8080/index.html
189+
ab -n 1000 -c 50 http://localhost:8080/index.html
148190
```
149191

192+
This command sends 1000 requests with 50 concurrent connections.
193+
150194
You can also use the **`test_server.ps1`** PowerShell script located in the `src/test` directory for automated testing
151195
scenarios.
152196

@@ -156,31 +200,64 @@ scenarios.
156200

157201
### Thread Pool Architecture
158202

159-
The `Server.java` class initializes a fixed-size thread pool. It runs an infinite loop to accept incoming TCP
160-
connections. Each accepted client `Socket` is wrapped in a `Client` object and handed off as a task to the thread pool.
161-
This design decouples connection acceptance from request processing, allowing the server to remain responsive to new
162-
clients even while handling long-running requests.
203+
The `Server.java` class initializes a fixed-size thread pool using `ExecutorService`. It runs an infinite loop to accept
204+
incoming TCP
205+
connections. Each accepted client `Socket` is wrapped in a `Client` object and added to a `LinkedBlockingQueue`. A
206+
separate queue processor thread continuously dequeues clients and submits them to the thread pool for processing.
207+
208+
**Key Design Benefits:**
209+
210+
- Decouples connection acceptance from request processing
211+
- Prevents thread exhaustion through pool size limits
212+
- Graceful handling of connection spikes through request queuing
213+
- Efficient resource utilization with thread reuse
163214

164215
### Request Handling Pipeline
165216

166217
For each client connection, a `ClientHandler` instance is executed by a worker thread. The process is as follows:
167218

168-
1. **Read & Parse**: `ClientHandler` reads the raw request from the socket's input stream.
169-
2. **Validation**: `RequestHandler` parses the raw string into a structured `HttpRequest` DTO. It validates the request
170-
format, method, headers (like `Host`), and path safety.
219+
1. **Read & Parse**: `ClientHandler` reads the raw HTTP request from the socket's input stream using a `BufferedReader`.
220+
2. **Validation**: `RequestHandler` parses the raw string into a structured `HttpRequest` DTO. It validates:
221+
- Request format and HTTP version
222+
- HTTP method (GET/POST only)
223+
- Required headers (especially `Host`)
224+
- Path safety (prevents directory traversal)
225+
- Content-Type for POST requests
171226
3. **Dispatch**: Based on the HTTP method, `ClientHandler` proceeds:
172-
- **GET**: It serves static or binary files from the `resources` directory.
173-
- **POST**: It processes the JSON body and saves it to the `uploads` directory.
174-
4. **Response**: `ResponseHandler` constructs the appropriate HTTP response (e.g., `200 OK`, `201 Created`,
175-
`404 Not Found`) and writes it to the socket's output stream.
227+
- **GET**: Serves static HTML files or binary files (images, text) from the `resources` directory
228+
- **POST**: Validates JSON payload, generates unique filename, and saves to `uploads` directory
229+
4. **Response**: `ResponseHandler` constructs the appropriate HTTP response with proper status codes:
230+
- `200 OK` - Successful GET
231+
- `201 Created` - Successful POST
232+
- `400 Bad Request` - Malformed request or invalid JSON
233+
- `403 Forbidden` - Path traversal or host mismatch
234+
- `404 Not Found` - Resource doesn't exist
235+
- `405 Method Not Allowed` - Unsupported HTTP method
236+
- `415 Unsupported Media Type` - Wrong Content-Type or file type
237+
- `500 Internal Server Error` - Server-side errors
176238

177239
### Security Measures
178240

179-
- **Path Traversal**: `RequestHandler` canonicalizes all requested file paths and strictly ensures they resolve to a
180-
location *within* the `resources` folder. Any request containing `..` or attempting to access a parent directory is
181-
rejected with a `403 Forbidden` error.
182-
- **Host Header Validation**: All requests are required to have a `Host` header that matches the server's own address.
183-
This is a key requirement of HTTP/1.1 and helps prevent certain types of attacks.
241+
- **Path Traversal Protection**: `RequestHandler` validates all requested paths before file access:
242+
- Blocks `..`, `./`, `//`, and URL-encoded variants
243+
- Canonicalizes paths using Java's `Path.normalize()`
244+
- Ensures resolved paths stay within `resources` directory
245+
- Returns `403 Forbidden` for any violations
246+
247+
- **Host Header Validation**:
248+
- All HTTP/1.1 requests must include a valid `Host` header
249+
- Server validates the header matches its own address
250+
- Accepts `localhost`, `127.0.0.1`, or `0.0.0.0` variations
251+
- Returns `400 Bad Request` if missing, `403 Forbidden` if mismatched
252+
253+
- **Request Size Limiting**:
254+
- Maximum request size enforced at 8192 bytes
255+
- Prevents memory exhaustion attacks
256+
257+
- **Input Validation**:
258+
- JSON validation using Google's Gson library
259+
- File type restrictions (only HTML, TXT, PNG, JPG/JPEG)
260+
- Content-Type verification for POST requests
184261

185262
---
186263

@@ -189,15 +266,67 @@ For each client connection, a `ClientHandler` instance is executed by a worker t
189266
The server can be configured via command-line arguments:
190267

191268
```sh
192-
java -jar http_server.jar [port] [host] [thread_pool_size]
269+
java -cp target/myartifactid-0.0-SNAPSHOT.jar Main [port] [host] [thread_pool_size]
193270
```
194271

272+
**Parameters:**
273+
195274
- **`port`**: The port number to bind to. (Default: `8080`)
196275
- **`host`**: The host address to bind to. (Default: `127.0.0.1`)
197276
- **`thread_pool_size`**: The number of worker threads. (Default: `10`)
198277

278+
**Examples:**
279+
280+
```sh
281+
# Default configuration
282+
java -cp target/myartifactid-0.0-SNAPSHOT.jar Main
283+
284+
# Custom port
285+
java -cp target/myartifactid-0.0-SNAPSHOT.jar Main 9000
286+
287+
# Bind to all interfaces
288+
java -cp target/myartifactid-0.0-SNAPSHOT.jar Main 8080 0.0.0.0
289+
290+
# Custom port, host, and 20 threads
291+
java -cp target/myartifactid-0.0-SNAPSHOT.jar Main 8000 0.0.0.0 20
292+
```
293+
294+
---
295+
296+
## Testing Checklist
297+
298+
Use the interactive test interface at `http://127.0.0.1:8080/test.html` to verify:
299+
300+
- ✅ GET / → Serves index.html
301+
- ✅ GET /about.html → Serves HTML page
302+
- ✅ GET /logo.png → Downloads PNG as binary
303+
- ✅ GET /photo.jpg → Downloads JPEG as binary
304+
- ✅ GET /sample.txt → Downloads text file as binary
305+
- ✅ POST /upload (JSON) → Creates file, returns 201
306+
- ❌ GET /nonexistent.html → Returns 404
307+
- ❌ PUT /index.html → Returns 405
308+
- ❌ DELETE /file.txt → Returns 405
309+
- ❌ POST /upload (XML) → Returns 415
310+
- ❌ POST /upload (invalid JSON) → Returns 400
311+
- ❌ GET /document.pdf → Returns 415
312+
- 🔒 GET /../etc/passwd → Returns 403
313+
- 🔒 GET /../../sensitive.txt → Returns 403
314+
- 🔒 GET //etc/hosts → Returns 403
315+
316+
## Author
317+
318+
**Vimal Kumar**
319+
320+
- GitHub: [@yamiSukehiro2907](https://github.com/yamiSukehiro2907)
321+
199322
---
200323

201-
## License
324+
## Acknowledgments
325+
326+
This project was built as part of a Computer Networks assignment to demonstrate understanding of:
202327

203-
This project is licensed under the MIT License.
328+
- Low-level socket programming
329+
- HTTP/1.1 protocol implementation
330+
- Multi-threaded server architecture
331+
- Network security best practices
332+
- Concurrent programming patterns

0 commit comments

Comments
 (0)