Chapter 2 Application Layer Computer Networking A Top

  • Slides: 147
Download presentation
Chapter 2 Application Layer Computer Networking: A Top Down Approach, 5 th edition. Jim

Chapter 2 Application Layer Computer Networking: A Top Down Approach, 5 th edition. Jim Kurose, Keith Ross Addison-Wesley, April 2009. 2: Application Layer 1

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2 Web and HTTP r 2. 3 FTP r 2. 4 Electronic Mail v r 2. 6 P 2 P applications r 2. 7 Socket programming with TCP r 2. 8 Socket programming with UDP SMTP, POP 3, IMAP r 2. 5 DNS 2: Application Layer 2

Chapter 2: Application Layer Our goals: r conceptual, implementation aspects of network application protocols

Chapter 2: Application Layer Our goals: r conceptual, implementation aspects of network application protocols v transport-layer service models v client-server paradigm v peer-to-peer paradigm r learn about protocols by examining popular application-level protocols v v HTTP FTP SMTP / POP 3 / IMAP DNS r programming network applications v socket API 2: Application Layer 3

Some network apps r e-mail r voice over IP r web r real-time video

Some network apps r e-mail r voice over IP r web r real-time video r remote login conferencing r grid computing r P 2 P file sharing r r multi-user network r r instant messaging games r streaming stored video clips r 2: Application Layer 4

Creating a network app write programs that v v v run on (different) end

Creating a network app write programs that v v v run on (different) end systems communicate over network e. g. , web server software communicates with browser software No need to write software for network-core devices v v Network-core devices do not run user applications on end systems allows for rapid app development, propagation application transport network data link physical 2: Application Layer 5

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2 Web and HTTP r 2. 3 FTP r 2. 4 Electronic Mail v SMTP, POP 3, IMAP r 2. 5 DNS r 2. 6 P 2 P applications r 2. 7 Socket programming with TCP r 2. 8 Socket programming with UDP r 2. 9 Building a Web server 2: Application Layer 6

Application architectures r Client-server r Peer-to-peer (P 2 P) r Hybrid of client-server and

Application architectures r Client-server r Peer-to-peer (P 2 P) r Hybrid of client-server and P 2 P 2: Application Layer 7

Client-server architecture server: v always-on host v permanent IP address v server farms for

Client-server architecture server: v always-on host v permanent IP address v server farms for scaling clients: client/server v v communicate with server may be intermittently connected may have dynamic IP addresses do not communicate directly with each other 2: Application Layer 8

Pure P 2 P architecture r no always-on server r arbitrary end systems directly

Pure P 2 P architecture r no always-on server r arbitrary end systems directly communicate peer-peer r peers are intermittently connected and change IP addresses Highly scalable but difficult to manage 2: Application Layer 9

Hybrid of client-server and P 2 P Skype v voice-over-IP P 2 P application

Hybrid of client-server and P 2 P Skype v voice-over-IP P 2 P application v centralized server: finding address of remote party: v client-client connection: direct (not through server) Instant messaging v chatting between two users is P 2 P v centralized service: client presence detection/location • user registers its IP address with central server when it comes online • user contacts central server to find IP addresses of buddies 2: Application Layer 10

Processes communicating Process: program running within a host. r within same host, two processes

Processes communicating Process: program running within a host. r within same host, two processes communicate using inter-process communication (defined by OS). r processes in different hosts communicate by exchanging messages Client process: process that initiates communication Server process: process that waits to be contacted r Note: applications with P 2 P architectures have client processes & server processes 2: Application Layer 11

Sockets r process sends/receives messages to/from its socket r socket analogous to door v

Sockets r process sends/receives messages to/from its socket r socket analogous to door v v sending process shoves message out door sending process relies on transport infrastructure on other side of door which brings message to socket at receiving process host or server process controlled by app developer process socket TCP with buffers, variables Internet TCP with buffers, variables controlled by OS r API: (1) choice of transport protocol; (2) ability to fix a few parameters (lots more on this later) 2: Application Layer 12

Addressing processes r to receive messages, process must have identifier r host device has

Addressing processes r to receive messages, process must have identifier r host device has unique 32 -bit IP address r Q: does IP address of host suffice for identifying the process? 2: Application Layer 13

Addressing processes r to receive messages, process must have identifier r host device has

Addressing processes r to receive messages, process must have identifier r host device has unique 32 -bit IP address r Q: does IP address of host on which process runs suffice for identifying the process? v A: No, many processes can be running on same host r identifier includes both IP address and port numbers associated with process on host. r Example port numbers: v v HTTP server: 80 Mail server: 25 r to send HTTP message to gaia. cs. umass. edu web server: v v IP address: 128. 119. 245. 12 Port number: 80 r more shortly… 2: Application Layer 14

App-layer protocol defines r Types of messages exchanged, v e. g. , request, response

App-layer protocol defines r Types of messages exchanged, v e. g. , request, response r Message syntax: v what fields in messages & how fields are delineated r Message semantics v meaning of information in fields Public-domain protocols: r defined in RFCs r allows for interoperability r e. g. , HTTP, SMTP Proprietary protocols: r e. g. , Skype r Rules for when and how processes send & respond to messages 2: Application Layer 15

