Chinaunix首页 | 论坛 | 博客
  • 博客访问: 803093
  • 博文数量: 274
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 862
  • 用 户 组: 普通用户
  • 注册时间: 2015-10-24 15:31
个人简介

不合格的程序猿

文章分类

全部博文(274)

文章存档

2019年(3)

2018年(1)

2017年(4)

2016年(160)

2015年(106)

我的朋友

分类: LINUX

2016-01-05 20:24:26

 前几天读了张中庆老师的《Apache源代码全景分析》让我受益匪浅,因为公司最近要分析Apache源代码中的mod_ssl部分,但是这本书中这部分介绍的非常少,在此的基础上我开始了mod_ssl的探索:

    要分析mod_ssl,首先要分析的openssl在通信中的位置,那就是位于TCP以上,http(应用层以下),它是对应用层数据的加密过程,其中用到了比如RSA,sha1等加密算法,知道了它的位置,那么在apache服务器端它处于什么位置上呢?我们从挂钩入手。

    挂钩的概念:从大的方面来看,Apache对HTTP的请求可以分为连接、处理和断开连接三个阶段;从小的方面而言,每个阶段又可以分为更多的子阶段。比如对HTTP的请求,我们可以进一步划分为客户身份验证、客户权限认证、请求校验等阶段,每一个阶段调用相应的函数进行处理。在Apache中,这些子阶段可以用术语“挂钩(HOOK)”来描述。

    下面我们来看看mod_ssl的挂钩函数:

     static void ssl_register_hooks(apr_pool_t *p)
{
    /* ssl_hook_ReadReq needs to use the BrowserMatch settings so must
     * run after mod_setenvif's post_read_request hook. */
    static const char *pre_prr[] = { "mod_setenvif.c", NULL };

----------------------------------------------------过滤器-----------------------------------------------------

    ssl_io_filter_register(p);

----------------------------------------------------过滤器-----------------------------------------------------

----------------------------------------------------挂钩函数-----------------------------------------------------

    ap_hook_pre_connection(ssl_hook_pre_connection,NULL,NULL, APR_HOOK_MIDDLE);
    ap_hook_test_config   (ssl_hook_ConfigTest,    NULL,NULL, APR_HOOK_MIDDLE);
    ap_hook_post_config   (ssl_init_Module,        NULL,NULL, APR_HOOK_MIDDLE);
    ap_hook_http_scheme   (ssl_hook_http_scheme,   NULL,NULL, APR_HOOK_MIDDLE);
    ap_hook_default_port  (ssl_hook_default_port,  NULL,NULL, APR_HOOK_MIDDLE);
    ap_hook_pre_config    (ssl_hook_pre_config,    NULL,NULL, APR_HOOK_MIDDLE);
    ap_hook_child_init    (ssl_init_Child,         NULL,NULL, APR_HOOK_MIDDLE);
    ap_hook_check_user_id (ssl_hook_UserCheck,     NULL,NULL, APR_HOOK_FIRST);
    ap_hook_fixups        (ssl_hook_Fixup,         NULL,NULL, APR_HOOK_MIDDLE);
    ap_hook_access_checker(ssl_hook_Access,        NULL,NULL, APR_HOOK_MIDDLE);
    ap_hook_auth_checker  (ssl_hook_Auth,          NULL,NULL, APR_HOOK_MIDDLE);
    ap_hook_post_read_request(ssl_hook_ReadReq, pre_prr,NULL, APR_HOOK_MIDDLE);
    ap_hook_insert_filter (ssl_hook_Insert_Filter, NULL,NULL, APR_HOOK_MIDDLE);

----------------------------------------------------挂钩函数-----------------------------------------------------
/*    ap_hook_handler       (ssl_hook_Upgrade,       NULL,NULL, APR_HOOK_MIDDLE); */

    ssl_var_register(p);

    APR_REGISTER_OPTIONAL_FN(ssl_proxy_enable);
    APR_REGISTER_OPTIONAL_FN(ssl_engine_disable);

    APR_REGISTER_OPTIONAL_FN(ssl_extlist_by_oid);
}
   上面的代码可以清楚的看到挂钩函数的注册,在此先暂不考虑过滤器的内容虽然它非常重要,挂钩的注册都是以ap_hook_xxx为命名的,而调用则是ap_run_xxx,每一个挂钩的开始部分都是各个模块所通用的比如ap_hook_pre_connection,但是后面的比如ssl_hook_pre_connection则是各个模块对该挂钩的自己的实现,在程序中运行挂钩函数ap_run_pre_connection时,Apache会遍历所用注册过它的模块,调用顺序可以用后面的APR_HOOK_MIDDLE来声明。如果很多的挂钩都是APR_HOOK_MIDDLE顺序,那么Apache将任意执行APR_HOOK_MIDDLE相同的顺序。

    下面初探各个挂钩的含义:

    ap_hook_pre_connection(ssl_hook_pre_connection,NULL,NULL, APR_HOOK_MIDDLE);
    功能:初始化连接上下文,最重要的是初始化了ssl的过滤器,这个过滤器来真正调用read()函数来读取客户端请求。

    ap_hook_test_config   (ssl_hook_ConfigTest,    NULL,NULL, APR_HOOK_MIDDLE);
    功能:如果有证书,将列出所有证书文件。

    ap_hook_post_config   (ssl_init_Module,        NULL,NULL, APR_HOOK_MIDDLE);
    功能:这个函数相当复杂,所做的工作也非常之多,主要是读取证书、公私钥之类的操作。

    ap_hook_pre_config    (ssl_hook_pre_config,    NULL,NULL, APR_HOOK_MIDDLE);
    功能:初始化加密算法/初始化ssl库/加载加密算法等操作。

    ap_hook_child_init    (ssl_init_Child,         NULL,NULL, APR_HOOK_MIDDLE);

    功能:初始化ssl子进程并生成随机种子,重新获得互斥体

    ap_hook_post_read_request(ssl_hook_ReadReq, pre_prr,NULL, APR_HOOK_MIDDLE);
    功能:对url进行判断是否正确。

    ap_hook_insert_filter (ssl_hook_Insert_Filter, NULL,NULL, APR_HOOK_MIDDLE);

    功能:插入ssl过滤器。  

    在具体分析源代码前,对mod_ssl挂钩初步理解后我们来看看mod_ssl的挂钩在Apache中的位置。

    要理解mod_ssl在处理流程中的位置,我们首先要理解整个apache是怎么处理请求的。

    我们首先看Apache的初始化阶段,其中也是mod_ssl的初始化阶段

    Apache运行MAIN函数入口->首先要将相应的可选挂钩注册到核心->初始化在命令行输入的指令信息并赋值->分配全局内存池->将读取配置文件的命令行指令信息存放在相应的链表中->Apache根据指令加载与连接模块->对通过命令行传入的参数进行重写,只有mpm才用到->对指令进行进一步解析->读取配置文件,并生成配置树->

    注:Apache总是从读取配置文件如httpd.conf开始的,所有的指令读取后最重要保存到内存中。Apache是使用树结构保存所有的指令(ap_directive_t),在整个配置文件预处理结束后,整个配置文件将转换为ap_directive_t配置树结构。在这个阶段Apache会调用ap_set_listener函数来创建套接字,换句话说,Apache的socket是在读取配置文件时创建的。

    ->运行ap_run_pre_config()挂钩

    注:在处理配置树前,需要修改配置树的模块在此修改配置树,其中mod_ssl实现该挂钩,对应的挂钩函数为ssl_hook_pre_config(),在这个挂钩中,mod_ssl会初始化算法内存,加载ERR算法字符串,初始化SSL的lib库,加载所有的加密算法,判断SSL版本号,注册内存清理函数的操作。

    ->处理配置树->所有挂钩排序->检验配置文件挂钩ap_run_test_config()->

    注:其中mod_ssl也对该挂钩进行了实现,但是从日志打出的结果看,mod_ssl什么也没有做

