Computer network

HTTP caching mechanism

The HTTP cache mechanism is that after the browser sends an HTTP request to the server for the first time, if the server returns the request resource and adds some cached fields in the response header, the request result and cache identifier are stored in the browser cache. All the PROCESSING of the HTTP cache is determined according to the response header returned by the first request resource. If both strong cache and negotiated cache exist, strong cache takes precedence.

Advantages of caching

  • Reduce redundant data transmission
  • Save network costs and alleviate network bottlenecks
  • Reduced range delay
  • By reducing the requirements on the original server, the server can respond faster and avoid overloads

The process for loading a web page is as follows

  1. The browser determines whether the strong cache is hit based on the HTTP header of a resource request. If the request is hit and the cache has not expired, the browser does not send a request to the server but obtains the resource from the cache. The return status code is 200
  2. If no match is found, the browser sends a resource loading request to the server and checks whether the cache is invalid based on the parameters carried in the request. If the cache is invalid, the browser does not return the resource information and continues to load resources from the cache
  3. If the negotiated cache is not hit, the server returns the resource in its entirety and updates the cache

Strong cache: If the requested data matches the mandatory cache, the browser directly obtains the data from the local cache and does not interact with the server. The response status code is 200

The associated Cache fields are: cache-control to indicate the amount of time the resource is cached including the permission of the Cache object, the desirable parameter max-age, and the public/private/no-cache/no-store parameters to set the access permission

Negotiated cache: When a strong cache is not hit, the browser sends the request to the server. The server determines whether the cache is hit based on the value of if-modify-since in the request header and the actual modification time of the resource. If the cache is hit, the status code 304 is returned. If the cache is not hit, the resource is returned and the cache is updated.

Alternatively, If the if-none-match parameter containing the Etag value is added to the header of the request, the unique identifier of the resource is determined. If the change indicates that the resource content is modified, the Match is not matched; otherwise, the Match is not matched

Reference documentation

Good articles

The storage mechanism

The browser storage mechanism provides a way to store user data on the client and interact with the server using cookies and sessions.

The cookie and session

Cookies and sessions are sessions used to track the identity of a browser user. The differences are as follows:

  • Storage location: Cookies are stored on the browser and sessions are stored on the server
  • Usage:
    1. Cookie mechanism: Special information sent by the server to the client is saved in text on the client. When we set the cookie cache time, the cookie will be saved in memory, until the expiration time will disappear; If the cache time is not set, the session cookie is displayed. If the browser is closed, the cookie disappears
    2. Session mechanism: When the server receives a request to create a session object, it checks whether the sessionID exists in the request parameter. If yes, it obtains the session object using the sessionID and performs corresponding operations. If not, a new session object is created and the sessionId is returned to the client in the response and stored as a cookie.
  • Security: Session security is greater than cookie security
  • Store content format: Cookies are stored as text by storing string types, while sessions are stored through the data structure of HashTable, which supports any object
  • Storage size: the cookie size cannot exceed 4Kb, and the session size is unlimited
  • Application scenarios
    1. Cookie: saves the last browsing information and browsing count of the user
    2. Session: The shopping cart information of the online mall and the special information for each user

webstorage

To overcome some of the limitations of having cookies, 1) provide a path to store session data outside of cookies and 2) provide a mechanism to store large amounts of data across sessions. Two apis are provided: localStorage and sessionStorage

  • Storage size: 5MB for storing data
  • Storage location: all in the client side, do not interact with the server side
  • Storage type: Only strings can be stored

The advantages of webstorage

  • Relatively large storage space, up to 5mb
  • Save network traffic, stored in the local can be directly obtained, and do not need to be like cookies, each time the request to be sent to the server.
  • Security: Compared with cookies, they are not sent to the server with HTTP headers, so they are relatively secure without worrying about interception

The difference between localStorage and sessionStorage is that localstorage is permanently stored unless it is cleared, while sessionStorage is only valid for the current session and is cleared once the browser or page is closed.

