SlideShare a Scribd company logo
1 of 29
1
CGI
Common Gateway Interface
Server-side Programming
Lecture
Rich Internet Applications
 An RIA is a web application that provides the
client with the features and functionality of
desktop applications
 Requires transferring the processing from the
server to the client
 Javascript is one enabling technology for a RIA
RIAs in the Internet client-server
model
Client (browser) Web server
Client does
all the
processing
(eg play
videos as
they come
in)
Data (eg
multimedia) stay
on the server
HTTP request for resource
Server sends code but
keeps data
Some technologies that support
RIA development
 Javascript (and associated ECMA dialects)
 Adobe Flash
 Flash player and IDE
 Java Applets and Java Webstart (see later)
 AJAX
 Asynchronous JavaScript and XML
Server-Side Programming
 Lots of programs/applications designed to
run on the machines on which they are
installed
 How can a remote client request access to
these?
CGI programming
 CGI => Common Gateway Interface
 A protocol for interfacing local applications with a web
server
 Sequence of steps
 Client sends URL request
 Program runs at the server side
 Output is collected and sent back to the client
 Often the output is an HTML “built” by the server
CGI using HTML and C language
 Why do we need CGI?
 To read the information on the forms (HTML)
 To build a customised HTML response to users
 To understand the concept lets use C at first...
 CGI is completely independent of the language
and OS
 CGI is implemented in (almost) all webservers
CGI programs can be written in any language
supported by the server.
This includes compiled programming languages,
such as C and C++; interpreted languages, such
as Perl, Python, Ruby, and languages, such as
Java, that lie somewhere in between.
Hello World!
#include <iostream>
using namespace std;
int main(void) {
cout << "Content-Type: text/html;charset=us-asciinn";
/** Print the HTML response page to STDOUT. **/
cout << "<html>n";
cout << "<head><title>CGI Output</title></head>n";
cout << "<body>n" ;
cout << "<h1>Hello, world.</h1>n";
cout << "this is my first CGI" << "n";
cout << "</body>n";
cout << "</html>n";
return 0;
}
Compile, then place the executable inside cgi-bin directory of xitami
Test using a browser, URL: http://localhost:8080/cgi-bin/helloworld
How to submit data using forms
 GET
 http://www.someurl/cgi-bin/script?var1=1&var2=4
 Web server has a special directory called cgi-bin
 Two variables:
 var1=1
 var2=4
 Special characters are encoded
 ~ would be encoded as %7E (% followed by ASCII
code)
GET
 So variables from the forms go on URL
 The environment variable is:
 $QUERY_STRING
 Most browsers limit the size of URLs (256
chars, some more, e.g., IE is 2083 chars)
 When you have too much data, use POST
instead...
Multiply example – the HTML file
<form method="get"
action="http://it026945/cgi-bin/testingcgi/multiply">
<div><label>Number 1: <input name="m" size="5"></label></div>
<div><label>Number 2: <input name="n" size="5"></label></div>
<div><input type="submit" value="Multiply"></div>
</form>
Multiply example
Action="http://it026945/cgi-bin/testingcgi/multiply">
 multiply is an executable under:/var/www/cgi-bin/
 with x permissions for all!
 Variables in URL:
 After submission, URL becomes:
 http://it026945/cgi-bin/testingcgi/multiply?m=1&n=2
