分类 wifidog流程 下的文章

wifidog用php实现验证流程

步骤
1.首先简单说说wifidog认证的过程
客户端首次连接到wifi后,浏览器请求将会被重定向到:

login/?gw_address=%s&gw_port=%d&gw_id=%s&url=%s

验证通过后,客户端被重定向到网关,url格式如下:
http://网关地址:网关端口/wifidog/auth?token=
wifidong会启动一个线程周期性地报告每一个用户的状态信息,并通过如下地址发送给认证
服务器:

auth_server:/auth/?stage=
ip=
mac=
token=
incoming=
outgoing=

认证服务器根据该状态信息决定是否允许该用户继续连接,并回复网关,回复格式为:Auth:状态码,
如:Auth:1
常用状态码:
0:AUTH_DENIED,表示拒绝
1:AUTH_ALLOWED,验证通过
验证通过后,将重定向到如下地址:
portal/?gw_id=%s
wifidog的ping协议
wifidog通过ping协议将当前状态信息发送给认证服务器,发送地址为:

http://auth_sever/ping/?
gw_id=%s
sys_uptime=%lu
sys_memfree=%u
sys_load=%.2f
wifidog_uptime=%lu

认证服务器须返回一个“Pong”作为回应。
具体php实现代码如下

public function auth()
    {
        //响应客户端的定时认证,可在此处做各种统计、计费等等
        /*
            wifidog 会通过这个接口传递连接客户端的信息,然后根据返回,对客户端做开通、断开等处理,具体返回值可以看wifidog的文档
        wifidog主要提交如下参数
        1.ip
        2. mac
        3. token(login页面下发的token)
        4.incoming 下载流量
        5.outgoing 上传流量
        6.stage  认证阶段,就两种 login 和 counters
        */


        $stage = $_GET['stage'] == 'counters'?'counters':'login';
        if($stage == 'login')
        {
            //XXXX跳过login 阶段的处理XXXX不能随便跳过的
            //默认返回 允许
            echo "Auth: 1";
        }
        else if($stage == 'counters')
        {

            //做一个简单的流量判断验证,下载流量超值时,返回下线通知,否则保持在线
            if(!empty($_GET['incoming']) and $_GET['incoming'] > 10000000)
            {
                echo "Auth: 0";
            }else{
                echo "Auth: 1\n";
            }
        }
        else
            echo "Auth: 0"; //其他情况都返回拒绝


        /*
            返回值:主要有这两种就够了
        0 - 拒绝
        1 - 放行

        官方文档如下
        0 - AUTH_DENIED - User firewall users are deleted and the user removed.
        6 - AUTH_VALIDATION_FAILED - User email validation timeout has occured and user/firewall is deleted(用户邮件验证超时,防火墙关闭该用户)
        1 - AUTH_ALLOWED - User was valid, add firewall rules if not present
        5 - AUTH_VALIDATION - Permit user access to email to get validation email under default rules (用户邮件验证时,向用户开放email)
        -1 - AUTH_ERROR - An error occurred during the validation process
        */
    }
    public function portal()
    {
        /*
         wifidog 带过来的参数 如下
        1. gw_id
        */
        //重定到指定网站 或者 显示splash广告页面
        redirect('http://www.baidu.com', 'location', 302);

    }
    public function ping()
    {
        //url请求 "gw_id=$gw_id&sys_uptime=$sys_uptime&sys_memfree=$sys_memfree&sys_load=$sys_load&wifidog_uptime=$wifidog_uptime";
        //log_message($this->config->item('MY_log_threshold'), __CLASS__.':'.__FUNCTION__.':'.debug_printarray($_GET));

        //判断各种参数是否为空
        if( !(isset($_GET['gw_id']) and isset($_GET['sys_uptime']) and isset($_GET['sys_memfree']) and isset($_GET['sys_load']) and isset($_GET['wifidog_uptime']) ) )
        {
            echo '{"error":"2"}';
            return;
        }
        //添加心跳日志处理功能
        /*
            此处可获取 wififog提供的 如下参数
        1.gw_id  来自wifidog 配置文件中,用来区分不同的路由设备
        2.sys_uptime 路由器的系统启动时间
        3.sys_memfree 系统内存使用百分比
        4.wifidog_uptime wifidog持续运行时间(这个数据经常会有问题)
        */

        //返回值
        echo 'Pong';
    }
    /**
     * wifidog 的gw_message 接口,信息提示页面
     */
    function gw_message()
    {
        if (isset($_REQUEST["message"])) {
            switch ($_REQUEST["message"]) {
                case 'failed_validation':
                    //auth的stage为login时,被服务器返回AUTH_VALIDATION_FAILED时,来到该处处理
                    //认证失败,请重新认证
                    break;
                case 'denied':
                    //auth的stage为login时,被服务器返回AUTH_DENIED时,来到该处处理
                    //认证被拒
                    break;
                case 'activate':
                    //auth的stage为login时,被服务器返回AUTH_VALIDATION时,来到该处处理
                    //待激活
                    break;
                default:
                    break;
            }
        }else{
            //不回显任何信息
        }
    }

