42
1 2: Application Layer 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach Featuring the Internet, 3 rd edition. Jim Kurose, Keith Ross Addison-Wesley, July 2004. Thanks and enjoy! JFK/KWR All material copyright 1996-2005 J.F Kurose and K.W. Ross, All Rights Reserved 2: Application Layer 2 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 file sharing 2.7 Socket programming with TCP 2.8 Socket programming with UDP 2.9 Building a Web server

Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

1

2: Application Layer 1

Chapter 2Application Layer

Computer Networking: A Top Down Approach Featuring the Internet, 3rd edition. Jim Kurose, Keith RossAddison-Wesley, July 2004.

Thanks and enjoy! JFK/KWR

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

2: Application Layer 2

Chapter 2: Application layer

2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic Mail

SMTP, POP3, IMAP2.5 DNS

2.6 P2P file sharing2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server

Page 2: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

2

2: Application Layer 3

Chapter 2: Application LayerOur goals:

conceptual, implementation aspects of network application protocols

transport-layer service modelsclient-server paradigmpeer-to-peer paradigm

learn about protocols by examining popular application-level protocols

HTTPFTPSMTP / POP3 / IMAPDNS

programming network applications

socket API

2: Application Layer 4

Some network apps

E-mailWebInstant messagingRemote loginP2P file sharingMulti-user network gamesStreaming stored video clips

Internet telephoneReal-time video conferenceMassive parallel computing

Page 3: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

3

2: Application Layer 5

Creating a network appWrite programs that

run on different end systems andcommunicate over a network.e.g., Web: Web server software communicates with browser software

little software written for devices in network core

network core devices do not run user application codeapplication on end systems allows for rapid app development, propagation

applicationtransportnetworkdata linkphysical

applicationtransportnetworkdata linkphysical

applicationtransportnetworkdata linkphysical

2: Application Layer 6

Chapter 2: Application layer

2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic Mail

SMTP, POP3, IMAP2.5 DNS

2.6 P2P file sharing2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server

Page 4: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

4

2: Application Layer 7

Application architectures

Client-serverPeer-to-peer (P2P)Hybrid of client-server and P2P

2: Application Layer 8

Client-server architectureserver:

always-on hostpermanent IP addressserver farms for scaling

clients:communicate with servermay be intermittently connectedmay have dynamic IP addressesdo not communicate directly with each other

Page 5: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

5

2: Application Layer 9

Pure P2P architecture

no always-on serverarbitrary end systems directly communicatepeers are intermittently connected and change IP addressesexample: Gnutella

Highly scalable

But difficult to manage

2: Application Layer 10

Hybrid of client-server and P2P

NapsterFile transfer P2PFile search centralized:

• Peers register content at central server• Peers query same central server to locate content

Instant messagingChatting between two users is P2PPresence detection/location centralized:

• User registers its IP address with central server when it comes online

• User contacts central server to find IP addresses of buddies

Page 6: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

6

2: Application Layer 11

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

2: Application Layer 12

Sockets

process sends/receives messages to/from its socketsocket analogous to door

sending process shoves message out doorsending process relies on transport infrastructure on other side of door which brings message to socket at receiving process

process

TCP withbuffers,variables

socket

host orserver

process

TCP withbuffers,variables

socket

host orserver

Internet

controlledby OS

controlled byapp developer

API: (1) choice of transport protocol; (2) ability to fix a few parameters (lots more on this later)

Page 7: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

7

2: Application Layer 13

Addressing processesFor a process to receive messages, it must have an identifierA host has a unique32-bit IP addressQ: does the IP address of the host on which the process runs suffice for identifying the process?Answer: No, many processes can be running on same host

Identifier includes both the IP address and port numbersassociated with the process on the host.Example port numbers:

HTTP server: 80Mail server: 25

More on this later

2: Application Layer 14

App-layer protocol defines

Types of messages exchanged, e.g., request & response messagesSyntax of message types: what fields in messages & how fields are delineatedSemantics of the fields, i.e., meaning of information in fieldsRules for when and how processes send & respond to messages

Public-domain protocols:defined in RFCsallows for interoperabilitye.g., HTTP, SMTP

