Commit graph

373 commits

Author SHA1 Message Date
Justine Tunney
f3e28aa192 Make SSL handshakes much faster
This change boosts SSL handshake performance from 2,627 to ~10,000 per
second which is the same level of performance as NGINX at establishing
secure connections. That's impressive if we consider that redbean is a
forking frontend application server. This was accomplished by:

  1. Enabling either SSL session caching or SSL tickets. We choose to
     use tickets since they reduce network round trips too and that's
     a more important metric than wrk'ing localhost.

  2. Fixing mbedtls_mpi_sub_abs() which is the most frequently called
     function. It's called about 12,000 times during an SSL handshake
     since it's the basis of most arithmetic operations like addition
     and for some strange reason it was designed to make two needless
     copies in addition to calling malloc and free. That's now fixed.

  3. Improving TLS output buffering during the SSL handshake only, so
     that only a single is write and read system call is needed until
     blocking on the ping pong.

redbean will now do a better job wiping sensitive memory from a child
process as soon as it's not needed. The nice thing about fork is it's
much faster than reverse proxying so the goal is to use the different
address spaces along with setuid() to minimize the risk that a server
key will be compromised in the event that application code is hacked.
2021-07-11 23:17:47 -07:00
Justine Tunney
8c4cce043c Make improvements to redbean
The following Lua APIs have been added:

  - IsDaemon() → bool
  - ProgramPidPath(str)

The following Lua hooks have been added:

  - OnClientConnection(ip:int,port:int,serverip:int,serverport:int) → bool
  - OnProcessCreate(pid:int,ip:int,port:int,serverip:int,serverport:int)
  - OnProcessDestroy(pid:int)
  - OnServerStart()
  - OnServerStop()
  - OnWorkerStart()
  - OnWorkerStop()

redbean now does a better job at applying gzip on the fly from the local
filesystem, using a streaming chunked api with constant memory, which is
useful for doing things like serving a 4gb text file off NFS, and having
it start transmitting in milliseconds. redbean will also compute entropy
on the beginnings of files to determine if compression is profitable.

This change pays off technical debts relating to memory, such as relying
on exit() to free() allocations. That's now mostly fixed so it should be
easier now to spot memory leaks in malloc traces.

