Yu.ding 2 years ago
parent
commit
defb055422

+ 3 - 3
usr/src/ast_init.c

@@ -218,7 +218,7 @@ unsigned char *base64_decode(unsigned char *code)
 int main(int argc, char **argv) {
     FILE *fp;
     unsigned char s[256];//S-box
-    unsigned char key[64];
+    unsigned char key[128];
     unsigned char pData[64];
     int i;
     int reset_exist = 0;
@@ -272,10 +272,10 @@ int main(int argc, char **argv) {
         sprintf(pData,"%ld",Timestamp);
 
         len = strlen(pData);
-        printf("pData is %s, length: %d\n",pData,len);
+        printf("pData is %s, length: %ld\n",pData,len);
         rc4_init(s, (unsigned char*)key, (unsigned long)strlen(key));//已经完成了初始化
         rc4_crypt(s, (unsigned char*)pData, len);//加密
-        printf("pData2 is %s, length: %d\n",pData,strlen(pData));
+        printf("pData2 is %s, length: %ld\n",pData,strlen(pData));
 
         memset(sql_tmp,0,sizeof(sql_tmp));
         sprintf(sql_tmp,"insert into D_T_S_Z_L(prop_key,prop_value) values ('LIMITED_DATETIME','%s')",base64_encode(pData));  //base64后写入数据库

+ 380 - 0
usr/src/ast_init_raspberrypi.c

@@ -0,0 +1,380 @@
+/*
+============================================================================
+Name        : ast_init
+Author      : dy
+Version     : v1.0
+Copyright   : ZYCOO copyright
+Description : set init info to mysql and redis
+============================================================================
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+#include <sys/time.h>
+#include <time.h>
+#include <ctype.h>
+#include <mysql/mysql.h>
+#include "hiredis/hiredis.h"
+
+MYSQL *g_conn; // mysql 连接
+MYSQL_RES *g_res; // mysql 记录集
+MYSQL_ROW g_row; // 字符串数组,mysql 记录行
+
+#define MAX_SIZE 2048
+#define MIDLE_SIZE 512
+#define MINI_SIZE 64
+#define KEYVALLEN 100
+#define MAX 65534
+#define VERSION "V1.0.1"
+#define RESET_FILE "/init/sql/.DS_Store"
+
+char uuid[64] = {0};
+long Timestamp;
+char g_host_name[MINI_SIZE];
+char g_user_name[MINI_SIZE] = "root";
+char g_password[MINI_SIZE];
+char g_db_name[MINI_SIZE] = "init_db";
+char sql_tmp[MIDLE_SIZE];
+const unsigned int g_db_port = 3306;
+
+void mytime(){
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+    Timestamp = tv.tv_sec + 45*24*60*60;
+}
+
+void get_uuid(){
+    FILE *fp;
+    memset(uuid,'\0',sizeof(uuid));
+    fp=popen("cat /proc/cpuinfo | grep 'Serial' | awk '{print $3}'","r");
+    fgets(uuid,sizeof(uuid),fp);
+    if (uuid[strlen(uuid) - 1] == '\n')
+    {
+        uuid[strlen(uuid) - 1] = '\0';
+    }
+    pclose(fp);
+}
+
+/*初始化函数*/
+void rc4_init(unsigned char*s, unsigned char*key, unsigned long Len)
+{
+    int i = 0, j = 0;
+    char k[256] = { 0 };
+    unsigned char tmp = 0;
+    for (i = 0; i<256; i++)
+    {
+        s[i] = i;
+        k[i] = key[i%Len];
+    }
+    for (i = 0; i<256; i++)
+    {
+        j = (j + s[i] + k[i]) % 256;
+        tmp = s[i];
+        s[i] = s[j];//交换s[i]和s[j]
+        s[j] = tmp;
+    }
+}
+ 
+/*加解密*/
+void rc4_crypt(unsigned char*s, unsigned char*Data, unsigned long Len)
+{
+    int i = 0, j = 0, t = 0;
+    unsigned long k = 0;
+    unsigned char tmp;
+    for (k = 0; k<Len; k++)
+    {
+        i = (i + 1) % 256;
+        j = (j + s[i]) % 256;
+        tmp = s[i];
+        s[i] = s[j];//交换s[x]和s[y]
+        s[j] = tmp;
+        t = (s[i] + s[j]) % 256;
+        Data[k] ^= s[t];
+    }
+}
+
+void print_mysql_error(const char *msg) { // 打印最后一次错误
+if (msg)
+    printf("%s: %s\n", msg, mysql_error(g_conn));
+else
+    puts(mysql_error(g_conn));
+}
+
+int executesql(const char * sql) {
+/*query the database according the sql*/
+if (mysql_real_query(g_conn, sql, strlen(sql))) // 如果失败
+    return -1; // 表示失败
+
+return 0; // 成功执行
+}
+
+
+int init_mysql() { // 初始化连接
+// init the database connection
+g_conn = mysql_init(NULL);
+
+/* connect the database */
+if(!mysql_real_connect(g_conn, g_host_name, g_user_name, g_password, g_db_name, g_db_port, NULL, 0)) // 如果失败
+    return -1;
+
+// 是否连接已经可用
+if (executesql("set names utf8")) // 如果失败
+    return -1;
+
+return 0; // 返回成功
+}
+
+unsigned char *base64_encode(unsigned char *str)  
+{  
+    long len;  
+    long str_len;  
+    unsigned char *res;  
+    int i,j;  
+//定义base64编码表  
+    unsigned char *base64_table="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";  
+  
+//计算经过base64编码后的字符串长度  
+    str_len=strlen(str);  
+    if(str_len % 3 == 0)
+        len=str_len/3*4;  
+    else  
+        len=(str_len/3+1)*4;  
+  
+    res=malloc(sizeof(unsigned char)*len+1);  
+    res[len]='\0';  
+  
+//以3个8位字符为一组进行编码  
+    for(i=0,j=0;i<len-2;j+=3,i+=4)  
+    {  
+        res[i]=base64_table[str[j]>>2]; //取出第一个字符的前6位并找出对应的结果字符  
+        res[i+1]=base64_table[(str[j]&0x3)<<4 | (str[j+1]>>4)]; //将第一个字符的后位与第二个字符的前4位进行组合并找到对应的结果字符  
+        res[i+2]=base64_table[(str[j+1]&0xf)<<2 | (str[j+2]>>6)]; //将第二个字符的后4位与第三个字符的前2位组合并找出对应的结果字符  
+        res[i+3]=base64_table[str[j+2]&0x3f]; //取出第三个字符的后6位并找出结果字符  
+    }  
+  
+    switch(str_len % 3)  
+    {  
+        case 1:  
+            res[i-2]='=';  
+            res[i-1]='=';  
+            break;  
+        case 2:  
+            res[i-1]='=';  
+            break;  
+    }  
+  
+    return res;  
+}
+
+unsigned char *base64_decode(unsigned char *code)  
+{  
+//根据base64表,以字符找到对应的十进制数据  
+    int table[]={0,0,0,0,0,0,0,0,0,0,0,0,
+    		 0,0,0,0,0,0,0,0,0,0,0,0,
+    		 0,0,0,0,0,0,0,0,0,0,0,0,
+    		 0,0,0,0,0,0,0,62,0,0,0,
+    		 63,52,53,54,55,56,57,58,
+    		 59,60,61,0,0,0,0,0,0,0,0,
+    		 1,2,3,4,5,6,7,8,9,10,11,12,
+    		 13,14,15,16,17,18,19,20,21,
+    		 22,23,24,25,0,0,0,0,0,0,26,
+    		 27,28,29,30,31,32,33,34,35,
+    		 36,37,38,39,40,41,42,43,44,
+    		 45,46,47,48,49,50,51
+    	       };  
+    long len;  
+    long str_len;  
+    unsigned char *res;  
+    int i,j;  
+  
+//计算解码后的字符串长度  
+    len=strlen(code);  
+//判断编码后的字符串后是否有=  
+    if(strstr(code,"=="))  
+        str_len=len/4*3-2;  
+    else if(strstr(code,"="))  
+        str_len=len/4*3-1;  
+    else  
+        str_len=len/4*3;  
+  
+    res=malloc(sizeof(unsigned char)*str_len+1);  
+    res[str_len]='\0';  
+  
+//以4个字符为一位进行解码  
+    for(i=0,j=0;i < len-2;j+=3,i+=4)  
+    {  
+        res[j]=((unsigned char)table[code[i]])<<2 | (((unsigned char)table[code[i+1]])>>4); //取出第一个字符对应base64表的十进制数的前6位与第二个字符对应base64表的十进制数的后2位进行组合  
+        res[j+1]=(((unsigned char)table[code[i+1]])<<4) | (((unsigned char)table[code[i+2]])>>2); //取出第二个字符对应base64表的十进制数的后4位与第三个字符对应bas464表的十进制数的后4位进行组合  
+        res[j+2]=(((unsigned char)table[code[i+2]])<<6) | ((unsigned char)table[code[i+3]]); //取出第三个字符对应base64表的十进制数的后2位与第4个字符进行组合  
+    }  
+  
+    return res;  
+  
+}
+
+int main(int argc, char **argv) {
+    FILE *fp;
+    unsigned char s[256];//S-box
+    unsigned char key[128];
+    unsigned char pData[64];
+    int i;
+    int reset_exist = 0;
+    unsigned long len = 10;
+    long timestamp_tmp;
+
+    memset(key,0,sizeof(key));
+    memset(pData,0,sizeof(pData));
+    memset(s,0,sizeof(s));
+    get_uuid();
+    mytime();
+    sprintf(key,"8051dt%s6924szl",uuid);
+    //如果数据库为空将日期时间戳加密后写入mysql数据库,否则读取时间
+    strcpy(g_host_name,getenv("MYSQL"));
+    strcpy(g_password,getenv("MYSQL_ROOT_PASSWORD"));
+
+    if (init_mysql()){              //连接数据库
+        print_mysql_error(NULL);
+        exit(1);
+    }
+    memset(sql_tmp,0,sizeof(sql_tmp));
+    sprintf(sql_tmp,"select * from D_T_S_Z_L where prop_key='SYSTEM_UUID'");
+    if (executesql(sql_tmp)){
+        print_mysql_error(NULL);
+        exit(1);
+    }
+    g_res = mysql_store_result(g_conn); 
+    if(mysql_num_rows(g_res) == 0){
+        memset(sql_tmp,0,sizeof(sql_tmp));
+        sprintf(sql_tmp,"insert into D_T_S_Z_L(prop_key,prop_value) values ('SYSTEM_UUID','%s')",uuid);  //写入UUID
+        if (executesql(sql_tmp)){
+            print_mysql_error(NULL);
+            exit(1);
+        }
+    }
+    memset(sql_tmp,0,sizeof(sql_tmp));
+    sprintf(sql_tmp,"select * from D_T_S_Z_L where prop_key='LIMITED_DATETIME'");
+    if (executesql(sql_tmp)){
+        print_mysql_error(NULL);
+        exit(1);
+    }
+    g_res = mysql_store_result(g_conn); 
+    
+    fp = fopen(RESET_FILE, "r");
+    if(fp != NULL){
+        reset_exist = 1;
+        fclose(fp);
+    }
+
+    if(mysql_num_rows(g_res) == 0 && reset_exist == 0){
+        sprintf(pData,"%ld",Timestamp);
+
+        len = strlen(pData);
+        printf("pData is %s, length: %ld\n",pData,len);
+        rc4_init(s, (unsigned char*)key, (unsigned long)strlen(key));//已经完成了初始化
+        rc4_crypt(s, (unsigned char*)pData, len);//加密
+        printf("pData2 is %s, length: %ld\n",pData,strlen(pData));
+
+        memset(sql_tmp,0,sizeof(sql_tmp));
+        sprintf(sql_tmp,"insert into D_T_S_Z_L(prop_key,prop_value) values ('LIMITED_DATETIME','%s')",base64_encode(pData));  //base64后写入数据库
+        if (executesql(sql_tmp)){
+            print_mysql_error(NULL);
+            exit(1);
+        }
+        fp = fopen(RESET_FILE, "w");
+        fprintf(fp, " ");
+        fclose(fp);
+    }
+    else if(mysql_num_rows(g_res) != 0)
+    {
+        g_row=mysql_fetch_row(g_res);
+
+		if(g_row[2] == NULL){
+			mysql_free_result(g_res); //释放结果
+			mysql_close(g_conn); // 关闭链接
+			return 0;
+		}
+        strcpy(pData,base64_decode((unsigned char *) g_row[2]));
+		rc4_init(s, (unsigned char*)key, strlen(key));//已经完成了初始化
+		rc4_crypt(s, (unsigned char*)pData, len);//解密
+        timestamp_tmp = atol(pData);
+        if(Timestamp >= timestamp_tmp){
+            Timestamp = timestamp_tmp;
+        }else{
+            sprintf(pData,"%ld",Timestamp);
+
+            len = strlen(pData);
+            rc4_init(s, (unsigned char*)key, strlen(key));//已经完成了初始化
+            rc4_crypt(s, (unsigned char*)pData, len);//加密
+
+            memset(sql_tmp,0,sizeof(sql_tmp));
+            sprintf(sql_tmp,"insert into D_T_S_Z_L(prop_key,prop_value) values ('LIMITED_DATETIME','%s')",base64_encode(pData));  //base64后写入数据库
+            if (executesql(sql_tmp)){
+                print_mysql_error(NULL);
+                exit(1);
+            }
+            fp = fopen(RESET_FILE, "w");
+            fprintf(fp, " ");
+            fclose(fp);
+        }
+    }
+    else
+    {
+        return 0;
+    }
+    
+    //将数据写入redis数据库
+    char *redis_host = getenv("REDIS");
+    char *redis_password = getenv("REDIS_PASSWORD");
+    unsigned int redis_port = atoi(getenv("REDIS_PORT"));
+    redisContext *c;
+    redisReply *reply;
+
+    struct timeval timeout = { 1, 500000 };
+    c = redisConnectWithTimeout(redis_host, redis_port, timeout);
+    if (c == NULL || c->err) {
+        if (c) {
+            printf("Connection error: %s\n", c->errstr);
+            redisFree(c);
+        } else {
+            printf("Connection error: can't allocate redis context\n");
+        }
+        return 0;
+    }
+
+    //数据库登录认证
+    reply = redisCommand(c, "AUTH %s", redis_password);
+    if (reply->type == REDIS_REPLY_ERROR) {
+        printf("Redis认证失败!\n");
+        freeReplyObject(reply);
+        redisFree(c);
+        return 0;
+    }
+    freeReplyObject(reply);
+
+    //选择数据库
+    reply = redisCommand(c, "SELECT 0");
+    freeReplyObject(reply);
+
+    reply = redisCommand(c,"exists SYSTEM_UUID");
+    if(reply->type == 3 && reply->integer == 0){
+        freeReplyObject(reply);
+        reply = redisCommand(c,"set SYSTEM_UUID %s",uuid);
+    }
+    freeReplyObject(reply);
+
+    reply = redisCommand(c,"exists LIMITED_DATETIME");
+    if(reply->type == 3 && reply->integer == 0){
+        freeReplyObject(reply);
+        reply = redisCommand(c,"set LIMITED_DATETIME %ld",Timestamp);
+    }
+    freeReplyObject(reply);
+        
+    redisFree(c);
+
+    mysql_free_result(g_res); //释放结果
+    mysql_close(g_conn); // 关闭链接
+}
+

+ 6 - 6
usr/src/fail2ban_conf.c

@@ -249,10 +249,10 @@ banaction = iptables-multiport\n\
 mta = mail\n\
 protocol = tcp\n\
 chain = INPUT\n\
-action_ = \%(banaction)s[name=\%(__name__)s, port=\"\%(port)s\", protocol=\"\%(protocol)s\", chain=\"\%(chain)s\"]\n\
-action_mw = \%(banaction)s[name=\%(__name__)s, port=\"\%(port)s\", protocol=\"\%(protocol)s\", chain=\"\%(chain)s\"]\n\
-action_mwl = \%(banaction)s[name=\%(__name__)s, port=\"\%(port)s\", protocol=\"\%(protocol)s\", chain=\"\%(chain)s\"]\n\
-action = \%(action_)s\n\n\
+action_ = %%(banaction)s[name=%%(__name__)s, port=\"%%(port)s\", protocol=\"%%(protocol)s\", chain=\"%%(chain)s\"]\n\
+action_mw = %%(banaction)s[name=%%(__name__)s, port=\"%%(port)s\", protocol=\"%%(protocol)s\", chain=\"%%(chain)s\"]\n\
+action_mwl = %%(banaction)s[name=%%(__name__)s, port=\"%%(port)s\", protocol=\"%%(protocol)s\", chain=\"%%(chain)s\"]\n\
+action = %%(action_)s\n\n\
 "\
 );
 
@@ -317,7 +317,7 @@ enabled = %s\n\
 ignoreip = 127.0.0.1/32 %s \n\
 port = 22\n\
 filter = sshd\n\
-logpath = /var/log/auth.log\n\
+logpath = /init/logs/auth.log\n\
 maxretry = %s\n\
 findtime = %s\n\
 bantime = %s\n\n\
@@ -331,7 +331,7 @@ in, ignored, g_row[2], g_row[3], g_row[4]
     mysql_free_result(g_res); // 释放结果集
     mysql_close(g_conn); // 关闭链接
     	
-	sprintf(cmd,"echo \"\" > /var/log/auth.log;echo \"\" > /var/log/fail2ban.log ;echo \"\" > /var/log/asterisk/messages;asterisk -rx \"logger reload\";service fail2ban restart");
+	sprintf(cmd,"echo \"\" > /init/logs/auth.log;echo \"\" > /var/log/fail2ban.log ;echo \"\" > /var/log/asterisk/messages;asterisk -rx \"logger reload\";service fail2ban restart");
 
 	system(cmd);
 }

+ 333 - 0
usr/src/fail2ban_init.c

@@ -0,0 +1,333 @@
+/*
+============================================================================
+Name        : generate_paging_conf.sh
+Author      : ssc
+Version     : v1.0
+Copyright   : ZYCOO copyright
+Description : Generate paging info from mysql to paging conf file
+============================================================================
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+#include <time.h>
+#include <ctype.h>
+#include <mysql/mysql.h>
+
+MYSQL *g_conn; // mysql 连接
+MYSQL_RES *g_res; // mysql group记录集
+MYSQL_ROW g_row; // 字符串数组,mysql 记录行
+MYSQL_RES *d_res; // mysql device记录集
+MYSQL_ROW d_row; // 字符串数组,mysql 记录行
+
+#define NORMAL_SIZE 256
+#define MAX_SIZE 2048
+#define MIDLE_SIZE 512
+#define MINI_SIZE 64
+#define CONFIG_FILE "/etc/fail2ban/jail.conf"
+#define KEYVALLEN 100
+#define VERSION "V1.0.1"
+
+#define FAIL2BAN_BASIC_SQL "select name,enable,max_retry,find_time,ban_time from t_pbx_fail2ban_basic"
+#define FAIL2BAN_SIP_IGNORED_SQL "select ip,netmask_length from t_pbx_fail2ban_ignored where protocol_sip='1' and enable='1'"
+#define FAIL2BAN_SSH_IGNORED_SQL "select ip,netmask_length from t_pbx_fail2ban_ignored where protocol_ssh='1' and enable='1'"
+
+char g_host_name[MINI_SIZE];
+char g_user_name[MINI_SIZE];
+char g_password[MINI_SIZE];
+char g_db_name[MINI_SIZE];
+const unsigned int g_db_port = 3306;
+
+//读取配置文件函数----功能:删除左边空格
+char *l_trim(char *szOutput, const char *szInput)
+{
+    assert(szInput != NULL);
+    assert(szOutput != NULL);
+    assert(szOutput != szInput);
+    for   (NULL; *szInput != '\0' && isspace(*szInput); ++szInput)
+    {
+        ;
+    }
+    return strcpy(szOutput, szInput);
+}
+
+//   删除右边的空格   
+char *r_trim(char *szOutput, const char *szInput)
+{
+    char *p = NULL;
+    assert(szInput != NULL);
+    assert(szOutput != NULL);
+    assert(szOutput != szInput);
+    strcpy(szOutput, szInput);
+    for(p = szOutput + strlen(szOutput) - 1; p >= szOutput && isspace(*p); --p)
+    {
+        ;
+    }
+    *(++p) = '\0';
+    return szOutput;
+}
+
+//   删除两边的空格   
+char *a_trim(char *szOutput, const char *szInput)
+{
+    char *p = NULL;
+    assert(szInput != NULL);
+    assert(szOutput != NULL);
+    l_trim(szOutput, szInput);
+    for   (p = szOutput + strlen(szOutput) - 1; p >= szOutput && isspace(*p); --p)
+    {
+        ;
+    }
+    *(++p) = '\0';
+    return szOutput;
+}
+//main函数接口 参数1:配置文件路径 参数2:配置文件的那一部分,如general 参数3:键名 参数4:键值
+int GetProfileString(char *profile, char *AppName, char *KeyName, char *KeyVal )
+{
+    char appname[32], keyname[32];
+    char *buf, *c;
+    char buf_i[KEYVALLEN], buf_o[KEYVALLEN];
+    FILE *fp;
+    int found = 0; /* 1 AppName 2 KeyName */
+    if( (fp = fopen( profile, "r" )) == NULL )
+    {
+        printf( "openfile [%s] error [%s]\n", profile, strerror(errno) );
+        return(-1);
+    }
+    fseek( fp, 0, SEEK_SET );
+    memset( appname, 0, sizeof(appname) );
+    sprintf( appname, "[%s]", AppName );
+
+    while( !feof(fp) && fgets( buf_i, KEYVALLEN, fp ) != NULL )
+    {
+        l_trim(buf_o, buf_i);
+        if( strlen(buf_o) <= 0 )
+            continue;
+        buf = NULL;
+        buf = buf_o;
+
+        if( found == 0 )
+        {
+            if( buf[0] != '[' )
+            {
+                continue;
+            }
+            else if ( strncmp(buf, appname, strlen(appname)) == 0 )
+            {
+                found = 1;
+                continue;
+            }
+
+        }
+        else if( found == 1 )
+        {
+            if( buf[0] == '#' )
+            {
+                continue;
+            }
+            else if ( buf[0] == '[' )
+            {
+                break;
+            }
+            else
+            {
+                if( (c = (char *)strchr(buf, '=')) == NULL )
+                    continue;
+                memset( keyname, 0, sizeof(keyname) );
+
+                sscanf( buf, "%[^=|^ |^\t]", keyname );
+                if( strcmp(keyname, KeyName) == 0 )
+                {
+                    sscanf( ++c, "%[^\n]", KeyVal );
+                    char *KeyVal_o = (char *)malloc(strlen(KeyVal) + 1);
+                    if(KeyVal_o != NULL)
+                    {
+                        memset(KeyVal_o, 0, sizeof(KeyVal_o));
+                        a_trim(KeyVal_o, KeyVal);
+                        if(KeyVal_o && strlen(KeyVal_o) > 0)
+                            strcpy(KeyVal, KeyVal_o);
+                        free(KeyVal_o);
+                        KeyVal_o = NULL;
+                    }
+                    found = 2;
+                    break;
+                }
+                else
+                {
+                    continue;
+                }
+            }
+        }
+    }
+    fclose( fp );
+    if( found == 2 )
+        return(0);
+    else
+        return(-1);
+}
+
+char * mytime(){
+        time_t my_time;
+        time(&my_time);
+        char *time_string = ctime(&my_time);
+        if (time_string[strlen(time_string) - 1] == '\n')
+        {
+                time_string[strlen(time_string) - 1] = '\0';
+        }
+        return time_string;
+}
+
+void print_mysql_error(const char *msg) { // 打印最后一次错误
+if (msg)
+    printf("%s: %s\n", msg, mysql_error(g_conn));
+else
+    puts(mysql_error(g_conn));
+}
+
+int executesql(const char * sql) {
+/*query the database according the sql*/
+if (mysql_real_query(g_conn, sql, strlen(sql))) // 如果失败
+    return -1; // 表示失败
+
+return 0; // 成功执行
+}
+
+
+int init_mysql() { // 初始化连接
+// init the database connection
+g_conn = mysql_init(NULL);
+
+/* connect the database */
+if(!mysql_real_connect(g_conn, g_host_name, g_user_name, g_password, g_db_name, g_db_port, NULL, 0)) // 如果失败
+    return -1;
+
+// 是否连接已经可用
+if (executesql("set names utf8")) // 如果失败
+    return -1;
+
+return 0; // 返回成功
+}
+
+int main(int argc, char **argv) {
+    char in[8] = {0};
+	char tmp[MIDLE_SIZE] = {0};
+	char ignored[MIDLE_SIZE] = {0};
+	char cmd[MIDLE_SIZE] = {0};
+
+    strcpy(g_host_name,getenv("MYSQL"));
+    strcpy(g_user_name,getenv("MYSQL_USER"));
+    strcpy(g_password,getenv("MYSQL_PASSWORD"));
+    strcpy(g_db_name,getenv("MYSQL_DATABASE"));
+
+    if (init_mysql()){
+        print_mysql_error(NULL);
+        exit(1);
+    }
+
+    if (executesql(FAIL2BAN_BASIC_SQL)){
+        print_mysql_error(NULL);
+        exit(1);
+    }
+
+    g_res = mysql_store_result(g_conn); // 从服务器传送结果集至本地,mysql_use_result直接使用服务器上的记录集
+    FILE *conf_fail2ban_fp = fopen(CONFIG_FILE, "w+");
+
+    if (conf_fail2ban_fp == NULL){
+        perror("Open paging conf file Error: ");
+        exit(1);
+    }
+
+    fprintf(conf_fail2ban_fp, "[DEFAULT]\n\
+ignoreip = 127.0.0.1/32\n\
+bantime  = 3600\n\
+maxretry = 3\n\
+backend = auto\n\
+banaction = iptables-multiport\n\
+mta = mail\n\
+protocol = tcp\n\
+chain = INPUT\n\
+action_ = %%(banaction)s[name=%%(__name__)s, port=\"%%(port)s\", protocol=\"%%(protocol)s\", chain=\"%%(chain)s\"]\n\
+action_mw = %%(banaction)s[name=%%(__name__)s, port=\"%%(port)s\", protocol=\"%%(protocol)s\", chain=\"%%(chain)s\"]\n\
+action_mwl = %%(banaction)s[name=%%(__name__)s, port=\"%%(port)s\", protocol=\"%%(protocol)s\", chain=\"%%(chain)s\"]\n\
+action = %%(action_)s\n\n\
+"\
+);
+
+    while ((g_row=mysql_fetch_row(g_res)))
+    { // 打印结果集
+        if (g_row[0] == NULL || g_row[1] == NULL || g_row[2] == NULL || g_row[3] == NULL || g_row[4] == NULL)
+        {
+            printf("some feild is empty!\n");
+            continue;
+        }
+
+        if(strcmp((const char *)g_row[1], "1") == 0)
+            strcpy(in, "true");
+        else
+            strcpy(in, "false");
+
+        if(strcmp((const char*)g_row[0], "sip") == 0){
+            if (executesql(FAIL2BAN_SIP_IGNORED_SQL)){
+                print_mysql_error(NULL);
+                exit(1);
+            }
+            d_res = mysql_store_result(g_conn);
+            memset(ignored,0,sizeof(ignored));
+            while(d_row = mysql_fetch_row(d_res))
+            {
+                strcat(ignored,(char *)d_row[0]);
+                strcat(ignored,"/");
+                strcat(ignored,(char *)d_row[1]);
+                strcat(ignored," ");
+            }
+            fprintf(conf_fail2ban_fp, "[sip-iptables]\n\
+enabled = %s\n\
+ignoreip = 127.0.0.1/32 %s \n\
+filter = sip\n\
+action = iptables-allports[name=VOIP, protocol=all]\n\
+logpath = /var/log/asterisk/messages\n\
+maxretry = %s\n\
+findtime = %s\n\
+bantime = %s\n\n\
+",\
+in, ignored, g_row[2], g_row[3], g_row[4]
+);
+            mysql_free_result(d_res);
+        }
+        else if(strcmp((const char*)g_row[0], "ssh") == 0)
+        {
+            if (executesql(FAIL2BAN_SSH_IGNORED_SQL)){
+                print_mysql_error(NULL);
+                exit(1);
+            }
+            d_res = mysql_store_result(g_conn);
+            memset(ignored,0,sizeof(ignored));
+            while(d_row = mysql_fetch_row(d_res))
+            {
+                strcat(ignored,(char *)d_row[0]);
+                strcat(ignored,"/");
+                strcat(ignored,(char *)d_row[1]);
+                strcat(ignored," ");
+            }
+            fprintf(conf_fail2ban_fp, "[SSH]\n\
+enabled = %s\n\
+ignoreip = 127.0.0.1/32 %s \n\
+port = 22\n\
+filter = sshd\n\
+logpath = /init/logs/auth.log\n\
+maxretry = %s\n\
+findtime = %s\n\
+bantime = %s\n\n\
+",\
+in, ignored, g_row[2], g_row[3], g_row[4]
+);
+            mysql_free_result(d_res);
+        }
+    }
+    fclose(conf_fail2ban_fp);
+    mysql_free_result(g_res); // 释放结果集
+    mysql_close(g_conn); // 关闭链接
+}