What transport service does an app need? Data loss r some apps (e. g.

What transport service does an app need? Data loss r some apps (e. g. , audio) can tolerate some loss r other apps (e. g. , file transfer, telnet) require 100% reliable data transfer Timing r some apps (e. g. , Internet telephony, interactive games) require low delay to be “effective” Throughput r some apps (e. g. , multimedia) require minimum amount of throughput to be “effective” r other apps (“elastic apps”) make use of whatever throughput they get Security r Encryption, data integrity, … 2: Application Layer 16

Transport service requirements of common apps Data loss Throughput Time Sensitive file transfer e-mail

Transport service requirements of common apps Data loss Throughput Time Sensitive file transfer e-mail Web documents real-time audio/video no loss-tolerant no no no yes, 100’s msec stored audio/video interactive games instant messaging loss-tolerant no loss elastic audio: 5 kbps-1 Mbps video: 10 kbps-5 Mbps same as above few kbps up elastic Application yes, few secs yes, 100’s msec yes and no 2: Application Layer 17

Internet transport protocols services TCP service: r connection-oriented: setup r r required between client

Internet transport protocols services TCP service: r connection-oriented: setup r r required between client and server processes reliable transport between sending and receiving process flow control: sender won’t overwhelm receiver congestion control: throttle sender when network overloaded does not provide: timing, minimum throughput guarantees, security UDP service: r unreliable data transfer between sending and receiving process r does not provide: connection setup, reliability, flow control, congestion control, timing, throughput guarantee, or security Q: why bother? Why is there a UDP? 2: Application Layer 18

Internet apps: application, transport protocols Application e-mail remote terminal access Web file transfer streaming

Internet apps: application, transport protocols Application e-mail remote terminal access Web file transfer streaming multimedia Internet telephony Application layer protocol Underlying transport protocol SMTP [RFC 2821] Telnet [RFC 854] HTTP [RFC 2616] FTP [RFC 959] HTTP (eg Youtube), RTP [RFC 1889] SIP, RTP, proprietary (e. g. , Skype) TCP TCP TCP or UDP typically UDP 2: Application Layer 19

Overview of Internet Services r What services can we offer on the Internet? v

Overview of Internet Services r What services can we offer on the Internet? v In 1971, RFC 172 unveiled the File Transfer Protocol (FTP) which allowed users to list files on remote servers and transfer files back and forth between the local host and the remote server. v In 1972, the first electronic mail (e-mail) software (SNDMSG and READMAIL) was developed, with its protocol later being standardized as Simple Mail Transfer Protocol (SMTP) in RFC 821 in 1982. SMTP allows e-mails to be sent between computers, and gradually becomes the most popular network application. v The first Telnet specification, RFC 318, was published in the same year, which allows users to log onto remote server machines as if they were sitting in front of those computers. 2: Application Layer 20

Overview of Internet Services r What services can we offer on the Internet? v

Overview of Internet Services r What services can we offer on the Internet? v In 1979, USENET, a consortium of UNIX companies and users, was established. USENET users formed thousands of newsgroups that operate on bulletin-board-like systems where users can read and post messages. The messages transferring between news servers were later standardized as Network News Transfer Protocol (NNTP) in RFC 977 in 1986. In the 1980 s, different from the above systems which are typically accessible only to authorized users, many of the new Internet services were open to virtually anyone having appropriate client software. v Archie is the first Internet search engine which allows users to search in the database of selected anonymous FTP sites for files. 2: Application Layer 21 v

Overview of Internet Services r What services can we offer on the Internet? Gopher,

Overview of Internet Services r What services can we offer on the Internet? Gopher, standardized in RFC 1436 in 1993, provides a menu-driven interface to search the Internet. v Domain Name System (DNS), specified in RFC 1035 in 1987, solves the problems of host addressing and naming by abstracting a host’s IP address as an understandable host name. v The World Wide Web (WWW), originated in 1989 at the European Laboratory for Particle Physics (CERN) and later specified as Hypertext Transfer Protocol (HTTP) in RFC 1945 in 1996, allows access to documents in the format of Hypertext Makeup Language (HTML) that integrates text, graphics, sounds, video and animations. 2: Application Layer 22 v

Overview of Internet Services r What services can we offer on the Internet? v

Overview of Internet Services r What services can we offer on the Internet? v P 2 P is considered the future of message and data exchange because it allows users exchange files with peers without going through centralized servers. Bit. Torrent (BT) is an example of P 2 P applications. Though IETF does not have protocols standardized for P 2 P, JXTA (Juxtapose), a P 2 P protocol specification begun by Sun Microsystems from 2001, aims to improve the interoperability of P 2 P applications. 2: Application Layer 23

Classification of Servers r Internet servers can be classified from two perspectives. r One

Classification of Servers r Internet servers can be classified from two perspectives. r One is how a server handles requests, either concurrently or iteratively. r The other way of classification depends on the underlying transport protocol. A connection-oriented server can be implemented with TCP while a connectionless server implemented with UDP. The combination of these perspectives yields four types of Internet servers. 2: Application Layer 24

Concurrent vs. Iterative Server r A concurrent server processes multiple clients at a time

Concurrent vs. Iterative Server r A concurrent server processes multiple clients at a time with concurrency. v v When the server accepts a client, it creates a child process or a thread. Each child process is an instance of the server program, and it inherits the socket descriptors and other variables from the parent process. The child process serves the client, while the parent process is free to accept new clients. Since the parent process simply handles new client arrivals, it would not be blocked by heavy workload from clients. Similarly, since each client is handled by a child process and all processes have chances to be scheduled to run by the processor. r 2: Application Layer 25

Concurrent vs. Iterative Server r An iterative server processes only one client at a

Concurrent vs. Iterative Server r An iterative server processes only one client at a time. v When multiple clients arrive, instead of forking any child processes, it queues clients and handles them in a sequential order. v If too many clients are present or some clients have requests with long service times, iterative processing may cause blocking which prolongs the response time to clients. v An iterative server is only suitable in the scenarios where clients have few requests with short service times. 2: Application Layer 26

Connection-oriented Server vs. Connectionless Server r First, for each packet sent, a connection-oriented server

Connection-oriented Server vs. Connectionless Server r First, for each packet sent, a connection-oriented server has 20 bytes of TCP header overhead, while a connectionless server has only 8 bytes of UDP header overhead. r Second, a connection-oriented server must establish a connection with the client before sending data, and must terminate the connection afterward. The connectionless server, however, simply transmits the data to the client without a connection setup. Because a connectionless server does not maintain any connection state, it can dynamically support more short -lived clients. r 2: Application Layer 27

Connection-oriented Server vs. Connectionless Server r Finally, when one or more links between the

Connection-oriented Server vs. Connectionless Server r Finally, when one or more links between the client and the server become congested, the connection-oriented server throttles the client by TCP’s congestion control. On the other hand, the connectionless client and server have an unregulated data sending rate, which is constrained only by the application itself or the bandwidth limit of the access links. r Thus, excessive loss due to persistent congestion could happen to the connectionless Internet service, and it costs the client or server extra efforts to retransmit the lost data if needed. 2: Application Layer 28

Chapter 2: Application layer r 2. 1 Principles of network applications v v app

Chapter 2: Application layer r 2. 1 Principles of network applications v v app architectures app requirements r 2. 2 Web and HTTP r 2. 4 Electronic Mail v SMTP, POP 3, IMAP r 2. 6 P 2 P applications r 2. 7 Socket programming with TCP r 2. 8 Socket programming with UDP r 2. 5 DNS 2: Application Layer 29

Web and HTTP First some jargon r Web page consists of objects r Object

Web and HTTP First some jargon r Web page consists of objects r Object can be HTML file, JPEG image, Java applet, audio file, … r Web page consists of base HTML-file which includes several referenced objects r Each object is addressable by a URL r Example URL: www. someschool. edu/some. Dept/pic. gif host name path name 2: Application Layer 30

Web and HTTP r By using a Web browser (IE, Fire. Fox, Chrome), users

Web and HTTP r By using a Web browser (IE, Fire. Fox, Chrome), users can access any online Web pages by an underlying procedure. 1. 2. 3. The server name in the URL is resolved into an IP address through DNS. The browser connects, by TCP 3 -way handshake, to the Web server listening on a TCP port, usually port 80. The browser issues a HTTP request to the Web server. 2: Application Layer 31

Uniform Resource Locator (URL) r A URL is a compact string representation of a

Uniform Resource Locator (URL) r A URL is a compact string representation of a resource’s location on the Internet. URLs make it possible to direct users to a variety of information through a number of different Internet protocols. The common syntax of the URL is as: <service>//<user>: <password>@<host>: <port>/<url-path> where some or all of “<user>: <password>@”, “: <password>”, “: <port>”, and “/<url-path>” might be omitted. Service ftp http gopher mailto news nntp telnet wais file prospero Description File Transfer protocol Hypertext Transfer Protocol The Gopher protocol Electronic mail address USENET news using NNTP access Reference to interactive sessions Wide Area Information Servers Host-specific file names Prospero Directory Service 2: Application Layer 32

Uniform Resource Locator (URL) r After the specific scheme comes the data starting with

Uniform Resource Locator (URL) r After the specific scheme comes the data starting with r r a double slash “//”. The <user> and <password> are optional; if present, the user name and password are separated by a colon “: ” and followed by an at-sign “@”. The <host> indicates the domain name or IP address of a network host. The <port>, separated from the host by a colon, is the host’s port number to connect to. The <url-path> specifies the details of how the specified resource can be addressed. Note that the slash “/” between the host (or port) and the url-path is not part of the url-path. 2: Application Layer 33

Uniform Resource Locator (URL) r Some URL examples: v http: //www. cs. nctu. edu.

Uniform Resource Locator (URL) r Some URL examples: v http: //www. cs. nctu. edu. tw/chinese/ccg/title. Main. gif v https: //mail. cs. nctu. edu. tw/ v ftp: //john: secret@ftp. cs. nctu. edu. tw/projects/book. txt v telnet: //mail. cs. nctu. edu. tw: 110/ 2: Application Layer 34

HTTP overview HTTP: hypertext transfer protocol r Web’s application layer protocol r client/server model

HTTP overview HTTP: hypertext transfer protocol r Web’s application layer protocol r client/server model v client: browser that requests, receives, “displays” Web objects v server: Web server sends objects in response to requests HT TP req ues PC running HT t TP res Explorer pon se st ue q e r P nse Server T o p running HT es r P T Apache Web HT server Mac running Navigator 2: Application Layer 35

HTTP overview (continued) Uses TCP: r client initiates TCP connection (creates socket) to server,

HTTP overview (continued) Uses TCP: r client initiates TCP connection (creates socket) to server, port 80 r server accepts TCP connection from client r HTTP messages (applicationlayer protocol messages) exchanged between browser (HTTP client) and Web server (HTTP server) r TCP connection closed HTTP is “stateless” r server maintains no information about past client requests aside Protocols that maintain “state” are complex! r past history (state) must be maintained r if server/client crashes, their views of “state” may be inconsistent, must be reconciled 2: Application Layer 36

HTTP connections Nonpersistent HTTP r At most one object is sent over a TCP

HTTP connections Nonpersistent HTTP r At most one object is sent over a TCP connection. Persistent HTTP r Multiple objects can be sent over single TCP connection between client and server. 2: Application Layer 37

Nonpersistent HTTP (contains text, Suppose user enters URL references to 10 www. some. School.

Nonpersistent HTTP (contains text, Suppose user enters URL references to 10 www. some. School. edu/some. Department/home. index jpeg images) 1 a. HTTP client initiates TCP connection to HTTP server (process) at www. some. School. edu on port 80 2. HTTP client sends HTTP request message (containing URL) into TCP connection socket. Message indicates that client wants object some. Department/home. index 1 b. HTTP server at host www. some. School. edu waiting for TCP connection at port 80. “accepts” connection, notifying client 3. HTTP server receives request message, forms response message containing requested object, and sends message into its socket time 2: Application Layer 38

Nonpersistent HTTP (cont. ) 4. HTTP server closes TCP 5. HTTP client receives response

Nonpersistent HTTP (cont. ) 4. HTTP server closes TCP 5. HTTP client receives response connection. message containing html file, displays html. Parsing html file, finds 10 referenced jpeg objects time 6. Steps 1 -5 repeated for each of 10 jpeg objects 2: Application Layer 39

Non-Persistent HTTP: Response time Definition of RTT: time for a small packet to travel

Non-Persistent HTTP: Response time Definition of RTT: time for a small packet to travel from client to server and back. Response time: r one RTT to initiate TCP connection r one RTT for HTTP request and first few bytes of HTTP response to return r file transmission time total = 2 RTT+transmit time initiate TCP connection RTT request file RTT file received time to transmit file time 2: Application Layer 40

Persistent HTTP Nonpersistent HTTP issues: r requires 2 RTTs per object r OS overhead

Persistent HTTP Nonpersistent HTTP issues: r requires 2 RTTs per object r OS overhead for each TCP connection r browsers often open parallel TCP connections to fetch referenced objects Persistent HTTP r server leaves connection open after sending response r subsequent HTTP messages between same client/server sent over open connection r client sends requests as soon as it encounters a referenced object r as little as one RTT for all the referenced objects 2: Application Layer 41

HTTP request message r two types of HTTP messages: request, response. r ASCII (human-readable

HTTP request message r two types of HTTP messages: request, response. r ASCII (human-readable format) r HTTP request message consists of: 1. The request line, which includes the method to be applied to the resource, the identifier of the resource, and the protocol version in use; 2. the header, which defines various features of the data that is requested or being provided; 3. an empty line, which is used to separate the header from the message body; 4. an optional message body. 2: Application Layer 42

HTTP request message: general format 2: Application Layer 43

HTTP request message: general format 2: Application Layer 43

HTTP request message r HTTP request message: request line (GET, POST, HEAD commands) GET

HTTP request message r HTTP request message: request line (GET, POST, HEAD commands) GET /somedir/page. html HTTP/1. 1 Host: www. someschool. edu User-agent: Mozilla/4. 0 header Connection: close lines Accept-language: fr Carriage return, line feed indicates end of message (extra carriage return, line feed) 2: Application Layer 44

HTTP request message: Method Request Method Description CONNECT Dynamically switch the request connection to

HTTP request message: Method Request Method Description CONNECT Dynamically switch the request connection to a tunnel, e. g. SSL tunneling. DELETE Delete the specified resource at the server, if possible. GET Request a representation of the specified resource. HEAD Ask for the response as GET, but without the response body (only meta-info). OPTIONS Request the HTTP methods the server supports for the specified URL. POST Submit data to be a new subordinate of the specified resource. PUT Request data to be stored under the specified resource. TRACE Invoke a remote application-layer loop-back of the request. 2: Application Layer 45

Uploading form input Post method: r Web page often includes form input for users

Uploading form input Post method: r Web page often includes form input for users to fill r Form input is uploaded to server in entity body URL method: r A request generated with a form can also use GET method r Input is uploaded in URL field of request line: www. somesite. com/animalsearch? monkeys&banana 2: Application Layer 46

HTTP response message r After receiving a request message, a server responds with an

HTTP response message r After receiving a request message, a server responds with an HTTP response message. r The first status line of a response message includes the protocol version followed by a numeric status code and its associated textual phrase. v The status-code is a 3 -digit integer code reporting the result of the attempt to satisfy the request. r Header lines follow the status line, which include connection, date, server, last-modified, contentlength, content-type, . . . r Header lines are terminated by cr+lf, then followed by entity body. 2: Application Layer 47

HTTP response message status line (protocol status code status phrase) header lines data, e.

HTTP response message status line (protocol status code status phrase) header lines data, e. g. , requested HTML file HTTP/1. 1 200 OK Connection close Date: Thu, 06 Aug 1998 12: 00: 15 GMT Server: Apache/1. 3. 0 (Unix) Last-Modified: Mon, 22 Jun 1998 …. . . Content-Length: 6821 Content-Type: text/html data data. . . 2: Application Layer 48

HTTP response status codes In first line in server->client response message. A few sample

HTTP response status codes In first line in server->client response message. A few sample codes: 200 OK v request succeeded, requested object later in this message 301 Moved Permanently v requested object moved, new location specified later in this message (Location: ) 400 Bad Request v request message not understood by server 404 Not Found v requested document not found on this server 505 HTTP Version Not Supported 2: Application Layer 49

Trying out HTTP (client side) for yourself 1. Telnet to your favorite Web server:

Trying out HTTP (client side) for yourself 1. Telnet to your favorite Web server: telnet cis. poly. edu 80 Opens TCP connection to port 80 (default HTTP server port) at cis. poly. edu. Anything typed in sent to port 80 at cis. poly. edu 2. Type in a GET HTTP request: GET /~ross/ HTTP/1. 1 Host: cis. poly. edu By typing this in (hit carriage return twice), you send this minimal (but complete) GET request to HTTP server 3. Look at response message sent by HTTP server! 2: Application Layer 50

User-server state: cookies Example: r Susan always access Internet always from PC r visits

User-server state: cookies Example: r Susan always access Internet always from PC r visits specific e 1) cookie header line of HTTP response message commerce site for first 2) cookie header line in time HTTP request message r when initial HTTP 3) cookie file kept on user’s host, managed by requests arrives at site, user’s browser site creates: 4) back-end database at v unique ID Web site v entry in backend database for ID Many major Web sites use cookies Four components: 2: Application Layer 51

