what-happens-when README

The project's README from github.com/alex/what-happens-when. As one markdown file: README.md.

What happens when...

This repository is an attempt to answer the age-old interview question "What happens when you type google.com into your browser's address box and press enter?"

Except instead of the usual story, we're going to try to answer this question in as much detail as possible. No skipping out on anything.

This is a collaborative process, so dig in and try to help out! There are tons of details missing, just waiting for you to add them! So send us a pull request, please!

This is all licensed under the terms of the Creative Commons Zero_ license.

Read this in 简体中文_ (simplified Chinese), 日本語_ (Japanese), 한국어_ (Korean) and Spanish_. NOTE: these have not been reviewed by the alex/what-happens-when maintainers.

Table of Contents

.. contents:: :backlinks: none :local:

The "g" key is pressed

The following sections explain the physical keyboard actions and the OS interrupts. When you press the key "g" the browser receives the event and the auto-complete functions kick in. Depending on your browser's algorithm and if you are in private/incognito mode or not various suggestions will be presented to you in the dropdown below the URL bar. Most of these algorithms sort and prioritize results based on search history, bookmarks, cookies, and popular searches from the internet as a whole. As you are typing "google.com" many blocks of code run and the suggestions will be refined with each keypress. It may even suggest "google.com" before you finish typing it.

The "enter" key bottoms out

To pick a zero point, let's choose the Enter key on the keyboard hitting the bottom of its range. At this point, an electrical circuit specific to the enter key is closed (either directly or capacitively). This allows a small amount of current to flow into the logic circuitry of the keyboard, which scans the state of each key switch, debounces the electrical noise of the rapid intermittent closure of the switch, and converts it to a keycode integer, in this case 13. The keyboard controller then encodes the keycode for transport to the computer. This is now almost universally over a Universal Serial Bus (USB) or Bluetooth connection, but historically has been over PS/2 or ADB connections.

In the case of the USB keyboard:

In the case of Virtual Keyboard (as in touch screen devices):

Interrupt fires [NOT for USB keyboards]

The keyboard sends signals on its interrupt request line (IRQ), which is mapped to an interrupt vector (integer) by the interrupt controller. The CPU uses the Interrupt Descriptor Table (IDT) to map the interrupt vectors to functions (interrupt handlers) which are supplied by the kernel. When an interrupt arrives, the CPU indexes the IDT with the interrupt vector and runs the appropriate handler. Thus, the kernel is entered.

(On Windows) A WM_KEYDOWN message is sent to the app

The HID transport passes the key down event to the KBDHID.sys driver which converts the HID usage into a scancode. In this case, the scan code is VK_RETURN (0x0D). The KBDHID.sys driver interfaces with the KBDCLASS.sys (keyboard class driver). This driver is responsible for handling all keyboard and keypad input in a secure manner. It then calls into Win32K.sys (after potentially passing the message through 3rd party keyboard filters that are installed). This all happens in kernel mode.

