; tiny-http: an HTTP/1.0 server for Linux in x86-64 assembly. ; ; For now it answers every connection with the same few bytes. ; ; build/tiny-http [port] default 8080 bits 64 default rel %define SYS_READ 0 %define SYS_WRITE 1 %define SYS_CLOSE 3 %define SYS_SOCKET 41 %define SYS_ACCEPT 43 %define SYS_BIND 49 %define SYS_LISTEN 50 %define SYS_EXIT 60 %define AF_INET 2 %define SOCK_STREAM 1 %define REQUEST_MAX 4096 ; text name, "bytes"... defines name and name.len %macro text 2+ %1: db %2 %{1}.len equ $ - %1 %endmacro section .text global _start _start: mov edi, 8080 cmp qword [rsp], 2 ; argc: was a port given? jb .socket mov rsi, [rsp + 16] ; argv[1] call parse_port mov edi, eax .socket: rol di, 8 ; the port in network byte order mov word [addr], AF_INET mov [addr + 2], di ; sin_addr stays 0: every interface mov eax, SYS_SOCKET mov edi, AF_INET mov esi, SOCK_STREAM xor edx, edx syscall test eax, eax js fail_socket mov r12d, eax ; r12 = the listening socket, for good mov eax, SYS_BIND mov edi, r12d lea rsi, [addr] mov edx, 16 syscall test eax, eax js fail_bind mov eax, SYS_LISTEN mov edi, r12d mov esi, 64 ; backlog syscall .accept: mov eax, SYS_ACCEPT mov edi, r12d xor esi, esi ; we never ask who it is xor edx, edx syscall test eax, eax js .accept mov r13d, eax ; r13 = this client mov eax, SYS_READ ; take the request off the socket, mov edi, r13d ; or closing it would send a reset lea rsi, [request] mov edx, REQUEST_MAX syscall mov eax, SYS_WRITE mov edi, r13d lea rsi, [reply] mov edx, reply.len syscall mov eax, SYS_CLOSE mov edi, r13d syscall jmp .accept ; rsi = a NUL-terminated port number. Returns it in eax, or exits with usage. parse_port: xor eax, eax .digit: movzx ecx, byte [rsi] inc rsi test ecx, ecx jz .end sub ecx, '0' cmp ecx, 9 ja fail_usage imul eax, eax, 10 add eax, ecx cmp eax, 65535 ja fail_usage jmp .digit .end: test eax, eax jz fail_usage ret fail_usage: lea rsi, [usage] mov edx, usage.len jmp die fail_socket: lea rsi, [no_socket] mov edx, no_socket.len jmp die fail_bind: lea rsi, [no_bind] mov edx, no_bind.len die: mov eax, SYS_WRITE mov edi, 2 ; stderr syscall mov eax, SYS_EXIT mov edi, 1 syscall section .rodata text reply, "HTTP/1.0 200 OK", 13, 10, "Content-Type: text/plain", 13, 10, 13, 10, "hello from tiny-http", 10 text usage, "usage: tiny-http [port 1-65535]", 10 text no_socket, "tiny-http: socket() failed", 10 text no_bind, "tiny-http: cannot bind that port", 10 section .bss addr: resb 16 ; sockaddr_in request: resb REQUEST_MAX