Cookies: keeping “state” (cont. ) client ebay 8734 cookie file ebay 8734 amazon 1678

Cookies: keeping “state” (cont. ) client ebay 8734 cookie file ebay 8734 amazon 1678 server usual http request msg usual http response Set-cookie: 1678 usual http request msg cookie: 1678 one week later: usual http response msg Amazon server creates ID 1678 for user create entry cookiespecific action access ebay 8734 amazon 1678 usual http request msg cookie: 1678 usual http response msg backend database cookiespectific action 2: Application Layer 52

Cookies (continued) What cookies can bring: r authorization r shopping carts r recommendations r

Cookies (continued) What cookies can bring: r authorization r shopping carts r recommendations r user session state (Web e-mail) aside Cookies and privacy: r cookies permit sites to learn a lot about you r you may supply name and e-mail to sites How to keep “state”: r protocol endpoints: maintain state at sender/receiver over multiple transactions r cookies: http messages carry state 2: Application Layer 53

Web caches (proxy server) Goal: satisfy client request without involving origin server r user

Web caches (proxy server) Goal: satisfy client request without involving origin server r user sets browser: Web accesses via cache r browser sends all HTTP requests to cache v v object in cache: cache returns object else cache requests object from origin server, then returns object to client origin server HT client. HTTP TP req ues Proxy server t res pon se t s ue q re P nse o T p HT es r TP T H client est u q e Pr T nse o p HT res P T HT origin server 2: Application Layer 54

More about Web caching r cache acts as both client and server r typically

More about Web caching r cache acts as both client and server r typically cache is installed by ISP (university, company, residential ISP) Why Web caching? r reduce response time for client request r reduce traffic on an institution’s access link. r Internet dense with caches: enables “poor” content providers to effectively deliver content (but so does P 2 P file sharing) 2: Application Layer 55

Caching example origin servers Assumptions r average object size = 100, 000 bits r

Caching example origin servers Assumptions r average object size = 100, 000 bits r avg. request rate from institution’s browsers to origin servers = 15/sec r delay from institutional router to any origin server and back to router = 2 sec Consequences public Internet 1. 5 Mbps access link institutional network 10 Mbps LAN r utilization on LAN = 15% r utilization on access link = 100% r total delay = Internet delay + access delay + LAN delay = 2 sec + minutes + milliseconds institutional cache 2: Application Layer 56

Caching example (cont) origin servers possible solution r increase bandwidth of access link to,

Caching example (cont) origin servers possible solution r increase bandwidth of access link to, say, 10 Mbps consequence public Internet r utilization on LAN = 15% r utilization on access link = 15% = Internet delay + access delay + LAN delay = 2 sec + msecs r often a costly upgrade 10 Mbps access link r Total delay institutional network 10 Mbps LAN institutional cache 2: Application Layer 57

Caching example (cont) possible solution: install cache r suppose hit rate is 0. 4

Caching example (cont) possible solution: install cache r suppose hit rate is 0. 4 consequence origin servers public Internet r 40% requests will be satisfied almost immediately r 60% requests satisfied by origin server r utilization of access link reduced to 60%, resulting in negligible delays (say 10 msec) r total avg delay = Internet delay + access delay + LAN delay =. 6*(2. 01) secs +. 4*milliseconds < 1. 4 secs 1. 5 Mbps access link institutional network 10 Mbps LAN institutional cache 2: Application Layer 58