Example
SERVER-SIDE: Response
CLIENT-SIDE
Multiply example – the C file
#include <stdio.h>
#include <stdlib.h>
#include <windows.h> //for Windows operating system – Sleep()
int main(void)
{
char *data;
long m,n;
printf("%s%c%cn","Content-Type:text/html;charset=iso-8859-1",13,10);
printf("<TITLE>Multiplication results</TITLE>n");
printf("<H3>Multiplication results</H3>n");
data = getenv("QUERY_STRING");//here it is your data!!!
if(data == NULL)
printf("<P>Error!");
else if(sscanf(data,"m=%ld&n=%ld",&m,&n)!=2)//check for 2 inputs
printf("<P>Error! Invalid data.");
else
printf("<P>%ld * %ld = %ld.",m,n,m*n);
//Sleep(1000); // uncomment that to see who runs the process...
return 0;
}
//from http://www.cs.tut.fi/~jkorpela/forms/cgic.html (July2010)
Recall the sscanf() function in C
• On success, the function returns the number of items
successfully read.
• This count can match the expected number of readings or
fewer, even zero, if a matching failure happens.
• In the case of an input failure before any data could be
successfully read, EOF is returned.
int sscanf ( const char * str, const char * format, ...);
Read formatted data from string
char * getenv ( const char * name );
Get environment string
•Retrieves a C string containing the value of the environment
variable whose name is specified as argument.
•If the requested variable is not part of the environment list, the
function returns a NULL pointer.
•The string pointed by the pointer returned by this function shall
not be modified by the program.
•The same memory location may be used in subsequent calls
to getenv, overwriting the previous content.
getenv() function in C
char * fgets ( char * str, int num, FILE * stream );
Get string from stream
Reads characters from stream and stores them as a C string
into str until (num-1) characters have been read or either a newline
or a the End-of-File is reached, whichever comes first.
A newline character makes fgets stop reading, but it is considered a
valid character and therefore it is included in the string copied to str.
A null character is automatically appended in str after the
characters read to signal the end of the C string.
fgets() function in C
POST
 (GET was originally used only to get data from
server)
 data is passed via standard input stream (stdin)
 the length (in bytes) of the data passed via
$CONTENT_LENGTH.
 If the program reads more than the length,
 ...unpredictable behaviour may happen!
Multiply example – the HTML file
<form method="post"
action="http://it026945/cgi-bin/testingcgi/multiply">
<div><label>Number 1: <input name="m" size="5"></label></div>
<div><label>Number 2: <input name="n" size="5"></label></div>
<div><input type="submit" value="Multiply"></div>
</form>
Multiply with POST – C file
...#define MAXLEN 80
int main(void)
{
char *lenstr;
char input[MAXLEN];
long m,n, len;
printf("%s%c%cn","Content-Type:text/html;charset=iso-8859-1",13,10);
lenstr = getenv("CONTENT_LENGTH");
if(lenstr == NULL || sscanf(lenstr,"%ld",&len)!=1 || len > MAXLEN)
printf("<P>There was an error in the content sent to Apache.");
else {
fgets(input, len+1, stdin);
printf("<P>Form received by Apache.<br>");
printf("The form contains %ld bytes.<br>",len);
printf("<P>Apache received this: %s <br>",input);
if(sscanf(input,"m=%ld&n=%ld",&m,&n)!=2)
printf("<P>An error occurred, both variables must be numeric.");
else
printf("<P><h3> %ld * %ld = %ld.</h3>",m,n,m*n);
}
return 0;
}
//adapted from http://www.cs.tut.fi/~jkorpela/forms/cgic.html (July2010)
Self-generating form in C
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *data;
long m,n;
printf("%s%c%cn","Content-Type:text/html;charset=iso-8859-1",13,10);
printf("<form method = "get" action="http://it026945/cgi-
bin/testingcgi/multiply2"><div><label>Multiplicand 1: <input
name="m" size="5"></label></div><div><label>Multiplicand 2: <input
name="n" size="5"></label></div><div><input type="submit"
value="Multiply!"></div></form>");
printf("<H3>Multiplication results</H3>");
data = getenv("QUERY_STRING");
if(data == NULL)
printf("<P>Error! Error in passing data from form to script.");
else if(sscanf(data,"m=%ld&n=%ld",&m,&n)!=2)
printf("<P>Error! Invalid data. Data must be numeric.");
else
printf("<P>The product of %ld and %ld is %ld.",m,n,m*n);
return 0;
}
Self-generating form in C
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *data;
long m,n;
static int flag=0;
printf("%s%c%cn","Content-Type:text/html;charset=utf-8",13,10);
printf("<form method = "get" action="http://localhost:8080/cgi-bin/multiply2_utf8">
<div><label>Multiplicand 1: <input name="m" size="5"></label></div>
<div><label>Multiplicand 2: <input name="n" size="5"></label></div>
<div><input type="submit" value="Multiply!"></div></form>");
printf("<H3>Multiplication results</H3>");
data = getenv("QUERY_STRING");
if(data == NULL) {
if( !flag ){
printf("<P>nothing to compute yet.");
} else {
printf("<P>Error! Error in passing data from form to script.");
}
} else if(sscanf(data,"m=%ld&n=%ld",&m,&n)!=2) {
printf("<P>Error! Invalid data. Data must be numeric.");
} else {
printf("<P>The product of %ld and %ld is %ld.",m,n,m*n);
flag = 1;
}
return 0;
}
Handling Special Characters
void decode(char *src, char *last, char *dest){
for(; src != last; src++, dest++)
if(*src == '+')
*dest = ' ';
else if(*src == '%') {
int code;
if(sscanf(src+1, "%2x", &code) != 1)
code = '?';
*dest = code;
src +=2;
} else
*dest = *src;
*dest = 'n';
*++dest = '0';
}
Problems with CGI
 Each a time request is made, a new process is
