/****************************************************************/
/*Title:	ftpsend.c					*/
/*Descr:						*/
/*Author:						*/
/*Create:						*/
/*Version:	1.0						*/
/*Modify: 							*/
/****************************************************************/
#define FTP_LOG_PATH	"/usr/local/omc/log"
#define FTP_LOG_FILE	"ftpsend"

#include <stdlib.h>	
#include <string.h>
#include <stdio.h>	
#include <time.h>
#include <dirent.h>	
#include <sys/stat.h>
#ifndef _LINUX_ES
	#include "mysql.h"
#else
	#include "/usr/include/mysql/mysql.h"
#endif
	
#include "../../../omcLib/c_program/ftp/ftp.h"
#include "ftpsend.h"

/******************************************************/
/******            Heartbeat Parameter           ******/
/******************************************************/
DWORD PROC_HEARTBEAT_OID[12]={1,3,6,1,4,1,1373,2,4,10,8};
int PROC_HEARTBEAT_OIDLEN=11;
int sendHeartbeat();

static MYSQL *omcPub_conn;
/***********  variables for send cdr file to the mss  ****************/
static MYSQL *cdrdb_conn;
static char serverinfo[128],*username,*pwd,*serverip,*remotepath;
static char localpath[128],sent_dir[128];
/*********** variables for send csta file to the mss  *****************/
static MYSQL *cstadb_conn;
static char csta_serverinfo[128],*csta_username,*csta_pwd,*csta_serverip,*csta_remotepath;
static char csta_localpath[128],csta_sent_dir[128];
/*********** variables for send normal file **************************/
int csta_send_flag=0;
int cdr_send_flag=0;

FileTransfer file_transfers[MAX_FILE_TRANSFER_NUM];
int g_file_transfer_count;

void fileTransUpdate(void);
void printfFileObject(FileTransfer* ft);
void send_normal_file(void);


//static int ftp_port = 21;
static struct itimerval itimer, old_itimer;
FILE *ftplog_fp;


static void On_Timer();
static void SetTimer();
static void send_init();
static void ftpsend_timer();
static void send_file();
static void send_cstafile();
static void send_log(const char *fmt, ...);
static void sendlog_init();
static void sendlog_timer();





int main(int argc, char *argv[]){
	pid_t pid;
	if (argc == 2 && strstr(argv[1], "-d")) {
		if ((pid = fork()) != 0)
			exit(0);
		setsid();
	}
	
	debug_init(1);
	iptrans_init();
	snmp_init(4957);
	//heartbeat_init(0);
	
	sendlog_init();
	send_init();	
	SetTimer();
	while (1) {
		sleep(1);
	}
	return 1;
}