Conditional GET r Goal: don’t send object if cache has up-to-date cached version r

Conditional GET r Goal: don’t send object if cache has up-to-date cached version r cache: specify date of cached copy in HTTP request If-modified-since: <date> r server: response contains no object if cached copy is up-to -date: HTTP/1. 0 304 Not Modified server cache HTTP request msg If-modified-since: <date> HTTP response object not modified HTTP/1. 0 304 Not Modified HTTP request msg If-modified-since: <date> HTTP response object modified HTTP/1. 0 200 OK <data> 2: Application Layer 59

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2 Web and HTTP r 2. 3 FTP r 2. 4 Electronic Mail v SMTP, POP 3, IMAP r 2. 5 DNS r 2. 6 P 2 P applications r 2. 7 Socket programming with TCP r 2. 8 Socket programming with UDP r 2. 9 Building a Web server 2: Application Layer 60

FTP: the file transfer protocol user at host FTP user client interface local file

FTP: the file transfer protocol user at host FTP user client interface local file system file transfer FTP server remote file system r Decades ago, to run programs on a remote machine, people had to save them in the disks, bring the disks to that machine. To solve the inefficiency, FTP was designed for reliabe file transfer over the Internet. r client/server model: ftp server: port 21 v client: side that initiates transfer (either to/from remote) v server: remote host r ftp: RFC 3659 in 2007 is the latest update. 2: Application Layer 61

FTP: separate control, data connections r FTP offers two kinds of accesses: TCP control

FTP: separate control, data connections r FTP offers two kinds of accesses: TCP control connection port 21 authenticated anonymous. The former requires an TCP data connection FTP account/password pair for user FTP port 20 client authentication. All an anonymous server user has to do is login as r Server opens another non“anonymous” or “ftp” and enter persistent TCP data the e-mail address as its connection at port 20 for file password (not strictly checked). transfer. r FTP client contacts FTP server at r FTP server maintains “state”: port 21 over TCP current directory, earlier r Control connection is persistent, authentication out-of-band; used for client authentication, sending control information. 2: Application Layer 62

FTP: Five Major Steps r There are five major steps in an FTP session:

FTP: Five Major Steps r There are five major steps in an FTP session: 1. 2. 3. 4. 5. Connect to or login on the computer the target files are to be downloaded to (or uploaded from). Invoke the FTP client program. Connect to the remote FTP server the files are to be downloaded from (or uploaded to). Provide user name and password for login on the remote server. Issue to the FTP server a sequence of commands to view and transfer the target files. Common FTP user commands 2: Application Layer 63

FTP commands, responses Sample commands: Sample return codes r sent as ASCII text over

FTP commands, responses Sample commands: Sample return codes r sent as ASCII text over r status code and phrase (as control channel r USER username r PASS password r LIST return list of file in r r current directory r RETR filename retrieves r r STOR filename stores r (gets) file (puts) file onto remote host in HTTP) 331 Username OK, password required 125 data connection already open; transfer starting 425 Can’t open data connection 452 Error writing file 2: Application Layer 64

Active and Passive Mode r When the control connection is initiated by the client

Active and Passive Mode r When the control connection is initiated by the client while the data connection is by the server, it is called “active mode”. r Another scheme is called “passive mode” - both connections are initiated by the client. r If the client is behind an NAT or firewall, the data connection from the server would probably be blocked. The client can request the server again for passive FTP by issuing the PASV command. r PASV asks the server to listen on a specific port for the data connection. The server acknowledges the client back by issuing PORT with the IP address and port number other than 20 2: Application Layer 65

Active and Passive Mode 2: Application Layer 66

Active and Passive Mode 2: Application Layer 66

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2 Web and HTTP r 2. 3 FTP r 2. 4 Electronic Mail v r 2. 6 P 2 P applications r 2. 7 Socket programming with TCP r 2. 8 Socket programming with UDP SMTP, POP 3, IMAP r 2. 5 DNS 2: Application Layer 67

Electronic Mail email is an asynchronous communication medium! Three major components: r user agents

Electronic Mail email is an asynchronous communication medium! Three major components: r user agents outgoing message queue user mailbox user agent mail server SMTP r mail servers r simple mail transfer protocol: SMTP User Agent r a. k. a. “mail reader” r composing, editing, reading mail messages r e. g. , Eudora, Outlook, elm, Mozilla Thunderbird r outgoing, incoming messages stored on server SMTP mail server user agent SMTP user agent mail server user agent 2: Application Layer 68

Electronic Mail: mail servers user agent Mail Servers r mailbox contains incoming messages for

Electronic Mail: mail servers user agent Mail Servers r mailbox contains incoming messages for user r message queue of outgoing (to be sent) mail messages (if delivery fails, re-try msg delivery every 30 minutes) r SMTP protocol between mail servers to send email messages v client: sending mail server v “server”: receiving mail server v Mail servers can operate in both client and server mode mail server SMTP mail server user agent SMTP user agent mail server user agent 2: Application Layer 69

Scenario: Alice sends message to Bob 1) Alice uses UA to compose message 4)

Scenario: Alice sends message to Bob 1) Alice uses UA to compose message 4) Alice’s mail server uses SMTP to send Alice’s message over and “to” bob@someschool. edu the TCP connection 2) Alice’s UA sends message to her 5) Bob’s mail server places the mail server; message placed in message in Bob’s mailbox message queue 6) Later on, Bob invokes his user (UA generates and sends SMTP agent to read message commands to the server) 3) Alice’s mail server opens TCP connection with Bob’s mail server 1 user agent 2 mail server 3 mail server 4 5 6 user agent 2: Application Layer 70

Electronic Mail: mail servers r mail user agent (MUA) - allow users to edit,

Electronic Mail: mail servers r mail user agent (MUA) - allow users to edit, send, receive msg. r mail transfer unit (MTU) and mail delivery agent (MDA) – MTA accepts msg from MUA, passes msg to the recipient’s MTA at the remote mail server. r mail retrieval agent – fetch msg from the recipient’s mailbox and pass msg to the recipient’s MUA 2: Application Layer 71

Electronic Mail: SMTP [RFC 2821] r uses TCP to reliably transfer email message from

Electronic Mail: SMTP [RFC 2821] r uses TCP to reliably transfer email message from client to server, on port 25 r direct transfer: from sending server to receiving server without going through any intermediate email server r three phases of transfer v handshaking (greeting) v transfer of messages v closure r command/response interaction v commands: ASCII text v response: status code and phrase r messages must be in 7 -bit ASCII this is problematic since it requires multimedia data to be encoded before transfer and to be decoded by the recipient 2: Application Layer 72

Sample SMTP interaction (once the TCP connection is established, the following interaction begins. )

Sample SMTP interaction (once the TCP connection is established, the following interaction begins. ) S: 220 hamburger. edu C: HELO crepes. fr S: 250 Hello crepes. fr, pleased to meet you C: MAIL FROM: <alice@crepes. fr> S: 250 alice@crepes. fr. . . Sender ok C: RCPT TO: <bob@hamburger. edu> S: 250 bob@hamburger. edu. . . Recipient ok C: DATA S: 354 Enter mail, end with ". " on a line by itself C: Do you like ketchup? C: How about pickles? C: . S: 250 Message accepted for delivery C: QUIT S: 221 hamburger. edu closing connection 2: Application Layer 73

Try SMTP interaction for yourself: r telnet servername 25 r see 220 reply from

Try SMTP interaction for yourself: r telnet servername 25 r see 220 reply from server r enter HELO, MAIL FROM, RCPT TO, DATA, QUIT commands above lets you send email without using email client (reader) SMTP Command HELO MAIL FROM: RCPT TO: DATA RSET QUIT Description Greet the receiver with the sender’s domain name. Indicates the sender, but could be spoofed too. Indicates the recipient. Indicates the mail data, terminated by a ". " in a single line. Reset the session. Close the session. 2: Application Layer 74

Try SMTP interaction for yourself: r Whenever the SMTP server receives a command from

Try SMTP interaction for yourself: r Whenever the SMTP server receives a command from a SMTP client, the server responds with a 3 digit numerical code that indicates either success or failure of the proceeding command. Response Description 2 xx Command accepted and processed. 3 xx General flow control. 4 xx Critical system or transfer failure. 5 xx Errors with the SMTP command. 2: Application Layer 75