spawned on the server
 This can quickly overwhelm sites that get a large
number of hits
 One solution is to install libraries directly callable
by the web server
mod_perl
mod_python
CGI can be inefficient...
 The executable is loaded in the server's
memory every time it is called
 Multiple copies
 API would be more efficient...
 Bad idea to do that using C/C++
 Unstable environment (crash the entire server)
 Apache offers modules with Perl and Python
APIs
 Scripting languages such as ASP and PHP
Security problems with CGI
 Program is running in your server...
 Suppose you want the user to run:
 system "whois $username" ;
 But what if the user actually sends:
 "john; rm -rf "
 system "whois john; rm -rf " ;
 The administrator: “Oh dear!Where are all my
files?”
In Linux
For Windows, http://technet.microsoft.com/en-us/sysinternals/bb897435.aspx
Server-side programming
 Better to use a language specially designed
for server-side programming
 See PHP programming next...
References
http://www.cs.tut.fi/~jkorpela/forms/cgic.html

More Related Content

Similar to CGI.ppt

CountryData.cppEDIT THIS ONE#include fstream #include str.pdf
CountryData.cppEDIT THIS ONE#include fstream #include str.pdfCountryData.cppEDIT THIS ONE#include fstream #include str.pdf
CountryData.cppEDIT THIS ONE#include fstream #include str.pdf
Aggarwalelectronic18
 

Similar to CGI.ppt (20)

C++ L01-Variables
C++ L01-VariablesC++ L01-Variables
C++ L01-Variables
 
Dartprogramming
DartprogrammingDartprogramming
Dartprogramming
 
Secure Programming
Secure ProgrammingSecure Programming
Secure Programming
 
Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0
 
Cgi
CgiCgi
Cgi
 
Practical basics on c++
Practical basics on c++Practical basics on c++
Practical basics on c++
 
Rapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesRapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devices
 
CountryData.cppEDIT THIS ONE#include fstream #include str.pdf
CountryData.cppEDIT THIS ONE#include fstream #include str.pdfCountryData.cppEDIT THIS ONE#include fstream #include str.pdf
CountryData.cppEDIT THIS ONE#include fstream #include str.pdf
 
Cocoa heads 09112017
Cocoa heads 09112017Cocoa heads 09112017
Cocoa heads 09112017
 
my accadanic project ppt
my accadanic project pptmy accadanic project ppt
my accadanic project ppt
 
Odp
OdpOdp
Odp
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 
Survey of programming language getting started in C
Survey of programming language getting started in CSurvey of programming language getting started in C
Survey of programming language getting started in C
 
270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 
Top 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesTop 10 Web Security Vulnerabilities
Top 10 Web Security Vulnerabilities
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 
Pycon - Python for ethical hackers
Pycon - Python for ethical hackers Pycon - Python for ethical hackers
Pycon - Python for ethical hackers
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++
 

Recently uploaded

"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
pritamlangde
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
Kamal Acharya
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 

Recently uploaded (20)

Worksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptxWorksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptx
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
 
👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...
👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...
👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptx
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth Reinforcement
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
fitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptfitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .ppt
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 

