-
Notifications
You must be signed in to change notification settings - Fork 2
/
NimpleHTTPServer.nim
199 lines (171 loc) · 5.7 KB
/
NimpleHTTPServer.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
##[
Simple HTTP server with net sockets
Compile only with: --threads:on --opt:speed
]##
when not compileOption("threads"):
{.error: "This module requires the --threads:on option.".}
# Imports
import net, httpcore, strutils, os, times, terminal
# Type HttpServer
type
HttpServer* = ref object
port: int
status: bool
content: string # custom content
timeout: int # in seconds
proc newHttpServer*(port: int, content = "", timeout = 0): HttpServer =
## Create a new HttpServer instance with the specified
## `port`, `timeout` and `content`
## If content is provided, then the server will serve the content
## no matter what the client asks for
result = HttpServer(port: port, content: content, timeout: timeout)
# In working http request
var
inWorking = false
stopped {.global.}: bool
thr: array[0..1, Thread[HttpServer]]
proc status*(s: HttpServer): bool =
## Get status of the HttpServer
if stopped:
s.status = false
else:
s.status = true
s.status
proc print(STATUS, text: string) =
## Prints error or success with nice and coloured output
if STATUS == "error":
stdout.styledWrite(fgRed, "[-] ")
elif STATUS == "success":
stdout.styledWrite(fgGreen, "[+] ")
elif STATUS == "loading":
stdout.styledWrite(fgBlue, "[*] ")
elif STATUS == "warning":
stdout.styledWrite(fgYellow, "[!] ")
stdout.write(text & "\n")
proc stop*(s: HttpServer) =
## Stops the server
if s.status:
var stopSocket = newSocket()
try:
stopSocket.connect("localhost", Port(s.port))
stopSocket.send("stop" & "\r\L")
except:
print("error", "The server is not running")
finally:
stopSocket.close()
s.status = false
stopped = true
else:
print("error", "The server is not running")
proc timeOutStop(s: HttpServer) {.thread.} =
## Stops the server thread after the timeout
if s.timeout > 0:
var
runtime = getTime().toUnix()
diff = 0'i64
while diff < s.timeout:
diff = getTime().toUnix() - runtime
s.stop()
s.status = false
stopped = true
# Forward declaration for startHttpServer
proc startHttpServer(s: HttpServer) {.thread.}
proc start*(s: HttpServer) =
## Start the server threads
s.status = true
stopped = false
# Start thread
createThread(thr[0], startHttpServer, s)
createThread(thr[1], timeOutStop, s)
sleep(1) # Needed
proc join*(s: HttpServer) =
## Stop everything and wait for the server to end
if not s.status:
print("error", "The server is not running")
joinThreads(thr)
s.status = false
proc validateFile(file: string): bool =
## Validate file existence
echo repr file
if fileExists(file):
return true
print("error", file & "not exist")
return false
#[
Help procedures
***************
]#
proc addHeaders(msg: var string, headers: HttpHeaders) =
## Add headers to the HTTP response
for k, v in headers:
msg.add(k & ": " & v & "\c\L")
proc buildHTTPResponse(code: HttpCode, content: string,
headers: HttpHeaders = nil): string =
## Build the full HTTP response
var msg = "HTTP/1.1 " & $code & "\c\L"
if headers != nil:
msg.addHeaders(headers)
# If the headers did not contain a Content-Length use our own
if headers.isNil() or not headers.hasKey("Content-Length"):
msg.add("Content-Length: ")
# this particular way saves allocations:
msg.addInt content.len
msg.add "\c\L"
msg.add "\c\L"
msg.add content
return msg
proc startHttpServer(s: HttpServer) {.thread.} =
## Thread procedure - starts the HTTP server and handles the
## incoming requests
# Socket init
var socket = newSocket()
socket.setSockOpt(OptReuseAddr, true)
socket.bindAddr(Port(s.port))
socket.listen()
print("loading", "Listening on port: " & $(s.port))
# Check incoming connections
while true:
var
client: net.Socket
address = ""
rec = ""
msg = ""
requestedFile = ""
stop = false
response = ""
socket.acceptAddr(client, address)
inWorking = true
while not stop:
try:
rec = client.recvLine(timeout=1000)
## Check if stop
if rec.contains("stop") and address == "127.0.0.1":
print("loading", "Server stopped")
socket.close()
s.status = false
return
if rec.contains("GET"):
requestedFile = rec.split("GET /")[1]
requestedFile = requestedFile.split("HTTP")[0].strip()
print("loading", address & " requested: " & requestedFile)
msg &= "\n" & rec
except:
stop = true
if s.content == "":
if validateFile(requestedFile):
let content = readFile(requestedFile)
response = $(buildHTTPResponse(Http200, content, newHttpHeaders()))
else:
response = $(buildHTTPResponse(Http404, "File not found", newHttpHeaders()))
else:
response = $(buildHTTPResponse(Http200, s.content, newHttpHeaders()))
if client.trySend(response):
discard
client.close()
inWorking = false
when isMainModule:
# Starts the http server and runs it for 30 seconds with 15 second timeout
var server = newHttpServer(8080)
server.start()
server.join()
echo server.status