Esempio n. 1
0
int	connectToBSI(struct sockaddr *sn, int *sock)
{
	*sock = -1;
	if (sn == NULL)
	{

		return -1;	/*	Silently give up on connection.	*/
	}

	*sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (*sock < 0)
	{
		putSysErrmsg("BSO can't open TCP socket", NULL);
		return -1;
	}

	if (connect(*sock, sn, sizeof(struct sockaddr)) < 0)
	{
		closesocket(*sock);
		*sock = -1;
		putSysErrmsg("BSO can't connect to TCP socket", NULL);
		return -1;
	}

	return 0;
}
Esempio n. 2
0
File: libbp.c Progetto: b/ION
static void	*timerMain(void *parm)
{
	TimerParms	*timer = (TimerParms *) parm;
	pthread_mutex_t	mutex;
	pthread_cond_t	cv;
	struct timeval	workTime;
	struct timespec	deadline;
	int		result;

	memset((char *) &mutex, 0, sizeof mutex);
	if (pthread_mutex_init(&mutex, NULL))
	{
		putSysErrmsg("can't start timer, mutex init failed", NULL);
		sm_SemGive(timer->semaphore);
		return NULL;
	}

	memset((char *) &cv, 0, sizeof cv);
	if (pthread_cond_init(&cv, NULL))
	{
		putSysErrmsg("can't start timer, cond init failed", NULL);
		sm_SemGive(timer->semaphore);
		return NULL;
	}

	getCurrentTime(&workTime);
	deadline.tv_sec = workTime.tv_sec + timer->interval;
	deadline.tv_nsec = workTime.tv_usec * 1000;
	pthread_mutex_lock(&mutex);
	result = pthread_cond_timedwait(&cv, &mutex, &deadline);
	pthread_mutex_unlock(&mutex);
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cv);
	if (result)
	{
		errno = result;
		if (errno != ETIMEDOUT)
		{
			putSysErrmsg("timer failure", NULL);
			sm_SemGive(timer->semaphore);
			return NULL;
		}
	}

	/*	Timed out; must wake up the main thread.		*/

	timer->interval = 0;	/*	Indicate genuine timeout.	*/
	sm_SemGive(timer->semaphore);
	return NULL;
}
Esempio n. 3
0
int	sendBytesByTCP(int *blockSocket, char *from, int length,
		struct sockaddr *sn)
{
	int	bytesWritten;

