Скачать презентацию Chapter 2 Application Layer A note on the Скачать презентацию Chapter 2 Application Layer A note on the

1b10772c891a32e7d1c6ca81572e6105.ppt

  • Количество слайдов: 135

Chapter 2 Application Layer A note on the use of these ppt slides: We’re Chapter 2 Application Layer A note on the use of these ppt slides: We’re making these slides freely available to all (faculty, students, readers). They’re in Power. Point form so you can add, modify, and delete slides (including this one) and slide content to suit your needs. They obviously represent a lot of work on our part. In return for use, we only ask the following: v If you use these slides (e. g. , in a class) in substantially unaltered form, that you mention their source (after all, we’d like people to use our book!) v If you post any slides in substantially unaltered form on a www site, that you note that they are adapted from (or perhaps identical to) our slides, and note our copyright of this material. Computer Networking: A Top Down Approach, 5 th edition. Jim Kurose, Keith Ross Addison-Wesley, April 2009. Thanks and enjoy! JFK/KWR All material copyright 1996 -2010 J. F Kurose and K. W. Ross, All Rights Reserved Application 2 -1

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

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

Some network apps v v v v e-mail web instant messaging remote login P Some network apps v v v v e-mail web instant messaging remote login P 2 P file sharing multi-user network games streaming stored video (You. Tube) v v voice over IP real-time video conferencing cloud computing … … v Application 2 -4

Creating a network app write programs that § run on (different) end systems § Creating a network app write programs that § 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 § network-core devices do not run user applications § applications on end systems allows for rapid app development, propagation application transport network data link physical Application 2 -5

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

Application architectures client-server v peer-to-peer (P 2 P) v hybrid of client-server and P Application architectures client-server v peer-to-peer (P 2 P) v hybrid of client-server and P 2 P v Application 2 -7

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

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

Hybrid of client-server and P 2 P Skype § voice-over-IP P 2 P application Hybrid of client-server and P 2 P Skype § voice-over-IP P 2 P application § centralized server: finding address of remote party: § client-client connection: direct (not through server) Instant messaging § chatting between two users is P 2 P § 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 Application 2 -10

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

Sockets v v process sends/receives messages to/from its socket analogous to door § sending Sockets v v process sends/receives messages to/from its socket analogous to door § 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 v host or server process controlled by app developer process socket TCP with buffers, variables Internet TCP with buffers, variables controlled by OS API: (1) choice of transport protocol; (2) ability to fix a few parameters (lots more on this later) Application 2 -12

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

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

App-layer protocol defines v types of messages exchanged, § e. g. , request, response App-layer protocol defines v types of messages exchanged, § e. g. , request, response v message syntax: § what fields in messages & how fields are delineated v message semantics § meaning of information in fields v public-domain protocols: v defined in RFCs v allows for interoperability v e. g. , HTTP, SMTP proprietary protocols: v e. g. , Skype rules for when and how processes send & respond to messages Application 2 -15