本文章由 http://www.wifidog.pro/2015/04/09/wifidog-php-2.html 整理编辑,转载请注明出处

wifidog认证wifidog流程auth server简单配置

前段时间使用wifidog进行wifi强制认证,现在做个小结。
1.首先简单说说wifidog认证的过程
客户端首次连接到wifi后,浏览器请求将会被重定向到:

login/?gw_address=%s&gw_port=%d&gw_id=%s&url=%s

验证通过后,客户端被重定向到网关,url格式如下:
http://网关地址:网关端口/wifidog/auth?token=
wifidong会启动一个线程周期性地报告每一个用户的状态信息,并通过如下地址发送给认证
服务器:

auth_server:/auth/?stage=
ip=
mac=
token=
incoming=
outgoing=

认证服务器根据该状态信息决定是否允许该用户继续连接,并回复网关,回复格式为:Auth:状态码,
如:Auth:1
常用状态码:
0:AUTH_DENIED,表示拒绝
1:AUTH_ALLOWED,验证通过
验证通过后,将重定向到如下地址:
portal/?gw_id=%s
wifidog的ping协议
wifidog通过ping协议将当前状态信息发送给认证服务器,发送地址为:

http://auth_sever/ping/?
gw_id=%s
sys_uptime=%lu
sys_memfree=%u
sys_load=%.2f
wifidog_uptime=%lu

认证服务器须返回一个“Pong”作为回应。
2.实战应用
struts配置文件:

<package name="index" namespace="/" extends="interceptorMy,struts-default">
<action name="login/" class="goodsAction" method="login">
<result name="success" type="redirect">/Login/index.jsp</result>
<result name="input">/error.jsp</result>
</action>
<action name="ping/" class="goodsAction" method="ping">
</action>
 <action name="auth/" class="goodsAction" method="auth">
</action>
<action name="portal/" class="goodsAction" method="portal">
</action>
</package>

Action方法