+ 1 - 1
usr/src/fail2ban_rule.c

@@ -135,7 +135,7 @@ char *get_fb_config(char *buf)
 	MYSQL_RES *res1;
 	MYSQL_ROW row1;
 	char sql[SIZE] = {0};
-	char tmp[SIZE_K*2] = {0};
+	char tmp[SIZE_K*3] = {0};
 	char ignored[SIZE_K*2] = {0};
 	int len1 = 16, len2 = 16, len3 = 16,len4 = 16;
 /*

BIN
usr/src/generate_context_conf


+ 2 - 3
usr/src/generate_context_conf.c

@@ -26,7 +26,7 @@ MYSQL_RES *d_res; // mysql phone记录集
 MYSQL_ROW d_row; // 字符串数组,mysql 记录行
 
 #define MAX_TRUNK_SIZE 256
-#define MAX_SIZE 2048
+#define MAX_SIZE 1024
 #define MIDLE_SIZE 512
 #define MINI_SIZE 64
 #define MYSQL_CONNECT_CONF "/etc/asterisk/exten_gen.ini"
@@ -44,8 +44,7 @@ char g_user_name[MINI_SIZE];
 char g_password[MINI_SIZE];
 char g_db_name[MINI_SIZE];
 const unsigned int g_db_port = 3306;
-char sql_tmp[MIDLE_SIZE];
-char exten_tmp[MAX_SIZE];
+char sql_tmp[MAX_SIZE];
 
 //读取配置文件函数----功能:删除左边空格
 char *l_trim(char *szOutput, const char *szInput)

BIN
usr/src/generate_extension_conf


+ 68 - 7
usr/src/generate_extension_conf.c

@@ -281,6 +281,67 @@ while ((g_row=mysql_fetch_row(g_res))){ // 打印结果集
         printf("some feild is empty!\n");
         continue;
     }
+    fprintf(conf_ivr_fp,"\
+[voicemenu-custom-%s]\n\
+include => %s\n\
+exten => %s,1,NoOp(%s)\n",\
+g_row[1],\
+g_row[6],\
+g_row[1],\
+g_row[0]\
+    );
+    if(g_row[5] != NULL){
+        fprintf(conf_ivr_fp,"same => n,Set(CHANNEL(language)=%s)\n",g_row[5]);
+    }
+    memset(prompt, 0, sizeof(prompt));
+    strncpy(prompt,g_row[2],strlen(g_row[2])-4);
+    fprintf(conf_ivr_fp,"\
+same => n,Set(COUNT=%s)\n\
+same => n(loop),Background(%s)\n",\
+g_row[3],\
+prompt
+    );
+    if(strcmp(g_row[4], "0") != 0 && g_row[4] != NULL){
+        fprintf(conf_ivr_fp,"same => n,WaitExten(%s)\n",g_row[4]);
+    }
+    fprintf(conf_ivr_fp,"\
+same => n,Set(COUNT=$[${COUNT}-1])\n\
+same => n,GotoIf($[${COUNT} < 0]?:loop)\n\
+same => n,WaitExten(1)\n");
+    KeysObject keysObject[MINI_SIZE];
+    memset(keysObject, 0, sizeof(keysObject));
+    if(g_row[7] != NULL){
+        pJson = cJSON_Parse(g_row[7]);
+        iCount = cJSON_GetArraySize(pJson);
+        for(int i = 0;i < iCount;i++){
+            pSub = cJSON_GetArrayItem(pJson,i);
+            if(pSub != NULL){
+                strcpy(keysObject[i].key,cJSON_GetObjectItem(pSub, "key")->valuestring);
+                strcpy(keysObject[i].type,cJSON_GetObjectItem(pSub, "type")->valuestring);
+                strcpy(keysObject[i].exten,cJSON_GetObjectItem(pSub, "exten")->valuestring);
+                if(strcmp(keysObject[i].type, "hangup") == 0){
+                    fprintf(conf_ivr_fp,"exten => %s,1,Hangup()\n",keysObject[i].key);
+                }
+                else if(strcmp(keysObject[i].type, "extension") == 0){
+                    fprintf(conf_ivr_fp,"exten => %s,1,Goto(default,%s,1)\n",keysObject[i].key,keysObject[i].exten);
+                }
+                else if(strcmp(keysObject[i].type, "ivr") == 0){
+                    fprintf(conf_ivr_fp,"exten => %s,1,Goto(voicemenu-custom-%s,%s,1)\n",keysObject[i].key,keysObject[i].exten,keysObject[i].exten);
+                }
+                else if(strcmp(keysObject[i].type, "group") == 0){
+                    fprintf(conf_ivr_fp,"exten => %s,1,Goto(paging-group-%s,%s,1)\n",keysObject[i].key,keysObject[i].exten,keysObject[i].exten);
+                }
+            }
+        }
+    }
+    fprintf(conf_ivr_fp,"\n\n");
+}
+/*
+while ((g_row=mysql_fetch_row(g_res))){ // 打印结果集
+    if (g_row[0] == NULL || g_row[1] == NULL || g_row[2] == NULL){
+        printf("some feild is empty!\n");
+        continue;
+    }
     sprintf(ivrstr,"\
 [voicemenu-custom-%s]\n\
 include => %s\n\
@@ -738,19 +799,19 @@ cJSON_GetObjectItem(pSub, "end_port")->valueint\
             pJson = cJSON_Parse(g_row[2]);
             pSub = cJSON_GetObjectItem(pJson, "bargein");
             if(cJSON_GetObjectItem(pSub, "enable")->valueint == 1){
-                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Macro(spy-barge,${EXTEN:%d},${CALLERID(num)})\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
+                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Macro(spy-barge,${EXTEN:%ld},${CALLERID(num)})\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
             }
             pSub = cJSON_GetObjectItem(pJson, "clear");
             if(cJSON_GetObjectItem(pSub, "enable")->valueint == 1){
-                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Macro(exten-clear,${EXTEN:%d},${CALLERID(num)})\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
+                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Macro(exten-clear,${EXTEN:%ld},${CALLERID(num)})\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
             }
             pSub = cJSON_GetObjectItem(pJson, "syp");
             if(cJSON_GetObjectItem(pSub, "enable")->valueint == 1){
-                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Macro(spy-normal,${EXTEN:%d},${CALLERID(num)})\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
+                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Macro(spy-normal,${EXTEN:%ld},${CALLERID(num)})\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
             }
             pSub = cJSON_GetObjectItem(pJson, "whisper");
             if(cJSON_GetObjectItem(pSub, "enable")->valueint == 1){
-                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Macro(spy-whisper,${EXTEN:%d},${CALLERID(num)})\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
+                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Macro(spy-whisper,${EXTEN:%ld},${CALLERID(num)})\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
             }
             pSub = cJSON_GetObjectItem(pJson, "wakeup");
             if(cJSON_GetObjectItem(pSub, "enable")->valueint == 1){
@@ -762,17 +823,17 @@ cJSON_GetObjectItem(pSub, "end_port")->valueint\
             }
             pSub = cJSON_GetObjectItem(pJson, "cf-alway");
             if(cJSON_GetObjectItem(pSub, "enable")->valueint == 1){
-                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Goto(app-cf-on,cf-${EXTEN:%d},1)\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
+                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Goto(app-cf-on,cf-${EXTEN:%ld},1)\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
                 fprintf(conf_featurecodes_fp, "exten = %s,1,Goto(app-cf-off,s,1)\n",cJSON_GetObjectItem(pSub, "code")->valuestring);
             }
             pSub = cJSON_GetObjectItem(pJson, "cf-busy");
             if(cJSON_GetObjectItem(pSub, "enable")->valueint == 1){
-                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Goto(app-cfb-on,cf-${EXTEN:%d},1)\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
+                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Goto(app-cfb-on,cf-${EXTEN:%ld},1)\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
                 fprintf(conf_featurecodes_fp, "exten = %s,1,Goto(app-cfb-off,s,1)\n",cJSON_GetObjectItem(pSub, "code")->valuestring);
             }
             pSub = cJSON_GetObjectItem(pJson, "cf-noanswer");
             if(cJSON_GetObjectItem(pSub, "enable")->valueint == 1){
-                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Goto(app-cfu-on,cf-${EXTEN:%d},1)\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
+                fprintf(conf_featurecodes_fp, "exten = _%s.,1,Goto(app-cfu-on,cf-${EXTEN:%ld},1)\n",cJSON_GetObjectItem(pSub, "code")->valuestring,strlen(cJSON_GetObjectItem(pSub, "code")->valuestring));
                 fprintf(conf_featurecodes_fp, "exten = %s,1,Goto(app-cfu-off,s,1)\n",cJSON_GetObjectItem(pSub, "code")->valuestring);
             }
         }

+ 7 - 2
usr/src/generate_group_conf.c

@@ -316,8 +316,13 @@ while ((g_row=mysql_fetch_row(g_res))){ // 打印结果集
             continue;
         }
         if(strcmp(d_row[2],"yes") == 0){
-            sprintf(exten_tmp, "%sSIP/%s&", exten_tmp, d_row[0]);
-            sprintf(dest_tmp, "%s%s|", dest_tmp, d_row[0]);
+            //sprintf(exten_tmp, "%sSIP/%s&", exten_tmp, d_row[0]);
+            //sprintf(dest_tmp, "%s%s|", dest_tmp, d_row[0]);
+            strcat(exten_tmp,"SIP/");
+            strcat(exten_tmp,d_row[0]);
+            strcat(exten_tmp,"&");
+            strcat(dest_tmp,d_row[0]);
+            strcat(dest_tmp,"|");
         }
         
         int id = atoi(d_row[1]);

+ 3 - 1
usr/src/generate_trunk_conf.c

@@ -880,7 +880,9 @@ trunkObject[i].allow\
                     }
 
                     if (strcmp(trunkObject[i].contact, "") != 0){
-                        sprintf(registrationString, "%s/%s", registrationString, trunkObject[i].contact);
+                        strcat(registrationString,"/");
+                        strcat(registrationString,trunkObject[i].contact);
+                        //sprintf(registrationString, "%s/%s", registrationString, trunkObject[i].contact);
                     }
 
                     if (strcmp(trunkObject[i].transport, "tcp") == 0){

+ 49 - 16
usr/src/generate_user_conf.c

@@ -35,7 +35,7 @@ MYSQL_ROW d_row; // 字符串数组,mysql 记录行
 #define KEYVALLEN 100
 #define VERSION "V1.0.1"
 
-#define QUERY_PAGING_USER_SQL "select id,phones,strategy,ring_duration from t_paging_users"
+#define QUERY_PAGING_USER_SQL "select id,phones,strategy,ring_duration,noanswer_dest from t_paging_users"
 
 char g_host_name[MINI_SIZE];
 char g_user_name[MINI_SIZE];
@@ -216,8 +216,9 @@ return 0; // 返回成功
 }
 
 int main(int argc, char **argv) {
-cJSON *pJson,*pSub;
+cJSON *pJson,*pSub,*dJson;
 int iCount=0;
+char noanswer_dest[64];
 /*
 memset(g_host_name, 0, sizeof(g_host_name));
 memset(g_user_name, 0, sizeof(g_user_name));
@@ -301,7 +302,7 @@ ringinuse = no\n\
 maxlen = 8\n\
 context = queue-custom\n\
 joinempty = no\n\
-leavewhenempty = no\n\
+leavewhenempty = paused,unavailable,invalid,unknown\n\
 periodic-announce-frequency = 0\n\
 reportholdtime = no\n\
 announce-frequency = 0\n\
@@ -314,21 +315,52 @@ queue-minutes =\n\
 queue-thankyou =\n\
 musicclass = queuemusic\n\
 \n",q,g_row[2]);
-            if(strcmp(g_row[2],"ringall") == 0){
-                for(int i = 0;i < iCount;i++){
-                    pSub = cJSON_GetArrayItem(pJson,i);
-                    if(pSub != NULL){
-                        fprintf(conf_queues_fp, "member => SIP/%s\n",pSub->valuestring);
-                        fprintf(conf_user_queue_fp, "exten => %s,1,Macro(queue,Q%d,${EXTEN},%s)\n", pSub->valuestring,q,g_row[3]);
-                    }
+            dJson = cJSON_Parse(g_row[4]);
+            memset(noanswer_dest,0,sizeof(noanswer_dest));
+            if(dJson)
+            {
+                if(strcmp(cJSON_GetObjectItem(dJson, "type")->valuestring, "hangup") == 0){
+                    strcpy(noanswer_dest,"Goto(hangup,s,1)");
+                }
+                else if(strcmp(cJSON_GetObjectItem(dJson, "type")->valuestring, "extension") == 0){
+                    sprintf(noanswer_dest,"Goto(default,%s,1)",cJSON_GetObjectItem(dJson, "exten")->valuestring);
                 }
-            }else{
-                for(int i = 0;i < iCount;i++){
-                    pSub = cJSON_GetArrayItem(pJson,i);
-                    if(pSub != NULL){
-                        fprintf(conf_queues_fp, "member => SIP/%s,%d\n",pSub->valuestring,i);
-                        fprintf(conf_user_queue_fp, "exten => %s,1,Macro(queue,Q%d,${EXTEN},%s)\n", pSub->valuestring,q,g_row[3]);
+                else if(strcmp(cJSON_GetObjectItem(dJson, "type")->valuestring, "user") == 0){
+                    int id = 100000 + cJSON_GetObjectItem(dJson, "id")->valueint;
+                    sprintf(noanswer_dest,"Goto(manager-queue-%s,s,1)",id);
+                }
+                else if(strcmp(cJSON_GetObjectItem(dJson, "type")->valuestring, "outcall") == 0){
+                    sprintf(noanswer_dest,"Goto(CallingRule_OutCall,%s,1)",cJSON_GetObjectItem(dJson, "exten")->valuestring);
+                }
+            }
+            else
+            {
+                strcpy(noanswer_dest,"Goto(hangup,s,1)");
+            }
+            if(iCount > 0)
+            {
+                if(strcmp(g_row[2],"ringall") == 0){
+                    for(int i = 0;i < iCount;i++){
+                        pSub = cJSON_GetArrayItem(pJson,i);
+                        if(pSub != NULL){
+                            fprintf(conf_queues_fp, "member => SIP/%s\n",pSub->valuestring);
+                            fprintf(conf_user_queue_fp, "exten => %s,1,Macro(queue,Q%d,${EXTEN},%s)\n", pSub->valuestring,q,g_row[3]);
+                            fprintf(conf_user_queue_fp, "same => n,%s\n", noanswer_dest);
+                        }
+                    }
+                    fprintf(conf_user_queue_fp, "exten => s,1,Macro(queue,Q%d,%s,%s)\n", q, pSub->valuestring,g_row[3]);
+                    fprintf(conf_user_queue_fp, "same => n,%s\n", noanswer_dest);
+                }else{
+                    for(int i = 0;i < iCount;i++){
+                        pSub = cJSON_GetArrayItem(pJson,i);
+                        if(pSub != NULL){
+                            fprintf(conf_queues_fp, "member => SIP/%s,%d\n",pSub->valuestring,i);
+                            fprintf(conf_user_queue_fp, "exten => %s,1,Macro(queue,Q%d,${EXTEN},%s)\n", pSub->valuestring,q,g_row[3]);
+                            fprintf(conf_user_queue_fp, "same => n,%s\n", noanswer_dest);
+                        }
                     }
+                    fprintf(conf_user_queue_fp, "exten => s,1,Macro(queue,Q%d,%s,%s)\n", q, pSub->valuestring,g_row[3]);
+                    fprintf(conf_user_queue_fp, "same => n,%s\n", noanswer_dest);
                 }
             }
         }
@@ -339,5 +371,6 @@ fclose(conf_user_queue_fp);
 mysql_free_result(g_res); // 释放结果集
 mysql_free_result(d_res);
 mysql_close(g_conn); // 关闭链接
+cJSON_Delete(dJson);
 cJSON_Delete(pJson);
 }