1 / 34

Internetteknologi (ITNET2)

Internetteknologi (ITNET2). Præsentation 21: Common Gateway Interface (CGI) illustreret med Perl og C. Mission. Efter denne 2x35 lektion vil I:

telma
Download Presentation

Internetteknologi (ITNET2)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Internetteknologi (ITNET2) Præsentation 21: Common Gateway Interface (CGI) illustreret med Perl og C

  2. Mission • Efter denne 2x35 lektion vil I: • Have opnået et basalt kendskab til Common Gateway Inteface (CGI) teknologien, med udgangspunkt i Perl, og forstå dens ligheder og forskelle med andre server side teknologier, såsom JSP/Servlets og ASP.NET • Dette er ikke et Perl kursus – så I vil ikke have lært Perl • Have set hvordan alternativt C kan anvendes m.f.

  3. Indhold i denne præsentation • Kort introduktion til CGI • Hvordan virker det? • Eksempler på CGI og Perl • Om fremtiden for CGI og Perl • CGI og C

  4. Hvad er “CGI”? • Common Gateway Interface • Standard til at afvikle et eksekverbart program (eller et script i Perls tilfælde) via Web servere • Web serveren skal blot vide hvem der har ansvaret for at afvikle koden, hvorefter den redelegere requestet • (Næsten) alle sprog kan bruges til at lave CGI programmer med (standard in/out + environment) • Herunder C/C++ , og de mest anvendte Perl og Python • CGI/Perl/C var i mange år det foretrukne værktøj til dynamisk server-side programmering, indtil ASP/ASP.NET, JSP/Servlets, PHP kom frem

  5. CGI Historie • Opfundet af NCSA Software Development Group • 1993? Svært at finde en præcis reference • Samme som opfandt Mosaic browseren (forløberen til Netscape) • Og NCSA httpd (én af de første web servere) • Find specificationen på: • http://hoohoo.ncsa.uiuc.edu/cgi/interface.html • Er i dag reelt en defacto standard for program kald

  6. Server side scripting - CGI Bruger indtaster data i form feltet i browser og taster submit: http://feedbackForm.htm Webserver findes via IP adresse & DNS Lytter på port f.eks. 80 1 HTTP Request (over TCP/IP) GET /feedback.pl 2 Webserveren modtager requestet: Finder det rette program via CGI interfacet, feks. (feedback.pl) En ny proces spawnes og programmet afvikles med de givne parametre, og resultatet afleveres på output stream LIGHEDER MED ASP/JSP? En typisk Header kunne se ud som følger: HTTP/1.0 200 OK Server: Netscape-Communications/1.1 Date: Tuesday, 25-Nov-97 01:22:04 GMT Last-modified: Thursday, 20-Nov-97 10:44:53 GMT Content-length: 6372 Content-type: text/html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <HTML> ... her følger resten af dokumentet 3 Browseren modtager response: Renderer HTML dokumentet til brugervenlig form

  7. Eksempler • I har prøvet at bruge både Servlets/JSP, PHP og ASP.NET – nu skal vi se hvordan CGI fungerer i relation til først et C eksempel og herefter et Perl eksempel • Her følger et par slides der kort illustrere dette

  8. Vi ser at HTML er indlejret. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); } } Server side:Servlet eksempel Resultatet <html> <head> <title>Hello World!</title> </head> <body bgcolor="white"> <a href="/examples/servlets/helloworld.html"> <img src="/examples/images/code.gif" height=24 width=24 align=right border=0 alt="view code"></a> <a href="/examples/servlets/index.html"> <img src="/examples/images/return.gif" height=24 width=24 align=right border=0 alt="return"></a> <h1>Hello World!</h1> </body> </html>

  9. Alt vi skal bruge er standard IO #include <stdio.h> main(int argc, char *argv[]) { char *cl; printf("Content-type: text/html%c%c",10,10); if(strcmp(getenv("REQUEST_METHOD"),"GET")) { printf("This script should be referenced with a METHOD of POST.\n"); exit(1); } else { printf("<p>You have contacted me using the POST method</p>"); } cl = getenv("QUERY_STRING"); printf("<p>"); printf("The Content of Query_String was: "); printf(cl); printf("</p>"); return 0; } Server sideCGI/C Page Vi anvender getenv til at kommunikere med serveren (environment variable) HTTP Get parametre strengen Kommer i env-var QUERY_STRING

  10. 1 #!/usr/bin/perl 2 # Fig. 27.11: fig27_11.pl 3 # Program to display CGI environment variables. 4 5 use CGI qw( :standard ); 6 7 $dtd = 8 "-//W3C//DTD XHTML 1.0 Transitional//EN\" 9 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"; 10 11 print( header() ); 12 13 print( start_html( { dtd => $dtd, 14 title => "Environment Variables..." } ) ); 15 16 print( "<table style = \"border: 0; padding: 2; 17 font-weight: bold\">" ); 18 19 print( Tr( th( "Variable Name" ), 20 th( "Value" ) ) ); 21 22 print( Tr( td( hr() ), td( hr() ) ) ); 23 24 foreach $variable ( sort( keys( %ENV ) ) ) { 25 26 print( Tr( td( { style => "background-color: #11bbff" }, 27 $variable ), 28 td( { style => "font-size: 12pt" }, 29 $ENV{ $variable } ) ) ); 30 31 print( Tr( td( hr() ), td( hr() ) ) ); 32 } 33 34 print( "</table>" ); 35 print( end_html() ); Server sideCGI/Perl Page CGI bibliotektet wrapper kommunikation med web serveren Metoderne kommer fra CGI bibliotektet

  11. Hvad skal der til for at køre CGI • JSP og Servlets bruger en ”Servlet Container” m. egen VM • Apache Tomcat, BEA Weblogic, Oracle AS, IBM WebSphere – alle standardiseret • ASP & ASP:NET bruger Windows og IIS Web server / .NET CLR • CGI/Perl er understøttet af stort set alle Web servere og operativsystemer, men der skal evt. downloades en operativsystem specifik perl fortolker. • Brug f.eks. Apache Web serveren, med mod_cgi/mod_perl modulet tilføjet • CGI/C – CGI/C++ såfremt det kan kompileres på platformen kan det som regel også afvikles af Web serveren hvis den understøtter CGI (som f.eks. Apache)

  12. PERL • PERL: Practical Extraction and Report Language • Høj-niveau programmeringssprog • Fortolket programmeringssprog (perl.exe) • Løst typet • Bruges som konsol sprog af administratorer til overvågning og rapporteringsopgaver • Virkeligt stærkt til streng behandling • Vandt derfor tidligt indpas på WWW i forb. Med CGI • (www.perl.com)

  13. PERL History • Opfundet af Larry Wall i 1987 • Perl 2: 1988 • Perl 3: 1989 • Perl 4: 1992 • Standard in UNIX – small programs only • Perl 5: 1994 • Full programming language – total rewrite • Subversions of Perl 5 • Rasmus Lehrdorf uses Perl to create PHP: 1995 • PerlNET: .NET Wrapper for Perl (runs unmanged) • Perl 6: currently under development (open source) • New: VM instead of interpreter

  14. The %ENV hash is a built-in table in Perl that contains the names and values of all the environment variables. 1 #!/usr/bin/perl 2 # Fig. 27.11: fig27_11.pl 3 # Program to display CGI environment variables. 4 5 use CGI qw( :standard ); 6 7 $dtd = 8 "-//W3C//DTD XHTML 1.0 Transitional//EN\" 9 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"; 10 11 print( header() ); 12 13 print( start_html( { dtd => $dtd, 14 title => "Environment Variables..." } ) ); 15 16 print( "<table style = \"border: 0; padding: 2; 17 font-weight: bold\">" ); 18 19 print( Tr( th( "Variable Name" ), 20 th( "Value" ) ) ); 21 22 print( Tr( td( hr() ), td( hr() ) ) ); 23 24 foreach $variable ( sort( keys( %ENV ) ) ) { 25 26 print( Tr( td( { style => "background-color: #11bbff" }, 27 $variable ), 28 td( { style => "font-size: 12pt" }, 29 $ENV{ $variable } ) ) ); 30 31 print( Tr( td( hr() ), td( hr() ) ) ); 32 } 33 34 print( "</table>" ); 35 print( end_html() ); The import tag :standard imports a predefined set of standard functions. Fig27_11.pl Instruct the Perl script to print a valid HTTP header, using function header from the CGI library. The use statement instructs Perl programs to include the contents (e.g., functions) of predefined packages called modules. The start_html function prints the document type definition for this document, as well as several opening XHTML tags (<html>, <head>, <title>, etc., up to the opening <body> tag). Function keys returns an unordered array containing all the keys in the %ENV hash. Specifies the value for the attribute style.

  15. Program Output

  16. Eksempel på brug af parametre • Vi husker fra JSP/Servlets og ASP, at alt kommunikation primært foregik via FORM elementer • Dette er også tilfældet i CGI/Perl • I det følgende gives et eksempel på dette • Først en simpel registreringsform • Og herefter en CGI/Perl side der henter data fra HTTP requestet

  17. 1 <!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN" 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 3 4 <!-- Fig. 27.12: fig27_12.html --> 5 6 <html> 7 <head> 8 <title>Sample form to take user input in XHTML</title> 9 </head> 10 11 <body style ="font-face: arial; font-size: 12pt"> 12 13 <div style ="font-size: 14pt; font-weight: bold"> 14 This is a sample registration form. 15 </div> 16 17 <br /> 18 Please fill in all fields and click Register. 19 20 <form method ="post"action ="/cgi-bin/fig27_13.pl"> 21 22 <img src ="images/user.gif"/><br /> 23 24 <div style ="color: blue" > 25 Please fill out the fields below.<br /> 26 </div> 27 28 <img src ="images/fname.gif"/> 29 <input type ="text"name ="fname"/><br /> 30 <img src ="images/lname.gif"/> 31 <input type ="text" name = "lname"/><br /> 32 <img src = "images/email.gif"/> 33 <input type ="text"name = "email"/><br /> 34 <img src = "images/phone.gif"/> 35 <input type ="text"name = "phone"/><br /> Fig27_12.html Form element which indicates that, when the user clicks Register, the form information is posted to the server. The statement action="cgi-bin/ fig27_13.pl" directs the server to execute the fig27_13.pl Perl script (located in the cgi-bin directory) to process the posted form data. Exactly like JSP/PHP/ASP.NET

  18. 36 37 <div style ="font-size: 10pt"> 38 Must be in the form (555)555-5555.<br /><br /> 39 </div> 40 41 <img src = "images/downloads.gif"/><br /> 42 <div style = "color: blue"> 43 Which book would you like information about?<br /> 44 </div> 45 46 <select name ="book"> 47 <option>Internet and WWW How to Program 2e</option> 48 <option>C++ How to Program 3e</option> 49 <option>Java How to Program 4e</option> 50 <option>XML How to Program 1e</option> 51 </select><br /><br /> 52 53 <img src = "images/os.gif"/><br /> 54 <div style ="color: blue"> 55 Which operating system are you currently using? 56 </div><br /> 57 58 <input type ="radio"name ="os" 59 value ="Windows NT" checked/> 60 Windows NT<input type ="radio" 61 name ="os"value ="Windows 2000" /> 62 Windows 2000<input type ="radio" 63 name ="os"value ="Windows 98/me" /> 64 Windows 98/me<br /><input type ="radio" 65 name ="os"value ="Linux" /> 66 Linux<input type ="radio"name ="os" 67 value ="Other" /> 68 Other<br /><input type ="submit" 69 value ="Register"/> 70 </form> Fig27_12.html

  19. 71 </body> 72 </html> Fig27_12.htmlProgram Output

  20. Function param is part of the Perl CGI module and retrieves values from a form field’s value. Same as ASP’s Request(”param”) & JSP’s request.getParameter(”param”) 1 #!/usr/bin/perl 2 # Fig. 27.13: fig27_13.pl 3 # Program to read information sent to the server 4 # from the form in the fig27_12.html document. 5 6 use CGI qw( :standard ); 7 8 $os = param( "os" ); 9 $firstName = param( "fname" ); 10 $lastName = param( "lname" ); 11 $email = param( "email" ); 12 $phone = param( "phone" ); 13 $book = param( "book" ); 14 15 $dtd = 16 "-//W3C//DTD XHTML 1.0 Transitional//EN\" 17 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"; 18 19 print( header() ); 20 21 print( start_html( { dtd => $dtd, 22 title => "Form Results" } ) ); 23 24 if ( $phone =~ / ^ \( \d{3} \) \d{3} - \d{4} $ /x ) { 25 print( "Hi " ); 26 print( span( { style => "color: blue; font-weight: bold" }, 27 $firstName ) ); 28 print( "!" ); 29 30 print( "\nThank you for completing the survey." ); 31 print( br(), "You have been added to the " ); 32 33 print( span( { style => "color: blue; font-weight: bold" }, 34 $book ) ); 35 print( " mailing list.", br(), br() ); Fig27_13.pl The if condition uses a regular expression to validate the phone number. The expression “\(” matches the opening parenthesis of the phone number. This sequence must be followed by three digits (\d{3}), a closing parenthesis, three digits, a hyphen and finally, four more digits. Dette kan også gøres i både JSP og ASP, men også i JavaScript – Client side

  21. Methods span and div add <span> and <div> tags to the page, respectively. If the phone number is not valid an error message is printed to the client 36 37 print( span( { style => "font-weight: bold" }, 38 "The following information has 39 been saved in our database: " ), br() ); 40 41 print( table( 42 Tr( th( { style => "background-color: #ee82ee" }, 43 "Name" ), 44 th( { style => "background-color: #9370db" }, 45 "E-mail" ), 46 th( { style => "background-color: #4169e1" }, 47 "Phone" ), 48 th( { style => "background-color: #40e0d0" }, 49 "OS" ) ), 50 51 Tr( { style => "background-color: #c0c0c0" }, 52 td( "$firstName $lastName" ), 53 td( $email ), 54 td( $phone ), 55 td( $os ) ) ) ); 56 57 print( br() ); 58 59 print( div( { style => "font-size: x-small" }, 60 "This is only a sample form. You have not been 61 added to a mailing list." ) ); 62 } 63 else { 64 print( div( { style => "color: red; font-size: x-large" }, 65 "INVALID PHONE NUMBER" ), br() ); 66 67 print( "A valid phone number must be in the form " ); 68 print( span( { style => "font-weight: bold" }, 69 "(555)555-5555." ) ); 70 Fig27_13.pl

  22. 71 print( div( { style => "color: blue" }, 72 "Click the Back button, and enter a 73 valid phone number and resubmit." ) ); 74 print( br(), br() ); 75 print( "Thank you." ); 76 } 77 78 print( end_html() ); Fig27_13.plProgram Output

  23. Standard Libraries available Wraps the reading of env and stdin Special HTML functions Sessions etc Using Extra Libraries for C Simplified query-results.cgi using cgihtml. #include "cgi-lib.h"#include "html-lib.h"int main(){   llist entries   read_cgi_input(&entries);   html_header();   html_begin("Query Results");   print_entries(entries);   html_end();   list_clear(&entries);}

  24. Eksempel på brug af Server-Side Includes (SSI eller .shtml) • Det er også muligt at opnå JSP/ASP lignende funktionalitet, dvs. med indlejrede ”tags” • Fra SHTML kan kommandoen ”EXEC” kaldes, der kalder et andet CGI script, og inkluder dets output – svarende til Server.Execute(”side.asp”) i ASP, og <jsp:include page=”side.jsp”/> i JSP. • I det følgende gives et eksempel på dette

  25. The command EXEC can be used to run CGI scripts and embed their output directly into a Web page. The ECHO command displays variable information. The ECHO command is followed by the keyword VAR and the name of the variable. For example, variable DATE_GMT contains the current date and time in Greenwich Mean Time (GMT). 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 3 4 <!-- Fig. 27.14: fig27_14.shtml --> 5 6 <html> 7 <head> 8 <title>Using Server Side Includes</title> 9 </head> 10 11 <body> 12 <h3 style ="text-align: center"> 13 Using Server Side Includes 14 </h3> 15 16 <!--#EXEC CGI="/cgi-bin/fig27_15.pl" --><br /> 17 18 The Greenwich Mean Time is 19 <span style ="color: blue"> 20 <!--#ECHO VAR="DATE_GMT" -->. 21 </span><br /> 22 23 The name of this document is 24 <span style ="color: blue"> 25 <!--#ECHO VAR="DOCUMENT_NAME" -->. 26 </span><br /> 27 28 The local date is 29 <span style ="color: blue"> 30 <!--#ECHO VAR="DATE_LOCAL" -->. 31 </span><br /> 32 Fig27_14.shtml

  26. 33 This document was last modified on 34 <span style ="color: blue"> 35 <!--#ECHO VAR="LAST_MODIFIED" -->. 36 </span><br /> 37 38 Your current IP Address is 39 <span style ="color: blue"> 40 <!--#ECHO VAR="REMOTE_ADDR" -->. 41 </span><br /> 42 43 My server name is 44 <span style ="color: blue"> 45 <!--#ECHO VAR="SERVER_NAME" -->. 46 </span><br /> 47 48 And I am using the 49 <span style ="color: blue"> 50 <!--#ECHO VAR="SERVER_SOFTWARE" --> 51 Web Server. 52 </span><br /> 53 54 You are using 55 <span style ="color: blue"> 56 <!--#ECHO VAR="HTTP_USER_AGENT" -->. 57 </span><br /> 58 59 This server is using 60 <span style ="color: blue"> 61 <!--#ECHO VAR="GATEWAY_INTERFACE" -->. 62 </span><br /> 63 64 <br /><br /> 65 <div style ="text-align: center; 66 font-size: xx-small"> 67 <hr /> Fig27_14.shtml

  27. 68 This document was last modified on 69 <!--#ECHO VAR="LAST_MODIFIED" -->. 70 </div> 71 </body> 72 </html> Fig27_14.shtmlProgram Output

  28. The file counter.dat, which contains the number of hits to date for the fig27_14.shtml Web page, is opened for input. Function open is called to create a filehandle to refer to the file during the execution of the script. 1 #!/usr/bin/perl 2 # Fig. 27.15: fig27_15.pl 3 # Program to track the number of times 4 # a Web page has been accessed. 5 6 use CGI qw( :standard ); 7 8 open( COUNTREAD, "counter.dat" ); 9 $data = <COUNTREAD>; 10 $data++; 11 close( COUNTREAD ); 12 13 open( COUNTWRITE, ">counter.dat" ); 14 print( COUNTWRITE $data ); 15 close( COUNTWRITE ); 16 17 print( header(), "<div style = \"text-align: center; 18 font-weight: bold\">" ); 19 print( "You are visitor number", br() ); 20 21 for ( $count = 0; $count < length( $data ); $count++ ) { 22 $number = substr( $data, $count, 1 ); 23 print( img( { src => "images/$number.gif" } ), "\n" ); 24 } 25 26 print( "</div>" ); Fig27_15.pl

  29. OO understøttelse i Perl: POOP Minder lidt om PHP 4 modellen http://www.codeproject.com/perl/camel_poop.asp POOP: OO Perl

  30. Også mulighed for DB adgang i PERL: DBI F.eks. MySQL drivere tilgængelige Se Deitel & Deitel eller www.perl.com Perl og Databaser

  31. CGI vs øvrige server-side sprog • Performance • CGI programmer spawnes og afsluttes for hver client request • performer dårligt ved mange samtidige request • Udover ny proces skal der også spawnes perl.exe (ved perl) • JSP/Servlets, ASP.NET og PHP håndterer flere samtidige requests mere intelligent • performer bedre ved mange samtidige request • Struktueringsmekanismer • Afhængigt af underliggende sprog • Ringe kontakt mellem CGI scripts og Web server • Mangler grundliggende objekter (f.eks. Session objektet) hvilket dog kan findes via eksterne libs

  32. Performance Comparison of Alternative Solutions For Web-To-Database Applications, by AMANDA W. WU, HAIBO WANG AND DAWN WILKINS, October 2000 http://rain.vislab.olemiss.edu/~ww1/Slide_Show_Images/SCC_Amanda/SCC_Amanda.pdf

  33. Om fremtiden for CGI I • Generelt kan man lave de fleste ting du kan lave i JSP/Servlets og/eller ASP/ASP.NET- i CGI/Perl, (eller CGI med et andet sprog) • Databaser, filadgang, regulære udtryk, algebra, logik … • Samtidigt findes der ufatteligt mange eksisterende scripts der kan køres, og mange sites bruger stadigvæk CGI til f.eks. Counter, FormMails, gæstebøger osv.

  34. Om fremtiden for CGI II • MEN: • CGI ikke velegnet til at udvikle større systemer • CGI har ikke IDE og debugging faciliteter • Svært at strukturere • Stærkt begrænset popularitet • DOG: • Vigtigt at kende teknologien – både historisk set – men også fordi der stadigvæk kører masser af CGI programmer hos kunder • Anvendeligt til indlejrede enheder • Godt til afvikling af ekstremt krævende databehandlingsalgoritmer

More Related