/*************************************************
Function:        // send_init
Description:     // 初始化一些公共参数,如远程服务器IP地址,登陆用户名和密码
Calls:           // 
Called By:       // main
Table Accessed:  // OMC_DB.omcPubVarConf; CDR_DB.cdrPubVarConf;
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 
Others:          // 
*************************************************/
void send_init()
{	
	char sqlstr[256],*pchr;
	int len;
	MYSQL_RES *res;
	MYSQL_ROW row;

	//初始化OMC_PUB数据库连接
	printf("init ftpsend......\n");
	
	omcPub_conn=mysql_conn("localhost","OMC_PUB");
	if(omcPub_conn == NULL)
		send_log("[ERR][send_init]:mysql_conn OMC_PUB");

	//update the information of file transfer object
	fileTransUpdate();

	cdrdb_conn=mysql_conn("localhost","CDR_DB");
	if(cdrdb_conn == NULL)
		send_log("[ERR][send_init]:mysql_conn CDR_DB");
	
	//**********************************************	
	//获得CDR_DB.cdrPubVarConf表中sending_directory的值
	sprintf(sqlstr,
			"SELECT pubVarValue FROM CDR_DB.cdrPubVarConf WHERE pubVarName='sending_directory'");
	
	res=mysql_getres(cdrdb_conn,sqlstr);
	if(res == NULL)
	{
		send_log("[ERR %d][send_init]:%s",mysql_errno(cdrdb_conn),sqlstr);
		return;
	}

	if((row = mysql_fetch_row(res)) != NULL) {
		strcpy(localpath,row[0]);
	}

	mysql_free_result(res);
		
	len = strlen(localpath);
	if (localpath[len-1] != '/'&&len<127){
		localpath[len]='/';
		localpath[len+1]='\0';
	}	

	//获得CDR_DB.cdrPubVarConf表中sent_directory的值
	sprintf(sqlstr,
			"SELECT pubVarValue FROM CDR_DB.cdrPubVarConf WHERE pubVarName='sent_directory'");
			
	res=mysql_getres(cdrdb_conn,sqlstr);
	if(res == NULL)
	{
		send_log("[ERR %d][send_init]:%s",mysql_errno(cdrdb_conn),sqlstr);
		return;
	}
		
	if((row = mysql_fetch_row(res)) != NULL) {
		strcpy(sent_dir,row[0]);
	}

	mysql_free_result(res);
		
	len = strlen(sent_dir);
	if (sent_dir[len-1] != '/'&&len<127){
		sent_dir[len]='/';
		sent_dir[len+1]='\0';
	}

	
	//**********************************************	
	//获取OMC_PUB.omcPubVarConf表中cdr_store_server的值
	sprintf(sqlstr,
			"SELECT pubVarValue FROM OMC_PUB.omcPubVarConf WHERE pubVarName='cdr_store_server'");
	
	res=mysql_getres(omcPub_conn,sqlstr);
	if(res == NULL)
	{
		send_log("[ERR %d][send_init]:%s",mysql_errno(omcPub_conn),sqlstr);
		return;
	}

	if((row = mysql_fetch_row(res)) != NULL) {
		strcpy(serverinfo,row[0]);
	}
	
	mysql_free_result(res);
	
	//user:password@ip>location
	
	len = strlen(serverinfo);
	
	if(len>5)
	{	
		if (serverinfo[len-1] != '/'&&len<127){
			serverinfo[len]='/';
			serverinfo[len+1]='\0';
		}	
		
		//ftp登陆用户名
		username = serverinfo;
		if((pchr = strstr(serverinfo, ":"))==NULL){
			send_log("[ERROR]cdr_store_server param error!\n");
			return;
		}
		*(pchr++) = '\0';
		
		//ftp登陆密码
		pwd = pchr;		
		if((pchr = strstr(pwd, "@"))==NULL){
			send_log("[ERROR]cdr_store_server param error!\n");
			return;
		}
		*(pchr++) = '\0';
		
		//ftp服务器IP地址
		serverip = pchr;//get password
		if((pchr = strstr(serverip, ">"))==NULL){
			send_log("[ERROR]cdr_store_server param error!\n");
			return;
		}
		*(pchr++) = '\0';
		
		//将要发送到远程服务器的目录
		remotepath = pchr;
		cdr_send_flag=1;
	}
	else
	{
		cdr_send_flag=0;
	}		
	//printf("%s--%s--%s--%s--%s\n",username,pwd,serverip,remotepath,localpath);		
	//**********************************************	
	
	
	//Get the parameter of sending csta to the mss
	cstadb_conn=mysql_conn("localhost","CSTA_DB");
	if(cstadb_conn == NULL)
		send_log("[ERR][send_init]:mysql_conn CSTA_DB");
	
	//**********************************************	
	//获得CSTA_DB.cstaPubVarConf表中sending_directory的值
	sprintf(sqlstr,
			"SELECT pubVarValue FROM CSTA_DB.cstaPubVarConf WHERE pubVarName='sending_directory'");
	
	res=mysql_getres(cstadb_conn,sqlstr);
	if(res == NULL)
	{
		send_log("[ERR %d][send_init]:%s",mysql_errno(cstadb_conn),sqlstr);
		return;
	}

	if((row = mysql_fetch_row(res)) != NULL) {
		strcpy(csta_localpath,row[0]);
	}
	
	mysql_free_result(res);
	
	len = strlen(csta_localpath);
	
	if (csta_localpath[len-1] != '/'&&len<127){
		csta_localpath[len]='/';
		csta_localpath[len+1]='\0';
	}	
	
	//printf("hi %s\n",csta_localpath);
	
	//获得CSTA_DB.cstaPubVarConf表中sent_directory的值
	sprintf(sqlstr,
			"SELECT pubVarValue FROM CSTA_DB.cstaPubVarConf WHERE pubVarName='sent_directory'");
	
	res=mysql_getres(cstadb_conn,sqlstr);
	if(res == NULL)
	{
		send_log("[ERR %d][send_init]:%s",mysql_errno(cstadb_conn),sqlstr);
		return;
	}
		
	if((row = mysql_fetch_row(res)) != NULL) {
		strcpy(csta_sent_dir,row[0]);
	}
	
	mysql_free_result(res);
		
	len = strlen(csta_sent_dir);
	if (csta_sent_dir[len-1] != '/'&&len<127){
		csta_sent_dir[len]='/';
		csta_sent_dir[len+1]='\0';
	}
	
	//printf("\nhi %s\n",csta_sent_dir);
	
	//**********************************************	
	//获取OMC_PUB.omcPubVarConf表中csta_store_server的值
	sprintf(sqlstr,
			"SELECT pubVarValue FROM OMC_PUB.omcPubVarConf WHERE pubVarName='csta_store_server'");
				
	res=mysql_getres(omcPub_conn,sqlstr);
	if(res == NULL)
	{
		send_log("[ERR %d][send_init]:%s",mysql_errno(omcPub_conn),sqlstr);
		return;
	}
	
	if((row = mysql_fetch_row(res)) != NULL) {
		strcpy(csta_serverinfo,row[0]);
	}
	
	mysql_free_result(res);
	
	//user:password@ip>location
	
	len = strlen(csta_serverinfo);
	if(len>5)
	{	
		if (csta_serverinfo[len-1] != '/'&&len<127){
			csta_serverinfo[len]='/';
			csta_serverinfo[len+1]='\0';
		}	
		
		//printf("\nhi  %s\n",csta_serverinfo);
		
		//ftp登陆用户名
		csta_username = csta_serverinfo;
		if((pchr = strstr(csta_serverinfo, ":"))==NULL){
			send_log("[ERROR]csta_store_server param error!\n");
			return;
		}
		*(pchr++) = '\0';
		
		//ftp登陆密码
		csta_pwd = pchr;		
		if((pchr = strstr(csta_pwd, "@"))==NULL){
			send_log("[ERROR]csta_store_server param error!\n");
			return;
		}
		*(pchr++) = '\0';
		
		//ftp服务器IP地址
		csta_serverip = pchr;//get password
		if((pchr = strstr(csta_serverip, ">"))==NULL){
			send_log("[ERROR]csta_store_server param error!\n");
			return;
		}
		*(pchr++) = '\0';
		
		//将要发送到远程服务器的目录
		csta_remotepath = pchr;
		csta_send_flag=1;
	}
	else
	{
		csta_send_flag=0;
	}		
	//printf("csta   %s--%s--%s--%s--%s\n",csta_username,csta_pwd,csta_serverip,csta_remotepath,csta_localpath);	
	
	//printf("OK\n");
	
	return;
}