What transport service does an app need? Data loss v some apps (e. g. What transport service does an app need? Data loss v some apps (e. g. , audio) can tolerate some loss v other apps (e. g. , file transfer, telnet) require 100% reliable data transfer Timing v some apps (e. g. , Internet telephony, interactive games) require low delay to be “effective” Throughput v some apps (e. g. , multimedia) require minimum amount of throughput to be “effective” v other apps (“elastic apps”) make use of whatever throughput they get Security v encryption, data integrity, … Application 2 -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 Application 2 -17

Internet transport protocols services TCP service: v v v connection-oriented: setup required between client Internet transport protocols services TCP service: v v v connection-oriented: setup 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: v v unreliable data transfer between sending and receiving process does not provide: connection setup, reliability, flow control, congestion control, timing, throughput guarantee, or security Q: why bother? Why is there a UDP? Application 2 -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 (e. g. , You. Tube), RTP [RFC 1889] SIP, RTP, proprietary (e. g. , Skype) TCP TCP TCP or UDP typically UDP Application 2 -19

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

Web and HTTP First, a review… v web page consists of objects v object Web and HTTP First, a review… v web page consists of objects v object can be HTML file, JPEG image, Java applet, audio file, … v web page consists of base HTML-file which includes several referenced objects v each object is addressable by a URL v example URL: www. someschool. edu/some. Dept/pic. gif host name path name Application 2 -21

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

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

HTTP connections non-persistent HTTP v at most one object sent over TCP connection. persistent HTTP connections non-persistent HTTP v at most one object sent over TCP connection. persistent HTTP v multiple objects can be sent over single TCP connection between client, server. Application 2 -24

Nonpersistent HTTP suppose user enters URL: (contains text, www. some. School. edu/some. Department/home. index Nonpersistent HTTP suppose user enters URL: (contains text, www. some. School. edu/some. Department/home. index references to 10 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 Application 2 -25

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 Application 2 -26

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: v one RTT to initiate TCP connection v one RTT for HTTP request and first few bytes of HTTP response to return v file transmission time total = 2 RTT+transmit time initiate TCP connection RTT request file RTT file received time to transmit file time Application 2 -27

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

HTTP request message v v two types of HTTP messages: request, response HTTP request HTTP request message v v two types of HTTP messages: request, response HTTP request message: § ASCII (human-readable format) request line (GET, POST, HEAD commands) header lines carriage return, line feed at start of line indicates end of header lines carriage return character line-feed character GET /index. html HTTP/1. 1rn Host: www-net. cs. umass. edurn User-Agent: Firefox/3. 6. 10rn Accept: text/html, application/xhtml+xmlrn Accept-Language: en-us, en; q=0. 5rn Accept-Encoding: gzip, deflatern Accept-Charset: ISO-8859 -1, utf-8; q=0. 7rn Keep-Alive: 115rn Connection: keep-alivern Application 2 -29

HTTP request message: general format request line header lines body Application 2 -30 HTTP request message: general format request line header lines body Application 2 -30

Uploading form input POST method: § web page often includes form input v input Uploading form input POST method: § web page often includes form input v input is uploaded to server in entity body URL method: v uses GET method v input is uploaded in URL field of request line: www. somesite. com/animalsearch? monkeys&banana Application 2 -31

Method types HTTP/1. 0 v GET v POST v HEAD § asks server to Method types HTTP/1. 0 v GET v POST v HEAD § asks server to leave requested object out of response HTTP/1. 1 v GET, POST, HEAD v PUT § uploads file in entity body to path specified in URL field v DELETE § deletes file specified in the URL field Application 2 -32

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 OKrn Date: Sun, 26 Sep 2010 20: 09: 20 GMTrn Server: Apache/2. 0. 52 (Cent. OS)rn Last-Modified: Tue, 30 Oct 2007 17: 00: 02 GMTrn ETag: "17 dc 6 -a 5 c-bf 716880"rn Accept-Ranges: bytesrn Content-Length: 2652rn Keep-Alive: timeout=10, max=100rn Connection: Keep-Alivern Content-Type: text/html; charset=ISO-88591rn data data. . . Application 2 -33

HTTP response status codes v v status code appears in 1 st line in HTTP response status codes v v status code appears in 1 st line in server->client response message. some sample codes: 200 OK § request succeeded, requested object later in this msg 301 Moved Permanently § requested object moved, new location specified later in this msg (Location: ) 400 Bad Request § request msg not understood by server 404 Not Found § requested document not found on this server 505 HTTP Version Not Supported Application 2 -34

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! (or use Wireshark!) Application 2 -35

User-server state: cookies example: v Susan always access Internet from PC v visits specific User-server state: cookies example: v Susan always access Internet from PC v visits specific e 1) cookie header line of HTTP response message commerce site for first 2) cookie header line in time HTTP request message v 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 § unique ID Web site § entry in backend database for ID many Web sites use cookies four components: Application 2 -36

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 cookiespecific action Application 2 -37

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

Web caches (proxy server) Goal: satisfy client request without involving origin server v v Web caches (proxy server) Goal: satisfy client request without involving origin server v v user sets browser: Web accesses via cache browser sends all HTTP requests to cache § 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 es qu e se Pr on T p HT res P TT H client st que re se TP pon HT es Pr T HT origin server Application 2 -39

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

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

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

Caching example (cont) origin servers possible solution: v install cache consequence v v v Caching example (cont) origin servers possible solution: v install cache consequence v v v public Internet suppose hit rate is 0. 4 § 40% requests will be satisfied almost immediately § 60% requests satisfied by origin server utilization of access link reduced to 60%, resulting in negligible delays (say 10 msec) 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 Application 2 -43

Conditional GET v v Goal: don’t send object if cache has up-to-date cached version Conditional GET v v Goal: don’t send object if cache has up-to-date cached version cache: specify date of cached copy in HTTP request If-modified-since: v 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: HTTP response HTTP/1. 0 304 Not Modified object not modified before HTTP request msg If-modified-since: HTTP response HTTP/1. 0 200 OK object modified after Application 2 -44

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

FTP: the file transfer protocol user at host v v FTP user client interface FTP: the file transfer protocol user at host v v FTP user client interface local file system file transfer FTP server remote file system transfer file to/from remote host client/server model § client: side that initiates transfer (either to/from remote) § server: remote host ftp: RFC 959 ftp server: port 21 Application 2 -46

FTP: separate control, data connections v v v FTP client contacts FTP server at FTP: separate control, data connections v v v FTP client contacts FTP server at port 21, TCP is transport protocol client authorized over control connection client browses remote directory by sending commands over control connection. when server receives file transfer command, server opens 2 nd TCP connection (for file) to client after transferring one file, server closes data connection. TCP control connection, server port 21 FTP client v v v TCP data connection, server port 20 FTP server opens another TCP data connection to transfer another file. control connection: “out of band” FTP server maintains “state”: current directory, earlier authentication Application 2 -47

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

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

Electronic Mail outgoing message queue user mailbox Three major components: v v v user Electronic Mail outgoing message queue user mailbox Three major components: v v v user agents mail servers simple mail transfer protocol: SMTP User Agent v a. k. a. “mail reader” v composing, editing, reading mail messages v e. g. , Outlook, elm, Mozilla Thunderbird, i. Phone mail client v outgoing, incoming messages stored on server user agent mail server SMTP mail server user agent SMTP user agent mail server user agent Application 2 -50

Electronic Mail: mail servers user agent Mail Servers v v v mailbox contains incoming Electronic Mail: mail servers user agent Mail Servers v v v mailbox contains incoming messages for user message queue of outgoing (to be sent) mail messages SMTP protocol between mail servers to send email messages § client: sending mail server § “server”: receiving mail server SMTP mail server user agent SMTP user agent mail server user agent Application 2 -51

Electronic Mail: SMTP [RFC 2821] v v v uses TCP to reliably transfer email Electronic Mail: SMTP [RFC 2821] v v v uses TCP to reliably transfer email message from client to server, port 25 direct transfer: sending server to receiving server three phases of transfer § handshaking (greeting) § transfer of messages § closure command/response interaction § commands: ASCII text § response: status code and phrase messages must be in 7 -bit ASCII Application 2 -52

Scenario: Alice sends message to Bob 4) SMTP client sends Alice’s message over the Scenario: Alice sends message to Bob 4) SMTP client sends Alice’s message over the TCP connection 5) Bob’s mail server places the message in Bob’s mailbox 6) Bob invokes his user agent to read message 1) Alice uses UA to compose message and “to” [email protected] edu 2) Alice’s UA sends message to her mail server; message placed in message queue 3) Client side of SMTP opens TCP connection with Bob’s mail server 1 user agent 2 mail server 3 mail server 4 5 6 user agent Application 2 -53