Proprietary protocols:e.g., KaZaA

Page 8: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

8

2: Application Layer 15

What transport service does an app need?

Data losssome apps (e.g., audio) can tolerate some lossother apps (e.g., file transfer, telnet) require 100% reliable data transfer

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

Bandwidthsome apps (e.g., multimedia) require minimum amount of bandwidth to be “effective”other apps (“elastic apps”) make use of whatever bandwidth they get

2: Application Layer 16

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

Bandwidth

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

Time Sensitive

nononoyes, 100’s msec

yes, few secsyes, 100’s msecyes and no

Page 9: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

9

2: Application Layer 17

Internet transport protocols services

TCP service:connection-oriented: setup required between client and server processesreliable transport between sending and receiving processflow control: sender won’t overwhelm receiver congestion control: throttle sender when network overloadeddoes not provide: timing, minimum bandwidth guarantees

UDP service:unreliable data transfer between sending and receiving processdoes not provide: connection setup, reliability, flow control, congestion control, timing, or bandwidth guarantee

Q: why bother? Why is there a UDP?

2: Application Layer 18

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]proprietary(e.g. RealNetworks)proprietary(e.g., Vonage,Dialpad)

Underlyingtransport protocol

TCPTCPTCPTCPTCP or UDP

typically UDP

Page 10: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

10

2: Application Layer 19

Chapter 2: Application layer

2.1 Principles of network applications

app architecturesapp requirements

2.2 Web and HTTP2.4 Electronic Mail

SMTP, POP3, IMAP2.5 DNS

2.6 P2P file sharing2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server

2: Application Layer 20

Web and HTTP

First some jargonWeb page consists of objectsObject can be HTML file, JPEG image, Java applet, audio file,…Web page consists of base HTML-file which includes several referenced objectsEach object is addressable by a URLExample URL:

www.someschool.edu/someDept/pic.gif

host name path name

Page 11: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

11

2: Application Layer 21

HTTP overview

HTTP: hypertext transfer protocolWeb’s application layer protocolclient/server model

client: browser that requests, receives, “displays” Web objectsserver: Web server sends objects in response to requests

HTTP 1.0: RFC 1945HTTP 1.1: RFC 2068

PC runningExplorer

Server running

Apache Webserver

Mac runningNavigator

HTTP request

HTTP request

HTTP response

HTTP response

2: Application Layer 22

HTTP overview (continued)

Uses TCP:client initiates TCP connection (creates socket) to server, port 80server accepts TCP connection from clientHTTP 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 maintainedif server/client crashes, their views of “state” may be inconsistent, must be reconciled

aside

Page 12: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

12

2: Application Layer 23

HTTP connections

Nonpersistent HTTPAt most one object is sent over a TCP connection.HTTP/1.0 uses nonpersistent HTTP

Persistent HTTPMultiple objects can be sent over single TCP connection between client and server.HTTP/1.1 uses persistent connections in default mode

2: Application Layer 24

Nonpersistent HTTPSuppose 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)

Page 13: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

13

2: Application Layer 25

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

2: Application Layer 26

Response time modelingDefinition of RRT: time to

send a small packet to travel from client to server and back.

Response time:one RTT to initiate TCP connectionone RTT for HTTP request and first few bytes of HTTP response to returnfile transmission time

total = 2RTT+transmit time

time to transmit file

initiate TCPconnection

RTT

requestfile

RTT

filereceived

time time

Page 14: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

14

2: Application Layer 27

Persistent HTTP

Nonpersistent HTTP issues:requires 2 RTTs per objectOS overhead for each TCP connectionbrowsers often open parallel TCP connections to fetch referenced objects

Persistent HTTPserver leaves connection open after sending responsesubsequent HTTP messages between same client/server sent over open connection

Persistent without pipelining:client issues new request only when previous response has been receivedone RTT for each referenced object

Persistent with pipelining:default in HTTP/1.1client sends requests as soon as it encounters a referenced objectas little as one RTT for all the referenced objects

2: Application Layer 28

HTTP request message

two types of HTTP messages: request, responseHTTP 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

Page 15: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

15

2: Application Layer 29

HTTP request message: general format

2: Application Layer 30