/*************************************************
Function:        // fileTransUpdate
Description:     // 更新fileTansfer对象信息
Calls:           // 
Called By:       // ftpsend_timer
Table Accessed:  // 
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 
Others:          // 该函数每分钟调用一次
*************************************************/
void fileTransUpdate()
{
	MYSQL_RES *res;
	MYSQL_ROW row;
	char sqlstr[256];
	int file_object_count;
	int len;
	
	//Update the file transfer object from the OMC_PUB.fileTransConf
	sprintf(sqlstr,"SELECT srcDir,dstDir,dstIP,filter,logName,logPass FROM OMC_PUB.fileTransConf where type=0");
	
	res=mysql_getres(omcPub_conn,sqlstr);
	if(res == NULL)
	{
		send_log("[ERR %d][fileTransUpdate]:%s",mysql_errno(omcPub_conn),sqlstr);
		return;
	}

	//Update the HPMN servers information
	file_object_count=0;
	while((row = mysql_fetch_row(res)) != NULL)
	{
		//Get the srcDir
		sprintf(file_transfers[file_object_count].srcDir,"%s",row[0]);
		//Get the dstDir
		sprintf(file_transfers[file_object_count].dstDir,"%s",row[1]);
		//Get the dstIP
		sprintf(file_transfers[file_object_count].dstIP,"%s",row[2]);
		//Get the filter
		sprintf(file_transfers[file_object_count].filter,"%s",row[3]);
		//Get the loginName
		sprintf(file_transfers[file_object_count].logName,"%s",row[4]);
		//Get the loginPass
		sprintf(file_transfers[file_object_count].logPass,"%s",row[5]);
		
		
		len = strlen(file_transfers[file_object_count].srcDir);
		if(file_transfers[file_object_count].srcDir[len-1] != '/'&&len<127)
		{
			file_transfers[file_object_count].srcDir[len]='/';
			file_transfers[file_object_count].srcDir[len+1]='\0';
		}
		
		len = strlen(file_transfers[file_object_count].dstDir);
		if (file_transfers[file_object_count].dstDir[len-1] != '/'&&len<127)
		{
			file_transfers[file_object_count].dstDir[len]='/';
			file_transfers[file_object_count].dstDir[len+1]='\0';
		}
		//printfFileObject(&file_transfers[file_object_count]);
		if(file_object_count == (MAX_FILE_TRANSFER_NUM-1))
			break;
		file_object_count++;
		
	}
	//Update the server count
	g_file_transfer_count=file_object_count;
	//printf("g_file_transfer_count=%d\n",g_file_transfer_count);
	//Free the database resource
	mysql_free_result(res);
}

/*************************************************
Function:        // printfFileObject
Description:     // Print the information of the specific file transfer object
Calls:           // 
Called By:       // 
Table Accessed:  // 
Table Updated:   // 
Input:           // ft:the file transfer object to print
Output:          // 
Return:          // 
Others:          // This funtion is for test
*************************************************/
void printfFileObject(FileTransfer* ft)
{
	printf("=======================================\n");
	printf("srcDir=%s\n",ft->srcDir);
	printf("dstDir=%s\n",ft->dstDir);
	printf("dstIP=%s\n",ft->dstIP);
	printf("filter=%s\n",ft->filter);
	printf("logName=%s\n",ft->logName);
	printf("logPass=%s\n",ft->logPass);
	printf("=======================================\n");
}



/*************************************************
Function:        // send_normal_file
Description:     // Send the normal files to the remote server
Calls:           // 
Called By:       // ftpsend_timer
Table Accessed:  // 
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 
Others:          //
*************************************************/

void send_normal_file()
{
	int nRet,connected=0;
	char fullpath[512],cmdstr[1024];
	char fileName[512],filter[32];
	struct dirent* pDirEnt;
	struct stat ftype;
	DIR* dir;
	int i;
	
	long fileSize;
	int checkFlag;
	struct stat fileStat;
	
	for(i=0;i<g_file_transfer_count;i++)
	{
		
		//open the src file	
		dir = opendir(file_transfers[i].srcDir);
		
		if(dir==NULL)
		{		
			continue;
		}
		connected=0;
		while((pDirEnt = readdir(dir))!=NULL)
		{
			if(strlen(pDirEnt->d_name)<3)
				continue;
			
			sprintf(fileName,"%s",pDirEnt->d_name);
			if(strcmp("*",file_transfers[i].filter) != 0)
			{	
				sprintf(filter,".%s",file_transfers[i].filter);
				if(strstr(fileName,filter) == NULL)
					continue;
			}	
				
			strcpy(fullpath,file_transfers[i].srcDir);
			strcat(fullpath,pDirEnt->d_name);
			if(lstat(fullpath,&ftype)<0)
				continue;
			if(S_ISREG(ftype.st_mode))
			{
				
				if(connected==0)
				{
					//connect the ftp server
					if((nRet=ftp_open(file_transfers[i].dstIP)==1))
					{		
						send_log("[ERROR]Ftp server(%s) open failed",file_transfers[i].dstIP);
						break;
					}
					//login the ftp server
					if((nRet=ftp_login(file_transfers[i].logName,file_transfers[i].logPass)==1))
					{	
						send_log("[ERROR]Ftp server login(%s,%s) failed",file_transfers[i].logName,file_transfers[i].logPass);
						break;
					}
					//change the destination directory
					if((nRet = ftp_cwd(file_transfers[i].dstDir)==1))
					{		
						send_log("[ERROR]Ftp CWD(%s) failed",file_transfers[i].dstDir);
						break;
					}
					connected=1;
				}
				
				send_log("sending file...%s\n",fullpath);
				checkFlag=0;
				do
				{
					stat(fullpath,&fileStat);
					if(checkFlag && fileSize==fileStat.st_size)
					{
						
						//put the file to send
						if((nRet = ftp_putfile(file_transfers[i].srcDir,pDirEnt->d_name)==1)){
							send_log("[ERROR]Upload failed");
							//printf("send file=%s failed\n",fullpath);
							break;
						}
						//printf("send file=%s successful\n",fullpath);
						send_log("Send the file=%s successful",fullpath);
						sprintf(cmdstr,"rm -rf %s",fullpath);
						system(cmdstr);
						if(connected!=0){
							send_log("quit");
							ftp_quit();
						}
						return;
						break;
					}	
					if(fileSize != fileStat.st_size)
						sleep(2);
				
					fileSize=fileStat.st_size;
					checkFlag=1;
				}while(stat(fullpath,&fileStat)==0);
				
			}
			else
			{
				continue;
			}		
		}
		
		closedir(dir);
		if(connected!=0)
		{
			send_log("quit");
			ftp_quit();
		}
		
	}
}

