An HTTP/1.0 server for Linux in x86-64 assembly. No libc; every build starts it and curls it.
1; tiny-http: an HTTP/1.0 server for Linux in x86-64 assembly.
2;
3; For now it answers every connection with the same few bytes.
4;
5; build/tiny-http [port] default 8080
7 bits 64
8 default rel
10%define SYS_READ 0
11%define SYS_WRITE 1
12%define SYS_CLOSE 3
13%define SYS_SOCKET 41
14%define SYS_ACCEPT 43
15%define SYS_BIND 49
16%define SYS_LISTEN 50
17%define SYS_EXIT 60
19%define AF_INET 2
20%define SOCK_STREAM 1
22%define REQUEST_MAX 4096
24; text name, "bytes"... defines name and name.len
25%macro text 2+
26%1: db %2
27%{1}.len equ $ - %1
28%endmacro
30 section .text
33_start:
34 mov edi, 8080
35 cmp qword [rsp], 2 ; argc: was a port given?
37 mov rsi, [rsp + 16] ; argv[1]
38 call parse_port
39 mov edi, eax
40.socket:
41 rol di, 8 ; the port in network byte order
45 mov eax, SYS_SOCKET
46 mov edi, AF_INET
47 mov esi, SOCK_STREAM
48 xor edx, edx
49 syscall
50 test eax, eax
51 js fail_socket
52 mov r12d, eax ; r12 = the listening socket, for good
54 mov eax, SYS_BIND
55 mov edi, r12d
57 mov edx, 16
58 syscall
59 test eax, eax
62 mov eax, SYS_LISTEN
63 mov edi, r12d
64 mov esi, 64 ; backlog
65 syscall
67.accept:
68 mov eax, SYS_ACCEPT
69 mov edi, r12d
70 xor esi, esi ; we never ask who it is
71 xor edx, edx
72 syscall
73 test eax, eax
75 mov r13d, eax ; r13 = this client
77 mov eax, SYS_READ ; take the request off the socket,
78 mov edi, r13d ; or closing it would send a reset
80 mov edx, REQUEST_MAX
81 syscall
83 mov eax, SYS_WRITE
84 mov edi, r13d
85 lea rsi, [reply]
86 mov edx, reply.len
87 syscall
89 mov eax, SYS_CLOSE
90 mov edi, r13d
91 syscall
94; rsi = a NUL-terminated port number. Returns it in eax, or exits with usage.
95parse_port:
96 xor eax, eax
97.digit: movzx ecx, byte [rsi]
98 inc rsi
99 test ecx, ecx
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
109.end: test eax, eax
110 jz fail_usage
111 ret
113fail_usage:
114 lea rsi, [usage]
115 mov edx, usage.len
117fail_socket:
118 lea rsi, [no_socket]
119 mov edx, no_socket.len
121fail_bind:
122 lea rsi, [no_bind]
123 mov edx, no_bind.len
124die: mov eax, SYS_WRITE
125 mov edi, 2 ; stderr
126 syscall
127 mov eax, SYS_EXIT
128 mov edi, 1
129 syscall
131 section .rodata
132text reply, "HTTP/1.0 200 OK", 13, 10, "Content-Type: text/plain", 13, 10, 13, 10, "hello from tiny-http", 10
133text usage, "usage: tiny-http [port 1-65535]", 10
134text no_socket, "tiny-http: socket() failed", 10
135text no_bind, "tiny-http: cannot bind that port", 10
137 section .bss
138addr: resb 16 ; sockaddr_in
139request:
140 resb REQUEST_MAX