Uploading form input

Post method:Web page often includes form inputInput is uploaded to server in entity body

URL method:Uses GET methodInput is uploaded in URL field of request line:

www.somesite.com/animalsearch?monkeys&banana

Page 16: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

16

2: Application Layer 31

Method types

HTTP/1.0GETPOSTHEAD

asks server to leave requested object out of response

HTTP/1.1GET, POST, HEADPUT

uploads file in entity body to path specified in URL field

DELETEdeletes file specified in the URL field

2: Application Layer 32

Exemple POSTPOST /path/script.cgi HTTP/1.0

From: [email protected]

User-Agent: HTTPTool/1.0

Content-Type: application/x-www-form-urlencoded

Content-Length: 32

home=Cosby&favorite+flavor=flies

Page 17: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

17

2: Application Layer 33

POST

dans une requête POST il n'y a pas qu'un entête: les données sont dans le corps du messageles données définissent des variables qui seront utilisées par le CGIl'url requise est normalement un programmela réponse HTTP est normalement la sortie d'un programme

2: Application Layer 34

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(protocol

status codestatus phrase)

headerlines

data, e.g., requestedHTML file

Page 18: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

18

2: Application Layer 35

HTTP response status codes

200 OKrequest succeeded, requested object later in this message

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

400 Bad Requestrequest message not understood by server

404 Not Foundrequested document not found on this server

505 HTTP Version Not Supported

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

2: Application Layer 36

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!

Page 19: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

19

2: Application Layer 37

Méthodes httpGET

C'est la méthode la plus courante pour demander une ressource. Une requête GET est sans effet sur la ressource, il doit être possible de répéter la requête sans effet.

HEAD Cette méthode ne demande que des informations sur la ressource, sans demander la ressource elle-même.

POST Cette méthode doit être utilisée lorsqu'une requête modifie la ressource.

OPTIONS Cette méthode permet d'obtenir les options de communication d'une ressource ou du serveur en général.

CONNECT Cette méthode permet d'utiliser un proxy comme un tunnel de communication.

TRACE Cette méthode demande au serveur de retourner ce qu'il a reçu, dans le but de tester et effectuer un diagnostic sur la connexion.

PUT Cette méthode permet d'ajouter une ressource sur le serveur.

DELETE Cette méthode permet de supprimer une ressource du serveur.

2: Application Layer 38

entêtesHost

Permet de préciser le site Web concerné par la requête, ce qui est nécessaire pour un serveur hébergeant plusieurs sites à la même adresse IP (name basedvirtual host, hôte virtuel basé sur le nom). (Obligatoire)

RefererIndique l'URI du document qui a donné un lien sur la ressource demandée. Cet en-tête permet aux webmasters d'observer d'où viennent les visiteurs.

User-Agent Indique le logiciel utilisé pour se connecter. Il s'agit généralement d'un navigateur Web ou d'un robot d'indexation.

Connectionconnection persistante ou non

AcceptCet en-tête liste les types MIME de contenu acceptés par le client. Le caractère étoile * peut servir à spécifier tous les types / sous-types.

Accept-CharsetSpécifie les encodages de caractères acceptés.

Accept-LanguageSpécifie les langages acceptés.

Page 20: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

20

2: Application Layer 39

RéponsesDate

Moment auquel le message est généré. Server

Indique quel modèle de serveur HTTP répond à la requête. Content-Length

Indique la taille en octets de la ressource. Content-Type

Indique le type MIME de la ressource. Expires

Indique le moment après lequel la ressource devrait être considérée obsolète ; permet aux navigateurs Web de déterminer jusqu'à quand garder la ressource en mémoire cache.

Last-ModifiedIndique la date de dernière modification de la ressource demandée.

2: Application Layer 40

Let’s look at HTTP in action

telnet exampleEthereal example

Page 21: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

21

2: Application Layer 41

CGI

Common Gateway Interfaceexécuter du code du côté serveurPassage de paramètre par la méthode POST ou la méthode GETVariables d'environnement

2: Application Layer 42

Exemple

en shell: date.cgi#!/bin/sh

tmp=`/bin/date`