Sample SMTP interaction S: C: S: C: C: C: S: 220 hamburger. edu HELO Sample SMTP interaction S: C: S: C: C: C: S: 220 hamburger. edu HELO crepes. fr 250 Hello crepes. fr, pleased to meet you MAIL FROM: 250 [email protected] fr. . . Sender ok RCPT TO: 250 [email protected] edu. . . Recipient ok DATA 354 Enter mail, end with ". " on a line by itself Do you like ketchup? How about pickles? . 250 Message accepted for delivery QUIT 221 hamburger. edu closing connection Application 2 -54

Try SMTP interaction for yourself: v telnet servername 25 see 220 reply from server Try SMTP interaction for yourself: v telnet servername 25 see 220 reply from server v enter HELO, MAIL FROM, RCPT TO, DATA, QUIT commands above lets you send email without using email client (reader) v Application 2 -55

SMTP: final words v v v SMTP uses persistent connections SMTP requires message (header SMTP: final words v v v SMTP uses persistent connections SMTP requires message (header & body) to be in 7 bit ASCII SMTP server uses CRLF to determine end of message comparison with HTTP: v v v HTTP: pull SMTP: push both have ASCII command/response interaction, status codes HTTP: each object encapsulated in its own response msg SMTP: multiple objects sent in multipart msg Application 2 -56

Mail access protocols user agent SMTP sender’s mail server v v access protocol user Mail access protocols user agent SMTP sender’s mail server v v access protocol user agent receiver’s mail server SMTP: delivery/storage to receiver’s server mail access protocol: retrieval from server § POP: Post Office Protocol [RFC 1939] • authorization (agent <-->server) and download § IMAP: Internet Mail Access Protocol [RFC 1730] • more features (more complex) • manipulation of stored msgs on server § HTTP: gmail, Hotmail, Yahoo! Mail, etc. Application 2 -57

POP 3 protocol authorization phase v v client commands: § user: declare username § POP 3 protocol authorization phase v v client commands: § user: declare username § pass: password server responses § +OK § -ERR transaction phase, client: v v list: list message numbers retr: retrieve message by number dele: delete quit 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 . dele 1 retr 2 . dele 2 quit +OK POP 3 server signing off on Application 2 -58

POP 3 (more) and IMAP more about POP 3 v previous example uses “download POP 3 (more) and IMAP more about POP 3 v previous example uses “download and delete” mode. v Bob cannot re-read email if he changes client v “download-and-keep”: copies of messages on different clients v POP 3 is stateless across sessions IMAP v keeps all messages in one place: at server v allows user to organize messages in folders v keeps user state across sessions: § names of folders and mappings between message IDs and folder name Application 2 -59

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: v header lines, e. g. , § To: § From: § Subject: different from SMTP commands! v header blank line body § the “message”, ASCII characters only Application 2 -60

RFC 822 An e-mail is a message made up of a string of ASCII RFC 822 An e-mail is a message made up of a string of ASCII characters in a format specified by RFC 822 (dating from 1982). v Two parts, separated by blank line: v § The header: sender, recipient, date, subject, delivery path, … § The body: containing the actual message content. v Use of ASCII causes problems for non. ASCII message bodies, e. g. attachments, non-US-ASCII characters.

An Example RFC 822 Message From: Kenny. Paterson@rhul. ac. uk To: Joe. Bloggs@rhul. ac. An Example RFC 822 Message From: Kenny. [email protected] ac. uk To: Joe. [email protected] ac. uk Cc: [email protected] com Subject: RFC 822 example Date: Fri, 15 Nov 2002 13: 58: 49 This is just a test message to illustrate RFC 822. It’s not very long and it’s not very exciting. But you get the point.

MIME = Multipurpose Internet Mail Extensions v Extends the capabilities of RFC 822 to MIME = Multipurpose Internet Mail Extensions v Extends the capabilities of RFC 822 to allow e-mail to carry non-textual content, non-USASCII character sets. v Uses extra header fields in RFC 822 e-mails to specify form and content of extensions. v Supports a variety of content types, but email still ASCII-coded for compatibility. v Specified in RFCs 2045 -2049.

MIME headers MIME specifies 5 new e-mail header fields: v MIME-Version (must be 1. MIME headers MIME specifies 5 new e-mail header fields: v MIME-Version (must be 1. 0) v Content-Type v Content-Transfer-Encoding v Content-ID - optional v Content-Disposition - optional

MIME Content-Type v Seven major content types with 15 sub -types. v Most important MIME Content-Type v Seven major content types with 15 sub -types. v Most important is Multipart/mixed, indicating that the body contains multiple parts. v Each part can be a separate MIME message – hence nesting of MIME messages to any level. v Parts separated by a boundary string defined in Content-Type field.

Content-Transfer Encoding RFC 822 e-mails can contain only ASCII characters. v MIME messages intended Content-Transfer Encoding RFC 822 e-mails can contain only ASCII characters. v MIME messages intended to transport arbitrary data. v The Content-Transfer-Encoding field indicates how data was encoded from raw data to ASCII. v base 64 is a common encoding: v § 24 data bits (3 bytes) at a time encoded to 4 ASCII characters.

An Example MIME Message From: j. bloggs@rhul. ac. uk To: Kenny. Paterson@rhul. ac. uk An Example MIME Message From: j. [email protected] ac. uk To: Kenny. [email protected] ac. uk Subject: That document Date: Wed, 13 Nov 2002 19: 55: 47 -0000 MIME-Version: 1. 0 Content-Type: multipart/mixed; boundary="----next part" ------next part Content-Type: text/plain; charset="iso-8859 -1" Content-Transfer-Encoding: 7 bit Kenny, here’s that document I said I’d send. Regards, Joe ------next part Content-Type: application/x-zip-compressed; name=“report. zip" Content-Transfer-Encoding: base 64 Content-Disposition: attachment; filename= “report. zip" rfvbnj 756 tb. GHUSISyuhssia 9982372 SHHS 3717277 vsg. GJ 77 JS 77 HFyt 6 GS 8 ------next part--

S/MIME Originated from RSA Data Security Inc. in 1995. v Further development by IETF S/MIME Originated from RSA Data Security Inc. in 1995. v Further development by IETF S/MIME working group at: v www. ietf. org/html. charters/smime-charter. html. Version 3 specified in RFCs 2630 -2634. v Allows flexible client-client security through encryption and signatures. v Widely supported, e. g. in Microsoft Outlook, Netscape Messenger, Lotus Notes. v

S/MIME Message Formats As the name suggests, S/MIME adds security features by extending MIME. S/MIME Message Formats As the name suggests, S/MIME adds security features by extending MIME. v S/MIME adds 5 new content type/subtype combinations, including: v § application/pkcs 7 -mime; smime-type=enveloped-data § application/pkcs 7 -mime; smime-type=signed-data § multipart/signed

S/MIME Processing v S/MIME processing can be applied to any MIME entity: § One S/MIME Processing v S/MIME processing can be applied to any MIME entity: § One part of a MIME multipart message. § End result of S/MIME processing is always another MIME entity, of S/MIME Content. Type. § Hence encryption and signature can be applied one after another, and in either order.

S/MIME Processing – Sender MIME entity v v v PKCS object S/MIME processing S/MIME S/MIME Processing – Sender MIME entity v v v PKCS object S/MIME processing S/MIME Base 64 entity encoding Initial S/MIME processing produces a PKCS object. PKCS=Public Key Cryptography Standard. PKCS object includes information needed for processing by recipient as well as the original content. But PKCS objects are in binary format, hence need for further base 64 encoding to produce final result MIME object of S/MIME content-type. Recipient performs steps in reverse.

S/MIME enveloped-data Enveloped. Data Session Recipient’s Key K Public Key S/MIME header PKCS object S/MIME enveloped-data Enveloped. Data Session Recipient’s Key K Public Key S/MIME header PKCS object Recipient. Info S/MIME body: E Encrypted. Key Encrypted. Content Info E MIME entity Encrypted. Content Base 64 encoding Base 64 encoded PKCS object

S/MIME enveloped-data An example message (from RFC 2633): Content-Type: application/pkcs 7 -mime; smime-type=enveloped-data; name=smime. S/MIME enveloped-data An example message (from RFC 2633): Content-Type: application/pkcs 7 -mime; smime-type=enveloped-data; name=smime. p 7 m Content-Transfer-Encoding: base 64 Content-Disposition: attachment; filename=smime. p 7 m rfvbnj 756 tb. Bghy. Hh. HUujh. Jhj. H 77 n 8 HHGT 9 HG 4 VQpfy. F 467 GI 7 n 8 HHGghy. Hh. HUujh. Jh 4 VQpfy. F 467 Gh. IGf. Hf. YGTrfvbnj. T 6 j. Hd f 8 HHGTrfvh. Jhj. H 776 tb. B 9 HG 4 VQbnj 7567 Gh. IGf. Hf. YT 6 ghy. Hh 6

S/MIME enveloped-data v v S/MIME enveloped-data type gives data confidentiality service through encryption. S/MIME S/MIME enveloped-data v v S/MIME enveloped-data type gives data confidentiality service through encryption. S/MIME header contains original To: , From: and Subject: fields, so protection not complete. Symmetric algorithm with session key for efficient bulk encryption and asymmetric encryption using recipient’s public key to protect session key. Recipient reverses steps: obtain K using private key, then use K to decrypt Encrypted. Content. § Algorithms needed are specified in Recipient. Info and Encrypted. Content. Info blocks.

S/MIME signed-data MIME entity Sender’s Private Key Signed. Data PKCS object S/MIME header Signer. S/MIME signed-data MIME entity Sender’s Private Key Signed. Data PKCS object S/MIME header Signer. Info Signer’s Cert Sig and Hash alg Hash Sign Sig and Hash MIME entity S/MIME body: Base 64 encoding Base 64 encoded PKCS object

S/MIME signed-data An example message (from RFC 2633): Content-Type: application/pkcs 7 -mime; smime-type=signed-data; name=smime. S/MIME signed-data An example message (from RFC 2633): Content-Type: application/pkcs 7 -mime; smime-type=signed-data; name=smime. p 7 m Content-Transfer-Encoding: base 64 Content-Disposition: attachment; filename=smime. p 7 m 567 Gh. IGf. Hf. YT 6 ghy. Hh. HUujpfy. F 4 f 8 HHGTrfvh. Jhj. H 776 tb. B 97 7 n 8 HHGT 9 HG 4 VQpfy. F 467 Gh. IGf. Hf. YT 6 rfvbnj 756 tb. Bghy. Hh. HU HUujh. Jh 4 VQpfy. F 467 Gh. IGf. Hf. YGTrfvbnj. T 6 j. H 7756 tb. B 9 H 7 n 8

S/MIME signed-data v v S/MIME signed-data type gives integrity, authenticity and non-repudiation services using S/MIME signed-data v v S/MIME signed-data type gives integrity, authenticity and non-repudiation services using sender signatures. Multiple signers supported – prepare a Signer. Info block for each one. Recipient checks signature using MIME entity embedded in PKCS object and public (verification) key of sender. Recipient without S/MIME capability cannot read the original message (even if he doesn’t care about signatures).

S/MIME Clear Signing v v v Uses MIME multipart/signed content type. First part contains S/MIME Clear Signing v v v Uses MIME multipart/signed content type. First part contains MIME entity to be signed. Second part contains S/MIME application/pkcs 7 -signature entity, created as for signed-data type. Recipients who have MIME but not S/MIME capability can still read message contents. Recipients who have S/MIME capability use first part as MIME object in S/MIME signature verification.

S/MIME Clear Signing Content-Type: multipart/signed; protocol= S/MIME Clear Signing Content-Type: multipart/signed; protocol="application/pkcs 7 -signature"; micalg=sha 1; boundary=boundary 42 --boundary 42 Content-Type: text/plain This is a clear-signed message. --boundary 42 Content-Type: application/pkcs 7 -signature; name=smime. p 7 s Content-Transfer-Encoding: base 64 Content-Disposition: attachment; filename=smime. p 7 s ghy. Hh. HUujh. Jhj. H 77 n 8 HHGTrfvbnj 756 tb. B 9 HG 4 VQpfy. F 4674 VQpfy. F 467 Gh. IGf. Hf. YT 6 j. H 77 n 8 HHGghy. Hh. HUujh. Jh 756 tb 6 --boundary 42 --

S/MIME Algorithms v Symmetric encryption: § DES, 3 DES, RC 2 with 40 and S/MIME Algorithms v Symmetric encryption: § DES, 3 DES, RC 2 with 40 and 64 bit keys. v Public key encryption: § RSA, El. Gamal. v Hashing: § SHA-1, MD 5. v Signature: § RSA, Digital Signature Standard (DSS).

Main Obstacles v End-to-end security only: § Firewall cannot inspect and filter email v Main Obstacles v End-to-end security only: § Firewall cannot inspect and filter email v Managing certificates § Needed for public key encryption and signature

PGP v v v PGP=“Pretty Good Privacy” First released in 1991, developed by Phil PGP v v v PGP=“Pretty Good Privacy” First released in 1991, developed by Phil Zimmerman, provoked export control and patent infringement controversy. Freeware: Open. PGP and variants: § www. openpgp. org, www. gnupg. org Commercial: formerly Network Associates International, now PGP Corporation at www. pgp. com Open. PGP specified in RFC 2440 and defined by IETF Open. PGP working group. § www. ietf. org/html. charters/openpgpcharter. html Available as plug-in for popular e-mail clients, can also be used as stand-alone software.

PGP v Functionality similar to S/MIME: § encryption for confidentiality. § signature for non-repudiation/authenticity. PGP v Functionality similar to S/MIME: § encryption for confidentiality. § signature for non-repudiation/authenticity. v Sign before encrypt, so signatures on unencrypted data. § Sigs can be detached and stored separately. v PGP-processed data is base 64 encoded and carried inside RFC 822 message body.

PGP Algorithms Broad range of algorithms supported: v Symmetric encryption: § DES, 3 DES, PGP Algorithms Broad range of algorithms supported: v Symmetric encryption: § DES, 3 DES, AES and others. v Public key encryption of session keys: § RSA or El. Gamal. v Hashing: § SHA-1, MD-5 and others. v Signature: § RSA, DSS, ECDSA and others.

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

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

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

Content distribution networks (CDNs) Content replication v v challenging to stream large files (e. Content distribution networks (CDNs) Content replication v v challenging to stream large files (e. g. , video) from single origin server in real time solution: replicate content at hundreds of servers throughout Internet § content downloaded to CDN servers ahead of time § placing content “close” to user avoids impairments (loss, delay) of sending content over long paths § CDN server typically in edge/access network Multimedia Networking origin server in North America CDN distribution node CDN server in S. America CDN server in Europe CDN server in Asia 7 -88

Content distribution networks (CDNs) Content replication v CDN (e. g. , Akamai) customer is Content distribution networks (CDNs) Content replication v CDN (e. g. , Akamai) customer is the content provider (e. g. , CNN) v CDN replicates customers’ content in CDN servers. v when provider updates content, CDN updates servers Multimedia Networking origin server in North America CDN distribution node CDN server in S. America CDN server in Europe CDN server in Asia 7 -89

CDN example HTTP request for www. foo. com/sports. html origin server 1 2 client CDN example HTTP request for www. foo. com/sports. html origin server 1 2 client 3 DNS query for www. cdn. com CDN’s authoritative DNS server HTTP request for www. cdn. com/www. foo. com/sports/ruth. gif CDN server near client origin server (www. foo. com) v distributes HTML v replaces: http: //www. foo. com/sports. ruth. gif with http: //www. cdn. com/www. foo. com/sports/ruth. gif Multimedia Networking CDN company (cdn. com) v distributes gif files v uses its authoritative DNS server to route redirect requests 7 -90

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: v v v client queries a root server to find com DNS server client queries com DNS server to get amazon. com DNS server client queries amazon. com DNS server to get IP address for www. amazon. com Application 2 -91

DNS: Root name servers v v contacted by local name server that can not DNS: Root name servers v v contacted by local name server that can not resolve name root name server: § 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 Application 2 -92

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

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

DNS name resolution example v v 2 host at cis. poly. edu wants IP DNS name resolution example v v 2 host at cis. poly. edu wants IP address for gaia. cs. umass. edu iterated query: v root DNS server contacted server replies with name of server to contact “I don’t know this name, but ask this server” 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 Application 2 -95

DNS name resolution example recursive query: v v root DNS server 2 puts burden DNS name resolution example recursive query: v v root DNS server 2 puts burden of name 7 resolution on contacted name server local DNS server heavy load? dns. poly. edu 1 3 6 TLD DNS server 5 4 8 requesting host authoritative DNS server dns. cs. umass. edu cis. poly. edu gaia. cs. umass. edu Application 2 -96

DNS: caching and updating records v once (any) name server learns mapping, it caches DNS: caching and updating records v once (any) name server learns mapping, it caches mapping § cache entries timeout (disappear) after some time § TLD servers typically cached in local name servers • Thus root name servers not often visited v update/notify mechanisms proposed IETF standard § RFC 2136 Application 2 -97

DNS records DNS: distributed db storing resource records (RR) RR format: (name, value, type, DNS records DNS: distributed db storing resource records (RR) RR format: (name, value, type, ttl) Type=A § name is hostname § value is IP address Type=NS Type=CNAME § name is alias name for some § “canonical” (the real) name www. ibm. com is really servereast. backup 2. ibm. com § name is domain (e. g. , § value is canonical name foo. com) § value is hostname of Type=MX authoritative name server § value is name of mailserver for this domain associated with name Application 2 -98

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 v v identification: 16 bit # for query, reply to query uses same # flags: § query or reply § recursion desired § recursion available § reply is authoritative Application 2 -99

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 Application 2 -100

Inserting records into DNS v v example: new startup “Network Utopia” register name networkuptopia. Inserting records into DNS v v example: new startup “Network Utopia” register name networkuptopia. com at DNS registrar (e. g. , Network Solutions) § 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) v v create authoritative server Type A record for www. networkuptopia. com; Type MX record for networkutopia. com How do people get IP address of your Web site? Application 2 -101

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

Pure P 2 P architecture v v v no always-on server arbitrary end systems Pure P 2 P architecture v v v no always-on server arbitrary end systems directly communicate peers are intermittently peer-peer connected and change IP addresses Three topics: § file distribution § searching for information § case Study: Skype Application 2 -103

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) Application 2 -104

File distribution time: server-client v v server sequentially sends N copies: § NF/us time File distribution time: server-client v v server sequentially sends N copies: § NF/us time 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) Application 2 -105

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

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 Application 2 -107

File distribution: Bit. Torrent P 2 P file distribution tracker: tracks peers participating in File distribution: Bit. Torrent 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 Application 2 -108

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

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

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! Application 2 -111

Exercise Problems (1) v Suppose your department has a local DNS server for all Exercise Problems (1) v Suppose your department has a local DNS server for all computers in the department. You are an ordinary user. Can you come up a way to determine if an external website was very likely accessed from a computer in your department a couple of seconds ago? Explain. 2: Application Layer 112

Exercise Problems (2) v Suppose Bob joins a Bit. Torrent torrent, but he does Exercise Problems (2) v Suppose Bob joins a Bit. Torrent torrent, but he does not want to upload any data to any other peers (so called free-riding). a) Bob claims that he can receive a complete copy of the file that is shared by the swarm. Is Bob’s claim possible? Why or why not? b) Bob further claims that he can further make his free-riding more efficient by using a collection of multiple computers with distinct IP addresses. Can he do that? 2: Application Layer 113