SMTP: final words r SMTP uses persistent connections r SMTP requires message (header &

SMTP: final words r SMTP uses persistent connections r SMTP requires message (header & body) to be encoded in 7 -bit ASCII r SMTP server uses CRLF to determine end of message Comparison with HTTP: r HTTP: pull r SMTP: push r both have ASCII command/response interaction, status codes r HTTP: each object encapsulated in its own response msg r SMTP: all of the msg’s objects into one single msg 2: Application Layer 76

Mail message format SMTP: protocol for exchanging email msgs RFC 822: standard for text

Mail message format SMTP: protocol for exchanging email msgs RFC 822: standard for text message format: r header lines, e. g. , To: v From: v Subject: different from SMTP commands! v header blank line body r body v the “message”, ASCII characters only 2: Application Layer 77

Internet Mail Addressing r After all, sending/receiving email requires an email address. r An

Internet Mail Addressing r After all, sending/receiving email requires an email address. r An e-mail address consists of three parts. user@{host. }network. v v An @ (at) symbol separates the first part (user) and the second part (host). The first and the second part identify the username and the mail server of the recipient, respectively. The third part tells the network or domain where the mail server is located. Note that the second part is often omitted for simplicity because the mail server of a domain can be looked up from DNS’s mail exchanger (MX) resource records 2: Application Layer 78

RFC 822 – Internet Message Header Format r The table below summaries common message

RFC 822 – Internet Message Header Format r The table below summaries common message header fields defined in RFC 822. Each field consists of a field name, a colon, and, for most fields, a value. Type Originator Receiver Trace Field From: Description The person(s) who wished this message to be sent. Reply-To: Provides a general mechanism to indicate any mailbox(es) to which responses are to be sent. To: The primary recipients of the message. Cc: Carbon copy to secondary recipients. Bcc: Blind carbon copy to recipients who receive the message without others, including the To: and Cc: recipients, seeing who else received it. Received: A copy of this field is added by each transport service that relays the message. Return. This field is added by the final transport system that Path: delivers the message to its recipient. 2: Application Layer 79

RFC 822 – Internet Message Header Format Type Reference Field Message-ID: Description Contains a

RFC 822 – Internet Message Header Format Type Reference Field Message-ID: Description Contains a unique identifier generated by the mail transport on the originating system In-Reply-To: Previous correspondence which this message answers. Provides a summary, or indicate the nature, of the message. Supplies the date and time the mail was sent Other Subject: Date: Extension X-anything: It is used to implement additional features that have not yet made it into an RFC, or never will. 2: Application Layer 80

Mail access protocols user agent SMTP sender’s mail server access protocol user agent receiver’s

Mail access protocols user agent SMTP sender’s mail server access protocol user agent receiver’s mail server r SMTP: delivery/storage to receiver’s server r Once msg is in the recipient’s mailbox, he can read his email by: 1. 2. Loggin onto the email server and executing a email reader program Using mail access protocol to retrieve email from the server to the user’s host r Mail access protocol: retrieval from server v POP: Post Office Protocol [RFC 1939] • authorization (agent <-->server) and download v v IMAP: Internet Mail Access Protocol [RFC 1730] • more features (more complex) • manipulation of stored msgs on server HTTP: gmail, Hotmail, Yahoo! Mail, etc. 2: Application Layer 81

POP 3 protocol POP 3 session goes through 3 stages: 1. authorization phase v

POP 3 protocol POP 3 session goes through 3 stages: 1. authorization phase v v 2. client commands: • user: declare username • pass: password server responses • +OK • -ERR transaction phase the client retrieves msg or mark msg for deletion, or obtain mail statistics v list: list message numbers v retr: retrieve message by number v dele: delete 3. Update phase v quit: end pop 3 session and delete marked msg S: C: S: +OK POP 3 server ready user bob +OK pass hungry +OK user successfully logged C: S: S: S: C: C: S: list 1 498 2 912. retr 1 <message 1 contents>. dele 1 retr 2 <message 1 contents>. dele 2 quit +OK POP 3 server signing off 2: Application Layer 82 on

POP 3 command Command Description USER name Identifies the user to the server AUTHORIZATION

POP 3 command Command Description USER name Identifies the user to the server AUTHORIZATION PASS string Enters user password AUTHORIZATION STAT TRANSACTION LIST [msg] Gets the number of messages in and octet size of maildrop Gets the size of one or all messages RETR msg Retrieves a message from the maildrop. TRANSACTION DELE msg Marks the msg as deleted from the maildrop. No operation. TRANSACTION Resets all messages that are marked as deleted to unmarked. Terminates the session. TRANSACTION NOOP RSET QUIT Session state TRANSACTION AUTHORIZATION, UPDATE 2: Application Layer 83

POP 3 (more) and IMAP More about POP 3 r Previous example uses r

POP 3 (more) and IMAP More about POP 3 r Previous example uses r r “download and delete” mode -> Bob cannot re-read e-mail if he changes client “Download-and-keep”: copies of messages on different clients During a pop 3 session, POP 3 is stateless across sessions POP 3 cannot manage a folder hierarchy on the mail server IMAP user to organize r r messages in a folder hierarchy Msg arrived at IMAP server is placed in the recipient’s INBOX IMAP supports extra commands to search folders for msg IMAP has commands to obtain components of msg IMAP keeps user state across sessions: v names of folders and mappings between message IDs and folder name 2: Application Layer 84

IMAP states An IMAP 4 server operates on port 143; it can be in

IMAP states An IMAP 4 server operates on port 143; it can be in one of four states. r. Non-authenticated: v When a connection is established between the IMAP server and the client, the server enters the nonauthenticated state. v r Selected: v r. Authenticated: v In the authenticated state, the client must select a mailbox to access before commands that affect messages can be permitted. When a pre-authenticated connection starts, the server enters the authenticated state when acceptable r authentication credentials have been provided or after an error in mailbox selection. When a mailbox has been successfully selected, the server enters the selected state. In this state, a mailbox has been selected to access. Logout: v When the client asks to exit the server, the server enters the logout state. At this time, the server will close the connection. 2: Application Layer 85

IMAP commands r Each IMAP 4 command starts Session state with an identifier called

IMAP commands r Each IMAP 4 command starts Session state with an identifier called a “tag” (e. g. Any Non. A 001, A 002, etc. ). Every command authenticated Authenticated being sent must use a unique tag. r The responses in IMAP 4 can be tagged or untagged. r A tagged status response Selected indicates the completion of a client command with a matched tag. r Untagged status responses indicate server greeting or server status other than the completion of a command. The sever status responses can take three forms: status response, server data, and command continuation request. Commands CAPABILITY, NOOP, LOGOUT AUTHENTICATE, LOGIN SELECT, EXAMINE, CREATE, DELETE, RENAME, SUBSCRIBE, UNSUBSCRIBE, LIST, LSUB, STATUS, APPDNED CHECK, CLOSE, EXPUNCGE, SEARCH, FETCH, STORE, COPY UID 2: Application Layer 86

IMAP response r Status response: The status responses can indicate either the result (OK,

IMAP response r Status response: The status responses can indicate either the result (OK, NO, or BAD) of the completed client command or the server’s greetings and alerts (PREAUTH and BYE). r Server data: The client must record certain server data when it is received, as noted in the description of that data. Data transmitted from the server to the client and status responses that do not indicate command completion are called untagged responses. Each untagged response is prefixed with the token “*”. r Command continuation request: Theses responses indicate that the server is ready to accept the continuation of a command from the client. The reminder of this response is a line of text. 2: Application Layer 87

Web-based mail r Webmail is an e-mail service accessed by a Web browser, as

Web-based mail r Webmail is an e-mail service accessed by a Web browser, as opposed to by a desktop e-mail program like Microsoft Outlook or Mozilla’s Thunderbird. r Webmail service providers are Microsoft Windows Live Hotmail, Yahoo! Mail, Google Gmail, and AOL Mail. r Two advantages of Webmail over desktop e-mail service are ubiquitous accessibility and negligible maintenance overhead. r By Webmail, e-mails are maintained and manipulated on a remote e-mail server through IMAP 4 commands. r Compared with Webmail, a desktop e-mail service requires clients retrieving e-mails from email servers through POP 3 or IMAP 4 commands and storing them locally in users’ computers. 2: Application Layer 88

Web-based mail r Two interfaces exist in Webmail services: 1. a Web interface using

Web-based mail r Two interfaces exist in Webmail services: 1. a Web interface using GET and POST HTTP commands between clients and the frontend Webmail server and 2. an e-mail interface using POP 3/IMAP 4 commands between the frontend Webmail server and backend e-mail servers. 2: Application Layer 89

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2 Web and HTTP r 2. 3 FTP r 2. 4 Electronic Mail v r 2. 6 P 2 P applications r 2. 7 Socket programming with TCP r 2. 8 Socket programming with UDP SMTP, POP 3, IMAP r 2. 5 DNS 2: Application Layer 90

DNS: Domain Name System People: many identifiers: v SSN, name, passport # Internet hosts,

DNS: Domain Name System People: many identifiers: v SSN, name, passport # Internet hosts, routers: v v IP address (32 bit) used for addressing datagrams “name”, e. g. , ww. yahoo. com - used by humans Q: map between IP addresses and name ? Domain Name System: r distributed database implemented in hierarchy of many name servers r application-layer protocol host, routers, name servers to communicate to resolve names (address/name translation) v note: core Internet function, implemented as application-layer protocol v complexity at network’s “edge” 2: Application Layer 91

DNS services r hostname to IP address translation r host aliasing v Canonical, alias

DNS services r hostname to IP address translation r host aliasing v Canonical, alias names r mail server aliasing r load distribution v replicated Web servers: set of IP addresses for one canonical name Why not centralize DNS? r single point of failure r traffic volume r distant centralized database r maintenance doesn’t scale! 2: Application Layer 92

Domain name space r The Internet is huge, so DNS needs a hierarchy to

Domain name space r The Internet is huge, so DNS needs a hierarchy to be scalable. . . 1. 2. 3. Organize hostname in a hiearchy of a domain tree such that hosts on the same level of the hierarchy inherit a unique domain name in hostname Each domain can extend down to various subdomains Each DNS server of a domaintains its own database and answers DNS queries from others r The domain name space is divided into several categories of top level domains 2: Application Layer 93

Top-leve domains Domain com org gov edu net int mil Two-letter country code arpa

Top-leve domains Domain com org gov edu net int mil Two-letter country code arpa Others Description Commercial organizations such as Intel (intel. com). Non-profit organizations such as WWW consortium (w 3. org). U. S. government organizations such as National Science Foundation (nsf. gov). Educational organizations such as UCLA (ucla. edu). Networking organizations such as Internet Assigned Numbers Authority which maintains the DNS root servers (gtld-servers. net). Organizations established by international treaties between governments. For example, International Telecommunication Union (itu. int). Reserved exclusively for the United States Military. For example, Networking Information Center, Department of Defense (nic. mil). The two-letter country code top level domains (cc. TLDs) are based on the ISO 3166 -1 two-letter country codes. Examples are tw (Taiwan) and uk (United Kingdom). Mostly unused now, except for the in-addr. arpa domain which is used to maintain a database for reverse DNS queries. Such as. bi (business), . idv (for individuals), and. info (similar to. com). 2: Application Layer 94

Example of the domain name space support given a hostname “host 1. cs. nctu.

Example of the domain name space support given a hostname “host 1. cs. nctu. edu. tw” 2: Application Layer 95

Zone and DNS name servers r A domain is usually a r Name servers,

Zone and DNS name servers r A domain is usually a r Name servers, usually running on superset of zones. For example, the tw domain contains four zones: org, com, edu, and tw itself. To be r specific, the tw zone contains domain names of the form *. tw, excluding *. org. tw, *. com. tw and *. edu. tw. r r Hosts of the. tw zone are usually for the purpose of administrating the delegated sub-domains. port 53, are hosts that contain a database built with zone data files and a resolution program to answer DNS queries. In a name server, a zone is a basic management unit whose information is stored in a zone data file. A name server may be authoritative for multiple zones, and for availability and load balancing concerns, a zone may also be supervised by multiple name servers to avoid possible breakdown caused by a high request rate overwhelming a single server. 2: Application Layer 96

Distributed, Hierarchical Database Root DNS Servers com DNS servers yahoo. com amazon. com DNS

Distributed, Hierarchical Database Root DNS Servers com DNS servers yahoo. com amazon. com DNS servers org DNS servers pbs. org DNS servers edu DNS servers poly. edu umass. edu DNS servers Client wants IP for www. amazon. com; 1 st approx: r client queries a root server to find com DNS server r client queries com DNS server to get amazon. com DNS server r client queries amazon. com DNS server to get IP address for www. amazon. com 2: Application Layer 97

DNS: Root name servers r contacted by local name server that can not resolve

DNS: Root name servers r contacted by local name server that can not resolve name r root name server: v v v contacts authoritative name server if name mapping not known gets mapping returns mapping to local name server a Verisign, Dulles, VA c Cogent, Herndon, VA (also LA) d U Maryland College Park, MD g US Do. D Vienna, VA h ARL Aberdeen, MD j Verisign, ( 21 locations) e NASA Mt View, CA f Internet Software C. Palo Alto, k RIPE London (also 16 other locations) i Autonomica, Stockholm (plus 28 other locations) m WIDE Tokyo (also Seoul, Paris, SF) CA (and 36 other locations) 13 root name servers worldwide b USC-ISI Marina del Rey, CA l ICANN Los Angeles, CA 2: Application Layer 98

TLD and Authoritative Servers r Top-level domain (TLD) servers: v responsible for com, org,

TLD and Authoritative Servers r Top-level domain (TLD) servers: v responsible for com, org, net, edu, etc, and all top -level country domains uk, fr, ca, jp. v Network Solutions maintains servers for com TLD v Educause for edu TLD r Authoritative DNS servers: v organization’s DNS servers, providing authoritative hostname to IP mappings for organization’s servers (e. g. , Web, mail). v can be maintained by organization or service provider 2: Application Layer 99

Local Name Server r does not strictly belong to hierarchy r each ISP (residential

Local Name Server r does not strictly belong to hierarchy r each ISP (residential ISP, company, university) has one. v also called “default name server” r when host makes DNS query, query is sent to its local DNS server v acts as proxy, forwards query into hierarchy 2: Application Layer 100

DNS name resolution example root DNS server 2 r Host at cis. poly. edu

DNS name resolution example root DNS server 2 r Host at cis. poly. edu wants IP address for gaia. cs. umass. edu iterated query: r contacted server replies with name of server to contact r “I don’t know this name, but ask this server” r Local DNS server sents iterative queries, but to requesting host, query to local DNS server is carried “recursively” 3 4 TLD DNS server 5 local DNS server dns. poly. edu 1 8 requesting host 7 6 authoritative DNS server dns. cs. umass. edu cis. poly. edu gaia. cs. umass. edu 2: Application Layer 101

DNS name resolution example recursive query: root DNS server 2 r puts burden of

DNS name resolution example recursive query: root DNS server 2 r puts burden of name 3 7 resolution on contacted name server r heavy load? The root local DNS server dns. poly. edu server becomes the bottleneck 1 8 r We hardly use this approach! requesting host 6 TLD DNS server 5 4 authoritative DNS server dns. cs. umass. edu cis. poly. edu gaia. cs. umass. edu 2: Application Layer 102

DNS: caching and updating records r once (any) name server learns mapping, it caches

DNS: caching and updating records r once (any) name server learns mapping, it caches mapping v cache entries timeout (disappear) after some time v TLD servers typically cached in local name servers • Thus root name servers not often visited r update/notify mechanisms under design by IETF v RFC 2136 v http: //www. ietf. org/html. charters/dnsind-charter. html 2: Application Layer 103

DNS records RR format: (name, value, type, ttl) DNS: distributed db storing resource records

DNS records RR format: (name, value, type, ttl) DNS: distributed db storing resource records (RR) organized in zone data files r Type=SOA: r An SOA marks the beginning of a DNS zone r data file and identifies the authoritative name server of that zone. r Type=A v name is hostname v value is IP address r Type=NS v name is domain v value is hostname of authoritative name server for this domain Type=CNAME v name is alias name for some “canonical” (the real) name www. ibm. com is really servereast. backup 2. ibm. com v value is canonical name r Type=MX v value is name of mailserver associated with name 2: Application Layer 104

DNS protocol, messages DNS protocol : query and reply messages, both with same message

DNS protocol, messages DNS protocol : query and reply messages, both with same message format msg header r identification: 16 bit # for query, reply to query uses same # r flags: v query or reply v recursion desired v recursion available v reply is authoritative 2: Application Layer 105

DNS protocol, messages Name, type fields for a query RRs in response to query

DNS protocol, messages Name, type fields for a query RRs in response to query records for authoritative servers additional “helpful” info that may be used 2: Application Layer 106

Inserting records into DNS r example: new startup “Network Utopia” r register name networkuptopia.

Inserting records into DNS r example: new startup “Network Utopia” r register name networkuptopia. com at DNS registrar (e. g. , Network Solutions) v v provide names, IP addresses of authoritative name server (primary and secondary) registrar inserts two RRs into com TLD server: (networkutopia. com, dns 1. networkutopia. com, NS) (dns 1. networkutopia. com, 212. 1, A) r create authoritative server Type A record for www. networkuptopia. com; Type MX record for networkutopia. com r How do people get IP address of your Web site? 2: Application Layer 107

Chapter 2: Application layer r 2. 1 Principles of network applications v v app

Chapter 2: Application layer r 2. 1 Principles of network applications v v app architectures app requirements r 2. 2 Web and HTTP r 2. 4 Electronic Mail v SMTP, POP 3, IMAP r 2. 6 P 2 P applications r 2. 7 Socket programming with TCP r 2. 8 Socket programming with UDP r 2. 5 DNS 2: Application Layer 108

Pure P 2 P architecture r no always-on server r arbitrary end systems directly

Pure P 2 P architecture r no always-on server r arbitrary end systems directly communicate peer-peer r peers are intermittently connected and change IP addresses r Three topics: v File distribution v Searching for information v Case Study: Skype 2: Application Layer 109

File Distribution: Server-Client vs P 2 P Question : How much time to distribute

File Distribution: Server-Client vs P 2 P Question : How much time to distribute file from one server to N peers? us: server upload bandwidth Server us File, size F d. N u 1 d 1 u 2 ui: peer i upload bandwidth d 2 di: peer i download bandwidth Network (with abundant bandwidth) 2: Application Layer 110

File distribution time: server-client r server sequentially sends N copies: v NF/us time r

File distribution time: server-client r server sequentially sends N copies: v NF/us time r client i takes F/di time to download Server F us d. N u 1 d 1 u 2 d 2 Network (with abundant bandwidth) Time to distribute F to N clients using = dcs = max { NF/us, F/min(di) } i client/server approach increases linearly in N (for large N) 2: Application Layer 111

File distribution time: P 2 P r server must send one Server F u

File distribution time: P 2 P r server must send one Server F u 1 d 1 u 2 d 2 copy: F/us time us r client i takes F/di time Network (with d. N to download abundant bandwidth) u. N r NF bits must be downloaded (aggregate) r fastest possible upload rate: us + Sui d. P 2 P = max { F/us, F/min(di) , NF/(us + i S ui ) } 2: Application Layer 112

Server-client vs. P 2 P: example Client upload rate = u, F/u = 1

Server-client vs. P 2 P: example Client upload rate = u, F/u = 1 hour, us = 10 u, dmin ≥ us 2: Application Layer 113

File distribution: Bit. Torrent r P 2 P file distribution tracker: tracks peers participating

File distribution: Bit. Torrent r P 2 P file distribution tracker: tracks peers participating in torrent: group of peers exchanging chunks of a file obtain list of peers trading chunks peer 2: Application Layer 114

Bit. Torrent (1) r file divided into 256 KB chunks. r peer joining torrent:

Bit. Torrent (1) r file divided into 256 KB chunks. r peer joining torrent: has no chunks, but will accumulate them over time v registers with tracker to get list of peers, connects to subset of peers (“neighbors”) r while downloading, peer uploads chunks to other peers may come and go r once peer has entire file, it may (selfishly) leave or (altruistically) remain v 2: Application Layer 115

Bit. Torrent (2) Sending Chunks: tit-for-tat r Alice sends chunks to four Pulling Chunks

Bit. Torrent (2) Sending Chunks: tit-for-tat r Alice sends chunks to four Pulling Chunks neighbors currently r at any given time, sending her chunks at the different peers have highest rate different subsets of v re-evaluate top 4 every file chunks 10 secs r periodically, a peer r every 30 secs: randomly (Alice) asks each select another peer, neighbor for list of starts sending chunks that they have. v newly chosen peer may r Alice sends requests for join top 4 her missing chunks v “optimistically unchoke” v rarest first 2: Application Layer 116

Bit. Torrent: Tit-for-tat (1) Alice “optimistically unchokes” Bob (2) Alice becomes one of Bob’s

Bit. Torrent: Tit-for-tat (1) Alice “optimistically unchokes” Bob (2) Alice becomes one of Bob’s top-four providers; Bob reciprocates (3) Bob becomes one of Alice’s top-four providers With higher upload rate, can find better trading partners & get file faster! 2: Application Layer 117

Distributed Hash Table (DHT) r DHT = distributed P 2 P database r Database

Distributed Hash Table (DHT) r DHT = distributed P 2 P database r Database has (key, value) pairs; v key: ss number; value: human name v key: content type; value: IP address r Peers query DB with key v DB returns values that match the key r Peers can also insert (key, value) peers

DHT Identifiers r Assign integer identifier to each peer in range [0, 2 n-1].

DHT Identifiers r Assign integer identifier to each peer in range [0, 2 n-1]. v Each identifier can be represented by n bits. r Require each key to be an integer in same range. r To get integer keys, hash original key. v eg, key = h(“Led Zeppelin IV”) v This is why they call it a distributed “hash” table

How to assign keys to peers? r Central issue: v Assigning (key, value) pairs

How to assign keys to peers? r Central issue: v Assigning (key, value) pairs to peers. r Rule: assign key to the peer that has the closest ID. r Convention in lecture: closest is the immediate successor of the key. r Ex: n=4; peers: 1, 3, 4, 5, 8, 10, 12, 14; key = 13, then successor peer = 14 v key = 15, then successor peer = 1 v

Circular DHT (1) 1 3 15 4 12 5 10 8 r Each peer

Circular DHT (1) 1 3 15 4 12 5 10 8 r Each peer only aware of immediate successor and predecessor. r “Overlay network”

Circle DHT (2) O(N) messages on avg to resolve query, when there are N

Circle DHT (2) O(N) messages on avg to resolve query, when there are N peers 0001 I am Who’s resp 0011 for key 1110 1111 1110 0100 1110 1100 1110 Define closest as closest successor 1010 1110 1000 0101 ?

Circular DHT with Shortcuts 1 3 15 Who’s resp for key 1110? 4 12

Circular DHT with Shortcuts 1 3 15 Who’s resp for key 1110? 4 12 5 10 8 r Each peer keeps track of IP addresses of predecessor, successor, short cuts. r Reduced from 6 to 2 messages. r Possible to design shortcuts so O(log N) neighbors, O(log N) messages in query

Peer Churn 1 • To handle peer churn, require 3 15 4 12 5

Peer Churn 1 • To handle peer churn, require 3 15 4 12 5 10 each peer to know the IP address of its two successors. • Each peer periodically pings its two successors to see if they are still alive. 8 r Peer 5 abruptly leaves r Peer 4 detects; makes 8 its immediate successor; asks 8 who its immediate successor is; makes 8’s immediate successor its second successor. r What if peer 13 wants to join?

P 2 P Case study: Skype clients (SC) r inherently P 2 P: pairs

P 2 P Case study: Skype clients (SC) r inherently P 2 P: pairs of users communicate. r proprietary application Skype login server -layer protocol (inferred via reverse engineering) r hierarchical overlay with SNs r Index maps usernames to IP addresses; distributed over SNs Supernode (SN) 2: Application Layer 125

Peers as relays r Problem when both Alice and Bob are behind “NATs”. v

Peers as relays r Problem when both Alice and Bob are behind “NATs”. v NAT prevents an outside peer from initiating a call to insider peer r Solution: v Using Alice’s and Bob’s SNs, Relay is chosen v Each peer initiates session with relay. v Peers can now communicate through NATs via relay 2: Application Layer 126

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2 Web and HTTP r 2. 3 FTP r 2. 4 Electronic Mail v r 2. 6 P 2 P applications r 2. 7 Socket programming with TCP r 2. 8 Socket programming with UDP SMTP, POP 3, IMAP r 2. 5 DNS 2: Application Layer 127

Socket programming Goal: learn how to build client/server application that communicate using sockets Socket

Socket programming Goal: learn how to build client/server application that communicate using sockets Socket API r introduced in BSD 4. 1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm r two types of transport service via socket API: v unreliable datagram v reliable, byte streamoriented socket a host-local, application-created, OS-controlled interface (a “door”) into which application process can both send and receive messages to/from another application process 2: Application Layer 128

Socket-programming using TCP Socket: a door between application process and endend-transport protocol (UCP or

Socket-programming using TCP Socket: a door between application process and endend-transport protocol (UCP or TCP) TCP service: reliable transfer of bytes from one process to another controlled by application developer controlled by operating system process socket TCP with buffers, variables host or server internet socket TCP with buffers, variables controlled by application developer controlled by operating system host or server 2: Application Layer 129

Socket programming with TCP Client must contact server r server process must first be

Socket programming with TCP Client must contact server r server process must first be running r server must have created socket (door) that welcomes client’s contact Client contacts server by: r creating client-local TCP socket r specifying IP address, port number of server process r When client creates socket: client TCP establishes connection to server TCP r When contacted by client, server TCP creates new socket for server process to communicate with client v allows server to talk with multiple clients v source port numbers used to distinguish clients (more in Chap 3) application viewpoint TCP provides reliable, in-order transfer of bytes (“pipe”) between client and server 2: Application Layer 130

Client/server socket interaction: TCP Server Client (running on hostid) create socket, port=x, for incoming

Client/server socket interaction: TCP Server Client (running on hostid) create socket, port=x, for incoming request: welcome. Socket = Server. Socket() TCP wait for incoming connection request connection. Socket = welcome. Socket. accept() read request from connection. Socket write reply to connection. Socket close connection. Socket setup create socket, connect to hostid, port=x client. Socket = Socket() send request using client. Socket read reply from client. Socket close client. Socket 2: Application Layer 131

Stream jargon r A stream is a sequence of characters that flow into or

Stream jargon r A stream is a sequence of characters that flow into or out of a process. r An input stream is attached to some input source for the process, e. g. , keyboard or socket. r An output stream is attached to an output source, e. g. , monitor or socket. Client process client TCP socket 2: Application Layer 132

Socket programming with TCP Example client-server app: 1) client reads line from standard input

Socket programming with TCP Example client-server app: 1) client reads line from standard input (in. From. User stream) , sends to server via socket (out. To. Server stream) 2) server reads line from socket 3) server converts line to uppercase, sends back to client 4) client reads, prints modified line from socket (in. From. Server stream) 2: Application Layer 133

