Web Proxy Server

chohk10·2023년 4월 25일
0

CSAPP Labs

목록 보기
4/4
post-thumbnail

CS:APP 원서를 기반으로 작성한 내용

Networks

Aside) What Does Network Adapter Mean?

The Global IP Internet

Internet Connections

TCP(Transmission Control Protocol)

  • A connection oriented protocol
  • 호스트가 서로 연결되고 (두개의 호스트간 연결이 established), arbitrarily long streams of bytes를 주고받으며 통신할 때 각각의 endpoint를 socket이라 부른다.
  • socket is ip address + port(16bit 숫자)

Port

  • Port를 사용하는 이유
    • 내가 접근하는 머신이 (호스트가) ssh 연결, ftp 연결, mail server 호스팅, web server 호스팅 등 다양한 서비스를 제공할 수 있는데, 이러한 것들을 구분해서 접근하기 위한 것
    • client도 마찬가지로 여러가지 일을 하고 있을 수 있는데, 다양한 프로그램(프로세스)을 구분하기 위해서 포트를 사용함
  • Ephemeral port : 주로 client에서 사용됨, dynamically assigned by client kernel, 해당 연결을 유지하는 동안에만 임시로 주어지는 것
  • Well-known port : 서버 측에서 다양한 서비스를 구현하고 있을 수 있는데, 그 중에서 원하는 서비스를 특정할 수 있도록, standard list가 존재함
    • 많이 사용되는 서비스들은 영구적으로 well-known ports에 할당이 되어있음
    • well-known service names :
      • echo server : 7/echo
      • ssh servers : 22/ssh
      • email server : 25/smtp
      • Web servers : 80/http
      • 리눅스 기기의 /etc/services 위치에 포트 매핑에 대한 정보가 담겨있는 파일이 있음
  • summary : 서버에 요청이 들어오면 커널이 어떤 프로세스를 깨울 것이며 들어오는 데이터를 어디에 활용할지 결정해야 함 -> 이때 특정 프로세스를 특정 포트와 연결을 해둠으로서 매핑이 가능하게 함

Sockets Interface

(sockets programming)
Set of system-level functions (interface) used in conjunction with Unix I/O to build network applications.

  • to a kernel socket is an endpoint of connection/communication
  • 응용 프로그램의 입장에서는 읽고 쓸 수 있는 file descriptor로 인식됨
    ==> socket interface가 제공하는 mental model 개념적인 모델인 것
    ==> 실제로는 읽고 쓸때마다 그냥 disk와는 다르게 온갖 네트워크 동작이 발생하는거고 아주 다르지만, 프로그래머 입장에서는 비슷하게 인식됨
    ==> 일반적인 file I/O와는 다르게 socket I/O는 application이 socket descriptor를 "open" 하는 것에서 차이가 있다고 함 (?? find out more about this later..)

Socket Address Structures

struct sockaddr

  • 처음 2개의 바이트가 어떤 타입의 소켓인지를 정의
  • 뒤로는 familty specific address
    Internel-specific socket address
  • ipv4, port, ip addr, zero padding

Sockets Interface

  • socket
    • socket() : socket initiating
      • AF_INET : IPV4를 사용
      • SOCK_STRAM : TCP connection
      • return int id for socket descriptor sockfd
      • file descriptors are identified and referred to with integer IDs
      • kernel assumes that the sedcriptor created is an active socket for the client end (so, liten fucntion is needed for the server side)
  • client
    • connect() : attempt to establish a connection with server
      • is blocked until connection is successful or fails
      • returns client descriptor clientfd
      • resulting connection is characterized by : (x:y, ip:port) (that of the client)
      • use getaddrinfo function for filling arguments such as socket length(sockelen_t addrlen)
  • server
    • bind() : designate which service this server is histing through the port number
      • ask the kernel to associate the server's socket address with the socket descriptor
      • SA (short for socket_addr)
      • socket length (use getaddrinfo)
    • listen() : tell the kernel to convert the socket to a listening socket
      • telling the kernel that this will be the server-side
      • backlog : number of requests to queue before starting to refuse requests
      • returns listenfd? : endpoint for client connection requests lasting for the lifetime of the server
      • distinguished from connected descriptor for concurrency
    • 서버의 경우 바로 connect를 할 수 있는 client와 다르게 bind와 listen 모두 해야지 listening socket을 형성할 수 있음
    • accept() : await for connection request from client
      • returns another file descriptor connected descriptor connfd : endpoint of the single established connection, created every time a connection request is accepted
      • to handle multiple clients at the same time - same port but different file descriptors
    • Serial Server : manage one request at a time
    • Multi-threading : manage other requests while handling a client
    • 지금 배우는건 하나의 client connection을 close 해야지 다음거를 accept할 수 있음