cat << ! Content-type: text/html <HTML><HEAD><TITLE>Script Cgi</TITLE></HEAD> <BODY> <CENTER> <H1>La date courante sur le serveur est</H1> $tmp </CENTER> </BODY> </HTML>

!l'URL affichera la date

Page 22: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

22

2: Application Layer 43

Avec un formulaire:<HTML><HEAD><TITLE>Formulaire simple</TITLE></HEAD><BODY><H2>Répondez aux questions suivantes</H2><FORM ACTION="http://www.monsite.com/cgi-bin/treat.pl"

METHOD=GET>Prénom : <INPUT TYPE="text" NAME=prenom SIZE=20><BR>Nom : <INPUT TYPE="text" NAME=nom SIZE=20><BR>Age : <SELECT NAME=age>

<OPTION>- de 18 ans<OPTION>19 à 40 ans<OPTION>41 à 60 ans<OPTION>+ de 60 ans

</SELECT><BR><INPUT TYPE=submit VALUE="Envoyer"> <INPUT TYPE=reset

VALUE="Remettre à zéro"></FORM></BODY>

2: Application Layer 44

Résultat

par la méthode get codage des paramètres:prenom=Hugues&nom=Fauconnier&age=41+%E0+60+ans

le navigateur génère l'url:http://www.monsite.com/cgi-

bin/treat.pl?prenom=Hugues&nom=Fauconnier&age=41+%E0+60+ans

Avec la méthode POSThttp://www.monsite.com/cgi-bin/treat.pl

prenom=Hugues&nom=Fauconnier&age=41

Page 23: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

23

2: Application Layer 45

Traitement en perl

fichier perl

2: Application Layer 46

Paramètres

Les paramètres sont accessibles par l'intermédiaire de la variable d'environnement QUERY_STRING

Page 24: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

24

2: Application Layer 47

Variables d'environnement

SERVER_SOFTWARE Le nom et la version du serveur HTTP répondant à la requête. (Format : nom/version)

SERVER_NAME Le nom d'hôte, alias DNS ou adresse IP du serveur.

GATEWAY_INTERFACE La révision de la spécification CGI que le serveur utilise. (Format : CGI/révision)

2: Application Layer 48

Variables…SERVER_PROTOCOL

Le nom et la révision du protocole dans lequel la requête a étéfaite (Format : protocole/révision)

SERVER_PORT Le numéro de port sur lequel la requête a été envoyée.

REQUEST_METHOD La méthode utilisée pour faire la requête. Pour HTTP, elle contient généralement « GET » ou « POST ».

PATH_INFO Le chemin supplémentaire du script tel que donné par le client. Par exemple, si le serveur héberge le script « /cgi-bin/monscript.cgi » et que le client demande l'url «http://serveur.org/cgi-bin/monscript.cgi/marecherche », alors PATH_INFO contiendra « marecherche ».

PATH_TRANSLATED Contient le chemin demandé par le client après que les conversions virtuel → physique aient été faites par le serveur.

Page 25: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

25

2: Application Layer 49

VariablesSCRIPT_NAME

Le chemin virtuel vers le script étant exécuté. Exemple : « /cgi-bin/script.cgi »

QUERY_STRING Contient tout ce qui suit le « ? » dans l'URL envoyée par le client. Toutes les variables provenant d'un formulaire envoyéavec la méthode « GET » sera contenue dans le QUERY_STRING sous la forme « var1=val1&var2=val2&... ».

REMOTE_HOST Le nom d'hôte du client. Si le serveur ne possède pas cette information (par exemple, lorsque la résolution DNS inverse est désactivée), REMOTE_HOST sera vide.

REMOTE_ADDR L'adresse IP du client.

AUTH_TYPE Le type d'identification utilisé pour protéger le script (s’il est protégé et si le serveur supporte l'identification).

2: Application Layer 50

VariablesAUTH_TYPE

Le type d'identification utilisé pour protéger le script (s’il est protégé et si le serveur supporte l'identification).

REMOTE_USER Le nom d'utilisateur du client, si le script est protégé et si le serveur supporte l'identification.

REMOTE_IDENT Nom d'utilisateur (distant) du client faisant la requête. Le serveur doit supporter l'identification RFC 931. Cette variable devraient être utilisée à des fins de journaux seulement.