->运行ap_run_open_logs()挂钩

    注:虽然mod_ssl没有在这个阶段有类似的处理,但这个挂钩在理解整个过程中还是很重要的,其中的mpm模块的prefork_open_logs()(linux系统)在这个挂钩中对套接字进行侦听等操作,包括套接字与指定IP地址/端口绑定在一起,同时在指定的端口上进行等重要操作。

    ->运行挂钩ap_run_post_config()(运行读取配置文件之后的挂钩函数)其中的mod_ssl的挂钩ssl_init_Module()实现了具体操作。

    注:这个挂钩在mod_ssl的初始化过程中时最重要的函数,我们可以单独用一个子流程来描述它

     ap_run_post_config()(ssl_init_Module())子流程(获得子进程id赋给mod_ssl模块配置结构->注册内存清理函数->初始化SSLModConfigRec结构(这个数据结构在mod_ssl数据结构分析中具体介绍)->将虚拟主机中相关端口赋值给apr_port_t
如果没有默认为443->得到虚拟主机支持的协议,与“https”做比较->ssl随机种子->找到证书的存放路径->读取证书,插入到全局配置中->判断公钥类型->读私钥文件->暂时初始化一个rsa和DH算法->ssl初始化互斥体->初始化相应的虚拟主机并初始化虚拟主机的公私钥->

初始化检查虚拟主机相关选项:主要是检查https端口是否被占用和冲突问题)

    ->进入主循环->清空所有挂钩函数->遍历所有模块注册的挂钩函数->再次运行读取配置文件,并生成配置树->运行挂钩ap_run_post_config()的过程->ap_mpm_run()

    注:ap_mpm_run()为多进程或多线程函数的入口。从这开始Apache将开启多进程(linux)处理客户端发送来的请求。

    重点过程总结:

    1.open_logs在主函数中被调用,而且是在ap_run_mpm调用之前。这意味着当主程序启动后,对应的端口就已经被创建完毕,并处于侦听状态。

    2.套接字的创建是在读取配置文件的时候进行的。

 

int main(int argc, const char * const argv[])                                                                                                             

{                                                                                                                                

    char c;                                                                                                                            

    int configtestonly = 0;                                                                                                                         

    const char *confname = SERVER_CONFIG_FILE;                                                                                                     

    const char *def_server_root = HTTPD_ROOT;                                                                                                          

    const char *temp_error_log = NULL;                                                                                                     

    const char *error;                                                                                                    

    process_rec *process;                                                                                               

    server_rec *server_conf;                                                                                                     

    apr_pool_t *pglobal;                                                                                       一些必要的初始化

    apr_pool_t *pconf;                                                                                                  

    apr_pool_t *plog; /* Pool of log streams, reset _after_ each read of conf */                                                                       

    apr_pool_t *ptemp; /* Pool for temporary config stuff, reset often */                                                                               

    apr_pool_t *pcommands; /* Pool for -D, -C and -c switches */                                                                                      

    apr_getopt_t *opt;                                                                                                  

    apr_status_t rv;                                                                                             

    module **mod;                                                                                                      

    const char *optarg;                                                                                                  

    APR_OPTIONAL_FN_TYPE(ap_signal_server) *signal_server;注册可选挂钩函数          

    AP_MONCONTROL(0); /* turn off profiling of startup */                                     便于测试用的测试函数                      

    process = init_process(&argc, &argv);                                             初始化输入的指令信息,并为指令赋值                 

    pglobal = process->pool;                                                                                                                               

    pconf = process->pconf;                                                                                                                                 

    ap_server_argv0 = process->short_name;                                                                                                                   

#if APR_CHARSET_EBCDIC                                                                                                                             

    if (ap_init_ebcdic(pglobal) != APR_SUCCESS) {                                                                                                       

        destroy_and_exit_process(process, 1);                                                                                                                 

    }                                                                                                                         

#endif                                                                                                                          

    apr_pool_create(&pcommands, pglobal);                                                                               为指令分配内存池          

    apr_pool_tag(pcommands, "pcommands");                                                                                                                 

    ap_server_pre_read_config  = apr_array_make(pcommands, 1, sizeof(char *));  将读取配置文件之前的命令行指令信息存放在链表中                                            

    ap_server_post_read_config = apr_array_make(pcommands, 1, sizeof(char *));     将读取配置文件之后的命令行指令信息存放在链表中                                      

    ap_server_config_defines   = apr_array_make(pcommands, 1, sizeof(char *));  将配置文件中的指令信息存放在链表中

    error = ap_setup_prelinked_modules(process);                                                  Apache根据指令加载预连接模块,如果错了就删除指令分配的内存                                          

    if (error) {                                                                                                                                

        ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_EMERG, 0, NULL, "%s: %s",                                      

                     ap_server_argv0, error);                                                                                                              

        destroy_and_exit_process(process, 1);                                                                                                       

    }                                                                                                                         

    ap_run_rewrite_args(process);                             对通过命令行传入的参数进行重写,只有mpm才用到              

    /* Maintain AP_SERVER_BASEARGS list in http_main.h to allow the MPM                                                                        

     * to safely pass on our args from its rewrite_args() handler.                                                                                          

     */                                                                                                                                

    apr_getopt_init(&opt, pcommands, process->argc, process->argv);       对指令进行进一步解析,用下面代码进行比较              

    while ((rv = apr_getopt(opt, AP_SERVER_BASEARGS, &c, &optarg))

            == APR_SUCCESS) {

        char **new;

        switch (c) {

        case 'c':

            new = (char **)apr_array_push(ap_server_post_read_config);

            *new = apr_pstrdup(pcommands, optarg);

            break;

        case 'C':

            new = (char **)apr_array_push(ap_server_pre_read_config);

            *new = apr_pstrdup(pcommands, optarg);

            break;

        case 'd':

            def_server_root = optarg;

            break;

        case 'D':

            new = (char **)apr_array_push(ap_server_config_defines);

            *new = apr_pstrdup(pcommands, optarg);

            /* Setting -D DUMP_VHOSTS is equivalent to setting -S */

            if (strcmp(optarg, "DUMP_VHOSTS") == 0)

                configtestonly = 1;

            /* Setting -D DUMP_MODULES is equivalent to setting -M */

            if (strcmp(optarg, "DUMP_MODULES") == 0)

                configtestonly = 1;

            break;

        case 'e':

            if (strcasecmp(optarg, "emerg") == 0) {

                ap_default_loglevel = APLOG_EMERG;

            }

            else if (strcasecmp(optarg, "alert") == 0) {

                ap_default_loglevel = APLOG_ALERT;

            }

            else if (strcasecmp(optarg, "crit") == 0) {

                ap_default_loglevel = APLOG_CRIT;

            }

            else if (strncasecmp(optarg, "err", 3) == 0) {

                ap_default_loglevel = APLOG_ERR;

            }

            else if (strncasecmp(optarg, "warn", 4) == 0) {

                ap_default_loglevel = APLOG_WARNING;

            }

            else if (strcasecmp(optarg, "notice") == 0) {

                ap_default_loglevel = APLOG_NOTICE;

            }

            else if (strcasecmp(optarg, "info") == 0) {

                ap_default_loglevel = APLOG_INFO;

            }

            else if (strcasecmp(optarg, "debug") == 0) {

                ap_default_loglevel = APLOG_DEBUG;

            }

            else {

                usage(process);

            }

            break;

        case 'E':

            temp_error_log = apr_pstrdup(process->pool, optarg);

            break;

        case 'X':

            new = (char **)apr_array_push(ap_server_config_defines);

            *new = "DEBUG";

            break;

        case 'f':

            confname = optarg;

            break;

        case 'v':

            printf("Server version: %s/n", ap_get_server_description());

            printf("Server built:   %s/n", ap_get_server_built());

            destroy_and_exit_process(process, 0);

        case 'V':

            show_compile_settings();

            destroy_and_exit_process(process, 0);

        case 'l':

            ap_show_modules();

            destroy_and_exit_process(process, 0);

        case 'L':

            ap_show_directives();

            destroy_and_exit_process(process, 0);

        case 't':

            configtestonly = 1;

            break;

        case 'S':

            configtestonly = 1;

            new = (char **)apr_array_push(ap_server_config_defines);

            *new = "DUMP_VHOSTS";

            break;

        case 'M':

            configtestonly = 1;

            new = (char **)apr_array_push(ap_server_config_defines);

            *new = "DUMP_MODULES";

            break;

        case 'h':

        case '?':

            usage(process);

        }

    }

    /* bad cmdline option?  then we die */                                                                     

    if (rv != APR_EOF || opt->ind < opt->argc) {                                                                       

        usage(process);                                                                    

}                                                                 

    apr_pool_create(&plog, pglobal);                                          分配全局内存池             

    apr_pool_tag(plog, "plog");                                                                   

    apr_pool_create(&ptemp, pconf);                                           为配置分配内存池          

    apr_pool_tag(ptemp, "ptemp");                                                                        

    /* Note that we preflight the config file once                                                                          

     * before reading it _again_ in the main loop.                                                                       

     * This allows things, log files configuration                                                                        

     * for example, to settle down.                                                                        

     */                                                                        

    ap_server_root = def_server_root;                                          设置根目录路径                                                            

    if (temp_error_log) {                                                                                                                                              

        ap_replace_stderr_log(process->pool, temp_error_log);                                                                                          

    }                                                                                                                                                     

    server_conf = ap_read_config(process, ptemp, confname, &ap_conftree);                    读取配置文件,并生成配置树      

     if (!server_conf) {                                                                         如果读取失败则释放内存池并退出                                 

        destroy_and_exit_process(process, 1);                                                                                                                 

    }                                                                                                                                                     

    if (ap_run_pre_config(pconf, plog, ptemp) != OK) {                           在处理配置树前,需要修改配置树的模块在此修改配置树

        ap_log_error(APLOG_MARK, APLOG_STARTUP |APLOG_ERR, 0,                                                                              如果错误则释放内存池并退出                                                                    

                     NULL, "Pre-configuration failed");                                                                                                       

    destroy_and_exit_process(process, 1);                                                                                                                

    }                                                                                                                                                     

    rv = ap_process_config_tree(server_conf, ap_conftree,                                                               处理配置树                    

                                process->pconf, ptemp);                                                                                           

    if (rv == OK) {                                                                           如果配置树读取成功则                               

        ap_fixup_virtual_hosts(pconf, server_conf);                                                   合并虚拟机配置并做一些初始化        

        ap_fini_vhost_config(pconf, server_conf);                                                                                                             

        apr_hook_sort_all();                                                                                 所有挂钩排序

        if (configtestonly) {                                                                                  测试配置文件                                   

            ap_run_test_config(pconf, server_conf);                                                  检验配置文件挂钩(mod_ssl在其中有实现)            

          ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, "Syntax OK");                                                              

            destroy_and_exit_process(process, 0);                                                                                                          

        }                                                                                                                   

    }                                                                                                                

    signal_server = APR_RETRIEVE_OPTIONAL_FN(ap_signal_server);                    重新注册挂钩函数                            

    if (signal_server) {                                                                                                                     

        int exit_status;                                                                                                                   

        if (signal_server(&exit_status, pconf) != 0) {                                                                                                        

            destroy_and_exit_process(process, exit_status);                                                                                             

        }                                                                                                                                                        

    }                                                                                                                                                     

    /* If our config failed, deal with that here. */                                                                                                               

    if (rv != OK) {                                                                   如果配置树错误则释放内存池并退出                              

        destroy_and_exit_process(process, 1);                                                                                                                

    }                                                                                                                                                     

    apr_pool_clear(plog);                                                          清除日志的内存池空间                                                  

    if ( ap_run_open_logs(pconf, plog, ptemp, server_conf) != OK) {                                                                                    运行日志挂钩函数(socket的相关实现),如果错误则记录日志并清空内存池退出。                                                             

        ap_log_error(APLOG_MARK, APLOG_STARTUP |APLOG_ERR,                                                                       

                     0, NULL, "Unable to open logs");                                                                                                     

    destroy_and_exit_process(process, 1);                                                                                                             

    }                                                                                                                                                     

    if ( ap_run_post_config(pconf, plog, ptemp, server_conf) != OK) {                           运行读取配置文件之后的挂钩函数,如果错误则记录日志并清空内存池退出。                                                                 

        ap_log_error(APLOG_MARK, APLOG_STARTUP |APLOG_ERR, 0,  NULL, "Configuration Failed");                                                                                                                  

        destroy_and_exit_process(process, 1);                                                                                                                 

    }                                                                                                                                                     

    apr_pool_destroy(ptemp);                                                                                                                                       

    for (;;) {                                                                            进入主循环。                                                               

        apr_hook_deregister_all();                                                                                   清空所有挂钩函数。                

        apr_pool_clear(pconf);                                                                                     清空配置文件内存池。                    

           for (mod = ap_prelinked_modules; *mod != NULL; mod++) {                         遍历所有模块进行挂钩的注册。   

            ap_register_hooks(*mod, pconf);                                                                                                                 

        }                                                                                                                                     

        /* This is a hack until we finish the code so that it only reads                                                                                

         * the config file once and just operates on the tree already in                                                                                 

         * memory.  rbb                                                                                                                                           

         */                                                                                                                                   

        ap_conftree = NULL;                                                                                清空配置树                                                

        apr_pool_create(&ptemp, pconf);                                                                                   配置文件内存池的建立   

        apr_pool_tag(ptemp, "ptemp");                                                                                                                         

        ap_server_root = def_server_root;                                                                                  设置服务器根目录          

        server_conf = ap_read_config(process, ptemp, confname, &ap_conftree);                            读取配置文件并生成配置树

        if (!server_conf) {                                                                                     如果错误则清空内存池并退出

            destroy_and_exit_process(process, 1);                                                                                                          

        }                                                                                                                                      

        if (ap_run_pre_config(pconf, plog, ptemp) != OK) {                                                          在处理配置树前,需要修改配置树的模块在此修改配置树                                                                          

            ap_log_error(APLOG_MARK, APLOG_STARTUP |APLOG_ERR,                                如果错误则释放内存池并退出

                         0, NULL, "Pre-configuration failed");                                                                                     

            destroy_and_exit_process(process, 1);                                                                                                          

        }                                                                                                                                                                 

        if (ap_process_config_tree(server_conf, ap_conftree, process->pconf,ptemp) != OK) {                                                如果错误则释放内存池并退出                                                          

            destroy_and_exit_process(process, 1);                                                                                                          

        }                                                                                                                                                                 

        ap_fixup_virtual_hosts(pconf, server_conf);                                                            合并虚拟机配置并做一些初始化

        ap_fini_vhost_config(pconf, server_conf);                                                                                                             

        apr_hook_sort_all();                                                                                 对所有挂钩进行排序                                                                                 

        apr_pool_clear(plog);                                                                                清除所用内存池                                

        if (ap_run_open_logs(pconf, plog, ptemp, server_conf) != OK) {                       运行日志挂钩函数(socket的相关实现),如果错误则记录日志并清空内存池退出。                                                                           

            ap_log_error(APLOG_MARK, APLOG_STARTUP |APLOG_ERR,                                                                          

                         0, NULL, "Unable to open logs");                                                                                         

            destroy_and_exit_process(process, 1);                                                                                                          

        }                                                                                                                                               

        if (ap_run_post_config(pconf, plog, ptemp, server_conf) != OK) {                     运行读取配置文件之后的挂钩函数     

            ap_log_error(APLOG_MARK, APLOG_STARTUP |APLOG_ERR,                                                                          

                         0, NULL, "Configuration Failed");                                                                                                    

          destroy_and_exit_process(process, 1);                                                                                                          

        }                                                                                                                                               

        apr_pool_destroy(ptemp);                                                                                                                                 

        apr_pool_lock(pconf, 1);                                                                           什么也没有做                                   

        ap_run_optional_fn_retrieve();                                                                                                                           

        if (ap_mpm_run(pconf, plog, server_conf))                                           运行多进程或多线程来创建子进程或子线程 

            break;

        apr_pool_lock(pconf, 0);

    }

apr_pool_lock(pconf, 0);

}

apr_pool_lock(pconf, 0);

    destroy_and_exit_process(process, 0);

    return 0; /* Termination 'ok' */

}



 

    待续...

阅读(1616) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~