chapter 2: application layercs456/s08/week9.pdfchapter 2: application layer 2.1 principles of...

61
1 Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP 2.3 FTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS 2.6 P2P applications 2.7 Socket programming with TCP 2.8 Socket programming with UDP

Upload: others

Post on 22-May-2020

41 views

Category:

Documents


0 download

TRANSCRIPT

1

Chapter 2: Application layer

❒ 2.1 Principles of network applications

❒ 2.2 Web and HTTP

❒ 2.3 FTP

❒ 2.4 Electronic Mail� SMTP, POP3, IMAP

❒ 2.5 DNS

❒ 2.6 P2P applications

❒ 2.7 Socket programming with TCP

❒ 2.8 Socket programming with UDP

2

Socket programming

Socket API❒ introduced in BSD4.1 UNIX, 1981

❒ explicitly created, used, released by apps

❒ client/server paradigm

❒ two types of transport service via socket API:

� unreliable datagram

� reliable, byte stream-oriented

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

socket

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

3

Socket-programming using TCP

Socket: a door between application process and end-end-transport protocol (UDP or TCP)

TCP service: reliable transfer of bytes from one process to another

process

TCP withbuffers,variables

socket

controlled byapplicationdeveloper

controlled byoperatingsystem

host orserver

process

TCP withbuffers,variables

socket

controlled byapplicationdeveloper

controlled byoperatingsystem

host orserver

internet

4

Socket programming with TCP

Client must contact server

❒ server process must first be running

❒ server must have created socket (door) that welcomes client’s contact

Client contacts server by:

❒ creating client-local TCP socket

❒ specifying IP address, port number of server process

❒ When client creates socket: client TCP establishes connection to server TCP

❒ When contacted by client, server TCP creates new socketfor server process to communicate with client

� allows server to talk with multiple clients

� source port numbers used to distinguish clients

TCP provides reliable, in-ordertransfer of bytes (“pipe”) between client and server

application viewpoint

5

Client/server socket interaction: TCP

wait for incomingconnection requestconnectionSocket =welcomeSocket.accept()

create socket,port=x , forincoming request:welcomeSocket =

ServerSocket()

create socket,connect to hostid , port=xclientSocket =

Socket()

closeconnectionSocket

read reply fromclientSocket

closeclientSocket

Server (running on hostid ) Client

send request usingclientSocketread request from

connectionSocket

write reply toconnectionSocket

TCP connection setup

6ou

tToS

erve

r

to network from network

inF

rom

Ser

ver

inF

rom

Use

r

keyboard monitor

Process

clientSocket

inputstream

inputstream

outputstream

TCPsocket

Client

process

client TCP socket

Stream jargon

❒ A stream is a sequence of characters that flow into or out of a process.

❒ An input stream is attached to some input source for the process, e.g., keyboard or socket.

❒ An output stream is attached to an output source, e.g., monitor or socket.

7

Socket programming with TCP