CGI.ppt

  • 2. Rich Internet Applications  An RIA is a web application that provides the client with the features and functionality of desktop applications  Requires transferring the processing from the server to the client  Javascript is one enabling technology for a RIA
  • 3. RIAs in the Internet client-server model Client (browser) Web server Client does all the processing (eg play videos as they come in) Data (eg multimedia) stay on the server HTTP request for resource Server sends code but keeps data
  • 4. Some technologies that support RIA development  Javascript (and associated ECMA dialects)  Adobe Flash  Flash player and IDE  Java Applets and Java Webstart (see later)  AJAX  Asynchronous JavaScript and XML
  • 5. Server-Side Programming  Lots of programs/applications designed to run on the machines on which they are installed  How can a remote client request access to these?
  • 6. CGI programming  CGI => Common Gateway Interface  A protocol for interfacing local applications with a web server  Sequence of steps  Client sends URL request  Program runs at the server side  Output is collected and sent back to the client  Often the output is an HTML “built” by the server
  • 7. CGI using HTML and C language  Why do we need CGI?  To read the information on the forms (HTML)  To build a customised HTML response to users  To understand the concept lets use C at first...  CGI is completely independent of the language and OS  CGI is implemented in (almost) all webservers
  • 8. CGI programs can be written in any language supported by the server. This includes compiled programming languages, such as C and C++; interpreted languages, such as Perl, Python, Ruby, and languages, such as Java, that lie somewhere in between.
  • 9. Hello World! #include <iostream> using namespace std; int main(void) { cout << "Content-Type: text/html;charset=us-asciinn"; /** Print the HTML response page to STDOUT. **/ cout << "<html>n"; cout << "<head><title>CGI Output</title></head>n"; cout << "<body>n" ; cout << "<h1>Hello, world.</h1>n"; cout << "this is my first CGI" << "n"; cout << "</body>n"; cout << "</html>n"; return 0; } Compile, then place the executable inside cgi-bin directory of xitami Test using a browser, URL: http://localhost:8080/cgi-bin/helloworld
  • 10. How to submit data using forms  GET  http://www.someurl/cgi-bin/script?var1=1&var2=4  Web server has a special directory called cgi-bin  Two variables:  var1=1  var2=4  Special characters are encoded  ~ would be encoded as %7E (% followed by ASCII code)
  • 11. GET  So variables from the forms go on URL  The environment variable is:  $QUERY_STRING  Most browsers limit the size of URLs (256 chars, some more, e.g., IE is 2083 chars)  When you have too much data, use POST instead...
  • 12. Multiply example – the HTML file <form method="get" action="http://it026945/cgi-bin/testingcgi/multiply"> <div><label>Number 1: <input name="m" size="5"></label></div> <div><label>Number 2: <input name="n" size="5"></label></div> <div><input type="submit" value="Multiply"></div> </form>
  • 13. Multiply example Action="http://it026945/cgi-bin/testingcgi/multiply">  multiply is an executable under:/var/www/cgi-bin/  with x permissions for all!  Variables in URL:  After submission, URL becomes:  http://it026945/cgi-bin/testingcgi/multiply?m=1&n=2
  • 15. Multiply example – the C file #include <stdio.h> #include <stdlib.h> #include <windows.h> //for Windows operating system – Sleep() int main(void) { char *data; long m,n; printf("%s%c%cn","Content-Type:text/html;charset=iso-8859-1",13,10); printf("<TITLE>Multiplication results</TITLE>n"); printf("<H3>Multiplication results</H3>n"); data = getenv("QUERY_STRING");//here it is your data!!! if(data == NULL) printf("<P>Error!"); else if(sscanf(data,"m=%ld&n=%ld",&m,&n)!=2)//check for 2 inputs printf("<P>Error! Invalid data."); else printf("<P>%ld * %ld = %ld.",m,n,m*n); //Sleep(1000); // uncomment that to see who runs the process... return 0; } //from http://www.cs.tut.fi/~jkorpela/forms/cgic.html (July2010)
  • 16. Recall the sscanf() function in C • On success, the function returns the number of items successfully read. • This count can match the expected number of readings or fewer, even zero, if a matching failure happens. • In the case of an input failure before any data could be successfully read, EOF is returned. int sscanf ( const char * str, const char * format, ...); Read formatted data from string
  • 17. char * getenv ( const char * name ); Get environment string •Retrieves a C string containing the value of the environment variable whose name is specified as argument. •If the requested variable is not part of the environment list, the function returns a NULL pointer. •The string pointed by the pointer returned by this function shall not be modified by the program. •The same memory location may be used in subsequent calls to getenv, overwriting the previous content. getenv() function in C
  • 18. char * fgets ( char * str, int num, FILE * stream ); Get string from stream Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first. A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str. A null character is automatically appended in str after the characters read to signal the end of the C string. fgets() function in C
  • 19. POST  (GET was originally used only to get data from server)  data is passed via standard input stream (stdin)  the length (in bytes) of the data passed via $CONTENT_LENGTH.  If the program reads more than the length,  ...unpredictable behaviour may happen!
  • 20. Multiply example – the HTML file <form method="post" action="http://it026945/cgi-bin/testingcgi/multiply"> <div><label>Number 1: <input name="m" size="5"></label></div> <div><label>Number 2: <input name="n" size="5"></label></div> <div><input type="submit" value="Multiply"></div> </form>
  • 21. Multiply with POST – C file ...#define MAXLEN 80 int main(void) { char *lenstr; char input[MAXLEN]; long m,n, len; printf("%s%c%cn","Content-Type:text/html;charset=iso-8859-1",13,10); lenstr = getenv("CONTENT_LENGTH"); if(lenstr == NULL || sscanf(lenstr,"%ld",&len)!=1 || len > MAXLEN) printf("<P>There was an error in the content sent to Apache."); else { fgets(input, len+1, stdin); printf("<P>Form received by Apache.<br>"); printf("The form contains %ld bytes.<br>",len); printf("<P>Apache received this: %s <br>",input); if(sscanf(input,"m=%ld&n=%ld",&m,&n)!=2) printf("<P>An error occurred, both variables must be numeric."); else printf("<P><h3> %ld * %ld = %ld.</h3>",m,n,m*n); } return 0; } //adapted from http://www.cs.tut.fi/~jkorpela/forms/cgic.html (July2010)
  • 22. Self-generating form in C #include <stdio.h> #include <stdlib.h> int main(void) { char *data; long m,n; printf("%s%c%cn","Content-Type:text/html;charset=iso-8859-1",13,10); printf("<form method = "get" action="http://it026945/cgi- bin/testingcgi/multiply2"><div><label>Multiplicand 1: <input name="m" size="5"></label></div><div><label>Multiplicand 2: <input name="n" size="5"></label></div><div><input type="submit" value="Multiply!"></div></form>"); printf("<H3>Multiplication results</H3>"); data = getenv("QUERY_STRING"); if(data == NULL) printf("<P>Error! Error in passing data from form to script."); else if(sscanf(data,"m=%ld&n=%ld",&m,&n)!=2) printf("<P>Error! Invalid data. Data must be numeric."); else printf("<P>The product of %ld and %ld is %ld.",m,n,m*n); return 0; }
  • 23. Self-generating form in C #include <stdio.h> #include <stdlib.h> int main(void) { char *data; long m,n; static int flag=0; printf("%s%c%cn","Content-Type:text/html;charset=utf-8",13,10); printf("<form method = "get" action="http://localhost:8080/cgi-bin/multiply2_utf8"> <div><label>Multiplicand 1: <input name="m" size="5"></label></div> <div><label>Multiplicand 2: <input name="n" size="5"></label></div> <div><input type="submit" value="Multiply!"></div></form>"); printf("<H3>Multiplication results</H3>"); data = getenv("QUERY_STRING"); if(data == NULL) { if( !flag ){ printf("<P>nothing to compute yet."); } else { printf("<P>Error! Error in passing data from form to script."); } } else if(sscanf(data,"m=%ld&n=%ld",&m,&n)!=2) { printf("<P>Error! Invalid data. Data must be numeric."); } else { printf("<P>The product of %ld and %ld is %ld.",m,n,m*n); flag = 1; } return 0; }
  • 24. Handling Special Characters void decode(char *src, char *last, char *dest){ for(; src != last; src++, dest++) if(*src == '+') *dest = ' '; else if(*src == '%') { int code; if(sscanf(src+1, "%2x", &code) != 1) code = '?'; *dest = code; src +=2; } else *dest = *src; *dest = 'n'; *++dest = '0'; }
  • 25. Problems with CGI  Each a time request is made, a new process is spawned on the server  This can quickly overwhelm sites that get a large number of hits  One solution is to install libraries directly callable by the web server mod_perl mod_python
  • 26. CGI can be inefficient...  The executable is loaded in the server's memory every time it is called  Multiple copies  API would be more efficient...  Bad idea to do that using C/C++  Unstable environment (crash the entire server)  Apache offers modules with Perl and Python APIs  Scripting languages such as ASP and PHP
  • 27. Security problems with CGI  Program is running in your server...  Suppose you want the user to run:  system "whois $username" ;  But what if the user actually sends:  "john; rm -rf "  system "whois john; rm -rf " ;  The administrator: “Oh dear!Where are all my files?” In Linux For Windows, http://technet.microsoft.com/en-us/sysinternals/bb897435.aspx
  • 28. Server-side programming  Better to use a language specially designed for server-side programming  See PHP programming next...