The difference between cookies and Webstorage

  • More storage space
  • Saves network traffic. Once data is saved locally, data requests to the server are avoided, reducing unnecessary data transfer between the browser and the server
  • Relatively safer
  • It has its own setItem, getItem, Clear and other encapsulated apis, while cookies need to be wrapped by developers themselves

Refer to the blog

Good articles

HTTP response status code

  • 301 indicates that the requested resource is permanently assigned to the new URL
  • 302 indicates that the requested resource has been assigned a new URL, but temporarily
  • 303 indicates that a GET request is required to obtain the direction
  • 304 indicates that the client sends a request for resources, but the requested resources and cache contents remain unchanged
  • 403 indicates that the server received the request but refused to execute it
  • 401 indicates that the request is not authorized. Consider whether the user login authentication information has expired
  • 500 The server is faulty
  • 204 Request Content The response was successful, but the response data is empty
  • 502 Error gateway
  • 503 Gateway timeout request. The problem may be front-end or back-end

Get and POST

A. the b. the C. the D. the

  • Parameter location: Get is stored in the URL query, post is stored in the body
  • Parameter size: Generally, get does not exceed 32 KB, and POST does not exceed 1 GB
  • Security: GET is less secure because it passes directly into the address bar
  • Cacheability: GET can cache its parameters, post cannot cache its parameters

Do you understand cyber attacks? How to solve

XSS: cross-site scripting attacks. An XSS attack is an attack that injects malicious client code into a website to gain access to users’ private data while using a browser. There are three types: reflection, storage, DOM – based.
  1. Reflective: Simply “reflects” the user’s input back to the browser, enticing the user to click on a malicious link or submit a form to inject a script into the target’s site
  2. Storage: The data entered by the user is stored on the server. When the browser requests the data, the script is returned from the server and executed.
  3. DOM – based: Attacks occur only on the client. This refers to the fact that client-side malicious scripts can modify the DOM, independent of server data.

Defense plan:

  1. If cookie is set to httpOnly, cookies cannot be obtained by JS scripts
  2. Verifies user input and filters special characters

(a)

CSRF attack: cross-site request forgery. The attacker steals the identity of the user and sends malicious requests in the name of the user (that is, using the login status of the user to launch attacks).
  1. Add the verification code on the login page for authentication
  2. The request is accompanied by validation information. The server sends a random token, carries the token with the request, and verifies whether it is valid.
  3. Refer: The HTTP request header has a refer field that can be used by the back end to intercept requests
3, SQL injection: through the SQL command inserted into the Web form submission or input domain name or page request query string, ultimately to deceive the server to execute malicious SQL commands.
  • The front-end can be done to filter the user’s input
4. Man in the middle attack: a man in the middle intercepts the request sent by the client to the server, and then communicates with the server disguised as the client. In this way, the content of the server can be intercepted and sent to the client.

This attack mode is through various technical means placing virtual attacker control of a computer in the network connection of the two communication between the host and the host is called “middlemen”, the “middleman” to establish a connection with the original computer and allows it to read or alteration of information, but two original computer is considered to be in mutual communication between them.