	while (1)	/*	Continue until not interrupted.		*/
	{
		bytesWritten = isend(*blockSocket, from, length, 0);
		if (bytesWritten < 0)
		{
			switch (errno)
			{
			case EINTR:	/*	Interrupted; retry.	*/
				continue;

			case EPIPE:	/*	Lost connection.	*/
			case EBADF:
			case ETIMEDOUT:
			case ECONNRESET:
				closesocket(*blockSocket);
				*blockSocket = -1;
				bytesWritten = 0;
			}

			putSysErrmsg("TCP BSO write() error on socket", NULL);
		}

		return bytesWritten;
	}
}
Esempio n. 4
0
static int	run_sdatest(uvast destEngineId)
{
	SenderThreadParms	parms;
	pthread_t		senderThread;

	isignal(SIGTERM, interruptThread);
	if (destEngineId)
	{
		/*	Must start sender thread.			*/

		parms.destEngineId = destEngineId;
		parms.running = 1;
		if (pthread_begin(&senderThread, NULL, sendItems, &parms))
		{
			putSysErrmsg("sdatest can't create send thread", NULL);
			return 1;
		}
	}

	if (sda_run(getLengthOfItem, handleItem) < 0)
	{
		putErrmsg("sdatest sda_run failed.", NULL);
	}

	if (destEngineId)
	{
		parms.running = 0;
		pthread_join(senderThread, NULL);
	}

	writeErrmsgMemos();
	writeMemo("[i] sdatest main thread has ended.");
	ionDetach();
	return 0;
}
Esempio n. 5
0
File: udpts.c Progetto: b/ION
static int	udpParseMamsEndpoint(MamsEndpoint *ep)
{
	char	*colon;
	char	hostName[MAXHOSTNAMELEN + 1];
	UdpTsep	tsep;

	if (ep == NULL || ep->ept == NULL)
	{
		errno = EINVAL;
		putErrmsg("udpts can't parse MAMS endpoint name.", NULL);
		return -1;
	}

	colon = strchr(ep->ept, ':');
	*colon = '\0';
	istrcpy(hostName, ep->ept, sizeof hostName);
	*colon = ':';
	tsep.portNbr = atoi(colon + 1);
	tsep.ipAddress = getInternetAddress(hostName);
	ep->tsep = MTAKE(sizeof(UdpTsep));
	if (ep->tsep == NULL)
	{
		putSysErrmsg("udpts can't record parsed MAMS endpoint name.",
				NULL);
		return -1;
	}

	memcpy((char *) (ep->tsep), (char *) &tsep, sizeof(UdpTsep));
//printf("parsed '%s' to port %d address %d.\n", ep->ept, tsep.portNbr,
//tsep.ipAddress);
	return 0;
}
Esempio n. 6
0
File: udpts.c Progetto: b/ION
static int	udpParseAmsEndpoint(AmsEndpoint *dp)
{
	char	*colon;
	char	hostName[MAXHOSTNAMELEN + 1];
	UdpTsep	tsep;

	if (dp == NULL || dp->ept == NULL)
	{
		errno = EINVAL;
		putErrmsg("udpts can't parse AMS endpoint.", NULL);
		return -1;
	}

	colon = strchr(dp->ept, ':');
	*colon = '\0';
	istrcpy(hostName, dp->ept, sizeof hostName);
	*colon = ':';
	tsep.portNbr = atoi(colon + 1);
	tsep.ipAddress = getInternetAddress(hostName);
	dp->tsep = MTAKE(sizeof(UdpTsep));
	if (dp->tsep == NULL)
	{
		putSysErrmsg("udpts can't record parsed AMS endpoint name.",
				NULL);
		return -1;
	}

	memcpy((char *) (dp->tsep), (char *) &tsep, sizeof(UdpTsep));

	/*	Also parse out the QOS of this endpoint.		*/

	dp->diligence = AmsBestEffort;
	dp->sequence = AmsArrivalOrder;
	return 0;
}
Esempio n. 7
0
static int	loadMibFromRcSource(char *mibSource)
{
	int		sourceFile;
	LoadMibState	state;
	char		buf[256];
	int		length;
	int		result = 0;

	if (*mibSource == '\0')		/*	Use default file name.	*/
	{
		mibSource = "mib.amsrc";
	}

	sourceFile = iopen(mibSource, O_RDONLY, 0777);
	if (sourceFile < 0)
	{
		putSysErrmsg("Can't open MIB source file", mibSource);
		return -1;
	}

	memset((char *) &state, 0, sizeof state);
	state.abandoned = 0;
	state.currentOperation = LoadDormant;
	state.lineNbr = 0;
	while (1)
	{
		if (igets(sourceFile, buf, sizeof(buf), &length) == NULL)
		{
			if (length == 0)	/*	End of file.	*/
			{
				break;		/*	Out of loop.	*/
			}

			putErrmsg("Failed reading MIB.", mibSource);
			break;			/*	Out of loop.	*/
		}

		state.lineNbr++;
		if (rcParse(&state, buf, length) < 0)
		{
			isprintf(buf, sizeof buf, "amsrc error at line %d.",
					state.lineNbr);
			writeMemo(buf);
			result = -1;
			break;			/*	Out of loop.	*/
		}

		if (state.abandoned)
		{
			writeMemo("[?] Abandoning MIB load.");
			result = -1;
			break;			/*	Out of loop.	*/
		}
	}

	close(sourceFile);
	return result;
}
Esempio n. 8
0
File: udpts.c Progetto: b/ION
static void	*udpAmsReceiver(void *parm)
{
	AmsInterface		*tsif = (AmsInterface *) parm;
	int			fd;
	AmsSAP			*amsSap;
	char			*buffer;
	sigset_t		signals;
	int			length;
	struct sockaddr_in	fromAddr;
	unsigned int		fromSize;

	fd = (long) (tsif->sap);
	amsSap = tsif->amsSap;
	buffer = MTAKE(UDPTS_MAX_MSG_LEN);
	if (buffer == NULL)
	{
		putSysErrmsg(NoMemoryMemo, NULL);
		return NULL;
	}

	sigfillset(&signals);
	pthread_sigmask(SIG_BLOCK, &signals, NULL);
	while (1)
	{
		fromSize = sizeof fromAddr;
		length = recvfrom(fd, buffer, UDPTS_MAX_MSG_LEN, 0,
				(struct sockaddr *) &fromAddr, &fromSize);
		if (length < 2)	/*	length == 1 is "shutdown"	*/
		{
			if (length < 0)
			{
				if (errno == EINTR)
				{
					continue;
				}

				putSysErrmsg("udpts failed receiving AMS \
message", NULL);
			}

			close(fd);
			MRELEASE(buffer);
			tsif->sap = NULL;
			return NULL;
		}

		/*	Got an AMS message.				*/

		if (enqueueAmsMsg(amsSap, (unsigned char *) buffer, length) < 0)
		{
			putErrmsg("udpts discarded AMS message.", NULL);
		}
	}
}
Esempio n. 9
0
File: pmqlsi.c Progetto: b/ION
static void	*handleMessages(void *parm)
{
	/*	Main loop for message reception and handling.		*/

	ReceiverThreadParms	*rtp = (ReceiverThreadParms *) parm;
	int			segLength;
	char			msgbuf[PMQLSA_MSGSIZE];
	unsigned int		mqp;	/*	Priority of rec'd msg.	*/

	iblock(SIGTERM);
	while (rtp->running)
	{	
		segLength = mq_receive(rtp->mq, msgbuf, sizeof msgbuf, &mqp);
		switch (segLength)
		{
		case 1:				/*	Normal stop.	*/
			continue;

		case -1:
			putSysErrmsg("pmqlsi failed receiving msg", NULL);
			pthread_kill(rtp->mainThread, SIGTERM);
			rtp->running = 0;
			continue;
		}

		if (ltpHandleInboundSegment(msgbuf, segLength) < 0)
		{
			putErrmsg("Can't handle inbound segment.", NULL);
			pthread_kill(rtp->mainThread, SIGTERM);
			rtp->running = 0;
			continue;
		}

		/*	Make sure other tasks have a chance to run.	*/

		sm_TaskYield();
	}

	writeErrmsgMemos();
	writeMemo("[i] pmqlsi receiver thread has ended.");
	return NULL;
}
Esempio n. 10
0
int	sendSegmentByAOS(int linkSocket, char *from, int length)
{
	int	bytesWritten;

	while (1)	/*	Continue until not interrupted.		*/
	{
		bytesWritten = isend(linkSocket, from, length, 0);
		if (bytesWritten < 0)
		{
			if (errno == EINTR)	/*	Interrupted.	*/
			{
				continue;	/*	Retry.		*/
			}

			putSysErrmsg("LSO send() error on socket", NULL);
		}

		return bytesWritten;
	}
}
Esempio n. 11
0
int	ltpcli(int a1, int a2, int a3, int a4, int a5,
		int a6, int a7, int a8, int a9, int a10)
{
	char	*ductName = (char *) a1;
#else
int	main(int argc, char *argv[])
{
	char	*ductName = (argc > 1 ? argv[1] : NULL);
#endif
	VInduct			*vduct;
	PsmAddress		vductElt;
	ReceiverThreadParms	rtp;
	pthread_t		receiverThread;

	if (ductName == NULL)
	{
		PUTS("Usage: ltpcli <local engine number>]");
		return 0;
	}

	if (bpAttach() < 0)
	{
		putErrmsg("ltpcli can't attach to BP.", NULL);
		return -1;
	}

	findInduct("ltp", ductName, &vduct, &vductElt);
	if (vductElt == 0)
	{
		putErrmsg("No such ltp duct.", ductName);
		return -1;
	}

	if (vduct->cliPid != ERROR && vduct->cliPid != sm_TaskIdSelf())
	{
		putErrmsg("CLI task is already started for this duct.",
				itoa(vduct->cliPid));
		return -1;
	}

	/*	All command-line arguments are now validated.		*/

	if (ltp_attach() < 0)
	{
		putErrmsg("ltpcli can't initialize LTP.", NULL);
		return -1;
	}

	/*	Set up signal handling; SIGTERM is shutdown signal.	*/

	ionNoteMainThread("ltpcli");
	isignal(SIGTERM, interruptThread);

	/*	Start the receiver thread.				*/

	rtp.vduct = vduct;
	rtp.running = 1;
	if (pthread_begin(&receiverThread, NULL, handleNotices, &rtp))
	{
		putSysErrmsg("ltpcli can't create receiver thread", NULL);
		return 1;
	}

	/*	Now sleep until interrupted by SIGTERM, at which point
	 *	it's time to stop the induct.				*/

	writeMemo("[i] ltpcli is running.");
	ionPauseMainThread(-1);

	/*	Time to shut down.					*/

	rtp.running = 0;

	/*	Stop the receiver thread by interrupting client access.	*/

	ltp_interrupt(BpLtpClientId);
	pthread_join(receiverThread, NULL);
	writeErrmsgMemos();
	writeMemo("[i] ltpcli duct has ended.");
	ionDetach();
	return 0;
}
Esempio n. 12
0
static int	run_file2dgr(char *remoteHostName, char *fileName)
{
	int		cyclesLeft;
	char		ownHostName[MAXHOSTNAMELEN + 1];
	unsigned int	ownIpAddress;
	unsigned int	remoteIpAddress;
	unsigned short	remotePortNbr = TEST_PORT_NBR;
	PsmMgtOutcome	outcome;
	DgrRC		rc;
	FILE		*inputFile;
	char		line[256];
	int		lineLen;
	struct timeval	startTime;
	unsigned long	bytesSent;

	cyclesLeft = cyclesRequested;
	getNameOfHost(ownHostName, sizeof ownHostName);
	ownIpAddress = getInternetAddress(ownHostName);
	remoteIpAddress = getInternetAddress(remoteHostName);
	sm_ipc_init();
	wmPtr = malloc(wmSize);
	if (wmPtr == NULL
	|| psm_manage(wmPtr, wmSize, "dgr", &dgrwm, &outcome) < 0
	|| outcome == Refused)
	{
		putErrmsg("Can't acquire DGR working memory.", NULL);
		writeErrmsgMemos();
		return 0;
	}
#if 0
psm_start_trace(dgrwm, 10000000, NULL);
#endif

	memmgr_add("dgr", allocFromDgrMemory, releaseToDgrMemory, dgrAtoP,
			dgrPtoA);
	if (dgr_open(ownIpAddress, 2, 0, ownIpAddress, "dgr", &dgr, &rc) < 0
	|| rc != DgrOpened)
	{
		putErrmsg("Can't open dgr service.", NULL);
		writeErrmsgMemos();
		return 0;
	}

	inputFile = fopen(fileName, "r");
	if (inputFile == NULL)
	{
		putSysErrmsg("Can't open input file", fileName);
		writeErrmsgMemos();
		return 0;
	}

	eofLineLen = strlen(eofLine);
	getCurrentTime(&startTime);
	bytesSent = 0;

	/*	Copy text lines from file to SDR.			*/

	while (cyclesLeft > 0)
	{
		if (fgets(line, 256, inputFile) == NULL)
		{
			if (feof(inputFile))
			{
				if (dgr_send(dgr, remotePortNbr,
					remoteIpAddress, DGR_NOTE_FAILED,
					eofLine, eofLineLen, &rc) < 0)
				{
					putErrmsg("dgr_send failed.", NULL);
					writeErrmsgMemos();
					fclose(inputFile);
					return 0;
				}

				bytesSent += eofLineLen;
				fclose(inputFile);
				cyclesLeft--;
				if (cyclesLeft == 0)
				{
					inputFile = NULL;
					break;
				}

				inputFile = fopen(fileName, "r");
				if (inputFile == NULL)
				{
					putSysErrmsg("Can't reopen input file",
							NULL);
					writeErrmsgMemos();
					return 0;
				}

				continue;
			}
			else
			{
				putSysErrmsg("Can't read from input file",
						NULL);
				writeErrmsgMemos();
				fclose(inputFile);
				return 0;
			}
		}

		lineLen = strlen(line);
		if (dgr_send(dgr, remotePortNbr, remoteIpAddress,
				DGR_NOTE_FAILED, line, lineLen, &rc) < 0)
		{
			putErrmsg("dgr_send failed", NULL);
			writeErrmsgMemos();
			fclose(inputFile);
			return 0;
		}

		bytesSent += lineLen;
	}

	report(&startTime, bytesSent);
	writeMemo("[i] file2dgr waiting 10 sec for retransmission to stop.");
	snooze(10);
	dgr_close(dgr);
#if 0
psm_print_trace(dgrwm, 0);
psm_stop_trace(dgrwm);
#endif
	if (inputFile)
	{
		fclose(inputFile);
	}

	return 0;
}
Esempio n. 13
0
static int	loadMibFromXmlSource(char *mibSource)
{
	int		sourceFile;
	LoadMibState	state;
	char		buf[256];
	int		done = 0;
	size_t		length;
	int		result = 0;

	if (*mibSource == '\0')		/*	Use default file name.	*/
	{
		mibSource = "amsmib.xml";
	}

	sourceFile = iopen(mibSource, O_RDONLY, 0777);
	if (sourceFile < 0)
	{
		putSysErrmsg("Can't open MIB source file", mibSource);
		return -1;
	}

	memset((char *) &state, 0, sizeof state);
	state.abandoned = 0;
	state.currentOperation = LoadDormant;
	state.parser = XML_ParserCreate(NULL);
	if (state.parser == NULL)
	{
		putSysErrmsg("Can't open XML parser", NULL);
		close(sourceFile);
		return -1;
	}

	XML_SetElementHandler(state.parser, startElement, endElement);
	XML_SetUserData(state.parser, &state);
	while (!done)
	{
		length = read(sourceFile, buf, sizeof(buf));
		switch (length)
		{
		case -1:
			putSysErrmsg("Failed reading MIB", mibSource);

			/*	Intentional fall-through to next case.	*/

		case 0:			/*	End of file.		*/
			done = 1;
			break;

		default:
			done = (length < sizeof buf);
		}

		if (XML_Parse(state.parser, buf, length, done)
				== XML_STATUS_ERROR)
		{
			isprintf(buf, sizeof buf, "XML error at line %d.", (int)
					XML_GetCurrentLineNumber(state.parser));
			putSysErrmsg(buf, XML_ErrorString
					(XML_GetErrorCode(state.parser)));
			result = -1;
			break;		/*	Out of loop.		*/
		}

		if (state.abandoned)
		{
			writeMemo("[?] Abandoning MIB load.");
			result = -1;
			break;		/*	Out of loop.		*/
		}
	}

	XML_ParserFree(state.parser);
	close(sourceFile);
	return result;
}
Esempio n. 14
0
File: ion.c Progetto: b/ION
static int	checkNodeListParms(IonParms *parms, char *wdName,
			unsigned long nodeNbr)
{
	char		*nodeListDir;
	char		nodeListFileName[265];
	int		nodeListFile;
	int		lineNbr = 0;
	int		lineLen;
	char		lineBuf[256];
	unsigned long	lineNodeNbr;
	int		lineWmKey;
	char		lineSdrName[MAX_SDR_NAME + 1];
	char		lineWdName[256];
	int		result;

	nodeListDir = getenv("ION_NODE_LIST_DIR");
	if (nodeListDir == NULL)	/*	Single node on machine.	*/
	{
		if (parms->wmKey == 0)
		{
			parms->wmKey = ION_DEFAULT_SM_KEY;
		}

		if (parms->wmKey != ION_DEFAULT_SM_KEY)
		{
			putErrmsg("Config parms wmKey != default.",
					itoa(ION_DEFAULT_SM_KEY));
			return -1;
		}

		if (parms->sdrName[0] == '\0')
		{
			istrcpy(parms->sdrName, ION_DEFAULT_SDR_NAME,
					sizeof parms->sdrName);
		}

		if (strcmp(parms->sdrName, ION_DEFAULT_SDR_NAME) != 0)
		{
			putErrmsg("Config parms sdrName != default.",
					ION_DEFAULT_SDR_NAME);
			return -1;
		}

		return 0;
	}

	/*	Configured for multi-node operation.			*/

	isprintf(nodeListFileName, sizeof nodeListFileName, "%.255s%cion_nodes",
			nodeListDir, ION_PATH_DELIMITER);
	if (nodeNbr == 0)	/*	Just attaching.			*/
	{
		nodeListFile = open(nodeListFileName, O_RDONLY, 0);
	}
	else			/*	Initializing the node.		*/
	{
		nodeListFile = open(nodeListFileName, O_RDWR | O_CREAT, 00666);
	}

	if (nodeListFile < 0)
	{
		putSysErrmsg("Can't open ion_nodes file", nodeListFileName);
		writeMemo("[?] Remove ION_NODE_LIST_DIR from env?");
		return -1;
	}

	while (1)
	{
		if (igets(nodeListFile, lineBuf, sizeof lineBuf, &lineLen)
				== NULL)
		{
			if (lineLen < 0)
			{
				close(nodeListFile);
				putErrmsg("Failed reading ion_nodes file.",
						nodeListFileName);
				return -1;
			}

			break;		/*	End of file.		*/
		}

		lineNbr++;
		if (sscanf(lineBuf, "%lu %d %31s %255s", &lineNodeNbr,
				&lineWmKey, lineSdrName, lineWdName) < 4)
		{
			close(nodeListFile);
			putErrmsg("Syntax error at line#", itoa(lineNbr));
			writeMemoNote("[?] Repair ion_nodes file.",
					nodeListFileName);
			return -1;
		}

		if (lineNodeNbr == nodeNbr)		/*	Match.	*/
		{
			/*	lineNodeNbr can't be zero (we never
			 *	write such lines to the file), so this
			 *	must be matching non-zero node numbers.
			 *	So we are re-initializing this node.	*/

			close(nodeListFile);
			if (strcmp(lineWdName, wdName) != 0)
			{
				putErrmsg("CWD conflict at line#",
						itoa(lineNbr));
				writeMemoNote("[?] Repair ion_nodes file.",
						nodeListFileName);
				return -1;
			}

			if (parms->wmKey == 0)
			{
				parms->wmKey = lineWmKey;
			}

			if (parms->wmKey != lineWmKey)
			{
				putErrmsg("WmKey conflict at line#",
						itoa(lineNbr));
				writeMemoNote("[?] Repair ion_nodes file.",
						nodeListFileName);
				return -1;
			}

			if (parms->sdrName[0] == '\0')
			{
				istrcpy(parms->sdrName, lineSdrName,
						sizeof parms->sdrName);
			}

			if (strcmp(parms->sdrName, lineSdrName) != 0)
			{
				putErrmsg("SdrName conflict at line#",
						itoa(lineNbr));
				writeMemoNote("[?] Repair ion_nodes file.",
						nodeListFileName);
				return -1;
			}

			return 0;
		}

		/*	lineNodeNbr does not match nodeNbr (which may
		 *	be zero).					*/

		if (strcmp(lineWdName, wdName) == 0)	/*	Match.	*/
		{
			close(nodeListFile);
			if (nodeNbr == 0)	/*	Attaching.	*/
			{
				parms->wmKey = lineWmKey;
				istrcpy(parms->sdrName, lineSdrName,
						MAX_SDR_NAME + 1);
				return 0;
			}

			/*	Reinitialization conflict.		*/

			putErrmsg("NodeNbr conflict at line#", itoa(lineNbr));
			writeMemoNote("[?] Repair ion_nodes file.",
					nodeListFileName);
			return -1;
		}

		/*	Haven't found matching line yet.  Continue.	*/
	}

	/*	No matching lines in file.				*/

	if (nodeNbr == 0)	/*	Attaching to existing node.	*/
	{
		close(nodeListFile);
		putErrmsg("No node has been initialized in this directory.",
				wdName);
		return -1;
	}

	/*	Initializing, so append line to the nodes list file.	*/

	if (parms->wmKey == 0)
	{
		parms->wmKey = ION_DEFAULT_SM_KEY;
	}

	if (parms->sdrName[0] == '\0')
	{
		istrcpy(parms->sdrName, ION_DEFAULT_SDR_NAME,
				sizeof parms->sdrName);
	}

	isprintf(lineBuf, sizeof lineBuf, "%lu %d %.31s %.255s\n",
			nodeNbr, parms->wmKey, parms->sdrName, wdName);
	result = iputs(nodeListFile, lineBuf);
	close(nodeListFile);
	if (result < 0)
	{
		putErrmsg("Failed writing to ion_nodes file.", NULL);
		return -1;
	}

	return 0;
}
Esempio n. 15
0
File: udpts.c Progetto: b/ION
static int	udpAmsInit(AmsInterface *tsif, char *epspec)
{
	unsigned short		portNbr;
	unsigned int		ipAddress;
	char			hostName[MAXHOSTNAMELEN + 1];
	struct sockaddr		socketName;
	struct sockaddr_in	*inetName;
	socklen_t		nameLength;
	int			fd;
	char			endpointNameText[32];
	int			eptLen;
	long			longfd;

	if (strcmp(epspec, "@") == 0)	/*	Default.		*/
	{
		epspec = NULL;	/*	Force default selection.	*/
	}

	parseSocketSpec(epspec, &portNbr, &ipAddress);
	if (ipAddress == 0)
	{
		getNameOfHost(hostName, sizeof hostName);
		ipAddress = getInternetAddress(hostName);
	}
	else
	{
		if (getInternetHostName(ipAddress, hostName) == NULL)
		{
			putErrmsg("Unknown host in endpoint.", epspec);
			return -1;
		}
	}

	portNbr = htons(portNbr);
	ipAddress = htonl(ipAddress);
	memset((char *) &socketName, 0, sizeof socketName);
	inetName = (struct sockaddr_in *) &socketName;
	inetName->sin_family = AF_INET;
	inetName->sin_port = portNbr;
	memcpy((char *) &(inetName->sin_addr.s_addr), (char *) &ipAddress, 4);
	fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (fd < 0)
	{
		putSysErrmsg("udpts can't open AMS SAP", NULL);
		return -1;
	}

	nameLength = sizeof(struct sockaddr);
	if (reUseAddress(fd)
	|| bind(fd, &socketName, nameLength) < 0
	|| getsockname(fd, &socketName, &nameLength) < 0)
	{
		putSysErrmsg("udpts can't initialize AMS SAP", NULL);
		return -1;
	}

	portNbr = inetName->sin_port;
	portNbr = ntohs(portNbr);
	memcpy((char *) &ipAddress, (char *) &(inetName->sin_addr.s_addr), 4);
	ipAddress = ntohl(ipAddress);
	tsif->diligence = AmsBestEffort;
	tsif->sequence = AmsArrivalOrder;
	isprintf(endpointNameText, sizeof endpointNameText, "%s:%hu", hostName,
			portNbr);
	eptLen = strlen(endpointNameText) + 1;
	tsif->ept = MTAKE(eptLen);
	if (tsif->ept == NULL)
	{
		close(fd);
		putSysErrmsg(NoMemoryMemo, NULL);
		return -1;
	}

	istrcpy(tsif->ept, endpointNameText, eptLen);
	longfd = fd;
	tsif->sap = (void *) longfd;
	return 0;
}
Esempio n. 16
0
File: libbp.c Progetto: b/ION
int	bp_receive(BpSAP sap, BpDelivery *dlvBuffer, int timeoutSeconds)
{
	Sdr		sdr = getIonsdr();
	VEndpoint	*vpoint;
			OBJ_POINTER(Endpoint, endpoint);
	Object		dlvElt;
	Object		bundleAddr;
	Bundle		bundle;
	TimerParms	timerParms;
	pthread_t	timerThread;
	int		result;
	char		*dictionary;

	CHKERR(sap && dlvBuffer);
	if (timeoutSeconds < BP_BLOCKING)
	{
		putErrmsg("Illegal timeout interval.", itoa(timeoutSeconds));
		return -1;
	}

	vpoint = sap->vpoint;
	sdr_begin_xn(sdr);
	if (vpoint->appPid != sm_TaskIdSelf())
	{
		sdr_exit_xn(sdr);
		putErrmsg("Can't receive: not owner of endpoint.",
				itoa(vpoint->appPid));
		return -1;
	}

	if (sm_SemEnded(vpoint->semaphore))
	{
		sdr_exit_xn(sdr);
		writeMemo("[?] Endpoint has been stopped.");

		/*	End task, but without error.			*/

		return -1;
	}

	/*	Get oldest bundle in delivery queue, if any; wait
	 *	for one if necessary.					*/

	GET_OBJ_POINTER(sdr, Endpoint, endpoint, sdr_list_data(sdr,
			vpoint->endpointElt));
	dlvElt = sdr_list_first(sdr, endpoint->deliveryQueue);
	if (dlvElt == 0)
	{
		sdr_exit_xn(sdr);
		if (timeoutSeconds == BP_POLL)
		{
			dlvBuffer->result = BpReceptionTimedOut;
			return 0;
		}

		/*	Wait for semaphore to be given, either by the
		 *	deliverBundle() function or by timer thread.	*/

		if (timeoutSeconds == BP_BLOCKING)
		{
			timerParms.interval = -1;
		}
		else	/*	This is a receive() with a deadline.	*/
		{
			timerParms.interval = timeoutSeconds;
			timerParms.semaphore = vpoint->semaphore;
			if (pthread_create(&timerThread, NULL, timerMain,
					&timerParms) < 0)
			{
				putSysErrmsg("Can't enable interval timer",
						NULL);
				return -1;
			}
		}

		/*	Take endpoint semaphore.			*/

		if (sm_SemTake(vpoint->semaphore) < 0)
		{
			putErrmsg("Can't take endpoint semaphore.", NULL);
			return -1;
		}

		if (sm_SemEnded(vpoint->semaphore))
		{
			writeMemo("[i] Endpoint has been stopped.");

			/*	End task, but without error.		*/

			return -1;
		}

		/*	Have taken the semaphore, one way or another.	*/

		sdr_begin_xn(sdr);
		dlvElt = sdr_list_first(sdr, endpoint->deliveryQueue);
		if (dlvElt == 0)	/*	Still nothing.		*/
		{
			/*	Either sm_SemTake() was interrupted
			 *	or else timer thread gave semaphore.	*/

			sdr_exit_xn(sdr);
			if (timerParms.interval == 0)
			{
				/*	Timer expired.			*/

				dlvBuffer->result = BpReceptionTimedOut;
				pthread_join(timerThread, NULL);
			}
			else	/*	Interrupted.			*/
			{
				dlvBuffer->result = BpReceptionInterrupted;
				if (timerParms.interval != -1)
				{
					pthread_cancel(timerThread);
					pthread_join(timerThread, NULL);
				}
			}

			return 0;
		}
		else		/*	Bundle was delivered.		*/
		{
			if (timerParms.interval != -1)
			{
				pthread_cancel(timerThread);
				pthread_join(timerThread, NULL);
			}
		}
	}

	/*	At this point, we have got a dlvElt and are in an SDR
	 *	transaction.						*/

	bundleAddr = sdr_list_data(sdr, dlvElt);
	sdr_stage(sdr, (char *) &bundle, bundleAddr, sizeof(Bundle));
	dictionary = retrieveDictionary(&bundle);
	if (dictionary == (char *) &bundle)
	{
		sdr_cancel_xn(sdr);
		putErrmsg("Can't retrieve dictionary.", NULL);
		return -1;
	}

	/*	Now fill in the data indication structure.		*/

	dlvBuffer->result = BpPayloadPresent;
	if (printEid(&bundle.id.source, dictionary,
			&dlvBuffer->bundleSourceEid) < 0)
	{
		sdr_cancel_xn(sdr);
		putErrmsg("Can't print source EID.", NULL);
		return -1;
	}

	dlvBuffer->bundleCreationTime.seconds = bundle.id.creationTime.seconds;
	dlvBuffer->bundleCreationTime.count = bundle.id.creationTime.count;
	dlvBuffer->adminRecord = bundle.bundleProcFlags & BDL_IS_ADMIN;
	dlvBuffer->adu = zco_add_reference(sdr, bundle.payload.content);
	dlvBuffer->ackRequested = bundle.bundleProcFlags & BDL_APP_ACK_REQUEST;

	/*	Now before returning we send delivery status report
	 *	if it is requested.					*/

	if (SRR_FLAGS(bundle.bundleProcFlags) & BP_DELIVERED_RPT)
	{
		bundle.statusRpt.flags |= BP_DELIVERED_RPT;
		getCurrentDtnTime(&bundle.statusRpt.deliveryTime);
	}

	if (bundle.statusRpt.flags)
	{
		result = sendStatusRpt(&bundle, dictionary);
		if (result < 0)
		{
			sdr_cancel_xn(sdr);
			putErrmsg("Can't send status report.", NULL);
			return -1;
		}
	}

	/*	Finally delete the delivery list element and, if
	 *	possible, destroy the bundle itself.			*/

	if (dictionary)
	{
		MRELEASE(dictionary);
	}

	sdr_list_delete(sdr, dlvElt, (SdrListDeleteFn) NULL, NULL);
	bundle.dlvQueueElt = 0;
	sdr_write(sdr, bundleAddr, (char *) &bundle, sizeof(Bundle));
	if (bpDestroyBundle(bundleAddr, 0) < 0)
	{
		sdr_cancel_xn(sdr);
		putErrmsg("Can't destroy bundle.", NULL);
		return -1;
	}

	if (sdr_end_xn(sdr) < 0)
	{
		putErrmsg("Failure in bundle reception.", NULL);
		return -1;
	}

	return 0;
}
Esempio n. 17
0
int	tcpclo(int a1, int a2, int a3, int a4, int a5,
		int a6, int a7, int a8, int a9, int a10)
{
	char	*ductName = (char *) a1;
#else
int	main(int argc, char *argv[])
{
	char	*ductName = (argc > 1 ? argv[1] : NULL);
#endif
	unsigned char		*buffer;
	VOutduct		*vduct;
	PsmAddress		vductElt;
	Sdr			sdr;
	Outduct			duct;
	ClProtocol		protocol;
	Outflow			outflows[3];
	int			i;
	char			*hostName;
	unsigned short		portNbr;
	unsigned int		hostNbr;
	struct sockaddr		socketName;
	struct sockaddr_in	*inetName;
	int			running = 1;
	pthread_mutex_t		mutex;
	KeepaliveThreadParms	parms;
	ReceiveThreadParms	rparms;
	pthread_t		keepaliveThread;
	pthread_t		receiverThread;
	Object			bundleZco;
	BpExtendedCOS		extendedCOS;
	char			destDuctName[MAX_CL_DUCT_NAME_LEN + 1];
	unsigned int		bundleLength;
	int			ductSocket = -1;
	int			bytesSent;
	int 			keepalivePeriod = 0;
	VInduct			*viduct;

	if (ductName == NULL)
	{
		PUTS("Usage: tcpclo <remote host name>[:<port number>]");
		return 0;
	}

	if (bpAttach() < 0)
	{
		putErrmsg("tcpclo can't attach to BP", NULL);
		return 1;
	}

	buffer = MTAKE(TCPCLA_BUFSZ);
	if (buffer == NULL)
	{
		putErrmsg("No memory for TCP buffer in tcpclo.", NULL);
		return 1;
	}

	findOutduct("tcp", ductName, &vduct, &vductElt);
	if (vductElt == 0)
	{
		putErrmsg("No such tcp duct.", ductName);
		MRELEASE(buffer);
		return 1;
	}

	if (vduct->cloPid != ERROR && vduct->cloPid != sm_TaskIdSelf())
	{
		putErrmsg("CLO task is already started for this duct.",
				itoa(vduct->cloPid));
		MRELEASE(buffer);
		return 1;
	}

	/*	All command-line arguments are now validated.		*/

	sdr = getIonsdr();
	CHKERR(sdr_begin_xn(sdr));
	sdr_read(sdr, (char *) &duct, sdr_list_data(sdr, vduct->outductElt),
			sizeof(Outduct));
	sdr_read(sdr, (char *) &protocol, duct.protocol, sizeof(ClProtocol));
	sdr_exit_xn(sdr);
	if (protocol.nominalRate == 0)
	{
		vduct->xmitThrottle.nominalRate = DEFAULT_TCP_RATE;
	}
	else
	{
		vduct->xmitThrottle.nominalRate = protocol.nominalRate;
	}

	memset((char *) outflows, 0, sizeof outflows);
	outflows[0].outboundBundles = duct.bulkQueue;
	outflows[1].outboundBundles = duct.stdQueue;
	outflows[2].outboundBundles = duct.urgentQueue;
	for (i = 0; i < 3; i++)
	{
		outflows[i].svcFactor = 1 << i;
	}

	hostName = ductName;
	parseSocketSpec(ductName, &portNbr, &hostNbr);
	if (portNbr == 0)
	{
		portNbr = BpTcpDefaultPortNbr;
	}

	portNbr = htons(portNbr);
	if (hostNbr == 0)
	{
		putErrmsg("Can't get IP address for host.", hostName);
		MRELEASE(buffer);
		return 1;
	}

	hostNbr = htonl(hostNbr);
	memset((char *) &socketName, 0, sizeof socketName);
	inetName = (struct sockaddr_in *) &socketName;
	inetName->sin_family = AF_INET;
	inetName->sin_port = portNbr;
	memcpy((char *) &(inetName->sin_addr.s_addr), (char *) &hostNbr, 4);
	if (_tcpOutductId(&socketName, "tcp", ductName) < 0)
	{
		putErrmsg("Can't record TCP Outduct ID for connection.", NULL);
		MRELEASE(buffer);
		return -1;
	}

	/*	Set up signal handling.  SIGTERM is shutdown signal.	*/

	oK(tcpcloSemaphore(&(vduct->semaphore)));
	isignal(SIGTERM, shutDownClo);
#ifndef mingw
	isignal(SIGPIPE, handleConnectionLoss);
#endif

	/*	Start the keepalive thread for the eventual connection.	*/
	
	tcpDesiredKeepAlivePeriod = KEEPALIVE_PERIOD;
	parms.cloRunning = &running;
	pthread_mutex_init(&mutex, NULL);
	parms.mutex = &mutex;
	parms.socketName = &socketName;
	parms.ductSocket = &ductSocket;
	parms.keepalivePeriod = &keepalivePeriod;
	if (pthread_begin(&keepaliveThread, NULL, sendKeepalives, &parms))
	{
		putSysErrmsg("tcpclo can't create keepalive thread", NULL);
		MRELEASE(buffer);
		pthread_mutex_destroy(&mutex);
		return 1;
	}

	// Returns the VInduct Object of first induct with same protocol
	// as the outduct. The VInduct is required to create an acq area.
	// The Acq Area inturn uses the throttle information from VInduct
	// object while receiving bundles. The throttle information 
	// of all inducts of the same induct will be the same, so choosing 
	// any induct will serve the purpose.
	
	findVInduct(&viduct,protocol.name);
	if(viduct == NULL)
	{
		putErrmsg("tcpclo can't get VInduct", NULL);
		MRELEASE(buffer);
		pthread_mutex_destroy(&mutex);
		return 1;
	
	}

	rparms.vduct =  viduct;
	rparms.bundleSocket = &ductSocket;
	rparms.mutex = &mutex;
	rparms.cloRunning = &running;
	if (pthread_begin(&receiverThread, NULL, receiveBundles, &rparms))
	{
		putSysErrmsg("tcpclo can't create receive thread", NULL);
		MRELEASE(buffer);
		pthread_mutex_destroy(&mutex);
		return 1;
	}

	/*	Can now begin transmitting to remote duct.		*/

	{
		char	txt[500];

		isprintf(txt, sizeof(txt),
			"[i] tcpclo is running, spec=[%s:%d].", 
			inet_ntoa(inetName->sin_addr),
			ntohs(inetName->sin_port));
		writeMemo(txt);
	}

	while (running && !(sm_SemEnded(tcpcloSemaphore(NULL))))
	{
		if (bpDequeue(vduct, outflows, &bundleZco, &extendedCOS,
				destDuctName, 0, -1) < 0)
		{
			running = 0;	/*	Terminate CLO.		*/
			continue;
		}

		if (bundleZco == 0)	/*	Interrupted.		*/
		{
			continue;
		}

		CHKZERO(sdr_begin_xn(sdr));
		bundleLength = zco_length(sdr, bundleZco);
		sdr_exit_xn(sdr);
		pthread_mutex_lock(&mutex);
		bytesSent = sendBundleByTCPCL(&socketName, &ductSocket,
			bundleLength, bundleZco, buffer, &keepalivePeriod);
		pthread_mutex_unlock(&mutex);
		if(bytesSent < 0)
		{
			running = 0;	/*	Terminate CLO.		*/
		}

		/*	Make sure other tasks have a chance to run.	*/

		sm_TaskYield();
	}
	writeMemo("[i] tcpclo done sending");

	if (sendShutDownMessage(&ductSocket, SHUT_DN_NO, -1, &socketName) < 0)
	{
		putErrmsg("Sending Shutdown message failed!!",NULL);
	}

	if (ductSocket != -1)
	{
		closesocket(ductSocket);
		ductSocket=-1;
	}

	running = 0;
	pthread_join(keepaliveThread, NULL);
	writeMemo("[i] tcpclo keepalive thread killed");

	pthread_join(receiverThread, NULL);
	writeMemo("[i] tcpclo receiver thread killed");

	writeErrmsgMemos();
	writeMemo("[i] tcpclo duct has ended.");
	oK(_tcpOutductId(&socketName, NULL, NULL));
	MRELEASE(buffer);
	pthread_mutex_destroy(&mutex);
	bp_detach();
	return 0;
}
Esempio n. 18
0
int	udplsi(int a1, int a2, int a3, int a4, int a5,
		int a6, int a7, int a8, int a9, int a10)
{
	char	*endpointSpec = (char *) a1;
#else
int	main(int argc, char *argv[])
{
	char	*endpointSpec = (argc > 1 ? argv[1] : NULL);
#endif
	LtpVdb			*vdb;
	unsigned short		portNbr = 0;
	unsigned int		ipAddress = INADDR_ANY;
	struct sockaddr		socketName;
	struct sockaddr_in	*inetName;
	ReceiverThreadParms	rtp;
	socklen_t		nameLength;
	pthread_t		receiverThread;
	int			fd;
	char			quit = '\0';

	/*	Note that ltpadmin must be run before the first
	 *	invocation of ltplsi, to initialize the LTP database
	 *	(as necessary) and dynamic database.			*/ 

	if (ltpInit(0) < 0)
	{
		putErrmsg("udplsi can't initialize LTP.", NULL);
		return 1;
	}

	vdb = getLtpVdb();
	if (vdb->lsiPid != ERROR && vdb->lsiPid != sm_TaskIdSelf())
	{
		putErrmsg("LSI task is already started.", itoa(vdb->lsiPid));
		return 1;
	}

	/*	All command-line arguments are now validated.		*/

	if (endpointSpec)
	{
		if(parseSocketSpec(endpointSpec, &portNbr, &ipAddress) != 0)
		{
			putErrmsg("Can't get IP/port for endpointSpec.",
					endpointSpec);
			return -1;
		}
	}

	if (portNbr == 0)
	{
		portNbr = LtpUdpDefaultPortNbr;
	}

	portNbr = htons(portNbr);
	ipAddress = htonl(ipAddress);
	memset((char *) &socketName, 0, sizeof socketName);
	inetName = (struct sockaddr_in *) &socketName;
	inetName->sin_family = AF_INET;
	inetName->sin_port = portNbr;
	memcpy((char *) &(inetName->sin_addr.s_addr), (char *) &ipAddress, 4);
	rtp.linkSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (rtp.linkSocket < 0)
	{
		putSysErrmsg("LSI can't open UDP socket", NULL);
		return -1;
	}

	nameLength = sizeof(struct sockaddr);
	if (reUseAddress(rtp.linkSocket)
	|| bind(rtp.linkSocket, &socketName, nameLength) < 0
	|| getsockname(rtp.linkSocket, &socketName, &nameLength) < 0)
	{
		closesocket(rtp.linkSocket);
		putSysErrmsg("Can't initialize socket", NULL);
		return 1;
	}

	/*	Set up signal handling; SIGTERM is shutdown signal.	*/

	ionNoteMainThread("udplsi");
	isignal(SIGTERM, interruptThread);

	/*	Start the receiver thread.				*/

	rtp.running = 1;
	if (pthread_begin(&receiverThread, NULL, handleDatagrams, &rtp))
	{
		closesocket(rtp.linkSocket);
		putSysErrmsg("udplsi can't create receiver thread", NULL);
		return 1;
	}

	/*	Now sleep until interrupted by SIGTERM, at which point
	 *	it's time to stop the link service.			*/

	{
		char	txt[500];

		isprintf(txt, sizeof(txt),
			"[i] udplsi is running, spec=[%s:%d].", 
			inet_ntoa(inetName->sin_addr), ntohs(portNbr));
		writeMemo(txt);
	}

	ionPauseMainThread(-1);

	/*	Time to shut down.					*/

	rtp.running = 0;

	/*	Wake up the receiver thread by sending it a 1-byte
	 *	datagram.						*/

	fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (fd >= 0)
	{
		isendto(fd, &quit, 1, 0, &socketName, sizeof(struct sockaddr));
		closesocket(fd);
	}

	pthread_join(receiverThread, NULL);
	closesocket(rtp.linkSocket);
	writeErrmsgMemos();
	writeMemo("[i] udplsi has ended.");
	ionDetach();
	return 0;
}
Esempio n. 19
0
File: stcpclo.c Progetto: b/ION
int	stcpclo(int a1, int a2, int a3, int a4, int a5,
		int a6, int a7, int a8, int a9, int a10)
{
	char	*ductName = (char *) a1;
#else
int	main(int argc, char *argv[])
{
	char	*ductName = (argc > 1 ? argv[1] : NULL);
#endif
	unsigned char		*buffer;
	VOutduct		*vduct;
	PsmAddress		vductElt;
	Sdr			sdr;
	Outduct			duct;
	ClProtocol		protocol;
	Outflow			outflows[3];
	int			i;
	char			*hostName;
	unsigned short		portNbr;
	unsigned int		hostNbr;
	struct sockaddr		socketName;
	struct sockaddr_in	*inetName;
	int			running = 1;
	pthread_mutex_t		mutex;
	KeepaliveThreadParms	parms;
	pthread_t		keepaliveThread;
	Object			bundleZco;
	BpExtendedCOS		extendedCOS;
	char			destDuctName[MAX_CL_DUCT_NAME_LEN + 1];
	unsigned int		bundleLength;
	int			ductSocket = -1;
	int			bytesSent;

	if (ductName == NULL)
	{
		PUTS("Usage: stcpclo <remote host name>[:<port number>]");
		return 0;
	}

	if (bpAttach() < 0)
	{
		putErrmsg("stcpclo can't attach to BP.", NULL);
		return -1;
	}

	buffer = MTAKE(TCPCLA_BUFSZ);
	if (buffer == NULL)
	{
		putErrmsg("No memory for TCP buffer in stcpclo.", NULL);
		return -1;
	}

	findOutduct("stcp", ductName, &vduct, &vductElt);
	if (vductElt == 0)
	{
		putErrmsg("No such stcp duct.", ductName);
		MRELEASE(buffer);
		return -1;
	}

	if (vduct->cloPid > 0 && vduct->cloPid != sm_TaskIdSelf())
	{
		putErrmsg("CLO task is already started for this duct.",
				itoa(vduct->cloPid));
		MRELEASE(buffer);
		return -1;
	}

	/*	All command-line arguments are now validated.		*/

	sdr = getIonsdr();
	sdr_read(sdr, (char *) &duct, sdr_list_data(sdr, vduct->outductElt),
			sizeof(Outduct));
	sdr_read(sdr, (char *) &protocol, duct.protocol, sizeof(ClProtocol));
	if (protocol.nominalRate <= 0)
	{
		vduct->xmitThrottle.nominalRate = DEFAULT_TCP_RATE;
	}
	else
	{
		vduct->xmitThrottle.nominalRate = protocol.nominalRate;
	}

	memset((char *) outflows, 0, sizeof outflows);
	outflows[0].outboundBundles = duct.bulkQueue;
	outflows[1].outboundBundles = duct.stdQueue;
	outflows[2].outboundBundles = duct.urgentQueue;
	for (i = 0; i < 3; i++)
	{
		outflows[i].svcFactor = 1 << i;
	}

	hostName = ductName;
	parseSocketSpec(ductName, &portNbr, &hostNbr);
	if (portNbr == 0)
	{
		portNbr = BpTcpDefaultPortNbr;
	}

	portNbr = htons(portNbr);
	if (hostNbr == 0)
	{
		putErrmsg("Can't get IP address for host.", hostName);
		MRELEASE(buffer);
		return -1;
	}

	hostNbr = htonl(hostNbr);
	memset((char *) &socketName, 0, sizeof socketName);
	inetName = (struct sockaddr_in *) &socketName;
	inetName->sin_family = AF_INET;
	inetName->sin_port = portNbr;
	memcpy((char *) &(inetName->sin_addr.s_addr), (char *) &hostNbr, 4);

	/*	Set up signal handling.  SIGTERM is shutdown signal.	*/

	oK(stcpcloSemaphore(&(vduct->semaphore)));
	isignal(SIGTERM, shutDownClo);
	isignal(SIGPIPE, handleConnectionLoss);

	/*	Start the keepalive thread for the eventual connection.	*/

	parms.cloRunning = &running;
	pthread_mutex_init(&mutex, NULL);
	parms.mutex = &mutex;
	parms.socketName = &socketName;
	parms.ductSocket = &ductSocket;
	if (pthread_create(&keepaliveThread, NULL, sendKeepalives, &parms))
	{
		putSysErrmsg("stcpclo can't create keepalive thread", NULL);
		MRELEASE(buffer);
		pthread_mutex_destroy(&mutex);
		return 1;
	}

	/*	Can now begin transmitting to remote duct.		*/

	writeMemo("[i] stcpclo is running.");
	while (!(sm_SemEnded(stcpcloSemaphore(NULL))))
	{
		if (bpDequeue(vduct, outflows, &bundleZco, &extendedCOS,
				destDuctName) < 0)
		{
			sm_SemEnd(stcpcloSemaphore(NULL));/*	Stop.	*/
			continue;
		}

		if (bundleZco == 0)	/*	Interrupted.		*/
		{
			continue;
		}

		bundleLength = zco_length(sdr, bundleZco);
		pthread_mutex_lock(&mutex);
		bytesSent = sendBundleByTCP(&socketName, &ductSocket,
				bundleLength, bundleZco, buffer);
		pthread_mutex_unlock(&mutex);
		if (bytesSent < bundleLength)
		{
			sm_SemEnd(stcpcloSemaphore(NULL));/*	Stop.	*/
			continue;
		}

		/*	Make sure other tasks have a chance to run.	*/

		sm_TaskYield();
	}

	running = 0;			/*	Terminate keepalive.	*/
	pthread_join(keepaliveThread, NULL);
	if (ductSocket != -1)
	{
		close(ductSocket);
	}

	pthread_mutex_destroy(&mutex);
	writeErrmsgMemos();
	writeMemo("[i] stcpclo duct has ended.");
	MRELEASE(buffer);
	ionDetach();
	return 0;
}
Esempio n. 20
0
static void	*handleDatagrams(void *parm)
{
	/*	Main loop for UDP datagram reception and handling.	*/

	ReceiverThreadParms	*rtp = (ReceiverThreadParms *) parm;
	char			*procName = "udplsi";
	char			*buffer;
	int			segmentLength;
	struct sockaddr_in	fromAddr;
	socklen_t		fromSize;

	snooze(1);	/*	Let main thread become interruptable.	*/
	buffer = MTAKE(UDPLSA_BUFSZ);
	if (buffer == NULL)
	{
		putErrmsg("udplsi can't get UDP buffer.", NULL);
		ionKillMainThread(procName);
		return NULL;
	}

	/*	Can now start receiving bundles.  On failure, take
	 *	down the LSI.						*/

	while (rtp->running)
	{	
		fromSize = sizeof fromAddr;
		segmentLength = irecvfrom(rtp->linkSocket, buffer, UDPLSA_BUFSZ,
				0, (struct sockaddr *) &fromAddr, &fromSize);
		switch (segmentLength)
		{
		case -1:
			putSysErrmsg("Can't acquire segment", NULL);
			ionKillMainThread(procName);

			/*	Intentional fall-through to next case.	*/

		case 1:				/*	Normal stop.	*/
			rtp->running = 0;
			continue;
		}

		if (ltpHandleInboundSegment(buffer, segmentLength) < 0)
		{
			putErrmsg("Can't handle inbound segment.", NULL);
			ionKillMainThread(procName);
			rtp->running = 0;
			continue;
		}

		/*	Make sure other tasks have a chance to run.	*/

		sm_TaskYield();
	}

	writeErrmsgMemos();
	writeMemo("[i] udplsi receiver thread has ended.");

	/*	Free resources.						*/

	MRELEASE(buffer);
	return NULL;
}
Esempio n. 21
0
static void	*csHeartbeat(void *parm)
{
	CsState		*csState = (CsState *) parm;
	pthread_mutex_t	mutex;
	pthread_cond_t	cv;
	int		cycleCount = 6;
	int		i;
	Venture		*venture;
	int		j;
	Unit		*unit;
	Cell		*cell;
	int		result;
	struct timeval	workTime;
	struct timespec	deadline;

	CHKNULL(csState);
	if (pthread_mutex_init(&mutex, NULL))
	{
		putSysErrmsg("Can't start heartbeat, mutex init failed", NULL);
		return NULL;
	}

	if (pthread_cond_init(&cv, NULL))
	{
		pthread_mutex_destroy(&mutex);
		putSysErrmsg("Can't start heartbeat, cond init failed", NULL);
		return NULL;
	}
#ifndef mingw
	sigset_t	signals;

	sigfillset(&signals);
	pthread_sigmask(SIG_BLOCK, &signals, NULL);
#endif
	while (1)
	{
		lockMib();
		if (cycleCount > 5)	/*	Every N5_INTERVAL sec.	*/
		{
			cycleCount = 0;
			stopOtherConfigServers(csState);
		}

		for (i = 1; i <= MAX_VENTURE_NBR; i++)
		{
			venture = (_mib(NULL))->ventures[i];
			if (venture == NULL) continue;
			for (j = 0; j <= MAX_UNIT_NBR; j++)
			{
				unit = venture->units[j];
				if (unit == NULL
				|| (cell = unit->cell)->mamsEndpoint.ept
						== NULL)
				{
					continue;
				}

				if (cell->heartbeatsMissed == 3)
				{
					clearMamsEndpoint
						(&(cell->mamsEndpoint));
				}
				else if (cell->heartbeatsMissed < 3)
				{
					if (sendMamsMsg (&cell->mamsEndpoint,
						&csState->tsif, heartbeat,
						0, 0, NULL) < 0)
					{
						putErrmsg("Can't send \
heartbeat.", NULL);
					}
				}

				cell->heartbeatsMissed++;
			}
		}

		/*	Now sleep for N3_INTERVAL seconds.		*/

		unlockMib();
		getCurrentTime(&workTime);
		deadline.tv_sec = workTime.tv_sec + N3_INTERVAL;
		deadline.tv_nsec = workTime.tv_usec * 1000;
		pthread_mutex_lock(&mutex);
		result = pthread_cond_timedwait(&cv, &mutex, &deadline);
		pthread_mutex_unlock(&mutex);
		if (result)
		{
			errno = result;
			if (errno != ETIMEDOUT)
			{
				putSysErrmsg("Heartbeat failure", NULL);
				break;
			}
		}

		cycleCount++;
	}
Esempio n. 22
0
File: udpts.c Progetto: b/ION
static int	udpMamsInit(MamsInterface *tsif)
{
	unsigned short		portNbr;
	unsigned int		ipAddress;
	char			hostName[MAXHOSTNAMELEN + 1];
	struct sockaddr		socketName;
	struct sockaddr_in	*inetName;
	socklen_t		nameLength;
	int			fd;
	char			endpointNameText[32];
	int			eptLen;
	long			longfd;

	parseSocketSpec(tsif->endpointSpec, &portNbr, &ipAddress);
//printf("parsed endpoint spec to port %d address %d.\n", portNbr, ipAddress);
	if (ipAddress == 0)
	{
		getNameOfHost(hostName, sizeof hostName);
		ipAddress = getInternetAddress(hostName);
	}
	else
	{
		if (getInternetHostName(ipAddress, hostName) == NULL)
		{
			putErrmsg("Unknown host in endpoint.",
					tsif->endpointSpec);
			return -1;
		}
	}

	portNbr = htons(portNbr);
	ipAddress = htonl(ipAddress);
	memset((char *) &socketName, 0, sizeof socketName);
	inetName = (struct sockaddr_in *) &socketName;
	inetName->sin_family = AF_INET;
	inetName->sin_port = portNbr;
	memcpy((char *) &(inetName->sin_addr.s_addr), (char *) &ipAddress, 4);
	fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (fd < 0)
	{
		putSysErrmsg("udpts can't open MAMS SAP", NULL);
		return -1;
	}

	nameLength = sizeof(struct sockaddr);
	if (reUseAddress(fd)
	|| bind(fd, &socketName, nameLength) < 0
	|| getsockname(fd, &socketName, &nameLength) < 0)
	{
		putSysErrmsg("udpts can't initialize AMS SAP", NULL);
		return -1;
	}

	portNbr = inetName->sin_port;
	portNbr = ntohs(portNbr);
	memcpy((char *) &ipAddress, (char *) &(inetName->sin_addr.s_addr), 4);
	ipAddress = ntohl(ipAddress);
	isprintf(endpointNameText, sizeof endpointNameText, "%s:%hu", hostName,
			portNbr);
//printf("resulting ept is '%s'.\n", endpointNameText);
	eptLen = strlen(endpointNameText) + 1;
	tsif->ept = MTAKE(eptLen);
	if (tsif->ept == NULL)
	{
		close(fd);
		putSysErrmsg(NoMemoryMemo, NULL);
		return -1;
	}

	istrcpy(tsif->ept, endpointNameText, eptLen);
	longfd = fd;
	tsif->sap = (void *) longfd;
	return 0;
}
Esempio n. 23
0
File: pmqlsi.c Progetto: b/ION
int	pmqlsi(int a1, int a2, int a3, int a4, int a5,
		int a6, int a7, int a8, int a9, int a10)
{
	char	*mqName = (char *) a1;
#else
int	main(int argc, char *argv[])
{
	char	*mqName = (argc > 1 ? argv[1] : NULL);
#endif
	LtpVdb			*vdb;
	struct mq_attr		mqAttributes =
					{ 0, PMQLSA_MAXMSG, PMQLSA_MSGSIZE, 0 };
	ReceiverThreadParms	rtp;
	pthread_t		receiverThread;
	char			stop = '0';

	if (mqName == NULL)
	{
		puts("Usage: pmqlsi <message queue name>");
		return 0;
	}

	/*	Note that ltpadmin must be run before the first
	 *	invocation of ltplsi, to initialize the LTP database
	 *	(as necessary) and dynamic database.			*/ 

	if (ltpInit(0, 0) < 0)
	{
		putErrmsg("pmqlsi can't initialize LTP.", NULL);
		return 1;
	}

	vdb = getLtpVdb();
	if (vdb->lsiPid > 0 && vdb->lsiPid != sm_TaskIdSelf())
	{
		putErrmsg("LSI task is already started.", itoa(vdb->lsiPid));
		return 1;
	}

	/*	All command-line arguments are now validated.		*/

	rtp.mq = mq_open(mqName, O_RDWR | O_CREAT, 0777, &mqAttributes);
	if (rtp.mq == (mqd_t) -1)
	{
		putSysErrmsg("pmglsi can't open message queue", mqName);
		return 1;
	}

	/*	Set up signal handling; SIGTERM is shutdown signal.	*/

	isignal(SIGTERM, interruptThread);

	/*	Start the receiver thread.				*/

	rtp.running = 1;
	rtp.mainThread = pthread_self();
	if (pthread_create(&receiverThread, NULL, handleMessages, &rtp))
	{
		mq_close(rtp.mq);
		putSysErrmsg("pmqlsi can't create receiver thread", NULL);
		return 1;
	}

	/*	Now sleep until interrupted by SIGTERM, at which point
	 *	it's time to stop the link service.			*/

	writeMemo("[i] pmqlsi is running");
	snooze(2000000000);

	/*	Time to shut down.					*/

	rtp.running = 0;
	mq_send(rtp.mq, &stop, 1, 0);	/*	Tell receiver to stop.	*/
	pthread_join(receiverThread, NULL);
	mq_close(rtp.mq);
	writeErrmsgMemos();
	writeMemo("[i] pmqlsi duct has ended.");
	return 0;
}
Esempio n. 24
0
int	bputa(int a1, int a2, int a3, int a4, int a5,
          int a6, int a7, int a8, int a9, int a10)
{
#else
int	main(int argc, char **argv)
{
#endif
    char		ownEid[64];
    BpSAP		txSap;
    RxThreadParms	parms;
    Sdr		sdr;
    pthread_t	rxThread;
    int		haveRxThread = 0;
    Object		pduZco;
    OutFdu		fduBuffer;
    BpUtParms	utParms;
    uvast		destinationNodeNbr;
    char		destEid[64];
    char		reportToEidBuf[64];
    char		*reportToEid;
    Object		newBundle;
    Object		pduElt;

    if (bp_attach() < 0)
    {
        putErrmsg("CFDP can't attach to BP.", NULL);
        return 0;
    }

    isprintf(ownEid, sizeof ownEid, "ipn:" UVAST_FIELDSPEC ".%u",
             getOwnNodeNbr(), CFDP_SEND_SVC_NBR);
    if (bp_open(ownEid, &txSap) < 0)
    {
        putErrmsg("CFDP can't open own 'send' endpoint.", ownEid);
        return 0;
    }

    if (txSap == NULL)
    {
        putErrmsg("bputa can't get Bundle Protocol SAP.", NULL);
        return 0;
    }

    if (cfdpAttach() < 0)
    {
        bp_close(txSap);
        putErrmsg("bputa can't attach to CFDP.", NULL);
        return 0;
    }

    sdr = bp_get_sdr();
    parms.mainThread = pthread_self();
    parms.running = 1;
    if (pthread_begin(&rxThread, NULL, receivePdus, &parms))
    {
        bp_close(txSap);
        putSysErrmsg("bputa can't create receiver thread", NULL);
        return -1;
    }

    haveRxThread = 1;
    writeMemo("[i] bputa is running.");
    while (parms.running)
    {
        /*	Get an outbound CFDP PDU for transmission.	*/

        if (cfdpDequeueOutboundPdu(&pduZco, &fduBuffer) < 0)
        {
            writeMemo("[?] bputa can't dequeue outbound CFDP PDU; \
terminating.");
            parms.running = 0;
            continue;
        }

        /*	Determine quality of service for transmission.	*/

        if (fduBuffer.utParmsLength == sizeof(BpUtParms))
        {
            memcpy((char *) &utParms, (char *) &fduBuffer.utParms,
                   sizeof(BpUtParms));
        }
        else
        {
            memset((char *) &utParms, 0, sizeof(BpUtParms));
            utParms.reportToNodeNbr = 0;
            utParms.lifespan = 86400;	/*	1 day.	*/
            utParms.classOfService = BP_STD_PRIORITY;
            utParms.custodySwitch = NoCustodyRequested;
            utParms.srrFlags = 0;
            utParms.ackRequested = 0;
            utParms.extendedCOS.flowLabel = 0;
            utParms.extendedCOS.flags = 0;
            utParms.extendedCOS.ordinal = 0;
        }

        cfdp_decompress_number(&destinationNodeNbr,
                               &fduBuffer.destinationEntityNbr);
        if (destinationNodeNbr == 0)
        {
            writeMemo("[?] bputa declining to send to node 0.");
            continue;
        }

        isprintf(destEid, sizeof destEid, "ipn:" UVAST_FIELDSPEC ".%u",
                 destinationNodeNbr, CFDP_RECV_SVC_NBR);
        if (utParms.reportToNodeNbr == 0)
        {
            reportToEid = NULL;
        }
        else
        {
            isprintf(reportToEidBuf, sizeof reportToEidBuf,
                     "ipn:" UVAST_FIELDSPEC ".%u",
                     utParms.reportToNodeNbr,
                     CFDP_RECV_SVC_NBR);
            reportToEid = reportToEidBuf;
        }

        /*	Send PDU in a bundle.				*/

        newBundle = 0;
        if (bp_send(txSap, destEid, reportToEid, utParms.lifespan,
                    utParms.classOfService, utParms.custodySwitch,
                    utParms.srrFlags, utParms.ackRequested,
                    &utParms.extendedCOS, pduZco, &newBundle) <= 0)
        {
            putErrmsg("bputa can't send PDU in bundle; terminated.",
                      NULL);
            parms.running = 0;
        }

        if (newBundle == 0)
        {
            continue;	/*	Must have stopped.	*/
        }

        /*	Enable cancellation of this PDU.		*/

        if (sdr_begin_xn(sdr) == 0)
        {
            parms.running = 0;
            continue;
        }

        pduElt = sdr_list_insert_last(sdr, fduBuffer.extantPdus,
                                      newBundle);
        if (pduElt)
        {
            bp_track(newBundle, pduElt);
        }

        if (sdr_end_xn(sdr) < 0)
        {
            putErrmsg("bputa can't track PDU; terminated.", NULL);
            parms.running = 0;
        }

        /*	Make sure other tasks have a chance to run.	*/

        sm_TaskYield();
    }
Esempio n. 25
0
File: amsbenchs.c Progetto: b/ION
int	amsbenchs(int a1, int a2, int a3, int a4, int a5,
		int a6, int a7, int a8, int a9, int a10)
{
	int		count = a1;
	int		size = a2;
#else
int	main(int argc, char **argv)
{
	int		count = (argc > 1 ? atoi(argv[1]) : 0);
	int		size = (argc > 2 ? atoi(argv[2]) : 0);
#endif
	char		*application = "amsdemo";
	char		*authority = "test";
	char		*buffer;
	AmsNode		me;
	AmsEventMgt	rules;
	int		subjectNbr;
	int		content;

	if (count < 1 || size < 4 || size > 65535)
	{
		PUTS("Usage: amsbenchs <# of msgs to send> <msg length>");
		return 0;
	}

	buffer = malloc(size);
	if (buffer == NULL)
	{
		putSysErrmsg("No memory for amsbenchs.", NULL);
		return 0;
	}

	memset(buffer, ' ', size);
	if (ams_register("amsmib.xml", NULL, NULL, NULL, 0, application,
			authority, "", "benchs", &me) < 0)
	{
		putSysErrmsg("amsbenchs can't register", NULL);
		return -1;
	}

	memset((char *) &rules, 0, sizeof(AmsEventMgt));
	rules.errHandler = reportError;
	if (ams_set_event_mgr(me, &rules) < 0)
	{
		ams_unregister(me);
		putSysErrmsg("amsbenchs can't set event manager", NULL);
		return -1;
	}

	subjectNbr = ams_lookup_subject_nbr(me, "bench");
	if (subjectNbr < 0)
	{
		ams_unregister(me);
		putErrmsg("Subject 'bench' is unknown.", NULL);
		return -1;
	}

	snooze(1);	/*	Wait for subscriptions to arrive.	*/
	while (count > 0)
	{
		content = htonl(count);
		memcpy(buffer, (char *) &content, sizeof(int));
		if (ams_publish(me, subjectNbr, 0, 0, size, buffer, 0) < 0)
		{
			putErrmsg("Unable to publish message.", NULL);
			break;
		}

		count--;
	}

	writeErrmsgMemos();
	PUTS("Message publication ended; press ^C when test is done.");
	signal(SIGINT, handleQuit);
	snooze(3600);
	ams_unregister(me);
	return 0;
}
Esempio n. 26
0
int	pmqlso(int a1, int a2, int a3, int a4, int a5,
		int a6, int a7, int a8, int a9, int a10)
{
	char		*mqName = (char *) a1;
	uvast		remoteEngineId = a2 != 0 ? strtouvast((char *) a2) : 0;
#else
int	main(int argc, char *argv[])
{
	char		*mqName = argc > 1 ? argv[1] : NULL;
	uvast		remoteEngineId = argc > 2 ? strtouvast(argv[2]) : 0;
#endif
	Sdr		sdr;
	LtpVspan	*vspan;
	PsmAddress	vspanElt;
	struct mq_attr	mqAttributes = { 0, PMQLSA_MAXMSG, PMQLSA_MSGSIZE, 0 };
	mqd_t		mq;
	int		running;
	int		segmentLength;
	char		*segment;

	if (remoteEngineId == 0 || mqName == NULL)
	{
		puts("Usage: pmqlso <message queue name> <remote engine ID>");
		return 0;
	}

	/*	Note that ltpadmin must be run before the first
	 *	invocation of ltplso, to initialize the LTP database
	 *	(as necessary) and dynamic database.			*/

	if (ltpInit(0) < 0)
	{
		putErrmsg("pmqlso can't initialize LTP.", NULL);
		return 1;
	}

	sdr = getIonsdr();
	CHKERR(sdr_begin_xn(sdr));	/*	Just to lock memory.	*/
	findSpan(remoteEngineId, &vspan, &vspanElt);
	if (vspanElt == 0)
	{
		sdr_exit_xn(sdr);
		putErrmsg("No such engine in database.", itoa(remoteEngineId));
		return 1;
	}

	if (vspan->lsoPid > 0 && vspan->lsoPid != sm_TaskIdSelf())
	{
		sdr_exit_xn(sdr);
		putErrmsg("LSO task is already started for this span.",
				itoa(vspan->lsoPid));
		return 1;
	}

	/*	All command-line arguments are now validated.		*/

	sdr_exit_xn(sdr);
	mq = mq_open(mqName, O_RDWR | O_CREAT, 0777, &mqAttributes);
	if (mq == (mqd_t) -1)
	{
		putSysErrmsg("pmqlso can't open message queue", mqName);
		return 1;
	}

	oK(_pmqlsoSemaphore(&vspan->segSemaphore));
	isignal(SIGTERM, interruptThread);

	/*	Can now begin transmitting to remote engine.		*/

	writeMemo("[i] pmqlso is running.");
	running = 1;
	while (running && !(sm_SemEnded(_pmqlsoSemaphore(NULL))))
	{
		segmentLength = ltpDequeueOutboundSegment(vspan, &segment);
		if (segmentLength < 0)
		{
			running = 0;	/*	Terminate LSO.		*/
			continue;
		}

		if (segmentLength == 0)	/*	Interrupted.		*/
		{
			continue;
		}

		if (segmentLength > PMQLSA_MSGSIZE)
		{
			putErrmsg("Segment is too big for PMQ LSO.",
					itoa(segmentLength));
			running = 0;	/*	Terminate LSO.		*/
			continue;
		}

		if (sendSegmentByPMQ(mq, segment, segmentLength) < 0)
		{
			putSysErrmsg("pmqlso failed sending segment", mqName);
			running = 0;	/*	Terminate LSO.	*/
			continue;
		}

		/*	Make sure other tasks have a chance to run.	*/

		sm_TaskYield();
	}

	mq_close(mq);
	writeErrmsgMemos();
	writeMemo("[i] pmqlso duct has ended.");
	ionDetach();
	return 0;
}