Example client-server app:1) client reads line from standard input (inFromUser stream) , sends to server via socket (outToServer 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 (inFromServer stream)

8

Example: Java client (TCP)

import java.io.*; import java.net.*; class TCPClient {

public static void main(String argv[]) throws Exception {

String sentence; String modifiedSentence;

BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

Socket clientSocket = new Socket("hostname", 6789);

DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

Createinput stream

Create client socket,

connect to server

Createoutput stream

attached to socket

9

Example: Java client (TCP), cont.

BufferedReader inFromServer = new BufferedReader(newInputStreamReader(clientSocket.getInputStream()));

sentence = inFromUser.readLine();

outToServer.writeBytes(sentence + '\n');

modifiedSentence = inFromServer.readLine();

System.out.println("FROM SERVER: " + modifiedSentence);

clientSocket.close();

} }

Createinput stream

attached to socket

Send lineto server

Read linefrom server

10

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

class TCPServer {

public static void main(String argv[]) throws Exception {

String clientSentence; String capitalizedSentence;

ServerSocket welcomeSocket = new ServerSocket(6789);

while(true) {

Socket connectionSocket = welcomeSocket.accept();

BufferedReader inFromClient = new BufferedReader(newInputStreamReader(connectionSocket.getInputStream()));

Createwelcoming socket

at port 6789

Wait, on welcomingsocket for contact

by client

Create inputstream, attached

to socket

11

Example: Java server (TCP), cont

DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

clientSentence = inFromClient.readLine();

capitalizedSentence = clientSentence.toUpperCase() + '\n';

outToClient.writeBytes(capitalizedSentence); }

} }

Read in linefrom socket

Create outputstream, attached

to socket

Write out lineto socket

End of while loop,loop back and wait foranother client connection

12

Chapter 4: Network Layer

❒ 4. 1 Introduction

❒ 4.2 Virtual circuit and datagram networks

❒ 4.3 What’s inside a router

❒ 4.4 IP: Internet Protocol� Datagram format

� IPv4 addressing

� ICMP

� IPv6

❒ 4.5 Routing algorithms� Link state

� Distance Vector

� Hierarchical routing

❒ 4.6 Routing in the Internet� RIP

� OSPF

� BGP

❒ 4.7 Broadcast and multicast routing

13

NAT: Network Address Translation

10.0.0.1

10.0.0.2

10.0.0.3

10.0.0.4

138.76.29.7

local network(e.g., home network)

10.0.0/24

rest ofInternet

Datagrams with source or destination in this networkhave 10.0.0/24 address for source, destination (as usual)

All datagrams leaving localnetwork have same single source NAT IP address: 138.76.29.7,different source port numbers

14

NAT: Network Address Translation

❒ Motivation: local network uses just one IP address as far as outside world is concerned:

� range of addresses not needed from ISP: just one IP address for all devices

� can change addresses of devices in local network without notifying outside world

� can change ISP without changing addresses of devices in local network

� devices inside local net not explicitly addressable, visible by outside world (a security plus).

15

NAT: Network Address Translation

Implementation: NAT router must:

� outgoing datagrams: replace (source IP address, port #) of every outgoing datagram to (NAT IP address, new port #). . . remote clients/servers will respond using (NAT IP address, new port #) as destination addr.

� remember (in NAT translation table) every (source IP address, port #) to (NAT IP address, new port #) translation pair

� incoming datagrams: replace (NAT IP address, new port #) in dest fields of every incoming datagram with corresponding (source IP address, port #) stored in NAT table

16

NAT: Network Address Translation

10.0.0.1

10.0.0.2

10.0.0.3

S: 10.0.0.1, 3345D: 128.119.40.186, 80

1

10.0.0.4

138.76.29.7

1: host 10.0.0.1 sends datagram to 128.119.40.186, 80

NAT translation tableWAN side addr LAN side addr

138.76.29.7, 5001 10.0.0.1, 3345…… ……

S: 128.119.40.186, 80 D: 10.0.0.1, 3345 4

S: 138.76.29.7, 5001D: 128.119.40.186, 802

2: NAT routerchanges datagramsource addr from10.0.0.1, 3345 to138.76.29.7, 5001,updates table

S: 128.119.40.186, 80 D: 138.76.29.7, 5001 3

3: Reply arrivesdest. address:138.76.29.7, 5001

4: NAT routerchanges datagramdest addr from138.76.29.7, 5001 to 10.0.0.1, 3345

17

NAT: Network Address Translation

❒ 16-bit port-number field:

� 60,000 simultaneous connections with a single LAN-side address!

❒ NAT is controversial:

� routers should only process up to layer 3

� violates end-to-end argument• NAT possibility must be taken into account by app designers, eg, P2P applications

� address shortage should instead be solved by IPv6

18

NAT traversal problem

❒ client wants to connect to server with address 10.0.0.1� server address 10.0.0.1 local to LAN (client can’t use it as destination addr)

� only one externally visible NATted address: 138.76.29.7

❒ solution 1: statically configure NAT to forward incoming connection requests at given port to server� e.g., (138.76.29.7, port 2500) always forwarded to 10.0.0.1 port 25000

10.0.0.1

10.0.0.4

NAT router

138.76.29.7

Client?

19

NAT traversal problem

❒ solution 2: Universal Plug and Play (UPnP) Internet Gateway Device (IGD) Protocol. Allows NATted host to:� learn public IP address (138.76.29.7)

� enumerate existing port mappings

� add/remove port mappings (with lease times)

i.e., automate static NAT port map configuration

10.0.0.1

10.0.0.4

NAT router

138.76.29.7

IGD

20

NAT traversal problem

❒ solution 3: relaying (used in Skype)

� NATed server establishes connection to relay

� External client connects to relay

� relay bridges packets between to connections

10.0.0.1

NAT router

138.76.29.7

Client

1. connection torelay initiatedby NATted host

2. connection torelay initiatedby client

3. relaying established

21

Chapter 2Application Layer

Computer Networking: A Top Down Approach, 4th edition. Jim Kurose, Keith RossAddison-Wesley, July 2007.

A note on the use of these ppt slides:We’re making these slides freely available to all (faculty, students, readers). They’re in PowerPoint 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:� 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!)� 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.

Thanks and enjoy! JFK/KWR

All material copyright 1996-2007J.F Kurose and K.W. Ross, All Rights Reserved

22

Chapter 2: Application layer

❒ 2.1 Principles of network applications

❒ 2.2 Web and HTTP

❒ 2.3 FTP

❒ 2.4 Electronic Mail� SMTP, POP3, IMAP

❒ 2.5 DNS

❒ 2.6 P2P applications

❒ 2.7 Socket programming with TCP

❒ 2.8 Socket programming with UDP

23

Chapter 2: Application Layer

Our goals:

❒ conceptual, implementation aspects of network application protocols

� transport-layer service models

� client-server paradigm

� peer-to-peer paradigm

❒ learn about protocols by examining popular application-level protocols� HTTP

� FTP

� SMTP / POP3 / IMAP

� DNS

❒ programming network applications

� socket API

24

Some network apps

❒ e-mail

❒ web

❒ instant messaging

❒ remote login

❒ P2P file sharing

❒ multi-user network games

❒ streaming stored video clips

❒ voice over IP

❒ real-time video conferencing

❒ grid computing

25

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

applicationtransportnetworkdata linkphysical

applicationtransportnetworkdata linkphysical

applicationtransportnetworkdata linkphysical

26

Chapter 2: Application layer

❒ 2.1 Principles of network applications

❒ 2.2 Web and HTTP

❒ 2.3 FTP

❒ 2.4 Electronic Mail� SMTP, POP3, IMAP

❒ 2.5 DNS

❒ 2.6 P2P applications

❒ 2.7 Socket programming with TCP

❒ 2.8 Socket programming with UDP

❒ 2.9 Building a Web server

27

Application architectures

❒ Client-server

❒ Peer-to-peer (P2P)

❒ Hybrid of client-server and P2P

28

Client-server architecture

server:

� always-on host

� permanent IP address

� server farms for scaling

clients:� communicate with server

� may be intermittently connected

� may have dynamic IP addresses

� do not communicate directly with each other

client/server

29

Pure P2P architecture

❒ no always-on server

❒ arbitrary end systems directly communicate

❒ peers are intermittently connected and change IP addresses

Highly scalable but difficult to manage

peer-peer

30

Hybrid of client-server and P2P

Skype� voice-over-IP P2P application� centralized server: finding address of remote party: � client-client connection: direct (not through server)

Instant messaging� chatting between two users is P2P� 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

31

Processes communicating

Process: program running within a host.

❒ within same host, two processes communicate using inter-process communication (defined by OS).

❒ processes in different hosts communicate by exchanging messages

Client process: process that initiates communication

Server process: process that waits to be contacted

❒ Note: applications with P2P architectures have client processes & server processes

32

App-layer protocol defines

❒ Types of messages exchanged, � e.g., request, response

❒ Message syntax:� what fields in messages & how fields are delineated

❒ Message semantics � meaning of information in fields

❒ Rules for when and how processes send & respond to messages

Public-domain protocols:

❒ defined in RFCs

❒ allows for interoperability

❒ e.g., HTTP, SMTP

Proprietary protocols:

❒ e.g., Skype

33

What transport service does an app need?

Data loss

❒ some apps (e.g., audio) can tolerate some loss

❒ other apps (e.g., file transfer, telnet) require 100% reliable data transfer

Timing

❒ some apps (e.g., Internet telephony, interactive games) require low delay to be “effective”

Throughput

❒ some apps (e.g., multimedia) require minimum amount of throughput to be “effective”

❒ other apps (“elastic apps”) make use of whatever throughput they get

Security

❒ Encryption, data integrity, …

34

Transport service requirements of common apps

Application

file transfere-mail

Web documentsreal-time audio/video

stored audio/videointeractive gamesinstant messaging

Data loss

no lossno lossno lossloss-tolerant

loss-tolerantloss-tolerantno loss

Throughput

elasticelasticelasticaudio: 5kbps-1Mbpsvideo:10kbps-5Mbpssame as above few kbps upelastic

Time Sensitive

nononoyes, 100’s msec

yes, few secsyes, 100’s msecyes and no

35

Internet transport protocols services

TCP service:❒ 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:❒ 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?

36

Internet apps: application, transport protocols

Application

e-mailremote terminal access

Web file transfer

streaming multimedia

Internet telephony

Applicationlayer 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)

Underlyingtransport protocol

TCPTCPTCPTCPTCP or UDP

typically UDP

37

Chapter 2: Application layer

❒ 2.1 Principles of network applications � app architectures

� app requirements

❒ 2.2 Web and HTTP

❒ 2.4 Electronic Mail� SMTP, POP3, IMAP

❒ 2.5 DNS

❒ 2.6 P2P applications

❒ 2.7 Socket programming with TCP

❒ 2.8 Socket programming with UDP

38

Web and HTTP

First some jargon

❒ Web page consists of objects

❒ Object can be HTML file, JPEG image, Java applet, audio file,…

❒ Web page consists of base HTML-file which includes several referenced objects

❒ Each object is addressable by a URL

❒ Example URL:

www.someschool.edu/someDept/pic.gif

host name path name

39

HTTP overview

HTTP: hypertext transfer protocol

❒ 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

PC runningExplorer

Server running

Apache Webserver

Mac runningNavigator

HTTP request

HTTP reque

st

HTTP response

HTTP respo

nse

40

HTTP overview (continued)

Uses TCP:❒ client initiates TCP connection (creates socket) to server, port 80

❒ server accepts TCP connection from client

❒ HTTP messages (application-layer protocol messages) exchanged between browser (HTTP client) and Web server (HTTP server)

❒ TCP connection closed

HTTP is “stateless”❒ server maintains no information about past client requests

Protocols that maintain “state”are complex!

❒ past history (state) must be maintained

❒ if server/client crashes, their views of “state” may be inconsistent, must be reconciled

aside

41

HTTP connections

Nonpersistent HTTP

❒ At most one object is sent over a TCP connection.

Persistent HTTP

❒ Multiple objects can be sent over single TCP connection between client and server.

42

Nonpersistent HTTP

Suppose user enters URL www.someSchool.edu/someDepartment/home.index

1a. HTTP client initiates TCP connection to HTTP server (process) at www.someSchool.edu on port 80

2. HTTP client sends HTTP request message (containing URL) into TCP connection socket. Message indicates that client wants object someDepartment/home.index

1b. HTTP server at host www.someSchool.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

(contains text, references to 10

jpeg images)

43

Nonpersistent HTTP (cont.)

5. HTTP client receives response message containing html file, displays html. Parsing html file, finds 10 referenced jpeg objects

6. Steps 1-5 repeated for each of 10 jpeg objects

4. HTTP server closes TCP connection.

time

44

Non-Persistent HTTP: Response time

Definition of RTT: time for a small packet to travel from client to server and back.

Response time:

❒ one RTT to initiate TCP connection

❒ one RTT for HTTP request and first few bytes of HTTP response to return

❒ file transmission time

total = 2RTT+transmit time

time to transmit file

initiate TCPconnection

RTT

requestfile

RTT

filereceived

time time

45

Persistent HTTP

Nonpersistent HTTP issues:

❒ requires 2 RTTs per object

❒ OS overhead for each TCP connection

❒ browsers often open parallel TCP connections to fetch referenced objects

Persistent HTTP

❒ server leaves connection open after sending response

❒ subsequent HTTP messages between same client/server sent over open connection

❒ client sends requests as soon as it encounters a referenced object

❒ as little as one RTT for all the referenced objects

46

HTTP request message

❒ two types of HTTP messages: request, response

❒ HTTP request message:� ASCII (human-readable format)

GET /somedir/page.html HTTP/1.1Host: www.someschool.edu User-agent: Mozilla/4.0Connection: close Accept-language:fr

(extra carriage return, line feed)

request line(GET, POST,

HEAD commands)

headerlines

Carriage return, line feed

indicates end of message

47

HTTP request message: general format

48

Uploading form input

Post method:

❒ Web page often includes form input

❒ Input is uploaded to server in entity body

URL method:

❒ Uses GET method

❒ Input is uploaded in URL field of request line:

www.somesite.com/animalsearch?monkeys&banana

49

Method types

HTTP/1.0

❒ GET

❒ POST

❒ HEAD� asks server to leave requested object out of response

HTTP/1.1

❒ GET, POST, HEAD

❒ PUT� uploads file in entity body to path specified in URL field

❒ DELETE� deletes file specified in the URL field

50

HTTP response message

HTTP/1.1 200 OK Connection closeDate: 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 data data data ...

status line(protocolstatus code

status phrase)

headerlines

data, e.g., requestedHTML file

51

HTTP response status codes

200 OK� request succeeded, requested object later in this message

301 Moved Permanently� requested object moved, new location specified later in this message (Location:)

400 Bad Request� request message not understood by server

404 Not Found� requested document not found on this server

505 HTTP Version Not Supported

In first line in server->client response message.

A few sample codes:

52

Trying out HTTP (client side) for yourself

1. Telnet to your favorite Web server:

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

telnet cis.poly.edu 80

2. Type in a GET HTTP request:

GET /~ross/ HTTP/1.1Host: cis.poly.edu

By typing this in (hit carriagereturn twice), you sendthis minimal (but complete) GET request to HTTP server

3. Look at response message sent by HTTP server!

53

User-server state: cookies

Many major Web sites use cookies

Four components:1) cookie header line of HTTP response message

2) cookie header line in HTTP request message

