Index: /branches/rel_avx_2_7_4/avx_cli.spec
===================================================================
--- /branches/rel_avx_2_7_4/avx_cli.spec	(revision 9092)
+++ /branches/rel_avx_2_7_4/avx_cli.spec	(working copy)
@@ -130,6 +130,8 @@
 install -Dm 0755 scripts/check_avxd.sh %{buildroot}/ca/bin/
 install -Dm 0755 scripts/ping_gw.sh %{buildroot}/ca/bin/
 install -Dm 0755 scripts/kdump_cleanup.sh %{buildroot}/ca/bin/
+install -Dm 0755 scripts/ssmtp_config.pl %{buildroot}/ca/bin/
+install -Dm 0755 scripts/msmtp_config.pl %{buildroot}/ca/bin/
 install -Dm 0755 src/backend/backend %{buildroot}/ca/bin/
 install -Dm 0644 src/library/version/other_root_version %{buildroot}/ca/conf/version
 install -Dm 0755 src/backend/res_budget %{buildroot}/ca/bin/
@@ -183,6 +185,8 @@
 install -Dm 0755 tools/words %{buildroot}/ca/etc/
 install -Dm 0644 tools/gnupg_homedir.tgz %{buildroot}/ca/etc/
 install -Dm 0644 tools/recovery_pub_cert.pem %{buildroot}/ca/etc/recovery_pub_cert.pem
+install -Dm 0755 src/library/ca_mail/sendmail.cf %{buildroot}/ca/etc/sendmail.cf
+install -Dm 0755 src/library/ca_mail/ssmtp.conf.def %{buildroot}/ca/etc/ssmtp.conf.def
 install -Dm 0644 conf/template/large.xml %{buildroot}/ca/conf/template/large.xml
 install -Dm 0644 conf/template/medium.xml %{buildroot}/ca/conf/template/medium.xml
 install -Dm 0644 conf/template/small.xml %{buildroot}/ca/conf/template/small.xml
@@ -344,6 +348,8 @@
 %attr (755,root,root)/ca/bin/check_avxd.sh
 %attr (755,root,root)/ca/bin/ping_gw.sh
 %attr (755,root,root)/ca/bin/kdump_cleanup.sh
+%attr (755,root,root)/ca/bin/ssmtp_config.pl
+%attr (755,root,root)/ca/bin/msmtp_config.pl
 %attr (755,root,root)/ca/bin/avxupdate
 %attr (755,root,root)/ca/bin/backend
 %attr (755,root,root)/ca/bin/res_budget
@@ -399,6 +405,8 @@
 %attr (644,root,root)/ca/etc/gnupg_homedir.tgz
 %attr (755,root,root)/ca/etc/words
 %attr (644,root,root)/ca/etc/recovery_pub_cert.pem
+%attr (755,root,root)/ca/etc/sendmail.cf
+%attr (755,root,root)/ca/etc/ssmtp.conf.def
 %attr (644,root,root)/ca/conf/template/large.xml
 %attr (644,root,root)/ca/conf/template/medium.xml
 %attr (644,root,root)/ca/conf/template/small.xml
Index: /branches/rel_avx_2_7_4/scripts/msmtp_config.pl
===================================================================
--- /branches/rel_avx_2_7_4/scripts/msmtp_config.pl	(revision 0)
+++ /branches/rel_avx_2_7_4/scripts/msmtp_config.pl	(working copy)
@@ -0,0 +1,109 @@
+#!/usr/bin/perl
+
+use File::Copy;
+use Getopt::Std;
+use Fcntl qw(:flock :seek);
+
+$conf_file = "/etc/msmtprc";
+$conf_tmp_file = "/tmp/msmtprc";
+
+my $mail_server_addr;
+my $mail_server_port;
+my $mail_server_ssl;
+my $mail_server_username;
+my $mail_server_password;
+
+if ( $ARGV[0] eq "edit_server") {
+    $mail_server_addr = $ARGV[1];
+	$mail_server_port = $ARGV[2];
+    $mail_server_ssl = $ARGV[3];
+    &edit_server;
+}
+
+if ( $ARGV[0] eq "edit_user") {
+    $mail_server_username = $ARGV[1];
+    $mail_server_password = $ARGV[2];
+    &edit_user;
+}
+
+if ( $ARGV[0] eq "no_user") {
+    &no_user;
+}
+
+sub edit_server {
+	open (CONFIG_FILE, "< $conf_file") || die "Can't open msmtp config file: $!\n";
+	open (TMP_FILE, "> $conf_tmp_file") || die "Can't open tmp msmtp config file: $!\n";
+	while(<CONFIG_FILE>)
+	{
+		my($line) = $_;
+		chomp($line);
+		@word = split(/\s/, $line);
+		if (@word[0] eq "host" || @word[0] eq "#host"){
+			print TMP_FILE "host $mail_server_addr\n";
+		}
+		elsif (@word[0] eq "port" || @word[0] eq "#port")
+		{
+			print TMP_FILE "port $mail_server_port\n";
+		} 
+		elsif (@word[0] eq "tls" || @word[0] eq "#tls") 
+		{
+			if ($mail_server_ssl == 1) {
+				print TMP_FILE "tls on\n";
+			} else {
+				print TMP_FILE "tls off\n";
+			}
+		} else {
+			print TMP_FILE "$line\n";
+		}
+	}
+	close(CONFIG_FILE);
+	close(TMP_FILE);
+	copy($conf_tmp_file, $conf_file) or die "Copy failed: $!";
+}
+
+sub edit_user {
+	open (CONFIG_FILE, "< $conf_file") || die "Can't open msmtp config file: $!\n";
+	open (TMP_FILE, "> $conf_tmp_file") || die "Can't open tmp msmtp config file: $!\n";
+	while(<CONFIG_FILE>)
+	{
+		my($line) = $_;
+		chomp($line);
+		@word = split(/\s/, $line);
+		if (@word[0] eq "user" || @word[0] eq "#user") {
+			print TMP_FILE "user $mail_server_username\n";
+		} elsif (@word[0] eq "from" || @word[0] eq "#from"){
+			print TMP_FILE "from $mail_server_username\n";
+		} elsif (@word[0] eq "password" || @word[0] eq "#password") {
+			print TMP_FILE "password $mail_server_password\n";
+		} else {
+			print TMP_FILE "$line\n";
+		}
+	}
+	close(CONFIG_FILE);
+	close(TMP_FILE);
+	copy($conf_tmp_file, $conf_file) or die "Copy failed: $!";
+}
+
+sub no_user {
+	open (CONFIG_FILE, "< $conf_file") || die "Can't open msmtp config file: $!\n";
+	open (TMP_FILE, "> $conf_tmp_file") || die "Can't open tmp msmtp config file: $!\n";
+	while(<CONFIG_FILE>)
+	{
+		my($line) = $_;
+		chomp($line);
+		@word = split(/\s/, $line);
+		if (@word[0] eq "user" || @word[0] eq "#user") {
+			print TMP_FILE "#user \n";
+		} elsif (@word[0] eq "from" || @word[0] eq "#from") {
+			print TMP_FILE "#from \n";
+		} 
+		elsif (@word[0] eq "password" || @word[0] eq "#password") {
+			print TMP_FILE "#password \n";
+		} else {
+			print TMP_FILE "$line\n";
+		}
+	}
+	close(CONFIG_FILE);
+	close(TMP_FILE);
+	copy($conf_tmp_file, $conf_file) or die "Copy failed: $!";
+}
\ No newline at end of file
Index: /branches/rel_avx_2_7_4/scripts/ssmtp_config.pl
===================================================================
--- /branches/rel_avx_2_7_4/scripts/ssmtp_config.pl	(revision 0)
+++ /branches/rel_avx_2_7_4/scripts/ssmtp_config.pl	(working copy)
@@ -0,0 +1,104 @@
+#!/usr/bin/perl
+
+use File::Copy;
+use Getopt::Std;
+use Fcntl qw(:flock :seek);
+
+$conf_file = "/etc/ssmtp/ssmtp.conf";
+$conf_tmp_file = "/tmp/ssmtp.conf";
+
+my $mail_server_addr;
+my $mail_server_ssl;
+my $mail_server_username;
+my $mail_server_password;
+
+if ( $ARGV[0] eq "edit_server") {
+    $mail_server_addr = $ARGV[1];
+    @str = split(/:/, $ARGV[1]);
+    $mail_server_port = @str[1];
+    $mail_server_ssl = $ARGV[2];
+    &edit_server;
+}
+
+if ( $ARGV[0] eq "edit_user") {
+    $mail_server_username = $ARGV[1];
+    $mail_server_password = $ARGV[2];
+    &edit_user;
+}
+
+if ( $ARGV[0] eq "no_user") {
+    &no_user;
+}
+
+sub edit_server {
+	open (CONFIG_FILE, "< $conf_file") || die "Can't open ssmtp config file: $!\n";
+	open (TMP_FILE, "> $conf_tmp_file") || die "Can't open tmp ssmtp config file: $!\n";
+	while(<CONFIG_FILE>)
+	{
+		my($line) = $_;
+		chomp($line);
+		@word = split(/=/, $line);
+		if (@word[0] eq "mailhub" || @word[0] eq "#mailhub") {
+			print TMP_FILE "mailhub=$mail_server_addr\n";
+		} elsif (@word[0] eq "UseTLS" || @word[0] eq "#UseTLS") {
+			if ($mail_server_ssl == 1) {
+				print TMP_FILE "UseTLS=YES\n";
+			} else {
+				print TMP_FILE "UseTLS=NO\n";
+			}
+		} elsif (@word[0] eq "UseSTARTTLS" || @word[0] eq "#UseSTARTTLS") {
+			if ($mail_server_port == 587 && $mail_server_ssl == 1) {
+				print TMP_FILE "UseSTARTTLS=YES\n";    
+			} else {
+				print TMP_FILE "#UseSTARTTLS=YES\n";    
+			}
+		} else {
+			print TMP_FILE "$line\n";
+		}
+	}
+	close(CONFIG_FILE);
+	close(TMP_FILE);
+	copy($conf_tmp_file, $conf_file) or die "Copy failed: $!";
+}
+
+sub edit_user {
+	open (CONFIG_FILE, "< $conf_file") || die "Can't open ssmtp config file: $!\n";
+	open (TMP_FILE, "> $conf_tmp_file") || die "Can't open tmp ssmtp config file: $!\n";
+	while(<CONFIG_FILE>)
+	{
+		my($line) = $_;
+		chomp($line);
+		@word = split(/=/, $line);
+		if (@word[0] eq "AuthUser" || @word[0] eq "#AuthUser") {
+			print TMP_FILE "AuthUser=$mail_server_username\n";
+		} elsif (@word[0] eq "AuthPass" || @word[0] eq "#AuthPass") {
+			print TMP_FILE "AuthPass=$mail_server_password\n";
+		} else {
+			print TMP_FILE "$line\n";
+		}
+	}
+	close(CONFIG_FILE);
+	close(TMP_FILE);
+	copy($conf_tmp_file, $conf_file) or die "Copy failed: $!";
+}
+
+sub no_user {
+	open (CONFIG_FILE, "< $conf_file") || die "Can't open ssmtp config file: $!\n";
+	open (TMP_FILE, "> $conf_tmp_file") || die "Can't open tmp ssmtp config file: $!\n";
+	while(<CONFIG_FILE>)
+	{
+		my($line) = $_;
+		chomp($line);
+		@word = split(/=/, $line);
+		if (@word[0] eq "AuthUser" || @word[0] eq "#AuthUser") {
+			print TMP_FILE "#AuthUser=\n";
+		} elsif (@word[0] eq "AuthPass" || @word[0] eq "#AuthPass") {
+			print TMP_FILE "#AuthPass=\n";
+		} else {
+			print TMP_FILE "$line\n";
+		}
+	}
+	close(CONFIG_FILE);
+	close(TMP_FILE);
+	copy($conf_tmp_file, $conf_file) or die "Copy failed: $!";
+}
Index: /branches/rel_avx_2_7_4/src/avxd/Makefile
===================================================================
--- /branches/rel_avx_2_7_4/src/avxd/Makefile	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/avxd/Makefile	(working copy)
@@ -22,6 +22,8 @@
        -L ../library/avxvainst -lavxvainst \
        -L ../library/avxnet -lavxnet \
        -L ../library/ca_util -lcautil \
+       -L${TOP}/lib/libopenssl-1.1.1  -lcrypto-tls13 -lssl-tls13 \
+       -lssl -lcrypto \
 	   -L ../library/avxssl -lavxssl \
 	   -L $(TOP)/kern/CNN55XX-SDK/api/ -lnitrox-1.3-01 \
        -L ../../lib/avxpci -lavxpci \
@@ -29,6 +31,7 @@
        -L ../../lib/feactl -lfeactl -lresolv \
        -L ../../lib/casnmp -lcasnmp \
        -L ../library/avx_log -lavxlog \
+       -L ../library/ca_regex -lcaregex \
        -L ../library/version -lversion \
        -lpcre \
        -lcurl \
Index: /branches/rel_avx_2_7_4/src/backend/Makefile
===================================================================
--- /branches/rel_avx_2_7_4/src/backend/Makefile	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/backend/Makefile	(working copy)
@@ -22,10 +22,12 @@
        -L${TOP}/lib/vtch -lvtch -lmsgpack -lresolv\
        -lxmlrpc_util -lxmlrpc -lxmlrpc_client\
        -L ../library/ca_util -lcautil -L ../library/ca_ui -lcaui -L ../library/node_man -lnode \
+       -L${TOP}/src/library/ca_mail -lcamail \
        -L${TOP}/lib/libopenssl-1.1.1  -lcrypto-tls13 -lssl-tls13 \
        -lutil  -L ../library/avxnet -lavxnet \
        -L$(TOP)/src/library/management -lsuppress_print \
        -L../library/version -lversion -L../library/avx_log -lavxlog \
+       -L../library/ca_regex -lcaregex \
        -L ../library/avxvainst -lavxvainst \
 	   -L ../library/avxssl -lavxssl \
 	   -L $(TOP)/kern/CNN55XX-SDK/api/ -lnitrox-1.3-01 \
Index: /branches/rel_avx_2_7_4/src/backend/sys_tool.c
===================================================================
--- /branches/rel_avx_2_7_4/src/backend/sys_tool.c	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/backend/sys_tool.c	(working copy)
@@ -76,6 +76,7 @@
 #include "../feactl/apv_feactl.h"
 #include "../feactl/avx_ul.h"
 #include "../../src/library/ca_util/ca_util.h"
+#include "../../src/library/ca_mail/sys_mail.h"
 #include "property.h"
 #include "property_model.h"
 #include "property_mem.h"
@@ -328,6 +329,16 @@
         "#system timezone configuration"
     },
     {
+        write_system_mail_conf,
+        CMD_NORMAL | CMD_ARRAYOS | CMD_GLOBAL,
+        "#system mail configuration"
+    }, 
+    {
+        write_system_mail_relay,
+        CMD_NORMAL|CMD_ARRAYOS | CMD_GLOBAL,
+        "#system mail relay configuration"
+    },
+    {
         write_dhcp_config,
         CMD_NORMAL | CMD_ARRAYOS | CMD_GLOBAL,
         "#avx dhcp configuration"
@@ -450,6 +461,15 @@
         CMD_NORMAL | CMD_ARRAYOS | CMD_GLOBAL
     },
     {
+        clear_system_mail_conf,
+        CMD_NORMAL| CMD_ARRAYOS |CMD_GLOBAL
+    },
+    {
+        clear_system_mail_relay,
+        CMD_NORMAL | CMD_ARRAYOS | CMD_GLOBAL
+    },
+
+    {
         clear_iphost,
         CMD_NORMAL | CMD_ARRAYOS | CMD_GLOBAL
     },
Index: /branches/rel_avx_2_7_4/src/bin/encode_lickey/Makefile
===================================================================
--- /branches/rel_avx_2_7_4/src/bin/encode_lickey/Makefile	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/bin/encode_lickey/Makefile	(working copy)
@@ -32,6 +32,7 @@
        -L${TOP}/lib/vtch -lvtch -lmsgpack -lresolv\
        -L${TOP}/lib/casnmp -lcasnmp\
        -L${TOP}/src/library/version -lversion -L${TOP}/src/library/avx_log -lavxlog \
+       -L${TOP}/src/library/ca_regex -lcaregex\
        -L${TOP}/lib/avxpci -lavxpci\
        -L${TOP}/lib/version -lversion \
        -lpcre \
Index: /branches/rel_avx_2_7_4/src/cli/Makefile
===================================================================
--- /branches/rel_avx_2_7_4/src/cli/Makefile	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/cli/Makefile	(working copy)
@@ -10,7 +10,10 @@
 LINK = $(LIBRARY) -lcurses -lutil -lresolv \
 		-L ../library/node_man -lnode \
 		-L ../library/ca_ui -lcaui \
-		-L ../library/ca_util -lcautil \
+		-L${TOP}/lib/libopenssl-1.1.1  -lcrypto-tls13 -lssl-tls13 \
+		-lssl -lcrypto \
+		-lcrypto -L ../library/ca_util -lcautil \
+		-L ../library/ca_mail -lcamail \
 		-lcrypt -L ../library/version -lversion \
 		-L ../library/management -lsuppress_print \
 		-L ../library/avx_log -lavxlog \
@@ -21,7 +24,8 @@
 		-L ../../lib/vtch/ -lvtch -lmsgpack \
 		-L ../../lib/feactl/ -lfeactl -lpcre \
 		-L ../library/avxnet -lavxnet \
-		-L../../lib/casnmp -lcasnmp -lcurl -luuid -L../library/avxha -lavxha -lxmlrpc_util -lxmlrpc -lxmlrpc_client \
+		-L ../library/ca_regex -lcaregex \
+		-L ../../lib/casnmp -lcasnmp -lcurl -luuid -L../library/avxha -lavxha -lxmlrpc_util -lxmlrpc -lxmlrpc_client \
 		-I${TOP}/src/library/avxresource/ -L${TOP}/src/library/avxresource/ -lavxresource
 
 FLAGS += $(JSON_LIB) -I../library/avx_log 
Index: /branches/rel_avx_2_7_4/src/generator/commands.pm
===================================================================
--- /branches/rel_avx_2_7_4/src/generator/commands.pm	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/generator/commands.pm	(working copy)
@@ -21,61 +21,347 @@
 #I really recommend using 3 space tab stops, or this looks horrible
 #At the top it is an array of hashesdeemed
 my @AoH = (
-	{
-		obj_type => "ITEM",
-		name => "exit",
-		menu => ".",
-		help_string => "Exit from the current access mode",
-		cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
-		user_level => "CLI_LEVEL_USER",
-		function_name => "down_acc_level",
-		function_args => [],
-	},
-	{
-		obj_type => "ITEM",
-		name => "quit",
-		menu => ".",
-		help_string => "Exit from CLI",
-		cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
-		user_level => "CLI_LEVEL_USER",
-		function_name => "quit_acc_level",
-		function_args => [],
-	},
-	{
-		obj_type => "ITEM",
-		name => "help",
-		menu => ".",
-		help_string => "List commands with brief description",
-		cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
-		user_level => "CLI_LEVEL_USER",
-		function_name => "ui_help",
-		function_args => [],
-	},
-	{
-		obj_type => "ITEM",
-		name => "disable",
-		menu => ".",
-		help_string => "Exit out of enable mode",
-		cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
-		user_level => "CLI_LEVEL_ENABLE",
-		function_name => "quit_priv",
-		function_args => [],
-	},
-	{
-		obj_type => "ITEM",
-		name => "enable",
-		menu => ".",
-		help_string => "Access privileged mode",
-		cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
-		user_level => "CLI_LEVEL_USER",
-		function_name => "enter_priv",
-		function_args => [{
-					type => "STRING",
-					help_string => "recovery    Recover Enable password", 
-					optional => "YES",
-					default_value => "NULL",
-				},],
-	},
+    {
+	obj_type => "MENU",
+	name => "system",
+	parent_menu => ".",
+	uniq_name => "root_system",
+	cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+	user_level => "CLI_LEVEL_ENABLE",
+	help_string => "System commands",
+    },
+    {
+	obj_type => "MENU",
+	name => "mail",
+	parent_menu => "root_system",
+	uniq_name => "root_system_mail",
+	cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+	user_level => "CLI_LEVEL_CONFIG",
+	help_string => "Set system mail",
+    },
+    {
+	obj_type => "MENU",
+	name => "external",
+	parent_menu => "root_system_mail",
+	uniq_name => "root_system_mail_external",
+	user_level => "CLI_LEVEL_CONFIG",
+	cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+	help_string => "External mail server configuration",
+    },
+    {
+	obj_type => "ITEM",
+	name => "on",
+	menu => "root_system_mail_external",
+	cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL|CMD_GLOBAL",
+	user_level => "CLI_LEVEL_CONFIG",
+	help_string => "Use external mail server to delivery mail",
+	function_name => "system_mail_external_on",
+	function_args => [],
+    },
+    {
+	obj_type => "ITEM",
+	name => "off",
+	menu => "root_system_mail_external",
+	cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL|CMD_GLOBAL",
+	user_level => "CLI_LEVEL_CONFIG",
+	help_string => "Use local mail server to delivery mail",
+	function_name => "system_mail_external_off",
+	function_args => [],
+    },
+    {
+	obj_type => "ITEM",
+	name => "server",
+	menu => "root_system_mail_external",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL|CMD_GLOBAL",
+        user_level => "CLI_LEVEL_CONFIG",
+        help_string => "Configure the external SMTP mail server",
+        function_name => "system_mail_external_server",
+        function_args => [ {
+				type => "STRING",
+				help_string => "External SMTP server name or External SMTP server ip",
+                                    optional => "NO",
+                           },
+                           {
+				type => "U16",
+                                help_string => "External SMTP server port, default value is 25",
+                                optional => "YES",
+                                default_value => "25",
+                            },
+                            {
+				type => "U16",
+                                help_string => "External SMTP server use SSL/TLS connectivity or not(1-yes, 0-no), default value is 0",
+                                optional => "YES",
+                                default_value => "0",
+                            },],
+    },
+    {
+	obj_type => "ITEM",
+        name => "user",
+        menu => "root_system_mail_external",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL|CMD_SPECIAL_LOG",
+        user_level => "CLI_LEVEL_CONFIG",
+        help_string => "Configure the sender address on the external SMTP mail server",
+        function_name => "system_mail_external_user",
+        function_args => [ {
+				type => "STRING",
+                                help_string => "User name on External SMTP server",
+                                optional => "NO",
+                            },
+                                {
+				    type => "STRING",
+                                    help_string => "Password of this user",
+                                    optional => "NO",
+                                },],
+    },
+    {
+	obj_type => "MENU",
+	name => "relay",
+	parent_menu => "root_system_mail",
+	uniq_name => "root_system_mail_relay",
+        user_level => "CLI_LEVEL_CONFIG",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+        help_string => "System mail relay server configuration",
+    },
+    {
+	obj_type => "ITEM",
+        name => "on",
+        menu => "root_system_mail_relay",
+	cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL|CMD_GLOBAL",
+        user_level => "CLI_LEVEL_CONFIG",
+        help_string => "Enable a relay server configuration",
+        function_name => "system_mail_relay_on",
+        function_args => [],
+    },
+    {
+	obj_type => "ITEM",
+        name => "off",
+        menu => "root_system_mail_relay",
+	cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL|CMD_GLOBAL",
+        user_level => "CLI_LEVEL_CONFIG",
+        help_string => "Disable a relay server configuration",
+        function_name => "system_mail_relay_off",
+        function_args => [],
+    },
+    {
+	obj_type => "ITEM",
+        name => "server",
+        menu => "root_system_mail_relay",
+	cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+	user_level => "CLI_LEVEL_CONFIG",
+        help_string => "To config a relay server",
+        function_name => "system_mail_relay_server_add",
+        function_args => [ {
+				type => "STRING",
+                                help_string => "Hostname to relay",
+                                optional => "NO",
+			   },
+                           {
+			        type =>"STRING",
+                                help_string => "Relay server name or relay server ip",
+                                optional => "NO",
+                           },],
+    },
+    {
+	obj_type => "ITEM",
+	name => "hostname",
+        menu => "root_system_mail",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+        user_level => "CLI_LEVEL_CONFIG",
+        help_string => "Set SMTP EHLO/HELO hostname",
+        function_name => "system_mail_hostname",
+        function_args => [ {
+				type => "STRING",
+                                help_string => "SMTP EHLO/HELO hostname",
+                                optional => "NO",
+                           },
+                           {
+				type => "U32",
+                                help_string => "Whether to send alert messages when the hostname is the same as the mail server domain name (1: Yes, 0: No, default is 0)",
+                                optional => "YES",
+                                default_value => "0",
+                           }, ],
+    },
+    {
+        obj_type => "ITEM",
+        name => "from",
+        menu => "root_system_mail",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+        user_level => "CLI_LEVEL_CONFIG",
+        help_string => "Set SMTP From header",
+        function_name => "system_mail_from",
+        function_args => [ {
+                                type => "STRING",
+                                help_string => "Value of SMTP From header",
+                                optional => "NO",
+                            }, ],
+    },
+    {
+        obj_type => "MENU",
+        name => "external",
+        parent_menu => "root_no_system_mail",
+        uniq_name => "root_no_system_mail_external",
+        user_level => "CLI_LEVEL_CONFIG",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+        help_string => "Delete the configuration of the external SMTP mail server",
+    },
+    {
+        obj_type => "ITEM",
+        name => "server",
+        menu => "root_no_system_mail_external",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+        user_level => "CLI_LEVEL_CONFIG",
+        help_string => "Delete the external SMTP mail server",
+        function_name => "no_system_mail_external_server",
+        function_args => [],
+    },
+    {
+        obj_type => "ITEM",
+        name => "user",
+        menu => "root_no_system_mail_external",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+        user_level => "CLI_LEVEL_CONFIG",
+        help_string => "Delete the sender address on the external SMTP mail server",
+        function_name => "no_system_mail_external_user",
+        function_args => [],
+    },
+    {
+        obj_type => "MENU",
+        name => "relay",
+        parent_menu => "root_no_system_mail",
+        uniq_name => "root_no_system_mail_relay",
+        user_level => "CLI_LEVEL_CONFIG",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+        help_string => "Delete a record of system mail relay server configuration",
+    },
+    {
+        obj_type => "ITEM",
+        name => "server",
+        menu => "root_no_system_mail_relay",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+	user_level => "CLI_LEVEL_CONFIG",
+        help_string => "Delete a system mail relay server",
+        function_name => "system_mail_relay_server_del",
+        function_args => [ {
+				type => "STRING",
+                                help_string => "Hostname to del",
+                                optional => "NO",
+                            },],
+    },
+    {
+        obj_type => "ITEM",
+        name => "from",
+        menu => "root_no_system_mail",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+        user_level => "CLI_LEVEL_CONFIG",
+        help_string => "Reset SMTP From header",
+        function_name => "no_system_mail_from",
+        function_args => [],
+    },
+    {
+        obj_type => "ITEM",
+        name => "hostname",
+        menu => "root_no_system_mail",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+        user_level => "CLI_LEVEL_CONFIG",
+        help_string => "Reset SMTP ELHO/HELO hostname",
+        function_name => "no_system_mail_hostname",
+        function_args => [],
+    },
+    {
+        obj_type => "ITEM",
+        name => "mail",
+        menu => "root_show_system",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+        user_level => "CLI_LEVEL_ENABLE",
+        help_string => "Display system mail configuration",
+        function_name => "show_system_mail_conf",
+        function_args => [],
+    },
+    {
+        obj_type => "ITEM",
+        name => "relay",
+        menu => "root_show_system",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+        user_level => "CLI_LEVEL_ENABLE",
+        help_string => "Display system mail relay configuration",
+        function_name => "show_system_mail_relay",
+        function_args => [],
+    },
+    {
+        obj_type => "ITEM",
+        name => "mail",
+        menu => "root_clear_system",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+        user_level => "CLI_LEVEL_CONFIG",
+        help_string => "Reset system mail configuration",
+        function_name => "clear_system_mail_conf",
+        function_args => [],
+    },
+    {
+        obj_type => "ITEM",
+        name => "relay",
+        menu => "root_clear_system",
+        user_level => "CLI_LEVEL_CONFIG",
+        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+        help_string => "Clear system mail relay configuration",
+        function_name => "clear_system_mail_relay",
+        function_args => [],
+    },
+    {	
+	obj_type => "ITEM",
+	name => "exit",
+	menu => ".",
+	help_string => "Exit from the current access mode",
+	cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+	user_level => "CLI_LEVEL_USER",
+	function_name => "down_acc_level",
+	function_args => [],
+    },
+    {
+	obj_type => "ITEM",
+	name => "quit",
+	menu => ".",
+	help_string => "Exit from CLI",
+	cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+	user_level => "CLI_LEVEL_USER",
+	function_name => "quit_acc_level",
+	function_args => [],
+    },
+    {
+    	obj_type => "ITEM",
+	name => "help",
+	menu => ".",
+	help_string => "List commands with brief description",
+	cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+	user_level => "CLI_LEVEL_USER",
+	function_name => "ui_help",
+	function_args => [],
+    },
+    {
+    	obj_type => "ITEM",
+	name => "disable",
+	menu => ".",
+	help_string => "Exit out of enable mode",
+	cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+	user_level => "CLI_LEVEL_ENABLE",
+	function_name => "quit_priv",
+	function_args => [],
+    },
+    {
+	obj_type => "ITEM",
+	name => "enable",
+	menu => ".",
+	help_string => "Access privileged mode",
+	cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+	user_level => "CLI_LEVEL_USER",
+	function_name => "enter_priv",
+	function_args => [{
+				type => "STRING",
+				help_string => "recovery    Recover Enable password", 
+				optional => "YES",
+				default_value => "NULL",
+			},],
+    },
 	{
 		obj_type =>"MENU",
 		parent_menu => ".",
@@ -2251,15 +2537,6 @@
 	},
 	{
 		obj_type => "MENU",
-		name => "system",
-		parent_menu => ".",
-		uniq_name => "root_system",
-		cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
-		user_level => "CLI_LEVEL_ENABLE",
-		help_string => "System commands",
-	},
-	{
-		obj_type => "MENU",
 		name => "boot",
 		parent_menu => "root_system",
 		uniq_name => "root_system_boot",
@@ -2342,15 +2619,6 @@
         function_name => "system_next_ustack",
         function_args => [],
     },
-    {
-        obj_type => "MENU",
-        name => "mail",
-        parent_menu => "root_system",
-        uniq_name => "root_system_mail",
-        cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
-        user_level => "CLI_LEVEL_CONFIG",
-        help_string => "Set system mail",
-    },
 	{
 		obj_type => "ITEM",
 		name => "from",
@@ -2833,6 +3101,42 @@
 					},
 					],
 	},
+                {
+                obj_type => "ITEM",
+                name => "alert",
+                menu => "root_log",
+                cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL|CMD_GLOBAL",
+                user_level => "CLI_LEVEL_CONFIG",
+                help_string => "Add a new alert log or change an old alert log",
+                function_name => "avx_log_set_alert_add",
+                function_args => [{
+                                                                type => "U32",
+                                                                help_string => "alert log id",
+                                                                optional => "NO",
+                                                            },
+                                  {
+                                                                type => "STRING",
+                                                                help_string => "regular expression to match the log messages",
+                                                                optional => "NO",
+                                                            },
+                                  {
+                                                                type => "STRING",
+                                                                help_string => "email address",
+                                                                optional => "NO",
+                                                            },
+                                  {
+                                                                type => "U32",
+                                                                help_string => "interval to send the email (0..10000 minutes, 0 means to email right away)",
+                                                                optional => "NO",
+                                                            },
+                                  {
+                                                                type => "STRING",
+                                                                help_string => "alert log type: data or count",
+                                                                optional => "YES",
+                                                                default_value => "\"data\"",
+                                                            },
+                                  ],
+        },
 	{
 		obj_type => "MENU",
 		parent_menu => "root_no",
@@ -2842,6 +3146,21 @@
 		help_string => "Remove log configuration",
 		uniq_name => "root_no_log",
 	},
+        {
+                obj_type => "ITEM",
+                name => "alert",
+                menu => "root_no_log",
+                cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL|CMD_GLOBAL",
+                user_level => "CLI_LEVEL_CONFIG",
+                help_string => "Delete an old alert log",
+                function_name => "log_set_alert_delete",
+                function_args => [{
+                                                                type => "U32",
+                                                                help_string => "alert log id",
+                                                                optional => "NO",
+                                                            },
+                                  ],
+        },
 	{
 		obj_type => "ITEM",
 		menu => "root_no_log",
@@ -2910,6 +3229,16 @@
 		user_level => "CLI_LEVEL_CONFIG",
 		help_string => "Clear log data or reset logging configuration",
 	},
+        {
+                obj_type => "ITEM",
+                name => "alert",
+                menu => "root_clear_log",
+                help_string => "Clear all the alert log settings",
+                cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL|CMD_GLOBAL",
+                user_level => "CLI_LEVEL_CONFIG",
+                function_name => "clear_log_alert",
+                function_args => [],
+        },
 	{
 		obj_type => "ITEM",
 		name => "buff",
@@ -3174,6 +3503,22 @@
 				default_value =>"100",
 			}, ],
 	},
+        {
+                obj_type => "ITEM",
+                name => "alert",
+                menu => "root_show_log",
+                cmd_attribute => "CMD_ARRAYOS|CMD_NORMAL",
+                user_level => "CLI_LEVEL_ENABLE",
+                help_string => "Show one or all alert log setting(s)",
+                function_name => "log_show_alert",
+                function_args => [{
+                                                                type => "U32",
+                                                                help_string => "alert log id",
+                                                                optional => "YES",
+                                                                default_value => "0",
+                                                            },
+                                  ],
+        },
 	{
 		obj_type => "MENU",
 		name => "write",
Index: /branches/rel_avx_2_7_4/src/library/Makefile
===================================================================
--- /branches/rel_avx_2_7_4/src/library/Makefile	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/library/Makefile	(working copy)
@@ -5,7 +5,7 @@
 
 include $(TOP)/Makefile.master
 
-SDIRS=avx_log avxssl node_man ca_ui ca_util version avxha management avxnet avxvainst avxresource
+SDIRS = ca_mail avx_log avxssl node_man ca_ui ca_util ca_regex version avxha management avxnet avxvainst avxresource
 
 # since we are using some utils that might not be on the build machine
 # lets not fail the entire build, but still be noise about failing to
Index: /branches/rel_avx_2_7_4/src/library/avx_log/avx_log.h
===================================================================
--- /branches/rel_avx_2_7_4/src/library/avx_log/avx_log.h	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/library/avx_log/avx_log.h	(working copy)
@@ -3,11 +3,24 @@
 
 #include <netinet/in.h>
 
+#define MAX_LOG_STRING 1024
 #define MAX_IP_LEN 46
 #define AVX_LOG_MAX_HOST 	6
 #define MAX_KEY_WORD_LENGTH 40
 //#define MAX_MODULE_NAME_LENGTH 40
 #define AVX_LOG_MAX_FILTER 20
+#define AVX_LOG_MAX_ALERT_NUM         32
+#define AVX_LOG_MAX_SHORT_LINE_SIZE    128
+#define AVX_LOG_MAX_LONG_TOKEN_SIZE    64
+#define AVX_LOG_MAX_ALERT_INTERVAL  10000 /*10000 minutes*/
+/*define alert logs flags*/
+#define AVX_LOG_ALERT_NORMAL          0x0000
+#define AVX_LOG_ALERT_INUSE           0x0001  /*this element is used*/
+#define AVX_LOG_ALERT_COUNT           0x0002  /*only count the number of matches*/
+#define AVX_LOG_MAX_DATA_SIZE         5 * 1024
+#define AVX_LOG_MAX_LINE_SIZE         256
+#define AVX_LOG_MAX_MBOX_NUM          (AVX_LOG_MAX_ALERT_NUM * 5) / 4
+#define AVX_LOG_SENDMAIL_TIME         3
 
 typedef struct {
     uint16_t filter_id;
@@ -70,9 +83,40 @@
 	LOG_IDX_MAX
 };
 
+struct _regex_node;
+
+typedef struct _log_alert_t {
+        int id;    
+        int flags;
+        int interval;  /*in seconds*/
+        int timer;     /*if = 0, means the data should be sent out*/
+        char match[AVX_LOG_MAX_SHORT_LINE_SIZE + 1];
+        char email[AVX_LOG_MAX_LONG_TOKEN_SIZE + 1];
+        int count; /*how many times the log matches in a minutes*/
+} log_alert_t;
+#define LOG_SHM_MAGIC 0xABCD1234
+typedef struct _log_alert_buffer_t {
+        int magic_count;
+        log_alert_t alerts[AVX_LOG_MAX_ALERT_NUM + 1];
+} log_alert_buffer_t;
+
+typedef struct _log_mbox_t {
+        int id;   /*alert id*/
+        int len;  /*the mail data length*/
+        char data[AVX_LOG_MAX_DATA_SIZE + 1];
+} log_mbox_t;
+
+typedef struct _log_mbox_buffer_t {
+        int count;
+        log_mbox_t mboxes[AVX_LOG_MAX_MBOX_NUM + 1];
+} log_mbox_buffer_t;
+
 extern int avx_log(enum avxlog_idx idx, int argn, ...);
 extern avxlog_cfg_t * avxlog_cfg_attach(void);
 extern int clear_avxlog(void);
 extern char * write_avxlog_conf(void);
-
+extern int clear_log_alert(void);
+extern int log_set_alert_delete(int);
+extern int log_alert_data_reset(void);
+extern int log_show_alert(int id);
 #endif	/* _AVX_LOG_ */
Index: /branches/rel_avx_2_7_4/src/library/avx_log/avx_log.c
===================================================================
--- /branches/rel_avx_2_7_4/src/library/avx_log/avx_log.c	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/library/avx_log/avx_log.c	(working copy)
@@ -23,6 +23,9 @@
 #include "ca_ui.h"
 #include "../avxvainst/va_log.h"
 #include "../../../lib/casnmp/snmp.h"
+#include "../../proxy_shm.h"
+#include "../../library/ca_regex/avx_regex.h"
+#include "../../library/ca_regex/patricia.h"
 
 #define	CA_SHM_LOG_KEY		1407
 #define AVX_LOG_BUFF_SIZE   (1024 * 10)
@@ -47,6 +50,12 @@
 
 #endif
 
+int32_t log_node_cmp(void *nodea, void *nodeb);
+int log_alert_check(char *msg);
+static int log_alert_put(char *msg, int id);
+int log_alert_data_reset(void);
+struct _patricia_tree;
+static struct _patricia_tree *regex_tree = NULL;
 struct avxlog_msg {
 	enum avxlog_idx idx;
 	enum avxlog_level level;
@@ -67,6 +76,8 @@
 };
 
 static avxlog_cfg_t * log_cfg_p;
+static log_alert_buffer_t * log_alert_buf;
+static log_mbox_buffer_t * mbox_buffer;
 static struct avxlog_msg avxlog_table[LOG_IDX_MAX] = {
 	{LOG_IDX_TEST, AVXLOG_EMERG, 0, ARRAY_COMPINFO_BRAND " test log",
 		"This log is for test.", "Ignore it"},
@@ -112,6 +123,7 @@
 
 
 static int avxlog_conf_wrapper(char *buf, int len);
+static int log_alert_regex_valid(char *regex, char *reason, int32_t max_reason_len);
 
 int
 avxlog_cfg_p_init(void)
@@ -137,6 +149,78 @@
 	return 0;
 }
 
+int
+log_mbox_p_init(void)
+{
+        int shm_id;
+        void *p = NULL;
+
+        shm_id = shmget(LOG_MBOX_BUF_SHM_KEY, sizeof(log_mbox_buffer_t), IPC_CREAT | 0666);
+        if (shm_id < 0) {
+                perror("AVX mbox get failed");
+                log_cfg_p = NULL;
+                return 1;
+        }
+
+        p = shmat(shm_id, NULL, 0);
+        if (p == (void *)-1) {
+                perror("AVX mbox attach failed!\n");
+                return 1;
+        }
+
+        mbox_buffer = (log_mbox_buffer_t *) p;
+        bzero(mbox_buffer, sizeof(log_mbox_buffer_t));
+        return 0;
+}
+
+log_mbox_buffer_t *
+mbox_attach(void)
+{
+        if (mbox_buffer == NULL) {
+                log_mbox_p_init();
+        }
+        return mbox_buffer;
+}
+
+int
+mbox_detach(void)
+{
+        if (mbox_buffer != NULL) {
+                shmdt(mbox_buffer);
+                mbox_buffer = NULL;
+        }
+
+        return 0;
+}
+
+void rebuild_regex_tree(void) {
+        regex_node_t *regex_node = NULL;
+        int i;
+
+	for (i = 1; i <= AVX_LOG_MAX_ALERT_NUM; i++) {
+	   
+	   if(log_alert_buf->alerts[i].flags & AVX_LOG_ALERT_INUSE) { 
+	        if (regex_tree == NULL) {
+		     regex_tree = regex_tree_alloc();
+		     if (regex_tree == NULL) {
+			return ;
+		     }
+	        }
+                regex_node = regex_insert_dup(regex_tree, log_alert_buf->alerts[i].match, strlen(log_alert_buf->alerts[i].match));
+		if (regex_node == NULL){
+			return ;
+		}
+		regex_node->data = malloc(sizeof(int));
+		if (regex_node->data == NULL) {
+			regex_delete(regex_tree, regex_node);
+			return ;
+		}
+		/*use the regex_node.data to save the id*/
+		*((int *)(regex_node->data)) = i;
+	    }
+        }       
+ 
+}
 avxlog_cfg_t *
 avxlog_cfg_attach(void)
 {
@@ -147,6 +231,44 @@
 }
 
 int
+log_alert_buffer_init(void)
+{
+        int shm_id;
+        void *p = NULL;
+
+        shm_id = shmget(LOG_ALERT_BUF_SHM_KEY, sizeof(log_alert_buffer_t), IPC_CREAT | 0666);
+        if (shm_id < 0) {
+                perror("AVX log get log alert buffer failed");
+                log_alert_buf = NULL;
+                return 1;
+        }
+
+        p = shmat(shm_id, NULL, 0);
+        if (p == (void *)-1) {
+                perror("AVX log attach log alert buffer failed!\n");
+                return 1;
+        }
+
+        log_alert_buf = (log_alert_buffer_t *) p;
+        if (log_alert_buf->magic_count != LOG_SHM_MAGIC) {
+            memset(log_alert_buf, 0, sizeof(log_alert_buffer_t));
+	    if(regex_tree != NULL){
+	       patricia_tree_free(regex_tree);
+	       regex_tree = NULL;
+	    }
+            log_alert_buf->magic_count = LOG_SHM_MAGIC;
+        }
+	else {
+	    if(regex_tree != NULL){
+	       patricia_tree_free(regex_tree);
+	       regex_tree = NULL;
+	    }
+	    rebuild_regex_tree();
+	}
+        return 0;
+}
+
+int
 avxlog_cfg_detach(void)
 {
 	if (log_cfg_p != NULL) {
@@ -157,6 +279,30 @@
 	return 0;
 }
 
+log_alert_buffer_t *
+log_alert_attach(void)
+{
+        if (log_alert_buf == NULL) {
+		log_alert_buffer_init();
+        }
+        return log_alert_buf;
+}
+
+int
+log_alert_detach(void)
+{
+        if (log_alert_buf != NULL) {
+                shmdt(log_alert_buf);
+                log_alert_buf = NULL;
+		if(regex_tree != NULL) {
+		    patricia_tree_free(regex_tree);
+		    regex_tree = NULL;
+		}
+        }
+
+        return 0;
+}
+
 int
 avxlog_on(void)
 {
@@ -178,6 +324,424 @@
 }
 
 int
+avx_log_set_alert_add(int id, char *match, char *email, int interval, char *flag)
+{
+        log_alert_buffer_t* alert_buf;
+        char reason[AVX_LOG_MAX_SHORT_LINE_SIZE + 1] = "";
+        regex_node_t *regex_node = NULL;
+        alert_buf = log_alert_attach();
+        regex_node_t *matched_node = NULL;
+        struct regex_result_list *result_list = NULL;
+
+        if (alert_buf == NULL) {
+                printf("Can't get log config.\n");
+                return -1;
+        }
+
+        /*check the alert log id*/
+        if ( (id < 1) || (id > AVX_LOG_MAX_ALERT_NUM) ) {
+
+                printf("Alert log ID must be in the range of 1..%u.\n", AVX_LOG_MAX_ALERT_NUM);
+                return -1;
+        }
+        /*check the regular expression*/
+        if (!match) {
+
+                printf("Wrong regular expression.\n");
+                return -1;
+        }
+        else {
+
+                memset(reason, 0, sizeof(reason));
+                if (!log_alert_regex_valid(match, reason, sizeof(reason) - 1)) {
+
+                        printf("%s", reason);
+                        return -1;
+                }
+        }
+
+        /*check the email address*/
+        if (!email) {
+
+                printf("Wrong email address.\n");
+                return -1;
+        }
+        else {
+
+                if (!strchr(email, '@')) {
+
+                        printf("Email: '@' expected.\n");
+                        return -1;
+                }
+
+                if (strchr(email, ' ')) {
+
+                        printf("Email: SPACE unexpected.\n");
+                        return -1;
+                }
+        }
+        /*check the alert interval*/
+        if ( (interval < 0) || (interval > AVX_LOG_MAX_ALERT_INTERVAL) ) {
+
+                printf("Alert interval must be in the range of 1..%u.\n",
+                        AVX_LOG_MAX_ALERT_INTERVAL);
+                return -1;
+        }
+        if (!strcasecmp(flag, "count")) {
+	}
+        else if (strcasecmp(flag, "data")) {
+
+                printf("Flag can only be data or count.\n");
+                return -1;
+        } 
+        if (alert_buf->alerts[id].flags & AVX_LOG_ALERT_INUSE) {
+
+                        printf("Type \"YES\" to overwrite alert log %d: ", id);
+                        memset(reason, 0, sizeof(reason));
+                        if (fgets(reason, sizeof(reason), stdin) == NULL)
+                        {
+                                printf("Not overwrite.\n");
+                                return 0;
+                        }
+
+                        if (strcasecmp(reason, "YES\n") != 0)
+                        {
+                                printf("Not overwrite.\n");
+                                return 0;
+                        }
+                        if(regex_tree != NULL) {
+
+				result_list = regex_match(regex_tree, alert_buf->alerts[id].match, strlen(alert_buf->alerts[id].match), NULL, NULL,NULL);
+				if(result_list) {
+				   matched_node = SLIST_FIRST(result_list);
+				   if(matched_node != NULL){
+					regex_delete(regex_tree, matched_node);
+				   }
+                                }
+                        }
+                        memset(&alert_buf->alerts[id], 0,sizeof(alert_buf->alerts[id]));
+           }
+ 
+	if (regex_tree == NULL) {
+		regex_tree = regex_tree_alloc();
+		if (regex_tree == NULL) {
+			return -1;
+		}
+	}
+        regex_node = regex_insert_dup(regex_tree, match, strlen(match));
+	if (regex_node == NULL){
+		return -1;
+	}
+        regex_node->data = malloc(sizeof(int));
+	if (regex_node->data == NULL) {
+		regex_delete(regex_tree, regex_node);
+		return -1;
+	}
+	/*use the regex_node.data to save the id*/
+	*((int *)(regex_node->data)) = id;
+       
+        alert_buf->alerts[id].flags |= AVX_LOG_ALERT_INUSE;
+        
+	if (!strcasecmp(flag, "count")) {
+                 alert_buf->alerts[id].flags  |= AVX_LOG_ALERT_COUNT;
+        }
+	alert_buf->alerts[id].id=id;
+
+        strncpy(alert_buf->alerts[id].email, email, sizeof(alert_buf->alerts[id].email) - 1);
+
+        alert_buf->alerts[id].timer = alert_buf->alerts[id].interval = interval * 60; /*change to seconds*/
+        strncpy(alert_buf->alerts[id].match, match, sizeof(alert_buf->alerts[id].match) - 1);
+        return 0;
+}
+ 
+int clear_log_alert(void) {
+        int i;
+	struct _regex_node *matched_node;
+        struct regex_result_list *result_list = NULL;
+        log_alert_buffer_t* alert_buf = log_alert_attach();
+        if (alert_buf == NULL) {
+                printf("Can't get log config.\n");
+                return -1;
+        }
+        log_mbox_buffer_t* mbox_buf = mbox_attach();
+        if(mbox_buf  == NULL) {
+                printf("Can't get mbox buffer.\n");
+                return -1;
+        }
+	for (i = 1; i <= AVX_LOG_MAX_ALERT_NUM; i++) {
+		if (alert_buf->alerts[i].flags & AVX_LOG_ALERT_INUSE) {
+			/*free alert.pnode_match.data*/
+			if(regex_tree == NULL) {
+			    break;
+			}
+			result_list = regex_match(regex_tree,alert_buf->alerts[i].match,strlen(alert_buf->alerts[i].match),NULL, NULL,NULL);
+			if(result_list) {
+				matched_node = SLIST_FIRST(result_list);
+			        if (matched_node != NULL) {
+					regex_delete(regex_tree, matched_node);
+				}
+			}
+
+
+	        }
+       }
+       if (regex_tree && regex_tree_empty(regex_tree)) {
+		regex_tree_free(regex_tree);
+		regex_tree = NULL;
+       }
+       bzero(alert_buf, sizeof(log_alert_buffer_t)); /*clear all the alert setting*/
+       bzero(mbox_buf, sizeof(log_mbox_buffer_t)); /*clear all the alert setting*/
+       return 0;
+}
+
+int log_alert_mbox_clear(int id) {
+        int i;
+	log_mbox_t *mbox;
+        log_mbox_buffer_t* mbox_buf = mbox_attach();
+        if(mbox_buf  == NULL) {
+                printf("Can't get mbox buffer.\n");
+                return -1;
+        }
+
+        if ( (id < 0) || (id > AVX_LOG_MAX_MBOX_NUM) )
+                return -1;
+
+        if (!id) {
+
+                /*clear all mboxes's data*/
+                bzero(mbox_buf, sizeof(log_mbox_buffer_t));
+        }
+        else {
+
+                /*clear one mbox's data, firstly clear the dedicated buffer*/
+                mbox = &mbox_buf->mboxes[id];
+                bzero(mbox, sizeof(*mbox));
+
+                /*clear extra buffer*/
+                for (i = AVX_LOG_MAX_ALERT_NUM + 1; i <= AVX_LOG_MAX_MBOX_NUM; i++) {
+
+                        mbox = &mbox_buf->mboxes[i];
+                        if (mbox->id == id)
+                                bzero(mbox, sizeof(*mbox));
+                }
+        }
+        return 0;
+}
+
+int log_set_alert_delete(int id) {
+        log_alert_buffer_t *alert_buf = log_alert_attach();
+	struct _regex_node* matched_node=NULL;
+        struct regex_result_list *result_list = NULL;
+        if (alert_buf == NULL) {
+                printf("Can't get log config.\n");
+                return -1;
+        }
+        if (alert_buf->alerts[id].flags & AVX_LOG_ALERT_INUSE) {
+                if(regex_tree) {
+			result_list = regex_match(regex_tree,alert_buf->alerts[id].match,strlen(alert_buf->alerts[id].match),NULL, NULL,NULL);
+			if(result_list) {
+				   matched_node = SLIST_FIRST(result_list);
+				   if(matched_node != NULL) {
+					regex_delete(regex_tree, matched_node);
+				   }
+			}
+		}
+                memset(&alert_buf->alerts[id], 0, sizeof(alert_buf->alerts[id]));
+        }
+        log_alert_mbox_clear(id);
+
+        return 0;
+}
+
+int log_alert_data_reset(void)
+{
+        int i;
+        log_alert_t *alert;
+        log_mbox_t *mbox;
+        log_mbox_buffer_t* mbox_buf = mbox_attach();
+        if(mbox_buf  == NULL) {
+                printf("Can't get mbox buffer.\n");
+                return -1;
+        }
+        log_alert_buffer_t* alert_buf = log_alert_attach();
+        if (alert_buf == NULL) {
+                printf("Can't get log config.\n");
+                return -1;
+        }
+	
+        /*clear all the mboxes' data which is sent out*/
+        for (i = 1; i <= AVX_LOG_MAX_ALERT_NUM; i++) {
+
+                alert = &alert_buf->alerts[i];
+                mbox = &mbox_buf->mboxes[i];
+                if (alert->flags & AVX_LOG_ALERT_INUSE) {
+
+                        if (!alert->timer) { /*if = 0, must be sent out*/
+
+                                alert->timer = alert->interval;
+                                bzero(mbox, sizeof(*mbox));
+
+                                /*for count alert, reset count to zero*/
+                                /*for non-count, should also be 0*/
+                                alert->count = 0;
+                        }
+                        else {
+                                alert->timer = (alert->timer > AVX_LOG_SENDMAIL_TIME) ?
+                                (alert->timer - AVX_LOG_SENDMAIL_TIME) : 0;
+                        }
+                }
+        }
+
+        /*clear all the backup mbox space, they are sent out*/
+        bzero(&mbox_buf->mboxes[0], sizeof(log_mbox_t));
+        bzero(&mbox_buf->mboxes[AVX_LOG_MAX_ALERT_NUM + 1],
+                (AVX_LOG_MAX_MBOX_NUM - AVX_LOG_MAX_ALERT_NUM) * sizeof(log_mbox_t));
+
+        return 0;
+}
+
+char *log_write_alert(int id)
+{
+        int i;
+        unsigned int buf_size;
+        char* buff;
+        char* write_pos;
+        log_alert_buffer_t* abuf = log_alert_attach();
+        if (abuf == NULL) {
+                printf("Can't get log config.\n");
+                return NULL;
+        }
+        log_mbox_buffer_t * mbox_buf=mbox_attach();
+        if(mbox_buf==NULL) {
+              printf("Can't get mbox");
+             return NULL;
+        }
+
+         log_alert_t *alert;
+
+        /*check id*/
+        if ( (id < 0) || (id > AVX_LOG_MAX_ALERT_NUM) )
+            return NULL;
+
+
+        /*allocate buffer*/
+        buf_size = AVX_LOG_MAX_LINE_SIZE * AVX_LOG_MAX_ALERT_NUM + 1;
+        buff = (char *)calloc(buf_size, 1);
+        if (!buff)
+                return NULL;
+
+        write_pos = buff;
+        if (!id) {
+
+                /*write all the alert logs*/
+                                for (i = 1; i <= AVX_LOG_MAX_ALERT_NUM; i++) {
+
+                        alert = &abuf->alerts[i];
+                        if (alert->flags & AVX_LOG_ALERT_INUSE) {
+
+                                write_pos += snprintf(write_pos, (buff - write_pos + buf_size),
+                                                     "log alert %d \"%s\" \"%s\" %d \"%s\"\n",
+                                                     i, alert->match, alert->email, alert->interval / 60,
+                                                     (alert->flags & AVX_LOG_ALERT_COUNT) ? "count" : "data");
+                        }
+                }
+        }
+        else {
+                /*only print the specified alert log*/
+                alert = &abuf->alerts[id];
+                if (alert->flags & AVX_LOG_ALERT_INUSE) {
+
+                        snprintf(buff, buf_size, "log alert %d \"%s\" \"%s\" %d \"%s\"\n",
+                                 id, alert->match, alert->email, alert->interval / 60,
+                                 (alert->flags & AVX_LOG_ALERT_COUNT) ? "count" : "data");
+                }
+        }
+
+        return buff;
+}
+
+int log_show_alert(int id)
+{
+        char *buf_alert;
+
+        if ( (id < 0) || (id > AVX_LOG_MAX_ALERT_NUM) ) {
+
+                printf("Alert log ID must be in the range of 0..%u.\n"
+                       "0 means show all the alert logs\n", AVX_LOG_MAX_ALERT_NUM);
+                return -1;
+        }
+
+        buf_alert = log_write_alert(id);
+        if (buf_alert) {
+                printf("%s\n", buf_alert);
+                free(buf_alert);
+        }
+
+        return 0;
+}
+
+static int log_alert_regex_valid(char *regex, char *reason, int32_t max_reason_len)
+{
+        int i, len, num_non_meta = 0;
+
+        len = strlen(regex);
+        for (i = 0; i < len; i++) {
+
+                if (regex[i] == '^') {
+                        /* Caret is only allowed at the beginning */
+                        if (i != 0) {
+                                if (reason != NULL) {
+                                        snprintf(reason, max_reason_len, "Invalid regular "
+                                                        "expression: caret (^) is only allowed at "
+                                                        "the beginning of the expression\n");
+                                }
+                                return 0;
+                        }
+                } else if(regex[i] == '$') {
+                        /* Dollar is only allowed at the end */
+                        if(i != len-1) {
+                                if (reason != NULL) {
+                                        snprintf(reason, max_reason_len, "Invalid regular "
+                                                        "expression: dollar ($) is only allowed at "
+                                                        "the end of the expression\n");
+                                }
+                                return 0;
+                        }
+                } else if(regex[i] == '*') {
+                        /* Consecutive meta characters are not allowed */
+                        if(i != 0 && i != len-1 &&
+                                (regex[i-1] == '*' || regex[i+1] == '*' ||
+                                 regex[i-1] == '^' || regex[i+1] == '^' ||
+                                 regex[i-1] == '$' || regex[i+1] == '$'))
+                        {
+                                if (reason != NULL) {
+                                        snprintf(reason, max_reason_len, "Invalid regular "
+                                                        "expression: consecutive meta characters are "
+                                                        "not allowed\n");
+                                }
+                                return 0;
+                        }
+                } else if(regex[i] != '*') {
+                        num_non_meta++;
+                }
+        }
+
+        if (num_non_meta == 0) {
+                /*
+                 * At least one non-meta character is required. Note that this
+                 * catches the "^$" case.
+                 */
+        if (reason != NULL) {
+                        snprintf(reason, max_reason_len, "Invalid regular expression: "
+                                        "must contain at least one non-meta character\n");
+                }
+                return 0;
+        }
+
+        return 1;
+}
+
+int
 avxlog_off(void)
 {
         avxlog_cfg_t * cfg_p;
@@ -243,6 +807,10 @@
         return 0;
 }
 
+int32_t log_node_cmp(void *nodea, void *nodeb)
+{
+        return 1;
+}
 
 int
 avx_log(enum avxlog_idx idx, int argn, ...)
@@ -260,6 +828,7 @@
 	int level;
 	char log_flag[MAXPATHLEN] = {0};
 	char logstr[4096];
+        
 
 	if (idx >= LOG_IDX_MAX) {
 		return 1;
@@ -339,7 +908,6 @@
 
 	/* settimezone(); */
 	fprintf(fp, "%-7s %-20s ", level_str, timestamp_str);
-
 	va_start(ap, argn);
 	vsnprintf(logstr, 4096, avxlog_table[idx].log_fmt, ap);
 	fprintf(fp, logstr);
@@ -358,12 +926,118 @@
 	vsyslog(level, avxlog_table[idx].log_fmt, va);
 	closelog();
 	va_end(va);
-
+	log_alert_check(logstr);
 	snmp_send_syslog_trap(avxlog_table[idx].level, logstr);
-	
 	return 0;
 }
 
+int log_alert_check(char *msg)
+{
+        log_alert_t *alert;
+        regex_node_t *regex_node = NULL;
+        struct regex_result_list *result_list = NULL;
+        int id;
+        log_alert_buffer_t *alert_buf = log_alert_attach();
+        if (!msg)
+                return -1; /*invalid log message*/
+        if (!regex_tree) /*regex tree null*/
+                return -1;
+	if(alert_buf == NULL) {
+	        printf("Could not attach alert buf");
+		return -1;
+	}
+
+        /*do the regex match*/
+        result_list = regex_match(regex_tree, msg, strlen(msg), log_node_cmp, NULL, NULL);
+        if(!SLIST_EMPTY(result_list)) {
+                SLIST_FOREACH(regex_node, result_list, next_match) {
+                                /*get the alert buf id*/
+                                id = *((int *)(regex_node->data));
+                                alert = &alert_buf->alerts[id];
+                                if (alert->flags & AVX_LOG_ALERT_INUSE) {
+                                        if (alert->flags & AVX_LOG_ALERT_COUNT)
+                                                alert->count++;
+                                        else
+                                                log_alert_put(msg, id);
+                                }
+                        
+                }
+        }
+
+        return 0;
+}
+
+static int log_alert_put(char *msg, int id)
+{
+        int i;
+        log_mbox_t *mbox;
+        log_alert_t *alert;
+        log_mbox_buffer_t* mbox_buf = mbox_attach();
+        if(mbox_buf  == NULL) {
+                printf("Can't get mbox buffer.\n");
+                return -1;
+        }
+	log_alert_buffer_t* alert_buf = log_alert_attach();
+        if (alert_buf == NULL) {
+                printf("Can't get log config.\n");
+                return -1;
+        }
+        if ((!msg) || (id < 1) || (id > AVX_LOG_MAX_ALERT_NUM))
+                return -1;
+
+        /*check the data space enough or not, first check the dedicated buffer*/
+        mbox = &mbox_buf->mboxes[id];
+        alert = &alert_buf->alerts[id];
+        if ((strlen(msg) + mbox->len + 2) <= sizeof(mbox->data)) {
+                /* use snprintf instead of sprintf to avoid buf overun */
+                mbox->len += snprintf(mbox->data + mbox->len, sizeof(mbox->data) - mbox->len, "%s\n", msg);
+        }
+        else {
+
+                /*dedicated buffer is full, need to set timer to be 0 for sendmail*/
+                /*and find the extra buffer*/
+                alert->timer = 0;  /*need to send the message*/
+                for (i = AVX_LOG_MAX_ALERT_NUM + 1; i <= AVX_LOG_MAX_MBOX_NUM; i++) {
+
+                        mbox = &mbox_buf->mboxes[i];
+                        if (mbox->id <= 0) {
+
+                                /*if we can find a empty mbox, that means the current*/
+                                /*alert log has no other extra buffer after this point*/
+                                /*since: 1. the smaller box gets used early; */
+                                /*       2. all the extra boxes will be sent out soon*/
+                                mbox->id = id; /*reserver the mail box*/
+                                mbox->len = 0;
+                                break;
+                        }
+
+                        if ((mbox->id == id) &&
+                                ((strlen(msg) + mbox->len + 2) <= sizeof(mbox->data)))
+                                break;
+                }
+
+                if (i > AVX_LOG_MAX_MBOX_NUM) {
+
+                        /*lose the message since can not find extra space!*/
+                        /*do nothing for now*/
+                }
+                else {
+
+                        /* use snprintf instead of sprintf to avoid buf overun */
+                        mbox->len += snprintf(mbox->data + mbox->len, sizeof(mbox->data) - mbox->len, "%s\n", msg);
+                        /*find a usable mbox*/
+                        /*save into dedicated buffer, add a newline and change length*/
+                        #if 0
+                        mbox->len += sprintf(mbox->data + mbox->len, "%s\n", msg);
+                        #endif
+                }
+        }
+
+        return 0;
+}
+
+                                        
+
 int avxlog_set_facility(char *facility){
     int numfac = 0;
     avxlog_cfg_t * cfg_p;
@@ -734,6 +1408,7 @@
 {
     size_t offset;
     avxlog_cfg_t * cfg_p;
+    char* buf_alert;
     int i;
 
     if (buf == NULL || len == 0) {
@@ -817,6 +1492,15 @@
             }
         }
     }
+    
+    buf_alert = log_write_alert(0);
+    if (buf_alert) {
+        offset += snprintf(buf + offset,
+                             len - offset,
+                             "%s", buf_alert);
+        free(buf_alert);
+    }
+
 
     return offset;
 }
@@ -999,4 +1683,4 @@
         return -1;
     }
     return 0;
-}
\ No newline at end of file
+}
Index: /branches/rel_avx_2_7_4/src/library/avxresource/Makefile
===================================================================
--- /branches/rel_avx_2_7_4/src/library/avxresource/Makefile	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/library/avxresource/Makefile	(working copy)
@@ -7,6 +7,7 @@
     -L${TOP}/src/library/node_man/ -I${TOP}/src/library/node_man/ -lnode \
     -L${TOP}/src/library/ca_ui/ -I${TOP}/src/library/ca_ui/ -lcaui \
     -L${TOP}/src/library/avx_log/ -I${TOP}/src/library/avx_log/ -lavxlog \
+    -L${TOP}/src/library/ca_regex/ -I${TOP}/src/library/ca_regex/ -lcaregex \
     -L${TOP}/src/library/avxresource/ -I${TOP}/src/library/avxresource/ -lavxresource \
     -L${TOP}/lib/avxpci/ -I${TOP}/lib/avxpci/ -lavxpci \
     -L${TOP}/src/library/avxvainst/ -I${TOP}/src/library/avxvainst/ -lavxvainst \
@@ -20,6 +21,8 @@
     -I/usr/include/libvirt/ -I/usr/include/libxml2/ -lxmlrpc_util -lxmlrpc -lxmlrpc_client -lxml2 \
     -L${TOP}/kern/CNN55XX-SDK/api/ -lnitrox-1.3-01 -lutil \
     -lpthread -lcurl -lresolv -lpcre -ljson-c \
+    -L${TOP}/lib/libopenssl-1.1.1/  -lcrypto-tls13 -lssl-tls13 \
+    -lssl -lcrypto \
     -L${TOP}/src/library/ca_util/ -I${TOP}/src/library/ca_util/ -lcautil \
     -L${TOP}/src/library/version/ -I${TOP}/src/library/version/ -lversion 
 
Index: /branches/rel_avx_2_7_4/src/library/avxvainst/Makefile
===================================================================
--- /branches/rel_avx_2_7_4/src/library/avxvainst/Makefile	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/library/avxvainst/Makefile	(working copy)
@@ -69,7 +69,7 @@
 	$(CC) $(DEBUG) $(FLAGS) $(INCLUDE) -c testmain.c
 
 testmain: testmain.o
-	$(CC) $(DEBUG) $(FLAGS) $(INCLUDE) -lmsgpack -lvirt -lxmlrpc_util -lxmlrpc -lxmlrpc_client -lxml2 -lutil avx_dpdk.o va_utils.o va_xmlrpc.o va_info.o va_error.o va_resource.o va_console.o va_config.o libvirt_connection.o va_log.o avx_macpool.o va_instance.o testmain.o avx_host.o avx_host_list.o avx_host_config.o -o testmain -L ../ca_ui -lcaui -L ../avx_log -lavxlog -L ../node_man -lnode -L ../management -lsuppress_print  -L../../../lib/avxmodel -lavxmodel -L../../../lib/avxpci/ -lavxpci -L../avxnet -lavxnet -L../../../lib/vtch/ -lvtch -L../../../lib/feactl/ -lfeactl -L ../ca_util -lcautil -L../../../lib/casnmp -lcasnmp -L../version -lversion -L../avxha -lavxha -L../avxssl -lavxssl -lresolv -L$(TOP)/kern/CNN55XX-SDK/api/ -lnitrox-1.3-01
+	$(CC) $(DEBUG) $(FLAGS) $(INCLUDE) -lmsgpack -lvirt -lxmlrpc_util -lxmlrpc -lxmlrpc_client -lxml2 -lutil avx_dpdk.o va_utils.o va_xmlrpc.o va_info.o va_error.o va_resource.o va_console.o va_config.o libvirt_connection.o va_log.o avx_macpool.o va_instance.o testmain.o avx_host.o avx_host_list.o avx_host_config.o -o testmain -L ../ca_ui -lcaui -L ../avx_log -lavxlog -L ../ca_regex -lcaregex -L ../node_man -lnode -L ../management -lsuppress_print  -L../../../lib/avxmodel -lavxmodel -L../../../lib/avxpci/ -lavxpci -L../avxnet -lavxnet -L../../../lib/vtch/ -lvtch -L../../../lib/feactl/ -lfeactl -lcrypto -lssl -L../../../lib/libopenssl-1.1.1  -lcrypto-tls13 -lssl-tls13 -L ../ca_util -lcautil -L../../../lib/casnmp -lcasnmp -L../version -lversion -L../avxha -lavxha -L../avxssl -lavxssl -lresolv -L$(TOP)/kern/CNN55XX-SDK/api/ -lnitrox-1.3-01
 
 clean:
 	/bin/rm -f *.o *.core core.* *.out *.a testmain avx_host
Index: /branches/rel_avx_2_7_4/src/library/ca_mail/Makefile
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_mail/Makefile	(revision 0)
+++ /branches/rel_avx_2_7_4/src/library/ca_mail/Makefile	(working copy)
@@ -0,0 +1,36 @@
+# ArrayOS
+
+TOP = ../../..
+
+include ${TOP}/Makefile.master
+
+LIB=	ca_mail
+SRCS=   sys_mail.c
+INCS=	sys_mail.h
+
+FILES=  sendmail.cf
+FILESDIR=/ca/etc
+
+CC = gcc
+AR = ar
+RM = rm 
+
+CFLAGS+= -I${TOP}/src/library/management/ \
+	 -I${TOP}/src/library/ca_util \
+	 -I${TOP}/lib/libopenssl-1.1.1 \
+	 -I${TOP}/lib/libopenssl-1.1.1/include \
+	 -I${TOP}/src/library/node_man \
+	 -L/lib64 -L/usr/lib64
+
+LINK = -lnode -lsuppressprint -lcrypto -lssl -ldl
+
+all: sys_mail.o libcamail.a
+
+ca_mail.o: sys_mail.c sys_mail.h
+	$(CC) $(CFLAGS) -c sys_mail.c $(LINK)
+
+libcamail.a:
+	$(AR) rs libcamail.a sys_mail.o
+
+clean:
+	$(RM) -f *.o *.core *.out *.a
Index: /branches/rel_avx_2_7_4/src/library/ca_mail/sendmail.cf
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_mail/sendmail.cf	(revision 0)
+++ /branches/rel_avx_2_7_4/src/library/ca_mail/sendmail.cf	(working copy)
@@ -0,0 +1,1843 @@
+#
+# Copyright (c) 1998-2004, 2009, 2010 Sendmail, Inc. and its suppliers.
+#	All rights reserved.
+# Copyright (c) 1983, 1995 Eric P. Allman.  All rights reserved.
+# Copyright (c) 1988, 1993
+#	The Regents of the University of California.  All rights reserved.
+#
+# By using this file, you agree to the terms and conditions set
+# forth in the LICENSE file which can be found at the top level of
+# the sendmail distribution.
+#
+#
+
+######################################################################
+######################################################################
+#####
+#####		SENDMAIL CONFIGURATION FILE
+#####
+######################################################################
+#####
+#####	DO NOT EDIT THIS FILE!  Only edit the source .mc file.
+#####
+######################################################################
+######################################################################
+
+#####  $Id: cfhead.m4,v 8.121 2010/01/07 18:20:19 ca Exp $  #####
+#####  $Id: cf.m4,v 8.32 1999/02/07 07:26:14 gshapiro Exp $  #####
+#####  setup for linux  #####
+#####  $Id: linux.m4,v 8.13 2000/09/17 17:30:00 gshapiro Exp $  #####
+
+
+
+#####  $Id: local_procmail.m4,v 8.22 2002/11/17 04:24:19 ca Exp $  #####
+
+
+#####  $Id: no_default_msa.m4,v 8.2 2001/02/14 05:03:22 gshapiro Exp $  #####
+
+#####  $Id: smrsh.m4,v 8.14 1999/11/18 05:06:23 ca Exp $  #####
+
+#####  $Id: mailertable.m4,v 8.25 2002/06/27 23:23:57 gshapiro Exp $  #####
+
+#####  $Id: virtusertable.m4,v 8.23 2002/06/27 23:23:57 gshapiro Exp $  #####
+
+#####  $Id: redirect.m4,v 8.15 1999/08/06 01:47:36 gshapiro Exp $  #####
+
+#####  $Id: always_add_domain.m4,v 8.11 2000/09/12 22:00:53 ca Exp $  #####
+
+#####  $Id: use_cw_file.m4,v 8.11 2001/08/26 20:58:57 gshapiro Exp $  #####
+
+
+#####  $Id: use_ct_file.m4,v 8.11 2001/08/26 20:58:57 gshapiro Exp $  #####
+
+
+#####  $Id: local_procmail.m4,v 8.22 2002/11/17 04:24:19 ca Exp $  #####
+
+#####  $Id: access_db.m4,v 8.27 2006/07/06 21:10:10 ca Exp $  #####
+
+#####  $Id: blacklist_recipients.m4,v 8.13 1999/04/02 02:25:13 gshapiro Exp $  #####
+
+#####  $Id: accept_unresolvable_domains.m4,v 8.10 1999/02/07 07:26:07 gshapiro Exp $  #####
+
+
+#####  $Id: proto.m4,v 8.760 2012/09/07 16:30:15 ca Exp $  #####
+
+# level 10 config file format
+V10/Berkeley
+
+# override file safeties - setting this option compromises system security,
+# addressing the actual file configuration problem is preferred
+# need to set this before any file actions are encountered in the cf file
+#O DontBlameSendmail=safe
+
+# default LDAP map specification
+# need to set this now before any LDAP maps are defined
+#O LDAPDefaultSpec=-h localhost
+
+##################
+#   local info   #
+##################
+
+# my LDAP cluster
+# need to set this before any LDAP lookups are done (including classes)
+#D{sendmailMTACluster}$m
+
+Cwlocalhost
+# file containing names of hosts for which we receive email
+Fw/etc/mail/local-host-names
+
+# my official domain name
+# ... define this only if sendmail cannot automatically determine your domain
+#Dj$w.Foo.COM
+Dj $w.alert_pseudo_domain
+
+# host/domain names ending with a token in class P are canonical
+CP.
+
+# "Smart" relay host (may be null)
+DS
+
+
+# operators that cannot be in local usernames (i.e., network indicators)
+CO @ % !
+
+# a class with just dot (for identifying canonical names)
+C..
+
+# a class with just a left bracket (for identifying domain literals)
+C[[
+
+# access_db acceptance class
+C{Accept}OK RELAY
+
+
+C{ResOk}OKR
+
+
+# Hosts for which relaying is permitted ($=R)
+FR-o /etc/mail/relay-domains
+
+# arithmetic map
+Karith arith
+# macro storage map
+Kmacro macro
+# possible values for TLS_connection in access map
+C{Tls}VERIFY ENCR
+
+
+
+
+
+# dequoting map
+Kdequote dequote
+
+# class E: names that should be exposed as from this host, even if we masquerade
+# class L: names that should be delivered locally, even if we have a relay
+# class M: domains that should be converted to $M
+# class N: domains that should not be converted to $M
+#CL root
+C{E}root
+C{w}localhost.localdomain
+
+
+
+# my name for error messages
+DnMAILER-DAEMON
+
+
+# Mailer table (overriding domains)
+Kmailertable hash -o /etc/mail/mailertable.db
+
+# Virtual user table (maps incoming users)
+Kvirtuser hash -o /etc/mail/virtusertable.db
+
+CPREDIRECT
+
+# Access list database (for spam stomping)
+Kaccess hash -T<TMPF> -o /etc/mail/access.db
+
+# Configuration version number
+DZ8.14.7
+
+
+###############
+#   Options   #
+###############
+
+# strip message body to 7 bits on input?
+O SevenBitInput=False
+
+# 8-bit data handling
+#O EightBitMode=pass8
+
+# DSCP marking of traffic (IP_TOS)
+#O InetQoS=none
+
+# wait for alias file rebuild (default units: minutes)
+O AliasWait=10
+
+# location of alias file
+O AliasFile=/etc/aliases
+
+# minimum number of free blocks on filesystem
+O MinFreeBlocks=100
+
+# maximum message size
+#O MaxMessageSize=0
+
+# substitution for space (blank) characters
+O BlankSub=.
+
+# avoid connecting to "expensive" mailers on initial submission?
+O HoldExpensive=False
+
+# checkpoint queue runs after every N successful deliveries
+#O CheckpointInterval=10
+
+# default delivery mode
+O DeliveryMode=background
+
+# error message header/file
+#O ErrorHeader=/etc/mail/error-header
+
+# error mode
+#O ErrorMode=print
+
+# save Unix-style "From_" lines at top of header?
+#O SaveFromLine=False
+
+# queue file mode (qf files)
+#O QueueFileMode=0600
+
+# temporary file mode
+O TempFileMode=0600
+
+# match recipients against GECOS field?
+#O MatchGECOS=False
+
+# maximum hop count
+#O MaxHopCount=25
+
+# location of help file
+O HelpFile=/etc/mail/helpfile
+
+# ignore dots as terminators in incoming messages?
+#O IgnoreDots=False
+
+# name resolver options
+#O ResolverOptions=+AAONLY
+
+# deliver MIME-encapsulated error messages?
+O SendMimeErrors=True
+
+# Forward file search path
+O ForwardPath=$z/.forward.$w:$z/.forward
+
+# open connection cache size
+O ConnectionCacheSize=2
+
+# open connection cache timeout
+O ConnectionCacheTimeout=5m
+
+# persistent host status directory
+#O HostStatusDirectory=.hoststat
+
+# single thread deliveries (requires HostStatusDirectory)?
+#O SingleThreadDelivery=False
+
+# use Errors-To: header?
+O UseErrorsTo=False
+
+# log level
+O LogLevel=9
+
+# send to me too, even in an alias expansion?
+#O MeToo=True
+
+# verify RHS in newaliases?
+O CheckAliases=False
+
+# default messages to old style headers if no special punctuation?
+O OldStyleHeaders=True
+
+# SMTP daemon options
+
+O DaemonPortOptions=Port=smtp,Addr=127.0.0.1, Name=MTA
+
+# SMTP client options
+#O ClientPortOptions=Family=inet, Address=0.0.0.0
+
+# Modifiers to define {daemon_flags} for direct submissions
+#O DirectSubmissionModifiers
+
+# Use as mail submission program? See sendmail/SECURITY
+#O UseMSP
+
+# privacy flags
+O PrivacyOptions=authwarnings,novrfy,noexpn,restrictqrun
+
+# who (if anyone) should get extra copies of error messages
+#O PostmasterCopy=Postmaster
+
+# slope of queue-only function
+#O QueueFactor=600000
+
+# limit on number of concurrent queue runners
+#O MaxQueueChildren
+
+# maximum number of queue-runners per queue-grouping with multiple queues
+#O MaxRunnersPerQueue=1
+
+# priority of queue runners (nice(3))
+#O NiceQueueRun
+
+# shall we sort the queue by hostname first?
+#O QueueSortOrder=priority
+
+# minimum time in queue before retry
+#O MinQueueAge=30m
+
+# how many jobs can you process in the queue?
+#O MaxQueueRunSize=0
+
+# perform initial split of envelope without checking MX records
+#O FastSplit=1
+
+# queue directory
+O QueueDirectory=/var/spool/mqueue
+
+# key for shared memory; 0 to turn off, -1 to auto-select
+#O SharedMemoryKey=0
+
+# file to store auto-selected key for shared memory (SharedMemoryKey = -1)
+#O SharedMemoryKeyFile
+
+# timeouts (many of these)
+#O Timeout.initial=5m
+O Timeout.connect=1m
+#O Timeout.aconnect=0s
+#O Timeout.iconnect=5m
+#O Timeout.helo=5m
+#O Timeout.mail=10m
+#O Timeout.rcpt=1h
+#O Timeout.datainit=5m
+#O Timeout.datablock=1h
+#O Timeout.datafinal=1h
+#O Timeout.rset=5m
+#O Timeout.quit=2m
+#O Timeout.misc=2m
+#O Timeout.command=1h
+O Timeout.ident=0
+#O Timeout.fileopen=60s
+#O Timeout.control=2m
+O Timeout.queuereturn=5d
+#O Timeout.queuereturn.normal=5d
+#O Timeout.queuereturn.urgent=2d
+#O Timeout.queuereturn.non-urgent=7d
+#O Timeout.queuereturn.dsn=5d
+O Timeout.queuewarn=4h
+#O Timeout.queuewarn.normal=4h
+#O Timeout.queuewarn.urgent=1h
+#O Timeout.queuewarn.non-urgent=12h
+#O Timeout.queuewarn.dsn=4h
+#O Timeout.hoststatus=30m
+#O Timeout.resolver.retrans=5s
+#O Timeout.resolver.retrans.first=5s
+#O Timeout.resolver.retrans.normal=5s
+#O Timeout.resolver.retry=4
+#O Timeout.resolver.retry.first=4
+#O Timeout.resolver.retry.normal=4
+#O Timeout.lhlo=2m
+#O Timeout.auth=10m
+#O Timeout.starttls=1h
+
+# time for DeliverBy; extension disabled if less than 0
+#O DeliverByMin=0
+
+# should we not prune routes in route-addr syntax addresses?
+#O DontPruneRoutes=False
+
+# queue up everything before forking?
+O SuperSafe=True
+
+# status file
+O StatusFile=/var/log/mail/statistics
+
+# time zone handling:
+#  if undefined, use system default
+#  if defined but null, use TZ envariable passed in
+#  if defined and non-null, use that info
+#O TimeZoneSpec=
+
+# default UID (can be username or userid:groupid)
+O DefaultUser=8:12
+
+# list of locations of user database file (null means no lookup)
+O UserDatabaseSpec=/etc/mail/userdb.db
+
+# fallback MX host
+#O FallbackMXhost=fall.back.host.net
+
+# fallback smart host
+#O FallbackSmartHost=fall.back.host.net
+
+# if we are the best MX host for a site, try it directly instead of config err
+O TryNullMXList=True
+
+# load average at which we just queue messages
+#O QueueLA=8
+
+# load average at which we refuse connections
+#O RefuseLA=12
+
+# log interval when refusing connections for this long
+#O RejectLogInterval=3h
+
+# load average at which we delay connections; 0 means no limit
+#O DelayLA=0
+
+# maximum number of children we allow at one time
+#O MaxDaemonChildren=0
+
+# maximum number of new connections per second
+#O ConnectionRateThrottle=0
+
+# Width of the window 
+#O ConnectionRateWindowSize=60s
+
+# work recipient factor
+#O RecipientFactor=30000
+
+# deliver each queued job in a separate process?
+#O ForkEachJob=False
+
+# work class factor
+#O ClassFactor=1800
+
+# work time factor
+#O RetryFactor=90000
+
+# default character set
+#O DefaultCharSet=unknown-8bit
+
+# service switch file (name hardwired on Solaris, Ultrix, OSF/1, others)
+#O ServiceSwitchFile=/etc/mail/service.switch
+
+# hosts file (normally /etc/hosts)
+#O HostsFile=/etc/hosts
+
+# dialup line delay on connection failure
+#O DialDelay=0s
+
+# action to take if there are no recipients in the message
+#O NoRecipientAction=none
+
+# chrooted environment for writing to files
+#O SafeFileEnvironment
+
+# are colons OK in addresses?
+#O ColonOkInAddr=True
+
+# shall I avoid expanding CNAMEs (violates protocols)?
+#O DontExpandCnames=False
+
+# SMTP initial login message (old $e macro)
+O SmtpGreetingMessage=$j Sendmail $v/$Z; $b
+
+# UNIX initial From header format (old $l macro)
+O UnixFromLine=From $g $d
+
+# From: lines that have embedded newlines are unwrapped onto one line
+#O SingleLineFromHeader=False
+
+# Allow HELO SMTP command that does not include a host name
+#O AllowBogusHELO=False
+
+# Characters to be quoted in a full name phrase (@,;:\()[] are automatic)
+#O MustQuoteChars=.
+
+# delimiter (operator) characters (old $o macro)
+O OperatorChars=.:%@!^/[]+
+
+# shall I avoid calling initgroups(3) because of high NIS costs?
+#O DontInitGroups=False
+
+# are group-writable :include: and .forward files (un)trustworthy?
+# True (the default) means they are not trustworthy.
+#O UnsafeGroupWrites=True
+
+
+# where do errors that occur when sending errors get sent?
+#O DoubleBounceAddress=postmaster
+
+# issue temporary errors (4xy) instead of permanent errors (5xy)?
+#O SoftBounce=False
+
+# where to save bounces if all else fails
+#O DeadLetterDrop=/var/tmp/dead.letter
+
+# what user id do we assume for the majority of the processing?
+#O RunAsUser=sendmail
+
+# maximum number of recipients per SMTP envelope
+#O MaxRecipientsPerMessage=0
+
+# limit the rate recipients per SMTP envelope are accepted
+# once the threshold number of recipients have been rejected
+#O BadRcptThrottle=0
+
+
+# shall we get local names from our installed interfaces?
+O DontProbeInterfaces=True
+
+# Return-Receipt-To: header implies DSN request
+#O RrtImpliesDsn=False
+
+# override connection address (for testing)
+#O ConnectOnlyTo=0.0.0.0
+
+# Trusted user for file ownership and starting the daemon
+#O TrustedUser=root
+
+# Control socket for daemon management
+#O ControlSocketName=/var/spool/mqueue/.control
+
+# Maximum MIME header length to protect MUAs
+#O MaxMimeHeaderLength=0/0
+
+# Maximum length of the sum of all headers
+#O MaxHeadersLength=32768
+
+# Maximum depth of alias recursion
+#O MaxAliasRecursion=10
+
+# location of pid file
+#O PidFile=/var/run/sendmail.pid
+
+# Prefix string for the process title shown on 'ps' listings
+#O ProcessTitlePrefix=prefix
+
+# Data file (df) memory-buffer file maximum size
+#O DataFileBufferSize=4096
+
+# Transcript file (xf) memory-buffer file maximum size
+#O XscriptFileBufferSize=4096
+
+# lookup type to find information about local mailboxes
+#O MailboxDatabase=pw
+
+# override compile time flag REQUIRES_DIR_FSYNC
+#O RequiresDirfsync=true
+
+# list of authentication mechanisms
+#O AuthMechanisms=EXTERNAL GSSAPI KERBEROS_V4 DIGEST-MD5 CRAM-MD5
+
+# Authentication realm
+#O AuthRealm
+
+# default authentication information for outgoing connections
+#O DefaultAuthInfo=/etc/mail/default-auth-info
+
+# SMTP AUTH flags
+O AuthOptions=A
+
+# SMTP AUTH maximum encryption strength
+#O AuthMaxBits
+
+# SMTP STARTTLS server options
+#O TLSSrvOptions
+
+
+# Input mail filters
+#O InputMailFilters
+
+
+# CA directory
+#O CACertPath
+# CA file
+#O CACertFile
+# Server Cert
+#O ServerCertFile
+# Server private key
+#O ServerKeyFile
+# Client Cert
+#O ClientCertFile
+# Client private key
+#O ClientKeyFile
+# File containing certificate revocation lists 
+#O CRLFile
+# DHParameters (only required if DSA/DH is used)
+#O DHParameters
+# Random data source (required for systems without /dev/urandom under OpenSSL)
+#O RandFile
+
+# Maximum number of "useless" commands before slowing down
+#O MaxNOOPCommands=20
+
+# Name to use for EHLO (defaults to $j)
+#O HeloName
+
+############################
+# QUEUE GROUP DEFINITIONS  #
+############################
+
+
+###########################
+#   Message precedences   #
+###########################
+
+Pfirst-class=0
+Pspecial-delivery=100
+Plist=-30
+Pbulk=-60
+Pjunk=-100
+
+#####################
+#   Trusted users   #
+#####################
+
+# this is equivalent to setting class "t"
+Ft/etc/mail/trusted-users
+Troot
+Tdaemon
+Tuucp
+
+#########################
+#   Format of headers   #
+#########################
+
+H?P?Return-Path: <$g>
+HReceived: $?sfrom $s $.$?_($?s$|from $.$_)
+	$.$?{auth_type}(authenticated$?{auth_ssf} bits=${auth_ssf}$.)
+	$.by $j ($v/$Z)$?r with $r$. id $i$?{tls_version}
+	(version=${tls_version} cipher=${cipher} bits=${cipher_bits} verify=${verify})$.$?u
+	for $u; $|;
+	$.$b
+H?D?Resent-Date: $a
+H?D?Date: $a
+H?F?Resent-From: $?x$x <$g>$|$g$.
+H?F?From: $?x$x <$g>$|$g$.
+H?x?Full-Name: $x
+# HPosted-Date: $a
+# H?l?Received-Date: $b
+H?M?Resent-Message-Id: <$t.$i@$j>
+H?M?Message-Id: <$t.$i@$j>
+
+#
+######################################################################
+######################################################################
+#####
+#####			REWRITING RULES
+#####
+######################################################################
+######################################################################
+
+############################################
+###  Ruleset 3 -- Name Canonicalization  ###
+############################################
+Scanonify=3
+
+# handle null input (translate to <@> special case)
+R$@			$@ <@>
+
+# strip group: syntax (not inside angle brackets!) and trailing semicolon
+R$*			$: $1 <@>			mark addresses
+R$* < $* > $* <@>	$: $1 < $2 > $3			unmark <addr>
+R@ $* <@>		$: @ $1				unmark @host:...
+R$* [ IPv6 : $+ ] <@>	$: $1 [ IPv6 : $2 ]		unmark IPv6 addr
+R$* :: $* <@>		$: $1 :: $2			unmark node::addr
+R:include: $* <@>	$: :include: $1			unmark :include:...
+R$* : $* [ $* ]		$: $1 : $2 [ $3 ] <@>		remark if leading colon
+R$* : $* <@>		$: $2				strip colon if marked
+R$* <@>			$: $1				unmark
+R$* ;			   $1				strip trailing semi
+R$* < $+ :; > $*	$@ $2 :; <@>			catch <list:;>
+R$* < $* ; >		   $1 < $2 >			bogus bracketed semi
+
+# null input now results from list:; syntax
+R$@			$@ :; <@>
+
+# strip angle brackets -- note RFC733 heuristic to get innermost item
+R$*			$: < $1 >			housekeeping <>
+R$+ < $* >		   < $2 >			strip excess on left
+R< $* > $+		   < $1 >			strip excess on right
+R<>			$@ < @ >			MAIL FROM:<> case
+R< $+ >			$: $1				remove housekeeping <>
+
+# strip route address <@a,@b,@c:user@d> -> <user@d>
+R@ $+ , $+		$2
+R@ [ $* ] : $+		$2
+R@ $+ : $+		$2
+
+# find focus for list syntax
+R $+ : $* ; @ $+	$@ $>Canonify2 $1 : $2 ; < @ $3 >	list syntax
+R $+ : $* ;		$@ $1 : $2;			list syntax
+
+# find focus for @ syntax addresses
+R$+ @ $+		$: $1 < @ $2 >			focus on domain
+R$+ < $+ @ $+ >		$1 $2 < @ $3 >			move gaze right
+R$+ < @ $+ >		$@ $>Canonify2 $1 < @ $2 >	already canonical
+
+
+# convert old-style addresses to a domain-based address
+R$- ! $+		$@ $>Canonify2 $2 < @ $1 .UUCP >	resolve uucp names
+R$+ . $- ! $+		$@ $>Canonify2 $3 < @ $1 . $2 >		domain uucps
+R$+ ! $+		$@ $>Canonify2 $2 < @ $1 .UUCP >	uucp subdomains
+
+# if we have % signs, take the rightmost one
+R$* % $*		$1 @ $2				First make them all @s.
+R$* @ $* @ $*		$1 % $2 @ $3			Undo all but the last.
+R$* @ $*		$@ $>Canonify2 $1 < @ $2 >	Insert < > and finish
+
+# else we must be a local name
+R$*			$@ $>Canonify2 $1
+
+
+################################################
+###  Ruleset 96 -- bottom half of ruleset 3  ###
+################################################
+
+SCanonify2=96
+
+# handle special cases for local names
+R$* < @ localhost > $*		$: $1 < @ $j . > $2		no domain at all
+R$* < @ localhost . $m > $*	$: $1 < @ $j . > $2		local domain
+R$* < @ localhost . UUCP > $*	$: $1 < @ $j . > $2		.UUCP domain
+
+# check for IPv4/IPv6 domain literal
+R$* < @ [ $+ ] > $*		$: $1 < @@ [ $2 ] > $3		mark [addr]
+R$* < @@ $=w > $*		$: $1 < @ $j . > $3		self-literal
+R$* < @@ $+ > $*		$@ $1 < @ $2 > $3		canon IP addr
+
+
+
+
+
+# if really UUCP, handle it immediately
+
+# try UUCP traffic as a local address
+R$* < @ $+ . UUCP > $*		$: $1 < @ $[ $2 $] . UUCP . > $3
+R$* < @ $+ . . UUCP . > $*	$@ $1 < @ $2 . > $3
+
+# hostnames ending in class P are always canonical
+R$* < @ $* $=P > $*		$: $1 < @ $2 $3 . > $4
+R$* < @ $* $~P > $*		$: $&{daemon_flags} $| $1 < @ $2 $3 > $4
+R$* CC $* $| $* < @ $+.$+ > $*	$: $3 < @ $4.$5 . > $6
+R$* CC $* $| $*			$: $3
+# pass to name server to make hostname canonical
+R$* $| $* < @ $* > $*		$: $2 < @ $[ $3 $] > $4
+R$* $| $*			$: $2
+
+# local host aliases and pseudo-domains are always canonical
+R$* < @ $=w > $*		$: $1 < @ $2 . > $3
+R$* < @ $=M > $*		$: $1 < @ $2 . > $3
+R$* < @ $={VirtHost} > $* 	$: $1 < @ $2 . > $3
+R$* < @ $* . . > $*		$1 < @ $2 . > $3
+
+
+##################################################
+###  Ruleset 4 -- Final Output Post-rewriting  ###
+##################################################
+Sfinal=4
+
+R$+ :; <@>		$@ $1 :				handle <list:;>
+R$* <@>			$@				handle <> and list:;
+
+# strip trailing dot off possibly canonical name
+R$* < @ $+ . > $*	$1 < @ $2 > $3
+
+# eliminate internal code
+R$* < @ *LOCAL* > $*	$1 < @ $j > $2
+
+# externalize local domain info
+R$* < $+ > $*		$1 $2 $3			defocus
+R@ $+ : @ $+ : $+	@ $1 , @ $2 : $3		<route-addr> canonical
+R@ $*			$@ @ $1				... and exit
+
+# UUCP must always be presented in old form
+R$+ @ $- . UUCP		$2!$1				u@h.UUCP => h!u
+
+# delete duplicate local names
+R$+ % $=w @ $=w		$1 @ $2				u%host@host => u@host
+
+
+
+##############################################################
+###   Ruleset 97 -- recanonicalize and call ruleset zero   ###
+###		   (used for recursive calls)		   ###
+##############################################################
+
+SRecurse=97
+R$*			$: $>canonify $1
+R$*			$@ $>parse $1
+
+
+######################################
+###   Ruleset 0 -- Parse Address   ###
+######################################
+
+Sparse=0
+
+R$*			$: $>Parse0 $1		initial parsing
+R<@>			$#local $: <@>		special case error msgs
+R$*			$: $>ParseLocal $1	handle local hacks
+R$*			$: $>Parse1 $1		final parsing
+
+#
+#  Parse0 -- do initial syntax checking and eliminate local addresses.
+#	This should either return with the (possibly modified) input
+#	or return with a #error mailer.  It should not return with a
+#	#mailer other than the #error mailer.
+#
+
+SParse0
+R<@>			$@ <@>			special case error msgs
+R$* : $* ; <@>		$#error $@ 5.1.3 $: "553 List:; syntax illegal for recipient addresses"
+R@ <@ $* >		< @ $1 >		catch "@@host" bogosity
+R<@ $+>			$#error $@ 5.1.3 $: "553 User address required"
+R$+ <@>			$#error $@ 5.1.3 $: "553 Hostname required"
+R$*			$: <> $1
+R<> $* < @ [ $* ] : $+ > $*	$1 < @ [ $2 ] : $3 > $4
+R<> $* < @ [ $* ] , $+ > $*	$1 < @ [ $2 ] , $3 > $4
+R<> $* < @ [ $* ] $+ > $*	$#error $@ 5.1.2 $: "553 Invalid address"
+R<> $* < @ [ $+ ] > $*		$1 < @ [ $2 ] > $3
+R<> $* <$* : $* > $*	$#error $@ 5.1.3 $: "553 Colon illegal in host name part"
+R<> $*			$1
+R$* < @ . $* > $*	$#error $@ 5.1.2 $: "553 Invalid host name"
+R$* < @ $* .. $* > $*	$#error $@ 5.1.2 $: "553 Invalid host name"
+R$* < @ $* @ > $*	$#error $@ 5.1.2 $: "553 Invalid route address"
+R$* @ $* < @ $* > $*	$#error $@ 5.1.3 $: "553 Invalid route address"
+R$* , $~O $*		$#error $@ 5.1.3 $: "553 Invalid route address"
+
+
+# now delete the local info -- note $=O to find characters that cause forwarding
+R$* < @ > $*		$@ $>Parse0 $>canonify $1	user@ => user
+R< @ $=w . > : $*	$@ $>Parse0 $>canonify $2	@here:... -> ...
+R$- < @ $=w . >		$: $(dequote $1 $) < @ $2 . >	dequote "foo"@here
+R< @ $+ >		$#error $@ 5.1.3 $: "553 User address required"
+R$* $=O $* < @ $=w . >	$@ $>Parse0 $>canonify $1 $2 $3	...@here -> ...
+R$- 			$: $(dequote $1 $) < @ *LOCAL* >	dequote "foo"
+R< @ *LOCAL* >		$#error $@ 5.1.3 $: "553 User address required"
+R$* $=O $* < @ *LOCAL* >
+			$@ $>Parse0 $>canonify $1 $2 $3	...@*LOCAL* -> ...
+R$* < @ *LOCAL* >	$: $1
+
+#
+#  Parse1 -- the bottom half of ruleset 0.
+#
+
+SParse1
+
+# handle numeric address spec
+R$* < @ [ $+ ] > $*	$: $>ParseLocal $1 < @ [ $2 ] > $3	numeric internet spec
+R$* < @ [ $+ ] > $*	$: $1 < @ [ $2 ] : $S > $3	Add smart host to path
+R$* < @ [ $+ ] : > $*		$#esmtp $@ [$2] $: $1 < @ [$2] > $3	no smarthost: send
+R$* < @ [ $+ ] : $- : $*> $*	$#$3 $@ $4 $: $1 < @ [$2] > $5	smarthost with mailer
+R$* < @ [ $+ ] : $+ > $*	$#esmtp $@ $3 $: $1 < @ [$2] > $4	smarthost without mailer
+
+# handle virtual users
+R$+			$: <!> $1		Mark for lookup
+R<!> $+ < @ $={VirtHost} . > 	$: < $(virtuser $1 @ $2 $@ $1 $: @ $) > $1 < @ $2 . >
+R<!> $+ < @ $=w . > 	$: < $(virtuser $1 @ $2 $@ $1 $: @ $) > $1 < @ $2 . >
+R<@> $+ + $+ < @ $* . >
+			$: < $(virtuser $1 + + @ $3 $@ $1 $@ $2 $@ +$2 $: @ $) > $1 + $2 < @ $3 . >
+R<@> $+ + $* < @ $* . >
+			$: < $(virtuser $1 + * @ $3 $@ $1 $@ $2 $@ +$2 $: @ $) > $1 + $2 < @ $3 . >
+R<@> $+ + $* < @ $* . >
+			$: < $(virtuser $1 @ $3 $@ $1 $@ $2 $@ +$2 $: @ $) > $1 + $2 < @ $3 . >
+R<@> $+ + $+ < @ $+ . >	$: < $(virtuser + + @ $3 $@ $1 $@ $2 $@ +$2 $: @ $) > $1 + $2 < @ $3 . >
+R<@> $+ + $* < @ $+ . >	$: < $(virtuser + * @ $3 $@ $1 $@ $2 $@ +$2 $: @ $) > $1 + $2 < @ $3 . >
+R<@> $+ + $* < @ $+ . >	$: < $(virtuser @ $3 $@ $1 $@ $2 $@ +$2 $: ! $) > $1 + $2 < @ $3 . >
+R<@> $+ < @ $+ . >	$: < $(virtuser @ $2 $@ $1 $: @ $) > $1 < @ $2 . >
+R<@> $+			$: $1
+R<!> $+			$: $1
+R< error : $-.$-.$- : $+ > $* 	$#error $@ $1.$2.$3 $: $4
+R< error : $- $+ > $* 	$#error $@ $(dequote $1 $) $: $2
+R< $+ > $+ < @ $+ >	$: $>Recurse $1
+
+# short circuit local delivery so forwarded email works
+
+
+R$=L < @ $=w . >	$#local $: @ $1			special local names
+R$+ < @ $=w . >		$#local $: $1			regular local name
+
+# not local -- try mailer table lookup
+R$* <@ $+ > $*		$: < $2 > $1 < @ $2 > $3	extract host name
+R< $+ . > $*		$: < $1 > $2			strip trailing dot
+R< $+ > $*		$: < $(mailertable $1 $) > $2	lookup
+R< $~[ : $* > $* 	$>MailerToTriple < $1 : $2 > $3		check -- resolved?
+R< $+ > $*		$: $>Mailertable <$1> $2		try domain
+
+# resolve remotely connected UUCP links (if any)
+
+# resolve fake top level domains by forwarding to other hosts
+
+
+
+# pass names that still have a host to a smarthost (if defined)
+R$* < @ $* > $*		$: $>MailerToTriple < $S > $1 < @ $2 > $3	glue on smarthost name
+
+# deal with other remote names
+R$* < @$* > $*		$#esmtp $@ $2 $: $1 < @ $2 > $3	user@host.domain
+
+# handle locally delivered names
+R$=L			$#local $: @ $1		special local names
+R$+			$#local $: $1			regular local names
+
+###########################################################################
+###   Ruleset 5 -- special rewriting after aliases have been expanded   ###
+###########################################################################
+
+SLocal_localaddr
+Slocaladdr=5
+R$+			$: $1 $| $>"Local_localaddr" $1
+R$+ $| $#ok		$@ $1			no change
+R$+ $| $#$*		$#$2
+R$+ $| $*		$: $1
+
+
+
+
+# deal with plussed users so aliases work nicely
+R$+ + *			$#local $@ $&h $: $1
+R$+ + $*		$#local $@ + $2 $: $1 + *
+
+# prepend an empty "forward host" on the front
+R$+			$: <> $1
+
+
+
+R< > $+			$: < > < $1 <> $&h >		nope, restore +detail
+
+R< > < $+ <> + $* >	$: < > < $1 + $2 >		check whether +detail
+R< > < $+ <> $* >	$: < > < $1 >			else discard
+R< > < $+ + $* > $*	   < > < $1 > + $2 $3		find the user part
+R< > < $+ > + $*	$#local $@ $2 $: @ $1		strip the extra +
+R< > < $+ >		$@ $1				no +detail
+R$+			$: $1 <> $&h			add +detail back in
+
+R$+ <> + $*		$: $1 + $2			check whether +detail
+R$+ <> $*		$: $1				else discard
+R< local : $* > $*	$: $>MailerToTriple < local : $1 > $2	no host extension
+R< error : $* > $*	$: $>MailerToTriple < error : $1 > $2	no host extension
+
+R< $~[ : $+ > $+	$: $>MailerToTriple < $1 : $2 > $3 < @ $2 >
+
+R< $+ > $+		$@ $>MailerToTriple < $1 > $2 < @ $1 >
+
+
+###################################################################
+###  Ruleset 90 -- try domain part of mailertable entry 	###
+###################################################################
+
+SMailertable=90
+R$* <$- . $+ > $*	$: $1$2 < $(mailertable .$3 $@ $1$2 $@ $2 $) > $4
+R$* <$~[ : $* > $*	$>MailerToTriple < $2 : $3 > $4		check -- resolved?
+R$* < . $+ > $* 	$@ $>Mailertable $1 . <$2> $3		no -- strip & try again
+R$* < $* > $*		$: < $(mailertable . $@ $1$2 $) > $3	try "."
+R< $~[ : $* > $*	$>MailerToTriple < $1 : $2 > $3		"." found?
+R< $* > $*		$@ $2				no mailertable match
+
+###################################################################
+###  Ruleset 95 -- canonify mailer:[user@]host syntax to triple	###
+###################################################################
+
+SMailerToTriple=95
+R< > $*				$@ $1			strip off null relay
+R< error : $-.$-.$- : $+ > $* 	$#error $@ $1.$2.$3 $: $4
+R< error : $- : $+ > $*		$#error $@ $(dequote $1 $) $: $2
+R< error : $+ > $*		$#error $: $1
+R< local : $* > $*		$>CanonLocal < $1 > $2
+R< $~[ : $+ @ $+ > $*<$*>$*	$# $1 $@ $3 $: $2<@$3>	use literal user
+R< $~[ : $+ > $*		$# $1 $@ $2 $: $3	try qualified mailer
+R< $=w > $*			$@ $2			delete local host
+R< $+ > $*			$#relay $@ $1 $: $2	use unqualified mailer
+
+###################################################################
+###  Ruleset CanonLocal -- canonify local: syntax		###
+###################################################################
+
+SCanonLocal
+# strip local host from routed addresses
+R< $* > < @ $+ > : $+		$@ $>Recurse $3
+R< $* > $+ $=O $+ < @ $+ >	$@ $>Recurse $2 $3 $4
+
+# strip trailing dot from any host name that may appear
+R< $* > $* < @ $* . >		$: < $1 > $2 < @ $3 >
+
+# handle local: syntax -- use old user, either with or without host
+R< > $* < @ $* > $*		$#local $@ $1@$2 $: $1
+R< > $+				$#local $@ $1    $: $1
+
+# handle local:user@host syntax -- ignore host part
+R< $+ @ $+ > $* < @ $* >	$: < $1 > $3 < @ $4 >
+
+# handle local:user syntax
+R< $+ > $* <@ $* > $*		$#local $@ $2@$3 $: $1
+R< $+ > $* 			$#local $@ $2    $: $1
+
+###################################################################
+###  Ruleset 93 -- convert header names to masqueraded form	###
+###################################################################
+
+SMasqHdr=93
+
+
+# do not masquerade anything in class N
+R$* < @ $* $=N . >	$@ $1 < @ $2 $3 . >
+
+R$* < @ *LOCAL* >	$@ $1 < @ $j . >
+
+###################################################################
+###  Ruleset 94 -- convert envelope names to masqueraded form	###
+###################################################################
+
+SMasqEnv=94
+R$* < @ *LOCAL* > $*	$: $1 < @ $j . > $2
+
+###################################################################
+###  Ruleset 98 -- local part of ruleset zero (can be null)	###
+###################################################################
+
+SParseLocal=98
+
+# addresses sent to foo@host.REDIRECT will give a 551 error code
+R$* < @ $+ .REDIRECT. >		$: $1 < @ $2 . REDIRECT . > < ${opMode} >
+R$* < @ $+ .REDIRECT. > <i>	$: $1 < @ $2 . REDIRECT. >
+R$* < @ $+ .REDIRECT. > < $- >	$#error $@ 5.1.1 $: "551 User has moved; please try " <$1@$2>
+
+
+
+
+
+
+######################################################################
+###  D: LookUpDomain -- search for domain in access database
+###
+###	Parameters:
+###		<$1> -- key (domain name)
+###		<$2> -- default (what to return if not found in db)
+###		<$3> -- mark (must be <(!|+) single-token>)
+###			! does lookup only with tag
+###			+ does lookup with and without tag
+###		<$4> -- passthru (additional data passed unchanged through)
+######################################################################
+
+SD
+R<$*> <$+> <$- $-> <$*>		$: < $(access $4:$1 $: ? $) > <$1> <$2> <$3 $4> <$5>
+R<?> <$+> <$+> <+ $-> <$*>	$: < $(access $1 $: ? $) > <$1> <$2> <+ $3> <$4>
+R<?> <[$+.$-]> <$+> <$- $-> <$*>	$@ $>D <[$1]> <$3> <$4 $5> <$6>
+R<?> <[$+::$-]> <$+> <$- $-> <$*>	$: $>D <[$1]> <$3> <$4 $5> <$6>
+R<?> <[$+:$-]> <$+> <$- $-> <$*>	$: $>D <[$1]> <$3> <$4 $5> <$6>
+R<?> <$+.$+> <$+> <$- $-> <$*>	$@ $>D <$2> <$3> <$4 $5> <$6>
+R<?> <$+> <$+> <$- $-> <$*>	$@ <$2> <$5>
+R<$* <TMPF>> <$+> <$+> <$- $-> <$*>	$@ <<TMPF>> <$6>
+R<$*> <$+> <$+> <$- $-> <$*>	$@ <$1> <$6>
+
+######################################################################
+###  A: LookUpAddress -- search for host address in access database
+###
+###	Parameters:
+###		<$1> -- key (dot quadded host address)
+###		<$2> -- default (what to return if not found in db)
+###		<$3> -- mark (must be <(!|+) single-token>)
+###			! does lookup only with tag
+###			+ does lookup with and without tag
+###		<$4> -- passthru (additional data passed through)
+######################################################################
+
+SA
+R<$+> <$+> <$- $-> <$*>		$: < $(access $4:$1 $: ? $) > <$1> <$2> <$3 $4> <$5>
+R<?> <$+> <$+> <+ $-> <$*>	$: < $(access $1 $: ? $) > <$1> <$2> <+ $3> <$4>
+R<?> <$+::$-> <$+> <$- $-> <$*>		$@ $>A <$1> <$3> <$4 $5> <$6>
+R<?> <$+:$-> <$+> <$- $-> <$*>		$@ $>A <$1> <$3> <$4 $5> <$6>
+R<?> <$+.$-> <$+> <$- $-> <$*>		$@ $>A <$1> <$3> <$4 $5> <$6>
+R<?> <$+> <$+> <$- $-> <$*>	$@ <$2> <$5>
+R<$* <TMPF>> <$+> <$+> <$- $-> <$*>	$@ <<TMPF>> <$6>
+R<$*> <$+> <$+> <$- $-> <$*>	$@ <$1> <$6>
+
+######################################################################
+###  CanonAddr --	Convert an address into a standard form for
+###			relay checking.  Route address syntax is
+###			crudely converted into a %-hack address.
+###
+###	Parameters:
+###		$1 -- full recipient address
+###
+###	Returns:
+###		parsed address, not in source route form
+######################################################################
+
+SCanonAddr
+R$*			$: $>Parse0 $>canonify $1	make domain canonical
+
+
+######################################################################
+###  ParseRecipient --	Strip off hosts in $=R as well as possibly
+###			$* $=m or the access database.
+###			Check user portion for host separators.
+###
+###	Parameters:
+###		$1 -- full recipient address
+###
+###	Returns:
+###		parsed, non-local-relaying address
+######################################################################
+
+SParseRecipient
+R$*				$: <?> $>CanonAddr $1
+R<?> $* < @ $* . >		<?> $1 < @ $2 >			strip trailing dots
+R<?> $- < @ $* >		$: <?> $(dequote $1 $) < @ $2 >	dequote local part
+
+# if no $=O character, no host in the user portion, we are done
+R<?> $* $=O $* < @ $* >		$: <NO> $1 $2 $3 < @ $4>
+R<?> $*				$@ $1
+
+
+R<NO> $* < @ $* $=R >		$: <RELAY> $1 < @ $2 $3 >
+R<NO> $* < @ $+ >		$: $>D <$2> <NO> <+ To> <$1 < @ $2 >>
+R<$+> <$+>			$: <$1> $2
+
+
+
+R<RELAY> $* < @ $* >		$@ $>ParseRecipient $1
+R<$+> $*			$@ $2
+
+
+######################################################################
+###  check_relay -- check hostname/address on SMTP startup
+######################################################################
+
+
+
+SLocal_check_relay
+Scheck_relay
+R$*			$: $1 $| $>"Local_check_relay" $1
+R$* $| $* $| $#$*	$#$3
+R$* $| $* $| $*		$@ $>"Basic_check_relay" $1 $| $2
+
+SBasic_check_relay
+# check for deferred delivery mode
+R$*			$: < $&{deliveryMode} > $1
+R< d > $*		$@ deferred
+R< $* > $*		$: $2
+
+R$+ $| $+		$: $>D < $1 > <?> <+ Connect> < $2 >
+R   $| $+		$: $>A < $1 > <?> <+ Connect> <>	empty client_name
+R<?> <$+>		$: $>A < $1 > <?> <+ Connect> <>	no: another lookup
+R<?> <$*>		$: OK				found nothing
+R<$={Accept}> <$*>	$@ $1				return value of lookup
+R<REJECT> <$*>		$#error $@ 5.7.1 $: "550 Access denied"
+R<DISCARD> <$*>		$#discard $: discard
+R<QUARANTINE:$+> <$*>	$#error $@ quarantine $: $1
+R<ERROR:$-.$-.$-:$+> <$*>	$#error $@ $1.$2.$3 $: $4
+R<ERROR:$+> <$*>		$#error $: $1
+R<$* <TMPF>> <$*>		$#error $@ 4.3.0 $: "451 Temporary system failure. Please try again later."
+R<$+> <$*>		$#error $: $1
+
+
+######################################################################
+###  check_mail -- check SMTP `MAIL FROM:' command argument
+######################################################################
+
+SLocal_check_mail
+Scheck_mail
+R$*			$: $1 $| $>"Local_check_mail" $1
+R$* $| $#$*		$#$2
+R$* $| $*		$@ $>"Basic_check_mail" $1
+
+SBasic_check_mail
+# check for deferred delivery mode
+R$*			$: < $&{deliveryMode} > $1
+R< d > $*		$@ deferred
+R< $* > $*		$: $2
+
+# authenticated?
+R$*			$: $1 $| $>"tls_client" $&{verify} $| MAIL
+R$* $| $#$+		$#$2
+R$* $| $*		$: $1
+
+R<>			$@ <OK>			we MUST accept <> (RFC 1123)
+R$+			$: <?> $1
+R<?><$+>		$: <@> <$1>
+R<?>$+			$: <@> <$1>
+R$*			$: $&{daemon_flags} $| $1
+R$* f $* $| <@> < $* @ $- >	$: < ? $&{client_name} > < $3 @ $4 >
+R$* u $* $| <@> < $* >	$: <?> < $3 >
+R$* $| $*		$: $2
+# handle case of @localhost on address
+R<@> < $* @ localhost >	$: < ? $&{client_name} > < $1 @ localhost >
+R<@> < $* @ [127.0.0.1] >
+			$: < ? $&{client_name} > < $1 @ [127.0.0.1] >
+R<@> < $* @ localhost.$m >
+			$: < ? $&{client_name} > < $1 @ localhost.$m >
+R<@> < $* @ localhost.localdomain >
+			$: < ? $&{client_name} > < $1 @ localhost.localdomain >
+R<@> < $* @ localhost.UUCP >
+			$: < ? $&{client_name} > < $1 @ localhost.UUCP >
+R<@> $*			$: $1			no localhost as domain
+R<? $=w> $*		$: $2			local client: ok
+R<? $+> <$+>		$#error $@ 5.5.4 $: "553 Real domain name required for sender address"
+R<?> $*			$: $1
+R$*			$: <?> $>CanonAddr $1		canonify sender address and mark it
+R<?> $* < @ $+ . >	<?> $1 < @ $2 >			strip trailing dots
+# handle non-DNS hostnames (*.bitnet, *.decnet, *.uucp, etc)
+R<?> $* < @ $* $=P >	$: <OKR> $1 < @ $2 $3 >
+R<?> $* < @ $j >	$: <OKR> $1 < @ $j >
+R<?> $* < @ $+ >	$: <OKR> $1 < @ $2 >		... unresolvable OK
+
+# check sender address: user@address, user@, address
+R<$+> $+ < @ $* >	$: @<$1> <$2 < @ $3 >> $| <F:$2@$3> <U:$2@> <D:$3>
+R<$+> $+		$: @<$1> <$2> $| <U:$2@>
+R@ <$+> <$*> $| <$+>	$: <@> <$1> <$2> $| $>SearchList <+ From> $| <$3> <>
+R<@> <$+> <$*> $| <$*>	$: <$3> <$1> <$2>		reverse result
+# retransform for further use
+R<?> <$+> <$*>		$: <$1> $2	no match
+R<$+> <$+> <$*>		$: <$1> $3	relevant result, keep it
+
+# handle case of no @domain on address
+R<?> $*			$: $&{daemon_flags} $| <?> $1
+R$* u $* $| <?> $*	$: <OKR> $3
+R$* $| $*		$: $2
+R<?> $*			$: < ? $&{client_addr} > $1
+R<?> $*			$@ <OKR>			...local unqualed ok
+R<? $+> $*		$#error $@ 5.5.4 $: "553 Domain name required for sender address " $&f
+							...remote is not
+# check results
+R<?> $*			$: @ $1		mark address: nothing known about it
+R<$={ResOk}> $*		$: @ $2		domain ok
+R<TEMP> $*		$#error $@ 4.1.8 $: "451 Domain of sender address " $&f " does not resolve"
+R<PERM> $*		$#error $@ 5.1.8 $: "553 Domain of sender address " $&f " does not exist"
+R<$={Accept}> $*	$# $1		accept from access map
+R<DISCARD> $*		$#discard $: discard
+R<QUARANTINE:$+> $*	$#error $@ quarantine $: $1
+R<REJECT> $*		$#error $@ 5.7.1 $: "550 Access denied"
+R<ERROR:$-.$-.$-:$+> $*		$#error $@ $1.$2.$3 $: $4
+R<ERROR:$+> $*		$#error $: $1
+R<<TMPF>> $*		$#error $@ 4.3.0 $: "451 Temporary system failure. Please try again later."
+R<$+> $*		$#error $: $1		error from access db
+
+
+
+######################################################################
+###  check_rcpt -- check SMTP `RCPT TO:' command argument
+######################################################################
+
+SLocal_check_rcpt
+Scheck_rcpt
+R$*			$: $1 $| $>"Local_check_rcpt" $1
+R$* $| $#$*		$#$2
+R$* $| $*		$@ $>"Basic_check_rcpt" $1
+
+SBasic_check_rcpt
+# empty address?
+R<>			$#error $@ nouser $: "553 User address required"
+R$@			$#error $@ nouser $: "553 User address required"
+# check for deferred delivery mode
+R$*			$: < $&{deliveryMode} > $1
+R< d > $*		$@ deferred
+R< $* > $*		$: $2
+
+
+######################################################################
+R$*			$: $1 $| @ $>"Rcpt_ok" $1
+R$* $| @ $#TEMP $+	$: $1 $| T $2
+R$* $| @ $#$*		$#$2
+R$* $| @ RELAY		$@ RELAY
+R$* $| @ $*		$: O $| $>"Relay_ok" $1
+R$* $| T $+		$: T $2 $| $>"Relay_ok" $1
+R$* $| $#TEMP $+	$#error $2
+R$* $| $#$*		$#$2
+R$* $| RELAY		$@ RELAY
+R T $+ $| $*		$#error $1
+# anything else is bogus
+R$*			$#error $@ 5.7.1 $: "550 Relaying denied"
+
+
+######################################################################
+### Rcpt_ok: is the recipient ok?
+######################################################################
+SRcpt_ok
+R$*			$: $>ParseRecipient $1		strip relayable hosts
+
+
+
+# blacklist local users or any host from receiving mail
+R$*			$: <?> $1
+R<?> $+ < @ $=w >	$: <> <$1 < @ $2 >> $| <F:$1@$2> <U:$1@> <D:$2>
+R<?> $+ < @ $* >	$: <> <$1 < @ $2 >> $| <F:$1@$2> <D:$2>
+R<?> $+			$: <> <$1> $| <U:$1@>
+R<> <$*> $| <$+>	$: <@> <$1> $| $>SearchList <+ To> $| <$2> <>
+R<@> <$*> $| <$*>	$: <$2> <$1>		reverse result
+R<?> <$*>		$: @ $1		mark address as no match
+R<$={Accept}> <$*>	$: @ $2		mark address as no match
+
+R<REJECT> $*		$#error $@ 5.2.1 $: "550 Mailbox disabled for this recipient"
+R<DISCARD> $*		$#discard $: discard
+R<QUARANTINE:$+> $*	$#error $@ quarantine $: $1
+R<ERROR:$-.$-.$-:$+> $*		$#error $@ $1.$2.$3 $: $4
+R<ERROR:$+> $*		$#error $: $1
+R<<TMPF>> $*		$#error $@ 4.3.0 $: "451 Temporary system failure. Please try again later."
+R<$+> $*		$#error $: $1		error from access db
+R@ $*			$1		remove mark
+
+# authenticated via TLS?
+R$*			$: $1 $| $>RelayTLS	client authenticated?
+R$* $| $# $+		$# $2			error/ok?
+R$* $| $*		$: $1			no
+
+R$*			$: $1 $| $>"Local_Relay_Auth" $&{auth_type}
+R$* $| $# $*		$# $2
+R$* $| NO		$: $1
+R$* $| $*		$: $1 $| $&{auth_type}
+R$* $|			$: $1
+R$* $| $={TrustAuthMech}	$# RELAY
+R$* $| $*		$: $1
+# anything terminating locally is ok
+R$+ < @ $=w >		$@ RELAY
+R$+ < @ $* $=R >	$@ RELAY
+R$+ < @ $+ >		$: $>D <$2> <?> <+ To> <$1 < @ $2 >>
+R<RELAY> $*		$@ RELAY
+R<$* <TMPF>> $*		$#TEMP $@ 4.3.0 $: "451 Temporary system failure. Please try again later."
+R<$*> <$*>		$: $2
+
+
+
+# check for local user (i.e. unqualified address)
+R$*			$: <?> $1
+R<?> $* < @ $+ >	$: <REMOTE> $1 < @ $2 >
+# local user is ok
+R<?> $+			$@ RELAY
+R<$+> $*		$: $2
+
+######################################################################
+### Relay_ok: is the relay/sender ok?
+######################################################################
+SRelay_ok
+# anything originating locally is ok
+# check IP address
+R$*			$: $&{client_addr}
+R$@			$@ RELAY		originated locally
+R0			$@ RELAY		originated locally
+R127.0.0.1		$@ RELAY		originated locally
+RIPv6:::1		$@ RELAY		originated locally
+R$=R $*			$@ RELAY		relayable IP address
+R$*			$: $>A <$1> <?> <+ Connect> <$1>
+R<RELAY> $* 		$@ RELAY		relayable IP address
+
+R<<TMPF>> $*		$#TEMP $@ 4.3.0 $: "451 Temporary system failure. Please try again later."
+R<$*> <$*>		$: $2
+R$*			$: [ $1 ]		put brackets around it...
+R$=w			$@ RELAY		... and see if it is local
+
+
+# check client name: first: did it resolve?
+R$*			$: < $&{client_resolve} >
+R<TEMP>			$#TEMP $@ 4.4.0 $: "450 Relaying temporarily denied. Cannot resolve PTR record for " $&{client_addr}
+R<FORGED>		$#error $@ 5.7.1 $: "550 Relaying denied. IP name possibly forged " $&{client_name}
+R<FAIL>			$#error $@ 5.7.1 $: "550 Relaying denied. IP name lookup failed " $&{client_name}
+R$*			$: <@> $&{client_name}
+# pass to name server to make hostname canonical
+R<@> $* $=P 		$:<?>  $1 $2
+R<@> $+			$:<?>  $[ $1 $]
+R$* .			$1			strip trailing dots
+R<?> $=w		$@ RELAY
+R<?> $* $=R			$@ RELAY
+R<?> $*			$: $>D <$1> <?> <+ Connect> <$1>
+R<RELAY> $*		$@ RELAY
+R<$* <TMPF>> $*		$#TEMP $@ 4.3.0 $: "451 Temporary system failure. Please try again later."
+R<$*> <$*>		$: $2
+
+
+
+######################################################################
+###  F: LookUpFull -- search for an entry in access database
+###
+###	lookup of full key (which should be an address) and
+###	variations if +detail exists: +* and without +detail
+###
+###	Parameters:
+###		<$1> -- key
+###		<$2> -- default (what to return if not found in db)
+###		<$3> -- mark (must be <(!|+) single-token>)
+###			! does lookup only with tag
+###			+ does lookup with and without tag
+###		<$4> -- passthru (additional data passed unchanged through)
+######################################################################
+
+SF
+R<$+> <$*> <$- $-> <$*>		$: <$(access $4:$1 $: ? $)> <$1> <$2> <$3 $4> <$5>
+R<?> <$+> <$*> <+ $-> <$*>	$: <$(access $1 $: ? $)> <$1> <$2> <+ $3> <$4>
+R<?> <$+ + $* @ $+> <$*> <$- $-> <$*>
+			$: <$(access $6:$1+*@$3 $: ? $)> <$1+$2@$3> <$4> <$5 $6> <$7>
+R<?> <$+ + $* @ $+> <$*> <+ $-> <$*>
+			$: <$(access $1+*@$3 $: ? $)> <$1+$2@$3> <$4> <+ $5> <$6>
+R<?> <$+ + $* @ $+> <$*> <$- $-> <$*>
+			$: <$(access $6:$1@$3 $: ? $)> <$1+$2@$3> <$4> <$5 $6> <$7>
+R<?> <$+ + $* @ $+> <$*> <+ $-> <$*>
+			$: <$(access $1@$3 $: ? $)> <$1+$2@$3> <$4> <+ $5> <$6>
+R<?> <$+> <$*> <$- $-> <$*>	$@ <$2> <$5>
+R<$+ <TMPF>> <$*> <$- $-> <$*>	$@ <<TMPF>> <$5>
+R<$+> <$*> <$- $-> <$*>		$@ <$1> <$5>
+
+######################################################################
+###  E: LookUpExact -- search for an entry in access database
+###
+###	Parameters:
+###		<$1> -- key
+###		<$2> -- default (what to return if not found in db)
+###		<$3> -- mark (must be <(!|+) single-token>)
+###			! does lookup only with tag
+###			+ does lookup with and without tag
+###		<$4> -- passthru (additional data passed unchanged through)
+######################################################################
+
+SE
+R<$*> <$*> <$- $-> <$*>		$: <$(access $4:$1 $: ? $)> <$1> <$2> <$3 $4> <$5>
+R<?> <$+> <$*> <+ $-> <$*>	$: <$(access $1 $: ? $)> <$1> <$2> <+ $3> <$4>
+R<?> <$+> <$*> <$- $-> <$*>	$@ <$2> <$5>
+R<$+ <TMPF>> <$*> <$- $-> <$*>	$@ <<TMPF>> <$5>
+R<$+> <$*> <$- $-> <$*>		$@ <$1> <$5>
+
+######################################################################
+###  U: LookUpUser -- search for an entry in access database
+###
+###	lookup of key (which should be a local part) and
+###	variations if +detail exists: +* and without +detail
+###
+###	Parameters:
+###		<$1> -- key (user@)
+###		<$2> -- default (what to return if not found in db)
+###		<$3> -- mark (must be <(!|+) single-token>)
+###			! does lookup only with tag
+###			+ does lookup with and without tag
+###		<$4> -- passthru (additional data passed unchanged through)
+######################################################################
+
+SU
+R<$+> <$*> <$- $-> <$*>		$: <$(access $4:$1 $: ? $)> <$1> <$2> <$3 $4> <$5>
+R<?> <$+> <$*> <+ $-> <$*>	$: <$(access $1 $: ? $)> <$1> <$2> <+ $3> <$4>
+R<?> <$+ + $* @> <$*> <$- $-> <$*>
+			$: <$(access $5:$1+*@ $: ? $)> <$1+$2@> <$3> <$4 $5> <$6>
+R<?> <$+ + $* @> <$*> <+ $-> <$*>
+			$: <$(access $1+*@ $: ? $)> <$1+$2@> <$3> <+ $4> <$5>
+R<?> <$+ + $* @> <$*> <$- $-> <$*>
+			$: <$(access $5:$1@ $: ? $)> <$1+$2@> <$3> <$4 $5> <$6>
+R<?> <$+ + $* @> <$*> <+ $-> <$*>
+			$: <$(access $1@ $: ? $)> <$1+$2@> <$3> <+ $4> <$5>
+R<?> <$+> <$*> <$- $-> <$*>	$@ <$2> <$5>
+R<$+ <TMPF>> <$*> <$- $-> <$*>	$@ <<TMPF>> <$5>
+R<$+> <$*> <$- $-> <$*>		$@ <$1> <$5>
+
+######################################################################
+###  SearchList: search a list of items in the access map
+###	Parameters:
+###		<exact tag> $| <mark:address> <mark:address> ... <>
+###	where "exact" is either "+" or "!":
+###	<+ TAG>	lookup with and w/o tag
+###	<! TAG>	lookup with tag
+###	possible values for "mark" are:
+###		D: recursive host lookup (LookUpDomain)
+###		E: exact lookup, no modifications
+###		F: full lookup, try user+ext@domain and user@domain
+###		U: user lookup, try user+ext and user (input must have trailing @)
+###	return: <RHS of lookup> or <?> (not found)
+######################################################################
+
+# class with valid marks for SearchList
+C{Src}E F D U 
+SSearchList
+# just call the ruleset with the name of the tag... nice trick...
+R<$+> $| <$={Src}:$*> <$*>	$: <$1> $| <$4> $| $>$2 <$3> <?> <$1> <>
+R<$+> $| <> $| <?> <>		$@ <?>
+R<$+> $| <$+> $| <?> <>		$@ $>SearchList <$1> $| <$2>
+R<$+> $| <$*> $| <$+> <>	$@ <$3>
+R<$+> $| <$+>			$@ <$2>
+
+
+######################################################################
+###  trust_auth: is user trusted to authenticate as someone else?
+###
+###	Parameters:
+###		$1: AUTH= parameter from MAIL command
+######################################################################
+
+SLocal_trust_auth
+Strust_auth
+R$*			$: $&{auth_type} $| $1
+# required by RFC 2554 section 4.
+R$@ $| $*		$#error $@ 5.7.1 $: "550 not authenticated"
+R$* $| $&{auth_authen}		$@ identical
+R$* $| <$&{auth_authen}>	$@ identical
+R$* $| $*		$: $1 $| $>"Local_trust_auth" $2
+R$* $| $#$*		$#$2
+R$*			$#error $@ 5.7.1 $: "550 " $&{auth_authen} " not allowed to act as " $&{auth_author}
+
+######################################################################
+###  Relay_Auth: allow relaying based on authentication?
+###
+###	Parameters:
+###		$1: ${auth_type}
+######################################################################
+SLocal_Relay_Auth
+
+######################################################################
+###  srv_features: which features to offer to a client?
+###	(done in server)
+######################################################################
+Ssrv_features
+R$*		$: $>D <$&{client_name}> <?> <! "Srv_Features"> <>
+R<?>$*		$: $>A <$&{client_addr}> <?> <! "Srv_Features"> <>
+R<?>$*		$: <$(access "Srv_Features": $: ? $)>
+R<?>$*		$@ OK
+R<$* <TMPF>>$*	$#temp
+R<$+>$*		$# $1
+
+######################################################################
+###  try_tls: try to use STARTTLS?
+###	(done in client)
+######################################################################
+Stry_tls
+R$*		$: $>D <$&{server_name}> <?> <! "Try_TLS"> <>
+R<?>$*		$: $>A <$&{server_addr}> <?> <! "Try_TLS"> <>
+R<?>$*		$: <$(access "Try_TLS": $: ? $)>
+R<?>$*		$@ OK
+R<$* <TMPF>>$*	$#error $@ 4.3.0 $: "451 Temporary system failure. Please try again later."
+R<NO>$*		$#error $@ 5.7.1 $: "550 do not try TLS with " $&{server_name} " ["$&{server_addr}"]"
+
+######################################################################
+###  tls_rcpt: is connection with server "good" enough?
+###	(done in client, per recipient)
+###
+###	Parameters:
+###		$1: recipient
+######################################################################
+Stls_rcpt
+R$*			$: $(macro {TLS_Name} $@ $&{server_name} $) $1
+R$+			$: <?> $>CanonAddr $1
+R<?> $+ < @ $+ . >	<?> $1 <@ $2 >
+R<?> $+ < @ $+ >	$: $1 <@ $2 > $| <F:$1@$2> <U:$1@> <D:$2> <E:>
+R<?> $+			$: $1 $| <U:$1@> <E:>
+R$* $| $+	$: $1 $| $>SearchList <! "TLS_Rcpt"> $| $2 <>
+R$* $| <?>	$@ OK
+R$* $| <$* <TMPF>>	$#error $@ 4.3.0 $: "451 Temporary system failure. Please try again later."
+R$* $| <$+>	$@ $>"TLS_connection" $&{verify} $| <$2>
+
+######################################################################
+###  tls_client: is connection with client "good" enough?
+###	(done in server)
+###
+###	Parameters:
+###		${verify} $| (MAIL|STARTTLS)
+######################################################################
+Stls_client
+R$*		$: $(macro {TLS_Name} $@ $&{client_name} $) $1
+R$* $| $*	$: $1 $| $>D <$&{client_name}> <?> <! "TLS_Clt"> <>
+R$* $| <?>$*	$: $1 $| $>A <$&{client_addr}> <?> <! "TLS_Clt"> <>
+R$* $| <?>$*	$: $1 $| <$(access "TLS_Clt": $: ? $)>
+R$* $| <$* <TMPF>>	$#error $@ 4.3.0 $: "451 Temporary system failure. Please try again later."
+R$*		$@ $>"TLS_connection" $1
+
+######################################################################
+###  tls_server: is connection with server "good" enough?
+###	(done in client)
+###
+###	Parameter:
+###		${verify}
+######################################################################
+Stls_server
+R$*		$: $(macro {TLS_Name} $@ $&{server_name} $) $1
+R$*		$: $1 $| $>D <$&{server_name}> <?> <! "TLS_Srv"> <>
+R$* $| <?>$*	$: $1 $| $>A <$&{server_addr}> <?> <! "TLS_Srv"> <>
+R$* $| <?>$*	$: $1 $| <$(access "TLS_Srv": $: ? $)>
+R$* $| <$* <TMPF>>	$#error $@ 4.3.0 $: "451 Temporary system failure. Please try again later."
+R$*		$@ $>"TLS_connection" $1
+
+######################################################################
+###  TLS_connection: is TLS connection "good" enough?
+###
+###	Parameters:
+###		${verify} $| <Requirement> [<>]
+###		Requirement: RHS from access map, may be ? for none.
+######################################################################
+STLS_connection
+R$* $| <$*>$*			$: $1 $| <$2>
+# create the appropriate error codes
+R$* $| <PERM + $={Tls} $*>	$: $1 $| <503:5.7.0> <$2 $3>
+R$* $| <TEMP + $={Tls} $*>	$: $1 $| <403:4.7.0> <$2 $3>
+R$* $| <$={Tls} $*>		$: $1 $| <403:4.7.0> <$2 $3>
+# deal with TLS handshake failures: abort
+RSOFTWARE $| <$-:$+> $* 	$#error $@ $2 $: $1 " TLS handshake failed."
+RSOFTWARE $| $* 		$#error $@ 4.7.0 $: "403 TLS handshake failed."
+# deal with TLS protocol errors: abort
+RPROTOCOL $| <$-:$+> $* 	$#error $@ $2 $: $1 " STARTTLS failed."
+RPROTOCOL $| $* 		$#error $@ 4.7.0 $: "403 STARTTLS failed."
+R$* $| <$*> <VERIFY>		$: <$2> <VERIFY> <> $1
+R$* $| <$*> <VERIFY + $+>	$: <$2> <VERIFY> <$3> $1
+R$* $| <$*> <$={Tls}:$->$*	$: <$2> <$3:$4> <> $1
+R$* $| <$*> <$={Tls}:$- + $+>$*	$: <$2> <$3:$4> <$5> $1
+R$* $| $*			$@ OK
+# authentication required: give appropriate error
+# other side did authenticate (via STARTTLS)
+R<$*><VERIFY> <> OK		$@ OK
+R<$*><VERIFY> <$+> OK		$: <$1> <REQ:0> <$2>
+R<$*><VERIFY:$-> <$*> OK	$: <$1> <REQ:$2> <$3>
+R<$*><ENCR:$-> <$*> $*		$: <$1> <REQ:$2> <$3>
+R<$-:$+><VERIFY $*> <$*>	$#error $@ $2 $: $1 " authentication required"
+R<$-:$+><VERIFY $*> <$*> FAIL	$#error $@ $2 $: $1 " authentication failed"
+R<$-:$+><VERIFY $*> <$*> NO	$#error $@ $2 $: $1 " not authenticated"
+R<$-:$+><VERIFY $*> <$*> NOT	$#error $@ $2 $: $1 " no authentication requested"
+R<$-:$+><VERIFY $*> <$*> NONE	$#error $@ $2 $: $1 " other side does not support STARTTLS"
+R<$-:$+><VERIFY $*> <$*> $+	$#error $@ $2 $: $1 " authentication failure " $4
+R<$*><REQ:$-> <$*>		$: <$1> <REQ:$2> <$3> $>max $&{cipher_bits} : $&{auth_ssf}
+R<$*><REQ:$-> <$*> $-		$: <$1> <$2:$4> <$3> $(arith l $@ $4 $@ $2 $)
+R<$-:$+><$-:$-> <$*> TRUE	$#error $@ $2 $: $1 " encryption too weak " $4 " less than " $3
+R<$-:$+><$-:$-> <$*> $*		$: <$1:$2 ++ $5>
+R<$-:$+ ++ >			$@ OK
+R<$-:$+ ++ $+ >			$: <$1:$2> <$3>
+R<$-:$+> < $+ ++ $+ >		<$1:$2> <$3> <$4>
+R<$-:$+> $+			$@ $>"TLS_req" $3 $| <$1:$2>
+
+######################################################################
+###  TLS_req: check additional TLS requirements
+###
+###	Parameters: [<list> <of> <req>] $| <$-:$+>
+###		$-: SMTP reply code
+###		$+: Enhanced Status Code
+######################################################################
+STLS_req
+R $| $+		$@ OK
+R<CN> $* $| <$+>		$: <CN:$&{TLS_Name}> $1 $| <$2>
+R<CN:$&{cn_subject}> $* $| <$+>		$@ $>"TLS_req" $1 $| <$2>
+R<CN:$+> $* $| <$-:$+>	$#error $@ $4 $: $3 " CN " $&{cn_subject} " does not match " $1
+R<CS:$&{cert_subject}> $* $| <$+>	$@ $>"TLS_req" $1 $| <$2>
+R<CS:$+> $* $| <$-:$+>	$#error $@ $4 $: $3 " Cert Subject " $&{cert_subject} " does not match " $1
+R<CI:$&{cert_issuer}> $* $| <$+>	$@ $>"TLS_req" $1 $| <$2>
+R<CI:$+> $* $| <$-:$+>	$#error $@ $4 $: $3 " Cert Issuer " $&{cert_issuer} " does not match " $1
+ROK			$@ OK
+
+######################################################################
+###  max: return the maximum of two values separated by :
+###
+###	Parameters: [$-]:[$-]
+######################################################################
+Smax
+R:		$: 0
+R:$-		$: $1
+R$-:		$: $1
+R$-:$-		$: $(arith l $@ $1 $@ $2 $) : $1 : $2
+RTRUE:$-:$-	$: $2
+R$-:$-:$-	$: $2
+
+
+######################################################################
+###  RelayTLS: allow relaying based on TLS authentication
+###
+###	Parameters:
+###		none
+######################################################################
+SRelayTLS
+# authenticated?
+R$*			$: <?> $&{verify}
+R<?> OK			$: OK		authenticated: continue
+R<?> $*			$@ NO		not authenticated
+R$*			$: $&{cert_issuer}
+R$+			$: $(access CERTISSUER:$1 $)
+RRELAY			$# RELAY
+RSUBJECT		$: <@> $&{cert_subject}
+R<@> $+			$: <@> $(access CERTSUBJECT:$1 $)
+R<@> RELAY		$# RELAY
+R$*			$: NO
+
+######################################################################
+###  authinfo: lookup authinfo in the access map
+###
+###	Parameters:
+###		$1: {server_name}
+###		$2: {server_addr}
+######################################################################
+Sauthinfo
+R$*		$: $1 $| $>D <$&{server_name}> <?> <! AuthInfo> <>
+R$* $| <?>$*	$: $1 $| $>A <$&{server_addr}> <?> <! AuthInfo> <>
+R$* $| <?>$*	$: $1 $| <$(access AuthInfo: $: ? $)> <>
+R$* $| <?>$*	$@ no				no authinfo available
+R$* $| <$*> <>	$# $2
+
+
+
+
+
+#
+######################################################################
+######################################################################
+#####
+#####			MAIL FILTER DEFINITIONS
+#####
+######################################################################
+######################################################################
+
+#
+######################################################################
+######################################################################
+#####
+#####			MAILER DEFINITIONS
+#####
+######################################################################
+######################################################################
+
+#####################################
+###   SMTP Mailer specification   ###
+#####################################
+
+#####  $Id: smtp.m4,v 8.65 2006/07/12 21:08:10 ca Exp $  #####
+
+#
+#  common sender and masquerading recipient rewriting
+#
+SMasqSMTP
+R$* < @ $* > $*		$@ $1 < @ $2 > $3		already fully qualified
+R$+			$@ $1 < @ *LOCAL* >		add local qualification
+
+#
+#  convert pseudo-domain addresses to real domain addresses
+#
+SPseudoToReal
+
+# pass <route-addr>s through
+R< @ $+ > $*		$@ < @ $1 > $2			resolve <route-addr>
+
+# output fake domains as user%fake@relay
+
+# do UUCP heuristics; note that these are shared with UUCP mailers
+R$+ < @ $+ .UUCP. >	$: < $2 ! > $1			convert to UUCP form
+R$+ < @ $* > $*		$@ $1 < @ $2 > $3		not UUCP form
+
+# leave these in .UUCP form to avoid further tampering
+R< $&h ! > $- ! $+	$@ $2 < @ $1 .UUCP. >
+R< $&h ! > $-.$+ ! $+	$@ $3 < @ $1.$2 >
+R< $&h ! > $+		$@ $1 < @ $&h .UUCP. >
+R< $+ ! > $+		$: $1 ! $2 < @ $Y >		use UUCP_RELAY
+R$+ < @ $~[ $* : $+ >	$@ $1 < @ $4 >			strip mailer: part
+R$+ < @ >		$: $1 < @ *LOCAL* >		if no UUCP_RELAY
+
+
+#
+#  envelope sender rewriting
+#
+SEnvFromSMTP
+R$+			$: $>PseudoToReal $1		sender/recipient common
+R$* :; <@>		$@				list:; special case
+R$*			$: $>MasqSMTP $1		qualify unqual'ed names
+R$+			$: $>MasqEnv $1			do masquerading
+
+
+#
+#  envelope recipient rewriting --
+#  also header recipient if not masquerading recipients
+#
+SEnvToSMTP
+R$+			$: $>PseudoToReal $1		sender/recipient common
+R$+			$: $>MasqSMTP $1		qualify unqual'ed names
+R$* < @ *LOCAL* > $*	$: $1 < @ $j . > $2
+
+#
+#  header sender and masquerading header recipient rewriting
+#
+SHdrFromSMTP
+R$+			$: $>PseudoToReal $1		sender/recipient common
+R:; <@>			$@				list:; special case
+
+# do special header rewriting
+R$* <@> $*		$@ $1 <@> $2			pass null host through
+R< @ $* > $*		$@ < @ $1 > $2			pass route-addr through
+R$*			$: $>MasqSMTP $1		qualify unqual'ed names
+R$+			$: $>MasqHdr $1			do masquerading
+
+
+#
+#  relay mailer header masquerading recipient rewriting
+#
+SMasqRelay
+R$+			$: $>MasqSMTP $1
+R$+			$: $>MasqHdr $1
+
+Msmtp,		P=[IPC], F=mDFMuX, S=EnvFromSMTP/HdrFromSMTP, R=EnvToSMTP, E=\r\n, L=990,
+		T=DNS/RFC822/SMTP,
+		A=TCP $h
+Mesmtp,		P=[IPC], F=mDFMuXa, S=EnvFromSMTP/HdrFromSMTP, R=EnvToSMTP, E=\r\n, L=990,
+		T=DNS/RFC822/SMTP,
+		A=TCP $h
+Msmtp8,		P=[IPC], F=mDFMuX8, S=EnvFromSMTP/HdrFromSMTP, R=EnvToSMTP, E=\r\n, L=990,
+		T=DNS/RFC822/SMTP,
+		A=TCP $h
+Mdsmtp,		P=[IPC], F=mDFMuXa%, S=EnvFromSMTP/HdrFromSMTP, R=EnvToSMTP, E=\r\n, L=990,
+		T=DNS/RFC822/SMTP,
+		A=TCP $h
+Mrelay,		P=[IPC], F=mDFMuXa8, S=EnvFromSMTP/HdrFromSMTP, R=MasqSMTP, E=\r\n, L=2040,
+		T=DNS/RFC822/SMTP,
+		A=TCP $h
+
+
+######################*****##############
+###   PROCMAIL Mailer specification   ###
+##################*****##################
+
+#####  $Id: procmail.m4,v 8.22 2001/11/12 23:11:34 ca Exp $  #####
+
+Mprocmail,	P=/usr/bin/procmail, F=DFMSPhnu9, S=EnvFromSMTP/HdrFromSMTP, R=EnvToSMTP/HdrFromSMTP,
+		T=DNS/RFC822/X-Unix,
+		A=procmail -Y -m $h $f $u
+
+
+##################################################
+###   Local and Program Mailer specification   ###
+##################################################
+
+#####  $Id: local.m4,v 8.59 2004/11/23 00:37:25 ca Exp $  #####
+
+#
+#  Envelope sender rewriting
+#
+SEnvFromL
+R<@>			$n			errors to mailer-daemon
+R@ <@ $*>		$n			temporarily bypass Sun bogosity
+R$+			$: $>AddDomain $1	add local domain if needed
+R$*			$: $>MasqEnv $1		do masquerading
+
+#
+#  Envelope recipient rewriting
+#
+SEnvToL
+R$+ < @ $* >		$: $1			strip host part
+
+#
+#  Header sender rewriting
+#
+SHdrFromL
+R<@>			$n			errors to mailer-daemon
+R@ <@ $*>		$n			temporarily bypass Sun bogosity
+R$+			$: $>AddDomain $1	add local domain if needed
+R$*			$: $>MasqHdr $1		do masquerading
+
+#
+#  Header recipient rewriting
+#
+SHdrToL
+R$+			$: $>AddDomain $1	add local domain if needed
+R$* < @ *LOCAL* > $*	$: $1 < @ $j . > $2
+
+#
+#  Common code to add local domain name (only if always-add-domain)
+#
+SAddDomain
+R$* < @ $* > $* 	$@ $1 < @ $2 > $3	already fully qualified
+
+R$+			$@ $1 < @ *LOCAL* >	add local qualification
+
+Mlocal,		P=/usr/bin/procmail, F=lsDFMAw5:/|@qSPfhn9, S=EnvFromL/HdrFromL, R=EnvToL/HdrToL,
+		T=DNS/RFC822/X-Unix,
+		A=procmail -t -Y -a $h -d $u
+Mprog,		P=/usr/sbin/smrsh, F=lsDFMoqeu9, S=EnvFromL/HdrFromL, R=EnvToL/HdrToL, D=$z:/,
+		T=X-Unix/X-Unix/X-Unix,
+		A=smrsh -c $u
+
Index: /branches/rel_avx_2_7_4/src/library/ca_mail/ssmtp.conf.def
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_mail/ssmtp.conf.def	(revision 0)
+++ /branches/rel_avx_2_7_4/src/library/ca_mail/ssmtp.conf.def	(working copy)
@@ -0,0 +1,52 @@
+#
+# /etc/ssmtp.conf -- a config file for sSMTP sendmail.
+# 
+# See the ssmtp.conf(5) man page for a more verbose explanation of the
+# available options.
+#
+# The person who gets all mail for userids < 1000
+# Make this empty to disable rewriting.
+#root=postmaster
+
+# The place where the mail goes. The actual machine name is required
+# no MX records are consulted. Commonly mailhosts are named mail.domain.com
+# The example will fit if you are in domain.com and your mailhub is so named.
+mailhub=mail
+
+# Example for SMTP port number 2525
+# mailhub=mail.your.domain:2525
+# Example for SMTP port number 25 (Standard/RFC)
+# mailhub=mail.your.domain
+# Example for SSL encrypted connection
+# mailhub=mail.your.domain:465
+
+# Where will the mail seem to come from?
+#RewriteDomain=
+
+# The full hostname
+#Hostname=
+
+# Set this to never rewrite the "From:" line (unless not given) and to
+# use that address in the "from line" of the envelope.
+FromLineOverride=YES
+
+# Use SSL/TLS to send secure messages to server.
+#UseTLS=YES
+#UseSTARTTLS=YES
+#IMPORTANT: The following line is mandatory for TLS authentication
+TLS_CA_File=/etc/pki/tls/certs/ca-bundle.crt
+
+#AuthUser=
+#AuthPass=
+
+# Use SSL/TLS certificate to authenticate against smtp host.
+#UseTLSCert=YES
+
+# Use this RSA certificate.
+#TLSCert=/etc/pki/tls/private/ssmtp.pem
+
+# Get enhanced (*really* enhanced) debugging information in the logs
+# If you want to have debugging of the config file parsing, move this option
+# to the top of the config file and uncomment
+#Debug=YES
+
Index: /branches/rel_avx_2_7_4/src/library/ca_mail/sys_mail.h
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_mail/sys_mail.h	(revision 0)
+++ /branches/rel_avx_2_7_4/src/library/ca_mail/sys_mail.h	(working copy)
@@ -0,0 +1,103 @@
+#ifndef _SYS_MAIL_H_
+#define _SYS_MAIL_H_
+
+#define SYS_MAIL_SHM_MODE               SHM_R|SHM_W
+#define SYS_MAIL_SHM_SZ                	sizeof(sys_mail_conf_t)
+
+#define MAX_MAIL_FROM_LEN               256
+#define MAX_MAIL_HOSTNAME_LEN           128
+
+#define DEF_MAIL_FROM                   "%h<alert@log.domain>"
+#define DEF_MAIL_HOSTNAME               "%l.alert_pseudo_domain"
+
+#define SENDMAIL_HOSTNAME_DEF           "Dj"
+#define SENDMAIL_CONF_FILE              "/etc/mail/sendmail.cf"
+#define SENDMAIL_CONF_NEW_FILE          "/etc/mail/sendmail.cf.new"
+#define SENDMAIL_ORI_CONF_FILE          "/ca/etc/sendmail.cf"
+
+#ifdef UOS_X86
+#define SSMTP_SCRIPT                    "/ca/bin/msmtp_config.pl"
+#define SSMTP_CONF_DEF			        "/ca/etc/msmtp.conf.def"
+#define SSMTP_CONF			            "/etc/msmtprc"
+
+#else
+#define SSMTP_SCRIPT                    "/ca/bin/ssmtp_config.pl"
+#define SSMTP_CONF_DEF			        "/ca/etc/ssmtp.conf.def"
+#define SSMTP_CONF			            "/etc/ssmtp/ssmtp.conf"
+
+#endif
+
+
+
+
+/*
+* define mailertable file and path
+*/
+#define ERR_RELAY_ADD           "Error occurred when add a relay server!"
+#define ERR_RELAY_DEL           "Error occurred when delete a relay server!"
+#define MAILERTABLE_FILE        "/etc/mail/mailertable"
+#define MAILERTABLE_FILE_NEW    "/etc/mail/mailertable.new"
+#define MAILERTABLE_DB          "/etc/mail/mailertable.db"
+#define ENCRYPT_PASSWD_PREFIX	"XXXXXXXXX"
+#define ENCRYPT_PASSWD_PREFIX_LEN sizeof(ENCRYPT_PASSWD_PREFIX) - 1
+#define MAX_MAIL_RELAY_NUM      10
+#define MAX_MAIL_RELAY_HOSTNAME_LEN 50
+#define MAX_MAIL_RELAY_SERVER 30
+#define MAX_MAIL_EXTERN_SERVER_LEN 64
+#define MAX_MAIL_USER_LEN 32
+#define MAX_MAIL_PASSWD_LEN 64
+#define MAX_MAIL_ENCRPT_PASSWD_LEN ENCRYPT_PASSWD_PREFIX_LEN + 128
+
+/*
+* add structs for relay server & status
+*/
+typedef struct _mail_relay_status_t{
+        int relay_status;
+        int relay_num;
+}mail_relay_status_t;
+
+typedef struct _mail_relay_server_t{
+        char hostname[MAX_MAIL_RELAY_HOSTNAME_LEN+1];
+        char relayserver[MAX_MAIL_RELAY_SERVER+1];
+}mail_relay_server_t;
+
+typedef struct _mail_extern_server_t{
+        char extern_server[MAX_MAIL_EXTERN_SERVER_LEN+1];
+        int port;
+        char user[MAX_MAIL_USER_LEN+1];
+        char passwd[MAX_MAIL_ENCRPT_PASSWD_LEN+1];
+        int use_ssl;
+}mail_extern_server_t;
+
+/*end 10914*/
+
+typedef struct sys_mail_conf {
+        char from[MAX_MAIL_FROM_LEN+1];
+        char hostname[MAX_MAIL_HOSTNAME_LEN+1];
+        unsigned int hostname_behavior;    
+        /*
+         * Add structs for relay server % status
+         */
+        mail_relay_status_t mrelay_status;
+        mail_relay_server_t mrelay_server[MAX_MAIL_RELAY_NUM];
+        /* end add for 10914 */
+        int extern_mail_on;
+        mail_extern_server_t mextern_server; 
+} sys_mail_conf_t;
+
+/*
+* add new CLI reference function
+*/
+char *write_system_mail_relay(char *segment);
+int clear_system_mail_relay(void);
+int system_mail_relay_on(void);
+int system_mail_relay_off(void);
+int system_mail_relay_server_add(char *relayhostname, char *relayserver);
+int system_mail_relay_server_del(char *relayhostname);
+int show_system_mail_relay(void);
+
+char *write_system_mail_conf(char *segment);
+int clear_system_mail_conf(void);
+extern int sysmail_get_domainame(char * output, size_t len);
+
+#endif

Property changes on: src/library/ca_mail/sys_mail.h
___________________________________________________________________
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: /branches/rel_avx_2_7_4/src/library/ca_mail/sys_mail.c
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_mail/sys_mail.c	(revision 0)
+++ /branches/rel_avx_2_7_4/src/library/ca_mail/sys_mail.c	(working copy)
@@ -0,0 +1,1511 @@
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+#if !defined(__linux__)
+#include <machine/param.h>
+#endif
+#include <sys/types.h>
+#include <sys/ipc.h>
+#include <sys/shm.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <openssl/evp.h>
+#include "../../proxy_shm.h"
+#include "sys_mail.h"
+#include "../management/suppress_print.h"
+#include "../ca_util/ca_util.h"
+
+extern int set_node_name(char *name, int id);
+
+sys_mail_conf_t *attach_sys_mail_conf(void);
+void detach_sys_mail_conf(sys_mail_conf_t *conf_p);
+int check_from_string(char *from_str);
+int check_hostname_string(char *hostname);
+int write_fqdn_to_file(void);
+int write_hostname_to_file(char *hostname);
+
+int check_servername_relay(char *relayhostname);
+int check_ip_valid(char *address);
+char *system_mail_relay_get_config(void);
+int check_external_mail_string(char *name);
+int ssmtp_conf_file_update(sys_mail_conf_t *conf_p);
+
+#define RANDOM_KEY 	"sfG{[5+/au"
+#define WRITE_STR_LEN	1024
+
+#define CHARACTER_VALID		0
+#define CHARACTER_INVALID	1
+
+int
+check_servername_relay(char * relayserver)
+{
+    int i;
+    i = strlen(relayserver);
+    if( ((relayserver[i-1] < 48) || (relayserver[i-1]) > 57 ) && (relayserver[i-1] != '.')){
+        return 2;             
+    } else {
+        if(check_ip_valid(relayserver) != 0){
+                return -1;
+        }
+        return 1;
+    }
+}
+
+int 
+check_ip_valid(char *address)
+{
+    struct sockaddr_in ina;
+              
+    if( (ina.sin_addr.s_addr = inet_addr(address)) == -1){
+	if(cli_interactive()){
+        	printf("The address is invalid!\n");
+	}
+        return -1;
+    }
+        return 0;     
+} 
+
+int
+system_mail_relay_server_add(char *relayhostname, char *relayserver)
+{
+	FILE *mailertable_new_fpw;
+	sys_mail_conf_t *conf_p = attach_sys_mail_conf();
+	char *ptradd = system_mail_relay_get_config();
+	int i,j;
+
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not add mail relay config (Internal error - 1)\n");
+		}
+		if(ptradd){
+			free(ptradd);
+			ptradd = NULL;
+		}
+		return -1;
+	}
+
+	if( strlen(relayhostname) > MAX_MAIL_RELAY_HOSTNAME_LEN)	{
+		if(cli_interactive()){
+			printf("The length of hostname is over %d!\n", MAX_MAIL_RELAY_HOSTNAME_LEN);
+		}
+		detach_sys_mail_conf(conf_p);
+		if(ptradd){             
+                        free(ptradd);
+                        ptradd = NULL;
+                }
+		return -1;
+	}
+	if( strlen(relayserver) > MAX_MAIL_RELAY_SERVER){
+		if(cli_interactive()){
+			printf("The length of relayserver is over %d!\n", MAX_MAIL_RELAY_SERVER);
+		}
+		detach_sys_mail_conf(conf_p);
+		if(ptradd){             
+                        free(ptradd);
+                        ptradd = NULL;
+                }
+		return -1;
+	}	
+
+	for(i=0;i<MAX_MAIL_RELAY_NUM;i++){
+		if( strcasecmp(relayhostname, conf_p->mrelay_server[i].hostname) == 0)	{
+			if(cli_interactive()){
+				printf("The host is exist!\n");
+			}
+			detach_sys_mail_conf(conf_p);
+			if(ptradd){             
+        	                free(ptradd);
+                	        ptradd = NULL;
+               		}
+			return -1;
+		}
+		if( strlen(conf_p->mrelay_server[i].hostname) <= 0)	{
+			break;
+		}
+	}
+
+	j = check_servername_relay(relayserver);	
+
+	if( j == 1)	{
+		strcat(conf_p->mrelay_server[i].relayserver, "[");
+		strcat(conf_p->mrelay_server[i].relayserver, relayserver);
+		strcat(conf_p->mrelay_server[i].relayserver, "]");
+	}
+	if(j == 2)	{
+		strcpy( conf_p->mrelay_server[i].relayserver, relayserver);
+	}
+	if(j == -1){	
+		if(cli_interactive()){
+			printf("%s", ERR_RELAY_ADD);
+		}
+		detach_sys_mail_conf(conf_p);
+		if(ptradd){             
+        	        free(ptradd);
+                        ptradd = NULL;
+               	}
+		return -1;
+	}
+	
+	strcpy(conf_p->mrelay_server[i].hostname, relayhostname);
+	
+	if((mailertable_new_fpw = fopen(MAILERTABLE_FILE_NEW, "w")) == NULL){
+		if(cli_interactive()){
+			printf("Can not open file %s !", MAILERTABLE_FILE_NEW);
+		}
+		detach_sys_mail_conf(conf_p);
+		if(ptradd){             
+        	        free(ptradd);
+                        ptradd = NULL;
+               	}
+		return -1;
+	}
+
+	if(ptradd == NULL){
+		fprintf(mailertable_new_fpw, "%s     smtp:%s\n", conf_p->mrelay_server[i].hostname, conf_p->mrelay_server[i].relayserver);
+	}else {
+		for(i=0;i<MAX_MAIL_RELAY_NUM;i++){
+			if( strlen(conf_p->mrelay_server[i].hostname) <= 0)	{
+				break;
+			}
+			fprintf(mailertable_new_fpw, "%s     smtp:%s\n", conf_p->mrelay_server[i].hostname, conf_p->mrelay_server[i].relayserver);
+		}
+	} 
+	fclose(mailertable_new_fpw);
+
+	unlink(MAILERTABLE_FILE);
+	unlink(MAILERTABLE_DB);
+
+	if(rename(MAILERTABLE_FILE_NEW, MAILERTABLE_FILE) == -1){
+		detach_sys_mail_conf(conf_p);
+		if(ptradd){             
+        	        free(ptradd);
+                        ptradd = NULL;
+               	}
+		return -1;
+	}
+
+	if(conf_p->mrelay_status.relay_status == 1) {
+		/*printf("Mail relay module is on\n");*/
+		if( system("/usr/sbin/makemap hash " MAILERTABLE_DB " < " MAILERTABLE_FILE) != 0) {
+			detach_sys_mail_conf(conf_p);
+			if(ptradd) {
+				free(ptradd);
+				ptradd = NULL;
+			}
+			return -1;
+		}
+	}
+
+	conf_p->mrelay_status.relay_num += 1;
+
+	/*
+	i = strlen(relayserver) +50;
+	chadd = (char*)malloc(i*sizeof(char));
+	strcat(chadd, "The relay server ");
+	strcat(chadd, relayserver);
+	strcat(chadd, " was configured successfully!")
+	*/
+	if(ptradd) {
+		free(ptradd);
+		ptradd = NULL;
+	}
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int
+system_mail_relay_server_del(char * relayhostname)
+{
+	FILE *mailertable_new_fpw;
+	sys_mail_conf_t *conf_p = NULL;
+	char *ptrdel = system_mail_relay_get_config();
+	int i, j, k;
+	
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not del mail relay config (Internal error - 1)\n");
+		}
+		if(ptrdel){
+			free(ptrdel);
+			ptrdel = NULL;
+		}
+		return -1;
+	}
+
+	if(ptrdel == NULL){
+		if(cli_interactive()){
+			printf("Relay host %s was not configured", relayhostname);
+		}
+		detach_sys_mail_conf(conf_p);
+		if(ptrdel){
+			free(ptrdel);
+			ptrdel = NULL;
+		}
+		return -1;
+	}
+
+	if((mailertable_new_fpw = fopen(MAILERTABLE_FILE_NEW, "w")) == NULL){
+		if(cli_interactive()){
+			printf("Can not open file %s !", MAILERTABLE_FILE_NEW);
+		}
+		detach_sys_mail_conf(conf_p);
+		if(ptrdel){
+			free(ptrdel);
+			ptrdel = NULL;
+		}
+		return -1;
+	}
+
+	j = -1;
+	k = -1;
+	for( i = 0; i < MAX_MAIL_RELAY_NUM; i++ ){
+		if(strlen(conf_p->mrelay_server[i].hostname) <= 0){
+			if(j < 0){
+				if(cli_interactive()){
+					printf("Can not find the record, the relay host has not been configured!!");
+				}
+				detach_sys_mail_conf(conf_p);
+				return -1;
+			}
+			break;
+		}
+		if(strcasecmp(relayhostname, conf_p->mrelay_server[i].hostname) != 0){
+			fprintf(mailertable_new_fpw, "%s     smtp:%s\n", conf_p->mrelay_server[i].hostname, conf_p->mrelay_server[i].relayserver);
+			k++;
+		}else{
+			j = i;
+		}
+	}
+
+	fclose(mailertable_new_fpw);
+
+	unlink(MAILERTABLE_FILE);
+	unlink(MAILERTABLE_DB);
+
+	if(rename(MAILERTABLE_FILE_NEW, MAILERTABLE_FILE) == -1){
+		detach_sys_mail_conf(conf_p);
+		if(ptrdel){
+			free(ptrdel);
+			ptrdel = NULL;
+		}
+		return -1;
+	}
+
+	/*mailertable text is empty*/
+	if(k < 0) {
+		system_mail_relay_off();
+		conf_p->mrelay_status.relay_num = 0;
+		conf_p->mrelay_status.relay_status = 0;
+	}
+
+	if(conf_p->mrelay_status.relay_status == 1) {
+		/*printf("Mail relay module is on\n");*/
+		if( system("/usr/sbin/makemap hash " MAILERTABLE_DB " < " MAILERTABLE_FILE) != 0) {
+			detach_sys_mail_conf(conf_p);
+			if(ptrdel) {
+				free(ptrdel);
+				ptrdel = NULL;
+			}
+			return -1;
+		}
+	}
+
+	if(ptrdel)	{
+		free(ptrdel);
+		ptrdel = NULL;
+	}
+
+	/*
+	i = strlen(relayserver) +100;
+	chadd = (char*)malloc(i*sizeof(char));
+	strcat(chadd, "The relay configuration record ");
+	strcat(chadd, conf_p->mrelay_server[j].hostname);
+	strcat(chadd, " ");
+	strcat(chadd, conf_p->mrelay_server[j].relayserver);
+	strcat(chadd, " ");
+	strcat(chadd, " was deleted successfully!")
+	*/
+	
+	
+	detach_sys_mail_conf(conf_p);
+	return 0;
+	
+}
+
+char *
+write_system_mail_relay(char *segment)
+{
+	sys_mail_conf_t *conf_p = NULL;
+	char *ptrwri = system_mail_relay_get_config(); 
+	char *currptr, *saveptr;
+	char p[MAX_MAIL_RELAY_SERVER+1];
+	char *p1,*p2;
+	int i;
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not write mail relay config (Internal error - 1)\n");
+		}
+		if(ptrwri){
+			free(ptrwri);
+			ptrwri = NULL;
+		}
+		return NULL;
+	}
+
+	saveptr = (char *) malloc(50*(sizeof(conf_p->mrelay_server) + 20) +30);
+	if (saveptr == NULL) {
+		if(cli_interactive()){
+			printf("malloc error\n");
+		}
+		detach_sys_mail_conf(conf_p);
+		if(ptrwri){
+			free(ptrwri);
+			ptrwri = NULL;
+		}
+		return NULL;
+	}
+	currptr = saveptr;	
+
+	for( i = 0; i< MAX_MAIL_RELAY_NUM; i++)	{
+		if(strlen(conf_p->mrelay_server[i].hostname) <= 0){
+			break;
+		} else {
+			if(conf_p->mrelay_server[i].relayserver[0] != '[')	{
+				currptr += sprintf(currptr, "system mail relay server \"%s\" \"%s\"\n", conf_p->mrelay_server[i].hostname, conf_p->mrelay_server[i].relayserver);
+			}else{
+				p1 = &(conf_p->mrelay_server[i].relayserver[1]);
+				if ((p2 = strstr(conf_p->mrelay_server[i].relayserver, "]")) == NULL){
+					if(cli_interactive()){
+						printf("The relay server format is error!");
+					}
+					detach_sys_mail_conf(conf_p);
+					if(ptrwri){
+						free(ptrwri);
+						ptrwri = NULL;
+					}
+					free(saveptr);
+					return NULL;
+				}else{
+					memcpy(p, p1, (p2 - p1));
+					p[p2-p1] = '\0';
+					currptr += sprintf(currptr, "system mail relay server \"%s\" \"%s\"\n", conf_p->mrelay_server[i].hostname, p);
+				/*	
+					if(p)
+					{
+						free(p);
+						p = NULL;
+					}
+					*/
+				}
+
+			}
+		}
+	}
+
+	if(conf_p->mrelay_status.relay_status == 1)	{
+		currptr += sprintf(currptr, "system mail relay %s\n", "on");
+	}else{
+		currptr += sprintf(currptr, "system mail relay %s\n", "off");
+
+	}
+
+	*currptr = '\0';
+	
+	if(ptrwri)	{
+		free(ptrwri);
+		ptrwri = NULL;
+	}
+	detach_sys_mail_conf(conf_p);		
+	return(saveptr);
+}
+
+int
+system_mail_relay_off(void)
+{
+	sys_mail_conf_t *conf_p = NULL;
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not turn off mail relay (Internal error - 1)\n");
+		}
+		return -1;
+	}
+	if( system("rm -f " MAILERTABLE_DB) != 0){
+		if(cli_interactive()){
+			printf("Can not delete the db file for relay server!");
+		}
+		return -1;
+	}
+
+	conf_p->mrelay_status.relay_status = 0;
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+int
+system_mail_relay_on(void)
+{
+	sys_mail_conf_t *conf_p = NULL;
+	char *ptron = system_mail_relay_get_config();
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not turn on mail relay (Internal error - 1)\n");
+		}
+		if(ptron){
+			free(ptron);
+			ptron = NULL;
+		}
+		return -1;
+	}
+
+	if(ptron == NULL){
+		if(cli_interactive()){
+			printf("No configured relay server!\n");
+		}
+		conf_p->mrelay_status.relay_status = 0;
+		detach_sys_mail_conf(conf_p);
+		if(ptron){
+			free(ptron);
+			ptron = NULL;
+		}
+		return -1;
+	}
+	
+	if( system("/usr/sbin/makemap hash " MAILERTABLE_DB " < " MAILERTABLE_FILE) != 0) {
+		if(cli_interactive()){
+			printf("Can not enable the relay servers!\n");
+		}
+		detach_sys_mail_conf(conf_p);
+		if(ptron){
+			free(ptron);
+			ptron = NULL;
+		}
+		return -1;
+	}
+
+	if(ptron)	{
+		free(ptron);
+		ptron = NULL;
+	}
+	
+	conf_p->mrelay_status.relay_status = 1;
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int
+system_mail_external_on(void)
+{
+	sys_mail_conf_t *conf_p = NULL;
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not turn on external mail(Internal error - 1)\n");
+		}
+		return -1;
+	}
+
+	if (conf_p->mextern_server.extern_server[0] == '\0') {
+		if (cli_interactive()) {
+			printf("Please config an external mail server first.\n");
+		}
+		detach_sys_mail_conf(conf_p);
+		return -1;
+	}
+
+	conf_p->extern_mail_on = 1;
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int
+system_mail_external_off(void)
+{
+	sys_mail_conf_t *conf_p = NULL;
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not turn off external mail(Internal error - 1)\n");
+		}
+		return -1;
+	}
+
+	conf_p->extern_mail_on = 0;
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int
+system_mail_external_server(char *server_addr, uint16_t port, uint16_t use_ssl)
+{
+	char tmp_addr[MAX_MAIL_EXTERN_SERVER_LEN + sizeof(":65535")];
+	sys_mail_conf_t *conf_p = NULL;
+
+	if (server_addr == NULL || server_addr[0] == '\0') {
+		if (cli_interactive()) {
+			printf("server_address can not be NULL or empty\n");
+		}
+		return -1;
+	}
+
+	if (strlen(server_addr) > MAX_MAIL_EXTERN_SERVER_LEN) {
+		if (cli_interactive()) {
+			printf("server_address exceeds the length limit: %d\n", MAX_MAIL_EXTERN_SERVER_LEN);
+		}
+		return -1;
+	}
+
+	if (check_external_mail_string(server_addr) == CHARACTER_INVALID) {
+		return -1;
+	}
+
+	if (snprintf(tmp_addr, sizeof(tmp_addr), "%s:%u", server_addr, port) >= sizeof(tmp_addr)) {
+		if (cli_interactive()) {
+			printf("server_address:port exceeds the length limit: %lu\n", sizeof(tmp_addr));
+		}
+		return -1;
+	}
+
+	if (use_ssl != 0 && use_ssl != 1) {
+		if (cli_interactive()) {
+			printf("This ssl flag can only be 0 or 1\n");
+		}
+		return -1;
+	}
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not config external mail server(Internal error - 1)\n");
+		}
+		return -1;
+	}
+	ssmtp_conf_file_update(conf_p);
+
+	char cmd[256];
+	#ifdef UOS_X86
+	snprintf(cmd, sizeof(cmd), "%s edit_server %s %hu %u", SSMTP_SCRIPT, server_addr, port, use_ssl);
+	#else
+	snprintf(cmd, sizeof(cmd), "%s edit_server %s %u", SSMTP_SCRIPT, tmp_addr, use_ssl);
+    #endif
+	
+	if (system(cmd)) {
+		if (cli_interactive()) {
+			printf("Could not config external mail server(Internal error - 2)\n");
+		}
+		detach_sys_mail_conf(conf_p);
+		return -1;
+	}
+
+	strcpy(conf_p->mextern_server.extern_server, server_addr);
+	conf_p->mextern_server.port = port;
+	conf_p->mextern_server.use_ssl = use_ssl;
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int
+system_mail_external_user(char *user, char *passwd)
+{
+	sys_mail_conf_t *conf_p = NULL;
+
+	if (user == NULL || user[0] == '\0' || passwd == NULL || passwd[0] == '\0') {
+		if (cli_interactive()) {
+			printf("user and password can not be NULL or empty\n");
+		}
+		return -1;
+	}
+
+	if (strlen(user) > MAX_MAIL_USER_LEN) {
+		if (cli_interactive()) {
+			printf("user name %s exceeds the length limit: %d\n", user, MAX_MAIL_USER_LEN);
+		}
+		return -1;
+	}
+
+	if (check_external_mail_string(user) == CHARACTER_INVALID) {
+		return -1;
+	}
+
+	if (check_external_mail_string(passwd) == CHARACTER_INVALID) {
+		return -1;
+	}
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not config external mail server(Internal error - 1)\n");
+		}
+		return -1;
+	}
+	ssmtp_conf_file_update(conf_p);
+
+	int input_from_ca = 0;
+	char orig_passwd[MAX_MAIL_PASSWD_LEN + 1];
+	char mask_passwd[MAX_MAIL_ENCRPT_PASSWD_LEN + 1];
+	strcpy(mask_passwd, ENCRYPT_PASSWD_PREFIX);
+	char key[MAX_MAIL_USER_LEN + sizeof(RANDOM_KEY) + 3];
+	snprintf(key, sizeof(key), "%s@%s", user, RANDOM_KEY);
+	char cmd[256];
+
+	if (strncmp(passwd, ENCRYPT_PASSWD_PREFIX, ENCRYPT_PASSWD_PREFIX_LEN) == 0) {
+		/*We get password from ca.conf*/
+		input_from_ca = 1;
+		if (strlen(passwd) > MAX_MAIL_ENCRPT_PASSWD_LEN) {
+			/*This should never happen*/
+			if (cli_interactive()) {
+				printf("password %s exceeds the length limit: %lu\n", passwd, MAX_MAIL_ENCRPT_PASSWD_LEN);
+			}
+			detach_sys_mail_conf(conf_p);
+			return -1;
+		}
+
+		if (decrypt_passwd((unsigned char *)passwd + ENCRYPT_PASSWD_PREFIX_LEN, key, orig_passwd, sizeof(orig_passwd))) {
+			if (cli_interactive()) {
+				printf("password %s decrypt fail!\n", passwd);
+			}
+			detach_sys_mail_conf(conf_p);
+			return -1;
+		}
+
+		snprintf(cmd, sizeof(cmd), "%s edit_user %s %s", SSMTP_SCRIPT, user, orig_passwd);
+	} else {
+		/*we get password from user*/
+		if (strlen(passwd) > MAX_MAIL_PASSWD_LEN) {
+			if (cli_interactive()) {
+				printf("password %s exceeds the length limit: %d\n", passwd, MAX_MAIL_PASSWD_LEN);
+			}
+			detach_sys_mail_conf(conf_p);
+			return -1;
+		}
+
+		if (encrypt_passwd((unsigned char*)passwd, key, mask_passwd + ENCRYPT_PASSWD_PREFIX_LEN, sizeof(mask_passwd) - ENCRYPT_PASSWD_PREFIX_LEN)) {
+			if (cli_interactive()) {
+				printf("password %s encrypt fail!\n", passwd);
+			}
+			detach_sys_mail_conf(conf_p);
+			return -1;
+		}
+
+		snprintf(cmd, sizeof(cmd), "%s edit_user %s %s", SSMTP_SCRIPT, user, passwd);
+	}
+
+	if (system(cmd)) {
+		if (cli_interactive()) {
+			printf("Could not config external mail server(Internal error - 2)\n");
+		}
+		detach_sys_mail_conf(conf_p);
+		return -1;
+	}
+
+	strcpy(conf_p->mextern_server.user, user);
+	if (input_from_ca) {
+		strcpy(conf_p->mextern_server.passwd, passwd);
+	} else {
+		strcpy(conf_p->mextern_server.passwd, mask_passwd);
+	}
+
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int
+no_system_mail_external_server(void)
+{
+	sys_mail_conf_t *conf_p = NULL;
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not config external mail server(Internal error - 1)\n");
+		}
+		return -1;
+	}
+
+	/*we turn off external server first*/
+	conf_p->extern_mail_on = 0;
+	conf_p->mextern_server.extern_server[0] = '\0';
+	conf_p->mextern_server.port = 0;
+	conf_p->mextern_server.use_ssl = 0;
+
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int
+no_system_mail_external_user(void)
+{
+	sys_mail_conf_t *conf_p = NULL;
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not config external mail server(Internal error - 1)\n");
+		}
+		return -1;
+	}
+
+	char cmd[256];
+	snprintf(cmd, sizeof(cmd), "%s no_user", SSMTP_SCRIPT);
+
+	if (system(cmd)) {
+		if (cli_interactive()) {
+			printf("Could not config external mail server(Internal error - 2)\n");
+		}
+		detach_sys_mail_conf(conf_p);
+		return -1;
+	}
+
+
+	conf_p->mextern_server.user[0] = '\0';
+	conf_p->mextern_server.passwd[0] = '\0';
+
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int
+show_system_mail_relay(void)
+{
+	sys_mail_conf_t *conf_p = NULL;
+	char *str = system_mail_relay_get_config();
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not show mail relay config (Internal error - 1)\n");
+		}
+		if(str){
+			free(str);
+			str = NULL;
+		}
+		return -1;
+	}
+
+	if(str != NULL){
+		if(conf_p->mrelay_status.relay_status == 1){
+			printf("Mail relay module is on\n");
+		}
+		printf("%s", str);
+	}
+	if(conf_p->mrelay_status.relay_status == 0){
+		printf("Mail relay module is off\n");
+	}
+
+	if(str){
+		free(str);
+		str = NULL;
+	}
+	
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int 
+clear_system_mail_relay(void)
+{
+	sys_mail_conf_t *conf_p = NULL;
+	FILE *mailertable_fpw;
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not clear mail relay config (Internal error - 1)\n");
+		}
+		return -1;
+	}
+
+	memset(conf_p->mrelay_server, 0x00, MAX_MAIL_RELAY_NUM*sizeof(mail_relay_server_t));
+
+	if( ( mailertable_fpw = fopen(MAILERTABLE_FILE_NEW, "w")) == NULL){
+		return -1;
+	}
+	
+	fprintf(mailertable_fpw, "%s", " ");
+	fclose(mailertable_fpw);
+
+	unlink(MAILERTABLE_FILE);
+	if(rename(MAILERTABLE_FILE_NEW, MAILERTABLE_FILE) == -1){
+		detach_sys_mail_conf(conf_p);
+		return -1;
+	}
+	unlink(MAILERTABLE_DB);
+
+	conf_p->mrelay_status.relay_status = 0;
+	conf_p->mrelay_status.relay_num = 0;
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+char *
+system_mail_relay_get_config(void)
+{
+	FILE *mailertable_fpr;
+	char *line;
+	char *con_str;
+	sys_mail_conf_t *conf_p = NULL;
+	int i,j, linenr, linehr;
+	int linelen;
+
+	i = 0;
+	linenr = 0;
+	linehr = 0;
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not get system mail relay config "
+			       "(Internal error)\n");
+		}
+		return NULL;
+	}
+
+	memset(conf_p->mrelay_server, 0x00, MAX_MAIL_RELAY_NUM*sizeof(mail_relay_server_t));
+
+	if(( mailertable_fpr = fopen(MAILERTABLE_FILE, "r")) == NULL){
+		if(cli_interactive()){
+			printf("The mailertable file can not be opened or do not exist!\n");
+		}
+		detach_sys_mail_conf(conf_p);
+		return NULL;
+	}
+
+	if((line = (char*)malloc(500*sizeof(char))) == NULL){
+		if(cli_interactive()){
+			printf("Can not malloc memory!\n");
+		}
+		detach_sys_mail_conf(conf_p);
+		fclose(mailertable_fpr);
+		return NULL;
+	}
+	while( fgets(line, 500*sizeof(char), mailertable_fpr)){
+		linenr += 1;
+		linelen = strlen(line);
+		if(line[0] == '#' ||(line[0] == ' ') || (line == NULL)){
+			continue;
+		}else{
+			if((strstr( line, "smtp")) == NULL){
+				continue;
+			}
+			i = 0;
+			while((line[i] != ' ') && (line[i]) != '\t'){
+				conf_p->mrelay_server[linehr].hostname[i] = line[i];
+				i +=1;
+			}
+			conf_p->mrelay_server[linehr].hostname[i] = '\0';
+
+			while(line[i] != ':'){
+				i += 1;
+			}
+			i += 1;
+/*
+			if(line[i] == '[')
+			{
+				i += 1;
+				j = 0;
+				while(line[i] != ']')
+				{
+					conf_p->mrelay_server[linehr].relayserver[j] = line[i];
+					i += 1;
+					j += 1;
+				}
+				conf_p->mrelay_server[linehr].relayserver[j] = '\0';
+			}
+*/
+			j = 0;
+			while(line[i] != '\0' && line[i] != '\n'){
+				conf_p->mrelay_server[linehr].relayserver[j] = line[i];
+				i += 1;
+				j += 1;
+			}
+			conf_p->mrelay_server[linehr].relayserver[j+1] = '\0';
+			linehr += 1;
+		}
+	}
+
+	conf_p->mrelay_status.relay_num = linehr;
+/*	if((conf_p->mrelay_status.relay_num > 0) && (conf_p->mrelay_status.relay_status == 0)){
+		conf_p->mrelay_status.relay_status = 1;
+	}
+*/
+	if(linehr < 1){
+		detach_sys_mail_conf(conf_p);
+		fclose(mailertable_fpr);
+		free(line);
+		return NULL;
+	}
+	
+	con_str = (char*)malloc((linehr)*sizeof(mail_relay_server_t)+linehr*10);
+	bzero(con_str, ((linehr)*sizeof(mail_relay_server_t)+linehr*10));
+	for(i=0; i<conf_p->mrelay_status.relay_num; i++){
+		strcat(con_str, conf_p->mrelay_server[i].hostname);
+		strcat(con_str, "  ----->  ");
+		strcat(con_str, conf_p->mrelay_server[i].relayserver);
+		strcat(con_str, "\n");
+	}
+ 	detach_sys_mail_conf(conf_p);	
+	fclose(mailertable_fpr);
+	free(line);
+	return con_str;
+}
+
+/* end add 10914 */
+
+int
+system_mail_from(char *from_string)
+{
+	int len = strlen(from_string);
+	sys_mail_conf_t *conf_p;
+
+	if (len == 0) {
+		printf("From string cannot be empty\n");
+		return 0;
+	}
+
+	if (len > MAX_MAIL_FROM_LEN) {
+		printf("Length of from string cannot be greater than %d\n",
+		       MAX_MAIL_FROM_LEN);
+		return 0;
+	}
+
+	if (check_from_string(from_string) == -1) {
+		return 0;
+	}
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		printf("Could not set from string (Internal error)\n");
+		return 0;
+	}
+
+	strcpy(conf_p->from, from_string);
+
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int
+system_mail_hostname(char *hostname, unsigned int hostname_behavior)
+{
+	int len = strlen(hostname);
+	sys_mail_conf_t *conf_p;
+
+	if (len == 0) {
+		printf("Hostname cannot be empty\n");
+		return 0;
+	}
+
+	if (len > MAX_MAIL_HOSTNAME_LEN) {
+		printf("Length of hostname cannot be greater than %d\n",
+		       MAX_MAIL_HOSTNAME_LEN);
+		return 0;
+	}
+	
+	if (strchr(hostname, '.') == NULL) {
+		printf("Hostname must be a fully qualified domain name (FQDN).\n");
+		return 0;
+	}
+
+	if (check_hostname_string(hostname) == -1) {
+		return 0;
+	}
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		printf("Could not set hostname (Internal error - 1)\n");
+		return 0;
+	}
+
+	strcpy(conf_p->hostname, hostname);
+	conf_p->hostname_behavior = hostname_behavior;
+	if (write_fqdn_to_file() == -1) {
+		printf("Could not set hostname (Internal error - 2)\n");
+		detach_sys_mail_conf(conf_p);
+		return 0;
+	}
+
+	/*rewrite sendmail.cf file, Dj domain.The Dj item is the domain name*/
+	if (write_hostname_to_file(conf_p->hostname) == -1) {
+		printf("Could not set hostname (Internal error - 2)\n");
+		detach_sys_mail_conf(conf_p);
+		return 0;
+	}
+	/*change sendmail.cf file, need to restart sendmail */
+	system("systemctl restart sendmail");
+
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int
+no_system_mail_from(void)
+{
+	sys_mail_conf_t *conf_p = NULL;
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		printf("Could not set from string to default (Internal error)\n");
+		return 0;
+	}
+
+	strcpy(conf_p->from, DEF_MAIL_FROM);
+
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int
+no_system_mail_hostname(void)
+{
+	sys_mail_conf_t *conf_p = NULL;
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		printf("Could not set hostname to default (Internal error - 1)\n");
+		return 0;
+	}
+
+	strcpy(conf_p->hostname, DEF_MAIL_HOSTNAME);
+	if (0 == conf_p->hostname_behavior) {
+		/* init sendmail.cf file. Dj $w.alert_pseudo_domain.The Dj item is the domain name*/
+		if (write_hostname_to_file(DEF_MAIL_HOSTNAME) == -1) {
+			printf("Could not set hostname to default (Internal error - 2)\n");
+			detach_sys_mail_conf(conf_p);
+			return 0;
+		}
+	
+		if (write_fqdn_to_file() == -1) {
+			printf("Could not set hostname to default (Internal error - 2)\n");
+			detach_sys_mail_conf(conf_p);
+			return 0;
+		}
+		/*change sendmail.cf file, need to restart sendmail */
+		system("systemctl restart sendmail"); 
+	}
+	/*reset hostname_behavior to default*/
+	conf_p->hostname_behavior = 0;
+
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int
+clear_system_mail_conf(void)
+{
+	sys_mail_conf_t *conf_p = NULL;
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not clear mail config (Internal error - 1)\n");
+		}
+		return 0;
+	}
+
+	strcpy(conf_p->hostname, DEF_MAIL_HOSTNAME);
+	if (0 == conf_p->hostname_behavior) {
+		if (write_hostname_to_file(DEF_MAIL_HOSTNAME) != 0) {
+			if (cli_interactive()) {
+				printf("Could not clear mail config (Internal error - 2)\n");
+			}
+
+			detach_sys_mail_conf(conf_p);
+			return 0;
+		}
+
+		if (write_fqdn_to_file() != 0) {
+			if (cli_interactive()) {
+				printf("Could not clear mail config (Internal error - 2)\n");
+			}
+
+			detach_sys_mail_conf(conf_p);
+			return 0;
+		}
+		/*change sendmail.cf file, need to restart sendmail */
+		system("systemctl restart sendmail");
+	}
+
+	strcpy(conf_p->from, DEF_MAIL_FROM);
+	conf_p->hostname_behavior = 0;
+	conf_p->extern_mail_on = 0;
+	memset(&conf_p->mextern_server, 0, sizeof(conf_p->mextern_server));
+	system("cp -f /etc/ssmtp/ssmtp.conf /var/run/ssmtp.conf");
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+int
+show_system_mail_conf(void)
+{
+	char *str = write_system_mail_conf("");
+
+	if (str) {
+		printf("%s", str);
+		free(str);
+	}
+
+	return 0;
+}
+
+char *
+write_system_mail_conf(char *segment)
+{
+	int n = 0;
+	char *str = NULL;
+	sys_mail_conf_t *conf_p = NULL;
+
+	str = (char *)malloc(WRITE_STR_LEN * sizeof(char));
+	if (str == NULL) {
+		return NULL;
+	}
+
+	conf_p = attach_sys_mail_conf();
+	if (conf_p == NULL) {
+		if (cli_interactive()) {
+			printf("Could not get system mail config "
+			       "(Internal error)\n");
+		}
+		free(str);
+		return NULL;
+	}
+
+	n += sprintf((str+n), "system mail from \"%s\"\n", conf_p->from);
+	n += sprintf((str+n), "system mail hostname \"%s\" %d\n", conf_p->hostname, conf_p->hostname_behavior);
+
+	if (conf_p->mextern_server.extern_server[0]) {
+		n += sprintf((str+n), "system mail external server \"%s\" %d %d\n",
+				conf_p->mextern_server.extern_server,
+				conf_p->mextern_server.port,
+				conf_p->mextern_server.use_ssl);
+	}
+
+	if (conf_p->mextern_server.user[0]) {
+		n += sprintf((str+n), "system mail external user \"%s\" \"%s\"\n",
+				conf_p->mextern_server.user,
+				conf_p->mextern_server.passwd);
+	}
+
+	if (conf_p->extern_mail_on) {
+		n += sprintf((str+n), "system mail external on\n");
+	} else {
+		n += sprintf((str+n), "system mail external off\n");
+	}
+
+	detach_sys_mail_conf(conf_p);
+	return str;
+}
+
+#define MAX_LINE_LEN                    1024
+
+int
+write_fqdn_to_file(void)
+{
+	char name[MAX_LONG_TOKEN_SIZE+1] = "";
+
+	gethostname(name, MAX_LONG_TOKEN_SIZE+1);
+	if (name[0] == 0) {
+		/* the hostname are not initialize */
+		return 0;
+	}
+
+	/* will upgrade the domain name at set_node_name() */
+	return set_node_name(name,0);
+}
+
+int
+write_hostname_to_file(char *hostname)
+{
+	int esc = 0, n = 0;
+	char *str = hostname;
+	char host[MAX_MAIL_HOSTNAME_LEN+MAX_LONG_TOKEN_SIZE+1];
+	char name[MAX_LONG_TOKEN_SIZE+1];
+	char buff[MAX_LINE_LEN+1];
+	FILE *fpr, *fpw;
+	char cmd[256] = {0};
+
+	bzero(host, (MAX_MAIL_HOSTNAME_LEN+1));
+	while (*str) {
+		if (esc == 1) {
+			esc = 0;
+			switch (*str) {
+			case 'h':
+				gethostname(name, MAX_LONG_TOKEN_SIZE+1);
+				n += sprintf((host+n), "%s", name);
+				break;
+
+			case 'l':
+				host[n++] = '$';
+				host[n++] = 'w';
+				break;
+
+			default:
+				break;
+			}
+		} else if (*str == '%') {
+			esc = 1;
+		} else {
+			host[n++] = *str;
+		}
+
+		str++;
+	}
+
+	if (access(SENDMAIL_CONF_FILE, F_OK) == 0) {
+		bzero(cmd, sizeof(cmd));
+		snprintf(cmd, sizeof(cmd), "rm -f %s", SENDMAIL_CONF_FILE);
+		system(cmd);
+	}
+	bzero(cmd, sizeof(cmd));
+	snprintf(cmd, sizeof(cmd), "/bin/cp %s %s", SENDMAIL_ORI_CONF_FILE, SENDMAIL_CONF_FILE);
+	system(cmd);
+
+	fpr = fopen(SENDMAIL_CONF_FILE, "r");
+	if (fpr == NULL) {
+		return -1;
+	}
+
+	fpw = fopen(SENDMAIL_CONF_NEW_FILE, "w");
+	if (fpw == NULL) {
+		fclose(fpr);
+		return -1;
+	}
+
+	while (fgets(buff, (MAX_LINE_LEN+1), fpr)) {
+		if (strstr(buff, SENDMAIL_HOSTNAME_DEF) == buff) {
+			fprintf(fpw, "%s %s\n", SENDMAIL_HOSTNAME_DEF, host);
+		} else {
+			fprintf(fpw, "%s", buff);
+		}
+	}
+
+	fclose(fpr); 
+	fclose(fpw);
+
+	if (rename(SENDMAIL_CONF_NEW_FILE, SENDMAIL_CONF_FILE) == -1) {
+		return -1;
+	}
+
+	return 0;
+}
+
+
+int
+sysmail_get_domainame(char * output, size_t len)
+{
+	int esc = 0, n = 0;
+	char *str, *p;
+	char host[MAX_MAIL_HOSTNAME_LEN+MAX_LONG_TOKEN_SIZE+1];
+	char name[MAX_LONG_TOKEN_SIZE+1];
+	char buff[MAX_LINE_LEN+1];
+	sys_mail_conf_t *conf_p;
+
+	conf_p = attach_sys_mail_conf();	
+	if (conf_p == NULL) {
+		snprintf(output, len, "Unknown");
+		return -1;
+	}
+
+	if (conf_p->hostname_behavior) {
+		detach_sys_mail_conf(conf_p);
+		return -1;
+	}
+
+	str = conf_p->hostname;
+	bzero(host, (MAX_MAIL_HOSTNAME_LEN+MAX_LONG_TOKEN_SIZE+1));
+	while (*str) {
+		if (esc == 1) {
+			esc = 0;
+			switch (*str) {
+			case 'h':
+				gethostname(name, MAX_LONG_TOKEN_SIZE+1);
+				n += sprintf((host+n), "%s", name);
+				break;
+
+			case 'l':
+				gethostname(name, MAX_LONG_TOKEN_SIZE+1);
+				p = name;	
+				while(*p && *p != '.') {
+					host[n++] = *p++;
+				}
+				break;
+
+			default:
+				break;
+			}
+		} else if (*str == '%') {
+			esc = 1;
+		} else {
+			host[n++] = *str;
+		}
+
+		str++;
+	}
+
+	if (strlen(host) > len) {
+		snprintf(output, len, "Unknown");
+		detach_sys_mail_conf(conf_p);
+		return -1;
+	} else {
+		strncpy(output, host, len);
+		host[len] = '\0';
+	}
+
+	detach_sys_mail_conf(conf_p);
+	return 0;
+}
+
+sys_mail_conf_t *
+attach_sys_mail_conf(void)
+{
+	int shm_id = 0;
+	sys_mail_conf_t *conf_p = NULL;
+
+	shm_id = shmget(SYS_MAIL_SHM_KEY, 0, 0);
+	if (shm_id == -1) {
+		return NULL;
+	}
+
+	conf_p = (sys_mail_conf_t *)shmat(shm_id, NULL, 0);
+	if (conf_p == (sys_mail_conf_t *)-1) {
+		return NULL;
+	}
+
+	return conf_p;
+}
+
+void
+detach_sys_mail_conf(sys_mail_conf_t *conf_p)
+{
+	shmdt(conf_p);
+}
+
+int
+check_from_string(char *from_str)
+{
+	int esc = 0;
+	char *str = from_str;
+
+	while (*str) {
+		if (esc == 1) {
+			esc = 0;
+			switch (*str) {
+			case 'h':
+			case 'q':
+			case '%':
+				break;
+
+			default:
+				printf("Unsupported escape sequence %%%c\n", *str);
+				return -1;
+			}
+		} else if (*str == '%') {
+			esc = 1;
+		}
+
+		str++;
+	}
+
+	if (esc == 1) {
+		printf("Unsupported escape sequence %%\n");
+		return -1;
+	}
+
+	return 0;
+}
+
+int
+check_hostname_string(char *hostname)
+{
+	int esc = 0, i = 0;
+	char *str = hostname;
+
+	while (*str) {
+		if (esc == 1) {
+			esc = 0;
+			switch (*str) {
+			case 'h':
+			case 'l':
+				break;
+
+			default:
+				printf("Unsupported escape sequence %%%c\n", *str);
+				return -1;
+			}
+		} else if (*str == '%') {
+			esc = 1;
+		} else {
+			for (i=0; host_unsupp_chars[i] != '\0'; i++) {
+				if (*str == host_unsupp_chars[i]) {
+					printf("Unsupported character '%c'\n", *str);
+					return -1;
+				}
+			}
+		}
+
+		str++;
+	}
+
+	if (esc == 1) {
+		printf("Unsupported escape sequence %%\n");
+		return -1;
+	}
+
+	return 0;
+}
+
+int
+check_external_mail_string(char *name)
+{
+	char *str = name;
+
+	while (*str) {
+		switch (*str) {
+			case '(':
+			case ')':
+			case '&':
+			case ';':
+			case '<':
+			case '>':
+			case '\'':
+				printf("Unsupported character '%c'\n", *str);
+				return CHARACTER_INVALID;
+
+			default:
+				break;
+		}
+		str++;
+	}
+
+	return CHARACTER_VALID;
+}
+
+int ssmtp_conf_file_update(sys_mail_conf_t *conf_p)
+{	
+	char cmd[128];
+	
+	if (!conf_p) {
+		return 0;
+	}
+
+	/*If extern server configed, do not update*/
+	if (conf_p->mextern_server.extern_server[0] || 
+		conf_p->mextern_server.user[0]) {
+		return 0;
+	}	
+	
+	/*We cover it with ssmtp.conf.def */
+	snprintf(cmd, sizeof(cmd) -1, "/usr/bin/cp %s %s", SSMTP_CONF_DEF, SSMTP_CONF);
+	system(cmd);
+
+	return 1;
+}
+

Property changes on: src/library/ca_mail/sys_mail.c
___________________________________________________________________
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: /branches/rel_avx_2_7_4/src/library/ca_regex/Makefile
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_regex/Makefile	(revision 0)
+++ /branches/rel_avx_2_7_4/src/library/ca_regex/Makefile	(working copy)
@@ -0,0 +1,29 @@
+# ArrayOS
+
+TOP = ../../..
+
+include ${TOP}/Makefile.master
+
+SRCS=   avx_regex.c patricia.c regexp_match.c
+INCS=	avx_regex.h patricia.h regexp_match.h
+
+
+CC = gcc
+AR = ar
+RM = rm 
+
+CFLAGS+= -g -O0 -L/lib64 -L/usr/lib64
+
+
+all: avx_regex.o patricia.o regexp_match.o libcaregex.a
+avx_regex.o: avx_regex.c avx_regex.h
+	$(CC) $(CFLAGS) -c avx_regex.c
+patricia.o: patricia.c patricia.h
+	$(CC) $(CFLAGS) -c patricia.c
+regexp_match.o: regexp_match.c regexp_match.h
+	$(CC) $(CFLAGS) -c regexp_match.c
+libcaregex.a:
+	$(AR) rs libcaregex.a regexp_match.o patricia.o avx_regex.o
+
+clean:
+	$(RM) -f *.o *.core *.out *.a
Index: /branches/rel_avx_2_7_4/src/library/ca_regex/avx_regex.h
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_regex/avx_regex.h	(revision 0)
+++ /branches/rel_avx_2_7_4/src/library/ca_regex/avx_regex.h	(working copy)
@@ -0,0 +1,111 @@
+/*-----------------------------------------------------------------------------
+ *
+ * Copyright (C) 2002
+ * ClickArray Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification is not permitted unless authorized in writing by a duly
+ * appointed officer of ClickArray Inc. or its derivatives
+ *
+ * @(#) regex.h
+ *
+ * Modification History:
+ * $ArrayOS$ 
+ *
+ *-----------------------------------------------------------------------------
+ */
+#ifndef __REGEX_H__
+#define __REGEX_H__
+
+#include <sys/queue.h>
+#include "patricia.h"
+#include "regexp_match.h"
+
+#ifdef MALLOC_DECLARE
+MALLOC_DECLARE(M_REGEX_TREE);
+MALLOC_DECLARE(M_REGEX_NODE);
+#endif
+
+/* Allows us to use this code in userland and the kernel */
+#ifdef _KERNEL
+#define REGEX_MALLOC(var, type, size, m_type, m_flags) MALLOC(var, type, (size), m_type, m_flags)
+#define REGEX_FREE(var, malloc_type) FREE(var, malloc_type)
+#else
+#define REGEX_MALLOC(var, type, size, malloc_type, malloc_flags) var = (type)malloc(size)
+#define REGEX_FREE(var, malloc_type) free(var)
+#endif
+
+typedef patricia_tree_t regex_tree_t;
+
+/*
+ * This structure is used at the leaf of a patricia tree
+ * as a placeholder for a regular expression.
+ * If two regular expressions have the same prefix before
+ * the first *, then they will have the same node in the
+ * patricia tree. This structure is used to resolve this
+ * conflict by chaining regex nodes together.
+ */
+typedef struct _regex_node
+{
+    uint8_t *regular_expression;   
+	regexp* compiledReg;
+	SLIST_ENTRY(_regex_node) next_regex;
+	int perl_regex;
+    patricia_node_t *pat_node;
+    void *data;
+    struct _regex_node *next;
+	SLIST_ENTRY(_regex_node) next_match;
+} regex_node_t;
+
+/*
+ * This defines a function which is used to determine the relative
+ * ordering of two entities of the same type.
+ * Such a function is supplied by the client of the regex API so that
+ * the regex matching function can determine which regular expression best
+ * matches the input.
+ *
+ * It is assumed that this function will return:
+ * -1 if second parameter is "better" than the first
+ * 0 if they are "equal"
+ * 1 if the first parameter is "better" than the second
+ */
+typedef int32_t regex_node_cmp_t(void *, void *);
+int32_t host_rule_comp(void *cur_node, void *best_node);
+
+/*
+ * Used to pass results back to the client code
+ */
+SLIST_HEAD(regex_result_list, _regex_node); 
+
+SLIST_HEAD(regex_policy_list, _regex_node);
+
+typedef int (*regex_call_func_t) (regex_node_t *node, void* para);
+int regex_match_call(regex_tree_t *regex_tree, char *string, int32_t len, 
+			regex_call_func_t call_func, void* func_para);
+
+regex_tree_t 	*regex_tree_alloc(void);
+void 			regex_tree_free(regex_tree_t *tree);
+uint8_t 		regex_tree_empty(regex_tree_t *tree);
+regex_node_t 	*regex_insert(regex_tree_t *tree, char *pattern, int32_t len);
+regex_node_t 	*regex_insert_dup(regex_tree_t *tree, char *pattern, int32_t len);
+uint8_t 		regex_valid(char *regex, char *reason, int32_t max_reason_len);
+void 			regex_delete(regex_tree_t *tree, regex_node_t *node);
+struct 			regex_result_list *regex_match(regex_tree_t *regex_tree, 
+				                               char *string, int32_t len,
+				                               regex_node_cmp_t *node_compare,
+                                               int32_t *best_match_start,
+                                               int32_t *best_match_len);
+uint8_t         regex_search(char *string, int32_t string_len, char *regex,
+                             int32_t *match_len);
+
+struct regex_result_list *regex_match_list(struct regex_policy_list *head, char *string,
+                                      int32_t len,
+					                  regex_node_cmp_t *node_compare,
+					                  int32_t *best_match_start,
+                                      int32_t *best_match_len) ;
+#ifdef _KERNEL
+regex_node_t *regex_insert_list(struct regex_policy_list *head, char *pattern, int32_t len);
+
+void regex_delete_list(struct regex_policy_list *head, regex_node_t *regex_node);
+#endif
+#endif /* __REGEX_H__ */
Index: /branches/rel_avx_2_7_4/src/library/ca_regex/avx_regex.c
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_regex/avx_regex.c	(revision 0)
+++ /branches/rel_avx_2_7_4/src/library/ca_regex/avx_regex.c	(working copy)
@@ -0,0 +1,964 @@
+/*-----------------------------------------------------------------------------
+ *
+ * Copyright (C) 2002
+ * ClickArray Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification is not permitted unless authorized in writing by a duly
+ * appointed officer of ClickArray Inc. or its derivatives
+ *
+ * @(#) regex.c
+ *
+ * This file contains an API for doing simple regluar expression matching
+ * on strings.
+ *
+ * $ArrayOS$
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+#include <sys/param.h>
+
+#ifdef _KERNEL
+#include <sys/systm.h>
+#include <sys/malloc.h>
+#include <sys/kernel.h>
+#include <sys/unistd.h>
+#include <sys/param.h>
+#include <sys/mbuf.h>
+#include <sys/types.h>
+#include <sys/proc.h>
+#include <sys/kthread.h>
+#include <sys/sched.h>
+#include <sys/smp.h>
+#include <sys/taskqueue.h>
+#include <sys/sbuf.h>
+#include <sys/libkern.h>
+
+#else
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <limits.h>
+#endif
+
+#include "avx_regex.h"
+#include "patricia.h"
+
+extern regexp *regcomp(char *exp);
+
+#ifdef MALLOC_DEFINE
+MALLOC_DEFINE(M_REGEX_NODE, "regex_node_t",	"regex tree node");
+MALLOC_DEFINE(M_REGEX_TREE, "regex_tree_t", "regex tree");
+#endif
+
+#define TRUE   1
+#define FALSE  0
+
+
+/* We store a list of matching regular expressions here while searching */
+#define ATCP_MAXTHREADS 10
+static struct regex_result_list regex_matches_array[ATCP_MAXTHREADS];
+
+#ifndef _HC_REGEX
+	#define regex_matches  regex_matches_array[0]
+#else
+	#ifndef _KERNEL
+	/*uproxy: cpuid, BSD kernel: curatcp*/
+	extern __thread int cpuid;
+	#define regex_matches  regex_matches_array[cpuid]
+	#else
+	#define regex_matches  regex_matches_array[curatcp]
+	#endif
+#endif
+
+
+
+/*static uint8_t regex_search(char *string, int32_t string_len, char *regex);*/
+/**
+  *when called this function, the first arguments must be the current node
+  *because, we used this node to find whether it is already exist in the list
+  */
+int32_t
+host_rule_comp(void *cur_node, void *best_node)
+{
+	regex_node_t *regex_node_p;
+	/* the same node , return 0*/
+	if(cur_node == best_node)
+		return 0;
+	/*find whether the node is in the list*/
+	SLIST_FOREACH(regex_node_p, &regex_matches, next_match){
+		if(cur_node == regex_node_p->data){
+    		return 0;
+		}
+	}
+	return 1;
+}
+
+/* ---[ regex_tree_alloc ]-----------------------------------------------------
+ * 
+ * Allocates memory for a regular expression tree.
+ * 
+ * Inputs: none
+ * Outputs: a pointer to the new tree, or NULL if the tree could not be
+ *          allocated.
+ */
+regex_tree_t *regex_tree_alloc(void)
+{
+	return patricia_tree_alloc();
+}
+
+/* ---[ regex_tree_free ]------------------------------------------------------
+ *
+ * Frees the memory for a regular expression tree.
+ * NOTE: this function assumes that all regular expressions have been deleted
+ * from the tree.
+ *
+ * Inputs: tree - a pointer to the tree to free
+ * Outputs: none
+ */
+void regex_tree_free(regex_tree_t *tree)
+{
+	patricia_tree_free(tree);
+}
+
+/* ---[ regex_tree_empty ]-----------------------------------------------------
+ *
+ * Checks to see if a regular expression tree is empty
+ *
+ * Inputs: tree - a pointer to the tree to check
+ * 
+ * Outputs: TRUE (1) if the tree is empty
+ *          FALSE (0) otherwise
+ */
+uint8_t regex_tree_empty(regex_tree_t *tree)
+{
+	return patricia_tree_empty(tree);
+}
+
+/* ---[ regex_insert ]---------------------------------------------------------
+ * 
+ * Inserts a new regluar expression to a regular expression tree.
+ * 
+ * Inputs: tree - a pointer to the tree to insert into
+ *         pattern - the regular expression to insert
+ *         len - the length of the expression to insert
+ *
+ * Outputs: a pointer to the regex node which was created as a result of the
+ *          insertion, or a pointer to an already existing regex node from
+ *          a previous insert of the same expression, or NULL if the insertion
+ *          failed.
+ */
+regex_node_t *regex_insert(regex_tree_t *tree, char *pattern, int32_t len)
+{
+	char *wildcard_pos, *start_pos;
+	patricia_node_t *pat_node;
+	regex_node_t *new_regex_node, *found_regex_node, *curr;
+
+	/* Create a new regex node */
+	REGEX_MALLOC(new_regex_node, regex_node_t *, sizeof(regex_node_t),
+				M_REGEX_NODE, M_NOWAIT);
+	if (new_regex_node == NULL) {
+		return NULL;
+	}
+
+	new_regex_node->perl_regex = 0;
+	/* Allocate the regular expression field of the node */
+	REGEX_MALLOC(new_regex_node->regular_expression, uint8_t *, 
+			   strlen(pattern) + 1, M_TEMP, M_NOWAIT);
+	if (new_regex_node->regular_expression == NULL) {
+		REGEX_FREE(new_regex_node, M_REGEX_NODE);
+		return NULL;
+	}
+
+	/* Store the expression received from the caller */
+	memcpy(new_regex_node->regular_expression, pattern, len + 1);
+
+	/*
+	 * We want the first string in the expression not including the caret.
+	 */
+	if (pattern[0] == '^') {
+		start_pos = pattern + 1;
+	} else {
+		start_pos = pattern;
+	}
+
+	/* Skip over leading *'s, or until the end of the expression */
+	while (*start_pos == '*' && *start_pos != '\0') {
+		start_pos++;
+	}
+
+	/* Get the length of the first string */
+	for (wildcard_pos = start_pos; *wildcard_pos != '\0'; wildcard_pos++) {
+		if(*wildcard_pos == '*' || *wildcard_pos == '$') {
+			break;
+		}
+	}
+
+	/* Insert the prefix into the patricia tree */
+	pat_node = patricia_insearch(tree, start_pos, 
+								wildcard_pos - start_pos, PATRICIA_INSERT);
+
+	if (pat_node == NULL) {
+		REGEX_FREE(new_regex_node->regular_expression, M_TEMP);
+		REGEX_FREE(new_regex_node, M_REGEX_NODE);
+		return NULL;
+	}
+
+	if (pat_node->data == NULL) {
+		/* 
+		 * Fresh insertion, which means there are no other regular expressions
+		 * with the same prefix 
+		 */
+		pat_node->data = new_regex_node;
+		new_regex_node->pat_node = pat_node;
+		new_regex_node->next = NULL;
+	} else {
+		/* 
+		 * One or more existing regular expressions have the same prefix.
+		 * Make sure there aren't any exact duplicates and insert this one
+		 * into the list.
+		 */
+
+		found_regex_node = (regex_node_t *)pat_node->data;
+		curr = found_regex_node;
+
+		while (curr != NULL) {
+			if (strcmp((char *)curr->regular_expression, 
+			           (char *)new_regex_node->regular_expression) == 0) 
+			{
+				/* Send back this one, since it is a duplicate */
+				REGEX_FREE(new_regex_node->regular_expression, M_TEMP);
+				REGEX_FREE(new_regex_node, M_REGEX_NODE);
+				return curr;
+			}
+			curr = curr->next;
+		}
+
+		/* Put the new regex node into the tree */
+		new_regex_node->next = found_regex_node->next;
+		found_regex_node->next = new_regex_node;
+		new_regex_node->pat_node = pat_node;
+	}
+
+	new_regex_node->data = NULL;
+
+	return new_regex_node;
+}
+
+/* We add a new function,this is different from regex_insert
+ * when we add two patterns into the tree,if the pattern is the same
+ * regex_insert return the same address,but the regex_insert_dup return
+ * different address,this is why we add this function
+ */
+regex_node_t *regex_insert_dup(regex_tree_t *tree, char *pattern, int32_t len)
+{
+        char *wildcard_pos, *start_pos;
+        patricia_node_t *pat_node;
+        regex_node_t *new_regex_node, *found_regex_node;
+
+        /* Create a new regex node */
+        REGEX_MALLOC(new_regex_node, regex_node_t *, sizeof(regex_node_t),
+                        M_REGEX_NODE, M_NOWAIT);
+        if (new_regex_node == NULL) {
+                return NULL;
+        }   
+
+        /* Allocate the regular expression field of the node */
+        REGEX_MALLOC(new_regex_node->regular_expression, uint8_t *,
+                        strlen(pattern) + 1, M_TEMP, M_NOWAIT);
+        if (new_regex_node->regular_expression == NULL) {
+                REGEX_FREE(new_regex_node, M_REGEX_NODE);
+                return NULL;
+        }  
+
+	/* Store the expression received from the caller */
+        memcpy(new_regex_node->regular_expression, pattern, len + 1);
+
+        /*
+         * We want the first string in the expression not including the caret.
+         */
+        if (pattern[0] == '^') {
+                start_pos = pattern + 1;
+        } else {
+                start_pos = pattern;
+        }
+
+        /* Skip over leading *'s, or until the end of the expression */
+        while (*start_pos == '*' && *start_pos != '\0') {
+                start_pos++;
+        }
+
+        /* Get the length of the first string */
+        for (wildcard_pos = start_pos; *wildcard_pos != '\0'; wildcard_pos++) {
+                if(*wildcard_pos == '*' || *wildcard_pos == '$') {
+                        break;
+                }
+        }
+	/* Insert the prefix into the patricia tree */
+        pat_node = patricia_insearch(tree, start_pos,
+                        wildcard_pos - start_pos, PATRICIA_INSERT);
+
+        if (pat_node == NULL) {
+                REGEX_FREE(new_regex_node->regular_expression, M_TEMP);
+                REGEX_FREE(new_regex_node, M_REGEX_NODE);
+                return NULL;
+        }
+
+	if (pat_node->data == NULL) {
+                /* 
+                 * Fresh insertion, which means there are no other regular expressions
+                 * with the same prefix 
+                 */
+                pat_node->data = new_regex_node;
+                new_regex_node->pat_node = pat_node;
+                new_regex_node->next = NULL;
+        } else {
+                /* 
+                 * One or more existing regular expressions have the same prefix.
+                 * Make sure there aren't any exact duplicates and insert this one
+                 * into the list.
+                 */
+                found_regex_node = (regex_node_t *)pat_node->data;
+
+                /* Put the new regex node into the tree */
+                new_regex_node->next = found_regex_node->next;
+                found_regex_node->next = new_regex_node;
+                new_regex_node->pat_node = pat_node;
+        }
+
+        new_regex_node->data = NULL;
+
+        return new_regex_node;
+}
+/* ---[ regex_valid ]----------------------------------------------------------
+ *
+ * Determines if a regular expression is valid, according to the following
+ * rules:
+ *
+ * 1. Consecutive meta characters (^, *, $) are not allowed
+ * 2. At least one non-meta character must exist
+ * 3. Caret (^) can only appear at the beginning of the expression
+ * 4. Dollar ($) can only appear at the end of the expression
+ *
+ * Inputs: regex - the regular expression to check
+ *         reason - a character buffer where the failure message will be
+ *                  stored in the event that the regex is invalid
+ *         max_reason_len - Maximum number of characters to store in reason.
+ *
+ * Outputs: TRUE (1) if the regular expression is valid
+ *          FALSE (0) if the regular expression is invalid according to the
+ *                    4 rules above. Also, a message indicating why the
+ *                    regex is invalid is stored in the reason array parameter.
+ */
+uint8_t regex_valid(char *regex, char *reason, int32_t max_reason_len)
+{
+	int i, len, num_non_meta = 0;
+
+	len = strlen(regex);
+	for (i = 0; i < len; i++) {
+
+		if (regex[i] == '^') {
+			/* Caret is only allowed at the beginning */
+			if (i != 0) {
+				if (reason != NULL) {
+					snprintf(reason, max_reason_len, "Invalid regular "
+							"expression: caret (^) is only allowed at "
+							"the beginning of the expression\n");
+				}
+				return 0;
+			}
+		} else if(regex[i] == '$') {
+			/* Dollar is only allowed at the end */
+			if(i != len-1) {
+				if (reason != NULL) {
+					snprintf(reason, max_reason_len, "Invalid regular "
+							"expression: dollar ($) is only allowed at "
+							"the end of the expression\n");
+				}
+				return 0;
+			}
+		} else if(regex[i] == '*') {
+			/* Consecutive meta characters are not allowed */ 
+			if(i != 0 && i != len-1 && 
+				(regex[i-1] == '*' || regex[i+1] == '*' ||
+				 regex[i-1] == '^' || regex[i+1] == '^' ||
+				 regex[i-1] == '$' || regex[i+1] == '$')) 
+			{
+				if (reason != NULL) {
+					snprintf(reason, max_reason_len, "Invalid regular "
+							"expression: consecutive meta characters are "
+							"not allowed\n");
+				}
+				return 0;
+			}
+		} else if(regex[i] != '*') {
+			num_non_meta++;
+		}
+	}
+
+	if (num_non_meta == 0) {
+		/* 
+		 * At least one non-meta character is required. Note that this
+		 * catches the "^$" case.
+		 */
+		if (reason != NULL) {
+			snprintf(reason, max_reason_len, "Invalid regular expression: "
+					"must contain at least one non-meta character\n");
+		}
+		return 0;
+	}
+
+	return 1;
+}
+
+/* ---[ regex_delete ]---------------------------------------------------------
+ *
+ * Deletes a regular expression from a regular expression tree
+ *
+ * Inputs: tree - a pointer to the tree to delete from
+ *         node - a pointer to the regex node of the expression to delete.
+ *    
+ * Outputs: none
+ */
+void regex_delete(regex_tree_t *tree, regex_node_t *node)
+{
+	regex_node_t *list_head, *regex_node, *prev_node;
+	patricia_node_t *pat_node;
+
+	regex_node = node;
+	pat_node = regex_node->pat_node;
+	list_head = (regex_node_t *)pat_node->data;
+
+	if (list_head == regex_node && regex_node->next == NULL) {
+		/* 
+		 * This is the only regular expression with this prefix,
+		 * so we can delete the prefix from the tree 
+		 */
+		patricia_delete(tree, pat_node->key, pat_node->len);
+	} else {
+		/* 
+		 * There are one or more regular expressions with the same prefix
+		 * before the first star. We need to find where this one is
+		 * in the list pointed to by the patricia tree and delete it.
+		 */
+
+		prev_node = NULL;
+
+		while (list_head != NULL) {
+			if (list_head == regex_node) {
+				if(prev_node == NULL) {
+					/* 
+					 * It's the first node in the list, so reset
+					 * the patricia node to point to the next node 
+					 */
+					pat_node->data = regex_node->next;
+				} else {
+					/* Twiddle with the links */
+					prev_node->next = regex_node->next;
+				}
+				break;
+			}
+
+			/* Move on to the next node */
+			prev_node = list_head;
+			list_head = list_head->next;
+
+			if (list_head == NULL) {
+				/* 
+				 * This should never happen. If it does, print a nice fat
+				 * debug message 
+		                 */
+			}
+		}
+	}
+
+	REGEX_FREE(regex_node->regular_expression, M_TEMP);
+	REGEX_FREE(regex_node, M_REGEX_NODE);
+}
+
+/* ---[ regex_match ]----------------------------------------------------------
+ *
+ * Matches a string against the regular expressions stored in a regular
+ * expression tree.
+ * 
+ * Inputs: tree - the regular expression tree to search
+ *         string - the string to match
+ *         len - the length of the string to match
+ *         node_compare - a pointer to a function which:
+ *
+ *            Takes two pointers to the same data type and returns:
+ *            1. 1 if the first parameter is "better" than the second
+ *            2. 0 if the parameters are "equal"
+ *            3. -1 if the second parameter is "better" than the first
+ *
+ *            "better" and "equal" in this case mean relative to the
+ *            data structures passed as parameters, which are specific to
+ *            the caller.
+ *            Note that it is possible to pass NULL for this parameter
+ *            (see output description below)
+ *          best_match_start - a pointer to an integer. If the function 
+ *            finds a matching substring in the input string, it will 
+ *            store the offset of the start of the substring in this 
+ *            variable. If NULL is passed, nothing will be stored.
+ *          best_match_len - a pointer to an integer. If the function
+ *            finds a matching substring in the input string, it will
+ *            store the length of the substring in this variable. If
+ *            NULL is passed, nothing will be stored.
+ *
+ * Outputs: a list of regular expression nodes corresponding to regular
+ *          expressions which matched the input string. If NULL is passed
+ *          as the node_compare parameter, this list will consist of every
+ *          expression which matched the input. If node compare is non-null,
+ *          the list will contain one regex node corresponding to the
+ *          expression which "best" matched the input, as determined by
+ *          the node_compare function. 
+ *			there're some changes about the output, if the node_compare parameter
+ *			is NULL, the list returned only contains one matched expression which
+ *			is first found from the tree, we 
+ *			are not sure whether it is the hightest priority or not.
+ *          If we want to return all the matched regex string, pass a psudo-compare 
+ *			function, which always return 1.
+ */
+struct regex_result_list *regex_match(regex_tree_t *regex_tree, char *string,
+                                      int32_t len,
+					                  regex_node_cmp_t *node_compare,
+                                      int32_t *best_match_start,
+                                      int32_t *best_match_len)
+{
+	int pre_len, len2;
+	char *prefix, *exp;
+	patricia_node_t *pat_node;
+	regex_node_t *curr_node, *best_node = NULL, *dup_node_p = NULL;
+	uint8_t match, dup_node = 0;
+	int32_t match_len, match_start;
+
+	prefix = string;
+
+	/* Start out with an empty result list */
+	SLIST_INIT(&regex_matches);
+
+	
+	/* For each prefix of the string */
+	for (pre_len = len; pre_len > 0; pre_len--) {
+
+		pat_node = patricia_insearch(regex_tree, prefix, pre_len,
+										PATRICIA_MATCH_PREFIX);
+
+		/* We've found a prefix which matches, now find exact matches */
+		if (pat_node != NULL) {
+
+			/* Restrict len2 to the remaining length for patricia_insearch */
+			len2 = pat_node->len;
+			if (len2 > pre_len) {
+				len2 = pre_len;
+			}
+
+			for ( ; len2 > 0; len2--) {
+
+				/* Do an exact match */
+				pat_node = patricia_insearch(regex_tree, prefix, len2, 0);
+
+				if (pat_node != NULL) {
+
+					/* We found a match */
+					curr_node = (regex_node_t *)pat_node->data;
+
+					/*
+					 * Must loop through all associated nodes, since more than
+					 * one regex may have the same prefix
+					 */
+					while (curr_node != NULL) {
+
+						/*
+						 * Optimization: if we've already found a match
+						 * against an expression which is better from the
+						 * caller's perspective, then there is no point in
+						 * seeing if the rest of this expression matches.
+						 */
+						if (best_node != NULL && node_compare != NULL &&
+							node_compare(curr_node->data, 
+										 best_node->data) <= 0) 
+						{
+							/* 
+							 * Here if the caller has a precedence and the
+							 * current node is worse than the previous best
+							 
+							      */
+							curr_node = curr_node->next;
+							continue;
+						} 
+
+						exp = (char *)curr_node->regular_expression;
+
+						/*
+						 * Check for the start anchor, only match if it is not
+						 * there or if we have it and are at the front of the
+						 * url.
+						 */
+						if (*exp != '^' || (*exp == '^' && prefix == string)) {
+   
+							if (*exp == '^' || *exp == '*') {
+								match = regex_search(prefix + pat_node->len,
+											pre_len - pat_node->len,
+											exp + 1 + pat_node->len,
+								            &match_len);
+								match_start = 0;
+								match_len += (pat_node->len + 
+								              (prefix - string));
+							} else {
+								match = regex_search(prefix + pat_node->len,
+											pre_len - pat_node->len,
+											exp + pat_node->len,
+								            &match_len);
+								match_start = prefix - string;
+								match_len += pat_node->len;
+							}
+   
+							if (match) {
+#if 0
+								printf("Matched %s\n", exp);
+#endif
+
+								/*avoid match twice and insert twice,we assume regex_matches is not circular here*/
+								SLIST_FOREACH(dup_node_p, &regex_matches, next_match){
+									if(curr_node == dup_node_p){
+										dup_node = 1;
+									}
+								}
+								if(!dup_node){
+									SLIST_INSERT_HEAD(&regex_matches, curr_node,next_match);
+								}
+
+								if (node_compare == NULL) {
+									/* 
+									 * The caller doesn't care about
+									 * which one matched, just that a match
+									 * was found
+									 */
+									if (best_match_start != NULL) {
+										*best_match_start = match_start;
+									}
+									if (best_match_len != NULL) {
+										*best_match_len = match_len;
+									}
+									return &regex_matches;
+								}
+
+								/* Recompute the best node */
+								if (best_node == NULL ||
+									node_compare(curr_node->data, 
+												 best_node->data) > 0)
+								{
+									if (best_match_start != NULL) {
+										*best_match_start = match_start;
+									}
+									if (best_match_len != NULL) {
+                                    	*best_match_len = match_len;
+									}
+									best_node = curr_node;
+								}
+							}
+#if 0
+							else {
+								printf("Did not match %s\n", exp);
+							}
+#endif
+						}
+						curr_node = curr_node->next;
+					} /* while curr_node != NULL */
+				} /* if pat_node != NULL (exact) */
+			} /* for len2-- */
+		}  /* if pat_node != NULL (prefix) */
+
+		prefix++;
+	} /* for pre_len-- */
+
+	return &regex_matches;
+}
+
+/* ---[ regex_match_call ]----------------------------------------------------------
+ *
+ * Matches a string against the regular expressions stored in a regular
+ * expression tree.
+ * 
+ * Inputs: tree - the regular expression tree to search
+ *         string - the string to match
+ *         len - the length of the string to match
+ *         call_func - a pointer to a customized function.
+ *			   call_func used to perform some customized actions and need
+ *		       two para: matched regular node and customized func_para
+ *		   func_para - customized para for call_func
+ *      
+ * Outputs:  0  	normal end
+ *	    others	call_func stop the regex match process
+ */
+int regex_match_call(regex_tree_t *regex_tree, char *string, int32_t len, 
+		     regex_call_func_t call_func, void* func_para)
+{
+	int pre_len, len2, ret;
+	char *prefix, *exp;
+	patricia_node_t *pat_node;
+	regex_node_t *curr_node;
+	uint8_t match;
+	int32_t match_len, match_start;
+
+	prefix = string;
+	
+	/* For each prefix of the string */
+	for (pre_len = len; pre_len > 0; pre_len--) {
+		pat_node = patricia_insearch(regex_tree, prefix, pre_len, PATRICIA_MATCH_PREFIX);
+		/* We've found a prefix which matches, now find exact matches */
+		if (pat_node != NULL) {
+			/* Restrict len2 to the remaining length for patricia_insearch */
+			len2 = pat_node->len;
+			if (len2 > pre_len) {
+				len2 = pre_len;
+			}
+
+			for ( ; len2 > 0; len2--) {
+
+				/* Do an exact match */
+				pat_node = patricia_insearch(regex_tree, prefix, len2, 0);
+				if (pat_node != NULL) {
+					/* We found a match */
+					curr_node = (regex_node_t *)pat_node->data;
+					/*
+					 * Must loop through all associated nodes, since more than
+					 * one regex may have the same prefix
+					 */
+					while (curr_node != NULL) {
+						exp = (char *)curr_node->regular_expression;
+						/*
+						 * Check for the start anchor, only match if it is not
+						 * there or if we have it and are at the front of the
+						 * url.
+						 */
+						if (*exp != '^' || (*exp == '^' && prefix == string)) {
+   
+							if (*exp == '^' || *exp == '*') {
+								match = regex_search(prefix + pat_node->len,
+											pre_len - pat_node->len,
+											exp + 1 + pat_node->len,
+								            &match_len);
+								match_start = 0;
+								match_len += (pat_node->len +  (prefix - string));
+							} else {
+								match = regex_search(prefix + pat_node->len,
+											pre_len - pat_node->len,
+											exp + pat_node->len,
+								            &match_len);
+								match_start = prefix - string;
+								match_len += pat_node->len;
+							}
+   
+							if (match) {
+#if 0
+								printf("Matched %s\n", exp);
+#endif
+								if ((ret = call_func(curr_node, func_para)) != 0) {
+									return ret;
+								}
+							}
+						}
+						curr_node = curr_node->next;
+					} /* while curr_node != NULL */
+				} /* if pat_node != NULL (exact) */
+			} /* for len2-- */
+		}  /* if pat_node != NULL (prefix) */
+
+		prefix++;
+	} /* for pre_len-- */
+
+	return 0;
+}
+
+/* ---[ regex_search ]---------------------------------------------------------
+ *
+ * Match a string against a regular expression
+ *
+ * Inputs: string - the string to match
+ *         string_len - length of the string to match
+ *         regex - the regular expression
+ *
+ * Outputs: TRUE (1) if the string matches the regular expression
+ *          FALSE (0) otherwise
+ */
+uint8_t regex_search(char *string, int32_t string_len, char *regex,
+                     int32_t *match_len)
+{
+	int i, j;
+
+	*match_len = string_len;
+
+	if (*regex == '*') {
+		/* Skip over leading *'s */
+		regex++;
+
+		/*
+		 * If the regular expression ended at this star, or if some crazy
+		 * sysadmin decided to tack a dollar sign on the end, then it
+		 * matches.
+		 */
+		if (*regex == '\0' || *regex == '$') {
+			return TRUE;
+		}
+	} else if (*regex == '$') {
+		/* If the regular expression is only a dollar, we are done */
+		if (string_len == 0) {
+			return TRUE;
+		} else {
+			return FALSE;
+		}
+	} else if (*regex == '\0') {
+		/* The empty regular expression matches all strings */
+		*match_len = 0;
+		return TRUE;
+	}
+
+	for(j = 0; j < string_len; j++) {
+		/* See if we have the start of a match */
+		if(string[j] == regex[0]) {
+			i = 1;
+
+			/* Keep going while the string is matching the expression */
+			while(regex[i] == string[j+i]) {
+				if(regex[i] == '\0') {
+					break;
+				}
+				i++;
+			}
+
+			if (regex[i] == '*') {
+				regex += (i + 1);	/* We matched part of the expression */
+
+				/* Skip over consecutive *'s */
+				while (*regex == '*' && *regex != '\0') {
+					regex++;
+				}
+
+				if (regex[0] == '\0') {
+					return TRUE;	 /* Reached end of expression */
+				}
+			} else if(regex[i] == '$' && regex[i+1] == '\0') {
+				if (j+i == string_len) {
+					return TRUE;	 /* End anchor matched */
+				}
+				/* We need to keep going until we hit the end */
+			} else if(regex[i] == '\0') {
+				*match_len = j + i;
+				return TRUE;		 /* Reached end of expression */
+			}
+		}
+	}
+
+	return FALSE;
+}
+
+struct regex_result_list *regex_match_list(struct regex_policy_list *head, char *string,
+                                      int32_t len,
+					                  regex_node_cmp_t *node_compare,
+					                  int32_t *best_match_start,
+                                      int32_t *best_match_len) {
+	regex_node_t *curr_node;
+	char *regex_string;
+	SLIST_INIT(&regex_matches);
+	
+	
+	REGEX_MALLOC(regex_string, char *, len + 1, M_TEMP, M_NOWAIT);
+	strncpy(regex_string, string, len + 1);
+
+	SLIST_FOREACH(curr_node, head, next_regex) {
+		if(uregexec(curr_node->compiledReg, regex_string))
+		{
+			if(SLIST_EMPTY(&regex_matches) || 
+				(node_compare != NULL && node_compare(curr_node->data, SLIST_FIRST(&regex_matches)->data) > 0)) {
+				SLIST_INSERT_HEAD(&regex_matches, curr_node, next_match);
+			} else {
+				SLIST_INSERT_AFTER(SLIST_FIRST(&regex_matches), curr_node, next_match);
+			}
+		}
+	}
+	
+	REGEX_FREE(regex_string, M_TEMP);
+	
+	if(!SLIST_EMPTY(&regex_matches)) {
+		if(best_match_start != NULL) {
+			*best_match_start = 0;
+		}
+		if(best_match_len != NULL) {
+			*best_match_len = len;
+		}
+	}
+	
+	return &regex_matches;
+}
+
+regex_node_t *regex_insert_list(struct regex_policy_list *head, char *pattern, int32_t len)
+{
+	regex_node_t *new_regex_node, *curr;
+	int regex_prefix_len = strlen("<regex>");
+	
+	/* Create a new regex node */
+	REGEX_MALLOC(new_regex_node, regex_node_t *, sizeof(regex_node_t),
+				M_REGEX_NODE, M_NOWAIT);
+	if (new_regex_node == NULL) {
+		return NULL;
+	}
+	new_regex_node->data = NULL;
+	new_regex_node->perl_regex = 1;
+	
+	new_regex_node->compiledReg = regcomp(pattern);
+	if(new_regex_node->compiledReg == NULL) {
+		REGEX_FREE(new_regex_node, M_REGEX_NODE);
+		return NULL;
+	}
+	
+	/* Allocate the regular expression field of the node */
+	REGEX_MALLOC(new_regex_node->regular_expression, uint8_t *, 
+			   strlen(pattern) + regex_prefix_len + 1, M_TEMP, M_NOWAIT);
+	if (new_regex_node->regular_expression == NULL) {
+		REGEX_FREE(new_regex_node, M_REGEX_NODE);
+		return NULL;
+	}
+
+	/* Store the expression received from the caller */
+	memcpy(new_regex_node->regular_expression, "<regex>", regex_prefix_len);
+	memcpy(new_regex_node->regular_expression + regex_prefix_len, pattern, len);
+	*(new_regex_node->regular_expression + regex_prefix_len + len) = '\0';
+
+	SLIST_FOREACH(curr, head, next_regex) {
+		if (strcmp((char *)curr->regular_expression, 
+			           (char *)new_regex_node->regular_expression) == 0) 
+		{
+			/* Send back this one, since it is a duplicate */
+			REGEX_FREE(new_regex_node->regular_expression, M_TEMP);
+			regfree(new_regex_node->compiledReg);
+			REGEX_FREE(new_regex_node, M_REGEX_NODE);
+			return curr;
+		}
+	}
+	SLIST_INSERT_HEAD(head,new_regex_node,next_regex);
+
+	return new_regex_node;
+}
+
+void regex_delete_list(struct regex_policy_list *head, regex_node_t *regex_node)
+{	
+	regex_node_t *curr_node;
+	if(regex_node != NULL) {
+		SLIST_FOREACH(curr_node, head, next_regex) {
+			if(curr_node == regex_node) {
+				SLIST_REMOVE(head, regex_node, _regex_node, next_regex);
+			}
+		}
+		if(regex_node->regular_expression) {
+			REGEX_FREE(regex_node->regular_expression, M_TEMP);
+		}
+		if(regex_node->compiledReg) {
+			regfree(regex_node->compiledReg);
+		}
+		REGEX_FREE(regex_node, M_REGEX_NODE);
+	}
+}
+

Property changes on: src/library/ca_regex/avx_regex.c
___________________________________________________________________
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: /branches/rel_avx_2_7_4/src/library/ca_regex/patricia.h
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_regex/patricia.h	(revision 0)
+++ /branches/rel_avx_2_7_4/src/library/ca_regex/patricia.h	(working copy)
@@ -0,0 +1,95 @@
+/*------------------------------------------------------------------------------
+ *
+ * Copyright (C) 2000
+ * ClickArray Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification is not permitted unless authorized in writing by a duly
+ * appointed officer of ClickArray Inc. or its derivatives
+ *
+ * @(#) patricia.h
+ * 
+ * This header files contains structure defintions and external function
+ * declarations for an implementation of the PATRICIA tree data structure.
+ * PATRICIA stands for "Practical Algorithm To Retrieve Information Coded In
+ * Alphanumeric".
+ *
+ * Modification History:
+ * 10/09/2001 jwood     created
+ *
+ *------------------------------------------------------------------------------
+ */
+#ifndef __PATRICIA_H__
+#define __PATRICIA_H__
+#include <netinet/in.h>
+
+#define KID_MASK_SIZE         8   /* There are 96 printable ASCII characters,
+                                   * so we need 96 bits. 96/32 = 3, so we need
+                                   * 3 32 bit integers for all the bits */
+#define MIN_DELETE_FRACTION    3   /* If the number of deleted nodes in the 
+                                    * tree is greater than the total divided 
+                                    * by this number, then rebuild the tree, 
+                                    * discarding deleted nodes. */
+
+#ifdef MALLOC_DECLARE
+MALLOC_DECLARE(M_PATRICIA_TREE);
+MALLOC_DECLARE(M_PATRICIA_NODE);
+MALLOC_DECLARE(M_PATRICIA_KID);
+#endif
+
+#define PATRICIA_MATCH_EXACT   0x00000000
+#define PATRICIA_INSERT        0x00000001
+#define PATRICIA_MATCH_PREFIX  0x00000002
+#define PATRICIA_DNS_INSERT 0x00000001
+#define PATRICIA_MATCH_DNS_PREFIX 0x00000100
+
+struct _patricia_node;
+struct _patricia_kid;
+
+/* This structure defines an entry in a patricia node's linked list of
+ * children. */
+typedef struct _patricia_kid
+{
+    char name; /* Single character identifying which child it is */
+    struct _patricia_node *node; 
+               /* The actual patricia node which is the child */
+    struct _patricia_kid *brother;
+               /* The next kid node in the list */
+} patricia_kid_t;
+
+/* This structure defines a node in the patricia tree */
+typedef struct _patricia_node
+{
+    char *key;    /* Unique key for this node */
+    char* real_hostname;/*the real key name including the '*' or '.'*/
+    int32_t len;  /* Length of the key */
+    int32_t idx;  /* When searching, examine idxth bit of search key when you
+                   * reach this node. Then follow the link in the kid list 
+                   * which corresponds to the character */
+    int32_t valid;        /* Has this node been deleted? */
+    patricia_kid_t *kids; /* List of children */
+    uint32_t kid_mask[KID_MASK_SIZE]; /* Bit string used to keep track of which
+                                       * characters have real links to 
+                                       * children for this node */
+    void *data;   /* Used by application which is using
+                   * the patricia tree to link the node
+                   * with other data structures */
+} patricia_node_t;
+
+/* This structure defines the head of a patricia tree */
+typedef struct _patricia_tree
+{
+    struct _patricia_node *root;  
+    uint32_t total_node_count;    
+    uint32_t invalid_node_count; /* Number of deleted nodes */
+} patricia_tree_t;
+
+patricia_tree_t *patricia_tree_alloc(void);
+void patricia_tree_free(patricia_tree_t *tree);
+uint8_t patricia_tree_empty(patricia_tree_t *tree);
+patricia_node_t *patricia_insearch(patricia_tree_t *tree, char new_key[],
+                                   int32_t len, uint32_t flags);
+void *patricia_delete(patricia_tree_t *tree, char key[], int32_t len);
+void patricia_clear(patricia_tree_t *tree);
+
+#endif /* __PATRICIA_H__ */
Index: /branches/rel_avx_2_7_4/src/library/ca_regex/patricia.c
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_regex/patricia.c	(revision 0)
+++ /branches/rel_avx_2_7_4/src/library/ca_regex/patricia.c	(working copy)
@@ -0,0 +1,940 @@
+/*-----------------------------------------------------------------------------
+ *
+ * Copyright (C) 2000
+ * ClickArray Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification is not permitted unless authorized in writing by a duly
+ * appointed officer of ClickArray Inc. or its derivatives
+ *
+ * @(#) patricia.c
+ *
+ * This file contains an implementation of a PATRICIA tree. PATRICIA stands
+ * for "Practical Algorithm To Retreive Informatinon Coded In Alphanumeric"
+ *
+ * Modification History:
+ * $ArrayOS$
+ *
+ *-----------------------------------------------------------------------------
+ */
+#ifdef _KERNEL
+#include <sys/param.h>
+#include <sys/systm.h>
+#include <sys/kernel.h>
+#include <sys/malloc.h>
+#else
+//#include <bsd/bsd.h>
+#include <sys/types.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
+#include <sys/queue.h>
+#include "patricia.h"
+
+#define TRUE    1
+#define FALSE   0
+
+#ifdef MALLOC_DEFINE
+MALLOC_DEFINE(M_PATRICIA_TREE, "patricia_tree_t", "A patricia tree");
+MALLOC_DEFINE(M_PATRICIA_NODE, "patricia_node_t", "A patricia tree node");
+MALLOC_DEFINE(M_PATRICIA_KID,  "patricia_kid_t",  "A patricia tree kid");
+#endif
+
+#ifdef _KERNEL
+#define PATRICIA_MALLOC(var, type, size, m_type, m_flags) MALLOC(var, type, (size), m_type, m_flags)
+#define PATRICIA_FREE(var, malloc_type) FREE(var, malloc_type)
+#else
+#define PATRICIA_MALLOC(var, type, size, malloc_type, malloc_flags) var = (type)malloc(size)
+#define PATRICIA_FREE(var, malloc_type) free(var)
+#endif
+
+static int32_t patricia_rebuild(patricia_tree_t *tree, uint8_t del_tree);
+static patricia_node_t *get_ath_kid(patricia_node_t *node, char a);
+static uint8_t node_has_kids(patricia_node_t *node);
+static uint8_t set_ath_kid(patricia_node_t *node, char a, 
+						   patricia_node_t *kid_node);
+static void clear_ath_kid(patricia_node_t *node, char a);
+static uint8_t node_is_prefix(char *key, int32_t len, patricia_node_t *node,uint32_t dns_match_flag);
+
+
+#define PATRICIA_FLAG_SET(x, y) ((x) & (y))
+
+/* ----[ kid_in_list ]----------------------------------------------------------
+ *
+ * kid_in_list() checks to see if a node has a link to a child node which
+ * corresponds to the given character. Each node has a set of masks, one for
+ * each printable ASCII character (32 to 126 for a total of 96 chars). If 
+ * the bit corresponding to the given character is set in the node's set,
+ * then the node has a node in it's kid list which corresponds to that
+ * character. The entire idea of doing this is to avoid a linear search
+ * through the kid list of a node when nothing will be found anyway.
+ *
+ * Inputs: node - pointer to the node in the tree
+ *		 ch   - the character to check
+ * Outputs: 0 if there is no node in the kid list of the tree node which
+ *			corresponds to ch.
+ *		  !0 otherwise.
+ */
+static __inline uint32_t kid_in_list(patricia_node_t *node, unsigned char ch)
+{
+	int x, y;
+		 
+	x = ch >> 5;   /* ch / 32 */
+	y = ch - (x << 5);	/* ch % 32 */
+
+	if (x >= KID_MASK_SIZE) {
+		return 0;
+	}
+				
+	return (node->kid_mask[x] & (1 << y));
+}
+
+/* ---[ kid_register ]----------------------------------------------------------
+ * 
+ * kid_register() sets the bit in a patricia node's mask which corresponds to
+ * the given character. Should be used when an entry is added to the node's
+ * kid list.
+ *
+ * Inputs: node - a pointer to the node in the tree
+ *		 ch   - the character to register
+ * Outputs: nothing
+ */
+static __inline void kid_register(patricia_node_t *node, unsigned char ch)
+{
+	int x, y;
+
+	x = ch >> 5;   /* ch / 32 */
+	y = ch - (x << 5);	/* ch % 32 */
+
+	if (x >= KID_MASK_SIZE) {
+		return;
+	}
+
+	node->kid_mask[x] |= (1 << y);
+}
+#if 0
+/* ---[ kid_deregister ]--------------------------------------------------------
+ * 
+ * kid_deregister() clears the bit in a patricia node's mask which corresponds
+ * to the given character. Should be used whan an entry is removed from the
+ * node's kid list.
+ *
+ * Inputs: node - a pointer to the node in the tree
+ *		 ch - the character to deregister
+ * Outputs: nothing
+ */
+   change the second parameter type to unsigned char*/
+
+static __inline void kid_deregister(patricia_node_t *node, unsigned char ch)
+{
+	int x, y;
+
+	x = ch >> 5;   /* ch / 32 */
+	y = ch - (x << 5);	/* ch % 32 */
+
+	if (x >= KID_MASK_SIZE) {
+		return;
+	}
+
+	node->kid_mask[x] &= ~(1 << y);
+}
+#endif
+
+static int32_t patricia_transfer(patricia_node_t *tree,
+								 patricia_tree_t *new_tree,
+								 uint8_t free_all);
+static patricia_node_t *patricia_node_alloc(char *key, int32_t len,
+											int32_t idx);
+static void patricia_node_free(patricia_node_t *node);
+
+static patricia_kid_t *kid_alloc(void);
+static void kid_free(patricia_kid_t *kid);
+
+/* ---[ patricia_tree_alloc ]---------------------------------------------------
+ * 
+ * patricia_tree_alloc() creates a new patricia tree head structure,
+ * initializes it, and returns a pointer to it.
+ *
+ * Inputs: nothing
+ * Outputs: A pointer to the new tree head structure
+ */
+patricia_tree_t *patricia_tree_alloc(void)
+{
+	patricia_tree_t *new_tree;
+
+	PATRICIA_MALLOC(new_tree, patricia_tree_t *, sizeof(patricia_tree_t),
+		   M_PATRICIA_TREE, M_NOWAIT);
+
+	if(new_tree != NULL) {
+		new_tree->root = NULL;
+		new_tree->total_node_count = 0;
+		new_tree->invalid_node_count = 0;
+	}
+
+	return new_tree;
+}
+
+/* ---[ patricia_tree_free ]----------------------------------------------------
+ * 
+ * patricia_tree_free() deletes an existing patricia tree, including all
+ * associated memory.
+ *
+ * Inputs: tree - a pointer to the tree to delete
+ * Outputs: nothing
+ */
+void patricia_tree_free(patricia_tree_t *tree)
+{
+	/* Remove all nodes from the tree */
+	patricia_rebuild(tree, TRUE);
+
+	PATRICIA_FREE(tree, M_PATRICIA_TREE);
+}
+
+/* ---[ patricia_tree_empty ]---------------------------------------------------
+ *
+ * Checks to see if a patricia tree has any nodes
+ *
+ * Inputs: tree - a pointer to the tree to check
+ * Outputs: TRUE (1) if the tree is empty,
+ *          FALSE (0) otherwise
+ */
+uint8_t patricia_tree_empty(patricia_tree_t *tree)
+{
+	return tree->total_node_count <= 0;
+}
+
+/* ---[ patricia_insearch ]-----------------------------------------------------
+ *
+ * patricia_insearch() searches a patricia tree for a given string. In the
+ * event of a failed search, this function can optionally insert the key into
+ * the tree.
+ *
+ * Inputs: tree - a pointer to the tree to search and/or insert into.
+ *		 new_key - the string to search/insert.
+ *		 len - the length of new_key, not including null termination
+ *		 flags - indicates special options. If the 0th bit is set,
+ *				 store the given key in the tree if it is not found. If
+ *				 the 1st bit is set, match prefixes when searching.
+ * Outputs: A point to the node which was found in the patricia tree. This node
+ *		  can then be used to point at some other data structure via its
+ *		  data field.
+ */
+patricia_node_t *patricia_insearch(patricia_tree_t *tree, char *new_key, 
+								   int32_t len, uint32_t flags)
+{
+	patricia_node_t *new_node = NULL, *parent, *kid_node, *long_prefix = NULL;
+	int32_t i = 0;
+	uint32_t dns_match_flag = 0;
+       
+      
+
+	if(new_key == NULL || len <= 0) {
+		return NULL;
+	}
+        if(flags == PATRICIA_MATCH_DNS_PREFIX) {
+
+                flags = PATRICIA_MATCH_PREFIX;
+                dns_match_flag = 1; /*We must diff the dns inserting with other inserting*/
+        }
+
+	if(tree->root == NULL) {
+		if(!PATRICIA_FLAG_SET(flags, PATRICIA_INSERT)) {  
+			/* We are searching, not inserting, so just return *
+			 * a failed search */
+			return NULL;
+		} 
+
+		/* 
+		 * Create a new node and make it the root 
+		 */
+		new_node = patricia_node_alloc(new_key, len, 0);
+		if(new_node == NULL) {
+			return NULL; 
+		}
+
+		new_node->valid = TRUE;
+
+		tree->root = new_node;
+		tree->total_node_count++;
+	} else {
+		/* Start at the root */
+		parent = tree->root;
+		kid_node = get_ath_kid(parent, new_key[0]);
+
+		if (PATRICIA_FLAG_SET(flags, PATRICIA_MATCH_PREFIX) && 
+		    tree->root->valid && node_is_prefix(new_key, len, tree->root,dns_match_flag)) 
+		{
+			long_prefix = tree->root;
+		}
+
+		/* Search the list, taking the appropriate child at each step */
+		while(parent->idx < kid_node->idx && kid_node->idx <= len) {
+			parent = kid_node;
+
+			/* If 'a' is a printable ASCII character and idx is the string
+			 * index at this level, the 'ath' kid of a node is the link to 
+			 * the child node which has that character at position idx in its
+			 * key.
+			 */
+
+			/* If the next character of the search key is supposed to be a 
+			 * null terminator, make sure that's what we search for.
+			 */
+			if(kid_node->idx == len) {
+				kid_node = get_ath_kid(kid_node, '\0');
+ 
+				if (PATRICIA_FLAG_SET(flags, PATRICIA_MATCH_PREFIX)) {
+					if ((!long_prefix || (kid_node->len > long_prefix->len)) &&
+					    kid_node->valid && 
+					    node_is_prefix(new_key, len, kid_node,dns_match_flag))
+					{
+				    	long_prefix = kid_node;
+					}
+				}
+			} else {
+				kid_node = get_ath_kid(kid_node, new_key[kid_node->idx]);
+
+				if (PATRICIA_FLAG_SET(flags, PATRICIA_MATCH_PREFIX)) {
+					patricia_node_t *tmp;
+
+					if (new_key[parent->idx] != '\0') {
+						tmp = get_ath_kid(parent, '\0');
+					} else {
+						tmp = kid_node;
+					}
+
+					if ((!long_prefix || (tmp->len > long_prefix->len)) &&
+					    tmp->valid && node_is_prefix(new_key, len, tmp,dns_match_flag))
+					{
+						long_prefix = tmp;
+					}
+				}
+			}
+		}
+
+		/* If we have an exact match, then return it. Remove the length 
+		 * check to match prefixes... 
+		 */
+		if(((PATRICIA_FLAG_SET(flags, PATRICIA_MATCH_PREFIX) && 
+			 !PATRICIA_FLAG_SET(flags, PATRICIA_INSERT)) || 
+			len == kid_node->len) && 
+			strncmp(new_key, kid_node->key,
+			        (kid_node->len > len) ? (len) : (kid_node->len)) == 0) {
+			if(dns_match_flag) {
+
+				if(kid_node->len > len) return long_prefix;
+			}
+			if(kid_node->valid) {
+				return kid_node;
+			} else if(PATRICIA_FLAG_SET(flags, PATRICIA_INSERT)) {
+				/* If we are inserting and we found a matching node which was
+				 * previously deleted, resurrect the node */
+				kid_node->valid = TRUE;
+				tree->invalid_node_count--;
+				return kid_node;
+			} else {
+				return long_prefix;
+			}
+		} else if (PATRICIA_FLAG_SET(flags, PATRICIA_MATCH_PREFIX) &&
+				   long_prefix != NULL) 
+		{
+			/* 
+			 * No need for another comparison, since we already do that
+			 * every time we set long_prefix.
+			 */
+			return long_prefix;
+		}
+				
+		if(kid_node->valid && len == kid_node->len && 
+		   strncmp(new_key, kid_node->key, len) == 0) {
+			return kid_node;
+		} else if(!PATRICIA_FLAG_SET(flags, PATRICIA_INSERT)) {
+			return NULL; 
+		}
+
+		/* Find out where the key to insert and the key where the search
+		 * stopped differ. This point will be the index of the new node.
+		 */
+		while(i < len && i < kid_node->len && kid_node->key[i] == new_key[i]) {
+			i++;
+		}
+
+		/* Start at the top again */
+		parent = tree->root;
+		kid_node = get_ath_kid(parent, new_key[0]);
+
+		/* Search the list again, but this time stop at our new index level */
+		while(parent->idx < kid_node->idx && kid_node->idx <= i) {
+			parent = kid_node;
+			kid_node = get_ath_kid(kid_node, new_key[kid_node->idx]);
+		}
+
+		new_node = patricia_node_alloc(new_key, len, i);
+		if(new_node == NULL) {
+			return NULL;
+		}
+
+		/* Set the link to the child according to the character in the
+		 * child's key at the index of this new node */
+		if(!set_ath_kid(new_node, kid_node->key[i], kid_node)) {
+			patricia_node_free(new_node);
+			return NULL;
+		}
+
+		/* Set the parent's link to this node according to the character
+		 * in the new node's key at the index of the parent */
+		if(!set_ath_kid(parent, new_node->key[parent->idx], new_node)) {
+			patricia_node_free(new_node);
+			return NULL;
+		}
+
+		/* All other kid links are implicitly linked to the new node */
+
+		new_node->valid = TRUE;
+
+		tree->total_node_count++;
+	}
+
+	return new_node;
+}
+
+/* ---[ patricia_delete ]-------------------------------------------------------
+ * 
+ * paticia_delete() removes a string from a given patricia tree.
+ *
+ * Inputs: tree - a pointer to the tree to delete from
+ *		 key - the string to delete
+ *		 len - the length of the string to delete
+ * Outputs: A pointer to the data field of the deleted node if the node is
+ *		  found and deleted. NULL otherwise.
+ */
+void *patricia_delete(patricia_tree_t *tree, char key[], int32_t len)
+{
+	patricia_node_t *parent, *real_parent, *kid_node;
+	void *found_data = NULL;
+
+	if(len <= 0) {
+		return NULL;
+	}
+
+	if(tree->root == NULL) {
+		return NULL;			/* Empty tree */
+	} else {
+		/* Start at the root */
+		real_parent = NULL;
+		parent = tree->root;
+		kid_node = get_ath_kid(parent, key[0]);
+
+		/* Search the list, taking the appropriate child at each step */
+		while(parent->idx < kid_node->idx && kid_node->idx <= len) {
+			parent = kid_node;
+
+			/* If 'a' is a printable ASCII character and idx is the string
+			 * index at this level, the 'ath' kid of a node is the link to
+			 * the child node which has that character at position idx in its
+			 * key.
+			 */
+			kid_node = get_ath_kid(kid_node, key[kid_node->idx]);
+
+			/* If we just hit bottom, then parent and kid_node are one
+			 * and the same. Don't update the real parent pointer */
+			if(parent != kid_node) {
+				real_parent = parent;
+			}
+		}
+
+		/* If we didn't find the string, we can't delete it */
+		if(len != kid_node->len || strncmp(key, kid_node->key, len) != 0) {
+			return NULL;
+		}
+	}
+
+	/*
+	 * This if-else block was put here in an attempt to optimize the cases
+	 * where a node is a leaf in the tree. If a node is a leaf, we can simply
+	 * chop it off the bottom of the tree. If the node is internal, we just
+	 * flag that we've invalidated it so that it is no longer returned in
+	 * searches. After the number of invalid nodes is greater than 1/3rd of
+	 * the total number of nodes in the tree, we then rebuild the tree,
+	 * discarding invalidated nodes.
+	 *
+	 * Unfortunately, the "else" part of this block will probably never be
+	 * executed, since Patricia trees by definition don't really have leaf
+	 * nodes. We could determine a leaf using some sort of labelling process,
+	 * but that would just add complexity. The upshot is that we end up
+	 * always lazy deleting.
+	 */
+	if(node_has_kids(kid_node)) {	 /* This will always be true :-( */
+		/* Here if the node has children */
+
+		/* Just flag that this node is no longer valid */ 
+		kid_node->valid = FALSE;
+		tree->invalid_node_count++;
+
+		found_data = kid_node->data;
+		kid_node->data = NULL;
+
+		/* If more than a certain fraction of all nodes in the tree have been
+		 * deleted, rebuild the tree */
+		if(tree->invalid_node_count > 
+		   tree->total_node_count / MIN_DELETE_FRACTION) {
+			if(!patricia_rebuild(tree, FALSE)) {
+				/* We should probably delete the entire tree */
+				patricia_rebuild(tree, TRUE);
+				return NULL;
+			}
+		}
+
+		return found_data;
+	} else {
+		if(real_parent == NULL) {
+			found_data = kid_node->data;
+			/* We are deleting the root */
+			patricia_node_free(kid_node);
+			tree->total_node_count--;
+			tree->root = NULL;
+		} else {
+			clear_ath_kid(real_parent, kid_node->key[real_parent->idx]);
+			found_data = kid_node->data;
+			patricia_node_free(kid_node);
+			tree->total_node_count--;
+		}
+	}
+
+	return found_data;
+}			
+
+/* ---[ patricia_clear ]--------------------------------------------------------
+ *
+ * patricia_clear() is used to delete all nodes from a patricia tree. It is
+ * essentially a wrapper for patricia_rebuild(), with the del_tree parameter
+ * set to true.
+ *
+ * Inputs: tree - the tree to clear
+ * Outputs: nothing
+ */
+void patricia_clear(patricia_tree_t *tree)
+{
+	patricia_rebuild(tree, TRUE);
+}
+
+/* ---[ patricia_rebuild ]------------------------------------------------------
+ * 
+ * patricia_rebuild() is used to rebuild or delete the tree. In the rebuild
+ * case, a new tree is built from the existing nodes in the tree. In the
+ * delete case, the old tree is traversed and all nodes are deleted.
+ *
+ * Inputs: tree - the tree to operate on
+ *		 del_tree - if 1 (TRUE), delete the tree. Otherwise rebuild the tree,
+ *					discarding invalidated nodes along the way.
+ * Outputs: 1 (TRUE) if the tree was rebuilt successfully, 0 (FALSE) otherwise.
+ */
+static int32_t patricia_rebuild(patricia_tree_t *tree, uint8_t del_tree)
+{
+	patricia_node_t *old_root;
+
+	old_root = tree->root;
+	tree->root = NULL;
+	tree->total_node_count = 0;
+	tree->invalid_node_count = 0;
+
+	if(old_root != NULL) {
+		if(!patricia_transfer(old_root, tree, del_tree)) {
+			/* XXX Log some sort of fatal warning? */
+			return FALSE;
+		} 
+	}
+
+	return TRUE;
+}
+
+/* ---[ patricia_transfer ]-----------------------------------------------------
+ *
+ * patricia_transfer() is a recursive function which traverses a patricia
+ * tree and either inserts each node into a new tree, or deletes each node.
+ *
+ * Inputs: tree - the old tree
+ *		 new_tree - the tree to build
+ *		 free_all - if 1, delete all nodes in tree. Otherwise, only discard
+ *					invalid nodes in tree, inserting all others into new_tree.
+ * Outputs: 1 (TRUE) if the tree was transferred/deleted successfully,
+ *		  0 (FALSE) otherwise.
+ */
+static int32_t patricia_transfer(patricia_node_t *tree, 
+								 patricia_tree_t *new_tree,
+								 uint8_t free_all)
+{
+	patricia_kid_t *k;
+	patricia_node_t *parent, *kid_node;
+	uint32_t i = 0, retval = TRUE;
+
+	/*
+	 * Start out by recursively transferring/deleting all children. We have
+	 * to be careful here, since oftentimes nodes can be the children of their
+	 * children. This can lead to an infinite recursion unless we flag already
+	 * visited nodes somehow. This is accomplished here by setting the node's
+	 * comparison index to -1.
+	 */
+
+	k = tree->kids;
+	tree->idx = -1;	 /* Mark as visited */
+	while(k != NULL) {
+		tree->kids = tree->kids->brother;
+
+		/* If we haven't visited the child yet, recursively operate on it */
+		if(k->node->idx != -1) {
+			retval = patricia_transfer(k->node, new_tree, free_all);
+		}
+		kid_free(k);   
+		k = tree->kids;
+	}
+
+	/* If this node is not invalidated and we don't want to free the tree,
+	 * insert it into the new tree */
+	if(tree->valid && !free_all) {
+		if(new_tree->root == NULL) {
+
+			/* Use the existing memory */
+			tree->idx = 0;
+			tree->kids = NULL;
+			bzero(tree->kid_mask, (sizeof(uint32_t) * KID_MASK_SIZE));
+
+			new_tree->root = tree;
+			new_tree->total_node_count++;
+		} else {
+			parent = new_tree->root;
+			kid_node = get_ath_kid(parent, tree->key[0]);
+			
+			while(parent->idx < kid_node->idx && kid_node->idx <= tree->len) {
+				parent = kid_node;
+				kid_node = get_ath_kid(kid_node, tree->key[kid_node->idx]);
+			}
+
+			if(kid_node->len == tree->len && 
+			   strncmp(tree->key, kid_node->key, tree->len) == 0) 
+			{
+				/* This should never happen. We shouldn't have had duplicates
+				 * in the original tree, so we shouldn't have any in the
+				 * new tree either */
+				patricia_node_free(tree);
+				return retval;
+			}
+
+			while(i < tree->len && i < kid_node->len && 
+				  kid_node->key[i] == tree->key[i]) {
+				i++;
+			}
+
+			parent = new_tree->root;
+			kid_node = get_ath_kid(parent, tree->key[0]);
+ 
+			while(parent->idx < kid_node->idx && kid_node->idx <= i) {
+				parent = kid_node;
+				kid_node = get_ath_kid(kid_node, tree->key[kid_node->idx]);
+			}
+
+			tree->idx = i;
+			tree->kids = NULL;
+			bzero(tree->kid_mask, (sizeof(uint32_t) * KID_MASK_SIZE));
+			
+			if(!set_ath_kid(tree, kid_node->key[i], kid_node)) {
+				patricia_node_free(tree);
+				return FALSE;
+			}
+
+			if(!set_ath_kid(parent, tree->key[parent->idx], tree)) {
+				patricia_node_free(tree);	
+				return FALSE;
+			}
+
+			new_tree->total_node_count++;
+		}
+	} else {
+		/* Release the memory */
+		patricia_node_free(tree);
+	}
+
+	return retval;
+}
+		
+/* ---[ set_ath_kid ]-----------------------------------------------------------
+ * 
+ * set_ath_kid() is used to point a parent node at a child node through a link
+ * corresponding to one of the printable ASCII characters. Each node in the
+ * patricia tree has up to 97 child links (all printables plus 1 for '\0').
+ * 
+ * Inputs: node - the patricia tree node to set the link for
+ *		 a - the character of the link to set
+ *		 kid_node - the child node to point the parent at
+ * Outputs: 1 if everything was fine, 0 otherwise. Needed since this function
+ *		  allocates memory.
+ */
+static uint8_t set_ath_kid(patricia_node_t *node, char a, 
+						   patricia_node_t *kid_node)
+{
+	patricia_kid_t *k;
+
+	/* First, see if the parent is already pointing at the kid */
+
+	/* Note that the null terminator is a special case. If that's the 
+	 * character, we need to search the list no matter what, since the mask is
+	 * always going to give us a negative */
+
+	if(a != '\0' && !kid_in_list(node, a)) {
+		/* Kid does not exist, so create a new one */
+		k = kid_alloc();
+		if(k == NULL) {
+			return FALSE;
+		}
+
+		kid_register(node, a); /* Set the bit in node's mask corresponding to
+								* this character. This way we can avoid
+								* failed worst-case searches */
+		k->name = a;
+		k->node = kid_node;
+		k->brother = node->kids;
+		node->kids = k;
+	} else {
+		/* Search the list for the kid node corresponding to the character */
+		for(k = node->kids; k != NULL; k = k->brother) {
+			if(k->name == a) {
+				k->node = kid_node;
+				return TRUE;
+			}
+		}
+
+		/* We should only be here if a is the null terminator and the null
+		 * terminator is not already in the kid list. All other situtations
+		 * should have resulted in a successful search through the kid list
+		 */
+		if(a == '\0') {
+			k = kid_alloc();
+			if(k == NULL) {
+				return FALSE;
+			}
+			k->name = a;
+			k->node = kid_node;
+			k->brother = node->kids;
+			node->kids = k;
+		}
+	}
+
+	return TRUE; 
+}
+
+/* ---[ clear_ath_kid ]---------------------------------------------------------
+ *
+ * clear_ath_kid() removes a child link from a node
+ *
+ * Inputs: node - the node to delete the link from
+ *		 a - delete the link corresponding to this character
+ * Outputs: nothing
+ */
+static void clear_ath_kid(patricia_node_t *node, char a)
+{
+	patricia_kid_t *k, *prev;
+
+	if(a != '\0' && !kid_in_list(node, a)) {
+		return; /* character wasn't in the kid list anyway */
+	} else {
+		prev = NULL;
+		k = node->kids;
+		while(k != NULL) {
+			if(k->name == a) {
+				if(prev == NULL) {
+					node->kids = k->brother;
+				} else {
+					prev->brother = k->brother;
+				}
+				kid_free(k);
+				break;
+			}
+			prev = k;
+			k = k->brother;
+		}
+	}
+}
+
+/* ---[ get_ath_kid ]-----------------------------------------------------------
+ * 
+ * get_ath_kid() returns the child of a node corresponding to one of the
+ * printable ASCII characters.
+ *
+ * Inputs: node - a pointer to the parent node
+ *		 a - the character corresponding to the link to get
+ * Ouputs: the ath child of node, or the child which was pointed to by the
+ *		 kid link of node which corresponds to the given character.
+ */
+static patricia_node_t *get_ath_kid(patricia_node_t *node, char a)
+{
+	patricia_kid_t *k;
+
+	/* Optimization: if it's not a '\0' and it's not set in the mask, then
+	 * we know right away that it isn't in the kid list */
+	if(a != '\0' && !kid_in_list(node, a)) {
+		/* The parent is implicitly pointing to itself for all characters which
+		 * do not have links to other nodes */
+		return node;
+	}
+
+	/* Here if we are searching for '\0' or the character is in the list */
+	for(k = node->kids; k != NULL; k = k->brother) {
+		if(k->name == a) {
+			return k->node;
+		}
+	}
+
+	return node; 
+}	
+
+/* ---[ node_has_kids ]---------------------------------------------------------
+ *
+ * node_has_kids() is supposed to determine if the node is a leaf or not.
+ * But, by definition, all nodes in a patricia tree are internal, so this 
+ * function should always return true.
+ *
+ * Inputs: node - a pointer to the node to check
+ * Outputs: 1 (TRUE) if the node has one or more children, 0 (FALSE) otherwise.
+ */
+static uint8_t node_has_kids(patricia_node_t *node)
+{
+	if(node->kids != NULL) {
+		return TRUE;
+	}
+#if 0
+	for(k = node->kids; k != NULL; k = k->brother) {
+		/* If this kid is at or below this level of the tree and its not 
+		 * pointing to the node itself, then this is a real child */
+		if(k->node->idx >= node->idx) {
+			return TRUE;
+		}
+	}
+#endif
+
+	return FALSE;
+}
+			
+	
+/* ---[ patricia_node_alloc ]---------------------------------------------------
+ *
+ * patricia_node_alloc() creates a new patricia node, sets some fields 
+ * according to the values passed in, and returns the new node.
+ *
+ * Inputs: key - the string which should be assigned to the new node
+ *		 len - the length of key
+ *		 idx - the index to assign to this new node.
+ * Outpus: A pointer to the new patricia node, or NULL if one could not be
+ *		 allocated.
+ */
+static patricia_node_t *patricia_node_alloc(char *key, int32_t len,
+											int32_t idx)
+{
+	patricia_node_t *n;
+
+	PATRICIA_MALLOC(n, patricia_node_t *, sizeof(patricia_node_t),
+		   M_PATRICIA_NODE, M_NOWAIT);
+
+	if(n != NULL) {
+		PATRICIA_MALLOC(n->key, char *, sizeof(char) * (len+1), M_TEMP, M_NOWAIT);
+		if(n->key == NULL) {
+			PATRICIA_FREE(n, M_PATRICIA_NODE);
+			return NULL;
+		}
+		strncpy(n->key, key, len);
+		n->key[len] = '\0';
+		n->len = len;
+		n->idx = idx;
+		n->kids = NULL;
+		bzero(n->kid_mask, (sizeof(uint32_t) * KID_MASK_SIZE));
+		n->data = NULL;
+		n->valid = FALSE;
+		n->real_hostname = NULL; 
+	}
+
+	
+	return n;
+}
+
+/* ---[ patricia_node_free ]----------------------------------------------------
+ *
+ * patricia_node_free() releases all memory allocated to a node in the patricia
+ * tree.
+ *
+ * Inputs: node - the node to free
+ * Outputs: nothing
+ */
+static void patricia_node_free(patricia_node_t *node)
+{
+	patricia_kid_t *k;
+
+	if((node->real_hostname != NULL) && (node->real_hostname != node->key)) {
+	
+		PATRICIA_FREE(node->real_hostname, M_TEMP);
+	}
+	/************************/
+
+	if(node->key != NULL) {
+		PATRICIA_FREE(node->key, M_TEMP);
+	}
+	while(node->kids != NULL) {
+		k = node->kids;
+		node->kids = node->kids->brother;
+		PATRICIA_FREE(k, M_PATRICIA_KID);
+	}
+
+	PATRICIA_FREE(node, M_PATRICIA_NODE);
+}
+
+/* ---[ kid_alloc ]-------------------------------------------------------------
+ *
+ * kid_alloc() creates a new kid node and returns it.
+ * 
+ * Inputs: nothing
+ * Outputs: a pointer to the new kid node, NULL if allocation failed.
+ */
+static patricia_kid_t *kid_alloc(void)
+{
+	patricia_kid_t *k;
+	PATRICIA_MALLOC(k, patricia_kid_t *, sizeof(patricia_kid_t),
+		   M_PATRICIA_KID, M_NOWAIT);
+	return k;
+}
+
+/* ---[ kid_free ]--------------------------------------------------------------
+ *
+ * kid_free() releases memory for a kid node. 
+ *
+ * Inputs: kid - the kid node to free.
+ * Outputs: nothing.
+ */
+static void kid_free(patricia_kid_t *kid)
+{
+	PATRICIA_FREE(kid, M_PATRICIA_KID);
+}
+
+/*
+  Notice: This function now should be invoked only be patricia_insearch, for we use 
+  a global variable dns_match_flag. If other function want to invoke this function, 
+  you must first initialize the dns_match_flag to 0.
+*/
+static uint8_t node_is_prefix(char *key, int32_t len, patricia_node_t *node,uint32_t dns_match_flag)
+{
+        int32_t i = (len < node->len) ? len-1 : node->len-1;
+  
+        if (dns_match_flag) {
+   
+                if(len < node->len) return FALSE;    
+        }                
+
+	while (i >= 0 && key[i] == node->key[i]) {
+		i--;
+	}
+
+	if (i < 0) {
+		return TRUE;
+	}
+
+	return FALSE;
+}

Property changes on: src/library/ca_regex/patricia.c
___________________________________________________________________
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: /branches/rel_avx_2_7_4/src/library/ca_regex/regexp_match.h
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_regex/regexp_match.h	(revision 0)
+++ /branches/rel_avx_2_7_4/src/library/ca_regex/regexp_match.h	(working copy)
@@ -0,0 +1,34 @@
+/*
+ * Definitions etc. for regexp(3) routines.
+ *
+ * Caveat:  this is V8 regexp(3) [actually, a reimplementation thereof],
+ * not the System V one.
+ */
+
+#ifndef __REGEXP_MATCH_H_
+#define __REGEXP_MATCH_H_
+
+#define MAGIC   0234
+
+#define NSUBEXP  10
+
+typedef struct regexp {
+	char *startp[NSUBEXP];
+	char *endp[NSUBEXP];
+	char regstart;		/* Internal use only. */
+	char reganch;		/* Internal use only. */
+	char *regmust;		/* Internal use only. */
+	int regmlen;		/* Internal use only. */
+	char program[1];	/* Unwarranted chumminess with compiler. */
+} regexp;
+
+#ifdef _KERNEL
+regexp *regcomp(char *exp);
+void regfree(regexp *r);
+void regerror(const char* s);
+/*extern void regsub();*/
+#endif
+
+int uregexec(register regexp *prog, register char *string);
+
+#endif/*__REGEXP_MATCH_H_*/
Index: /branches/rel_avx_2_7_4/src/library/ca_regex/regexp_match.c
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_regex/regexp_match.c	(revision 0)
+++ /branches/rel_avx_2_7_4/src/library/ca_regex/regexp_match.c	(working copy)
@@ -0,0 +1,1341 @@
+/*
+ * regcomp and regexec -- regsub and regerror are elsewhere
+ * regular-expression syntax might require a total rethink.
+ */
+
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+
+#ifdef _KERNEL
+#include <machine/param.h>
+#include "opt_atcp_mm.h"
+
+#include <sys/systm.h>
+#include <sys/time.h>
+
+#include <sys/kernel.h>
+#include <sys/malloc.h>
+#include <sys/mbuf.h>
+
+
+#include "proxy_errs.h"
+
+#else 
+#include <string.h>
+#include <stdio.h>
+#include <ctype.h>
+#include <string.h>
+#include <stdlib.h>
+#endif /* #ifdef _KERNEL */
+
+
+#include "regexp_match.h"
+
+
+/*
+ * The "internal use only" fields in regexp.h are present to pass info from
+ * compile to execute that permits the execute phase to run lots faster on
+ * simple cases.  They are:
+ *
+ * regstart	char that must begin a match; '\0' if none obvious
+ * reganch	is the match anchored (at beginning-of-line only)?
+ * regmust	string (pointer into program) that match must include, or NULL
+ * regmlen	length of regmust string
+ *
+ * Regstart and reganch permit very fast decisions on suitable starting points
+ * for a match, cutting down the work a lot.  Regmust permits fast rejection
+ * of lines that cannot possibly match.  The regmust tests are costly enough
+ * that regcomp() supplies a regmust only if the r.e. contains something
+ * potentially expensive (at present, the only such thing detected is * or +
+ * at the start of the r.e., which can involve a lot of backup).  Regmlen is
+ * supplied because the test in regexec() needs it and regcomp() is computing
+ * it anyway.
+ */
+
+/*
+ * Structure for regexp "program".  This is essentially a linear encoding
+ * of a nondeterministic finite-state machine (aka syntax charts or
+ * "railroad normal form" in parsing technology).  Each node is an opcode
+ * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
+ * all nodes except BRANCH implement concatenation; a "next" pointer with
+ * a BRANCH on both ends of it is connecting two alternatives.  (Here we
+ * have one of the subtle syntax dependencies:  an individual BRANCH (as
+ * opposed to a collection of them) is never concatenated with anything
+ * because of operator precedence.)  The operand of some types of node is
+ * a literal string; for others, it is a node leading into a sub-FSM.  In
+ * particular, the operand of a BRANCH node is the first node of the branch.
+ * (NB this is *not* a tree structure:  the tail of the branch connects
+ * to the thing following the set of BRANCHes.)  The opcodes are:
+ */
+
+/* definition	number	opnd?	meaning */
+#define	END	0	/* no	End of program. */
+#define	BOL	1	/* no	Match "" at beginning of line. */
+#define	EOL	2	/* no	Match "" at end of line. */
+#define	ANY	3	/* no	Match any one character. */
+#define	ANYOF	4	/* str	Match any character in this string. */
+#define	ANYBUT	5	/* str	Match any character not in this string. */
+#define	BRANCH	6	/* node	Match this alternative, or the next... */
+#define	BACK	7	/* no	Match "", "next" ptr points backward. */
+#define	EXACTLY	8	/* str	Match this string. */
+#define	NOTHING	9	/* no	Match empty string. */
+#define	STAR	10	/* node	Match this (simple) thing 0 or more times. */
+#define	PLUS	11	/* node	Match this (simple) thing 1 or more times. */
+#define	WORDA	12	/* no	Match "" at wordchar, where prev is nonword */
+#define	WORDZ	13	/* no	Match "" at nonwordchar, where prev is word */
+#define	OPEN	20	/* no	Mark this point in input as start of #n. */
+			/*	OPEN+1 is number 1, etc. */
+#define	CLOSE	30	/* no	Analogous to OPEN. */
+
+/*
+ * Opcode notes:
+ *
+ * BRANCH	The set of branches constituting a single choice are hooked
+ *		together with their "next" pointers, since precedence prevents
+ *		anything being concatenated to any individual branch.  The
+ *		"next" pointer of the last BRANCH in a choice points to the
+ *		thing following the whole choice.  This is also where the
+ *		final "next" pointer of each individual branch points; each
+ *		branch starts with the operand node of a BRANCH node.
+ *
+ * BACK		Normal "next" pointers all implicitly point forward; BACK
+ *		exists to make loop structures possible.
+ *
+ * STAR,PLUS	'?', and complex '*' and '+', are implemented as circular
+ *		BRANCH structures using BACK.  Simple cases (one character
+ *		per match) are implemented with STAR and PLUS for speed
+ *		and to minimize recursive plunges.
+ *
+ * OPEN,CLOSE	...are numbered at compile time.
+ */
+
+/*
+ * A node is one char of opcode followed by two chars of "next" pointer.
+ * "Next" pointers are stored as two 8-bit pieces, high order first.  The
+ * value is a positive offset from the opcode of the node containing it.
+ * An operand, if any, simply follows the node.  (Note that much of the
+ * code generation knows about this implicit relationship.)
+ *
+ * Using two bytes for the "next" pointer is vast overkill for most things,
+ * but allows patterns to get big without disasters.
+ */
+#define	OP(p)	(*(p))
+#define	NEXT(p)	(((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
+#define	OPERAND(p)	((p) + 3)
+
+/*
+ * See regmagic.h for one further detail of program structure.
+ */
+
+
+/*
+ * Utility definitions.
+ */
+
+#ifndef CHARBITS
+#define	UCHARAT(p)	((int)*(unsigned char *)(p))
+#else
+#define	UCHARAT(p)	((int)*(p)&CHARBITS)
+#endif
+
+#ifndef STATIC
+#define	STATIC	static
+#endif
+
+static char regdummy;
+
+STATIC char *regnext(register char *p);
+
+
+#define	REGEXP_FAIL(m)	{ regerror(m); return(NULL); }
+#define	ISMULT(c)	((c) == '*' || (c) == '+' || (c) == '?')
+
+/*
+ * Flags to be passed up and down.
+ */
+#define	HASWIDTH	01	/* Known never to match null string. */
+#define	SIMPLE		02	/* Simple enough to be STAR/PLUS operand. */
+#define	SPSTART		04	/* Starts with * or +. */
+#define	WORST		0	/* Worst case. */
+
+#ifdef _KERNEL
+#define REGEX_MALLOC(var, type, size, m_type, m_flags) MALLOC(var, type, (size), m_type, m_flags)
+#define REGEX_FREE(var, malloc_type) FREE(var, malloc_type)
+#else
+#define REGEX_MALLOC(var, type, size, malloc_type, malloc_flags) var = (type)malloc(size)
+#define REGEX_FREE(var, malloc_type) free(var)
+#endif
+
+
+/*
+ * Global work variables for regcomp().
+ */
+static char *regparse;		/* Input-scan pointer. */
+static int regnpar;		/* () count. */
+static char *regcode;		/* Code-emit pointer; &regdummy = don't. */
+static long regsize;		/* Code size. */
+
+/*
+ * Forward declarations for regcomp()'s friends.
+ */
+STATIC char *reg(int paren, int* flagp);
+STATIC char *regbranch(int *flagp);
+STATIC char *regpiece(int* flagp);
+STATIC char *regatom(int *flagp);
+STATIC char *regnode(char op);
+STATIC void regc(char b);
+STATIC void reginsert(char op, char *opnd);
+STATIC void regtail(char* p, char* val);
+STATIC void regoptail(char* p, char* val);
+#ifdef STRCSPN
+STATIC int strcspn();
+#endif
+
+/*lib function, found from proxy_lib.c*/
+/* because isalnum is not a kernel function*/
+
+//#define isalnum(var) (isalpha(var)||isdigit(var))
+
+void
+regerror(const char* s)
+{
+#ifdef ERRAVAIL
+	error("regexp: %s", s);
+#else
+/*
+	fprintf(stderr, "regexp(3): %s\n", s);
+	exit(1);
+*/
+	return;	  /* let std. egrep handle errors */
+#endif
+	/* NOTREACHED */
+}
+
+
+/*
+ - regcomp - compile a regular expression into internal code
+ *
+ * We can't allocate space until we know how big the compiled form will be,
+ * but we can't compile it (and thus know how big it is) until we've got a
+ * place to put the code.  So we cheat:  we compile it twice, once with code
+ * generation turned off and size counting turned on, and once "for real".
+ * This also means that we don't allocate space until we are sure that the
+ * thing really will compile successfully, and we never have to move the
+ * code and thus invalidate pointers into it.  (Note that it has to be in
+ * one piece because free() must be able to free it all.)
+ *
+ * Beware that the optimization-preparation code in here knows about some
+ * of the structure of the compiled regexp.
+ */
+regexp *
+regcomp(char *exp)
+{
+	register regexp *r;
+	register char *scan;
+	register char *longest;
+	register int len;
+	int flags;
+
+	if (exp == NULL)
+		REGEXP_FAIL("NULL argument");
+
+	/* First pass: determine size, legality. */
+#ifdef notdef
+	if (exp[0] == '.' && exp[1] == '*') exp += 2;  /* aid grep */
+#endif
+	regparse = (char *)exp;
+	regnpar = 1;
+	regsize = 0L;
+	regcode = &regdummy;
+	regc(MAGIC);
+	if (reg(0, &flags) == NULL)
+		return(NULL);
+
+	/* Small enough for pointer-storage convention? */
+	if (regsize >= 32767L)		/* Probably could be 65535L. */
+		REGEXP_FAIL("regexp too big");
+
+	/* Allocate space. */
+	REGEX_MALLOC(r, regexp *, (sizeof(regexp) + (unsigned)regsize), M_PROXYTEMP, M_NOWAIT);
+	if (r == NULL)
+    {
+        /* add by zhangjz, it is very important to return NULL*/
+		REGEXP_FAIL("out of space");
+    }
+
+	/* Second pass: emit code. */
+	regparse = (char *)exp;
+	regnpar = 1;
+	regcode = r->program;
+	regc(MAGIC);
+	if (reg(0, &flags) == NULL)
+		return(NULL);
+
+	/* Dig out information for optimizations. */
+	r->regstart = '\0';	/* Worst-case defaults. */
+	r->reganch = 0;
+	r->regmust = NULL;
+	r->regmlen = 0;
+	scan = r->program+1;			/* First BRANCH. */
+	if (OP(regnext(scan)) == END) {		/* Only one top-level choice. */
+		scan = OPERAND(scan);
+
+		/* Starting-point info. */
+		if (OP(scan) == EXACTLY)
+			r->regstart = *OPERAND(scan);
+		else if (OP(scan) == BOL)
+			r->reganch++;
+
+		/*
+		 * If there's something expensive in the r.e., find the
+		 * longest literal string that must appear and make it the
+		 * regmust.  Resolve ties in favor of later strings, since
+		 * the regstart check works with the beginning of the r.e.
+		 * and avoiding duplication strengthens checking.  Not a
+		 * strong reason, but sufficient in the absence of others.
+		 */
+		if (flags&SPSTART) {
+			longest = NULL;
+			len = 0;
+			for (; scan != NULL; scan = regnext(scan))
+				if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
+					longest = OPERAND(scan);
+					len = strlen(OPERAND(scan));
+				}
+			r->regmust = longest;
+			r->regmlen = len;
+		}
+	}
+
+	return(r);
+}
+
+
+void 
+regfree(regexp * r)
+{
+	REGEX_FREE(r, M_PROXYTEMP);
+}
+
+
+/*
+ - reg - regular expression, i.e. main body or parenthesized thing
+ *
+ * Caller must absorb opening parenthesis.
+ *
+ * Combining parenthesis handling with the base level of regular expression
+ * is a trifle forced, but the need to tie the tails of the branches to what
+ * follows makes it hard to avoid.
+ */
+static char *
+reg(int paren, int* flagp)
+{
+	register char *ret;
+	register char *br;
+	register char *ender;
+	register int parno;
+	int flags;
+
+    /* add because compiler report error*/
+    parno = 0;
+	*flagp = HASWIDTH;	/* Tentatively. */
+
+	/* Make an OPEN node, if parenthesized. */
+	if (paren) {
+		if (regnpar >= NSUBEXP)
+			REGEXP_FAIL("too many ()");
+		parno = regnpar;
+		regnpar++;
+		ret = regnode(OPEN+parno);
+	} else
+		ret = NULL;
+
+	/* Pick up the branches, linking them together. */
+	br = regbranch(&flags);
+	if (br == NULL)
+		return(NULL);
+	if (ret != NULL)
+		regtail(ret, br);	/* OPEN -> first. */
+	else
+		ret = br;
+	if (!(flags&HASWIDTH))
+		*flagp &= ~HASWIDTH;
+	*flagp |= flags&SPSTART;
+	while (*regparse == '|' || *regparse == '\n') {
+		regparse++;
+		br = regbranch(&flags);
+		if (br == NULL)
+			return(NULL);
+		regtail(ret, br);	/* BRANCH -> BRANCH. */
+		if (!(flags&HASWIDTH))
+			*flagp &= ~HASWIDTH;
+		*flagp |= flags&SPSTART;
+	}
+
+	/* Make a closing node, and hook it on the end. */
+	ender = regnode((paren) ? CLOSE+parno : END);	
+	regtail(ret, ender);
+
+	/* Hook the tails of the branches to the closing node. */
+	for (br = ret; br != NULL; br = regnext(br))
+		regoptail(br, ender);
+
+	/* Check for proper termination. */
+	if (paren && *regparse++ != ')') {
+		REGEXP_FAIL("unmatched ()");
+	} else if (!paren && *regparse != '\0') {
+		if (*regparse == ')') {
+			REGEXP_FAIL("unmatched ()");
+		} else
+			REGEXP_FAIL("junk on end");	/* "Can't happen". */
+		/* NOTREACHED */
+	}
+
+	return(ret);
+}
+
+/*
+ - regbranch - one alternative of an | operator
+ *
+ * Implements the concatenation operator.
+ */
+static char *
+regbranch(int *flagp)
+{
+	register char *ret;
+	register char *chain;
+	register char *latest;
+	int flags;
+
+	*flagp = WORST;		/* Tentatively. */
+
+	ret = regnode(BRANCH);
+	chain = NULL;
+	while (*regparse != '\0' && *regparse != ')' &&
+	       *regparse != '\n' && *regparse != '|') {
+		latest = regpiece(&flags);
+		if (latest == NULL)
+			return(NULL);
+		*flagp |= flags&HASWIDTH;
+		if (chain == NULL)	/* First piece. */
+			*flagp |= flags&SPSTART;
+		else
+			regtail(chain, latest);
+		chain = latest;
+	}
+	if (chain == NULL)	/* Loop ran zero times. */
+		(void) regnode(NOTHING);
+
+	return(ret);
+}
+
+/*
+ - regpiece - something followed by possible [*+?]
+ *
+ * Note that the branching code sequences used for ? and the general cases
+ * of * and + are somewhat optimized:  they use the same NOTHING node as
+ * both the endmarker for their branch list and the body of the last branch.
+ * It might seem that this node could be dispensed with entirely, but the
+ * endmarker role is not redundant.
+ */
+static char *
+regpiece(int* flagp)
+{
+	register char *ret;
+	register char op;
+	register char *next;
+	int flags;
+
+	ret = regatom(&flags);
+	if (ret == NULL)
+		return(NULL);
+
+	op = *regparse;
+	if (!ISMULT(op)) {
+		*flagp = flags;
+		return(ret);
+	}
+
+	if (!(flags&HASWIDTH) && op != '?')
+		REGEXP_FAIL("*+ operand could be empty");
+	*flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
+
+	if (op == '*' && (flags&SIMPLE))
+		reginsert(STAR, ret);
+	else if (op == '*') {
+		/* Emit x* as (x&|), where & means "self". */
+		reginsert(BRANCH, ret);			/* Either x */
+		regoptail(ret, regnode(BACK));		/* and loop */
+		regoptail(ret, ret);			/* back */
+		regtail(ret, regnode(BRANCH));		/* or */
+		regtail(ret, regnode(NOTHING));		/* null. */
+	} else if (op == '+' && (flags&SIMPLE))
+		reginsert(PLUS, ret);
+	else if (op == '+') {
+		/* Emit x+ as x(&|), where & means "self". */
+		next = regnode(BRANCH);			/* Either */
+		regtail(ret, next);
+		regtail(regnode(BACK), ret);		/* loop back */
+		regtail(next, regnode(BRANCH));		/* or */
+		regtail(ret, regnode(NOTHING));		/* null. */
+	} else if (op == '?') {
+		/* Emit x? as (x|) */
+		reginsert(BRANCH, ret);			/* Either x */
+		regtail(ret, regnode(BRANCH));		/* or */
+		next = regnode(NOTHING);		/* null. */
+		regtail(ret, next);
+		regoptail(ret, next);
+	}
+	regparse++;
+	if (ISMULT(*regparse))
+		REGEXP_FAIL("nested *?+");
+
+	return(ret);
+}
+
+/*
+ - regatom - the lowest level
+ *
+ * Optimization:  gobbles an entire sequence of ordinary characters so that
+ * it can turn them into a single node, which is smaller to store and
+ * faster to run.  Backslashed characters are exceptions, each becoming a
+ * separate node; the code is simpler that way and it's not worth fixing.
+ */
+static char *
+regatom(int *flagp)
+{
+	register char *ret;
+	int flags;
+
+	*flagp = WORST;		/* Tentatively. */
+
+	switch (*regparse++) {
+	/* FIXME: these chars only have meaning at beg/end of pat? */
+	case '^':
+		ret = regnode(BOL);
+		break;
+	case '$':
+		ret = regnode(EOL);
+		break;
+	case '.':
+		ret = regnode(ANY);
+		*flagp |= HASWIDTH|SIMPLE;
+		break;
+	case '[': {
+			register int class;
+			register int classend;
+
+			if (*regparse == '^') {	/* Complement of range. */
+				ret = regnode(ANYBUT);
+				regparse++;
+			} else
+				ret = regnode(ANYOF);
+			if (*regparse == ']' || *regparse == '-')
+				regc(*regparse++);
+			while (*regparse != '\0' && *regparse != ']') {
+				if (*regparse == '-') {
+					regparse++;
+					if (*regparse == ']' || *regparse == '\0')
+						regc('-');
+					else {
+						class = UCHARAT(regparse-2)+1;
+						classend = UCHARAT(regparse);
+						if (class > classend+1)
+							REGEXP_FAIL("invalid [] range");
+						for (; class <= classend; class++)
+							regc(class);
+						regparse++;
+					}
+				} else
+					regc(*regparse++);
+			}
+			regc('\0');
+			if (*regparse != ']')
+				REGEXP_FAIL("unmatched []");
+			regparse++;
+			*flagp |= HASWIDTH|SIMPLE;
+		}
+		break;
+	case '(':
+		ret = reg(1, &flags);
+		if (ret == NULL)
+			return(NULL);
+		*flagp |= flags&(HASWIDTH|SPSTART);
+		break;
+	case '\0':
+	case '|':
+	case '\n':
+	case ')':
+		REGEXP_FAIL("internal urp");	/* Supposed to be caught earlier. */
+		break;
+	case '?':
+	case '+':
+	case '*':
+		REGEXP_FAIL("?+* follows nothing");
+		break;
+	case '\\':
+		switch (*regparse++) {
+		case '\0':
+			REGEXP_FAIL("trailing \\");
+			break;
+		case '<':
+			ret = regnode(WORDA);
+			break;
+		case '>':
+			ret = regnode(WORDZ);
+			break;
+		/* FIXME: Someday handle \1, \2, ... */
+		default:
+			/* Handle general quoted chars in exact-match routine */
+			goto de_fault;
+		}
+		break;
+	de_fault:
+	default:
+		/*
+		 * Encode a string of characters to be matched exactly.
+		 *
+		 * This is a bit tricky due to quoted chars and due to
+		 * '*', '+', and '?' taking the SINGLE char previous
+		 * as their operand.
+		 *
+		 * On entry, the char at regparse[-1] is going to go
+		 * into the string, no matter what it is.  (It could be
+		 * following a \ if we are entered from the '\' case.)
+		 * 
+		 * Basic idea is to pick up a good char in  ch  and
+		 * examine the next char.  If it's *+? then we twiddle.
+		 * If it's \ then we frozzle.  If it's other magic char
+		 * we push  ch  and terminate the string.  If none of the
+		 * above, we push  ch  on the string and go around again.
+		 *
+		 *  regprev  is used to remember where "the current char"
+		 * starts in the string, if due to a *+? we need to back
+		 * up and put the current char in a separate, 1-char, string.
+		 * When  regprev  is NULL,  ch  is the only char in the
+		 * string; this is used in *+? handling, and in setting
+		 * flags |= SIMPLE at the end.
+		 */
+		{
+			char *regprev;
+			register char ch;
+
+			regparse--;			/* Look at cur char */
+			ret = regnode(EXACTLY);
+			for ( regprev = 0 ; ; ) {
+				ch = *regparse++;	/* Get current char */
+				switch (*regparse) {	/* look at next one */
+
+				default:
+					regc(ch);	/* Add cur to string */
+					break;
+
+				case '.': case '[': case '(':
+				case ')': case '|': case '\n':
+				case '$': case '^':
+				case '\0':
+				/* FIXME, $ and ^ should not always be magic */
+				magic:
+					regc(ch);	/* dump cur char */
+					goto done;	/* and we are done */
+
+				case '?': case '+': case '*':
+					if (!regprev) 	/* If just ch in str, */
+						goto magic;	/* use it */
+					/* End mult-char string one early */
+					regparse = regprev; /* Back up parse */
+					goto done;
+
+				case '\\':
+					regc(ch);	/* Cur char OK */
+					switch (regparse[1]){ /* Look after \ */
+					case '\0':
+					case '<':
+					case '>':
+					/* FIXME: Someday handle \1, \2, ... */
+						goto done; /* Not quoted */
+					default:
+						/* Backup point is \, scan							 * point is after it. */
+						regprev = regparse;
+						regparse++; 
+						continue;	/* NOT break; */
+					}
+				}
+				regprev = regparse;	/* Set backup point */
+			}
+		done:
+			regc('\0');
+			*flagp |= HASWIDTH;
+			if (!regprev)		/* One char? */
+				*flagp |= SIMPLE;
+		}
+		break;
+	}
+
+	return(ret);
+}
+
+/*
+ - regnode - emit a node
+ */
+static char *			/* Location. */
+regnode(char op)
+{
+	register char *ret;
+	register char *ptr;
+
+	ret = regcode;
+	if (ret == &regdummy) {
+		regsize += 3;
+		return(ret);
+	}
+
+	ptr = ret;
+	*ptr++ = op;
+	*ptr++ = '\0';		/* Null "next" pointer. */
+	*ptr++ = '\0';
+	regcode = ptr;
+
+	return(ret);
+}
+
+/*
+ - regc - emit (if appropriate) a byte of code
+ */
+static void
+regc(char b)
+{
+	if (regcode != &regdummy)
+		*regcode++ = b;
+	else
+		regsize++;
+}
+
+/*
+ - reginsert - insert an operator in front of already-emitted operand
+ *
+ * Means relocating the operand.
+ */
+static void
+reginsert(char op, char *opnd)
+{
+	register char *src;
+	register char *dst;
+	register char *place;
+
+	if (regcode == &regdummy) {
+		regsize += 3;
+		return;
+	}
+
+	src = regcode;
+	regcode += 3;
+	dst = regcode;
+	while (src > opnd)
+		*--dst = *--src;
+
+	place = opnd;		/* Op node, where operand used to be. */
+	*place++ = op;
+	*place++ = '\0';
+	*place++ = '\0';
+}
+
+/*
+ - regtail - set the next-pointer at the end of a node chain
+ */
+static void
+regtail(char* p, char* val)
+{
+	register char *scan;
+	register char *temp;
+	register int offset;
+
+	if (p == &regdummy)
+		return;
+
+	/* Find last node. */
+	scan = p;
+	for (;;) {
+		temp = regnext(scan);
+		if (temp == NULL)
+			break;
+		scan = temp;
+	}
+
+	if (OP(scan) == BACK)
+		offset = scan - val;
+	else
+		offset = val - scan;
+	*(scan+1) = (offset>>8)&0377;
+	*(scan+2) = offset&0377;
+}
+
+/*
+ - regoptail - regtail on operand of first argument; nop if operandless
+ */
+static void
+regoptail(char* p, char* val)
+{
+	/* "Operandless" and "op != BRANCH" are synonymous in practice. */
+	if (p == NULL || p == &regdummy || OP(p) != BRANCH)
+		return;
+	regtail(OPERAND(p), val);
+}
+/*
+ * regexec and friends
+ */
+
+/*
+ * Global work variables for regexec().
+ */
+static __thread char *reginput;		/* String-input pointer. */
+static __thread char *regbol;		/* Beginning of input, for ^ check. */
+static __thread char **regstartp;	/* Pointer to startp array. */
+static __thread char **regendp;		/* Ditto for endp. */
+
+/*
+ * Forwards.
+ */
+STATIC int regtry(regexp * prog, char * string);
+STATIC int regmatch(char* prog);
+STATIC int regrepeat(char* p);
+
+#ifdef DEBUG
+int regnarrate = 0;
+STATIC char *regprop();
+#ifdef _KERNEL
+void regdump();
+#endif
+#endif
+
+/*
+ - regmatch - main matching routine
+ *
+ * Conceptually the strategy is simple:  check to see whether the current
+ * node matches, call self recursively to see whether the rest matches,
+ * and then act accordingly.  In practice we make some effort to avoid
+ * recursion, in particular by going through "ordinary" nodes (that don't
+ * need to know whether the rest of the match failed) by a loop instead of
+ * by recursion.
+ */
+static int			/* 0 failure, 1 success */
+regmatch(char* prog)
+{
+	register char *scan;	/* Current node. */
+	char *next;		/* Next node. */
+	/*extern char *strchr();*/
+
+	scan = prog;
+#ifdef DEBUG
+	if (scan != NULL && regnarrate)
+		fprintf(stderr, "%s(\n", regprop(scan));
+#endif
+	while (scan != NULL) {
+#ifdef DEBUG
+		if (regnarrate)
+			fprintf(stderr, "%s...\n", regprop(scan));
+#endif
+		next = regnext(scan);
+
+		switch (OP(scan)) {
+		case BOL:
+			if (reginput != regbol)
+				return(0);
+			break;
+		case EOL:
+			if (*reginput != '\0')
+				return(0);
+			break;
+		case WORDA:
+			/* Must be looking at a letter, digit, or _ */
+			if ((!isalnum(*reginput)) && *reginput != '_')
+				return(0);
+			/* Prev must be BOL or nonword */
+			if (reginput > regbol &&
+			    (isalnum(reginput[-1]) || reginput[-1] == '_'))
+				return(0);
+			break;
+		case WORDZ:
+			/* Must be looking at non letter, digit, or _ */
+			if (isalnum(*reginput) || *reginput == '_')
+				return(0);
+			/* We don't care what the previous char was */
+			break;
+		case ANY:
+			if (*reginput == '\0')
+				return(0);
+			reginput++;
+			break;
+		case EXACTLY: {
+				register int len;
+				register char *opnd;
+
+				opnd = OPERAND(scan);
+				/* Inline the first character, for speed. */
+				if (*opnd != *reginput)
+					return(0);
+				len = strlen(opnd);
+				if (len > 1 && strncmp(opnd, reginput, len) != 0)
+					return(0);
+				reginput += len;
+			}
+			break;
+		case ANYOF:
+ 			if (*reginput == '\0' || index(OPERAND(scan), *reginput) == NULL)
+				return(0);
+			reginput++;
+			break;
+		case ANYBUT:
+ 			if (*reginput == '\0' || index(OPERAND(scan), *reginput) != NULL)
+				return(0);
+			reginput++;
+			break;
+		case NOTHING:
+			break;
+		case BACK:
+			break;
+		case OPEN+1:
+		case OPEN+2:
+		case OPEN+3:
+		case OPEN+4:
+		case OPEN+5:
+		case OPEN+6:
+		case OPEN+7:
+		case OPEN+8:
+		case OPEN+9: {
+				register int no;
+				register char *save;
+
+				no = OP(scan) - OPEN;
+				save = reginput;
+
+				if (regmatch(next)) {
+					/*
+					 * Don't set startp if some later
+					 * invocation of the same parentheses
+					 * already has.
+					 */
+					if (regstartp[no] == NULL)
+						regstartp[no] = save;
+					return(1);
+				} else
+					return(0);
+			}
+			break;
+		case CLOSE+1:
+		case CLOSE+2:
+		case CLOSE+3:
+		case CLOSE+4:
+		case CLOSE+5:
+		case CLOSE+6:
+		case CLOSE+7:
+		case CLOSE+8:
+		case CLOSE+9: {
+				register int no;
+				register char *save;
+
+				no = OP(scan) - CLOSE;
+				save = reginput;
+
+				if (regmatch(next)) {
+					/*
+					 * Don't set endp if some later
+					 * invocation of the same parentheses
+					 * already has.
+					 */
+					if (regendp[no] == NULL)
+						regendp[no] = save;
+					return(1);
+				} else
+					return(0);
+			}
+			break;
+		case BRANCH: {
+				register char *save;
+
+				if (OP(next) != BRANCH)		/* No choice. */
+					next = OPERAND(scan);	/* Avoid recursion. */
+				else {
+					do {
+						save = reginput;
+						if (regmatch(OPERAND(scan)))
+							return(1);
+						reginput = save;
+						scan = regnext(scan);
+					} while (scan != NULL && OP(scan) == BRANCH);
+					return(0);
+					/* NOTREACHED */
+				}
+			}
+			break;
+		case STAR:
+		case PLUS: {
+				register char nextch;
+				register int no;
+				register char *save;
+				register int min;
+
+				/*
+				 * Lookahead to avoid useless match attempts
+				 * when we know what character comes next.
+				 */
+				nextch = '\0';
+				if (OP(next) == EXACTLY)
+					nextch = *OPERAND(next);
+				min = (OP(scan) == STAR) ? 0 : 1;
+				save = reginput;
+				no = regrepeat(OPERAND(scan));
+				while (no >= min) {
+					/* If it could work, try it. */
+					if (nextch == '\0' || *reginput == nextch)
+						if (regmatch(next))
+							return(1);
+					/* Couldn't or didn't -- back up. */
+					no--;
+					reginput = save + no;
+				}
+				return(0);
+			}
+			break;
+		case END:
+			return(1);	/* Success! */
+			break;
+		default:
+			regerror("memory corruption");
+			return(0);
+			break;
+		}
+
+		scan = next;
+	}
+
+	/*
+	 * We get here only if there's trouble -- normally "case END" is
+	 * the terminating point.
+	 */
+	regerror("corrupted pointers");
+	return(0);
+}
+
+/*
+ - regrepeat - repeatedly match something simple, report how many
+ */
+static int
+regrepeat(char* p)
+{
+	register int count = 0;
+	register char *scan;
+	register char *opnd;
+
+	scan = reginput;
+	opnd = OPERAND(p);
+	switch (OP(p)) {
+	case ANY:
+		count = strlen(scan);
+		scan += count;
+		break;
+	case EXACTLY:
+		while (*opnd == *scan) {
+			count++;
+			scan++;
+		}
+		break;
+	case ANYOF:
+		while (*scan != '\0' && index(opnd, *scan) != NULL) {
+			count++;
+			scan++;
+		}
+		break;
+	case ANYBUT:
+		while (*scan != '\0' && index(opnd, *scan) == NULL) {
+			count++;
+			scan++;
+		}
+		break;
+	default:		/* Oh dear.  Called inappropriately. */
+		regerror("internal foulup");
+		count = 0;	/* Best compromise. */
+		break;
+	}
+	reginput = scan;
+
+	return(count);
+}
+
+/*
+ - regnext - dig the "next" pointer out of a node
+ */
+static char *
+regnext(register char *p)
+{
+	register int offset;
+
+	if (p == &regdummy)
+		return(NULL);
+
+	offset = NEXT(p);
+	if (offset == 0)
+		return(NULL);
+
+	if (OP(p) == BACK)
+		return(p-offset);
+	else
+		return(p+offset);
+}
+
+#ifdef DEBUG
+#ifdef _KERNEL
+/*
+ - regdump - dump a regexp onto stdout in vaguely comprehensible form
+ */
+void
+regdump(regexp *r)
+{
+	register char *s;
+	register char op = EXACTLY;	/* Arbitrary non-END op. */
+	register char *next;
+	/*extern char *strchr();*/
+
+
+	s = r->program + 1;
+	while (op != END) {	/* While that wasn't END last time... */
+		op = OP(s);
+		printf("%2ld%s", s-r->program, regprop(s));	/* Where, what. */
+		next = regnext(s);
+		if (next == NULL)		/* Next ptr. */
+			printf("(0)");
+		else 
+			printf("(%ld)", (s-r->program)+(next-s));
+		s += 3;
+		if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
+			/* Literal string, where present. */
+			while (*s != '\0') {
+				putchar(*s);
+				s++;
+			}
+			s++;
+		}
+		putchar('\n');
+	}
+
+	/* Header fields of interest. */
+	if (r->regstart != '\0')
+		printf("start `%c' ", r->regstart);
+	if (r->reganch)
+		printf("anchored ");
+	if (r->regmust != NULL)
+		printf("must have \"%s\"", r->regmust);
+	printf("\n");
+}
+#endif /* #ifdef _KERNEL */
+
+/*
+ - regprop - printable representation of opcode
+ */
+static char *
+regprop(char *op)
+{
+	register char *p = "NONE";
+	static char buf[50];
+
+	(void) strcpy(buf, ":");
+
+	switch (OP(op)) {
+	case BOL:
+		p = "BOL";
+		break;
+	case EOL:
+		p = "EOL";
+		break;
+	case ANY:
+		p = "ANY";
+		break;
+	case ANYOF:
+		p = "ANYOF";
+		break;
+	case ANYBUT:
+		p = "ANYBUT";
+		break;
+	case BRANCH:
+		p = "BRANCH";
+		break;
+	case EXACTLY:
+		p = "EXACTLY";
+		break;
+	case NOTHING:
+		p = "NOTHING";
+		break;
+	case BACK:
+		p = "BACK";
+		break;
+	case END:
+		p = "END";
+		break;
+	case OPEN+1:
+	case OPEN+2:
+	case OPEN+3:
+	case OPEN+4:
+	case OPEN+5:
+	case OPEN+6:
+	case OPEN+7:
+	case OPEN+8:
+	case OPEN+9:
+		sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
+		p = NULL;
+		break;
+	case CLOSE+1:
+	case CLOSE+2:
+	case CLOSE+3:
+	case CLOSE+4:
+	case CLOSE+5:
+	case CLOSE+6:
+	case CLOSE+7:
+	case CLOSE+8:
+	case CLOSE+9:
+		sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
+		p = NULL;
+		break;
+	case STAR:
+		p = "STAR";
+		break;
+	case PLUS:
+		p = "PLUS";
+		break;
+	case WORDA:
+		p = "WORDA";
+		break;
+	case WORDZ:
+		p = "WORDZ";
+		break;
+	default:
+		regerror("corrupted opcode");
+		break;
+	}
+	if (p != NULL)
+		(void) strcat(buf, p);
+	return(buf);
+}
+#endif
+
+/*
+ * The following is provided for those people who do not have strcspn() in
+ * their C libraries.  They should get off their butts and do something
+ * about it; at least one public-domain implementation of those (highly
+ * useful) string routines has been published on Usenet.
+ */
+#ifdef STRCSPN
+/*
+ * strcspn - find length of initial segment of s1 consisting entirely
+ * of characters not from s2
+ */
+
+static int
+strcspn(char* s1, char* s2)
+{
+	register char *scan1;
+	register char *scan2;
+	register int count;
+
+	count = 0;
+	for (scan1 = s1; *scan1 != '\0'; scan1++) {
+		for (scan2 = s2; *scan2 != '\0';)	/* ++ moved down. */
+			if (*scan1 == *scan2++)
+				return(count);
+		count++;
+	}
+	return(count);
+}
+#endif
+
+/*
+ - regexec - match a regexp against a string
+ */
+int
+uregexec(register regexp *prog, register char *string)
+{
+	register char *s;
+	/*extern char *strchr();*/
+
+	/* Be paranoid... */
+	if (prog == NULL || string == NULL) {
+		regerror("NULL parameter");
+		return(0);
+	}
+
+	/* Check validity of program. */
+	if (UCHARAT(prog->program) != MAGIC) {
+		regerror("corrupted program");
+		return(0);
+	}
+
+	/* If there is a "must appear" string, look for it. */
+	if (prog->regmust != NULL) {
+		s = (char *)string;
+        /* modify by zhangjz ,Index is the kernel version of strchr !!*/
+		while ((s = index(s, prog->regmust[0])) != NULL) {
+			if (strncmp(s, prog->regmust, prog->regmlen) == 0)
+				break;	/* Found it. */
+			s++;
+		}
+		if (s == NULL)	/* Not present. */
+			return(0);
+	}
+
+	/* Mark beginning of line for ^ . */
+	regbol = (char *)string;
+
+	/* Simplest case:  anchored match need be tried only once. */
+	if (prog->reganch)
+		return(regtry(prog, string));
+
+	/* Messy cases:  unanchored match. */
+	s = (char *)string;
+	if (prog->regstart != '\0')
+		/* We know what char it must start with. */
+		while ((s = index(s, prog->regstart)) != NULL) {
+			if (regtry(prog, s)) {
+				return(1);
+			}
+			s++;
+		}
+	else
+		/* We don't -- general case. */
+		do {
+			if (regtry(prog, s)) {
+				return(1);
+			}
+		} while (*s++ != '\0');
+
+	/* Failure. */
+	return(0);
+}
+
+/*
+ - regtry - try match at specific point
+ */
+static int			/* 0 failure, 1 success */
+regtry(regexp * prog, char * string)
+{
+	register int i;
+	register char **sp;
+	register char **ep;
+	
+	reginput = string;
+	regstartp = prog->startp;
+	regendp = prog->endp;
+
+	sp = prog->startp;
+	ep = prog->endp;
+	for (i = NSUBEXP; i > 0; i--) {
+		*sp++ = NULL;
+		*ep++ = NULL;
+	}
+	if (regmatch(prog->program + 1)) {
+		prog->startp[0] = string;
+		prog->endp[0] = reginput;
+		return(1);
+	} else {
+		return(0);
+	}
+}

Property changes on: src/library/ca_regex/regexp_match.c
___________________________________________________________________
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: /branches/rel_avx_2_7_4/src/library/ca_util/Makefile
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_util/Makefile	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/library/ca_util/Makefile	(working copy)
@@ -3,16 +3,19 @@
 include $(TOP)/Makefile.master
 
 SRC = ca_util.c
-FLAGS =  -Wformat -Wall -Wno-long-long -O
-LINK = -lnode -lutil
+FLAGS =  -Wformat -Wall -Wno-long-long -O 
+
+LINK = -lnode -lutil -lcrypto -lcrypto-tls13
+
+
 
 all:  ca_util.o libcautil.a
 
 ca_util.o: ca_util.c  ca_util.h
-	$(CC) $(DEBUG) -fPIC $(FLAGS) $(INCLUDE) -c ca_util.c
+	$(CC) -fPIC  -I${TOP}/lib/libopenssl-1.1.1/include $(FLAGS) $(INCLUDE) -c ca_util.c
 
 libcautil.a:
-	$(AR) rs libcautil.a ca_util.o	
+	$(AR) rs libcautil.a ca_util.o 
 
 clean:
 	/bin/rm -f *.o *.core *.out *.a
Index: /branches/rel_avx_2_7_4/src/library/ca_util/ca_util.h
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_util/ca_util.h	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/library/ca_util/ca_util.h	(working copy)
@@ -325,6 +325,10 @@
 
 /*get random number*/
 extern long rand_num(void);
+
+int encrypt_passwd(unsigned char *decrypted_passwd, const char *key, char *encrypted_passwd, int output_len);
+int decrypt_passwd(unsigned char *encrypted_passwd, const char *key, char *decrypted_passwd, int output_len);
+
 /*extern int sleep_dot(int total, int interval);*/
 char * strrstr(char const *s1, char const *s2);
 const char* str_start_with(const char* haystack, const char* needle);
Index: /branches/rel_avx_2_7_4/src/library/ca_util/ca_util.c
===================================================================
--- /branches/rel_avx_2_7_4/src/library/ca_util/ca_util.c	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/library/ca_util/ca_util.c	(working copy)
@@ -73,10 +73,18 @@
 
 #include <sys/prctl.h>
 
+/*for AES encryption/decryption*/
+#include <openssl/evp.h>
+
 /*local lib*/
 #include "ca_util.h"
-#include "proxy_errs.h"
+#include "../../proxy_errs.h"
+
+#define AES_ENCRYPT_BUF_SIZE 512
 
+#define ROUND 5
+/* 8 bytes to salt the key_data during key generation. This is an example of compiled in salt.*/
+static char aes_salt[8] = "ARRAY-TM";
 
 /*define global variables*/
 int pflag = FALSE;     /*for debug print function: pprint use*/
@@ -86,6 +94,228 @@
 /* Initialize syslog(), if running as daemon. */
 char cur_path[MAX_LINE_SIZE + 1] = "";
 
+/*
+ *   This AES encryption/decryption functions using OpenSSL EVP apis
+ *     These implemention based on work of Saju Pillai (saju.pillai@gmail.com).
+ */
+
+
+extern int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
+                      const unsigned char *in, int inl);
+/*
+ * Encrypt *len bytes of data
+ * All data going in & out is considered binary (unsigned char[])
+ */
+unsigned char *aes_encrypt_helper(EVP_CIPHER_CTX *e, unsigned char *plaintext, int *len)
+{
+        /* max ciphertext len for a n bytes of plaintext is n + EVP_CIPHER_CTX_block_size(e) -1 bytes */
+        int c_len = *len + EVP_CIPHER_CTX_block_size(e), f_len = 0;
+        unsigned char *ciphertext = malloc(c_len);
+
+        /* allows reusing of 'e' for multiple encryption cycles */
+        EVP_EncryptInit_ex(e, NULL, NULL, NULL, NULL);
+
+        /* update ciphertext, c_len is filled with the length of ciphertext generated,
+ *         *len is the size of plaintext in bytes */
+        EVP_EncryptUpdate(e, ciphertext, &c_len, plaintext, *len);
+
+        /* update ciphertext with the final remaining bytes */
+        EVP_EncryptFinal_ex(e, ciphertext+c_len, &f_len);
+
+        *len = c_len + f_len;
+        return ciphertext;
+}
+
+/*
+ *  * Decrypt *len bytes of ciphertext
+ *   */
+unsigned char *aes_decrypt_helper(EVP_CIPHER_CTX *e, unsigned char *ciphertext, int *len)
+{
+        /* because we have padding ON, we must allocate an extra cipher block size of memory */
+        int p_len = *len, f_len = 0;
+        unsigned char *plaintext = malloc(p_len + EVP_CIPHER_CTX_block_size(e));
+
+        EVP_DecryptInit_ex(e, NULL, NULL, NULL, NULL);
+        EVP_DecryptUpdate(e, plaintext, &p_len, ciphertext, *len);
+        EVP_DecryptFinal_ex(e, plaintext+p_len, &f_len);
+
+        *len = p_len + f_len;
+        return plaintext;
+}
+
+int ca_aes_encrypt(unsigned char *plaintext, const char *input_key, unsigned char *ciphertext, int *output_len)
+{
+        /* "opaque" encryption, decryption ctx structures that libcrypto uses to record
+ *         status of enc operations */
+        EVP_CIPHER_CTX *en;
+
+        unsigned char *key_data;
+        int key_data_len, i;
+
+        /* the key_data is read from the argument list */
+        key_data = (unsigned char *)input_key;
+        key_data_len = strlen(input_key);
+
+        unsigned char key[32], iv[32];
+
+        /* 
+	* Gen key & IV for AES 256 CBC mode. A SHA1 digest is used to hash the supplied key material.
+	* nrounds is the number of times the we hash the material. More rounds are more secure but slower.
+ */
+        i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), (unsigned char *)&aes_salt, key_data, key_data_len, ROUND, key, iv);
+        if (i != 32) {
+               // englog(ENGLOG_CLI, CLI_SYS_ERR, "%s: Key size is %d bits - should be 256 bits\n", __FUNCTION__, i);
+                return -1;
+        }
+
+        en = EVP_CIPHER_CTX_new();
+        EVP_EncryptInit_ex(en, EVP_aes_256_cbc(), NULL, key, iv);
+
+        unsigned char *ciphertext_tmp;
+        int len;
+
+        /* The enc/dec functions deal with binary data and not C strings. strlen() will return length of the string without counting the '\0' string marker. We always pass in the marker byte to the encrypt/decrypt functions so that after decryption we end up with a legal C string */
+        len = strlen((char *)plaintext)+1;
+
+        ciphertext_tmp = aes_encrypt_helper(en, (unsigned char *)plaintext, &len);
+
+        if (len > *output_len) {
+                //englog(ENGLOG_CLI, CLI_SYS_ERR, "%s: Ciphertext is larger then given buffer size: %d, %d\n", __FUNCTION__, len, *output_len);
+                free(ciphertext_tmp);
+                EVP_CIPHER_CTX_free(en);
+                return -1;
+        }
+
+        memcpy(ciphertext, ciphertext_tmp, len);
+        *output_len = len;
+
+        free(ciphertext_tmp);
+        EVP_CIPHER_CTX_free(en);
+        return 0;
+}
+
+int ca_aes_decrypt(unsigned char *ciphertext, int cipher_len, const char *input_key, char *plaintext, int *output_len)
+{
+        /* "opaque" encryption, decryption ctx structures that libcrypto uses to record
+ *         status of enc operations */
+        EVP_CIPHER_CTX *de;
+
+        unsigned char *key_data;
+        int key_data_len, i;
+
+        /* the key_data is read from the argument list */
+        key_data = (unsigned char *)input_key;
+        key_data_len = strlen(input_key);
+
+        unsigned char key[32], iv[32];
+
+        /*
+	 * Gen key & IV for AES 256 CBC mode. A SHA1 digest is used to hash the supplied key material. * nrounds is the number of times the we hash the material. More rounds are more secure but slower 
+	 */
+        i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), (unsigned char *)&aes_salt, key_data, key_data_len, ROUND, key, iv);
+        if (i != 32) {
+               // englog(ENGLOG_CLI, CLI_SYS_ERR, "%s: Key size is %d bits - should be 256 bits\n", __FUNCTION__, i);
+                return -1;
+        }
+
+        de = EVP_CIPHER_CTX_new();
+        EVP_DecryptInit_ex(de, EVP_aes_256_cbc(), NULL, key, iv);
+
+        unsigned char *plaintext_tmp;
+        int len;
+
+        len = cipher_len;
+
+        plaintext_tmp = aes_decrypt_helper(de, ciphertext, &len);
+
+        if (len > *output_len) {
+                //englog(ENGLOG_CLI, CLI_SYS_ERR, "%s: Plaintext is larger then given buffer size: %d, %d\n", __FUNCTION__, len, *output_len);
+                free(plaintext_tmp);
+                EVP_CIPHER_CTX_free(de);
+                return -1;
+        }
+
+        memcpy(plaintext, plaintext_tmp, len);
+        *output_len = len;
+
+        free(plaintext_tmp);
+        EVP_CIPHER_CTX_free(de);
+        return 0;
+}
+
+unsigned char *base64_encrypt(unsigned char *decode_str, int decode_size)
+{
+   /* the last 1 byte is for the char \0 to end the string */
+   unsigned char *encode_str = malloc( (decode_size - 1) / 3 * 4 + 4 + 1);
+   EVP_EncodeBlock(encode_str, decode_str, decode_size);
+   return encode_str;
+}
+
+unsigned char *base64_decrypt(unsigned char *encode_str, int *decode_size)
+{
+  int encode_str_size = strlen((char *)encode_str);
+  unsigned char *decode_str = malloc(encode_str_size / 4 * 3);
+  int decode_size_tmp = EVP_DecodeBlock(decode_str, encode_str, encode_str_size);
+  /*we need to cut down the buffer size that padding with '\0'*/
+  while(encode_str[--encode_str_size] == '=') {
+    decode_size_tmp--;
+  }
+  *decode_size = decode_size_tmp;
+  return decode_str;
+}
+
+int decrypt_passwd(unsigned char *encrypted_passwd, const char *key, char *decrypted_passwd, int output_len)
+{
+        if(encrypted_passwd == NULL || encrypted_passwd[0] == '\0') {
+               // englog(ENGLOG_CLI, CLI_SYS_ERR, "%s: encrypted_passwd is invalid!\n", __FUNCTION__);
+                return -1;
+        }
+
+        /*1. decode passwd_in_db use base64_decrypt*/
+        int aes_en_size;
+        unsigned char* aes_en = base64_decrypt(encrypted_passwd, &aes_en_size);
+
+        /*2. decode aes_en_size use ca_aes_decrypt*/
+        int buf_size = output_len;
+        if (ca_aes_decrypt(aes_en, aes_en_size, key, decrypted_passwd, &buf_size)) {
+               // englog(ENGLOG_CLI, CLI_SYS_ERR, "%s: ca_aes_decrypt error!\n", __FUNCTION__);
+                free(aes_en);
+                return -1;
+        }
+
+        free(aes_en);
+        return 0;
+}
+
+int encrypt_passwd(unsigned char *decrypted_passwd, const char *key, char *encrypted_passwd, int output_len)
+{
+        if(decrypted_passwd == NULL || decrypted_passwd[0] == '\0') {
+               // englog(ENGLOG_CLI, CLI_SYS_ERR, "%s: decrypted_passwd is invalid!\n", __FUNCTION__);
+                return -1;
+        }
+
+        unsigned char encrypt[AES_ENCRYPT_BUF_SIZE];
+        int buf_size = AES_ENCRYPT_BUF_SIZE;
+
+        /*1. encode passwd_plain use ca_aes_encrypt*/
+        if (ca_aes_encrypt(decrypted_passwd, key, encrypt, &buf_size)) {
+               // englog(ENGLOG_CLI, CLI_SYS_ERR, "%s: ca_aes_encrypt error!\n", __FUNCTION__);
+                return -1;
+        }
+
+        /*2. encode encrypt use base64_encrypt*/
+        unsigned char *passwd_encrypt_tmp = base64_encrypt(encrypt, buf_size);
+        if (strlen((char *)passwd_encrypt_tmp) + 1 > output_len) {
+               // englog(ENGLOG_CLI, CLI_SYS_ERR, "%s: the encryption result's len is longer then provide buffer\n", __FUNCTION__);
+                free(passwd_encrypt_tmp);
+                return -1;
+        }
+
+        strlcpy(encrypted_passwd, (char *)passwd_encrypt_tmp, output_len);
+        free(passwd_encrypt_tmp);
+        return 0;
+}
+
 /**********************************
  **********************************
  *  string control functions
@@ -7397,4 +7627,4 @@
     }
     _FREE(new_src);
     return count;
-}
\ No newline at end of file
+}
Index: /branches/rel_avx_2_7_4/src/mgmt/Makefile
===================================================================
--- /branches/rel_avx_2_7_4/src/mgmt/Makefile	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/mgmt/Makefile	(working copy)
@@ -23,6 +23,8 @@
 
 AVX_APPS_LDFLAGS= -lxml2 -lvirt -lmsgpack -luuid
 
+AVX_SSL_LIBS_LDFLAGS= -L${TOP}/lib/libopenssl-1.1.1  -lcrypto-tls13 -lssl-tls13 -lcrypto -lssl
+
 FLAGS= -Wformat -g -Wall -Wno-long-long ${AVX_APPS_LDFLAGS} -lm \
     -L${TOP}/src/library/node_man/ -I${TOP}/src/library/node_man/ -lnode \
     -L${TOP}/src/library/ca_ui/ -I${TOP}/src/library/ca_ui/ -lcaui \
@@ -34,13 +36,16 @@
     -L${TOP}/lib/avxpci/ -I${TOP}/lib/avxpci/ -lavxpci \
     -L${TOP}/lib/casnmp/ -I${TOP}/lib/casnmp/ -lcasnmp \
     -L${TOP}/src/library/avx_log/ -I${TOP}/src/library/avx_log/ -lavxlog \
+    -L${TOP}/src/library/ca_regex/ -I${TOP}/src/library/ca_regex/ -lcaregex \
     -L${TOP}/lib/vtch/ -I${TOP}/lib/vtch/ -lvtch \
     -L${TOP}/src/library/avxha/ -I${TOP}/src/library/avxha/ -lavxha \
     -L${TOP}/src/library/avxssl/ -I${TOP}/src/library/avxssl/ -lavxssl \
     -I/usr/include/libvirt/ -I/usr/include/libxml2/ -lxmlrpc_util -lxmlrpc -lxmlrpc_client -lxml2 \
     -L${TOP}/kern/CNN55XX-SDK/api/ -lnitrox-1.3-01 -lutil \
     -lpthread -lcurl -lresolv -lpcre -ljson-c \
-    -L${TOP}/src/library/ca_util/ -I${TOP}/src/library/ca_util/ -lcautil \
+    -L${TOP}/lib/libopenssl-1.1.1  -lcrypto-tls13 -lssl-tls13 \
+    -lssl -lcrypto \
+    -lcrypto -L${TOP}/src/library/ca_util/ -I${TOP}/src/library/ca_util/ -lcautil \
     -L${TOP}/src/library/version/ -I${TOP}/src/library/version/ -lversion \
     -I${TOP}/src/library/avxresource/ -L${TOP}/src/library/avxresource/ -lavxresource \
     -I${TOP}/src
@@ -48,7 +53,7 @@
 all: ${TARGET} snmptool
 	
 ${TARGET}: ${AVX_MIB_INIT} 
-	${CC}  -fPIC -shared -g ${NET_SNMP_CFLAGS} ${AVX_APPS_CFLAGS} ${AVX_APPS_LDFLAGS} ${NET_SNMP_LIBS} $<  ${AVX_MIB_SRCS} ${AVX_APPS_LIB_STATIC} -ljson-c -o $@ 
+	${CC}  -fPIC -shared -g ${NET_SNMP_CFLAGS} ${AVX_APPS_CFLAGS} ${AVX_APPS_LDFLAGS} ${NET_SNMP_LIBS} $<  ${AVX_MIB_SRCS} ${AVX_SSL_LIBS_LDFLAGS} ${AVX_APPS_LIB_STATIC} -ljson-c -o $@ 
 
 ${AVX_MIB_INIT}: ${AVX_MIB_SRCS} ${AVX_MIB_HEADS}
 	@echo "Generate a new $@"
Index: /branches/rel_avx_2_7_4/src/monitord/Makefile
===================================================================
--- /branches/rel_avx_2_7_4/src/monitord/Makefile	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/monitord/Makefile	(working copy)
@@ -10,7 +10,7 @@
 
 INST_BIN=$(TARGET)
 
-INCLUDE+= -I../library/avx_log -I../../lib/feactl -I../../lib/avxpci -I../../lib/casnmp
+INCLUDE+= -I../library/avx_log -I../../lib/feactl -I../../lib/avxpci -I../../lib/casnmp -I${TOP}/src/library/ca_mail -I../library/ca_regex
 
 # This include a fake SLB library for testing.
 LIBS= $(LIBRARY) -lutil -lxmlrpc_util -lxmlrpc -lxmlrpc_client
@@ -18,6 +18,10 @@
 #Ticket-SmartDNS: link with sdns cli lib
 LIBS+= -L$(TOP)/src/library/avx_log -lavxlog \
 	-L$(TOP)/src/library/ca_ui -lcaui \
+	-L$(TOP)/src/library/ca_regex -lcaregex \
+	-L${TOP}/src/library/ca_mail -lcamail \
+	-L${TOP}/lib/libopenssl-1.1.1  -lcrypto-tls13 -lssl-tls13 \
+	-lssl -lcrypto \
 	-L$(TOP)/src/library/ca_util -lcautil \
 	-L$(TOP)/src/library/node_man -lnode \
 	-L$(TOP)/src/library/management -lsuppress_print \
@@ -30,14 +34,14 @@
 	-L$(TOP)/kern/CNN55XX-SDK/api/ -lnitrox-1.3-01 \
 	-L$(TOP)/lib/vtch/ -lvtch \
 	-L$(TOP)/lib/casnmp/ -lcasnmp \
-	-L$(TOP)/src/library/ca_util -lcautil \
+	-lcrypto -L$(TOP)/src/library/ca_util -lcautil \
 	-L$(TOP)/src/library/version -lversion \
 	-L$(TOP)/src/library/avxha -lavxha \
 	-lxml2  -pthread -lmsgpack -lvirt -lresolv -lpcre -lcurl  -luuid \
 	-I${TOP}/src/library/avxresource/ -L${TOP}/src/library/avxresource/ -lavxresource	
 
-SRC=monitor_daemon.c monitor_timer.c monitor_routine.c avx_monitor.c port_monitor.c disk_monitor.c
-OBJS=monitor_daemon.o monitor_timer.o monitor_routine.o avx_monitor.o port_monitor.o disk_monitor.o
+SRC=monitor_daemon.c monitor_timer.c monitor_routine.c avx_monitor.c port_monitor.c disk_monitor.c eventlog_monitor.c
+OBJS=monitor_daemon.o monitor_timer.o monitor_routine.o avx_monitor.o port_monitor.o disk_monitor.o eventlog_monitor.o
 
 FLAGS = $(JSON_LIB) ${INCLUDE} -Wformat -Wall -Wno-long-long -Werror -O
 
@@ -61,5 +65,8 @@
 disk_monitor.o: disk_monitor.c
 	$(CC) $(DEBUG) $(FLAGS) $(INCLUDE) $(DEFINES)  -c $<
 
+eventlog_monitor.o: eventlog_monitor.c
+	$(CC) $(DEBUG) $(FLAGS) $(INCLUDE) $(DEFINES)  -c $<
+
 clean:
 	$(RM) -f *.o *.core *.out  $(TARGET)
Index: /branches/rel_avx_2_7_4/src/monitord/eventlog_monitor.h
===================================================================
--- /branches/rel_avx_2_7_4/src/monitord/eventlog_monitor.h	(revision 0)
+++ /branches/rel_avx_2_7_4/src/monitord/eventlog_monitor.h	(working copy)
@@ -0,0 +1,6 @@
+#ifndef __EVENTLOG_MONITOR_H__
+#define __EVENTLOG_MONITOR_H__
+
+extern int eventlog_monitor(void);
+
+#endif
Index: /branches/rel_avx_2_7_4/src/monitord/eventlog_monitor.c
===================================================================
--- /branches/rel_avx_2_7_4/src/monitord/eventlog_monitor.c	(revision 0)
+++ /branches/rel_avx_2_7_4/src/monitord/eventlog_monitor.c	(working copy)
@@ -0,0 +1,412 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <signal.h>
+#include <sys/time.h> /*for gettimeofday*/
+#include <sys/wait.h>
+#include <sys/shm.h>
+#include <unistd.h>  /*for pause*/
+#include <sys/types.h>
+#include <sys/stat.h>
+#include "sys_mail.h"
+#include <syslog.h>
+#define ROOT_MAIL_PATH "/var/mail/root"
+#define ROOT_MAIL_MAXSIZE 10485760 /*10M*/
+
+#include "eventlog_monitor.h"
+#include "avx_log.h"
+#include "../proxy_shm.h"
+#define FASTLOG_MAX_LINE_SIZE 100
+#define FASTLOG_MAX_LONG_TOKEN_SIZE 40
+#define FASTLOG_MAX_ALERT_NUM 2
+
+#define target_email                 "ngurunathan@arraynetworks.com"
+#define RM_MAIL                      "/bin/rm -rf /var/spool/mqueue/*"
+#define SENDMAIL_PATH                "/usr/sbin/sendmail"
+#define SENDMAIL_HEADER_FROM         "From: %s<alert@log.domain>\n"
+#define SENDMAIL_HEADER_TO           "To: Alert Log System Operator(s)<%s>\n"
+#define SENDMAIL_HEADER_SUBJECT      "Subject: Log Alert ID: %d - %s\n"
+#define SENDMAIL_MESSAGE_COUNT       "ID %d: match %d time(s).\n"
+
+/* ssmtp is not supported on debian 10, use msmtp instead*/
+#if defined(__linux__)
+#define SSMTP_PATH                   "/usr/sbin/ssmtp"
+#define SSMTP_PATH_BIN               "ssmtp"
+
+#ifdef UOS_X86
+#undef  SSMTP_PATH
+#undef  SSMTP_PATH_BIN
+#define SSMTP_PATH                   "/usr/bin/msmtp"
+#define SSMTP_PATH_BIN               "msmtp"
+
+#endif
+#else
+#define SSMTP_PATH                   "/usr/local/sbin/ssmtp"
+#endif
+#define FROM_STR_SSMTP               "From: <%s>\n"
+#define FROM_STR                     "From: "
+
+char *get_from_header(char *hostname);
+char *get_sender_name(char *from_header);
+
+sys_mail_conf_t *sys_mail_conf_p;
+int shm_init_done=0;
+static int
+eventlog_shm_init(void)
+{
+        int shm_id = 0;
+
+        shm_id = shmget(SYS_MAIL_SHM_KEY, SYS_MAIL_SHM_SZ,
+                        SYS_MAIL_SHM_MODE|IPC_CREAT);
+        if (shm_id == -1) {
+                return -1;
+        }
+
+        sys_mail_conf_p = (sys_mail_conf_t *)shmat(shm_id, NULL, 0);
+        if (sys_mail_conf_p == NULL) {
+                return -1;
+        }
+
+        bzero(sys_mail_conf_p, sizeof(sys_mail_conf_t));
+        shm_init_done=1;
+
+        return 0;
+}
+log_alert_buffer_t*
+attach_log_alert_buffer(void)
+{
+        int shm_id = 0;
+	log_alert_buffer_t* log_alert = NULL;
+
+        shm_id = shmget(LOG_ALERT_BUF_SHM_KEY, 0, 0);
+        if (shm_id == -1) {
+                return NULL;
+        }
+
+        log_alert = (log_alert_buffer_t *)shmat(shm_id, NULL, 0);
+        if (log_alert == (log_alert_buffer_t *)-1) {
+                return NULL;
+        }
+        if (log_alert->magic_count != LOG_SHM_MAGIC) {
+                syslog(LOG_INFO, "Warning: logalert shared memory not initialized yet");
+                return NULL;
+        } 
+	
+
+        return log_alert;
+}
+
+log_mbox_buffer_t*
+attach_mbox_buffer(void)
+{
+        int shm_id = 0;
+        log_mbox_buffer_t* mbox_buffer = NULL;
+
+        shm_id = shmget(LOG_MBOX_BUF_SHM_KEY, 0, 0);
+        if (shm_id == -1) {
+                return NULL;
+        }
+
+        mbox_buffer = (log_mbox_buffer_t *)shmat(shm_id, NULL, 0);
+        if (mbox_buffer == (log_mbox_buffer_t *)-1) {
+                return NULL;
+        }
+
+        return mbox_buffer;
+}
+
+int
+detach_mbox(log_mbox_buffer_t *mbox_buffer)
+{
+        if (mbox_buffer != NULL) {
+                shmdt(mbox_buffer);
+                mbox_buffer = NULL;
+        }
+
+        return 0;
+}
+
+int
+detach_log_alert(log_alert_buffer_t* log_alert_buf)
+{
+        if (log_alert_buf != NULL) {
+                shmdt(log_alert_buf);
+                log_alert_buf = NULL;
+        }
+
+        return 0;
+}
+
+
+int eventlog_monitor(void){
+    if (!shm_init_done) {
+        if (eventlog_shm_init() == -1) {
+	    return -1;
+        }
+    }
+    log_alert_t *alert;
+    log_mbox_t *mbox;
+   log_alert_buffer_t* log_alert_buf;
+    log_alert_buf = attach_log_alert_buffer();
+    if(!log_alert_buf)
+    {
+    syslog(LOG_INFO,"log alert buf is null. returning");
+    return -1;
+    }
+    avx_log(LOG_IDX_CLI_AUTH_LOGIN, 1, "EVENTLOG_MONITOR");
+    log_mbox_buffer_t * mbox_buf=attach_mbox_buffer();
+    if(!mbox_buf) {
+    syslog(LOG_INFO,"mbox buf is null, returning");
+    return -1;
+    }
+
+    /*help variables*/
+    char str[FASTLOG_MAX_LINE_SIZE + 1] = "";
+    char hostname[FASTLOG_MAX_LONG_TOKEN_SIZE + 1] = "";
+    int fd[2];   /*for the pipe between the parent and the child*/
+    int pid;
+    int i, j;
+
+    //char *email;
+    struct stat sstat;
+    char *from;
+    char *sender;
+
+    
+    system(RM_MAIL);
+
+
+    memset(hostname, 0, sizeof(hostname));
+    if (gethostname(hostname, sizeof(hostname) -1) < 0) {
+
+        //do nothing for now
+    }
+
+        from = get_from_header(hostname);
+        sender = get_sender_name(from);
+    
+    //send the data out
+    for (i = 1; i <= AVX_LOG_MAX_ALERT_NUM; i++) {
+
+        alert = &log_alert_buf->alerts[i];
+        mbox = &mbox_buf->mboxes[i];
+        if (  (alert->flags & AVX_LOG_ALERT_INUSE) &&
+              (!alert->timer) &&
+              ( ( (alert->flags & AVX_LOG_ALERT_COUNT) && (alert->count) ) ||
+                  (mbox->len > 0) ) ) {
+
+            //setup the pipe between the parent and the child
+            if (pipe(fd) < 0) {
+
+                //currently do nothing
+                return -1;
+            }
+
+            //fork the child process to send the email
+            if ((pid = fork()) < 0) {
+
+                //currently do nothing, but return
+                return -1;
+            }
+
+            if (!pid) {
+
+                //in child process, send the mail, but need to read message
+        
+
+                //close standard file descriptors
+                close(STDIN_FILENO);
+                close(STDOUT_FILENO);
+                close(STDERR_FILENO);
+
+                //close fd[1], that is used by the parent, dup stdin, out to fd[0]
+                close(fd[1]);
+                dup(fd[0]);
+                dup(fd[0]);
+
+                //remove if the /var/mail/root reaches the limit size ROOT_MAIL_MAXSIZE
+                bzero(&sstat, sizeof(sstat));
+                if((stat(ROOT_MAIL_PATH, &sstat) == 0) && (sstat.st_size >= ROOT_MAIL_MAXSIZE)) {
+                   unlink(ROOT_MAIL_PATH);
+                }
+
+                if (sys_mail_conf_p->extern_mail_on) {
+                        if (execl(SSMTP_PATH, SSMTP_PATH_BIN, alert->email, NULL) < 0) {
+                                printf("Error in %s.\n",SSMTP_PATH_BIN);
+                                exit(-1);
+                        }
+
+                } else {
+                        if (sys_mail_conf_p->hostname_behavior) {
+                                if (execl(SENDMAIL_PATH, "sendmail", "-C", SENDMAIL_CONF_FILE, "-f", sender,
+                                                "-t", alert->email, NULL) < 0) {
+                                        printf("Error in sendmail.\n");
+                                        exit(-1);
+                                }
+                        } else {
+                                if (execl(SENDMAIL_PATH, "sendmail", "-f", sender,
+                                                "-t", alert->email, NULL) < 0) {
+                                        printf("Error in sendmail.\n");
+                                        exit(-1);
+                                }
+                        }
+                }
+
+                exit(0);
+            }
+
+            //now, in parent, close fd[1]
+            close(fd[0]);
+
+            if (sys_mail_conf_p->extern_mail_on) {
+                    snprintf(str, sizeof(str), FROM_STR_SSMTP, sys_mail_conf_p->mextern_server.user);
+                    write(fd[1], str, strlen(str));
+            } else {
+                    write(fd[1], from, strlen(from));
+            }
+
+            snprintf(str, sizeof(str), SENDMAIL_HEADER_TO, alert->email);
+	    syslog(LOG_INFO, "to %s",str);
+            write(fd[1], str, strlen(str));
+
+            //subject is like: ID 5: fail*return 
+        
+	snprintf(str, sizeof(str), SENDMAIL_HEADER_SUBJECT, i, alert->match);
+
+	    
+	    syslog(LOG_INFO, "sub %s",str);
+            write(fd[1], str, strlen(str));
+
+            if (sys_mail_conf_p->extern_mail_on) {
+                    //we need to insert a extra \n between subject and body if we use ssmtp tool
+                    write(fd[1], "\n", 1);
+            }
+
+            //begin to send data
+            if (alert->flags & AVX_LOG_ALERT_COUNT) {
+
+                //need to combinize the string
+                snprintf(str, sizeof(str), SENDMAIL_MESSAGE_COUNT, i, alert->count);
+                write(fd[1], str, strlen(str));
+            }
+            else {
+                
+                //get data from mbox
+                //get data from dedicated mbox firstly
+                write(fd[1], mbox->data, mbox->len);
+                if (mbox->len > (AVX_LOG_MAX_DATA_SIZE - MAX_LOG_STRING) ) {
+
+                    //check the extra mboxes
+                    for (j = AVX_LOG_MAX_ALERT_NUM + 1; j < AVX_LOG_MAX_MBOX_NUM; j++) {
+
+                        mbox = &mbox_buf->mboxes[j];
+                        if (mbox->id == i)    
+                            write(fd[1], mbox->data, mbox->len);
+                    }
+                }
+            }
+
+            //send out all the data
+            close(fd[1]);
+        }
+    }
+    log_alert_data_reset();
+    detach_log_alert(log_alert_buf);
+    detach_mbox(mbox_buf);
+    return 0;
+}
+
+#define MAX_FROM_HEADER_LEN             1024
+
+char *
+get_from_header(char *hostname)
+{
+        int esc = 0, n = 0;
+        char *str = sys_mail_conf_p->from;
+        static char from[MAX_FROM_HEADER_LEN + 1];
+
+        n += sprintf((from+n), FROM_STR);
+        while (*str) {
+                if (esc == 1) {
+                        esc = 0;
+                        switch (*str) {
+                        case 'h':
+                                n += sprintf((from+n), "%s", hostname);
+                                break;
+
+                        case 'q':
+                                n += sprintf((from+n), "\"");
+                                break;
+
+                        case '%':
+                                n += sprintf((from+n), "%%");
+                                break;
+
+                        default:
+                                break;
+                        }
+                } else if (*str == '%') {
+                        esc = 1;
+                } else {
+                        n += sprintf((from+n), "%c", *str);
+                }
+
+                str++;
+        }
+
+        n += sprintf((from+n), "\n");
+        /*write(fd, from, n);*/
+
+        return from;
+}
+
+/*
+*Get sender name from from header:
+*From: tmx@arraynetworks.com.cn\n       ->     tmx
+*From: hostname<alert@log.domain>\n     ->     alert
+*From: AN\n                             ->     AN
+*/
+char *
+get_sender_name(char *from_header)
+{
+        static char name[MAX_FROM_HEADER_LEN + 1];
+        char *at_pos = NULL;
+        char *beg_pos = NULL;
+
+        if ((at_pos = strchr(from_header, '@')) != NULL) {
+                beg_pos = at_pos;
+
+                do {
+                        beg_pos--;
+                } while((*beg_pos != '<') && beg_pos != from_header);
+
+                /*From: hostname<alert@log.domain>\n     ->     alert*/
+                if (*beg_pos == '<') {
+                        beg_pos++;
+                } else  {
+                        /*From: tmx@arraynetworks.com.cn\n       ->     tmx*/
+                        if(strncmp(from_header, FROM_STR, strlen(FROM_STR)) == 0) {
+                        beg_pos = from_header + strlen(FROM_STR);
+                        }
+                }
+
+                *at_pos = '\0';
+                sprintf(name, beg_pos);
+                *at_pos = '@';
+
+        } else {
+
+                /*From: AN\n    ->     AN*/
+                beg_pos = from_header;
+                if(strncmp(from_header, FROM_STR, strlen(FROM_STR)) == 0) {
+                        beg_pos = beg_pos + strlen(FROM_STR);
+                }
+
+                strncpy(name, beg_pos, strlen(beg_pos)-1);
+                *(name+strlen(beg_pos)-1)= '\0';
+
+        }
+        return name;
+}
+
+
Index: /branches/rel_avx_2_7_4/src/monitord/monitor_daemon.c
===================================================================
--- /branches/rel_avx_2_7_4/src/monitord/monitor_daemon.c	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/monitord/monitor_daemon.c	(working copy)
@@ -31,11 +31,13 @@
 #include "port_monitor.h"
 #include "avx_ul.h"
 #include "disk_monitor.h"
+#include "eventlog_monitor.h"
 
 static pid_t avx_mon;
 static pid_t lickey_mon;
 static pid_t port_mon;
 static pid_t disk_mon;
+static pid_t eventlog_mon;
 int debugmode = 0;
 
 static void
@@ -44,6 +46,7 @@
 	// remove all timer process
 	remove_timer(avx_mon);
 	remove_timer(lickey_mon);
+	remove_timer(eventlog_mon);
 	remove_routine(port_mon);
 }
 
@@ -100,11 +103,12 @@
 		printf("Failed to daemonize the program, error: %s\n", strerror(errno));
 		return ret;
 	}
-
 	avx_mon = add_timer(3, (timer_callback_t)avx_monitor);
+
 	lickey_mon = add_timer(60*60, (timer_callback_t)lickey_monitor);
 	port_mon = add_timer(1, (timer_callback_t)port_status_monitor);//add_routine(port_monitor);
 	disk_mon = add_timer(60*30, (timer_callback_t)disk_monitor);
+	eventlog_mon = add_timer(3, (timer_callback_t)eventlog_monitor);
 
 	ret = monitor_wait();
 
Index: /branches/rel_avx_2_7_4/src/proxy_shm.h
===================================================================
--- /branches/rel_avx_2_7_4/src/proxy_shm.h	(revision 9092)
+++ /branches/rel_avx_2_7_4/src/proxy_shm.h	(working copy)
@@ -125,4 +125,6 @@
 
 #define WEBUI_CONIFG_SHM_KEY         43000
 
+#define LOG_ALERT_BUF_SHM_KEY        42002
+#define LOG_MBOX_BUF_SHM_KEY         42003
 #endif				/* ifndef (_CA_SHM_H_) */
