Last active
November 23, 2020 21:35
-
-
Save zxdcm/069deadf53ed04990d9f34e73a49c276 to your computer and use it in GitHub Desktop.
Networks, HTTP, DNS, and so on
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Proxy may return info from cache!! | |
Forward proxy (for client) | |
Reverse proxy (for server, service) | |
(можно на отдельный сервер вынести отправку статического контента, | |
как раз reverse proxy) | |
CDN - Content Delivery Network | |
Proxy may return info from cache | |
Anycast - sends data to the near servers | |
Broadcast - to all servers | |
Multicast | |
Unicast | |
Geocast | |
CDN = anycast + proxy | |
Плюсы: | |
1. сокращение нагрузки на гл. сервер за счет кэширования на локальных | |
2. сокращение трафика | |
Можно передавать сжатые данные от главного сервера на вспомогательные. | |
Масштабирование | |
1. Горизонтальное | |
2. Вертикальное | |
1. | |
Кластер из серверов. | |
Есть балансировщик нагрузки (определяет на какой сервер слать запрос) | |
Балансировщики: аппаратные, программные. | |
Балансировщик хранит сессию пользователя -> | |
повторный запрос уйдет на тот же сервер (если держать соединение открытым) | |
-> прирост к производительности | |
Минусы: много функций на балансировщике -> станет узким местом. | |
Обмен локальными данными: | |
Разделить данные сессии пользователей между всеми нодами кластера. | |
Использование бд для храненния сессий. | |
Memcached | |
Объединяется RAM разных серверов в один пул. | |
Redis кластер | |
IP Packet = Header + Payload | |
TCP: | |
duplex - bidirectional | |
3 handshakes: | |
SYN - synchronize sequence numbers | |
Once data flows between both ends - each TCP segment has a sequence number. | |
Before communication can start, both ends need to synchronize the sequence number | |
of the first segments. | |
После установки соединения - оба могут отправлять данные | |
Закрытие: Fin flag + acknowledgment | |
HTTP: | |
first line - request line or responce line | |
request line: Action Resource HTTP_v | |
responce line (status line): http_v, status code, status message | |
DNS | |
https://habrastorage.org/getpro/habr/post_images/699/4aa/64a/6994aa64af1073ce4514b3a5a809e480.png | |
Ресурсная запись — это то, собственно ради чего в конечном счете и существует DNS. | |
Ресурсная запись — это единица хранения и передачи информации в DNS. | |
Каждая такая запись несет в себе информацию соответствия какого-то | |
имени и служебной информации в DNS, например соответствие имени домена — IP адреса. | |
Name | |
Time to live (TTL) - время хранения в кэше | |
Class - IN (для поддержки других протоколов, не TCP/IP) | |
тип (TYPE) — тип записи синтаксис и назначение записи | |
данные (DATA) — различная информация, формат и синтаксис которой определяется типом. | |
Типы: | |
A | |
Name TTL class data | |
k-max.name. 86400 IN A 81.177.139.65 | |
AAAA (ipv6) | |
CNAME (алиас) | |
ftp 86400 IN CNAME www.k-max.name. | |
MX (mail exchange) — указывает хосты для доставки почты, адресованной домену. | |
NS (name server/сервер имён) указывает на DNS-сервер, обслуживающий данный домен | |
PTR (pointer) — отображает IP-адрес в доменное имя (о данном типе записи поговорим ниже в разделе обратного преобразования имен). | |
... | |
https://habr.com/ru/post/137587/ | |
... | |
Делегирование — это операция передачи ответственности | |
за часть дерева доменных имен (зону) другому лицу или организации | |
после делегирования ответственности, информация хранимая делегирующей зоной уже не включает информацию по делегированному поддомену и его ресурсным записям хостов, | |
а хранит информацию о серверах имен, являющихся для делегируемого поддомена авторитативными | |
Сервера - первичный, вторичный, кэширующий | |
Клиенты DNS (resolver) | |
https://habrastorage.org/getpro/habr/post_images/8a3/03e/2fc/8a303e2fccdaf27e0a642ace38582ed8.png | |
Обратное преобразование имен | |
DNS используется в первую очередь для преобразования доменных имён в IP-адреса, | |
но он также может выполнять обратный процесс, | |
называемый Обратное преобразование имен или обратным отображением | |
Регистратором для корневого домена является организация ICANN. | |
Чтобы стать регистратором доменов в зонах второго уровня | |
(.com .net .org .biz .info .name .mobi .asia .aero .tel .travel .jobs ...), | |
необходимо получить аккредитацию ICANN. | |
WebSockets: | |
WebSockets provide a persistent connection between a client and server that both parties can use to start sending data at any time. | |
The client establishes a WebSocket connection through a process known as the WebSocket handshake. | |
If the server supports the WebSocket protocol, it agrees to the upgrade and communicates this through an Upgrade header in the response. | |
HTTP/1.1 101 WebSocket Protocol Handshake | |
Date: Wed, 16 Oct 2013 10:07:34 GMT | |
Connection: Upgrade | |
Upgrade: WebSocket | |
HTTP | |
1. Resources | |
The target of the http is the resource which is identified by URI (URL \ URN) | |
URLs & URNs | |
url - locator ~ web address; | |
urns - identifies a resource by name in a particular namespace: | |
urn:ietf:rfc:7230 // corresponds to the book Nineteen Eighty-Four by George Orwell, | |
syntax of URIs | |
scheme / protocol | |
http:// (https:) / mailto: / ftp: / ws (websocket-connections) wss (secure ws) / view-source (source code), urn, tel, ssh | |
Authority | |
^ domain / authority that governs the namespace / ip address | |
Port: | |
(gate on the web server); 80 - http; 443 - https; | |
path: | |
/path/to/myfile.html | |
query - extra params provided to web server (& - separator) | |
?key=value1&key2=value2 | |
fragment (#somewhereinthedoc) !!!!!!!!!! newer sent to request, | |
Anchor to the part of the document (a bookmark in the document) | |
It's better to use only http \ https, cos browsers might remove support of others | |
Data URLS | |
Data URLs, URLs prefixed with the data: scheme, allow content creators to embed small files inline in documents | |
data:[<mediatype>][;base64],<data> | |
data:text/html,<script>alert('hi');</script> | |
Unifor resource locator | |
MIME types (multipurpose internet mail extensions or MIME type) | |
type/subtype;parameter=value // param is optional; type/subtype - mandatory | |
text/plain;charset=UTF-8 | |
Discrete & Multipart | |
multipart - multiple component parts, each of which may habe own mime type; multiple fiels being sent together in one transaction | |
Discrete: | |
application - any kind of binary data | |
// application/pdf | |
// application/zip | |
// application/octet-stream (generic binary data with unknown type) | |
audio | |
//audio/mpeg | |
//audio/vorbis | |
font | |
//font/woff | |
//font/tff | |
image | |
//image/png | |
// image/svg+xml | |
model | |
// | |
text | |
// text/plain | |
// text/html | |
// text/csv | |
video | |
// video/mp4 | |
Unknown text - text/plain; Unknown binary data - application/octet-stream | |
Multipart types: | |
// multipart/form-data | |
// multipart/byteranges | |
//message/rfc822 (forwareded or replied to message quoting | |
//multipart/form-data (multiple component and each might have separate mimetype) | |
Если сервер шлет css как text/plain, браузер скорее всего не поймет. Но есть Mime sniffing, об этом позже. | |
text/javascript - так нужно слать | |
application/javascript - валидный, но для легаси | |
The multipart/form-data type can be used when sending the values of a completed HTML Form from browser to server. | |
--aBoundaryString | |
Content-Disposition: form-data; name="myFile"; filename="img.jpg" | |
Content-Type: image/jpeg | |
(data) | |
--aBoundaryString | |
Content-Disposition: form-data; name="myField" | |
-- - separator | |
The multipart/byteranges MIME type is used to send partial responses to the browser. | |
Importance of setting the correct MIME type | |
For security reasons, most browsers to not allow setting a custom actions | |
for resources with unrecognized mime type (application/octet-stream) | |
X-Content-Type-Options - header | |
X-Content-Type-Options: nosniff - отключает mime sniffing, использует тот который послал сервер | |
www or non www | |
1. один canonical другой нет + 301 редирект | |
2. использовать оба | |
Http - application layer protocol for transmitting hypermedia documents (such as html). | |
Properties: | |
Use client-server model; | |
Stateless protocol | |
TCP as transport layer (might use UDP) | |
Http - is exchaning of individual messages (oposite to stream of data) | |
TLS (encrypted TCP) | |
Http is also used to fetch images, videos, post forms. | |
User-agent is any tool that acts on the behalf of the user | |
Proxy: | |
- caching | |
- filtering | |
- load balancing | |
- logging | |
- auth | |
Http - human readable, extensible (headers semantics, stateless) | |
Though http is stateless, cookies allow the use of stateful sessions. | |
Flow: | |
1. open tcp connection (open new one, reuse, open several tcp connections) | |
2. send http message (human readable, before http2.0) | |
3. read response | |
4. close / reuse connection | |
Request consisnt of | |
- Method | |
- The path of the resource to fetch (without protocol, port) | |
- The version of http protocol | |
- Options headers | |
- Body (for post) | |
Response: | |
- Version of protocol | |
- Status code | |
- Status message | |
- Http headers | |
- Body (optional) | |
--Content negotiation | |
server side (1 request) Headers: Accept; Accept-Language: | |
client side (2 requests); Request -> Return list -> Request with params from list | |
Revved resources | |
(https, js, css) + hash | |
Хэш у этих ресурсов с Cache-Control: Cache + Expires: infinite | |
Vary: Accept-Encoding // Vary - свой кэш под разный Accept; | |
Vary: User-Agent // | |
As discussed above, caching servers will by default match future requests only to requests with exactly the same headers and header values | |
Cache eviction, когда ресурс stale, копия остается в кэше, делается новый запрос и он может вернуть 200 \ 304 (Not modified) | |
что значит что версия в кэше норм и ее можно исп, будет обновлено время. Сохраняется пропускная способность | |
cookies | |
Session management | |
Logins, shopping carts, game scores | |
Personalization | |
User preferences, themes, and other settings | |
Tracking | |
Recording and analyzing user behavior | |
Cookies are sent with every request, so they can worsen performance | |
(даже там где не нужны, поэтому возможно лучше localStorage) | |
Set-Cookie: yummy_cookie=choco | |
Set-Cookie: tasty_cookie=strawberry | |
The lifetime of a cookie can be defined in two ways: | |
Session cookies are deleted when the current session ends. | |
The browser defines when the "current session" ends, and some browsers use session restoring when restarting, which can cause session cookies to last indefinitely long. | |
Permanent cookies are deleted at a date specified by the Expires attribute, or after a period of time specified by the Max-Age attribute. | |
max-age override the Expires | |
Set-Cookie: id=a3fWa; Expires=Thu, 21 Oct 2021 07:28:00 GMT; Secure; HttpOnly | |
Secure - https only (except localhost) | |
HttpOnly - not available from js | |
Domain: | |
ommited - only the same origin | |
.domain.com - domain + subdomains | |
Path - когда слать куку | |
Path=/docs is set, these paths match: | |
/docs | |
/docs/Web/ | |
/docs/Web/HTTP | |
Set-Cookie: mykey=myvalue; SameSite=Strict | |
Strict - // разлогин при навигации с другого сайта | |
Этот режим означает, что c ваше приложение не будет отправлять куки ни на один запрос с другого ресурса. | |
Lax - // разлогина нет | |
Режим Lax решает проблемы с разлогированием описанную выше, но при этом сохраняет хороший уровень защиты. В сущности он добавляет исключение, когда куки передаются при навигации высокого уровня, которая использует “безопасные” HTTP методы. | |
Согласно RFC безопасными методами считаются GET, HEAD, OPTIONS и TRACE. | |
// Prefix | |
Еще один механизм против фиксации сессии | |
__Host- | |
& | |
__Secure- | |
https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies | |
Basic access authentication | |
The "Basic" HTTP authentication scheme is defined in RFC 7617, | |
which transmits credentials as user ID/password pairs, encoded using base64. | |
OVER HTTPS | |
server headers | |
The realm is used to describe the protected area or to indicate the scope of protection | |
This could be a message like "Access to the staging site" or similar, so that the user knows to which space they are trying to get access | |
WWW-Authenticate: <type> realm=<realm> | |
Proxy-Authenticate: <type> realm=<realm> | |
client headers | |
Authorization: <type> <credentials> <cred> - uncoded64 userId:password | |
Proxy-Authorization: <type> <credentials> | |
None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment