配置Nginx 运转CGI(Perl-cgi)

2019-08-05 21:43栏目:电脑操作

笔者的nginx安装目录为/usr/local/nginx

如何在Nginx中使用CGI

缘起
在探索到CGI到底为何物时,google SimpleCGI的时候,看到这篇文章,粗看了几眼,觉得不错,有几个感兴趣的topic:CGI,FastCGI,Nginx。

正文
For the most part,lack of CGI support in Nginx is not an issue and actually has an important side-benefit: because Nginx cannot directly execute external programs (CGI), a malicious person can't trick your system into uploading and executing an arbitrary script.

大体而言,Nginx中缺乏对CGI的支持不是问题,实际上还带来一些好处:因为Nginx不直接执行外部程序(CGI),心怀不轨的人不能通过上传并执行任意脚本来攻击你的系统。

There are still ways, of course (uploading a PHP script into a directory where you've got a directive to execute PHP FastCGI scripts for example), but it does in fact make it a bit more difficult (or conversely, easier to secure).

当然,依然存在一些攻击系统的方法,比如上传PHP脚本到某个目录,但你定向到给目录时,执行PHP FastCGI脚本,但这显然更加困难一些。

Still, sometimes you have a one-off simple CGI program you need to support and here's a recipe for exposing your CGI to Nginx as a FastCGI instead:

有时,需要支持一次性的CGI脚本。这里介绍一个将CGI程序转换为FastCGI然后传递给Nginx的方法:

Let's say this is our CGI program, written in Perl:

下面介绍一下这个Perl编写的CGI程序:

#!/usr/bin/perl

print "Content-type: text/htmlnn";
print "<html><body>Hello, world.</body></html>";
Make sure that the web server can read the file and it is marked as executable.

确保web服务器能够读取并将其看作可执行文件。

Next, we need a Perl wrapper that will run as a FastCGI and run this for us:

接下来,需要一个运行为FastCGI的Perl包装器来运行这个程序:

This one is still pretty ugly, but forwards stdio around correctly (not necessarily efficiently or prettily), and also reads and spits back out STDERR into fcgi STDERR. I am not entirely confident there is no race condition in the event that an app STDERRS out without any output data, but it works for my purposes. This is for the most part, not my own work; 99.9% of this came from the various improvements on the spawner script worked on in the mailing list and wiki here.. I just added some more pipe handling to enable communicating through STDERR, and a select loop to properly recieve both data streams. -- [email protected]

下面的这个包装器相当的简陋,但在stdio上大体正确(不需要高效或完美),也可以将标准STDERR读取和输出为fcgi的STDERR。不确定代码中在应用中没有任何输出数据的STDERRS中是否存在竞争条件,这个包装器很好满足了我的目标。包装器中99.9%的部分来自邮件列表和wiki,我(原作者)只添加了一些管道处理从而确保能够通过STDERR进行通信,以及一个接受合适的数据流的选择循环。

#!perl
use FCGI;
use Socket;
use FCGI::ProcManager;
sub shutdown { FCGI::CloseSocket($socket); exit; }
sub restart  { FCGI::CloseSocket($socket); &main; }
use sigtrap 'handler', &shutdown, 'normal-signals';
use sigtrap 'handler', &restart,  'HUP';
require 'syscall.ph';
use POSIX qw(setsid);
 
END()  { }
BEGIN() { }
{
  no warnings;
  *CORE::GLOBAL::exit = sub { die "fakeexitnrc=" . shift() . "n"; };
};
 
eval q{exit};
if ([email protected]) {
  exit unless [email protected] =~ /^fakeexit/;
}
&main;
 
sub daemonize() {
  chdir '/' or die "Can't chdir to /: $!";
  defined( my $pid = fork ) or die "Can't fork: $!";
  exit if $pid;
  setsid() or die "Can't start a new session: $!";
  umask 0;
}
 
sub main {
  $proc_manager = FCGI::ProcManager->new( {n_processes => 5} );
  $socket = FCGI::OpenSocket( "/var/run/nginx/cgiwrap-dispatch.sock", 10 )
  ; #use UNIX sockets - user running this script must have w access to the 'nginx' folder!!
  $request =
  FCGI::Request( *STDIN, *STDOUT, *STDERR, %req_params, $socket,
  &FCGI::FAIL_ACCEPT_ON_INTR );
  $proc_manager->pm_manage();
  if ($request) { request_loop() }
  FCGI::CloseSocket($socket);
}
 
sub request_loop {
  while ( $request->Accept() >= 0 ) {
    $proc_manager->pm_pre_dispatch();
 
    #processing any STDIN input from WebServer (for CGI-POST actions)
    $stdin_passthrough = '';
    { no warnings; $req_len = 0 $req_params{'CONTENT_LENGTH'}; };
    if ( ( $req_params{'REQUEST_METHOD'} eq 'POST' ) && ( $req_len != 0 ) ) {
      my $bytes_read = 0;
      while ( $bytes_read < $req_len ) {
        my $data = '';
        my $bytes = read( STDIN, $data, ( $req_len - $bytes_read ) );
        last if ( $bytes == 0 || !defined($bytes) );
        $stdin_passthrough .= $data;
        $bytes_read = $bytes;
      }
    }
 
    #running the cgi app
    if (
      ( -x $req_params{SCRIPT_FILENAME} ) &&    #can I execute this?
      ( -s $req_params{SCRIPT_FILENAME} ) &&    #Is this file empty?
      ( -r $req_params{SCRIPT_FILENAME} )      #can I read this file?
    ) {
      pipe( CHILD_RD,  PARENT_WR );
      pipe( PARENT_ERR, CHILD_ERR );
      my $pid = open( CHILD_O, "-|" );
      unless ( defined($pid) ) {
        print("Content-type: text/plainrnrn");
        print "Error: CGI app returned no output - Executing $req_params{SCRIPT_FILENAME} failed !n";
        next;
      }
      $oldfh = select(PARENT_ERR);
      $|    = 1;
      select(CHILD_O);
      $| = 1;
      select($oldfh);
      if ( $pid > 0 ) {
        close(CHILD_RD);
        close(CHILD_ERR);
        print PARENT_WR $stdin_passthrough;
        close(PARENT_WR);
        $rin = $rout = $ein = $eout = '';
        vec( $rin, fileno(CHILD_O),    1 ) = 1;
        vec( $rin, fileno(PARENT_ERR), 1 ) = 1;
        $ein    = $rin;
        $nfound = 0;
 
        while ( $nfound = select( $rout = $rin, undef, $ein = $eout, 10 ) ) {
          die "$!" unless $nfound != -1;
          $r1 = vec( $rout, fileno(PARENT_ERR), 1 ) == 1;
          $r2 = vec( $rout, fileno(CHILD_O),    1 ) == 1;
          $e1 = vec( $eout, fileno(PARENT_ERR), 1 ) == 1;
          $e2 = vec( $eout, fileno(CHILD_O),    1 ) == 1;
 
          if ($r1) {
            while ( $bytes = read( PARENT_ERR, $errbytes, 4096 ) ) {
              print STDERR $errbytes;
            }
            if ($!) {
              $err = $!;
              die $!;
              vec( $rin, fileno(PARENT_ERR), 1 ) = 0
              unless ( $err == EINTR or $err == EAGAIN );
            }
          }
          if ($r2) {
            while ( $bytes = read( CHILD_O, $s, 4096 ) ) {
              print $s;
            }
            if ( !defined($bytes) ) {
              $err = $!;
              die $!;
              vec( $rin, fileno(CHILD_O), 1 ) = 0
              unless ( $err == EINTR or $err == EAGAIN );
            }
          }
          last if ( $e1 || $e2 );
        }
        close CHILD_RD;
        close PARENT_ERR;
        waitpid( $pid, 0 );
      } else {
        foreach $key ( keys %req_params ) {
          $ENV{$key} = $req_params{$key};
        }
 
        # cd to the script's local directory
        if ( $req_params{SCRIPT_FILENAME} =~ /^(.*)/[^/] $/ ) {
          chdir $1;
        }
        close(PARENT_WR);
        #close(PARENT_ERR);
        close(STDIN);
        close(STDERR);
 
        #fcntl(CHILD_RD, F_DUPFD, 0);
        syscall( &SYS_dup2, fileno(CHILD_RD),  0 );
        syscall( &SYS_dup2, fileno(CHILD_ERR), 2 );
 
        #open(STDIN, "<&CHILD_RD");
        exec( $req_params{SCRIPT_FILENAME} );
        die("exec failed");
      }
    } else {
      print("Content-type: text/plainrnrn");
      print "Error: No such CGI app - $req_params{SCRIPT_FILENAME} may not exist or is not executable by this process.n";
    }
  }
}
Save the above script as /usr/local/bin/cgiwrap-fcgi.pl.
将上述文件保存为/usr/local/bin/cgiwrap-fcgi.pl。

Just running the program as above will bind it to a unix socket at /var/run/nginx/cgiwrap-dispatch.sock . Be sure your nginx worker process user has read/write access to this file. The script does not fork itself, so you will need to background it somehow (with Bash add an ampersand "&" at the end of your command to execute it).

运行上述程序将会将其绑定到位于/var/run/nginx/cgiwrap-dispatch.sock的Unix套接字。取保Nginx工作进程具有文件的读写权限。该脚本不会自我终结(?),需要将其运行为后台程序(Bash中在执行命令后添加&)

If this all works, then the next part is to setup Nginx:

如果工作了,接下来就是启动Nginx:

http {
  root  /var/www/htdocs;
  index index.html;
  location ~ ^/cgi-bin/.*.cgi$ {
    gzip off; #gzip makes scripts feel slower since they have to complete before getting gzipped
    fastcgi_pass  unix:/var/run/nginx/cgiwrap-dispatch.sock;
    fastcgi_index index.cgi;
    fastcgi_param SCRIPT_FILENAME /var/www/cgi-bin$fastcgi_script_name;
    fastcgi_param QUERY_STRING    $query_string;
    fastcgi_param REQUEST_METHOD  $request_method;
    fastcgi_param CONTENT_TYPE    $content_type;
    fastcgi_param CONTENT_LENGTH  $content_length;
    fastcgi_param GATEWAY_INTERFACE  CGI/1.1;
    fastcgi_param SERVER_SOFTWARE    nginx;
    fastcgi_param SCRIPT_NAME        $fastcgi_script_name;
    fastcgi_param REQUEST_URI        $request_uri;
    fastcgi_param DOCUMENT_URI      $document_uri;
    fastcgi_param DOCUMENT_ROOT      $document_root;
    fastcgi_param SERVER_PROTOCOL    $server_protocol;
    fastcgi_param REMOTE_ADDR        $remote_addr;
    fastcgi_param REMOTE_PORT        $remote_port;
    fastcgi_param SERVER_ADDR        $server_addr;
    fastcgi_param SERVER_PORT        $server_port;
    fastcgi_param SERVER_NAME        $server_name;
  }
}
Restart Nginx and point your browser at your CGI program. The above sample config will execute any .cgi file in cgi-bin with the cgiwrap-fcgi.pl wrapper, tweak this to your heart's content.
重启Nginx并将浏览器定向到CGI程序的URL。上面的简单配置将会使用cgiwrap-fcgi.pl包装执行位于cgi-bin所有.cgi后缀的文件,请谨记这一点,这可能会很危险。

I've been able to run Python, Perl, and C cgi apps with this - apps that use GET or POST.

可以使用GET或POST方法的C ,Perl,Python的cgi应用都可运行。

You may find that $document_root does not point to your actual document root (hardcoded upon build), so you can replace the fastcgi param DOCUMENT_ROOT with "/the/real/path". Also replace the SCRIPT_FILENAME param if that is used by your CGI wrapper (the one above does)

可以看到,$document_root没有指向实际的文档root(依赖构建的硬编码),需要将fastcgi参数DOCUMENT_ROOT替代为真实可用的参数,并将SCRIPT_FILENAME参书替代为CGI包装器使用的真实值。

后记
虽然,没有写过CGI代码,也没有配置安装过Nginx,但我觉的这些东西都很有趣,等我学完Rails,一定要好好研究研究Nginx,和Apahce一起比对学习。

更多Nginx相关教程见以下内容:

CentOS 6.2实战部署Nginx MySQL PHP

使用Nginx搭建WEB服务器

搭建基于Linux6.3 Nginx1.2 PHP5 MySQL5.5的Web服务器全过程

CentOS 6.3下Nginx性能调优

CentOS 6.3下配置Nginx加载ngx_pagespeed模块

CentOS 6.4安装配置Nginx Pcre php-fpm

Nginx安装配置使用详细笔记

Nginx日志过滤 使用ngx_log_if不记录特定日志

Nginx 的详细介绍:请点这里
Nginx 的下载地址:请点这里

本文永久更新链接地址:

缘起 在探索到CGI到底为何物时,google SimpleCGI的时候,看到这篇文章,粗看了几眼,觉得不错,有几个感兴趣的topic:...

虚拟机配置文件为/usr/local/nginx/conf/vhosts.conf

目前php fast-cgi已支持

以下操作均在su下完成

=====================

安装perl cgi模块

wget       
tar -zxvf FCGI-0.67.tar.gz      
cd FCGI-0.67      
perl Makefile.PL     
make && make install

安装FCGI-ProcManager:
wget      
tar -xzxf FCGI-ProcManager-0.18.tar.gz      
cd FCGI-ProcManager-0.18      
perl Makefile.PL      
make      make install

===================

先在/bin目录下放置一个perl写的分发器,取名叫perl-fcgi

vi /bin/perl-cgi

  1. #!/usr/bin/perl -w   
  2. use FCGI;   
  3. use Socket;   
  4. use FCGI::ProcManager;   
  5. sub shutdown { FCGI::CloseSocket($socket); exit; }   
  6. sub restart  { FCGI::CloseSocket($socket); &main; }   
  7. use sigtrap 'handler', &shutdown, 'normal-signals';   
  8. use sigtrap 'handler', &restart,  'HUP';   
  9. require 'syscall.ph';   
  10. use POSIX qw(setsid);   
  11.     
  12. #&daemonize; we don't daemonize when running under runsv   
  13. #this keeps the program alive or something after exec'ing perl scripts   
  14. END()   { }   
  15. BEGIN() { }   
  16. {   
  17.     no warnings;   
  18.     *CORE::GLOBAL::exit = sub { die "fakeexitnrc=" . shift() . "n"; };   
  19. };   
  20. eval q{exit};   
  21. if ($@) {   
  22.     exit unless $@ =~ /^fakeexit/;   
  23. }   
  24. &main;   
  25.     
  26. sub daemonize() {   
  27.     chdir '/' or die "Can't chdir to /: $!";   
  28.     defined( my $pid = fork ) or die "Can't fork: $!";   
  29.     exit if $pid;   
  30.     setsid() or die "Can't start a new session: $!";   
  31.     umask 0;   
  32. }   
  33.     
  34. sub main {   
  35.     
  36.      $socket = FCGI::OpenSocket( "127.0.0.1:10081", 10 ); #use IP sockets   
  37.     #$socket = FCGI::OpenSocket( "/var/run/nginx/perl_cgi-dispatch.sock", 10 );    
  38.     #use UNIX sockets - user running this script must have w access to the 'nginx' folder!!   
  39.     #foreach $item (keys %ENV) { delete $ENV{$item}; }   
  40.     $proc_manager = FCGI::ProcManager->new( {n_processes => 5} );   
  41.     #$socket = FCGI::OpenSocket( "/opt/nginx/fcgi/cgi.sock", 10 )   
  42.         ; #use UNIX sockets - user running this script must have w access to the 'nginx' folder!!   
  43.     $request =   
  44.         FCGI::Request( *STDIN, *STDOUT, *STDERR, %req_params, $socket,   
  45.         &FCGI::FAIL_ACCEPT_ON_INTR );   
  46.     $proc_manager->pm_manage();   
  47.     if ($request) { request_loop() }   
  48.     FCGI::CloseSocket($socket);   
  49. }   
  50.     
  51. sub request_loop {   
  52.     while ( $request->Accept() >= 0 ) {   
  53.         $proc_manager->pm_pre_dispatch();   
  54.     
  55.         #processing any STDIN input from WebServer (for CGI-POST actions)   
  56.         $stdin_passthrough = '';   
  57.         { no warnings; $req_len = 0   $req_params{'CONTENT_LENGTH'}; };   
  58.         if ( ( $req_params{'REQUEST_METHOD'} eq 'POST' ) && ( $req_len != 0 ) )   
  59.         {   
  60.             my $bytes_read = 0;   
  61.             while ( $bytes_read < $req_len ) {   
  62.                 my $data = '';   
  63.                 my $bytes = read( STDIN, $data, ( $req_len - $bytes_read ) );   
  64.                 last if ( $bytes == 0 || !defined($bytes) );   
  65.                 $stdin_passthrough .= $data;   
  66.                 $bytes_read  = $bytes;   
  67.             }   
  68.         }   
  69.     
  70.         #running the cgi app   
  71.         if (   
  72.             ( -x $req_params{SCRIPT_FILENAME} ) &&    #can I execute this?   
  73.             ( -s $req_params{SCRIPT_FILENAME} ) &&    #Is this file empty?   
  74.             ( -r $req_params{SCRIPT_FILENAME} )       #can I read this file?   
  75.             )   
  76.         {   
  77.             pipe( CHILD_RD,   PARENT_WR );   
  78.             pipe( PARENT_ERR, CHILD_ERR );   
  79.             my $pid = open( CHILD_O, "-|" );   
  80.             unless ( defined($pid) ) {   
  81.                 print("Content-type: text/plainrnrn");   
  82.                 print  
  83. "Error: CGI app returned no output - Executing $req_params{SCRIPT_FILENAME} failed !n";   
  84.                 next;   
  85.             }   
  86.             $oldfh = select(PARENT_ERR);   
  87.             $|     = 1;   
  88.             select(CHILD_O);   
  89.             $| = 1;   
  90.             select($oldfh);   
  91.             if ( $pid > 0 ) {   
  92.                 close(CHILD_RD);   
  93.                 close(CHILD_ERR);   
  94.                 print PARENT_WR $stdin_passthrough;   
  95.                 close(PARENT_WR);   
  96.                 $rin = $rout = $ein = $eout = '';   
  97.                 vec( $rin, fileno(CHILD_O),    1 ) = 1;   
  98.                 vec( $rin, fileno(PARENT_ERR), 1 ) = 1;   
  99.                 $ein    = $rin;   
  100.                 $nfound = 0;   
  101.     
  102.                 while ( $nfound =   
  103.                     select( $rout = $rin, undef, $ein = $eout, 10 ) )   
  104.                 {   
  105.                     die "$!" unless $nfound != -1;   
  106.                     $r1 = vec( $rout, fileno(PARENT_ERR), 1 ) == 1;   
  107.                     $r2 = vec( $rout, fileno(CHILD_O),    1 ) == 1;   
  108.                     $e1 = vec( $eout, fileno(PARENT_ERR), 1 ) == 1;   
  109.                     $e2 = vec( $eout, fileno(CHILD_O),    1 ) == 1;   
  110.     
  111.                     if ($r1) {   
  112.                         while ( $bytes = read( PARENT_ERR, $errbytes, 4096 ) ) {   
  113.                             print STDERR $errbytes;   
  114.                         }   
  115.                         if ($!) {   
  116.                             $err = $!;   
  117.                             die $!;   
  118.                             vec( $rin, fileno(PARENT_ERR), 1 ) = 0  
  119.                                 unless ( $err == EINTR or $err == EAGAIN );   
  120.                         }   
  121.                     }   
  122.                     if ($r2) {   
  123.                         while ( $bytes = read( CHILD_O, $s, 4096 ) ) {   
  124.                             print $s;   
  125.                         }   
  126.                         if ( !defined($bytes) ) {   
  127.                             $err = $!;   
  128.                             die $!;   
  129.                             vec( $rin, fileno(CHILD_O), 1 ) = 0  
  130.                                 unless ( $err == EINTR or $err == EAGAIN );   
  131.                         }   
  132.                     }   
  133.                     last if ( $e1 || $e2 );   
  134.                 }   
  135.                 close CHILD_RD;   
  136.                 close PARENT_ERR;   
  137.                 waitpid( $pid, 0 );   
  138.             } else {   
  139.                 foreach $key ( keys %req_params ) {   
  140.                     $ENV{$key} = $req_params{$key};   
  141.                 }   
  142.     
  143.                 # cd to the script's local directory   
  144.                 if ( $req_params{SCRIPT_FILENAME} =~ /^(.*)/[^/] $/ ) {   
  145.                     chdir $1;   
  146.                 }   
  147.                 close(PARENT_WR);   
  148.     
  149.                 #close(PARENT_ERR);   
  150.                 close(STDIN);   
  151.                 close(STDERR);   
  152.     
  153.                 #fcntl(CHILD_RD, F_DUPFD, 0);   
  154.                 syscall( &SYS_dup2, fileno(CHILD_RD),  0 );   
  155.                 syscall( &SYS_dup2, fileno(CHILD_ERR), 2 );   
  156.     
  157.                 #open(STDIN, "<&CHILD_RD");   
  158.                 exec( $req_params{SCRIPT_FILENAME} );   
  159.                 die("exec failed");   
  160.             }   
  161.         } else {   
  162.             print("Content-type: text/plainrnrn");   
  163.             print  
  164. "Error: No such CGI app - $req_params{SCRIPT_FILENAME} may not exist or is not executable by this process.n";   
  165.         }   
  166.     }   
  167. }  

给这个脚本执行权限

chmod x  /bin/perl-fcgi
然后试试看能否启动
/bin/perl-cgi &
若是成功则会出现以下信息
FastCGI: server (pid 21315): initialized
FastCGI: manager (pid 17915): server (pid 21315) started

如果遇到错误Can’t locate FCGI.pm,那么执行下面的命令

perl -MCPAN -e 'install FCGI'

perl -MCPAN -e 'install FCGI::ProcManager'

cd /usr/include; h2ph *.h */*.h

第一、二条命令是给perl安装FCGI模块,第三条是注册perl能识别的头文件,然后重新执行/bin/perl-fcgi, 如果正常的话,那么执行:

netstat -tunlp

列表中应该出现
tcp        0      0 127.0.0.1:10081             0.0.0.0:*                   LISTEN      5640/perl
启用分发器

/bin/perl-fcgi > /dev/null 2>&1 &
将其写入rc.local
echo "/bin/perl-fcgi > /dev/null 2>&1 &" >> /etc/rc.local
上面的方式启动后perl-fcgi是以执行它的用户身份运行的,对于web程序来说这是很不利的。老外用perl写了一个脚本Noah Friedman可以用指定的用户来运行某个程序,源程序在这里,这里也贴出来方便查阅

图片 1

版权声明:本文由威尼斯人app发布于电脑操作,转载请注明出处:配置Nginx 运转CGI(Perl-cgi)