/*************************************************
Function:        // sendHeartbeat
Description:     // Send process heartbeat to beatProc
Calls:           // snmp_send
Called By:       // on_Timer
Table Accessed:  // 
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 1:OK; 0:Fail
Others:          // 
*************************************************/
int sendHeartbeat()
{
	snmp_pdu pdu;
	snmp_addr addr;
	char proc_name[16];
	
	memset(proc_name,0,16);
	sprintf(proc_name,"ftpSend");
	
	//pdu
	memset(&pdu,0,sizeof(snmp_pdu));
	pdu.pdu_type=7;
	pdu.request_id=0;
	sprintf(pdu.community,"public");
	pdu.var_num=1;
	pdu.error_status=0;
	pdu.error_index=0;
	
	//Addr
	addr.local_port = 4957;
	//addr.remote_ip = inet_addr("127.0.0.1");
	addr.remote_ip = GetLocalIP();
	addr.broadcast = 0;
	addr.remote_port = 4957;
	
	//Varlist
	memcpy(pdu.var[0].oid,PROC_HEARTBEAT_OID,PROC_HEARTBEAT_OIDLEN*sizeof(DWORD));

	pdu.var[0].oidlen=PROC_HEARTBEAT_OIDLEN;
	pdu.var[0].vartype=0x04;
	pdu.var[0].msglen=16;
	memcpy(pdu.var[0].msg,proc_name,16);
	
	if(snmp_send(&pdu, &addr) <= 0)
	{
		send_log("Send heartbeat fail");
		return 0;
	}
	return 1;
}