Example: Java client (TCP) import java. io. *; import java. net. *; class TCPClient

Example: Java client (TCP) import java. io. *; import java. net. *; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modified. Sentence; Create input stream Create client socket, connect to server Create output stream attached to socket Buffered. Reader in. From. User = new Buffered. Reader(new Input. Stream. Reader(System. in)); Socket client. Socket = new Socket("hostname", 6789); Data. Output. Stream out. To. Server = new Data. Output. Stream(client. Socket. get. Output. Stream()); 2: Application Layer 134

Example: Java client (TCP), cont. Create input stream attached to socket Buffered. Reader in.

Example: Java client (TCP), cont. Create input stream attached to socket Buffered. Reader in. From. Server = new Buffered. Reader(new Input. Stream. Reader(client. Socket. get. Input. Stream())); sentence = in. From. User. read. Line(); Send line to server out. To. Server. write. Bytes(sentence + 'n'); Read line from server modified. Sentence = in. From. Server. read. Line(); System. out. println("FROM SERVER: " + modified. Sentence); client. Socket. close(); } } 2: Application Layer 135

Example: Java server (TCP) import java. io. *; import java. net. *; class TCPServer

Example: Java server (TCP) import java. io. *; import java. net. *; class TCPServer { Create welcoming socket at port 6789 Wait, on welcoming socket for contact by client Create input stream, attached to socket public static void main(String argv[]) throws Exception { String client. Sentence; String capitalized. Sentence; Server. Socket welcome. Socket = new Server. Socket(6789); while(true) { Socket connection. Socket = welcome. Socket. accept(); Buffered. Reader in. From. Client = new Buffered. Reader(new Input. Stream. Reader(connection. Socket. get. Input. Stream())); 2: Application Layer 136

Example: Java server (TCP), cont Create output stream, attached to socket Data. Output. Stream

Example: Java server (TCP), cont Create output stream, attached to socket Data. Output. Stream out. To. Client = new Data. Output. Stream(connection. Socket. get. Output. Stream()); Read in line from socket client. Sentence = in. From. Client. read. Line(); capitalized. Sentence = client. Sentence. to. Upper. Case() + 'n'; Write out line to socket out. To. Client. write. Bytes(capitalized. Sentence); } } } End of while loop, loop back and wait for another client connection 2: Application Layer 137

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2 Web and HTTP r 2. 3 FTP r 2. 4 Electronic Mail v r 2. 6 P 2 P applications r 2. 7 Socket programming with TCP r 2. 8 Socket programming with UDP SMTP, POP 3, IMAP r 2. 5 DNS 2: Application Layer 138

