web server

25
WEB WEB WEB SERVERS WEB SERVERS SERVERS SERVERS Using C Language Sujeet Kumar Singh 1 Web Server Using C Language Web Developer

Upload: sujeet-singh

Post on 16-Jul-2015

338 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Web server

WEB WEB WEB SERVERS

WEB SERVERSSERVERSSERVERS

Using C Language

Sujeet Kumar Singh

1Web Server  Using C Language

Web Developer

Page 2: Web server

Introduction to Web Server

The primary function of a web server is to deliver web pages on the request toclients. This means delivery of HTML documents and any additional content thatmay be included by a document, such as images, style sheets and scripts.

A user agent, commonly a web browser or web crawler, initiates communicationby making a request for a specific resource using HTTP and the server respondswith the content of that resource or an error message if unable to do so Thewith the content of that resource or an error message if unable to do so. Theresource is typically a real file on the server's secondary memory, but this is notnecessarily the case and depends on how the web server is implemented.

WebRequest

ClientWeb ServerResponse

2Web Server  Using C Language

Page 3: Web server

Request and Response header

A full request can contain more than one line, and a blank line must be sent at the end toqsignify the end of the request.

GET /index.html HTTP/1.0 Host: www paulgriffiths netHost: www.paulgriffiths.net User-Agent: Lynx/2.8.1rel.2 libwww-FM/2.14 Accept-Encoding: gzip, compress Accept-Language: en <BLANK LINE>

A response generated by the web server may be look like as shown below A blankA response generated by the web server may be look like as shown below. A blank line must be sent at the end to signify the end of the request.

HTTP/1.0 200 OK Server: PGWebServ v0.1 Content-Type: text/html <BLANK LINE>

3Web Server  Using C Language

Page 4: Web server

Socket Programming in C

Socket programming is used to connect two processrunning on two different host in a networking whichhave an host address through a specified porthave an host address through a specified port.

A socket address is a combination of host address ofthe host and port address used by it.

Socket Address=Host Address+ Port  Address

4Web Server  Using C Language

Page 5: Web server

Primary Header Files used in Socket Programming

Include file sequence may affect processing (order is important!)

<sys/types.h> - prerequisite typedefs

<errno.h> - names for “errno” values (error numbers)

<sys/socket.h> - struct sockaddr; system prototypes and constants

<netdb.h.h> - network info lookup prototypes and structures

<netinet/in.h> - struct sockaddr_in; byte ordering macros

<arpa/inet.h> - utility function prototypes

5Web Server  Using C Language

Page 6: Web server

Various Steps in Development of Web Server in C