Exercise Problems (3) v Consider two peers Alice and Bob. They join a torrent Exercise Problems (3) v Consider two peers Alice and Bob. They join a torrent with M peers in total including them that are sharing a file consisting of N chunks. Assume that at a particular time t, the chunks that a peer has are uniformly at random chosen from all N chunks, and no peer has all N chunks. What is the probability that Bob has all the chunks that Alice has, given that the numbers of chunks Bob and Alice have are denoted by nb and na, and nb>=na? 2: Application Layer 114

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

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 v v introduced in BSD 4. 1 UNIX, 1981 explicitly created, used, released by apps client/server paradigm two types of transport service via socket API: § unreliable datagram § 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 Application 2 -116

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 controlled by application developer controlled by operating system host or server Application 2 -117

Socket programming with TCP Client must contact server v server process must first be Socket programming with TCP Client must contact server v server process must first be running v server must have created socket (door) that welcomes client’s contact Client contacts server by: v creating client-local TCP socket v specifying IP address, port number of server process v when client creates socket: client TCP establishes connection to server TCP v when contacted by client, server TCP creates new socket for server process to communicate with client § allows server to talk with multiple clients § 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 Application 2 -118

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 Application 2 -119

Stream jargon v v v stream is a sequence of characters that flow into Stream jargon v v v stream is a sequence of characters that flow into or out of a process. input stream is attached to some input source for the process, e. g. , keyboard or socket. output stream is attached to an output source, e. g. , monitor or socket. Client process client TCP socket Application 2 -120

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) Application 2 -121

Example: Java client (TCP) import java. io. *; import java. net. *; class TCPClient Example: Java client (TCP) import java. io. *; import java. net. *; class TCPClient { create input stream create client. Socket object of type Socket, connect to server create output stream attached to socket This package defines Socket() and Server. Socket() classes public static void main(String argv[]) throws Exception { server name, String sentence; e. g. , www. umass. edu String modified. Sentence; server port # 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()); Application 2 -122

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); close socket client. Socket. close(); (clean up behind yourself!) } } Application 2 -123

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 accept() method for client contact create, new socket on return 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())); Application 2 -124

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 Application 2 -125

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

Socket programming with UDP: no “connection” between client and server v no handshaking v Socket programming with UDP: no “connection” between client and server v no handshaking v sender explicitly attaches IP address and port of destination to each packet v 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 Application 2 -127

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 Application 2 -128

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 Application 2 -129

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(); Application 2 -130

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(); } } Application 2 -131

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); Application 2 -132

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 Application 2 -133

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

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