Full Code of jcalvinowens/asmhttpd for AI

master 2cc6edacdbf3 cached
8 files
37.5 KB
11.0k tokens
1 requests
Download .txt
Repository: jcalvinowens/asmhttpd
Branch: master
Commit: 2cc6edacdbf3
Files: 8
Total size: 37.5 KB

Directory structure:
gitextract_bxrp70mk/

├── .gitignore
├── LICENSE
├── MACROS
├── Makefile
├── README
├── asmhttpd.asm
├── constants.inc
└── syscall.inc

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
asmhttpd
asmhttpd.o


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

                    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

                            NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.


================================================
FILE: MACROS
================================================

The syscall() macro should be invoked as follows:
	syscall(#,arg1,arg2,arg3,arg4,arg5,arg6)

Error checking is built into the macro. You _MUST_ define an error-handler.
If the syscall() macro is invoked without an error handler defined, the
assembler will throw an error.

You define error handlers like this:

	ech(label_for_your_error_code)
	; do shit
	ech(other_label_for_stuff)

The error checking consists of:

	or rax,rax
	js @ERROR_HANDLER

So, the FLAGS are set based on the error return of the syscall, which is nice.

The arguments are loaded with 32-bit 'mov' by default.
You can change that in the following ways:
	+arg	: Load arg with a 64-bit 'mov'
	^arg	: Load arg with a 32-bit 'mov' (redundant in this usage)
	^^arg	: Load arg with a 16-bit 'mov'
	^^^arg	: Load arg with an 8-bit 'mov'
	[arg]	: Load arg with 'lea' (eg, "lea rdi,[arg]")
	+[arg]	: Dereference arg and load (eg, "mov rdi,[arg]")
	^[arg]
	^^[arg]
	^^^[arg]
	[+arg]	: Discard brackets and load with 'mov' (eg, "mov rdi,arg")
	[^arg]	  (This functionality is stupid)
	[^^arg]
	[^^^arg]
	NULL	: Make the argument NULL (Always 64-bit, eg "xor rdi,rdi")

Note that the syscall number ("#" in the example) is also expanded in this fashion

--

In our thread-based model, each thread calls mmap() to grab it's own memory,
and sets %rbp the base of that memory.

The tmalloc(symbol,$bytes) macro "reserves" space in that memory. It defines
'symbol' to be [rbp+bytes].

So, for example:

tmalloc(crap,8)
tmalloc(shit,16)
tmalloc(moreshit,32)

crap is "rbp"
shit is "rbp+8"
moreshit is "rbp+24"


================================================
FILE: Makefile
================================================

asmhttpd: asmhttpd.o
	ld $^ -o $@

%.o: %.asm
	nasm -f elf64 -O0 -o $@ $<

clean:
	rm -f *.o asmhttpd


================================================
FILE: README
================================================
asmhttpd - The tiniest webserver ever written

HOW TO BUILD:
-------------

	Just run "make". You will need NASM on your system.

HOW TO RUN:
-----------

	./asmhttpd /path/to/your/webroot
	sudo ./asmhttpd /path/to/your/webroot

If run as root, it will listen on port 80. Otherwise, it will use port 8080.

HOW TINY IS IT?
---------------

The entire text and data fit on a single 4K page:

  {0}[calvin ~] cat /proc/$(pgrep -n asmhttpd)/maps
  00401000-00402000 r-xp 00001000 00:16 2483272 asmhttpd

Each client allocates an additional 4K page and a thread while connected.

The code is written in a monolithic "branching tree" style with no functions,
and uses registers for all local variables. RAM is only used for buffering the
HTTP request, and for building structures necessary for system calls.

Because there is no stack, and the targets of all branch instructions are
constants, traditional buffer overflow exploits are impossible.


================================================
FILE: asmhttpd.asm
================================================
; vim: syntax=nasm
;
; asmhttpd: A minimalist HTTP webserver for Linux, written in x86_64 assembly.
;
; Copyright (C) 2012 Calvin Owens <jcalvinowens@gmail.com>
;
; This program is free software; you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation; either version 2 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
; GNU General Public License for more details.

[bits 64]
global _start

%include "constants.inc"		; Flags for system calls, etc.
%include "syscall.inc"			; syscall() definition

%assign thread_memory_offset 0 ; This is rewritten each time tmalloc() is called
%macro reserve_thread_memory 2
	%define %1 rbp+%[thread_memory_offset]
	%define len%1 %2
	%assign thread_memory_offset thread_memory_offset+%[%2]
%endmacro
%define tmalloc(a,b) reserve_thread_memory a,b

%define GLOBAL_REQUEST_TIMEOUT 5
%define GLOBAL_MAX_HTTP_REQLEN 1024
%define THREAD_MEM_SIZE 4096
%define CLIENT_TIMEOUT_MS 60000
%define NAME_MAX 254

segment .text

SEGMENT_BEGIN:

Setsock_ARGUMENT:
	dd 0x00000001			; Turn option ON

Sighand_SIGPIPE:
	dq 0x0000000000000001		; SIG_IGN is 1
	dq 0x0000000000000000

SocketAddress:
	dw 0x0002			; AF_INET is 2 (AF_INET6 is 0xa)
	dw 0x5000			; TCP Port we want to bind to (:80) (Net byte ordering)
	dd 0x00000000                   ; Address to bind to (0.0.0.0 or ::)
	dd 0x00000000
	dd 0x00000000
	dd 0x00000000
	dd 0x00000000

SocketAddressNotRoot:
	dw 0x0002			; AF_INET is 2 (AF_INET6 is 0xa)
	dw 0x901F			; TCP Port we want to bind to (:8080) (Net byte ordering)
	dd 0x00000000                   ; Address to bind to (0.0.0.0 or ::)
	dd 0x00000000
	dd 0x00000000
	dd 0x00000000
	dd 0x00000000

DecAsciiConvTable:
	db 0x30,0x31,0x21,0x32,0x33,0x21,0x34,0x21,0x35,0x36,0x21,0x37,0x38,0x21,0x39,0x21

Response200:
	db "HTTP/1.1 200 OK",0x0d,0x0a
%define lenResponse200 17
Header12:
	db "Content-Length: "
%define lenHeader12 16

Error400:
	db "HTTP/1.1 400 Bad Request",0x0d,0x0a,0x0d,0x0a
%define lenError400 28
Error403:
	db "HTTP/1.1 403 Forbidden",0x0d,0x0a,0x0d,0x0a
%define lenError403 26
Error404:
	db "HTTP/1.1 404 Not Found",0x0d,0x0a,0x0d,0x0a
%define lenError404 26
Error408:
	db "HTTP/1.1 408 Request Timeout",0x0d,0x0a,0x0d,0x0a
%define lenError408 32
Error411:
	db "HTTP/1.1 411 Length Required",0x0d,0x0a,0x0d,0x0a
%define lenError411 32
Error413:
	db "HTTP/1.1 413 Request Entity Too Large",0x0d,0x0a,0x0d,0x0a
%define lenError413 41
Error414:
	db "HTTP/1.1 414 Request URI Too Long",0x0d,0x0a,0x0d,0x0a
%define lenError414 37
Error500:
	db "HTTP/1.1 500 Internal Server Error",0x0d,0x0a,0x0d,0x0a
%define lenError500 38
Error501:
	db "HTTP/1.1 501 Not Implemented",0x0d,0x0a,0x0d,0x0a
%define lenError501 32

Error599:
	db "HTTP/1.1 599 System Call Not Implemented",0x0d,0x0a,0x0d,0x0a
	db "Your kernel is probably missing openat2(): Upgrade to >= 5.6",0x0a
%define lenError599 105

HelpMessage:
	db "Usage: ./asmhttpd <webroot>",0x0a
%define lenHelpMessage 28

ech(____die)	; Who shall catch the catchers?

DieClientDisconnected:
syscall(sys_close,+rbx)
syscall(sys_munmap,+rbp,THREAD_MEM_SIZE)
syscall(sys_exit,-1)

DieError403:
lea rcx,[Error403]
mov edx,lenError403
jmp __die

DieError404:
lea rcx,[Error404]
mov edx,lenError404
jmp __die

DieError414:
lea rcx,[Error414]
mov edx,lenError414
jmp __die

DieError500:
lea rcx,[Error500]
mov edx,lenError500
jmp __die

DieError408:
lea rcx,[Error408]
mov edx,lenError408
jmp __die

DieError400:
lea rcx,[Error400]
mov edx,lenError400
jmp __die

DieError599:
lea rcx,[Error599]
mov edx,lenError599
jmp __die

PrintHelpMessageAndDie:
syscall(sys_write,2,[HelpMessage],lenHelpMessage)
jmp ____die

__die:
syscall(sys_write,+rbx,+rcx,+rdx)
syscall(sys_close,+rbx)
syscall(sys_munmap,+rbp,THREAD_MEM_SIZE)
____die:
syscall(sys_exit,-1);

HandleInitSysError:
HandleServeSysError:
mov rbx,rax
syscall(sys_exit,+rbx)

HandleGeneralSysErrorAfterOpen:
syscall(sys_close,+r13)
HandleGeneralSysError:
cmp eax,-EPERM
je DieError403	; Permission Denied
cmp eax,-ENOENT
je DieError404	; File not found
cmp eax,-EACCES
je DieError403	; Permission denied
cmp eax,-ENAMETOOLONG
je DieError414	; URI too long (although, is it?)
cmp eax,-EPIPE
je DieClientDisconnected
cmp eax,-ENOSYS
je DieError599

jmp DieError500

_start:

ech(HandleInitSysError)

; Parse command line arguments. At the start of the program, [rsp] contains a
; qword that tells us how many arguments we got, and [rsp+8] is the beginning of
; a list of pointers to the NUL-terminated argument strings.

; Make sure we have 2 arguments:
;	0:	[rsp+8*1]	Executable name (we ignore this)
;	1:	[rsp+8*2]	Webroot
mov r11,[rsp]
cmp r11,2
jne PrintHelpMessageAndDie

syscall(sys_open,+[rsp+8*2],O_DIRECTORY,NULL)
mov r15,rax	; Save webroot file descriptor

; Ignore SIGPIPE
syscall(sys_rt_sigact,13,[Sighand_SIGPIPE],NULL,8)

; Create and set SO_REUSEADDR on the socket
syscall(sys_socket,2,1,NULL)
mov rbx,rax

syscall(sys_setsockopt,+rbx,SOL_SOCKET,SO_REUSEADDR,[Setsock_ARGUMENT],4)
syscall(sys_getuid)
test rax,rax
jnz .NotRoot

; Bind, and drop privs (nobody)
syscall(sys_bind,+rbx,[SocketAddress],24)
syscall(sys_setgid,65535)
syscall(sys_setuid)
jmp .OverNotRoot

.NotRoot:
syscall(sys_bind,+rbx,[SocketAddressNotRoot],24)

.OverNotRoot:
syscall(sys_listen,+rbx,1024)

; Now, we can unmap everything but our single page, including the stack!
; If you use L5 pagetables, change the shift by 47 to 56

lea rdi,[SEGMENT_BEGIN]
shr rdi,12
inc rdi
shl rdi,12

; Unmap everything after .text
mov rsi,1
shl rsi,47
sub rsi,rdi
sub rsi,4096	; Highest page is off-limits
syscall(sys_munmap)

; Unmap everything before .text
mov rsi,rdi
shr rsi,12
dec rsi
shl rsi,12
dec rsi
xor rdi,rdi
syscall(sys_munmap)

ServeHTTP:

ech(HandleServeSysError)

mov r8,rbx ; file descriptor for listening socket
mov r9,CLONE_FS|CLONE_THREAD|CLONE_SIGHAND|CLONE_VM|CLONE_FILES
mov r10d,sys_accept
mov r12d,sys_clone
xor rsi,rsi
xor rdx,rdx

.AcceptNextRequest:

syscall(+r10,+r8)
mov rbx,rax
syscall(+r12,+r9)
jnz .AcceptNextRequest

;; (rbx contains client connection file descriptor)

HandleConnection:
ech(HandleGeneralSysError)

syscall(sys_mmap,NULL,THREAD_MEM_SIZE,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANONYMOUS|MAP_POPULATE,NULL,NULL)
mov rbp,rax	; Store offset for tmalloc() macro

tmalloc(PollStruct,8)

; Build a struct pollfd in memory
mov [PollStruct],rbx
mov dword [PollStruct+4],POLLIN

tmalloc(ClientRequest,GLOBAL_MAX_HTTP_REQLEN)

; Load offset and counter for receieve loop
lea r9,[ClientRequest]
mov r10d,GLOBAL_MAX_HTTP_REQLEN

ReceiveRequest:

syscall(sys_poll,[+PollStruct],1,CLIENT_TIMEOUT_MS)
jz DieError408

syscall(sys_read,+rbx,+r9,+r10)
jz DieClientDisconnected

; Did we get enough data to be valid?
mov ecx,GLOBAL_MAX_HTTP_REQLEN
sub rcx,r10
add rcx,rax
cmp rcx,18
jge GotEnough

; Need to wait for more, adjust offsets and block again
add r9,rax
sub r10,rax
jmp ReceiveRequest

GotEnough:
mov esi,0x0a0d0a0d
lea rdi,[r9+rax-4]
lea r8,[ClientRequest]

.FindTerminator:
cmp esi,dword [rdi]
je short .FoundTerminator

dec rdi		; If we haven't reached the beginning...
cmp rdi,r8	; ...then keep looking
jne short .FindTerminator

add r9,rax	; Adjust offset and counter
sub r10,rax
jz DieError414	; If zero, send 412 REQUEST URI TOO LARGE

jmp ReceiveRequest	; Go back up and wait for more data

.FoundTerminator:
lea r14,[r9+rax]	; Store last byte received from client

; Skip past the METHOD specification, find the start of the URI:
mov eax,0x20
lea rdi,[ClientRequest]
mov ecx,20
repne scasb
jne DieError400		; Go thou and fuck with me no more

mov r13,rdi

; NULL-terminate the filename
mov ecx,GLOBAL_MAX_HTTP_REQLEN
repne scasb
jne DieError400		; This should never happen

mov byte [rdi-1],0x00
lea r12,[rdi-1]		; Store addr of last byte of URI

lea r8,[rbp+thread_memory_offset]	; Load scratch address, to store offsets of escaped %xx literals
xor r10,r10	; Zero index registers
xor r9,r9
mov eax,0x25	; '%' in ASCII
mov rcx,r12	; Counter for 'repne scasb'...
sub rcx,r13	; ...subtract from end to get length
cmp rcx,3	; If there are less than 3 characters...
jl ExpandDone	; ...there can't be anything to unescape
mov rdi,r13	; Beginning of URI

ExpandChar:
repne scasb	; Search for a '%' character
jne ExpandOut	; ...if we didn't find one, we're done
cmp rcx,1	; If there are less than 2 characters left...
jle ExpandOut	; ...don't try to unescape
movzx rdx,word [rdi]	; Pull the ASCII-encoded hex byte into dx
ror dl,4	; You are not expected to understand this
ror dx,4
ror dl,4
and dh,0x44
shr dh,2
add dl,dh
shl dh,3
or dl,dh
mov [rdi-1],dl	; Overwrite the '%' character with the newly-unescaped byte
mov word [rdi],r10w	; Write NULL's over the just-unescaped ASCII-encoded hex
mov [r8+r9*8],rdi	; Add the address to our list of unescaped literals
inc r9	; Increment the counter
jmp short ExpandChar	; ...and do it again

ExpandOut:
or r9,r9	; If r9 is zero...
jz ExpandDone	; ...then there was nothing to un-escape - jump over copying
mov [r8+r9*8],rdi	; Store the offset of the last byte of the URI

xor rax,rax	; Zero out rax (index register for the loop)
mov rdi,[r8]	; Get the offset of the first un-escaped literal
mov rsi,rdi	; rsi holds the destination

DoCopying:
add rsi,2	; Jump over unescaped xx
mov rcx,[r8+rax*8+8]	; Load the offset of the next escapee
sub rcx,rsi	; Subtract where we are now to get how far to copy
rep movsb	; Boom
inc rax	; Increment the idex register
cmp rax,r9	; If we're not done...
jne DoCopying	; ...do it again

mov rcx,r9	; Use the number of %xx's we unescaped as a counter
xor dx,dx	; Zero dx so we can write NULL words
mov [rdi],dx	; NUL terminate the (now shorter) string

ExpandDone:

tmalloc(OpenAtStruct,24)
mov qword [OpenAtStruct],0
mov qword [OpenAtStruct+8],0
mov qword [OpenAtStruct+16],RESOLVE_IN_ROOT
syscall(sys_openat2,+r15,+r13,[OpenAtStruct],lenOpenAtStruct)
mov r13,rax	; Save file descriptor

ech(HandleGeneralSysErrorAfterOpen)	; Now if we crash we have to close the file to
					; avoid leaking file descriptors

tmalloc(StatStruct,144)

syscall(sys_fstat,+r13,[StatStruct])

; Make sure we have a regular file or a symlink
mov r12w,[StatStruct+24]	; Get the file mode
shr r12w,14
cmp r12w,2
jne DieError403

mov r12,[StatStruct+48]	; Get the file size out of the struct from stat()

lea rsp,[rbp+thread_memory_offset]	; Get scratch space, store it in rsp for awhile

; Convert the filesize to ASCII
mov rax,r12			; The file's length to convert (as an unsigned quadword)
mov ecx,16			; Counter for the conversion loop
lea rsi,[DecAsciiConvTable]	; Address of table for ASCII conversion
mov r8,0x199999999999999a	; Multiplicative inverse of 10d (0xa)
xor r9,r9			; Zero out registers for the ASCII string
xor r10,r10

DivisionLoop:
	shld r9,r10,8		; Shift the most significant byte of r10 into r9
	shl r10,8		; (shld only shifts in, not out, so we have to discard the byte)
	mul r8			; Execute the division
	shr rax,60		; Shift the most significant byte of the remainder to the least
	movzx rax,byte [rsi+rax]; Load the value from our conversion table
	or r10,rax		; Store the new value in r10
	mov rax,rdx		; Restore the working quotient for the next iteration
	loop DivisionLoop	; ...and do it again

mov [rsp],r10			; Store the ASCII decimal value in memory
mov [rsp+8],r9

mov eax,0x30	; Skip over the leading zeros (they break stupid browsers...)
mov ecx,16
mov rdi,rsp
repe scasb

mov r11,[rdi-1]	; Move the significant values back to the beginning of [rsp]
mov [rsp],r11
mov r11,[rdi-1+8]
mov [rsp+8],r11

lea rsp,[rsp+rcx+1]	; Skip past the ASCII number

mov rdi,rsp	; Copy to the scratch area...
mov rsi,Response200	; ...from the canned HTTP 200 response
mov ecx,lenResponse200	; Size
rep movsb	; Boom

mov rsi,Header12	; Copy the "Content-Length: " header
mov ecx,lenHeader12	; Size
rep movsb	; Boom

lea rsi,[rbp+thread_memory_offset]	; Load rsi with the address of the ASCII-expressed file size
mov rcx,rsp	; Get the address of the start of the send buffer
sub rcx,rsi	; Subtract the offset of the size from the offset of the buffer (strlen(num))
rep movsb	; ...and copy the difference in bytes to the header field

mov dword [rdi], 0x0a0d0a0d	; Terminate the HTTP response

lea rdx,[rdi+4]	; Address from which to send response plus 4...
sub rdx,rsp	; ...and subtract the end to get the length
syscall(sys_sendto,+rbx,[+rsp],+rdx,MSG_MORE,NULL,NULL)

keep_sending:
syscall(sys_sendfile,+rbx,+r13,NULL,+r12)
sub r12,rax
jnz keep_sending

; Close file descriptor and socket
syscall(sys_close,+r13)
syscall(sys_close,+rbx)

; Deallocate thread-local memory and exit
syscall(sys_munmap,+rbp,THREAD_MEM_SIZE)
syscall(sys_exit,NULL)

ud2	; SIGILL


================================================
FILE: constants.inc
================================================
;; syscalls
%define sys_accept	43
%define sys_bind	49
%define sys_chdir	80
%define sys_chroot	161
%define sys_clone	56
%define sys_close	3
%define sys_exit	60
%define sys_fstat	5
%define sys_getuid	102
%define sys_listen	50
%define sys_mmap	9
%define sys_munmap	11
%define sys_open	2
%define sys_openat2	437
%define sys_poll	7
%define sys_read	0
%define sys_rt_sigact	13
%define sys_sendfile	40
%define sys_sendto	44
%define sys_setgid	106
%define sys_setsockopt	54
%define sys_setuid	105
%define sys_socket	41
%define sys_write	1

;; errno
%define	EPERM		1;	/* Operation not permitted */
%define	ENOENT		2;	/* No such file or directory */
%define	EACCES		13;	/* Permission denied */
%define	EPIPE		32;	/* Broken pipe */
%define	ENAMETOOLONG	36;	/* File name too long */
%define	ENOSYS		38;	/* Invalid system call number */

;; For clone()
%define CLONE_VM	0x00000100; /* Set if VM shared between processes.  */
%define CLONE_FS	0x00000200; /* Set if fs info shared between processes.  */
%define CLONE_FILES	0x00000400; /* Set if open files shared between processes.  */
%define CLONE_SIGHAND	0x00000800; /* Set if signal handlers shared.  */
%define CLONE_THREAD	0x00010000; /* Set to add to same thread group.  */

;; For mmap()
%define PROT_READ	0x1;		/* Page can be read.  */
%define PROT_WRITE	0x2;		/* Page can be written.  */
%define MAP_PRIVATE	0x02;		/* Changes are private.  */
%define MAP_ANONYMOUS	0x20;		/* Don't use a file.  */
%define MAP_POPULATE	0x08000;	/* Populate (prefault) pagetables.  */

;; For poll()
%define POLLIN		0x1;		/* There is data to read */

;; For sendto()
%define MSG_MORE	0x8000;		/* TCP_CORK behavior */

;; For setsockopt()
%define SOL_SOCKET	1;
%define SO_REUSEADDR	2;

;; For open()
%define O_DIRECTORY     0x10000;

;; For openat2()
%define RESOLVE_IN_ROOT	0x10;


================================================
FILE: syscall.inc
================================================
; See the MACROS file for a description of how this monstrosity works

;; r64,r32,r16,r8,arg
%macro load_syscall_argument 0-*
	%if %0 == 4
		; Empty Argument
	%elif %0 == 5
		%defstr ___arg_str %[%5]
		%substr ___arg_c ___arg_str 1
			%if ___arg_c == '['
			%substr ___arg_c2 ___arg_str 2
			%if ___arg_c2 == "+"
				%substr ___arg_n ___arg_str 3,-2
				%deftok ___arg_n_t %[___arg_n]
				mov %1,___arg_n_t
				%undef ___arg_n_t
				%undef ___arg_n
			%else
				lea %1,%5
			%endif
			%undef ___arg_c2
		%elif ___arg_c == '+'
			%substr ___arg_n ___arg_str 2,-1
			%deftok ___arg_n_t %[___arg_n]
			mov %1,___arg_n_t
			%undef ___arg_n_t
			%undef ___arg_n
		%elif ___arg_c == '^'
			%define ___forced_imm_bit_len 32
			%substr ___arg_c2 ___arg_str 1,2
			%if ___arg_c2 == "^^"
				%define ___forced_imm_bit_len 16
				%substr ___arg_c3 ___arg_str 1,3
				%if ___arg_c3 == "^^^"
					%define ___forced_imm_bit_len 8
				%endif
				%undef ___arg_c3
			%endif
			%undef ___arg_c2
			%if ___forced_imm_bit_len == 32
				%substr ___arg_n ___arg_str 2,-1
				%deftok ___arg_n_t %[___arg_n]
				%substr ___arg_n_c ___arg_n 1,1
				%if ___arg_n_c != '['
					%warning "^thing is redundant in SYSCALL: thing is interpreted as 32bit by default" 
				%endif
				mov %2,___arg_n_t
				%undef ___arg_n_t
				%undef ___arg_n
			%elif ___forced_imm_bit_len == 16
				%substr ___arg_n ___arg_str 3,-1
				%deftok ___arg_n_t %[___arg_n]
				mov %3,___arg_n_t
				%undef ___arg_n_t
				%undef ___arg_n
			%elif ___forced_imm_bit_len == 8
				%substr ___arg_n ___arg_str 4,-1
				%deftok ___arg_n_t %[___arg_n]
				mov %4,___arg_n_t
				%undef ___arg_n_t
				%undef ___arg_n
			%endif
			%undef ___forced_imm_bit_len
		%elif ___arg_str == 'NULL'
			xor %1,%1
		%else
			mov %2,%5
		%endif
		%undef ___arg_c
		%undef ___arg_str
	%else
		%fatal "You fucked up the SYSCALL-load-arguments macro!"
	%endif
%endmacro

%macro macro_do_syscall 1-7
	load_syscall_argument rax,eax,ax,al,%1
	%if %0 >= 2
	load_syscall_argument rdi,edi,di,dil,%2
	%endif
	%if %0 >= 3
	load_syscall_argument rsi,esi,si,sil,%3
	%endif
	%if %0 >= 4
	load_syscall_argument rdx,edx,dx,dl,%4
	%endif
	%if %0 >= 5
	load_syscall_argument r10,r10d,r10w,r10b,%5
	%endif
	%if %0 >= 6
	load_syscall_argument r8,r8d,r8w,r8b,%6
	%endif
	%if %0 >= 7
	load_syscall_argument r9,r9d,r9w,r9b,%7
	%endif
	syscall	; Invoke loadall286+
	%ifdef __syserror_handler
		or rax,rax ; Set flags based on the return value
		js __syserror_handler
	%else
		%fatal "__syserror_handler is not defined!"
	%endif
%endmacro ;; Yo dawg, I heard you liked macros...
%define syscall(a,b,c,d,e,f,g) macro_do_syscall a,b,c,d,e,f,g
%define syscall(a,b,c,d,e,f) macro_do_syscall a,b,c,d,e,f
%define syscall(a,b,c,d,e) macro_do_syscall a,b,c,d,e
%define syscall(a,b,c,d) macro_do_syscall a,b,c,d
%define syscall(a,b,c) macro_do_syscall a,b,c
%define syscall(a,b) macro_do_syscall a,b
%define syscall(a) macro_do_syscall a

%macro change_syscall_error_handler 1
	%define __syserror_handler %1
%endmacro
%define ech(a) change_syscall_error_handler a
Download .txt
gitextract_bxrp70mk/

├── .gitignore
├── LICENSE
├── MACROS
├── Makefile
├── README
├── asmhttpd.asm
├── constants.inc
└── syscall.inc
Condensed preview — 8 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (40K chars).
[
  {
    "path": ".gitignore",
    "chars": 20,
    "preview": "asmhttpd\nasmhttpd.o\n"
  },
  {
    "path": "LICENSE",
    "chars": 18092,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Fr"
  },
  {
    "path": "MACROS",
    "chars": 1567,
    "preview": "\nThe syscall() macro should be invoked as follows:\n\tsyscall(#,arg1,arg2,arg3,arg4,arg5,arg6)\n\nError checking is built in"
  },
  {
    "path": "Makefile",
    "chars": 103,
    "preview": "\nasmhttpd: asmhttpd.o\n\tld $^ -o $@\n\n%.o: %.asm\n\tnasm -f elf64 -O0 -o $@ $<\n\nclean:\n\trm -f *.o asmhttpd\n"
  },
  {
    "path": "README",
    "chars": 942,
    "preview": "asmhttpd - The tiniest webserver ever written\n\nHOW TO BUILD:\n-------------\n\n\tJust run \"make\". You will need NASM on your"
  },
  {
    "path": "asmhttpd.asm",
    "chars": 12864,
    "preview": "; vim: syntax=nasm\n;\n; asmhttpd: A minimalist HTTP webserver for Linux, written in x86_64 assembly.\n;\n; Copyright (C) 20"
  },
  {
    "path": "constants.inc",
    "chars": 1807,
    "preview": ";; syscalls\n%define sys_accept\t43\n%define sys_bind\t49\n%define sys_chdir\t80\n%define sys_chroot\t161\n%define sys_clone\t56\n%"
  },
  {
    "path": "syscall.inc",
    "chars": 3056,
    "preview": "; See the MACROS file for a description of how this monstrosity works\n\n;; r64,r32,r16,r8,arg\n%macro load_syscall_argumen"
  }
]

About this extraction

This page contains the full source code of the jcalvinowens/asmhttpd GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 8 files (37.5 KB), approximately 11.0k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!