HTTP i ti ll t t b d t l hi h TCP/IP (th h itHTTP is essentially a text‐based protocol which runs over TCP/IP (though it can run over any transport protocol). The essential network steps are:

Create a listening socket

Accept a connection with itp

Fork a child process to service the connection, while the parent process  

goes back to accept more connections.

Read in the HTTP request

Send the HTTP response

Send the entity requested (e g an HTML document)Send the entity requested (e.g. an HTML document)

6Web Server  Using C Language

Page 7: Web server

Various Function of Web Server in C

V i C f ti ( d fi d f ti ) hi h i t t fVarious C functions (user defined function) which are important for implementation of a web server are as follows:

log()log()Logs messages to a log file. If the user requests an operation from

the Web server that is not allowed or can't be completed, then web servertries to inform the user directly. This is done by returning a fake Web page tothe user that includes the error message. Since this function is only calledfrom the child Web server process, the function can (once completed) exitand the main Web server process continues to allow further browserconnection requests. If this is not a recoverable error, then the process isconnection requests. If this is not a recoverable error, then the process isstopped.

web()D l i h h HTTP b d h d hDeals with the HTTP browser request and returns the data to the

browser. This function is called in a child process ‐‐ one for each Web request.It also allows the main Web server process to continue waiting for moreconnections. Checks are made to ensure the request is safe and can beqcompleted. After the checks have been made, it transmits the requested staticfile to the browser and exits.

7Web Server  Using C Language

Page 8: Web server

Various Function of Web Server in C

V i C f ti ( d fi d f ti ) hi h i t t fVarious C functions (user defined function) which are important for implementation of a web server are as follows:

main()main()This is the main Web server process function. After checking the

command parameters, it creates a socket for incoming browser requests, sitsin a loop accepting requests, and starts child processes to handle them. Itshould never end.

8Web Server  Using C Language

Page 9: Web server

Pseudo Code for the Functions

Pseudo code for the log() function is follows:Pseudo code for the log() function is follows:

log() {{ outputs error, sorry or log messages to the web server.log file

if t it it t th b f kif a sorry message, transmit it to the browser as a fake HTML response

if error or sorry message the program is stopped y g p g pp}

9Web Server  Using C Language

Page 10: Web server

Pseudo Code for the Functions

Pseudo code for the web() function is follows:Pseudo code for the web() function is follows:

web() - this function returns the request back to the browserbrowser{read from the socket the HTTP requestcheck it’s a simple GET commandh k t di t t d t th bcheck no parent directory requested to escape the web

servers home directoryif no file name given assume index.htmlcheck the file extension is valid and supportedppcheck the file is readable by opening ittransmit the HTTP header to the browsertransmit the file contents to the browserif LINUX sleep for one second to ensure the data arrivesif LINUX sleep for one second to ensure the data arrives at the browserStop}

10Web Server  Using C Language

Page 11: Web server

Pseudo Code for the Functions

Pseudo code for the main() function is follows:Pseudo code for the main() function is follows:

main(){{

check the directory supplied is sensible and not a security riskb dbecome a daemon processignore child programs (to avoid zombies when child processes stop)create a socket, bind it to a port number and start , plistening to the socketforever {

wait and accept incoming socket connectionfork a child processfork a child processif the child process then call the web functionelse close new connection

}}

11Web Server  Using C Language

Page 12: Web server

System Calls

Various system calls involved in request/response processes both at clientVarious system calls involved in request/response processes both at client and server side are as follows:

Server Parentsocket():Service

Clientsocket():Servicesocket():Service

bind():Port numberlisten():readyforever{

socket():Serviceconnect():Startwrite() & read()

{accept():wait for requestfork():create child

}Server Childwrite() & read()} write() & read()

12Web Server  Using C Language

Page 13: Web server

Socket System Calls

The socket() bind() listen() and accept() network system calls all workThe socket(), bind(), listen(), and accept() network system calls all worktogether to create a server process. They set up a socket ready for use tocommunicate over a network when combined. A socket is:

An input and output stream ‐‐ regular pipes and files, for example.

Remote access to or from a server ‐‐ when used over a network.

Bidirectional ‐‐ when you read and write the same socket at both ends.

Regular read and write functions ‐‐ used to send and receive data.

A stream (no natural structure) you have to decide the protocolA stream (no natural structure) ‐‐ you have to decide the protocol.

For HTTP ‐‐ the request message and response message are finished with a 

carriage return (CR or /r in C code) and a line feed (LF and /n in C code). The 

URL is terminated by a space character and the end of the requested file is 

highlighted by closing the socket. There are more complex alternatives in 

HTTP and many optional features, but this is the simplest way to do it.

13Web Server  Using C Language

Page 14: Web server

Socket System Calls : socket()

The socket() function creates the socket and returns the file descriptor whichThe socket() function creates the socket and returns the file descriptor, whichcan be used with any function that uses file descriptors, such as read, write,and close. The arguments tell the operating system what type of socket andcommunication you need.communication you need.

/* Create socket */

listener = socket(AF_INET, SOCK_STREAM, 0)

Note:‐listener is an integer type variablelistener  is an integer  type variableAF_INET, SOCK_STREAM are constants

14Web Server  Using C Language

Page 15: Web server

Socket System Calls : bind()

The bind() function attaches a particular port number to the socket When aThe bind() function attaches a particular port number to the socket. When aclient is trying to contact your server, it will use the IP address (often found byusing a DNS service to convert a hostname to an IP address) and the portnumber. The port number tells the operating system which service you wantnumber. The port number tells the operating system which service you wanton the server.

/* Assign socket address to socket */

bind(listener, (struct sockaddr *) &servaddr, sizeof(servaddr)

Note:‐sockaddr is a struct defined in socket hsockaddr is a struct defined in socket.hservaddr is struct type variable of sockaddr_in

15Web Server  Using C Language

Page 16: Web server

Socket System Calls : listen()

The listen() function call tells the operating system you are now ready toThe listen() function call tells the operating system you are now ready toaccept incoming requests. This is the final switch that makes the socketavailable to local and remote programs.

/* Make socket a listening socket */

listen(listener, LISTENQ)

Note:‐LISTENQ is a constantLISTENQ is a constant

16Web Server  Using C Language

Page 17: Web server

Socket System Calls : accept()

The accept() function does not return to your program until there is a socketThe accept() function does not return to your program until there is a socketconnection request to this IP address and port number. The accept() functionuses the file descriptor of the socket, but a new structure for the incomingconnection (struct sockaddr in) allows a server to check who is connecting toconnection (struct sockaddr_in) allows a server to check who is connecting toit.

/* Wait for connection */

(conn = accept(listener, NULL, NULL)

Note:‐conn is an integer type variableconn is an integer type variable

17Web Server  Using C Language

Page 18: Web server

Other System Calls

The fork() open() read() write() and close() are some other system callsThe fork(), open(), read(), write() and close() are some other system callsused for some other jobs. Fork() is used to create a sub process or a childprocess. Open(), read() and write() is work with the requested file by theclient. Close() is used to close the open connections.client. Close() is used to close the open connections.

18Web Server  Using C Language

Page 19: Web server

Other System Calls:fork()

Starts a child process In the parent it returns the process id (PID) of theStarts a child process. In the parent, it returns the process id (PID) of thechild, and in the child, it returns zero.

/* Fork child process to service connection */pid = fork()

Note:‐pid is an integer type variablepid is an integer type variable

19Web Server  Using C Language

Page 20: Web server

Other System Calls:open()

It is used to open the requested file by the clientIt is used to open the requested file by the client.

/* Open the directory server_root */open(server_root, O_RDONLY);

Note:‐Server root is a constant specifying the root directoryServer_root is a constant specifying the root directory.O_RDONLY is a open mode.

20Web Server  Using C Language

Page 21: Web server

Other System Calls:read()

It is used to read the requested file by the client It is used by both client asIt is used to read the requested file by the client. It is used by both client aswell as server to read files.

/* Reading the resource*/read(resource, &c, 1))

Note:‐Resouce is a contant specifying the resource nameResouce is a contant specifying the resource namec is char type variable1 is the read mode

21Web Server  Using C Language

Page 22: Web server

Other System Calls:write()

It is used to write the requested file by the client It is used by both client asIt is used to write the requested file by the client. It is used by both client aswell as server to write files.

/* Writing to the connection */write(conn, &c, 1)

Note:‐conn is an integer type constant representing accepted connectionconn is an integer type constant representing accepted connection.c is char type variable1 is the read mode

22Web Server  Using C Language

Page 23: Web server

Other System Calls:close()

It is used to close the listening socket and connected socketIt is used to close the listening socket and connected socket.

/* Close listening socket*/close(listener)

/* Close connected socket and exit */close(conn)close(conn)

23Web Server  Using C Language

Page 24: Web server

Sample TCP Client/Server Session

Various socket system calls called at both server and client at different levelsVarious socket system calls called at both server and client at different levelsare shown below:

socket()

Iterative Server

Remote Client

bind()

listen()

socket()

gethostbyname()

accept()

recv()/send()

connect()

recv()/send()recv()/send()

close()

recv()/send()

close()

24Web Server  Using C Language

Page 25: Web server

25Web Server  Using C Language