Common methods are as follows: DNS/ARP spoofing (sending DNS requests from customers to an attacker, who falsifies the DNS response and changes the correct IP address to another IP address, so as to obtain some important information entered by users on forged websites.

Refer to the link

Refer to the article

The browser’s same-origin policy and cookie scope

The same origin policy of the browser means that pages with the same protocol, domain name, and port number can communicate with each other.

The purpose is to ensure user information security and prevent malicious sites from stealing data.

The limits are as follows: Cookies, localStorage, and IndexDB cannot be read in non-same-origin scenarios. Dom not available

Solution: Use jSONP, CORS, or window.loaction.name + iframe to resolve cross-domain problems

Cookie: it is mainly some temporary data with low security requirements saved in the client through the browser, involving two important properties Domain, Path is used to indicate the scope of Cookie

  • Domian: indicates the domain name to which the cookie is added. The default domain name is the current domain name
  • Path: tells the browser the domain name to which the cookie is to be added

The scope of Cookie submitted by comprehensive browser: 1. Cookie under current domain name or parent domain name; 2. Cookies in the current path or parent path; If the two conditions are met, the submission will be successful

TCP’s three handshakes and four waves

A. the b. the C. the D. the

TCP three-way handshake process

  • The client sends a connection request packet with SYN=1 (indicating a connection request or a connection receiving request) and SEq = x (the initial sequence number) to the server. In this case, the client state is SYN-send and waiting for confirmation
  • After receiving the request packet, the server confirms the connection and sends ACK =1, SYN=1, ACK = X +1, and SEQ = Y to confirm the connection.
  • After receiving the confirmation, the client checks whether ACK is 1 and ACK is X +1. If yes, the client sets ACK=1 and ACK= Y +1, allocates resources for the TCP connection, and sends data packets to the server. The server confirms that the connection is established successfully.

Question: why do you have to shake hands three times? Is it ok to shake hands two times?

Because TCP is full-duplex communication, the three-way handshake ensures that both parties confirm the connection and negotiate the initial serial number. If there are only two handshakes, an infinite loop may occur. After the second handshake, the client does not know whether the server is ready or not, and thus ignores any data packets sent by the server. When the packet sent by the server does not receive a response, the client repeats the packet and becomes trapped in the loop.

The differences between TCP and UDP and their application scenarios

A. the b. the C. the D. the

TCP and UDP are transport layer protocols of TCP/IP.

TCP: reliable, byte stream oriented, connection-requiring transport-layer protocol with a total packet length of 20 bytes that supports point-to-point connections only.

UDP: a connection-oriented transport layer protocol that delivers as much data as possible. The packet header contains only 8 bytes and supports many-to-many, one-to-many, and many-to-one protocols.

When will the options request be used

A. the b. the C. the D. the

For complex cross-domain requests, the browser will send options pre-request before sending the actual request to determine whether the server supports complex cross-domain requests. If the response type is rejected, the real request will be aborted. Options carry the following parameters: access-Control-request-method, access-Control-request-headers

This action is triggered when:

  • The request type is not HEAD/GET/POST
  • The data types of the request header are content-Type: text/plain and multipart/form-data
  • Custom request headers

The history of HTTP and HTTPS

A. the b. the C. the D. the

HTTP is a stateless, request/reply, application-layer hypertext transfer protocol.

  • HTTP 0.9: Support short connection, request only support GET request, no request header description
  • HTTP 1.0: Added POST, DELETE, PUT, HEAD, response status code, introduced the concept of HTTP headers, with the ability to transmit other types of documents other than plain text HTML
  • http1.1
    1. Connections can be reused, saving the time of opening TCP connections for multiple times to load web document resources
    2. Add pipelining technology that allows a second request to be sent before the first reply has been fully sent, reducing communication latency
    3. Additional cache control mechanisms have been introduced
    4. Add the host header to provide the physical server processing speed so that different domain names can be configured on the same IP address of the server
  • http2.0
    1. Support for multiplexing, parallel requests can be processed within the same link, removing order and blocking constraints in HTTP1.x.
    2. Compress request header information, because request headers are similar across a series of requests, removing duplicates and transferring duplicate data costs
    3. Added the active server push function
    4. Data is transmitted in binary

Extension: HTTPS execution process

HTTPS is an ENCRYPTION protocol based on HTTP and combined with SSL. An HTTPS request actually includes two HTTP requests

  1. The client sends an HTTPS request to the server to connect to port 443
  2. After receiving the request, the server sends the public key to the client and keeps the private key for asymmetric encryption and decryption
  3. After receiving the certificate from the server, the client verifies the validity of the certificate. If the authentication succeeds, the client generates a random number, also called the key of the client, and performs asymmetric encryption with the public key of the server to convert the key of the client into ciphertext. If authentication fails, the HTTPS request fails
  4. The client initiates a second request and sends the encrypted ciphertext to the server.
  5. The server uses its own key to perform asymmetric decryption, obtains the client key, encrypts the data to be sent symmetrically with the client key, obtains the ciphertext, and sends it to the client.
  6. The client uses the client key and ciphertext to perform symmetric decryption and obtain the required data. Then, the second HTTPS HTTP request ends and the entire HTTPS transfer is complete.

Refer to the link

Reference Link 2

The difference between symmetric and asymmetric encryption

  • Symmetric encryption: the secret key used for encryption and encryption is the same, the algorithm is open, the calculation is small, and the encryption speed is fast
  • Asymmetric encryption: Requires a private key and a key. It is secure and slow

Application:

  1. Common symmetric encryption algorithms include DES, 3DES, Blowfish, IDEA, RC4, RC5, RC6, and AES
  2. Common asymmetric encryption algorithms include RSA, ECC (for mobile devices), Diffie-Hellman, El Gamal, AND DSA (for digital signature).
  3. The common summarization algorithms are MD2, MD4, MD5, HAVAL and SHA

Principles of DNS Resolution

A. the b. the C. the D. the

Enter the URL in the browser and check whether the local host file is mapped. If yes, the resolution is complete. If no, query the local DNS server. If there is a mapping in the local cache, the query ends. If there is no mapping, the next-level server initiates a query. The query can be performed in either of the following ways:

  • recursively

In recursive query, if the local DNS server does not query the corresponding mapped IP address, the DNS client queries the next-level server as the DNS client until the local DNS server finds the mapped IP address, and then returns to the next-level server

  • Iterative way

Iterative query means that if the local DNS server does not find the mapping IP address, the local DNS server queries the mapping IP address to the lower-level server

Principles of Ajax and FETCH

ajax:

  • Is an instance of XMLHttpRequest
  • The request succeeds only if the status is 200 or 304
  • The format is fragmented and prone to callback hell

fetch:

  • Basic promise implementation can also be combined with async/await
  • The fetch defaults to no cookie
  • All versions of IE do not support native FETCH
  • The server does not reject a request with a 400 or 500 status code, but only reject it when a network error causes the request to fail
// In the fetch post request method, Var data = new formData() var options = {method:'post', body:data, headers:{ 'Accept':'application/json' } } fetch(url,options).then(res=>{ console.log(res) }).catch((error)=>{ })Copy the code

Refer to the link

Simple and complex HTTP requests

A simple request

  • Request method
    1. GET
    2. POST
    3. HEAD
  • You cannot customize request header information, only these simple headers
    1. Accept
    2. Accept-Language
    3. Content-Language
    4. Content-type: Text /plain, multipart/form-data (data Type used for file upload), Application/X-www-form-urlencoded (most common form submit data Type for post)

Complex request

  • Anything that doesn’t fit a simple request is a complex request

When complex cross-domain requests are executed, a pre-request options is sent to test whether the server accepts the real request. If the response status is rejected, post and PUT requests are stopped.

The network layer

Network stratification refers to the sending or forwarding, packaging and unpacking of data, as well as the loading or unpacking of control information to be completed by different hardware and software modules.

The current common network layer is 5 layers, from bottom to top:

  • Physical layer: This layer is responsible for the transport of bitstreams between nodes, known as physical transport, colloquially referred to as the physical means of connecting computers.
  • Data link layer: This layer controls communication between the network layer and the physical layer. The main function is to achieve reliable transmission of data on unreliable physical lines
  • What the network layer does is determine the best path from node A in one network to node B in the other network by taking into account priority occurrence, network congestion, quality of service, and the cost of alternative routes.
  • The transport layer is where applications on two hosts provide end-to-end communication.
  • Application layer: Data transmitted by the receiving and transmission layer is parsed in a predefined format

Refer to the article

Cookies prohibit clients from obtaining HttpOnly

If the httpOnly attribute is set, the JS script cannot read the cookie information, effectively preventing XSS attacks and stealing the cookie content

// Set response.setHeader(' set-cookie ','HttpOnly; Domain = domainvalue; path = pathname; cookiename = httpOnlyTest')Copy the code

How axios works

  1. Features:
    1. Promise is a PROMISE based HTTP library that supports all of promise’s apis
    2. Interception of request and response is supported and request data and response data formats can be transformed
    3. The client supports XSRF defense

Refer to the blog