public String login() {
    try{
        System.out.println("login start!");
                System.out.println("gw_port:"+gw_port);
        System.out.println("login end!");

     }
    catch(Exception e)
    {
        e.printStackTrace();
        return INPUT;
    }
    return "success";
}
public void ping() {
    try{
        System.out.println("ping start!");
        System.out.println(gw_id);
        ServletActionContext.getResponse().getWriter().write("Pong");
        System.out.println("ping end!");
         }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
public void portal() {
    try{
        System.out.println("portal start");
        System.out.println("protal"+token);
    ServletActionContext.getResponse().sendRedirect("/demo/listAction");
        System.out.println("portal end");
     }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
public void auth() {
    try{
        System.out.println("auth start!");
        System.out.println("mac"+mac);
        System.out.println("stage"+stage);
        System.out.println("token"+token);
        ServletActionContext.getResponse().getWriter().write("Auth: 1");
        System.out.println("auth end!");

     }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

/Login/index.jsp代码:

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    DateFormat format=new SimpleDateFormat("yyMMddHHmmss");
    String formatData=format.format(new Date());
    int ramdom=new Random().nextInt(1000);
    String token=formatData+ramdom;
    if(session.getAttribute("token")==null)
       session.setAttribute("token",token);

%>
<form method="GET" action='http://192.168.1.1:2060/wifidog/auth'>
<input type='hidden' name='token' value="<s:property value="#session.token" />" />
<input type='submit' value='Welcome!'/>
</form>

上面的192.168.1.1为网关的ip,2060为网关端口。
当然,完全可以在处理完login后直接跳到该地址。我们这里为演示其认证流程,故跳到该页面
效果:
客户端连接到wifi后,打开任何连接均跳到上面的index.jsp中,点击"Welcome"后,跳到/demo/listAction,即我们的目标地址。此后点击其他连接将不再拦截。
提示:安装wifidog的路由器必须可以访问Internet,否则wifidog拦截失败,无法跳到我们设定的页面。

本文章由 http://www.wifidog.pro/2015/04/08/wifidog%E6%B5%81%E7%A8%8Bwifidog%E8%AE%A4%E8%AF%81.html 整理编辑,转载请注明出处

wifidog源码wifidog分析用户连接

用户连接启动线程(void thread_httpd(void * args))

此段代码是当有新用户(未认证的用户)连接时创建的线程,其主要功能为

获取用户浏览器发送过来的http报头
分析http报头,分析是否包含关键路径
不包含关键路径则调用404回调函数
包含关键路径则执行关键路径回调函数(这里主要讲解"/wifidog/auth"路径)

void
thread_httpd(void *args)
{
    void **params;
    httpd *webserver;
    request *r;

    params = (void **)args;
    webserver = *params;
    r = *(params + 1);
    free(params);

    /* 获取http报文 */
    if (httpdReadRequest(webserver, r) == 0) {
        debug(LOG_DEBUG, "Processing request from %s", r->clientAddr);
        debug(LOG_DEBUG, "Calling httpdProcessRequest() for %s", r->clientAddr);
        /* 分析http报文 */
        httpdProcessRequest(webserver, r);
        debug(LOG_DEBUG, "Returned from httpdProcessRequest() for %s", r->clientAddr);
    }
    else {
        debug(LOG_DEBUG, "No valid request received from %s", r->clientAddr);
    }
    debug(LOG_DEBUG, "Closing connection with %s", r->clientAddr);
    httpdEndRequest(r);
}



/* 被thread_httpd调用 */
void httpdProcessRequest(httpd *server, request *r)
{
    char dirName[HTTP_MAX_URL],
        entryName[HTTP_MAX_URL],
        *cp;
    httpDir *dir;
    httpContent *entry;

    r->response.responseLength = 0;
    strncpy(dirName, httpdRequestPath(r), HTTP_MAX_URL);
    dirName[HTTP_MAX_URL-1]=0;
    cp = rindex(dirName, '/');
    if (cp == NULL)
    {
        printf("Invalid request path '%s'\n",dirName);
        return;
    }
    strncpy(entryName, cp + 1, HTTP_MAX_URL);
    entryName[HTTP_MAX_URL-1]=0;
    if (cp != dirName)
        *cp = 0;
    else
        *(cp+1) = 0;

     /* 获取http报文中的关键路径,在main_loop中已经设置 */
    dir = _httpd_findContentDir(server, dirName, HTTP_FALSE);
    if (dir == NULL)
    {
        /* http报文中未包含关键路径,执行404回调函数(在404回调函数中新用户被重定向到认证服务器) */
        _httpd_send404(server, r);
        _httpd_writeAccessLog(server, r);
        return;
    }
    /* 获取关键路径内容描述符 */
    entry = _httpd_findContentEntry(r, dir, entryName);
    if (entry == NULL)
    {
        _httpd_send404(server, r);
        _httpd_writeAccessLog(server, r);
        return;
    }
    if (entry->preload)
    {
        if ((entry->preload)(server) < 0)
        {
            _httpd_writeAccessLog(server, r);
            return;
        }
    }
    switch(entry->type)
    {
        case HTTP_C_FUNCT:
        case HTTP_C_WILDCARD:
            /* 如果是被认证服务器重定向到网关的用户,此处的关键路径为"/wifidog/auth",并执行回调函数 */
            (entry->function)(server, r);
            break;

        case HTTP_STATIC:
            _httpd_sendStatic(server, r, entry->data);
            break;

        case HTTP_FILE:
            _httpd_sendFile(server, r, entry->path);
            break;

        case HTTP_WILDCARD:
            if (_httpd_sendDirectoryEntry(server, r, entry,
                        entryName)<0)
            {
                _httpd_send404(server, r);
            }
            break;
    }
    _httpd_writeAccessLog(server, r);
}

本文章由 http://www.wifidog.pro/2015/04/02/wifidog%E6%BA%90%E7%A0%81wifidog%E5%88%86%E6%9E%90.html 整理编辑,转载请注明出处

wifidog源码 - 初始化阶段

Wifidog是一个linux下开源的认证网关软件,它主要用于配合认证服务器实现无线路由器的认证放行功能。

wifidog是一个后台的服务程序,可以通过wdctrl命令对wifidog主程序进行控制。

本文解释wifidog在启动阶段所做的初始化主要工作(代码片段1.1)

初始化配置(先将配置结构体初始化为默认值,在读取配置文件修改配置结构体)
初始化已连接客户端列表(如果是通过wdctrl重启wifidog,将会读取之前wifidog的已连接客户端列表 代码片段1.2 代码片段1.3)
如无特殊情况,分离进程,建立守护进程 (代码片段1.1)
添加多个http请求回调函数(包括404错误回调函数) (见之后章节)
摧毁删除现有的iptables路由表规则 (见之后章节)
建立新的iptables路由表规则 (见之后章节)
启动多个功能线程 (见之后章节)
循环等待客户端连接 (见之后章节)

int main(int argc, char **argv) {

    s_config *config = config_get_config(); //就是返回全局变量config结构体的地址
    config_init(); //初始化全局变量config结构体为默认值

    parse_commandline(argc, argv); //根据传入参数执行操作(如果参数有-x则会设置restart_orig_pid为已运行的wifidog的pid)

    /* Initialize the config */
    config_read(config->configfile); //根据配置文件设置全局变量config结构体
    config_validate(); //判断GatewayInterface和AuthServer是否为空,空则无效退出程序。

    /* Initializes the linked list of connected clients */
    client_list_init(); //将已连接客户端链表置空。

    /* Init the signals to catch chld/quit/etc */
    init_signals(); //初始化一些信号

    if (restart_orig_pid) { //用于restart,如果有已运行的wifidog,先会kill它
        /*
         * We were restarted and our parent is waiting for us to talk to it over the socket
         */
        get_clients_from_parent(); //从已运行的wifidog中获取客户端列表,详见 代码片段1.2

        /*
         * At this point the parent will start destroying itself and the firewall. Let it finish it's job before we continue
         */

        while (kill(restart_orig_pid, 0) != -1) { //kill已运行的wifidog
            debug(LOG_INFO, "Waiting for parent PID %d to die before continuing loading", restart_orig_pid);
            sleep(1);
        }

        debug(LOG_INFO, "Parent PID %d seems to be dead. Continuing loading.");
    }

    if (config->daemon) { //创建为守护进程,config->daemon默认值为-1

        debug(LOG_INFO, "Forking into background");

        switch(safe_fork()) {
            case 0: /* child */
                setsid(); //创建新会话,脱离此终端,实现守护进程
                append_x_restartargv();
                main_loop(); //进入主循环(核心代码在此)。
                break;

            default: /* parent */
                exit(0);
                break;
        }
    }
    else {
        append_x_restartargv();
        main_loop();
    }

    return(0); /* never reached */
}

代码片段1.2(获取已启动的wifidog的客户端列表):

此段代表描述了新启动的wifidog如何从已启动的wifidog程序中获取已连接的客户端列表。发送端见 代码片段1.3

void get_clients_from_parent(void) {
    int sock;
    struct sockaddr_un sa_un;
    s_config * config = NULL;
    char linebuffer[MAX_BUF];
    int len = 0;
    char *running1 = NULL;
    char *running2 = NULL;
    char *token1 = NULL;
    char *token2 = NULL;
    char onechar;
    char *command = NULL;
    char *key = NULL;
    char *value = NULL;
    t_client * client = NULL;
    t_client * lastclient = NULL;

    config = config_get_config();

    debug(LOG_INFO, "Connecting to parent to download clients");

    /* 连接socket */
    sock = socket(AF_UNIX, SOCK_STREAM, 0);
    memset(&sa_un, 0, sizeof(sa_un));
    sa_un.sun_family = AF_UNIX;
    strncpy(sa_un.sun_path, config->internal_sock, (sizeof(sa_un.sun_path) - 1)); //config->internal_sock的值为"/tmp/wifidog.sock"

    /* 连接已启动的wifidog */
    if (connect(sock, (struct sockaddr *)&sa_un, strlen(sa_un.sun_path) + sizeof(sa_un.sun_family))) {
        debug(LOG_ERR, "Failed to connect to parent (%s) - client list not downloaded", strerror(errno));
        return;
    }

    debug(LOG_INFO, "Connected to parent. Downloading clients");

    LOCK_CLIENT_LIST();

    command = NULL;
    memset(linebuffer, 0, sizeof(linebuffer));
    len = 0;
    client = NULL;
    /* 接收数据,逐个字符接收 */
    /* 数据包格式为 CLIENT|ip=%s|mac=%s|token=%s|fw_connection_state=%u|fd=%d|counters_incoming=%llu|counters_outgoing=%llu|counters_last_updated=%lu\n */
    while (read(sock, &onechar, 1) == 1) {
        if (onechar == '\n') {
            /* 如果接收到末尾('\n'),则转为'\0' */
            onechar = '\0';
        }
        linebuffer[len++] = onechar;

        if (!onechar) {
            /* 以下将数据转化为t_client结构体添加到客户端列表 */
            debug(LOG_DEBUG, "Received from parent: [%s]", linebuffer);
            running1 = linebuffer;
            while ((token1 = strsep(&running1, "|")) != NULL) {
                if (!command) {
                    /* The first token is the command */
                    command = token1;
                }
                else {
                /* Token1 has something like "foo=bar" */
                    running2 = token1;
                    key = value = NULL;
                    while ((token2 = strsep(&running2, "=")) != NULL) {
                        if (!key) {
                            key = token2;
                        }
                        else if (!value) {
                            value = token2;
                        }
                    }
                }

                if (strcmp(command, "CLIENT") == 0) {
                    /* This line has info about a client in the client list */
                    if (!client) {
                        /* Create a new client struct */
                        client = safe_malloc(sizeof(t_client));
                        memset(client, 0, sizeof(t_client));
                    }
                }

                if (key && value) {
                    if (strcmp(command, "CLIENT") == 0) {
                        /* Assign the key into the appropriate slot in the connection structure */
                        if (strcmp(key, "ip") == 0) {
                            client->ip = safe_strdup(value);
                        }
                        else if (strcmp(key, "mac") == 0) {
                            client->mac = safe_strdup(value);
                        }
                        else if (strcmp(key, "token") == 0) {
                            client->token = safe_strdup(value);
                        }
                        else if (strcmp(key, "fw_connection_state") == 0) {
                            client->fw_connection_state = atoi(value);
                        }
                        else if (strcmp(key, "fd") == 0) {
                            client->fd = atoi(value);
                        }
                        else if (strcmp(key, "counters_incoming") == 0) {
                            client->counters.incoming_history = atoll(value);
                            client->counters.incoming = client->counters.incoming_history;
                        }
                        else if (strcmp(key, "counters_outgoing") == 0) {
                            client->counters.outgoing_history = atoll(value);
                            client->counters.outgoing = client->counters.outgoing_history;
                        }
                        else if (strcmp(key, "counters_last_updated") == 0) {
                            client->counters.last_updated = atol(value);
                        }
                        else {
                            debug(LOG_NOTICE, "I don't know how to inherit key [%s] value [%s] from parent", key, value);
                        }
                    }
                }
            }

            /* End of parsing this command */
            if (client) {
                /* Add this client to the client list */
                if (!firstclient) {
                    firstclient = client;
                    lastclient = firstclient;
                }
                else {
                    lastclient->next = client;
                    lastclient = client;
                }
            }

            /* Clean up */
            command = NULL;
            memset(linebuffer, 0, sizeof(linebuffer));
            len = 0;
            client = NULL;
        }
    }

    UNLOCK_CLIENT_LIST();
    debug(LOG_INFO, "Client list downloaded successfully from parent");

    close(sock);
}

代码片段1.3(已启动的wifidog发送客户端列表到新启动的wifidog):

//thread_wdctl_handler(void *arg)函数是wifidog启动后自动创建的控制线程,主要用于与wdctrl进行socket通信,根据wdctrl命令执行不同的操作。这里我们着重讲解的是wdctrl发送restart后wifidog的执行逻辑。
static void *
thread_wdctl_handler(void *arg)
{
    int fd,
        done,
        i;
    char request[MAX_BUF];
    ssize_t read_bytes,
        len;

    debug(LOG_DEBUG, "Entering thread_wdctl_handler....");

    fd = (int)arg;

    debug(LOG_DEBUG, "Read bytes and stuff from %d", fd);

    /* 初始化变量 */
    read_bytes = 0;
    done = 0;
    memset(request, 0, sizeof(request));

    /* 读取命令 */
    while (!done && read_bytes < (sizeof(request) - 1)) {
        len = read(fd, request + read_bytes,
                sizeof(request) - read_bytes); //读取wdctrl发送的命令

        /* 判断命令正确性 */
        for (i = read_bytes; i < (read_bytes + len); i++) {
            if (request[i] == '\r' || request[i] == '\n') {
                request[i] = '\0';
                done = 1;
            }
        }

        /* Increment position */
        read_bytes += len;
    }

        //判断命令
    if (strncmp(request, "status", 6) == 0) {
        wdctl_status(fd);
    } else if (strncmp(request, "stop", 4) == 0) {
        wdctl_stop(fd);
    } else if (strncmp(request, "reset", 5) == 0) {
        wdctl_reset(fd, (request + 6));
    } else if (strncmp(request, "restart", 7) == 0) {
        wdctl_restart(fd); //执行wdctl_restart(int afd)函数
    }

    if (!done) {
        debug(LOG_ERR, "Invalid wdctl request.");
                //关闭套接字
        shutdown(fd, 2);
        close(fd);
        pthread_exit(NULL);
    }

    debug(LOG_DEBUG, "Request received: [%s]", request);

        //关闭套接字
    shutdown(fd, 2);
    close(fd);
    debug(LOG_DEBUG, "Exiting thread_wdctl_handler....");

    return NULL;
}


//wdctl_restart(int afd)函数详解
static void
wdctl_restart(int afd)
{
    int sock,
        fd;
    char *sock_name;
    struct sockaddr_un sa_un;
    s_config * conf = NULL;
    t_client * client = NULL;
    char * tempstring = NULL;
    pid_t pid;
    ssize_t written;
    socklen_t len;

    conf = config_get_config();

    debug(LOG_NOTICE, "Will restart myself");

    /*
     * 准备内部连接socket
     */
    memset(&sa_un, 0, sizeof(sa_un));
    sock_name = conf->internal_sock; //conf->internal_sock值为"/tmp/wifidog.sock"
    debug(LOG_DEBUG, "Socket name: %s", sock_name);

    if (strlen(sock_name) > (sizeof(sa_un.sun_path) - 1)) {

        debug(LOG_ERR, "INTERNAL socket name too long");
        return;
    }

    debug(LOG_DEBUG, "Creating socket");
    sock = socket(PF_UNIX, SOCK_STREAM, 0); //建立内部socket套接字

    debug(LOG_DEBUG, "Got internal socket %d", sock);

    /* 如果sock_name文件存在,则删除*/
    unlink(sock_name);

    debug(LOG_DEBUG, "Filling sockaddr_un");
    strcpy(sa_un.sun_path, sock_name); 
    sa_un.sun_family = AF_UNIX;

    debug(LOG_DEBUG, "Binding socket (%s) (%d)", sa_un.sun_path, strlen(sock_name));


    if (bind(sock, (struct sockaddr *)&sa_un, strlen(sock_name) + sizeof(sa_un.sun_family))) {
        debug(LOG_ERR, "Could not bind internal socket: %s", strerror(errno));
        return;
    }

    if (listen(sock, 5)) {
        debug(LOG_ERR, "Could not listen on internal socket: %s", strerror(errno));
        return;
    }

    /*
     * socket建立完成,创建子进程
     */
    debug(LOG_DEBUG, "Forking in preparation for exec()...");
    pid = safe_fork();
    if (pid > 0) {
        /* 父进程 */

        /* 等待子进程连接此socket :*/
        debug(LOG_DEBUG, "Waiting for child to connect on internal socket");
        len = sizeof(sa_un);
        if ((fd = accept(sock, (struct sockaddr *)&sa_un, &len)) == -1){ //接受连接
            debug(LOG_ERR, "Accept failed on internal socket: %s", strerror(errno));
            close(sock);
            return;
        }

        close(sock);

        debug(LOG_DEBUG, "Received connection from child. Sending them all existing clients");

        /*子进程已经完成连接,发送客户端列表 */
        LOCK_CLIENT_LIST();
        client = client_get_first_client(); //获取第一个客户端
        while (client) {
            /* Send this client */
            safe_asprintf(&tempstring, "CLIENT|ip=%s|mac=%s|token=%s|fw_connection_state=%u|fd=%d|counters_incoming=%llu|counters_outgoing=%llu|counters_last_updated=%lu\n", client->ip, client->mac, client->token, client->fw_connection_state, client->fd, client->counters.incoming, client->counters.outgoing, client->counters.last_updated);
            debug(LOG_DEBUG, "Sending to child client data: %s", tempstring);
            len = 0;
            while (len != strlen(tempstring)) {
                written = write(fd, (tempstring + len), strlen(tempstring) - len); //发送给子进程
                if (written == -1) {
                    debug(LOG_ERR, "Failed to write client data to child: %s", strerror(errno));
                    free(tempstring);
                    break;
                }
                else {
                    len += written;
                }
            }
            free(tempstring);
            client = client->next;
        }
        UNLOCK_CLIENT_LIST();

        close(fd);

        debug(LOG_INFO, "Sent all existing clients to child. Committing suicide!");

        shutdown(afd, 2);
        close(afd);


        wdctl_stop(afd);
    }
    else {
        /* 子进程,先关闭资源 */
        close(wdctl_socket_server);
        close(icmp_fd);
        close(sock);
        shutdown(afd, 2);
        close(afd);
        debug(LOG_NOTICE, "Re-executing myself (%s)", restartargv[0]);

        setsid();
        execvp(restartargv[0], restartargv); //执行外部命令,这里重新启动wifidog

        debug(LOG_ERR, "I failed to re-execute myself: %s", strerror(errno));
        debug(LOG_ERR, "Exiting without cleanup");
        exit(1);
    }
}

本文章由 http://www.wifidog.pro/2015/04/02/wifidog%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%E5%88%9D%E5%A7%8B%E5%8C%96.html 整理编辑,转载请注明出处