CONTENT_TYPE Le type de contenu attaché à la requête, si des données sont attachées (comme lorsqu'un formulaire est envoyé avec la méthode « POST »).

CONTENT_LENGTH La longueur du contenu envoyé par le client.

Page 26: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

26

2: Application Layer 51

Variables

HTTP_ACCEPT • Les types de données MIME que le client accepte de recevoir.

• Exemple : text/*, image/jpeg, image/png, image/*, */*

HTTP_ACCEPT_LANGUAGE • Les langages dans lequel le client accepte de recevoir la réponse.

• Exemple : fr_CA, fr

HTTP_USER_AGENT • Le navigateur utilisé par le client.

• Exemple : Mozilla/5.0 (compatible; Konqueror/3; Linux)

2: Application Layer 52

User-server state: cookies

Many major Web sites use cookies

Four components:1) cookie header line of

HTTP response message2) cookie header line in

HTTP request message3) cookie file kept on

user’s host, managed by user’s browser

4) back-end database at Web site

Example:Susan access Internet always from same PCShe visits a specific e-commerce site for first timeWhen initial HTTP requests arrives at site, site creates a unique ID and creates an entry in backend database for ID

Page 27: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

27

2: Application Layer 53

Cookies: keeping “state” (cont.)

client serverusual http request msgusual http response +Set-cookie: 1678

usual http request msgcookie: 1678

usual http response msg

usual http request msgcookie: 1678

usual http response msg

cookie-specificaction

cookie-spectific

action

servercreates ID

1678 for user

entry in backend

database

access

access

Cookie file

amazon: 1678ebay: 8734

Cookie file

ebay: 8734

Cookie file

amazon: 1678ebay: 8734

one week later:

2: Application Layer 54

Cookies (continued)What cookies can bring:

authorizationshopping cartsrecommendationsuser session state (Web e-mail)

Cookies and privacy:cookies permit sites to learn a lot about youyou may supply name and e-mail to sitessearch engines use redirection & cookies to learn yet moreadvertising companies obtain info across sites

aside

Page 28: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

28

2: Application Layer 55

Web caches (proxy server)

user sets browser: Web accesses via cachebrowser 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 request

HTTP request

HTTP response

HTTP response

HTTP request

HTTP response

origin server

origin server

2: Application Layer 56

More about Web caching

Cache acts as both client and serverTypically 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)

Page 29: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

29

2: Application Layer 57

Caching example Assumptions

average object size = 100,000 bitsavg. request rate from institution’s browsers to origin servers = 15/secdelay from institutional router to any origin server and back to router = 2 sec

Consequencesutilization 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

2: Application Layer 58

Caching example (cont)Possible solution

increase bandwidth of access link to, say, 10 Mbps

Consequencesutilization on LAN = 15%utilization on access link = 15%Total delay = Internet delay + access delay + LAN delay

= 2 sec + msecs + msecsoften a costly upgrade

originservers

publicInternet

institutionalnetwork 10 Mbps LAN

10 Mbps access link

institutionalcache

Page 30: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

30

2: Application Layer 59

Caching example (cont)

Install cachesuppose hit rate is .4

Consequence40% requests will be satisfied almost immediately60% requests satisfied by origin serverutilization 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 + milliseconds < 1.4 secs

originservers

publicInternet

institutionalnetwork 10 Mbps LAN

1.5 Mbps access link

institutionalcache

2: Application Layer 60

Conditional GET

Goal: don’t send object if cache has up-to-date cached versioncache: specify date of cached copy in HTTP requestIf-modified-since:

<date>

server: response contains no object if cached copy is up-to-date: HTTP/1.0 304 Not

Modified

cache serverHTTP 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

Page 31: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

31

2: Application Layer 61

Compléments Javascript

Code qui s'exécute du côté du clientcalcul localcontrôle d'une zone de saisieaffichage d'alertefenêtres menus etc..

Balise :<SCRIPT languge="JavaScript1.2">le code...</SCRIPT>

2: Application Layer 62

Exemple: bonjour<HTML><HEAD><TITLE>Très facile</TITLE></HEAD>

