⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main.cpp

📁 WebCam Viewer Camera Server Version 1.0.5 Chipsbrain Engineer Final Release
💻 CPP
字号:
static const char version[] = "camserv: v1.0.5 (C) 2003 Chipsbrain Co., Ltd.\n";#include <pthread.h>#include <signal.h>#include <fcntl.h>#include <sys/socket.h>#include <sys/ioctl.h>#include <sys/types.h>#include <sys/stat.h>#include <sys/wait.h>		/* waitpid() */#include <stdlib.h>#include <stdio.h>#include <shadow.h>#include <string.h>#define __USE_XOPEN#include <unistd.h>#include "def.h"#include "net.h"#include "packet.h"#include "debug.h"#include "ioc_cmd.h"//#define DEBUG#ifdef DEBUG#define DBG(fmt,args...) fprintf(stderr, fmt, ## args)#else#define DBG(fmt,args...)#endif#define RUN_PATH	"/var/run/"CSock	g_CmdSock;#ifdef PAIR_LINECSock	g_DataSock;#endif#ifdef USE_MJPEG_DRIVERint g_mjpeg_driver;#endif#ifdef USE_DELAYint g_delay;#endiftypedef struct _TASK_INFO{        int                     data_sock;        int                     cmd_sock;        pthread_t               thread_id;        pthread_attr_t          thread_attr;        pthread_mutex_t         mutex;        pthread_mutexattr_t     mutex_attr;	int			task_num;	bool			java_client;        bool                    used;}TASK_INFO;TASK_INFO g_TaskInfo[DF_MAX_CONNECT];bool g_bAdminLoginned = false;static void Terminate(int iSigNo);static void TellJpegHeaderUpdate(int iSigNo);int GetNextConnectionNumber();void ReleaseConnectionNumber(TASK_INFO * pTaskInfo);void ReleaseConnectionNumber(int iCliNum);bool Init(void);void CloseAcceptSockets(int iCliNum);void *Run(void *arg);PERMISION UserAuthenticate(char * pszID, char *pszPwd);int main(int argc, char *argv[]){	pid_t pid; //,ppid;	int   do_fork = 0;	int   i;	//char *pathname;		/* file path */	//int fd;			/* file dscriptor */	//char buf[10];	printf ("%s", version);	//pid = getpid();	/*	pathname = "/var/run/camserv.pid";	fd = open(pathname, O_RDONLY);	if (fd > 0) {		printf("already run a deamon\n");		exit(0);	} else {		fd = creat(pathname, S_IRUSR|S_IWUSR);		memset(buf, 0, sizeof(buf));		snprintf(buf, sizeof(buf), "%ld\n", (long)pid);		buf[sizeof(buf) - 1] = 0;		printf("%s\n", buf);		write(fd, buf, sizeof(buf));	}	*/#if 0	ppid = getppid();	if(ppid == 1) {		fprintf(stderr, "already run this daemon!");		return 0; /* already a daemon */	}	printf("daemon start (%ld)\n", (long)ppid);#endif	/* Dojip */	/*	if (argc > 1) {		for (i = 1; i < argc; i++) {			if (!strcmp(argv[i], "-d"))				do_fork = 1;			else {				printf ("Usage: camserv [ -d ]...\n");				exit(1);			}		}	}	*/	do_fork = 1;	// daemonization	/* Dojip */	/* backgroud ourself */	if (do_fork) {		switch(fork()) {			case -1:				/* error */				perror("fork");				exit(1);				break;			case 0:				/* child, success */				DBG("child process\n");				break;			default:				/* parent, success */				DBG("parent process terminate\n");				exit(0);				break;		}	}	/* child (daemon) continues */	DBG("child (daemon) continues\n");#if 1	setsid(); /* obtain a new process group *///	for (i = getdtablesize(); i >= 0; --i) close(i); /* close all descriptors */	i = open("/dev/null", O_RDWR); dup(i); dup(i); /* handle standard I/O */	//signal(SIGCHLD, SIG_IGN); /* ignore child */	//signal(SIGTSTP, SIG_IGN); /* ignore tty signals */	//signal(SIGTTOU, SIG_IGN);	//signal(SIGTTIN, SIG_IGN);#endif	/* End Dojip */	DBG("fork()\n");	pid = fork();	if(pid == 0){ // child process		/* Dojip */		if (execv("./setupserv", NULL) < 0) {			perror("execv");			exit(1);		}	}	DBG("`setupserv' execute\n");	/*	 * monitor process	 */do_fork:	pid = fork();	if (pid < 0) {		perror("fork()");		exit(1);	}	if (pid != 0) {		/* 		 * monitor parent process		 */		waitpid(pid, NULL, 0);		goto do_fork;	}	/*	 * monitor child process	 */	int iConNum;	COMMAND cmd;	/*#ifdef USE_DELAY	if(argc < 2){		OutputDebugString("Usage : camserv delay");		return 0;	}	g_delay = atoi(argv[1]);#endif // USE_DELAY	*/		if(!Init()){		OutputDebugString("Initialize failure!!!");		return -1;	}	OutputDebugString(DF_START_MSG, "(Exit: Ctrl + Z)");	while(1){		iConNum = GetNextConnectionNumber();		if(iConNum != -1){			g_TaskInfo[iConNum].task_num = iConNum;			g_TaskInfo[iConNum].cmd_sock = g_CmdSock.Accept();#ifdef PAIR_LINE			g_TaskInfo[iConNum].data_sock = g_DataSock.Accept();			if(g_TaskInfo[iConNum].cmd_sock != -1 && 					g_TaskInfo[iConNum].data_sock != -1){#else			if(g_TaskInfo[iConNum].cmd_sock != -1){#endif				g_TaskInfo[iConNum].used = true;				if(recv(g_TaskInfo[iConNum].cmd_sock, &cmd, sizeof(COMMAND), 0) == -1){					Perror("recv(CLIENT_MODE)");					goto _retry;				}				if(cmd == JAVA_CLIENT){					g_TaskInfo[iConNum].java_client = true;					OutputDebugString("JAVA client...");				}				else if(cmd == APP_CLIENT){					g_TaskInfo[iConNum].java_client = false;					OutputDebugString("APP client...");				}				else{					OutputDebugString("Can't find client mode.");					goto _retry;				}				if(pthread_create(						&g_TaskInfo[iConNum].thread_id, 						&g_TaskInfo[iConNum].thread_attr, 						Run, 						(void *)&g_TaskInfo[iConNum]) != 0){					OutputDebugString(DF_ERR_THREAD, "(create)");					goto _retry;				}//				if(pthread_join(g_TaskInfo[iConNum].thread_id, NULL) != 0)//					OutputDebugString("th join error!");			}			else{				Perror("accept()");_retry:				CloseAcceptSockets(iConNum);				ReleaseConnectionNumber(iConNum);				continue;			}		}		else			OutputDebugString(DF_ERR_USERFULL);	}	printf("main process exit!\n");		return 0;}bool Init(void){	// Memory initialize...	memset(g_TaskInfo, 0, sizeof(TASK_INFO) * DF_MAX_CONNECT);	// Thread initialize...	for(int i = 0; i < DF_MAX_CONNECT; i++)		if(pthread_attr_init(&g_TaskInfo[i].thread_attr) != 0) {			OutputDebugString("pthread_attr_init");			return false;		}	// Mutex initialize...	for(int j = 0; j < DF_MAX_CONNECT; j++)		pthread_mutex_init(&g_TaskInfo[j].mutex, &g_TaskInfo[j].mutex_attr);	// Signal initialize...	if(signal(SIGTSTP, Terminate) == SIG_ERR) {		OutputDebugString("signal");		//printf("signal\n");		return false;	}	if(signal(SIGUSR1, TellJpegHeaderUpdate) == SIG_ERR) {		OutputDebugString("signal");		return false;	}		// Network initialize...	if(!g_CmdSock.Init(DF_PORT)) {		OutputDebugString("g_CmdSock.Init");		return false;	}#ifdef PAIR_LINE	if(!g_DataSock.Init(DF_PORT + 1)) {		OutputDebugString("g_DataSock.Init");		return false;	}#endif	// Time Init	InitTime();#ifdef USE_MJPEG_DRIVER	// JPEG device driver Init	if((g_mjpeg_driver = open(DF_MJPEG_DEVICE_DRIVER_PATH, O_RDONLY)) == -1) { // | O_SYNC)) == -1) 		OutputDebugString("open");		return false;	}//	ioctl(g_mjpeg_driver, MJPEG_IOCRESET);#endif	OutputDebugString("11111");	return true;}static void Terminate(int iSigNo){	//close socket	for(int j = 0; j < DF_MAX_CONNECT; j++)		pthread_mutex_destroy(&g_TaskInfo[j].mutex);	g_CmdSock.Disconnect();	g_DataSock.Disconnect();	for(int i = 0; i < DF_MAX_CONNECT; i++)		CloseAcceptSockets(i);#ifdef USE_MJPEG_DRIVER	//close mjpeg device driver	ioctl(g_mjpeg_driver, MJPEG_IOCSTOP);	close(g_mjpeg_driver);#endif		OutputDebugString(DF_END_MSG);	_exit(1);}static void TellJpegHeaderUpdate(int iSigNo){	COMMAND cmd = JPEG_HDR_UPDATE;		for(int i = 0; i < DF_MAX_CONNECT; i++){		if(!g_TaskInfo[i].java_client){			send(g_TaskInfo[i].cmd_sock, &cmd, sizeof(COMMAND), 0);		}	}}void CloseAcceptSockets(int iCliNum){	close(g_TaskInfo[iCliNum].cmd_sock);	close(g_TaskInfo[iCliNum].data_sock);}int GetNextConnectionNumber(){	for(int i = 0; i < DF_MAX_CONNECT; i++){		if(!g_TaskInfo[i].used)			return i;	}	return -1;}void ReleaseConnectionNumber(TASK_INFO * pTaskInfo){	memset(pTaskInfo, 0, sizeof(TASK_INFO));	pTaskInfo->used = false;}void ReleaseConnectionNumber(int iCliNum){	memset(&g_TaskInfo[iCliNum], 0, sizeof(TASK_INFO));	g_TaskInfo[iCliNum].used = false;}PERMISION UserAuthenticate(char * pszID, char * pszPwd){	spwd * pUserPwd;	char * pszEncryptedPwd;	pUserPwd = getspnam(pszID);	if(pUserPwd == NULL){		OutputDebugString("user not found.");		return PERMISION_DENY;	}	pszEncryptedPwd = crypt(pszPwd, pUserPwd->sp_pwdp);	if(strcmp(pszEncryptedPwd, pUserPwd->sp_pwdp))		return PERMISION_DENY;	if(!strcmp(pszID, "root"))		return PERMISION_ADMIN;	else		return PERMISION_ANONY;}void *Run(void *arg){	TASK_INFO TaskInfo = *((TASK_INFO *)arg);#ifdef PAIR_LINE	int	DataSock = TaskInfo.data_sock;#endif	int	CmdSock = TaskInfo.cmd_sock;	char	szRecvData[DF_MAX_MESSAGE_SIZE] = " ";	bool	bExit = false;	CPacket	Packet(TaskInfo.task_num);	int	iPacketSize = 0;#ifdef USE_DELAY	int 	iCnt = 0;#endif	COMMAND	cmd = NOTHING;	PARAMETER param;	PERMISION user_permision;	bool	bAdminThread = false;	/*	 * detach thread	 * when thread exit, it immediatly cleaned up automatically.	 */	pthread_detach(pthread_self());	OutputDebugString(TaskInfo.thread_id, " thread start.");	do{		memset(szRecvData, 0, DF_MAX_MESSAGE_SIZE);		if(recv(CmdSock, &cmd, sizeof(COMMAND), MSG_DONTWAIT) != -1)			OutputRunTime("response time : ");		switch(cmd)		{		case NOTHING:			break;		case REQ_LIVE:			cmd = STREAM_DATA;			//if(!Packet.FetchStream()){			if(Packet.FetchStream() <= 0){				OutputDebugString("Can't read stream size.");				cmd = STOP_LIVE;				break;			}			iPacketSize = Packet.Make(STREAM_LENGTH);			if(send(DataSock, Packet.GetPacket(), iPacketSize, 0) == -1){				Perror("send(REQ_LIVE)");				bExit = true;			}//			OutputDebugString(iPacketSize, " sent");			break;		case STREAM_DATA:			iPacketSize = Packet.Make(STREAM_DATA);			if(iPacketSize == 0){//				usleep(5000);				cmd = REQ_LIVE;				break;			}			if(send(DataSock, Packet.GetPacket(), iPacketSize, 0) == -1){				Perror("send(TRANSLATE_STREAM)");				bExit = true;			}//			OutputDebugString(iPacketSize, " sent");			break;		case STOP_LIVE:			while(Packet.IsPacketAlign() != 0){				OutputDebugString("Alinging packet...");				iPacketSize = Packet.Make(STREAM_DATA);				if(send(DataSock, Packet.GetPacket(), iPacketSize, 0) == -1){					Perror("send(TRANSLATE_STREAM AT PACKET ALIGN)");					bExit = true;				}			}			cmd = NOTHING;			break;		case SUCCESS:			break;		case FAIL:			break;		case DISCONNECT:			bExit = true;			break;		case WAIT4ERROR:			break;		case LOGIN:			memset(&param, 0, sizeof(PARAMETER));			if(recv(CmdSock, &param, sizeof(PARAMETER), 0) == -1){				Perror("recv(PARAMETER)");				bExit = true;			}			// 酒捞叼客 菩胶况靛 牢刘.			user_permision = UserAuthenticate(param.index[0], param.index[1]);			if(user_permision == PERMISION_ADMIN){				if(g_bAdminLoginned){					bExit = true;					user_permision = PERMISION_DENY;				}				else{					pthread_mutex_lock(&TaskInfo.mutex);					g_bAdminLoginned = true;					pthread_mutex_unlock(&TaskInfo.mutex);					bAdminThread= true;				}			}			else if(user_permision == PERMISION_ANONY){				if(GetNextConnectionNumber() == -1)					if(!g_bAdminLoginned)						user_permision = PERMISION_DENY;			}			if(send(CmdSock, (COMMAND *)&user_permision, sizeof(COMMAND), 0) == -1){				Perror("send(LOGIN_PERMISION)");				bExit = true;			}			cmd = NOTHING;			break;		default:			bExit = true;			break;		}#ifdef USE_DELAY		iCnt++;		if(iCnt == g_delay)		{			iCnt = 0;			usleep(100);		}#endif		OutputRunTime("process time : ");	}while(!bExit);	ReleaseConnectionNumber((TASK_INFO *)arg);	close(TaskInfo.cmd_sock);	close(TaskInfo.data_sock);	if(bAdminThread){		pthread_mutex_lock(&TaskInfo.mutex);		g_bAdminLoginned = false;		pthread_mutex_unlock(&TaskInfo.mutex);	}	OutputDebugString(TaskInfo.thread_id, " thread termiante.");	//printf("thread terminated %ld\n", (long)pthread_self());	return 0;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -