/*** TCP Server for inetd ***/
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <string.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define	DATAFILE	"/Users/j05017/jikken2/tcpip/data"
#define	DELIMITS	" \t\n\r"

char	datavalue[256];


/*cliant側で入力された文字を読み込む*/
int	GetLineFromPeer(char *line)
{
int	i;

for(i = 0 ; ; )
	{
	if(1 != read(0,line + i,1))
		continue;
	else
		{
		i++;
		*(line + i) = (char)0;
		}

	if(((char)('\n')) == (*(line + i - 1)))
		return i;
	}
}

/*送られてきたデータを判定する 
* もしクライアントからのデータとDATAFILE内のデータが一致したら
* 変換した物を返す
* でなければ空を返す
*/
char	*GetKeywordData(char *key)
{
FILE	*fp;
char	buff[256];

if((FILE *)NULL == (fp = fopen(DATAFILE,"r")))
	return (char *)NULL;

for(;;)
	{
	char	*p;
	char	*pp;

	fgets(buff,256,fp);

	if(feof(fp))
		break;

	if(ferror(fp))
		break;

	if((char *)NULL == (p = strtok(buff,DELIMITS)))
		continue;

	if((char *)NULL == (pp = strtok((char *)NULL,DELIMITS)))
		continue;

	if(0 == strcmp(p,key))
		{
		fclose(fp);
		strcpy(datavalue,pp);
		return datavalue;
		}
	}

fclose(fp);
return (char *)NULL;
}


int	main()
{
char	RecvBuff[256];

for(;;)
	{
	char	*p;
	char	SendBuff[256];
	char	*pp;

	(void)GetLineFromPeer(RecvBuff);	/* クライアントからデータを一行取得 */

	if(((char)('=')) == *(RecvBuff))	/* 終了したら */
		{
		close(0);
		exit(0);
		}

	if((char *)NULL != (p = strchr(RecvBuff,'=')))
		{
		*p = (char)0;

		if((char *)NULL == (pp = GetKeywordData(RecvBuff)))
			sprintf(SendBuff,"%s=\n",RecvBuff);
		else
			sprintf(SendBuff,"%s=%s\n",RecvBuff,pp);

		(void)write(0,SendBuff,strlen(SendBuff));
		}
	}
}