<SCRIPT language="JavaScript1.2">function bonjour(){

alert ("Bonjour madame, bonjour monsieur");}</SCRIPT>

<BODY bgcolor="WHITE" onLoad="bonjour();">

<H1>Bonjour</H1>

</BODY></HTML>

Page 32: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

32

2: Application Layer 63

Un peu plus: minicalculHTML><HEAD><TITLE>Petit calcul</TITLE></HEAD><BODY bgcolor='WHITE'>

<script language='JavaScript1.2' src='calcul.js'></script><script language='JavaScript1.2' src='fenetre.js'></script><script language='JavaScript1.2' src='ctrl.js'></script>

<CENTER><H1>Calcul</H1></CENTER>

Un petit exemple de formulaire.<P>Création d'une <A href='#A' onClick='afficheDoc();'>fenêtre avec JavaScript</A>

2: Application Layer 64

Suite

<FORM ACTION='Simul.html' METHOD='POST' NAME='Simul'><CENTER><TABLE BORDER=3><TR><TD>Argument 1

<TD> <INPUT TYPE='TEXT' SIZE=20 NAME='arg1' onChange='calcul();'></TR><TR><TD>* Argument 2

<TD> <INPUT TYPE='TEXT' SIZE=20 NAME='arg2' onChange='calcul();'>

</TR>

<TR><TD>Résultat=<TD> <INPUT TYPE='TEXT' SIZE=20

NAME='res' > </TR>

</TABLE><INPUT TYPE='BUTTON' VALUE='Vérifier' onClick='ctrl();'><INPUT TYPE='RESET' VALUE='Effacer tout'

onClick=' if (!confirm("Vraiment vous voulez effacer ?")) exit;'></CENTER></FORM></BODY></HTML>

Page 33: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

33

2: Application Layer 65

Fichiers jsctrl.js calcul

function ctrl(){if (isNaN(window.document.Simul.res.value )){alert ("Valeur incorrecte : " +

document.Simul.res.value + "?");document.forms[0].res.focus();

}}

function calcul(){

v1=document.forms[0].arg1.value;v2=document.forms[0].arg2.value;document.forms[0].res.value = v2*v1 ;

}

2: Application Layer 66

suite et finfenetre.js

function afficheDoc(){

options = "width=300,height=200";fenetre = window.open('','MU',options);

fenetre.document.open();manuel = "<HTML><HEAD><TITLE>Documentation</TITLE></HEAD>"

+ "<BODY bgcolor='white'>" + "Il n'y a pas besoin d'aide "+ " c'est facile."+ " Bonne chance !</BODY></HTML>";

fenetre.document.write(manuel);fenetre.document.close();

}

Page 34: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

34

2: Application Layer 67

Compléments: php

php est un langage de script pour les serveurs websde nombreuses fonctions permettent de traiter les requêtes httpici on est du côté du serveur…

2: Application Layer 68

Exemple simple<HTML> <HEAD><TITLE>Exemple très simple</TITLE></HEAD><BODY><H1>Exemple</H1>le <?php echo Date ("j/m/Y à H:i:s"); ?><P>

<?phpecho "Client :" . $_SERVER['HTTP_USER_AGENT'] . "<BR>";echo "Adresse IP client:".$_SERVER['REMOTE_ADDR']."<BR>";echo "Server: " . $_SERVER['SERVER_NAME'];

?>

</BODY></HTML>

Page 35: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

35

2: Application Layer 69

Résultat

Exemplele 8/11/2006 à 15:54:29 Client :Mozilla/4.0

(compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; InfoPath.1)

Adresse IP client:127.0.0.1Server: localhost

2: Application Layer 70

Reçu par le client<HTML> <HEAD><TITLE>Exemple très simple</TITLE></HEAD><BODY>

<H1>Exemple</H1>

le 8/11/2006 à 15:54:29<P>

Client :Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; InfoPath.1)<BR>Adresse IP client:127.0.0.1<BR>Server: localhost

</BODY></HTML>

Page 36: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

36

2: Application Layer 71

Php

On est ici côté serveur:les balises <?php> <?> sont interprétées par le serveur (apache par exemple) et servent àgénérer la page html reçu par le client