Aside) File descriptor

In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a process-unique identifier (handle) for a file or other input/output resource, such as a pipe or network socket.

File descriptors typically have non-negative integer values, with negative values being reserved to indicate "no value" or error conditions.

File descriptors are a part of the POSIX API. Each Unix process (except perhaps daemons) should have three standard POSIX file descriptors, corresponding to the three standard streams:

Integer value / Name / <unistd.h> symbolic constant / <stdio.h> file stream

  • 0 / Standard input / STDIN_FILENO / stdin
  • 1 / Standard output / STDOUT_FILENO / stdout
  • 2 / Standard error / STDERR_FILENO / stderr

출처 : File descriptor - Wikipedia

파일 디스크립터(File Descriptor)란 리눅스 혹은 유닉스 계열의 시스템에서 프로세스(process)가 파일(file)을 다룰 때 사용하는 개념으로, 프로세스에서 특정 파일에 접근할 때 사용하는 추상적인 값이다. 파일 디스크럽터는 일반적으로 0이 아닌 정수값을 갖는다. (위의 영문 글의 내용에 따라서 음수가 아닌 정수값을 갖는다는게 더 정확한 표현이 아닐까 생각한다.)

흔히 유닉스 시스템에서 모든 것을 파일이라고 한다. 일반적인 정규파일부터 디렉토리, 소켓, 파이프, 블록 디바이스, 케릭터 디바이스 등 모든 객체들을 파일로 관리한다. 유닉스 시스템에서 프로세스가 이 파일들을 접근할 때 파일 디스크립터라는 개념일 이용한다. 프로세스가 실행 중에 파일을 Open하면 커널은 해당 프로세스의 파일 디스크립터 숫자 중 사용하지 않는 가장 작은 값을 할당해준다. 그 다음 프로세스가 열려있는 파일에 시스템 콜을 이용해서 접근할 때, 파일 디스크립터(FD)값을 이용해서 파일을 지칭할 수 있다.
출처 : 파일 디스크립터란 무엇인가?

Host and Service Conversion

getaddrinfo

  • 다양한 잡다하고 이것저것 다 처리하려고 하지만, 이번 코스에서는 필요한 두가지 함수만 볼 예정
  • multi-threading 에 더 적합한 구조를 가지고 있다는 것이 중요함
  • linked list의 시작부분으로 return 값을 줌
  • 개발자는 linked list에서 연결되어있는 canonical name, 여러개의 ip address를 시도해볼 수 있음

addrinfo struct

  • socket()의 매개변수로 사용될 값들을 받을 수 있음

getnameinfo

  • ip address를 가지고 domain name를 가져올 수 있음

Freeaddrinfo

  • free up the memory when done

IPv4, IPv6

  • ./hostinfo www.facebook.com
  • IPv4 : 31.13.74.36
  • IPv6 : 2a03:2880:f00b:1e:face:b00c::25de (페이스북에서 귀엽게 IPv6 주소 중간에 'face'를 집어넣었음 ㅎㅎ)

DNS 서버는 전세계에 서버들이 있고 큰 회사들이 관리하며 제공하는 서버도 계속 돌아가면서 다르게 제공하면서 부하를 감당한다고 함

Web Servers

HTTP (HTTP Protocol)

  • TCP/IP based communication protocol used to deliver data on the World Wide Web