3) cookie file kept on user’s host, managed by user’s browser

4) back-end database at Web site

Example:

❒ Susan always access Internet always from PC

❒ visits specific e-commerce site for first time

❒ when initial HTTP requests arrives at site, site creates:

� unique ID

� entry in backend database for ID

54

Cookies: keeping “state” (cont.)

client server

usual http response msg

usual http response msg

cookie file

one week later:

usual http request msgcookie: 1678 cookie-

specificaction

access

ebay 8734usual http request msg Amazon server

creates ID1678 for user create

entry

usual http response Set-cookie: 1678

ebay 8734amazon 1678

usual http request msgcookie: 1678 cookie-

spectificaction

accessebay 8734amazon 1678

backenddatabase

55

Cookies (continued)

What cookies can bring:

❒ authorization

❒ shopping carts

❒ recommendations

❒ user session state (Web e-mail)

Cookies and privacy:

❒ cookies permit sites to learn a lot about you

❒ you may supply name and e-mail to sites

aside

How to keep “state”:

❒ protocol endpoints: maintain state at sender/receiver over multiple transactions

❒ cookies: http messages carry state

56

Web caches (proxy server)

❒ 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

Goal: satisfy client request without involving origin server

client

Proxyserver

client

HTTP reque

st

HTTP respo