unsigned long heartbeat_timeout=0;
void On_Timer()
{
	
	
	if(time(NULL) - heartbeat_timeout > 5)
	{
		heartbeat_timeout=time(NULL);
		sendHeartbeat();
	}
	sendlog_timer();
	ftpsend_timer();	
}

void SetTimer()
{
	struct sigaction act;
	act.sa_handler = On_Timer;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	if (sigaction(SIGALRM, &act, NULL) < 0) {
		perror("Produce Sigaction");
		exitLog("ftpsend:SetTimer, sigaction function error");
		exit(1);
	}
	


	itimer.it_interval.tv_sec = 1;
	itimer.it_interval.tv_usec = 0;
	itimer.it_value.tv_sec = 1;
	itimer.it_value.tv_usec = 0;

	if (setitimer(ITIMER_REAL, &itimer, &old_itimer) != 0) {
		printf("Setting Timer  error! \n");
		exitLog("ftpsend:SetTimer, setitimer function error");
		exit(1);
	}
}


/*************************************************
Function:        // ftpsend_timer
Description:     // 文件发送定时器
Calls:           // send_file
Called By:       // On_Timer
Table Accessed:  // 
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 
Others:          // 该函数每分钟调用一次
*************************************************/
void ftpsend_timer()
{
	static int m_state = 0;	
	static int update_time=INFO_UPDATE_TIME;
	
	//close the ftp function
	return;

	if(m_state==0){
		m_state=1;
		if(csta_send_flag==1)	
			send_cstafile();
		if(cdr_send_flag==1)
			send_file();
		
		send_normal_file();
		m_state=0;
	}
	if(update_time--<0)
	{
		update_time=INFO_UPDATE_TIME;
		fileTransUpdate();
	}	
	
}


void send_file()
{
	int nRet,connected=0;
	struct tm *t;
	long l_time;
	
	//check file exist
	struct dirent* pDirEnt;
	struct stat ftype;
	DIR* dir;
	char fullpath[512],cmdstr[1024];
	//int i=0;
	l_time = time(NULL);		
	t = localtime(&l_time);	
	
	//打开本地源目录	
	dir = opendir(localpath);
	//printf("The localpath is %s\n",localpath);
	if(dir==NULL){
		send_log("[ERROR]sending directory(%s) not exist!",localpath);		
		return;
	}

	while((pDirEnt = readdir(dir))!=NULL){
		strcpy(fullpath,localpath);
		strcat(fullpath,pDirEnt->d_name);
		if(lstat(fullpath,&ftype)<0)
			continue;
		if(S_ISREG(ftype.st_mode)){
			//printf("%d-dir-%s\n",i++,pDirEnt->d_name);			
			if(connected==0){
				send_log("Start sending files(%02d:%02d:%02d)\n",t->tm_hour, t->tm_min, t->tm_sec);
				send_log("Connect ftp server:%s,sending files from %s to %s\n",serverip,localpath,remotepath);				
				if(serverip==0||username==0||pwd==0||remotepath==0||localpath==0){
					send_log("[ERROR]cdr_store_server param error!\n");
					break;
				}
				//连接ftp远程服务器
				send_log("login %s",serverip);
				if((nRet=ftp_open(serverip)==1)){
					send_log("[ERROR]Ftp server open failed");
					break;
				}		
				//登陆ftp远程服务器
				if((nRet=ftp_login(username,pwd)==1)){			
					send_log("[ERROR]Ftp server login failed");
					break;
				}
				//改变远程服务器工作目录
				if((nRet = ftp_cwd(remotepath)==1)){		
					send_log("[ERROR]Ftp CWD failed");
					break;
				}	
				connected=1;
			}
			send_log("sending file...%s\n",fullpath);
			//传送文件
			
			if((nRet = ftp_putfile(localpath,pDirEnt->d_name)==1)){
				send_log("[ERROR]Upload failed");
				break;			
			}
			
				
			//move files
			l_time = time(NULL);		
			t = localtime(&l_time);	
			send_log("[OK]Upload successful!(%02d:%02d:%02d)\n",t->tm_hour, t->tm_min, t->tm_sec);
			if (chdir(sent_dir) == -1) {
				sprintf(cmdstr, "mkdir -p -m755 %s", sent_dir);
				system(cmdstr);
				if (chdir(sent_dir) == -1)
				{
					if(connected!=0){
						send_log("quit");
						ftp_quit();
					}
					closedir(dir);
					return;
				}
			}
			//把传送完的文件复制到sent_dir目录下
			sprintf(cmdstr, "mv %s %s -f",fullpath,sent_dir);
			system(cmdstr);
			if(connected!=0){
				send_log("quit");
				ftp_quit();
			}
			closedir(dir);
			return;
			
		}else{	
			continue;
		}
	}	
	
	closedir(dir);
	if(connected!=0){
		send_log("quit");
		ftp_quit();
	}
	return; 
}


void send_cstafile()
{
	int nRet,connected=0;
	struct tm *t;
	long l_time;
	
	//check file exist
	struct dirent* pDirEnt;
	struct stat ftype;
	DIR* dir;
	char fullpath[512],cmdstr[1024];
	
	l_time = time(NULL);		
	t = localtime(&l_time);	
	//打开本地源目录	
	dir = opendir(csta_localpath);
	//printf("The localpath is %s\n",localpath);
	if(dir==NULL){
		send_log("[ERROR]csta sending directory(%s) not exist!",csta_localpath);		
		return;
	}
	
	while((pDirEnt = readdir(dir))!=NULL){
		strcpy(fullpath,csta_localpath);
		strcat(fullpath,pDirEnt->d_name);
		if(lstat(fullpath,&ftype)<0)
			continue;
		
		if(S_ISREG(ftype.st_mode)){
			//printf("%d-dir-%s\n",i++,pDirEnt->d_name);			
			if(connected==0){
				
				send_log("Start sending files(%02d:%02d:%02d)\n",t->tm_hour, t->tm_min, t->tm_sec);
				send_log("Connect ftp server:%s,sending files from %s to %s\n",csta_serverip,csta_localpath,csta_remotepath);				
				if(csta_serverip==0||csta_username==0||csta_pwd==0||csta_remotepath==0||csta_localpath==0){
					send_log("[ERROR]csta_store_server param error!\n");
					break;
				}
				//连接ftp远程服务器
				send_log("login %s",csta_serverip);
				if((nRet=ftp_open(csta_serverip)==1)){		
					send_log("[ERROR]Ftp server open failed");
					break;
				}		
				
				//登陆ftp远程服务器
				if((nRet=ftp_login(csta_username,csta_pwd)==1)){			
					send_log("[ERROR]Ftp server login failed");
					break;
				}	
				
				//改变远程服务器工作目录
				if((nRet = ftp_cwd(csta_remotepath)==1)){		
					send_log("[ERROR]Ftp CWD failed");
					break;
				}	
				
				connected=1;
			}
			send_log("sending file...%s\n",fullpath);
			//传送文件
			
			if((nRet = ftp_putfile(csta_localpath,pDirEnt->d_name)==1)){
				send_log("[ERROR]Upload failed");
				break;			
			}
			
			{
				l_time = time(NULL);		
				t = localtime(&l_time);	
				send_log("[OK]Upload successful!(%02d:%02d:%02d)\n",t->tm_hour, t->tm_min, t->tm_sec);
				if (chdir(csta_sent_dir) == -1) {
					sprintf(cmdstr, "mkdir -p -m755 %s", csta_sent_dir);
					system(cmdstr);
					//printf("I am feake baba %s\n",cmdstr);	
					if (chdir(csta_sent_dir) == -1)
					{
						send_log("connected=%d,csta_sent_dir",connected);
						if(connected!=0){
							send_log("quit");
							ftp_quit();
						}
						closedir(dir);
						return;
					}
				}
				//把传送完的文件复制到sent_dir目录下
				sprintf(cmdstr, "mv %s %s -f",fullpath,csta_sent_dir);
				system(cmdstr);
				send_log("connected=%d,system",connected);
				if(connected!=0){
					send_log("quit");
					ftp_quit();
				}
				closedir(dir);
				return;
			}
		}else{	
			continue;
		}
	}	
	closedir(dir);
	if(connected!=0){
		send_log("quit");
		ftp_quit();
	}
	return; 
		
}

