Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1091824
  • 博文数量: 155
  • 博客积分: 2525
  • 博客等级: 大尉
  • 技术积分: 2242
  • 用 户 组: 普通用户
  • 注册时间: 2011-05-05 20:52
文章分类

全部博文(155)

文章存档

2013年(1)

2012年(149)

2011年(5)

分类: LINUX

2012-06-23 13:29:26


点击(此处)折叠或打开

  1. #include <stdarg.h>
  2. #include <errno.h>
  3. #include <stdio.h>
  4. #include <fcntl.h>
  5. #include <unistd.h>
  6. #include <string.h>
  7. #include <time.h>
  8. #include <sys/types.h>
  9. #include <sys/stat.h>
  10. #include <dirent.h>
  11. #include <errno.h>
  12. #include <netinet/in.h>
  13. #include <sys/socket.h>
  14. #include <resolv.h>
  15. #include <arpa/inet.h>
  16. #include <stdlib.h>
  17. #include <signal.h>
  18. #include <getopt.h>

  19. #define DEFAULTIP "127.0.0.1"
  20. #define DEFAULTPORT "80"
  21. #define DEFAULTBACK "10"
  22. #define DEFAULTDIR "/home"
  23. #define DEFAULTLOG "/tmp/das-server.log"

  24. void prterrmsg(char *msg);
  25. #define prterrmsg(msg) { perror(msg); abort(); }
  26. void wrterrmsg(char *msg);
  27. #define wrterrmsg(msg) { fputs(msg, logfp); fputs(strerror(errno), logfp);fflush(logfp); abort(); }

  28. void prtinfomsg(char *msg);
  29. #define prtinfomsg(msg) { fputs(msg, stdout); }
  30. void wrtinfomsg(char *msg);
  31. #define wrtinfomsg(msg) { fputs(msg, logfp); fflush(logfp);}

  32. #define MAXBUF 1024

  33. char buffer[MAXBUF + 1];
  34. char *host = 0;
  35. char *port = 0;
  36. char *back = 0;
  37. char *dirroot = 0;
  38. char *logdir = 0;
  39. unsigned char daemon_y_n = 0;
  40. FILE *logfp;

  41. #define MAXPATH 150

  42. /*----------------------------------------
  43.  *--- dir_up - 查找dirpath所指目录的上一级目录
  44.  *----------------------------------------
  45.  */
  46. char *dir_up(char *dirpath)
  47. {
  48.     static char Path[MAXPATH];
  49.     int len;

  50.     strcpy(Path, dirpath);
  51.     len = strlen(Path);
  52.     if (len > 1 && Path[len - 1] == '/')
  53.         len--;
  54.     while (Path[len - 1] != '/' && len > 1)
  55.         len--;
  56.     Path[len] = 0;
  57.     return Path;
  58. }

  59. /*------------------------------------------------------
  60.  *--- AllocateMemory - 分配空间并把d所指的内容复制
  61.  *------------------------------------------------------
  62.  */
  63. void AllocateMemory(char **s, int l, char *d)
  64. {
  65.     *s = malloc(l + 1);
  66.     bzero(*s, l + 1);
  67.     memcpy(*s, d, l);
  68. }
  69. /************关于本文档********************************************
  70. *filename: das-server.c
  71. *purpose: 这是在Linux下用C语言写的目录访问服务器,支持目录浏览和文件下载
  72. *wrote by: zhoulifa(zhoulifa@163.com) 周立发(http://zhoulifa.bokee.com)
  73. Linux爱好者 Linux知识传播者 SOHO族 开发者 最擅长C语言
  74. *date time:2007-01-26 19:32
  75. *Note: 任何人可以任意复制代码并运用这些文档,当然包括你的商业用途
  76. * 但请遵循GPL
  77. *Thanks to: Google.com
  78. *Hope:希望越来越多的人贡献自己的力量,为科学技术发展出力
  79. * 科技站在巨人的肩膀上进步更快!感谢有开源前辈的贡献!
  80. *********************************************************************/
  81. /*------------------------------------------------------
  82.  *--- GiveResponse - 把Path所指的内容发送到client_sock去
  83.  *-------------------如果Path是一个目录,则列出目录内容
  84.  *-------------------如果Path是一个文件,则下载文件
  85.  *------------------------------------------------------
  86.  */
  87. void GiveResponse(FILE * client_sock, char *Path)
  88. {
  89.     struct dirent *dirent;
  90.     struct stat info;
  91.     char Filename[MAXPATH];
  92.     DIR *dir;
  93.     int fd, len, ret;
  94.     char *p, *realPath, *realFilename, *nport;

  95.     /* 获得实际工作目录或文件 */
  96.     len = strlen(dirroot) + strlen(Path) + 1;
  97.     realPath = malloc(len + 1);
  98.     bzero(realPath, len + 1);
  99.     sprintf(realPath, "%s/%s", dirroot, Path);

  100.     /* 获得实际工作端口 */
  101.     len = strlen(port) + 1;
  102.     nport = malloc(len + 1);
  103.     bzero(nport, len + 1);
  104.     sprintf(nport, ":%s", port);

  105.     /* 获得实际工作目录或文件的信息以判断是文件还是目录 */
  106.     if (stat(realPath, &info)) {
  107.         fprintf(client_sock,
  108.                 "HTTP/1.1 200 OK\r\nServer: DAS by ZhouLifa\r\nConnection: close\r\n\r\n%d - %s"
  109.                 "Linux 下目录访问服务器

    100%%\">
    "
  110.                 "100%%\">", errno,
  111.                 strerror(errno));
  112.         fprintf(client_sock,
  113.                 "
  114. CC0000\" size=+2>请向管理员咨询为何出现如下错误提示:\n%s %s "
    ,
  115.                 Path, strerror(errno));
  116.         goto out;
  117.     }
  118.     /* 处理浏览文件请求,即下载文件 */
  119.     if (S_ISREG(info.st_mode)) {
  120.         fd = open(realPath, O_RDONLY);
  121.         len = lseek(fd, 0, SEEK_END);
  122.         p = (char *) malloc(len + 1);
  123.         bzero(p, len + 1);
  124.         lseek(fd, 0, SEEK_SET);
  125.         ret = read(fd, p, len);
  126.         close(fd);
  127.         fprintf(client_sock,
  128.                 "HTTP/1.1 200 OK\r\nServer: DAS by ZhouLifa\r\nConnection: keep-alive\r\nContent-type: application/*\r\nContent-Length:%d\r\n\r\n",
  129.                 len);
  130.         fwrite(p, len, 1, client_sock);
  131.         free(p);
  132.     } else if (S_ISDIR(info.st_mode)) {
  133.         /* 处理浏览目录请求 */
  134.         dir = opendir(realPath);
  135.         fprintf(client_sock,
  136.                 "HTTP/1.1 200 OK\r\nServer: DAS by ZhouLifa\r\nConnection: close\r\n\r\n%s"
  137.                 "Linux 下目录访问服务器

    100%%\">
    "
  138.                 "100%%\">", Path);
  139.         fprintf(client_sock,
  140.                 "
  141. \n",
  142.                 Path);
  143.         fprintf(client_sock,
  144.                 "
  145. \n");
  146.         if (dir == 0) {
  147.             fprintf(client_sock,
  148.                     "
  149. 目录 %s
    名称大小修改时间
    CC0000\" size=+2>%s"
    ,
  150.                     strerror(errno));
  151.             return;
  152.         }
  153.         /* 读取目录里的所有内容 */
  154.         while ((dirent = readdir(dir)) != 0) {
  155.             if (strcmp(Path, "/") == 0)
  156.                 sprintf(Filename, "/%s", dirent->d_name);
  157.             else
  158.                 sprintf(Filename, "%s/%s", Path, dirent->d_name);
  159.             fprintf(client_sock, "");
  160.             len = strlen(dirroot) + strlen(Filename) + 1;
  161.             realFilename = malloc(len + 1);
  162.             bzero(realFilename, len + 1);
  163.             sprintf(realFilename, "%s/%s", dirroot, Filename);
  164.             if (stat(realFilename, &info) == 0) {
  165.                 if (strcmp(dirent->d_name, "..") == 0)
  166.                     fprintf(client_sock,
  167.                             "http://%s%s%s\">(parent)",
  168.                             host, atoi(port) == 80 ? "" : nport,
  169.                             dir_up(Path));
  170.                 else
  171.                     fprintf(client_sock,
  172.                             "http://%s%s%s\">%s",
  173.                             host, atoi(port) == 80 ? "" : nport, Filename,
  174.                             dirent->d_name);
  175.                 if (S_ISDIR(info.st_mode))
  176.                     fprintf(client_sock, "目录");
  177.                 else if (S_ISREG(info.st_mode))
  178.                     fprintf(client_sock, "%d", info.st_size);
  179.                 else if (S_ISLNK(info.st_mode))
  180.                     fprintf(client_sock, "链接");
  181.                 else if (S_ISCHR(info.st_mode))
  182.                     fprintf(client_sock, "字符设备");
  183.                 else if (S_ISBLK(info.st_mode))
  184.                     fprintf(client_sock, "块设备");
  185.                 else if (S_ISFIFO(info.st_mode))
  186.                     fprintf(client_sock, "FIFO");
  187.                 else if (S_ISSOCK(info.st_mode))
  188.                     fprintf(client_sock, "Socket");
  189.                 else
  190.                     fprintf(client_sock, "(未知)");
  191.                 fprintf(client_sock, "%s", ctime(&info.st_ctime));
  192.             }
  193.             fprintf(client_sock, "\n");
  194.             free(realFilename);
  195.         }
  196.         fprintf(client_sock, "");
  197.     } else {
  198.         /* 既非常规文件又非目录,禁止访问 */
  199.         fprintf(client_sock,
  200.                 "HTTP/1.1 200 OK\r\nServer: DAS by ZhouLifa\r\nConnection: close\r\n\r\npermission denied"
  201.                 "Linux 下目录访问服务器

    100%%\">
    "
  202.                 "100%%\">");
  203.         fprintf(client_sock,
  204.                 "
  205. CC0000\" size=+2>你访问的资源'%s'被禁止访问,请联系管理员解决!"
    ,
  206.                 Path);
  207.     }
  208.   out:
  209.     free(realPath);
  210.     free(nport);
  211. }

  212. /*------------------------------------------------------
  213.  *--- getoption - 分析取出程序的参数
  214.  *------------------------------------------------------
  215.  */
  216. void getoption(int argc, char **argv)
  217. {
  218.     int c, len;
  219.     char *p = 0;

  220.     opterr = 0;
  221.     while (1) {
  222.         int option_index = 0;
  223.         static struct option long_options[] = {
  224.             {"host", 1, 0, 0},
  225.             {"port", 1, 0, 0},
  226.             {"back", 1, 0, 0},
  227.             {"dir", 1, 0, 0},
  228.             {"log", 1, 0, 0},
  229.             {"daemon", 0, 0, 0},
  230.             {0, 0, 0, 0}
  231.         };
  232.         /* 本程序支持如一些参数:
  233.          * --host IP地址 或者 -H IP地址
  234.          * --port 端口 或者 -P 端口
  235.          * --back 监听数量 或者 -B 监听数量
  236.          * --dir 网站根目录 或者 -D 网站根目录
  237.          * --log 日志存放路径 或者 -L 日志存放路径
  238.          * --daemon 使程序进入后台运行模式
  239.          */
  240.         c = getopt_long(argc, argv, "H:P:B:D:L",
  241.                         long_options, &option_index);
  242.         if (c == -1 || c == '?')
  243.             break;

  244.         if(optarg) len = strlen(optarg);
  245.         else len = 0;

  246.         if ((!c && !(strcasecmp(long_options[option_index].name, "host")))
  247.             || c == 'H')
  248.             p = host = malloc(len + 1);
  249.         else if ((!c
  250.                   &&
  251.                   !(strcasecmp(long_options[option_index].name, "port")))
  252.                  || c == 'P')
  253.             p = port = malloc(len + 1);
  254.         else if ((!c
  255.                   &&
  256.                   !(strcasecmp(long_options[option_index].name, "back")))
  257.                  || c == 'B')
  258.             p = back = malloc(len + 1);
  259.         else if ((!c
  260.                   && !(strcasecmp(long_options[option_index].name, "dir")))
  261.                  || c == 'D')
  262.             p = dirroot = malloc(len + 1);
  263.         else if ((!c
  264.                   && !(strcasecmp(long_options[option_index].name, "log")))
  265.                  || c == 'L')
  266.             p = logdir = malloc(len + 1);
  267.         else if ((!c
  268.                   &&
  269.                   !(strcasecmp
  270.                     (long_options[option_index].name, "daemon")))) {
  271.             daemon_y_n = 1;
  272.             continue;
  273.         }
  274.         else
  275.             break;
  276.         bzero(p, len + 1);
  277.         memcpy(p, optarg, len);
  278.     }
  279. }

  280. int main(int argc, char **argv)
  281. {
  282.     struct sockaddr_in addr;
  283.     int sock_fd, addrlen;

  284.     /* 获得程序工作的参数,如 IP 、端口、监听数、网页根目录、目录存放位置等 */
  285.     getoption(argc, argv);

  286.     if (!host) {
  287.         addrlen = strlen(DEFAULTIP);
  288.         AllocateMemory(&host, addrlen, DEFAULTIP);
  289.     }
  290.     if (!port) {
  291.         addrlen = strlen(DEFAULTPORT);
  292.         AllocateMemory(&port, addrlen, DEFAULTPORT);
  293.     }
  294.     if (!back) {
  295.         addrlen = strlen(DEFAULTBACK);
  296.         AllocateMemory(&back, addrlen, DEFAULTBACK);
  297.     }
  298.     if (!dirroot) {
  299.         addrlen = strlen(DEFAULTDIR);
  300.         AllocateMemory(&dirroot, addrlen, DEFAULTDIR);
  301.     }
  302.     if (!logdir) {
  303.         addrlen = strlen(DEFAULTLOG);
  304.         AllocateMemory(&logdir, addrlen, DEFAULTLOG);
  305.     }

  306.     printf
  307.         ("host=%s port=%s back=%s dirroot=%s logdir=%s %s是后台工作模式(进程ID:%d)\n",
  308.          host, port, back, dirroot, logdir, daemon_y_n?"":"不", getpid());

  309.     /* fork() 两次处于后台工作模式下 */
  310.     if (daemon_y_n) {
  311.         if (fork())
  312.             exit(0);
  313.         if (fork())
  314.             exit(0);
  315.         close(0), close(1), close(2);
  316.         logfp = fopen(logdir, "a+");
  317.         if (!logfp)
  318.             exit(0);
  319.     }

  320.     /* 处理子进程退出以免产生僵尸进程 */
  321.     signal(SIGCHLD, SIG_IGN);

  322.     /* 创建 socket */
  323.     if ((sock_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  324.         if (!daemon_y_n) {
  325.             prterrmsg("socket()");
  326.         } else {
  327.             wrterrmsg("socket()");
  328.         }
  329.     }

  330.     /* 设置端口快速重用 */
  331.     addrlen = 1;
  332.     setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &addrlen,
  333.                sizeof(addrlen));

  334.     addr.sin_family = AF_INET;
  335.     addr.sin_port = htons(atoi(port));
  336.     addr.sin_addr.s_addr = inet_addr(host);
  337.     addrlen = sizeof(struct sockaddr_in);
  338.     /* 绑定地址、端口等信息 */
  339.     if (bind(sock_fd, (struct sockaddr *) &addr, addrlen) < 0) {
  340.         if (!daemon_y_n) {
  341.             prterrmsg("bind()");
  342.         } else {
  343.             wrterrmsg("bind()");
  344.         }
  345.     }

  346.     /* 开启临听 */
  347.     if (listen(sock_fd, atoi(back)) < 0) {
  348.         if (!daemon_y_n) {
  349.             prterrmsg("listen()");
  350.         } else {
  351.             wrterrmsg("listen()");
  352.         }
  353.     }
  354.     while (1) {
  355.         int len;
  356.         int new_fd;
  357.         addrlen = sizeof(struct sockaddr_in);
  358.         /* 接受新连接请求 */
  359.         new_fd = accept(sock_fd, (struct sockaddr *) &addr, &addrlen);
  360.         if (new_fd < 0) {
  361.             if (!daemon_y_n) {
  362.                 prterrmsg("accept()");
  363.             } else {
  364.                 wrterrmsg("accept()");
  365.             }
  366.             break;
  367.         }
  368.         bzero(buffer, MAXBUF + 1);
  369.         sprintf(buffer, "连接来自于: %s:%d\n",
  370.                 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
  371.         if (!daemon_y_n) {
  372.             prtinfomsg(buffer);
  373.         } else {
  374.             wrtinfomsg(buffer);
  375.         }
  376.         /* 产生一个子进程去处理请求,当前进程继续等待新的连接到来 */
  377.         if (!fork()) {
  378.             bzero(buffer, MAXBUF + 1);
  379.             if ((len = recv(new_fd, buffer, MAXBUF, 0)) > 0) {
  380.                 FILE *ClientFP = fdopen(new_fd, "w");
  381.                 if (ClientFP == NULL) {
  382.                     if (!daemon_y_n) {
  383.                         prterrmsg("fdopen()");
  384.                     } else {
  385.                         prterrmsg("fdopen()");
  386.                     }
  387.                 } else {
  388.                     char Req[MAXPATH + 1] = "";
  389.                     sscanf(buffer, "GET %s HTTP", Req);
  390.                     bzero(buffer, MAXBUF + 1);
  391.                     sprintf(buffer, "请求取文件: \"%s\"\n", Req);
  392.                     if (!daemon_y_n) {
  393.                         prtinfomsg(buffer);
  394.                     } else {
  395.                         wrtinfomsg(buffer);
  396.                     }
  397.                     /* 处理用户请求 */
  398.                     GiveResponse(ClientFP, Req);
  399.                     fclose(ClientFP);
  400.                 }
  401.             }
  402.             exit(0);
  403.         }
  404.         close(new_fd);
  405.     }
  406.     close(sock_fd);
  407.     return 0;
  408. }
编译程序用下列命令:
gcc -Wall das-server.c -o das-server
注:das即 Dictory Access Server

以root用户启动服务程序用下列命令:
./das-server
或以普通用户启动服务程序用下列命令:
./das-server --port 7838

./das-server -P 7838

注:只有root用户才有权限启动1024以下的端口,所以如果想用默认的80端口就得用root来运行。

如果要想让程序在后台自动运行,即处理精灵模式下工作,在命令后面加上--daemon参数即可。
阅读(10015) | 评论(0) | 转发(1) |
0

上一篇:水调歌头 【宋】陈亮

下一篇:C语言测试

给主人留下些什么吧!~~