acompiled

The catalog contains seeded project examples. Your workspace stores your own projects and conversations.

zeroeight/tiny-http

Public
Star9

An HTTP/1.0 server for Linux in x86-64 assembly. No libc; every build starts it and curls it.

Take the port from argv[1]

Browse files
zeroeightcommitted 1 parent b468510 commit ae4bae47a791da759f2debc0a1765e7258b2615a
failing 2 steps in 1 ms
1 file changed +45−7
modified src/server.asm +45−7
@@ -1,6 +1,8 @@
11 ; tiny-http: an HTTP/1.0 server for Linux in x86-64 assembly.
22 ;
3−; For now it answers every connection on port 8080 with the same few bytes.
3+; For now it answers every connection with the same few bytes.
4+;
5+; build/tiny-http [port] default 8080
46
57 bits 64
68 default rel
@@ -30,6 +32,12 @@
3032
3133 _start:
3234 mov edi, 8080
35+ cmp qword [rsp], 2 ; argc: was a port given?
36+ jb .socket
37+ mov rsi, [rsp + 16] ; argv[1]
38+ call parse_port
39+ mov edi, eax
40+.socket:
3341 rol di, 8 ; the port in network byte order
3442 mov word [addr], AF_INET
3543 mov [addr + 2], di ; sin_addr stays 0: every interface
@@ -40,7 +48,7 @@ _start:
4048 xor edx, edx
4149 syscall
4250 test eax, eax
43− js fail
51+ js fail_socket
4452 mov r12d, eax ; r12 = the listening socket, for good
4553
4654 mov eax, SYS_BIND
@@ -49,7 +57,7 @@ _start:
4957 mov edx, 16
5058 syscall
5159 test eax, eax
52− js fail
60+ js fail_bind
5361
5462 mov eax, SYS_LISTEN
5563 mov edi, r12d
@@ -83,10 +91,38 @@ _start:
8391 syscall
8492 jmp .accept
8593
86−fail: mov eax, SYS_WRITE
94+; rsi = a NUL-terminated port number. Returns it in eax, or exits with usage.
95+parse_port:
96+ xor eax, eax
97+.digit: movzx ecx, byte [rsi]
98+ inc rsi
99+ test ecx, ecx
100+ jz .end
101+ sub ecx, '0'
102+ cmp ecx, 9
103+ ja fail_usage
104+ imul eax, eax, 10
105+ add eax, ecx
106+ cmp eax, 65535
107+ ja fail_usage
108+ jmp .digit
109+.end: test eax, eax
110+ jz fail_usage
111+ ret
112+
113+fail_usage:
114+ lea rsi, [usage]
115+ mov edx, usage.len
116+ jmp die
117+fail_socket:
118+ lea rsi, [no_socket]
119+ mov edx, no_socket.len
120+ jmp die
121+fail_bind:
122+ lea rsi, [no_bind]
123+ mov edx, no_bind.len
124+die: mov eax, SYS_WRITE
87125 mov edi, 2 ; stderr
88− lea rsi, [failed]
89− mov edx, failed.len
90126 syscall
91127 mov eax, SYS_EXIT
92128 mov edi, 1
@@ -94,7 +130,9 @@ fail: mov eax, SYS_WRITE
94130
95131 section .rodata
96132 text reply, "HTTP/1.0 200 OK", 13, 10, "Content-Type: text/plain", 13, 10, 13, 10, "hello from tiny-http", 10
97−text failed, "tiny-http: cannot listen on port 8080", 10
133+text usage, "usage: tiny-http [port 1-65535]", 10
134+text no_socket, "tiny-http: socket() failed", 10
135+text no_bind, "tiny-http: cannot bind that port", 10
98136
99137 section .bss
100138 addr: resb 16 ; sockaddr_in