Win32K.sys figures out what window is the active window through the GetForegroundWindow() API. This API provides the window handle of the browser's address box. The main Windows "message pump" then calls SendMessage(hWnd, WM_KEYDOWN, VK_RETURN, lParam). lParam is a bitmask that indicates further information about the keypress: repeat count (0 in this case), the actual scan code (can be OEM dependent, but generally wouldn't be for VK_RETURN), whether extended keys (e.g. alt, shift, ctrl) were also pressed (they weren't), and some other state.

The Windows SendMessage API is a straightforward function that adds the message to a queue for the particular window handle (hWnd). Later, the main message processing function (called a WindowProc) assigned to the hWnd is called in order to process each message in the queue.

The window (hWnd) that is active is actually an edit control and the WindowProc in this case has a message handler for WM_KEYDOWN messages. This code looks within the 3rd parameter that was passed to SendMessage (wParam) and, because it is VK_RETURN knows the user has hit the ENTER key.

(On OS X) A KeyDown NSEvent is sent to the app

The interrupt signal triggers an interrupt event in the I/O Kit kext keyboard driver. The driver translates the signal into a key code which is passed to the OS X WindowServer process. Resultantly, the WindowServer dispatches an event to any appropriate (e.g. active or listening) applications through their Mach port where it is placed into an event queue. Events can then be read from this queue by threads with sufficient privileges calling the mach_ipc_dispatch function. This most commonly occurs through, and is handled by, an NSApplication main event loop, via an NSEvent of NSEventType KeyDown.

(On GNU/Linux) the Xorg server listens for keycodes

When a graphical X server is used, X will use the generic event driver evdev to acquire the keypress. A re-mapping of keycodes to scancodes is made with X server specific keymaps and rules. When the scancode mapping of the key pressed is complete, the X server sends the character to the window manager (DWM, metacity, i3, etc), so the window manager in turn sends the character to the focused window. The graphical API of the window that receives the character prints the appropriate font symbol in the appropriate focused field.

Parse URL

Is it a URL or a search term?

When no protocol or valid domain name is given the browser proceeds to feed the text given in the address box to the browser's default web search engine. In many cases the URL has a special piece of text appended to it to tell the search engine that it came from a particular browser's URL bar.

Convert non-ASCII Unicode characters in the hostname

Check HSTS list

DNS lookup

ARP process

In order to send an ARP (Address Resolution Protocol) broadcast the network stack library needs the target IP address to lookup. It also needs to know the MAC address of the interface it will use to send out the ARP broadcast.

The ARP cache is first checked for an ARP entry for our target IP. If it is in the cache, the library function returns the result: Target IP = MAC.

If the entry is not in the ARP cache:

ARP Request::

Sender MAC: interface:mac:address:here
Sender IP: interface.ip.goes.here
Target MAC: FF:FF:FF:FF:FF:FF (Broadcast)
Target IP: target.ip.goes.here

Depending on what type of hardware is between the computer and the router:

Directly connected:

Hub:

Switch:

ARP Reply::

Sender MAC: target:mac:address:here
Sender IP: target.ip.goes.here
Target MAC: interface:mac:address:here
Target IP: interface.ip.goes.here

Now that the network library has the IP address of either our DNS server or the default gateway it can resume its DNS process:

Opening of a socket

Once the browser receives the IP address of the destination server, it takes that and the given port number from the URL (the HTTP protocol defaults to port 80, and HTTPS to port 443), and makes a call to the system library function named socket and requests a TCP socket stream - AF_INET/AF_INET6 and SOCK_STREAM.

At this point the packet is ready to be transmitted through either:

For most home or small business Internet connections the packet will pass from your computer, possibly through a local network, and then through a modem (MOdulator/DEModulator) which converts digital 1's and 0's into an analog signal suitable for transmission over telephone, cable, or wireless telephony connections. On the other end of the connection is another modem which converts the analog signal back into digital data to be processed by the next network node_ where the from and to addresses would be analyzed further.

Most larger businesses and some newer residential connections will have fiber or direct Ethernet connections in which case the data remains digital and is passed directly to the next network node_ for processing.

Eventually, the packet will reach the router managing the local subnet. From there, it will continue to travel to the autonomous system's (AS) border routers, other ASes, and finally to the destination server. Each router along the way extracts the destination address from the IP header and routes it to the appropriate next hop. The time to live (TTL) field in the IP header is decremented by one for each router that passes. The packet will be dropped if the TTL field reaches zero or if the current router has no space in its queue (perhaps due to network congestion).

This send and receive happens multiple times following the TCP connection flow:

TLS handshake

If a packet is dropped

Sometimes, due to network congestion or flaky hardware connections, TLS packets will be dropped before they get to their final destination. The sender then has to decide how to react. The algorithm for this is called TCP congestion control. This varies depending on the sender; the most common algorithms are cubic on newer operating systems and New Reno_ on almost all others.

HTTP protocol

If the web browser used was written by Google, instead of sending an HTTP request to retrieve the page, it will send a request to try and negotiate with the server an "upgrade" from HTTP to the SPDY protocol.

If the client is using the HTTP protocol and does not support SPDY, it sends a request to the server of the form::

GET / HTTP/1.1
Host: google.com
Connection: close
[other headers]

where [other headers] refers to a series of colon-separated key-value pairs formatted as per the HTTP specification and separated by single newlines. (This assumes the w

what-happens-when (alex/what-happens-when)

Searching Database…

这是什么?这是一份篇幅很长、细节极其丰富的讲解,回答了面试中的经典问题:在浏览器中输入 google.com 并按下回车后,中间究竟发生了什么,并完整梳理从按键到页面渲染呈现的全过程。
这是教程、参考文档,还是别的什么?这是一份由多人协作编写的 reStructuredText 文档,按顺序分成若干章节,每一章从技术层面深入讲解过程中的一个阶段;它不是工具,也不是带练习的课程。
内容是怎么组织的?我该从哪里开始读?内容按照事件发生的真实时间顺序自上而下展开:先从键盘上的物理按键讲起,接着是各操作系统特有的中断处理(Windows、OS X、Linux/Xorg),然后是 URL 解析、HSTS 检查、DNS 查询和 ARP 解析,之后继续讲解网络和渲染的其余环节。
我看这份文档需要什么基础知识吗?最好对操作系统、网络基础(DNS、ARP、TCP/IP)以及浏览器的工作原理有一定了解,因为讲解会深入到 USB 协议细节和内核中断处理,且几乎不做简化。
这份讲解已经完整了吗?还没有。作者明确表示,这份文档仍在持续完善中,许多细节尚未补充;它是由社区维护的文档,而不是经过权威审核的正式参考资料。
这份文档面向哪些人?面向希望深入了解加载一个 URL 时,从硬件、操作系统到网络各层底层究竟发生了什么的开发者和求职面试者。
有译本吗?有。社区提供了简体中文、日语、韩语和西班牙语的译本,不过维护者提醒,这些译本尚未经过准确性审校。
是否涵盖各操作系统之间的差异?涵盖。从按键到应用事件这一部分,分别详细讲解了 Windows(Win32K.sys、WMKEYDOWN)、OS X(WindowServer、NSEvent)和 GNU/Linux(Xorg、evdev)的情况。
网络部分讲得有多深?非常深入:包括 DNS 缓存的查找顺序、hosts 文件检查,以及完整的 ARP 过程讲解,还涉及直连、集线器和交换机之间的行为差异。
Creator
alex
Size
0.3 MB
Stars
43.4K
Updated
CommitFeb 08
Age
12y
Commits · 90 Days