Mais surtout php permetd'accéder aux variables d'environnementd'utiliser de nombreuses fonctionsalités

• sessions, paramètres etc.

Php sert souvent d'interface pour MySqlserveur simple de bases de données

2: Application Layer 72

Php

pas de typage ni de déclaration des variables$v est remplacé par la valeur de v (et permet aussi l'affectation)echo "$v";constantes define("PI, 3.1415);types des variables

numériques• $i=1;• $v=3.14;

chaînes de caractères (expressions régulières)• $nom="Hugues";• ',",{}

Page 37: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

37

2: Application Layer 73

php

tableauxindicés

• $tab[0]="un";• $tab=array("un","deux","trois");

associatifs• $m=array("un"=>"one",

"deux"=>"two");• $m["trois"]="three";

next() prev() key() currentdo{echo "Clé=key($m).Valeur= current($m)"}while(next($mes));foreach($m as $cle =>$val){echo "Clé=$cle.Valeur=$val";}

2: Application Layer 74

Php

structures de contrôlesif if elsewhiledo whileforforeach

• break, continue

Page 38: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

38

2: Application Layer 75

fonctionsfunction Nom([$arg1, $arg2, ...]){

corps}passage par valeur (et pas références &)exemplesfunction Add($i,$j){

$somme= $i + $j;return $somme;

}function Add($i,$j,&$somme){

$somme= $i + $j;}

2: Application Layer 76

divers

variables automatiques (locales)statiques (comme en C)globales

classes et objets

Page 39: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

39

2: Application Layer 77

Pour le serveur…

tableaux associatifs prédéfinis$_SERVER: environnement serveur

• REQUEST_METHOD• QUERY_STRING• CONTENT_LENGTH• SERVER_NAME• PATH_INFO• HTTP_USER_AGENT• REMOTE_ADDR• REMOTE_HOST• REMOTE_USER• REMOTE_PASSWORD

2: Application Layer 78

Suite

Autres tableaux$_ENV : environnement système$_COOKIE$_GET$_POST$_FILES$_REQUEST (variables des 4 précédents$_SESSION$GLOBALS les variables globales du scritp

Page 40: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

40

2: Application Layer 79

Cookies et php<?php// Est-ce que le Cookie existe ?if (isSet($_COOKIE['compteur'])){

$message = "Vous êtes déjà venu {$_COOKIE['compteur']} fois "

. "me rendre visite<BR>\n";// On incrémente le compteur $valeur = $_COOKIE['compteur'] + 1;

}else{

// Il faut créer le cookie avec la valeur 1$message = "Bonjour, je vous envoie un cookie<BR>\n";$valeur = 1;

} // Envoi du cookieSetCookie ("compteur", $valeur);?>

2: Application Layer 80

Cookies et php (fin)

<HTML><HEAD>

<TITLE>Les cookies</TITLE>

</HEAD>

<BODY>

<H1>Un compteur d'accès au site avec cookie</H1>

<?php echo $message; ?>

</BODY></HTML>

Page 41: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

41

2: Application Layer 81

En utilisant les sessions<?php// La fonction session_start fait tout le travail session_start();

?><HTML><HEAD><TITLE>Les cookies</TITLE>

</HEAD><BODY>

<H1>Un compteur d'accès au site avec Session</H1>

2: Application Layer 82

Fin <?phpif (!isSet($_SESSION['cp'])){

$_SESSION['cp']=1;echo "C'est la première fois, votre id

est:".session_id()."<BR>";}else{

$_SESSION['cp']++;echo "C'est votre ".$_SESSION['cp']." n-ième

connexion";if($_SESSION['cp']>10){

echo "on vous a trop vu"."<BR>";session_destroy();

}}?></BODY></HTML>

Page 42: Chapter 2 Application Layerhf/verif/ens/internet/http/http.pdf · 2: Application Layer 3 Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application

42

2: Application Layer 83

session

session_start()session_destroy()session_id()

on peut associer des variables à la session par le tableau associatif $_SESSIONelle sera accessible à chaque session_start() jusqu'au session_destroy() pour toute connexion qui fournit le session_id().