Socket programming with UDP: no “connection” between client and server r no handshaking r

Socket programming with UDP: no “connection” between client and server r no handshaking r sender explicitly attaches IP address and port of destination to each packet r server must extract IP address, port of sender from received packet application viewpoint UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server UDP: transmitted data may be received out of order, or lost 2: Application Layer 139

Client/server socket interaction: UDP Server (running on hostid) create socket, port= x. server. Socket

Client/server socket interaction: UDP Server (running on hostid) create socket, port= x. server. Socket = Datagram. Socket() read datagram from server. Socket write reply to server. Socket specifying client address, port number Client create socket, client. Socket = Datagram. Socket() Create datagram with server IP and port=x; send datagram via client. Socket read datagram from client. Socket close client. Socket 2: Application Layer 140

Example: Java client (UDP) Client process Input: receives packet (recall that. TCP received “byte

Example: Java client (UDP) Client process Input: receives packet (recall that. TCP received “byte stream”) Output: sends packet (recall that TCP sent “byte stream”) client UDP socket 2: Application Layer 141

Example: Java client (UDP) import java. io. *; import java. net. *; Create input

Example: Java client (UDP) import java. io. *; import java. net. *; Create input stream Create client socket Translate hostname to IP address using DNS class UDPClient { public static void main(String args[]) throws Exception { Buffered. Reader in. From. User = new Buffered. Reader(new Input. Stream. Reader(System. in)); Datagram. Socket client. Socket = new Datagram. Socket(); Inet. Address IPAddress = Inet. Address. get. By. Name("hostname"); byte[] send. Data = new byte[1024]; byte[] receive. Data = new byte[1024]; String sentence = in. From. User. read. Line(); send. Data = sentence. get. Bytes(); 2: Application Layer 142

Example: Java client (UDP), cont. Create datagram with data-to-send, length, IP addr, port Send

Example: Java client (UDP), cont. Create datagram with data-to-send, length, IP addr, port Send datagram to server Datagram. Packet send. Packet = new Datagram. Packet(send. Data, send. Data. length, IPAddress, 9876); client. Socket. send(send. Packet); Datagram. Packet receive. Packet = new Datagram. Packet(receive. Data, receive. Data. length); Read datagram from server client. Socket. receive(receive. Packet); String modified. Sentence = new String(receive. Packet. get. Data()); System. out. println("FROM SERVER: " + modified. Sentence); client. Socket. close(); } } 2: Application Layer 143

Example: Java server (UDP) import java. io. *; import java. net. *; Create datagram

Example: Java server (UDP) import java. io. *; import java. net. *; Create datagram socket at port 9876 class UDPServer { public static void main(String args[]) throws Exception { Datagram. Socket server. Socket = new Datagram. Socket(9876); byte[] receive. Data = new byte[1024]; byte[] send. Data = new byte[1024]; while(true) { Create space for received datagram Receive datagram Datagram. Packet receive. Packet = new Datagram. Packet(receive. Data, receive. Data. length); server. Socket. receive(receive. Packet); 2: Application Layer 144

Example: Java server (UDP), cont String sentence = new String(receive. Packet. get. Data()); Get

Example: Java server (UDP), cont String sentence = new String(receive. Packet. get. Data()); Get IP addr port #, of sender Inet. Address IPAddress = receive. Packet. get. Address(); int port = receive. Packet. get. Port(); String capitalized. Sentence = sentence. to. Upper. Case(); send. Data = capitalized. Sentence. get. Bytes(); Create datagram to send to client Write out datagram to socket } Datagram. Packet send. Packet = new Datagram. Packet(send. Data, send. Data. length, IPAddress, port); server. Socket. send(send. Packet); } } End of while loop, loop back and wait for another datagram 2: Application Layer 145

Chapter 2: Summary our study of network apps now complete! r application architectures v

Chapter 2: Summary our study of network apps now complete! r application architectures v client-server v P 2 P v hybrid r application service requirements: v reliability, bandwidth, delay r specific protocols: v HTTP v FTP v SMTP, POP, IMAP v DNS v P 2 P: Bit. Torrent, Skype r socket programming r Internet transport service model v v connection-oriented, reliable: TCP unreliable, datagrams: UDP 2: Application Layer 146

Chapter 2: Summary Most importantly: learned about protocols r typical request/reply message exchange: v

Chapter 2: Summary Most importantly: learned about protocols r typical request/reply message exchange: v v client requests info or service server responds with data, status code r message formats: v headers: fields giving info about data v data: info being communicated Important themes: r control vs. data msgs v in-band, out-of-band r centralized vs. decentralized r stateless vs. stateful r reliable vs. unreliable msg transfer r “complexity at network edge” 2: Application Layer 147