Features of HTTP

  • Connectionless : 클라이언트가 request를 보내면 response를 기다리고, 서버는 request의 내용을 처리해서 response를 돌려주며, 클라이언트는 response를 받으면 해당 연결을 해제한다. 따라서 클라이언트와 서버는 request 와 response를 할 때에만 서로를 알 수 있으며, 새로운 request에 대해서 서로는 새롭게 인식된다.
    • 한번의 통신이 끝나면 서로를 모르는 상태로, 연결이 끊어진 상태로 유지된다.
  • Media Independent : 클라이언트와 서버는 어떤 데이터 타입이든 주고받을 수 있다. (서로 해당 데이터를 어떻게 처리할지 알고만 있다면) 따라서, 서버와 클라이언트는 MIME-type을 사용해서 어떤 content type을 사용하는지 명시해주어야 한다.
  • Stateless : 클라이언트와 서버는 현재 request 동안에는 서로를 인지하고 있지만, 그 이후에는 서로를 잊어버린다. 이 특성으로 인해 클라이언트와 서버 모두 서로다른 request 사이사이에 서로에 대한 정보를 가지고 있지 못한다

Stateless?
Idea that each request sent from a client to a server contains all the necessary information for the server to fulfill that request, without the need for the server to store any information about previous requests from the same client.

This means that the server doesn't maintain any session data or context between requests from the same client. Instead, each request is handled independently, and the server processes the request based only on the information contained in that particular request. Once the server sends the response to the client, it no longer has any memory of that request.

The stateless nature of HTTP is what makes it a scalable and efficient protocol, as it allows for multiple requests to be processed simultaneously without the server having to maintain any additional information about previous requests. However, it also means that certain types of interactions, such as maintaining user sessions or tracking user activity, require additional mechanisms to be implemented by application developers.

MIME-type

HTTP Transactions

Connection - Request - Response - Close
An HTTP Transaction - CMU


깊게 공부하자면 정말 많은 내용들은 공부해야하는 것 같다. 우선 코치님이 조언하신 대로 너무 깊거나 너무 넓게 공부하지 말고 현재 필요한 정도로만 공부하고 넘어가야할 것 같다.
우선은 이번주 과제를 완수해야하니 Network에 대해서는 다음에 기회가 될 때 더 파보는걸로 하고 일단 넘어가자..! ㅠ

Reading List :
https://www.thetechplatform.com/post/what-is-http-protocol-architecture-and-components-of-http


Serving Dynamic Content

CGI Protocol

CGI is an application-level protocol used by web servers to execute external programs or scripts and generate dynamic content in response to a client's HTTP request.
(It is not directly related to any of the layers in the OSI model, although it is often used in conjunction with application-level protocols such as HTTP, which operates at the application layer.)

(이부분은 책을 읽어도 하나도 모르겠다...)
=> 그러니까, HTTP request에 대해서 response를 보내줄 때, external 프로그램/스크립트 등을 실행해서 dynamic하게 content를 생성해서 보내주는 것에 대한 protocol(규약)
request를 보내는 방법에 대해서도 rule이 있을거고, 정해진 rule에 맞춰 요청이 잘 들어왔다면 그거에 맞춰서 서버는 처리를 할거고, 그 response를 보내는 것에도 (아마도) rule이 있겠네!


HTTP도 프로토콜이고 지금 막 책에서 읽기 시작한 CGI도 프로토콜이고.. TCP/IP도 프로토콜이고... 이 프로토콜(통신 규약)이라는게 왜이렇게 많고 서로 뭐가 다르고 각각의 카테고리는 뭐길래?
=> Now I know they are all "protocols" of different kinds but note that CGI is not part of the OSI model.

7 Layers of OSI Model

OSI Model : Open Systems Interconnection reference model

The OSI model divides the complex task of computer-to-computer communications, traditionally called internetworking, into a series of stages known as layers.

Layers in the OSI model are ordered from the lowest layer to highest.

Physical Layer
The lowest layer of the OSI Model is concerned with electrically or optically transmitting raw unstructured data bits across the network from the physical layer of the sending device to the physical layer of the receiving device.

  • Fiber, Wireless, Hubs, etc.

Data Link Layer
At the data link layer, directly connected nodes are used to perform node-to-node data transfer where data is packaged into frames. The data link layer also corrects errors that may have occurred at the physical layer.

The data link layer encompasses two sub-layers of its own. The first, media access control (MAC), provides flow control and multiplexing for device transmissions over a network. The second, the logical link control (LLC), provides flow and error control over the physical medium as well as identifies line protocols.

  • Ethernet, Switch, Bridge, etc.