/*************************************************
Function:        // sendlog_init
Description:     // 创建日志文件,并且打开文件指针
Calls:           // 
Called By:       // main
Table Accessed:  // 
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 
Others:          // 
*************************************************/
void sendlog_init() 
{
		
	char log_file[64], cmdstr[64];
	long l_time;
	struct tm *t;
	
	l_time = time(NULL);	
	t = localtime(&l_time);
		
	//创建log文件夹	
	if (access(FTP_LOG_PATH, F_OK) != 0)
	{		
		sprintf(cmdstr, "mkdir -p -m755 %s", FTP_LOG_PATH);
		printf("%s\n", cmdstr);
		system(cmdstr);			
	}
		
	//创建日志文件
	sprintf(log_file, "%s/%s_%d_%d.log", FTP_LOG_PATH, FTP_LOG_FILE,
				  t->tm_mon + 1, t->tm_mday);
	ftplog_fp = fopen(log_file, "a");
	send_log("FTPSEND start up.%s", ctime(&l_time));
}

/*************************************************
Function:        // sendlog_timer
Description:     // 日志文件定时器,每天产生一个日志文件
Calls:           // 
Called By:       // On_Timer
Table Accessed:  // 
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 
Others:          // 此函数每分钟调用一次
*************************************************/
void sendlog_timer() 
{
	
	char log_file[64];		
	long l_time;		
	static int ch = 0;		
//	static short m_state;		
	struct tm *t;
	
//	if (m_state++ < 6)
//		return;		
//	m_state = 0;
			
	l_time = time(NULL);		
	t = localtime(&l_time);
	
	if (t->tm_hour == 0 && ch == 0)			
	{		
		if (ftplog_fp != NULL)					
			fclose(ftplog_fp);						
		sprintf(log_file, "%s/%s_%d_%d.log", FTP_LOG_PATH, FTP_LOG_FILE,
						  t->tm_mon + 1, t->tm_mday);				
		if ((ftplog_fp = fopen(log_file, "a")) != NULL)		{			
			ch = 1;		
			send_log("%s\n", log_file);
		}
//		else{
//			printf("cann't open file %s\n",log_file);
//			perror("cann't open file");
//		}
	}		
	else if (t->tm_hour > 0)
		ch = 0;
}


void send_log(const char *fmt, ...) 
{	
	char buf[2048];
		
	va_list ap;
		
	if (ftplog_fp == NULL)
			
	return;
		
	va_start(ap, fmt);
		
	vsprintf(buf, fmt, ap);
		
	fputs(buf, ftplog_fp);
	fputs("\n", ftplog_fp);
//	if(fputs(buf, ftplog_fp)>0){
//		printf("write OK\n");
//	}else{
//		perror("write error\n");
//	}
		
	fflush(ftplog_fp);
//	if(fflush(ftplog_fp)==0){
//		printf("flush OK\n");
//	}else{
//		perror("flush error\n");
//	}
		
	va_end(ap);
}