nse

HTTP request HTTP

reques

t

origin server

origin server

HTTP response HTTP

respon

se

57

More about Web caching

❒ cache acts as both client and server

❒ typically cache is installed by ISP (university, company, residential ISP)

Why Web caching?

❒ reduce response time for client request

❒ reduce traffic on an institution’s access link.

❒ Internet dense with caches: enables “poor”content providers to effectively deliver content (but so does P2P file sharing)

58

Caching example

Assumptions❒ 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%

❒ utilization on access link = 100%

❒ total delay = Internet delay + access delay + LAN delay

= 2 sec + minutes + milliseconds

originservers

publicInternet

institutionalnetwork 10 Mbps LAN

1.5 Mbps access link

institutionalcache

59

Caching example (cont)

possible solution❒ increase bandwidth of access link to, say, 10 Mbps

consequence❒ utilization on LAN = 15%

❒ utilization on access link = 15%

❒ Total delay = Internet delay + access delay + LAN delay

= 2 sec + msecs + msecs

❒ often a costly upgrade

originservers

publicInternet

institutionalnetwork 10 Mbps LAN

10 Mbps access link

institutionalcache

60

Caching example (cont)

possible solution: install cache

❒ suppose hit rate is 0.4

consequence❒ 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

originservers

publicInternet

institutionalnetwork 10 Mbps LAN

1.5 Mbps access link

institutionalcache

61

Conditional GET

❒ 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: <date>

❒ server: response contains no object if cached copy is up-to-date:

HTTP/1.0 304 Not Modified

cache server

HTTP request msgIf-modified-since:

<date>

HTTP responseHTTP/1.0

304 Not Modified

object not

modified

HTTP request msgIf-modified-since:

<date>

HTTP responseHTTP/1.0 200 OK

<data>

object modified