This change also fixes bugs and makes improvements to our SSL support.
Uniprocess mode failed handshakes are no longer an issue. Token Alpn is
offered so curl -v looks less weird. Hybrid SSL certificate loading is
now smarter about naming conflicts. Self-signed CA root anchors will no
longer be delivered to the client during the handshake.
2021-07-10 15:19:37 -07:00
Paul Kulchenko
98c674d915
Update Fetch() to POST if body is provided (#211) 2021-07-10 12:39:02 -07:00
Gautham
e99a4dcc8c
Add protoent and netent (#209)
The implementations of the getproto* functions follow from the getserv*
functions: same static name allocation, same type of internal function
that opens a file to search, aliases are not written to the struct, same
type of error handling/returns.

This changes also fixes a getaddrinfo AI_PASSIVE memory error. When
getaddrinfo is passed name = NULL and AI_PASSIVE in hints->ai_flags, it was
setting the s_addr value to INADDR_ANY but *not* returning the addrinfo
pointer via *res = ai. This caused a free(NULL) memory error when the caller
tried to free res, because the caller expects res to be a valid pointer to a
struct addrinfo.

Our non-standard API parseport() has been updated to use strtoimax.
strtoimax has an extra parameter endptr to store where the parsing was
terminated. endptr is used in parseport to check if the provided string
was valid.
2021-07-10 12:36:35 -07:00
Justine Tunney
c002e4ba76 Support hybrid ECDSA / RSA certificate loading 2021-07-09 19:21:00 -07:00
Justine Tunney
fe881982b5 Make slight SSL performance improvements 2021-07-08 21:54:21 -07:00
Justine Tunney
4178896aa0 Fix bug with redbean help flag 2021-07-08 18:28:11 -07:00
Justine Tunney
3641e99042 Add Lua API documentation to redbean -h | less 2021-07-08 17:55:35 -07:00
Justine Tunney
45d72920ba Fix chained certificate loading 2021-07-08 17:29:32 -07:00
Justine Tunney
feb0f9fb3a Make improvements to redbean
- Fix Content-Type inference when file extension has number
- Remove shoddy Class A granular IP classiifcation
- Have setuid() and setgid() take effect w/o daemonization
- Make GetParams() return empty table instead of nil
- Change SetLogLevel(int) to only apply to one message
- Make SetLogLevel(int) good enough to be access_log off
- Introduce ProgramUid(int) which is same as -U INT
- Introduce ProgramGid(int) which is same as -G INT
- Introduce ProgramLogPath(str) which is same as -L PATH
- Introduce ProgramDirectory(str) which is same as -D PATH
- Introduce ProgramLogBodies(bool) which is same as -b
- Introduce ProgramLogMessages(bool) which is same as -m
2021-07-08 15:56:23 -07:00
Justine Tunney
cc9366b200 Add file Slurp() API to redbean 2021-07-08 13:21:16 -07:00
Justine Tunney
c89bc56f6a Add HTTP/HTTPS Fetch() API to redbean
You can now say the following in your redbean Lua code:

    status,headers,payload = Fetch("https://foo.example")

The following Lua APIs have been introduced:

  - Fetch(str) → str,{str:str},str
  - GetHttpReason(int) → str
  - GetHttpReason(int) → str
  - ProgramSslFetchVerify(bool)
  - ProgramSslClientVerify(bool)

The following flags have been introduced:

  - `-j` enables client SSL verification
  - `-k` disables Fetch() SSL verification
  - `-t INT` may now be passed a negative value for keepalive

Lua exceptions now invoke Cosmopolitan's garbage collector when
unwinding the stack. So it's now safe to use _gc() w/ Lua 𝔱𝔥𝔯𝔬𝔴

See #97
2021-07-07 21:44:27 -07:00
Justine Tunney
36b2710e1a Update curl example to support ssl / https
Now that we know our SSL client works, and that it's able to verify
certificates, the next step will be adding it as an API to redbean.

See #97
2021-07-06 13:39:18 -07:00
Justine Tunney
e51034bab3 Make GCM AES faster
13.22% mbedtls_aesni_gcm_mult
    13.03% mbedtls_gcm_update
     9.85% mbedtls_aesni_crypt_ecb

Overhead improvement (perf record)

    10.97% mbedtls_aesni_gcm_mult
    10.59% mbedtls_aesni_crypt_ecb
     2.26% mbedtls_gcm_update
2021-07-06 08:27:16 -07:00
Justine Tunney
f8b9bd2b47 Attempt to make LLD happy
Things are a little better. The LLD that comes with Linux seems to work.
Old versions like LLVM 8 haven't been supported since Cosmopolitan v0.2.
Running Clang on Windows with --target=x86_64-pc-linux-gnu doesn't seem
to work. It has something to do with the recently added .zip section in
the linker script. But even if that's removed, LLD on Windows thinks it
is building an EFI application for some reason. Linker scripts are such
a brittle house of cards, even for just ld.bfd alone..

We should just find a way to run our one true musl-cross-make linux gcc
toolchain under Blinkenlights on non-Linux because GCC and Clang are so
nondeterministic, inconsistent, and unreproducible when built for other
operating systems. We need an actually portable compiler/linker that'll
always behave the same way no matter what.

See #180
2021-07-05 19:10:06 -07:00
Justine Tunney
0ecd71f697 Make chacha20 go faster 2021-07-05 14:03:50 -07:00
Gautham
c0bec24fa2
Improve getservbyname and getservbyport (#207)
- support aliases in /etc/services
- use case insensitive comparisons
- add tests
2021-07-05 12:25:26 -07:00
Justine Tunney
58fb2fb3d3 Add chunked transfer decoding to redbean 2021-07-05 01:05:10 -07:00
Justine Tunney
8d5f60a9cd Add more hashing apis to redbean 2021-07-05 01:05:10 -07:00
Gautham
0ea2907730
Add getservbyname and getservbyport (#204)
For every call of getservbyname/getservbyport the lookup of
/etc/services is done by opening the file and parsing each line
one-by-one. This is slow, but the implementation is simple.

This change also adds fixes for the gethostbyname function.
2021-07-04 16:31:42 -07:00
Justine Tunney
cfbd2afc19 Add example for printing <img> tag 2021-07-04 15:41:43 -07:00
Justine Tunney
a7bd4ed9ea Make redbean tinier
Under MODE=tiny or MODE=tinylinux we now go back to using my homebrew
version of DEFLATE decompression which is 10x smaller but 10x slower
than Chromium Zlib. In tiny mode we also disable compressed responses
howewver redbean will still serve precompressed responses. This change
also removes a few other dependencies like strftime() and getaddrinfo()
which means you can't say `-l localhost` in tiny mode, you have to say
something like `-l 127.0.0.1`.

    m=tinylinux
    make -j8 MODE=$m o/$m/tool/net/redbean-original.com
    ls -hal o/$m/tool/net/redbean-original.com

This change reduces the above size from 191.4 to 150.9 kb.
2021-07-04 12:26:54 -07:00
Justine Tunney
300876ee50 Fix typo 2021-07-03 10:16:38 -07:00
Justine Tunney
e6b22f1f65 Remove remaining build references to zip command 2021-07-03 08:37:15 -07:00
Justine Tunney
d6873f637f Release redbean 1.4 2021-07-03 05:58:47 -07:00
Justine Tunney
74200a0ea0 Make redbean ssl handshake go a little faster 2021-07-03 05:51:04 -07:00
Justine Tunney
87222aad35 Improve PrintMemoryIntervals 2021-07-03 04:19:10 -07:00
Justine Tunney
053ee714bd Add Braille Dump tool 2021-07-02 10:24:12 -07:00
Justine Tunney
8e69cf133a Restore basicidea.c from gist 2021-07-02 08:09:56 -07:00
Gautham
3fe7b95fd0
Add gethostbyname and gethostbyaddr (#200)
gethostbyname, gethostbyaddr follow simple implementations: they
internally call getaddrinfo and getnameinfo respectively, and fill out
the minimum details. remaining functions are stubs.
2021-07-01 07:55:11 -07:00
Justine Tunney
014d4bdab2 Make minor revisions to previous change 2021-06-30 10:45:27 -07:00
Justine Tunney
a68cc690ff Merge HTTP request / response parsing code
This change also fixes a bug so that DNS lookups work correctly when the
first answer is a CNAME record.
2021-06-27 17:04:32 -07:00
fabriziobertocci
5a6c0f27c3
Fix redundancy in ioctl(SIOCGIFADDR) (#198) 2021-06-27 09:03:14 -07:00
Justine Tunney
2d79ab6c15 Make sha1 / sha256 / sha512 go faster 2021-06-26 00:11:12 -07:00
Justine Tunney
5144c22189 Add test for ioctl(SIOCGIFCONF) and polyfill on BSDs
- Use nullness checks when calling weakly linked functions.

- Avoid typedef for reasons described in Linux Kernel style guide.

- Avoid enum in in Windows headers. Earlier in Cosmo's history all one
  hundred files in libc/nt/enum/ used to be enums and it resulted in
  gigabytes of DWARF data almost as large as everything else in the
  codebase combined.

- Bitfields aren't our friends. They have frequent ABI breakages,
  inconsistent arithmetic across compilers, and different endianness
  between cpus. Compiler authors also haven't invested much roi into
  making bit fields go fast so they produce poor assembly.

- Use memccpy() instead of strncpy() or snprintf() for length-bounded
  copying of C strings. strncpy() is a misunderstood function and
  snprintf() is awesome but memccpy() deserves more love.
2021-06-25 18:44:04 -07:00
Justine Tunney
86ab24ce56 Correct minor issues with recent SSL change 2021-06-24 15:22:24 -07:00
Justine Tunney
cc1920749e Add SSL to redbean
Your redbean can now interoperate with clients that require TLS crypto.
This is accomplished using a protocol polyglot that lets us distinguish
between HTTP and HTTPS regardless of the port number. Certificates will
be generated automatically, if none are supplied by the user. Footprint
increases by only a few hundred kb so redbean in MODY=tiny is now 1.0mb

- Add lseek() polyfills for ZIP executable
- Automatically polyfill /tmp/FOO paths on NT
- Fix readdir() / ftw() / nftw() bugs on Windows
- Introduce -B flag for slower SSL that's stronger
- Remove mbedtls features Cosmopolitan doesn't need
- Have base64 decoder support the uri-safe alternative
- Remove Truncated HMAC because it's forbidden by the IETF
- Add all the mbedtls test suites and make them go 3x faster
- Support opendir() / readdir() / closedir() on ZIP executable
- Use Everest for ECDHE-ECDSA because it's so good it's so good
- Add tinier implementation of sha1 since it's not worth the rom
- Add chi-square monte-carlo mean correlation tests for getrandom()
- Source entropy on Windows from the proper interface everyone uses

We're continuing to outperform NGINX and other servers on raw message
throughput. Using SSL means that instead of 1,000,000 qps you can get
around 300,000 qps. However redbean isn't as fast as NGINX yet at SSL
handshakes, since redbean can do 2,627 per second and NGINX does 4.3k

Right now, the SSL UX story works best if you give your redbean a key
signing key since that can be easily generated by openssl using a one
liner then redbean will do all the things that are impossibly hard to
do like signing ecdsa and rsa certificates that'll work in chrome. We
should integrate the let's encrypt acme protocol in the future.

Live Demo: https://redbean.justine.lol/
Root Cert: https://redbean.justine.lol/redbean1.crt
2021-06-24 13:20:50 -07:00
Justine Tunney
1beeb7a829 Flatten Mbed TLS directory structure 2021-06-24 11:13:12 -07:00
Justine Tunney
d0ac995dc0 Get Mbed TLS to build
This change configures Mbed TLS to support the fewest number of things
possible required to run an HTTPS server that caters to the sweet spot
of being legacy enough to support the vast majority of user agents but
modern enough that Chrome and Firefox remain happy. That should entail

- TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
- TLS_RSA_WITH_AES_128_CBC_SHA

Even though other suites still get included so what usually happens in
practice is ECDHE-RSA-AES256-GCM-SHA384 under TLS 1.2 will be selected
and the binary footprint is reasonable, and should cost us about 200kb
2021-06-24 11:12:59 -07:00
Justine Tunney
19bd27358a Import Mbed TLS v2.26.0 2021-06-24 11:12:45 -07:00
Justine Tunney
1ba33d233c Add root certificates 2021-06-24 11:12:23 -07:00
fabriziobertocci
fd0eefce17
Add ioctl(SIOCGIFxxx) support (#197)
- SIOCGIFCONFIG: reads and enumerate all the network interfaces
- SIOCGIFADDR: reads network address for a given interface
- SIOCGIFFLAGS: reads network flags for a given interface
- SIOCGIFNETMASK: reads network netmask for a given interface
- SIOCGIFBRDADDR: reads network broadcast address for a given interface
- SIOCGIFDSTADDR: reads peer destination address for a given
  interface (not supported for Windows)

This change defines Linux ABI structs for the above interfaces and adds
polyfills to ensure they behave consistently on XNU and Windows.
2021-06-24 10:53:27 -07:00
ahgamut
4d8f884e76 Get Info-ZIP's zip to build
* removed unnecessary files (like amiga/osdep.h)
* makefile has 4 targets: zip, zipnote, zipcloak, zipsplit
* added clang-format off at the start of all source files
* added necessary headers
2021-06-22 12:38:56 -07:00
ahgamut
4ce5664c4b added zip from Info-ZIP 2021-06-22 12:38:56 -07:00
Gautham
98c53ae526
Simplify getnameinfo (#196)
The getnameinfo implementation requires an address -> name lookup on the
hosts file (ie struct HostsTxt) and the previous implementation used
flags to check whether HostsTxt was sorted according to address or name,
and then re-sorted it if necessary. Now getnameinfo lookup does not
require sorting, it does a simple linear lookup, and so the related code
was simplified

See #172 for discussion.
2021-06-22 12:35:58 -07:00
Justine Tunney
1f87640d17 Add half close flag to netcat example 2021-06-15 11:24:24 -07:00
Justine Tunney
e4ef38403b Make port optional in X-Forwarded-For
This parser was being overly restrictive which presented integration
issues with haproxy which doesn't make it easy to pass the port info
2021-06-15 06:46:30 -07:00
Justine Tunney
87d7010495 Improve performance of bitscanning intrinsics
This change helps spectre more intelligently plan execution, by working
around false output dependencies, impacting ops like popcnt bsr and bsf
2021-06-15 06:29:51 -07:00
Justine Tunney
29cb53881e Fix SQLite home directory discovery on Windows
See #193
2021-06-12 00:28:06 -07:00
Justine Tunney
8d7d00af3a Pacify file locks on Windows
This change gets redbean SQLite working in write mode on Windows.
Warnings have been added to the appropriate and responsible places.
Hacking proprietary PC systems into production-worthy servers isn't
terribly high on the list of priorities. Consider BSD or Linux when
building online systems that service requests from multiple people.

Fixes #193
2021-06-12 00:01:55 -07:00