Network Layer
The network layer is responsible for receiving frames from the data link layer, and delivering them to their intended destinations among based on the addresses contained inside the frame. The network layer finds the destination by using logical addresses, such as IP (internet protocol). At this layer, routers are a crucial component used to quite literally route information where it needs to go between networks.

  • IP, ICMP, etc.

Transport Layer
The transport layer manages the delivery and error checking of data packets. It regulates the size, sequencing, and ultimately the transfer of data between systems and hosts. One of the most common examples of the transport layer is TCP or the Transmission Control Protocol.

  • TCP, UDP

Session Layer
The session layer controls the conversations between different computers. A session or connection between machines is set up, managed, and termined at layer 5. Session layer services also include authentication and reconnections.

  • API's, Sockets, WinSock

Presentation Layer
The presentation layer formats or translates data for the application layer based on the syntax or semantics that the application accepts. Because of this, it at times also called the syntax layer. This layer can also handle the encryption and decryption required by the application layer.

  • SSL, SSH, IMAP, FTP, MPEG, JPEG, etc.

Application Layer
At this layer, both the end user and the application layer interact directly with the software application. This layer sees network services provided to end-user applications such as a web browser or Office 365. The application layer identifies communication partners, resource availability, and synchronizes communication.

  • HTTP, FTP, SSH, DNS, etc.

Reading List


(정글 DOCS)

핵심 내용

  • TCP/IP : network layer, TCP 위의 HTTP, TCP 옆의 UDP
  • Sockets : the low level endpoint used for processing information across a network
  • Server:
    • Create a socket with the socket()
    • Bind the socket to an address using the bind()
    • Listen for connections with the listen()
    • Accept a connection with the accept()
    • To send and receive data, use the write() and read()
  • Client:
    • Create a socket with the socket()
    • Connect the socket to the address of the server using the connect()
    • To send and receive data, use the write() and read()

강의 요약

  1. 서버와 클라이언트의 통신 (CS:APP 그림 11.12)
  • 서버
    • socket() : 연결 통로 준비
    • bind() : 특정IP와 연결
    • listen() : 연결 후 요청을 기다리기
    • accept() : read/write 또는 receive/send 메소드를 짝으로 사용하여 요청/응답 처리. 단, listen()에서의 스레드와 다른 스레드를 만들어 진행한다.
      • 스레드 분리 이유: 서버는 여러 요청을 받아야 하기에, listen() 스레드는(母) 놔두고 계속 기다리게 하고, accept() 스레드는 (子) 요청을 처리하도록 만들어 둠
      • 단, 우리 과제에서는 멀티프로세싱까지 다루지는 않음
  • 클라이언트
    • socket() : 연결 통로 준비
    • connect() : 연결. 끝. 스레드 분리하지 않음
  1. HTTP / TCP / IP 통신 등
  • IP 위에 → TCP 위에 → HTTP 가 있음. 모두 P. 즉 protocol. 규약=약속
    • Physical 레이어에 가까울 수록 밑에 있다고 표현
  • IP단으로 갈 수록 하드웨어 환경(와이파이, LTE, 랜선, …) 레이어를 나눠서 설계하는 이유는, 각 단계 별 환경이 변할 수 있고, 다양한 이종의 장치들이 나올 수 있기 때문
    • 한번에 설계하면 다 바꿔야 하니까, 레이어를 나눠서 약속을 정해둔 것
  • TCP는 패킷 받는 게 보장됨 vs UDP는 패킷 받는 게 보장 안됨. 그냥 쏘는 것
    • 요새 동영상 스트리밍 같은 곳에 UDP 많이 씀. 중간에 화질 저하돼도 보는 데 문제 없으니까
    • 참고로 11장은 TCP 소켓으로 만들어지게 되어있음. 2kb를 주면 2kb를 받는 구조.
  • HTTP가 처음 나왔을 때 뜬 이유: 사람이 읽을 수 있어서

웹서버는 어떤 기능들의 모음일까요?

(정글 docs 가장 마지막에 있던 질문인데.. 아직 이거에 대해서 대답할 수 있을 정도로 개념이 잡히지 않은 것 같다.. ㅠㅠ)

0개의 댓글