Пример #1
0
CWBool ACEnterConfigure(int WTPIndex, CWProtocolMessage *msgPtr) {

	int seqNum;
	CWProtocolConfigureRequestValues configureRequest;
	
	CWLog("\n");
	CWLog("######### Configure State #########");	
	
	if(!(CWParseConfigureRequestMessage(msgPtr->msg, msgPtr->offset, &seqNum, &configureRequest))) {
		/* note: we can kill our thread in case of out-of-memory 
		 * error to free some space.
		 * we can see this just calling CWErrorGetLastErrorCode()
		 */
		return CW_FALSE;
	}

	CWLog("Configure Request Received");
	
	if(!(CWSaveConfigureRequestMessage(&configureRequest, &(gWTPs[WTPIndex].WTPProtocolManager)))){
		return CW_FALSE;
	}
		
	if(!(CWAssembleConfigureResponse(&(gWTPs[WTPIndex].messages), 
					 &(gWTPs[WTPIndex].messagesCount), 
					 gWTPs[WTPIndex].pathMTU, 
					 seqNum)))  { 
		return CW_FALSE;
	}
	
	if(!CWACSendFragments(WTPIndex)) {
		return CW_FALSE;
	}
	
	CWLog("Configure Response Sent");

	/* Destroy ConfigStatePending timer */
	if(!CWErr(CWTimerCancel(&(gWTPs[WTPIndex].currentTimer)))) {
		CWLog("%s %d [%d] CWTimerCancel Fail, close thread!",__FILE__,__LINE__,WTPIndex);
		//CWCloseThread();
		gWTPs[WTPIndex].isRequestClose = CW_TRUE;
		return CW_FALSE;
	}
	
	
	/* start Change State Pending timer */
	if(!CWErr(CWTimerRequest(gCWChangeStatePendingTimer,
				 &(gWTPs[WTPIndex].thread),
				 &(gWTPs[WTPIndex].currentTimer),
				 CW_CRITICAL_TIMER_EXPIRED_SIGNAL))) {
		CWLog("%s %d [%d] CWTimerRequest Fail, close thread!",__FILE__,__LINE__,WTPIndex);
		//CWCloseThread();
		gWTPs[WTPIndex].isRequestClose = CW_TRUE;
		return CW_FALSE;
	}
	//CWLog("CWTimerRequest Success !!!");

	gWTPs[WTPIndex].currentState = CW_ENTER_DATA_CHECK;
	
	return CW_TRUE;
}
Пример #2
0
void CWACEnterMainLoop() {

	struct sigaction act;
	
	CWLog("AC enters in the MAIN_LOOP");
	
	/* set signals
	 * all the thread we spawn will inherit these settings
	 */

        /*
         * BUG UMR03
         *
         * 20/10/2009 - Donato Capitella 
         */
        sigemptyset(&act.sa_mask);

	act.sa_flags = 0;
	/* called when a timer requested by the thread has expired */
	act.sa_handler = CWCriticalTimerExpiredHandler;
	sigaction(CW_CRITICAL_TIMER_EXPIRED_SIGNAL, &act, NULL);
	
	act.sa_flags = 0;
	/* called when a timer requested by the thread has expired */
	act.sa_handler = CWSoftTimerExpiredHandler;
	sigaction(CW_SOFT_TIMER_EXPIRED_SIGNAL, &act, NULL);
	
	/* signals will be unblocked by the threads that needs timers */
	CWThreadSetSignals(SIG_BLOCK, 2, CW_CRITICAL_TIMER_EXPIRED_SIGNAL,
 					 CW_SOFT_TIMER_EXPIRED_SIGNAL);

	if(!(CWThreadCreateSpecific(&gIndexSpecific, NULL))) {
		CWLog("Critical Error With Thread Data");
		exit(1);
	}
	
	CWThread thread_interface;
	if(!CWErr(CWCreateThread(&thread_interface, CWInterface, NULL))) {
		CWLog("Error starting Interface Thread");
		exit(1);
	}

	CW_REPEAT_FOREVER {
		/* CWACManageIncomingPacket will be called 
		 * when a new packet is ready to be read 
		 */
		if(!CWErr(CWNetworkUnsafeMultiHomed(&gACSocket, 
						    CWACManageIncomingPacket,
						    CW_FALSE)))
			exit(1);
	}
}
Пример #3
0
/*
 * Manage DTLS packets.
 */
CW_THREAD_RETURN_TYPE CWWTPReceiveDtlsPacket(void *arg)
{

	int readBytes;
	unsigned char buf[CW_BUFFER_SIZE];
	CWSocket sockDTLS = (long) arg;
	CWNetworkLev4Address addr;
	char *pData;

	CW_REPEAT_FOREVER {
		if (!CWErr(CWNetworkReceiveUnsafe(sockDTLS, buf, CW_BUFFER_SIZE - 1, 0, &addr, &readBytes))) {

			if (CWErrorGetLastErrorCode() == CW_ERROR_INTERRUPTED)
				continue;

			break;
		}

		/* Clone data packet */
		CW_CREATE_OBJECT_SIZE_ERR(pData, readBytes, {
					  CWLog("Out Of Memory");
					  return NULL;
					  }
		);
		memcpy(pData, buf, readBytes);

		CWLockSafeList(gPacketReceiveList);
		CWAddElementToSafeListTailwitDataFlag(gPacketReceiveList, pData, readBytes, CW_FALSE);
		CWUnlockSafeList(gPacketReceiveList);
	}
Пример #4
0
__inline__ int CWACGetActiveWTPs() {
	int tmp;
	if(!CWErr(CWThreadMutexLock(&gActiveWTPsMutex))) return 0;
		tmp = gActiveWTPs;
	CWThreadMutexUnlock(&gActiveWTPsMutex);
	
	return tmp;
}
Пример #5
0
int CWACSemPostForOpenSSLHack(void *s) {

	CWThreadTimedSem *semPtr = (CWThreadTimedSem*) s;
	
	if(!CWThreadTimedSemIsZero(semPtr)) {
		CWLog("This Semaphore's Value should really be 0");
		/* note: we can consider setting the value to 0 and going on,
		 * that is what we do here
		 */
		if(!CWErr(CWThreadTimedSemSetValue(semPtr, 0))) return 0;
	}
	
	if(!CWErr(CWThreadTimedSemPost(semPtr))) {
		return 0;
	}
	 
	return 1;
}
Пример #6
0
void CWCreateConnectionWithHostapdAC()
{

	CWThread thread_ipc_with_ac_hostapd;
	if (!CWErr(CWCreateThread(&thread_ipc_with_ac_hostapd, CWACipc_with_ac_hostapd, NULL))) {
		CWLog("Error starting Thread that receive command and 802.11 frame from hostapd (WTP side)");
		exit(1);
	}

}
Пример #7
0
__inline__ int CWACGetActiveWTPs() {
    int tmp;
    if(!CWErr(CWThreadMutexLock(&gActiveWTPsMutex)))
    {
        CWLog("F:%s L:%d Error locking  mutex",__FILE__,__LINE__);
        return 0;
    }
    tmp = gActiveWTPs;
    CWThreadMutexUnlock(&gActiveWTPsMutex);

    return tmp;
}
Пример #8
0
CWBool ACEnterDataCheck(int WTPIndex, CWProtocolMessage * msgPtr)
{

	/*CWProtocolMessage *messages = NULL; */
	int seqNum;
	CWProtocolChangeStateEventRequestValues *changeStateEvent;

	CWLog("\n");
	CWDebugLog("######### Status Event #########");

	/* Destroy ChangeStatePending timer */
	if (!CWErr(CWTimerCancel(&(gWTPs[WTPIndex].currentTimer)))) {

		CWCloseThread();
	}

	CW_CREATE_OBJECT_ERR(changeStateEvent,
			     CWProtocolChangeStateEventRequestValues, return CWErrorRaise(CW_ERROR_OUT_OF_MEMORY, NULL);
	    );
Пример #9
0
/*
 * Manage Discovery State
 */
CWStateTransition CWWTPEnterDiscovery()
{
	int i;
	CWBool j;

	CWLog("\n");
	CWLog("######### Discovery State #########");

	/* reset Discovery state */
	gCWDiscoveryCount = 0;
	CWNetworkCloseSocket(gWTPSocket);
	if (!CWErr(CWNetworkInitSocketClient(&gWTPSocket, NULL))) {
		return CW_QUIT;
	}

	/*
	 * note: gCWACList can be freed and reallocated (reading from config file)
	 * at each transition to the discovery state to save memory space
	 */
	for (i = 0; i < gCWACCount; i++)
		gCWACList[i].received = CW_FALSE;

	/* wait a random time */
	sleep(CWRandomIntInRange(gCWDiscoveryInterval, gCWMaxDiscoveryInterval));

	CW_REPEAT_FOREVER {
		CWBool sentSomething = CW_FALSE;

		/* we get no responses for a very long time */
		if (gCWDiscoveryCount == gCWMaxDiscoveries)
			return CW_ENTER_SULKING;

		/* send Requests to one or more ACs */
		for (i = 0; i < gCWACCount; i++) {

			/* if this AC hasn't responded to us... */
			if (!(gCWACList[i].received)) {
				/* ...send a Discovery Request */

				CWProtocolMessage *msgPtr = NULL;

				/* get sequence number (and increase it) */
				gCWACList[i].seqNum = CWGetSeqNum();

				if (!CWErr(CWAssembleDiscoveryRequest(&msgPtr, gCWACList[i].seqNum))) {
					exit(1);
				}

				CW_CREATE_OBJECT_ERR(gACInfoPtr, CWACInfoValues, return CW_QUIT;
				    );

				CWNetworkGetAddressForHost(gCWACList[i].address, &(gACInfoPtr->preferredAddress));

				CWUseSockNtop(&(gACInfoPtr->preferredAddress), CWDebugLog(str);
				    );

				j = CWErr(CWNetworkSendUnsafeUnconnected(gWTPSocket,
									 &(gACInfoPtr->preferredAddress),
									 (*msgPtr).msg, (*msgPtr).offset));
				/*
				 * log eventual error and continue
				 * CWUseSockNtop(&(gACInfoPtr->preferredAddress),
				 *       CWLog("WTP sends Discovery Request to: %s", str););
				 */

				CW_FREE_PROTOCOL_MESSAGE(*msgPtr);
				CW_FREE_OBJECT(msgPtr);
				CW_FREE_OBJECT(gACInfoPtr);

				/*
				 * we sent at least one Request in this loop
				 * (even if we got an error sending it)
				 */
				sentSomething = CW_TRUE;
			}
Пример #10
0
CWBool ACEnterRun(int WTPIndex, CWProtocolMessage *msgPtr, CWBool dataFlag) {

	CWBool toSend = CW_FALSE, timerSet = CW_TRUE;
	CWControlHeaderValues controlVal;
	CWProtocolMessage* messages = NULL;
	int messagesCount = 0;
	unsigned char StationMacAddr[MAC_ADDR_LEN];
	char string[10];
	char socketctl_path_name[50];
	char socketserv_path_name[50];
	msgPtr->offset = 0;

	// cancel NeighborDeadTimer timer
	CWStopNeighborDeadTimer(WTPIndex);
	timerSet = CW_FALSE;

	if (dataFlag) {
		/* We have received a Data Message... now just log this event and do actions by the dataType */
		CWLog("--> Received a DATA Message");

		if (msgPtr->data_msgType == CW_DATA_MSG_FRAME_TYPE) {
			/*Retrive mac address station from msg*/
			memset(StationMacAddr, 0, MAC_ADDR_LEN);
			memcpy(StationMacAddr, msgPtr->msg + SOURCE_ADDR_START, MAC_ADDR_LEN);

			int seqNum = CWGetSeqNum();

			//Send a Station Configuration Request
			if (CWAssembleStationConfigurationRequest(&(gWTPs[WTPIndex].messages),
					&(gWTPs[WTPIndex].messagesCount), gWTPs[WTPIndex].pathMTU, seqNum,
					StationMacAddr)) {

				if (CWACSendAcknowledgedPacket(WTPIndex,
						CW_MSG_TYPE_VALUE_STATION_CONFIGURATION_RESPONSE, seqNum))
					return CW_TRUE;
				else
					CWACStopRetransmission(WTPIndex);
			}
		} else {

			/************************************************************
			 * Update 2009:												*
			 *				Manage special data packets with frequency	*
			 *				statistics informations.					*
			 ************************************************************/

			if (msgPtr->data_msgType == CW_DATA_MSG_FREQ_STATS_TYPE) {

				int cells; /* How many cell are heard */
				int isAck;
				char * freqPayload;
				int socketIndex, indexToSend = htonl(WTPIndex);

				int sizeofAckInfoUnit = CW_FREQ_ACK_SIZE;
				int sizeofFreqInfoUnit = CW_FREQ_CELL_INFO_PAYLOAD_SIZE;
				int sizeOfPayload = 0, payload_offset = 0;

				/*-----------------------------------------------------------------------------------------------
				 *	Payload Management ( infos for frequency application) :
				 *		Ack       Structure : |  WTPIndex  |   Ack Value  | 
				 *      Freq Info Structure : |  WTPIndex  |  Number of cells  |  Frequecies Info Payload | 
				 *-----------------------------------------------------------------------------------------------*/

				memcpy(&isAck, msgPtr->msg, sizeof(int));

				isAck = ntohl(isAck);

				if (isAck == 0) { /* isnt an ack message */
					memcpy(&cells, msgPtr->msg + sizeof(int), sizeof(int));
					cells = ntohl(cells);
					sizeOfPayload = (cells * sizeofFreqInfoUnit) + (2 * sizeof(int));
				} else {
					sizeOfPayload = sizeofAckInfoUnit;
				}

				if ((freqPayload = malloc(sizeOfPayload)) != NULL) {

					memset(freqPayload, 0, sizeOfPayload);
					memcpy(freqPayload, &indexToSend, sizeof(int));
					payload_offset += sizeof(int);

					if (isAck == 0) {
						memcpy(freqPayload + payload_offset, msgPtr->msg + sizeof(int),
								sizeOfPayload - payload_offset);
					} else {
						memcpy(freqPayload + payload_offset, msgPtr->msg + sizeof(int),
								sizeOfPayload - payload_offset);
					}

					socketIndex = gWTPs[WTPIndex].applicationIndex;

					/****************************************************
					 *		Forward payload to correct application 		*
					 ****************************************************/

					if (!CWErr(CWThreadMutexLock(&appsManager.socketMutex[socketIndex]))) {
						CWLog("[ACrunState]:: Error locking socket Application Mutex");
						free(freqPayload);
						return CW_FALSE;
					}

					if (Writen(appsManager.appSocket[socketIndex], freqPayload, sizeOfPayload) < 0) {
						CWThreadMutexUnlock(&appsManager.socketMutex[socketIndex]);
						free(freqPayload);
						CWLog("[ACrunState]:: Error writing Message To Application");
						return CW_FALSE;
					}

					CWThreadMutexUnlock(&appsManager.socketMutex[socketIndex]);
					free(freqPayload);
				} else
					CWLog("[ACrunState]:: Malloc error (payload to frequency application");
			}

			if (msgPtr->data_msgType == CW_DATA_MSG_STATS_TYPE) {
				if (!UnixSocksArray[WTPIndex].data_stats_sock) { //Init Socket only the first time when the function is called
					if ((UnixSocksArray[WTPIndex].data_stats_sock = socket(AF_UNIX, SOCK_DGRAM, 0))
							< 0) {
						CWDebugLog("Error creating socket for data send");
						return CW_FALSE;
					}

					memset(&(UnixSocksArray[WTPIndex].clntaddr), (int) NULL,
							sizeof(UnixSocksArray[WTPIndex].clntaddr));
					UnixSocksArray[WTPIndex].clntaddr.sun_family = AF_UNIX;

					//make unix socket client path name by index i
					snprintf(string, sizeof(string), "%d", WTPIndex);
					string[sizeof(string) - 1] = 0;
					strcpy(socketctl_path_name, SOCKET_PATH_AC);
					strcat(socketctl_path_name, string);
					strcpy(UnixSocksArray[WTPIndex].clntaddr.sun_path, socketctl_path_name);

					unlink(socketctl_path_name);

					memset(&(UnixSocksArray[WTPIndex].servaddr), (int) NULL,
							sizeof(UnixSocksArray[WTPIndex].servaddr));
					UnixSocksArray[WTPIndex].servaddr.sun_family = AF_UNIX;

					//make unix socket server path name by index i
					strcpy(socketserv_path_name, SOCKET_PATH_RECV_AGENT);
					strcat(socketserv_path_name, string);
					strcpy(UnixSocksArray[WTPIndex].servaddr.sun_path, socketserv_path_name);
					CWDebugLog("%s\t%s", socketserv_path_name, socketctl_path_name);
					//fflush(stdout);
				}

				int nbytes;
				int totalBytesToSend = 0;
				bcopy((char*) msgPtr->msg, (char*) &totalBytesToSend, sizeof(unsigned int));
				totalBytesToSend = ntohl(totalBytesToSend);
				int pDataLen = totalBytesToSend; //len of Monitoring Data

				//CWDebugLog("\n%s\t%s", socketserv_path_name, socketctl_path_name);


				CWDebugLog("Total bytes to send %d", totalBytesToSend);

				//Send data stats from AC thread to monitor client over unix socket
				nbytes = sendto(UnixSocksArray[WTPIndex].data_stats_sock, msgPtr->msg, pDataLen, 0,
						(struct sockaddr *) &(UnixSocksArray[WTPIndex].servaddr),
						sizeof(UnixSocksArray[WTPIndex].servaddr));
				if (nbytes < 0) {
					CWDebugLog("Error sending data over socket");
					perror("send error");
					return CW_FALSE;
				}

			}
		}

		return CW_TRUE;
	}

	if (!(CWACParseGenericRunMessage(WTPIndex, msgPtr, &controlVal))) {
		/* Two possible errors: WRONG_ARG and INVALID_FORMAT
		 * In the second case we have an unexpected response: ignore the
		 * message and log the event.
		 */
		return CW_FALSE;
	}

	switch (controlVal.messageTypeValue) {
	case CW_MSG_TYPE_VALUE_CONFIGURE_UPDATE_RESPONSE: {
		CWProtocolResultCode resultCode;
		/*Update 2009:
		 Store Protocol specific response data*/
		CWProtocolVendorSpecificValues* protocolValues = NULL;

		if (!(CWParseConfigurationUpdateResponseMessage(msgPtr, controlVal.msgElemsLen,
				&resultCode, &protocolValues)))
			return CW_FALSE;

		CWACStopRetransmission(WTPIndex);

		if (timerSet) {
			if (!CWRestartNeighborDeadTimer(WTPIndex)) {
				CWDebugLog("CWRestartNeighborDeadTimer returned false");
				CWCloseThread();
			}
		} else {
			if (!CWStartNeighborDeadTimer(WTPIndex)) {
				CWDebugLog("CWStartNeighborDeadTimer returned false");
				CWCloseThread();
			}
		}

		//CWSaveConfigurationUpdateResponseMessage(resultCode, WTPIndex, protocolValues);

		if (resultCode == CW_PROTOCOL_SUCCESS) {
			CWDebugLog("Result Success for Configuration update!!");
			//gWTPs[WTPIndex].isRequestClose = CW_TRUE;
			//CWSignalThreadCondition(&gWTPs[WTPIndex].interfaceWait);
		}

		/*if (gWTPs[WTPIndex].interfaceCommandProgress == CW_TRUE) {
		 CWThreadMutexLock(&gWTPs[WTPIndex].interfaceMutex);
		 gWTPs[WTPIndex].interfaceResult = 1;
		 gWTPs[WTPIndex].interfaceCommandProgress = CW_FALSE;
		 CWSignalThreadCondition(&gWTPs[WTPIndex].interfaceComplete);

		 CWThreadMutexUnlock(&gWTPs[WTPIndex].interfaceMutex);
		 }*/

		break;
	}
	case CW_MSG_TYPE_VALUE_CHANGE_STATE_EVENT_REQUEST: {
		CWProtocolChangeStateEventRequestValues *valuesPtr;

		if (!(CWParseChangeStateEventRequestMessage2(msgPtr, controlVal.msgElemsLen, &valuesPtr)))
			return CW_FALSE;
		if (timerSet) {
			if (!CWRestartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		} else {
			if (!CWStartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		}
		if (!(CWSaveChangeStateEventRequestMessage(valuesPtr, &(gWTPs[WTPIndex].WTPProtocolManager))))
			return CW_FALSE;
		if (!(CWAssembleChangeStateEventResponse(&messages, &messagesCount,
				gWTPs[WTPIndex].pathMTU, controlVal.seqNum)))
			return CW_FALSE;

		toSend = CW_TRUE;
		break;
	}
	case CW_MSG_TYPE_VALUE_ECHO_REQUEST: {
		if (!(CWParseEchoRequestMessage(msgPtr, controlVal.msgElemsLen)))
			return CW_FALSE;
		if (timerSet) {
			if (!CWRestartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		} else {
			if (!CWStartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		}

		if (!(CWAssembleEchoResponse(&messages, &messagesCount, gWTPs[WTPIndex].pathMTU,
				controlVal.seqNum)))
			return CW_FALSE;

		toSend = CW_TRUE;
		break;
	}
	case CW_MSG_TYPE_VALUE_STATION_CONFIGURATION_RESPONSE: {
		CWProtocolResultCode resultCode;
		if (!(CWParseStationConfigurationResponseMessage(msgPtr, controlVal.msgElemsLen,
				&resultCode)))
			return CW_FALSE;
		CWACStopRetransmission(WTPIndex);
		if (timerSet) {
			if (!CWRestartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		} else {
			if (!CWStartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		}
		//CWSaveStationConfigurationResponseMessage(resultCode, WTPIndex);  <-- Must be Implemented ????

		break;
	}
	case CW_MSG_TYPE_VALUE_CLEAR_CONFIGURATION_RESPONSE: {
		CWProtocolResultCode resultCode;
		if (!(CWParseClearConfigurationResponseMessage(msgPtr, controlVal.msgElemsLen, &resultCode)))
			return CW_FALSE;
		CWACStopRetransmission(WTPIndex);
		if (timerSet) {
			if (!CWRestartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		} else {
			if (!CWStartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		}

		if (gWTPs[WTPIndex].interfaceCommandProgress == CW_TRUE) {
			CWThreadMutexLock(&gWTPs[WTPIndex].interfaceMutex);

			gWTPs[WTPIndex].interfaceResult = 1;
			gWTPs[WTPIndex].interfaceCommandProgress = CW_FALSE;
			CWSignalThreadCondition(&gWTPs[WTPIndex].interfaceComplete);

			CWThreadMutexUnlock(&gWTPs[WTPIndex].interfaceMutex);
		}

		break;
	}
	case CW_MSG_TYPE_VALUE_DATA_TRANSFER_REQUEST: {
		CWProtocolWTPDataTransferRequestValues valuesPtr;

		if (!(CWParseWTPDataTransferRequestMessage(msgPtr, controlVal.msgElemsLen, &valuesPtr)))
			return CW_FALSE;
		if (timerSet) {
			if (!CWRestartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		} else {
			if (!CWStartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		}
		if (!(CWAssembleWTPDataTransferResponse(&messages, &messagesCount, gWTPs[WTPIndex].pathMTU,
				controlVal.seqNum)))
			return CW_FALSE;
		toSend = CW_TRUE;
		break;
	}
	case CW_MSG_TYPE_VALUE_WTP_EVENT_REQUEST: {
		CWProtocolWTPEventRequestValues valuesPtr;

		if (!(CWParseWTPEventRequestMessage(msgPtr, controlVal.msgElemsLen, &valuesPtr)))
			return CW_FALSE;
		if (timerSet) {
			if (!CWRestartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		} else {
			if (!CWStartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		}
		if (!(CWSaveWTPEventRequestMessage(&valuesPtr, &(gWTPs[WTPIndex].WTPProtocolManager))))
			return CW_FALSE;

		if (!(CWAssembleWTPEventResponse(&messages, &messagesCount, gWTPs[WTPIndex].pathMTU,
				controlVal.seqNum)))
			return CW_FALSE;

		toSend = CW_TRUE;
		break;
	}
	default:
		/*
		 * We have an unexpected request and we have to send
		 * a corresponding response containing a failure result code
		 */
		CWLog("--> Not valid Request in Run State... we send a failure Response");
		if (timerSet) {
			if (!CWRestartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		} else {
			if (!CWStartNeighborDeadTimer(WTPIndex)) {
				CWCloseThread();
			}
		}
		if (!(CWAssembleUnrecognizedMessageResponse(&messages, &messagesCount,
				gWTPs[WTPIndex].pathMTU, controlVal.seqNum, controlVal.messageTypeValue + 1)))
			return CW_FALSE;

		toSend = CW_TRUE;
		/*return CWErrorRaise(CW_ERROR_INVALID_FORMAT, "Message not valid in Run State");*/
	}
	if (toSend) {
		int i;
		CWDebugLog("There is something so send...");

		if (messages == NULL)
			return CWErrorRaise(CW_ERROR_WRONG_ARG, NULL);

		for (i = 0; i < messagesCount; i++) {
#ifdef CW_NO_DTLS
			if(!CWNetworkSendUnsafeUnconnected(gWTPs[WTPIndex].socket,
							&gWTPs[WTPIndex].address,
							messages[i].msg,
							messages[i].offset) ) {
#else
			if (!(CWSecuritySend(gWTPs[WTPIndex].session, messages[i].msg, messages[i].offset))) {
#endif
				CWFreeMessageFragments(messages, messagesCount);
				CW_FREE_OBJECT(messages);
				return CW_FALSE;
			}
		}
		CWFreeMessageFragments(messages, messagesCount);
		CW_FREE_OBJECT(messages);
	}
	gWTPs[WTPIndex].currentState = CW_ENTER_RUN;
	gWTPs[WTPIndex].subState = CW_WAITING_REQUEST;

	CWDebugLog("Coming out of ACEnterRun..");

	return CW_TRUE;
}

CWBool CWACParseGenericRunMessage(int WTPIndex, CWProtocolMessage *msg,
		CWControlHeaderValues* controlVal) {

	if (msg == NULL || controlVal == NULL)
		return CWErrorRaise(CW_ERROR_WRONG_ARG, NULL);

	if (!(CWParseControlHeader(msg, controlVal)))
		/* will be handled by the caller */
		return CW_FALSE;

	/* skip timestamp */
	controlVal->msgElemsLen -= CW_CONTROL_HEADER_OFFSET_FOR_MSG_ELEMS;

	/* Check if it is a request */
	if (controlVal->messageTypeValue % 2 == 1) {

		return CW_TRUE;
	}

	if ((gWTPs[WTPIndex].responseSeqNum != controlVal->seqNum) || (gWTPs[WTPIndex].responseType
			!= controlVal->messageTypeValue)) {

		CWDebugLog("gWTPs: %d\n", gWTPs[WTPIndex].responseSeqNum);
		CWDebugLog("controlVal: %d\n", controlVal->seqNum);
		CWErrorRaise(CW_ERROR_INVALID_FORMAT, "Seq Num or Msg Type not valid!");
		return CW_FALSE;
	}

	return CW_TRUE;
}

/*Update 2009:
 Added vendValues to include a response payload (to pass response data)*/
CWBool CWParseConfigurationUpdateResponseMessage(CWProtocolMessage* msgPtr, int len,
		CWProtocolResultCode* resultCode, CWProtocolVendorSpecificValues** vendValues) {

	int offsetTillMessages;

	if (msgPtr == NULL || resultCode == NULL)
		return CWErrorRaise(CW_ERROR_WRONG_ARG, NULL);
	if ((msgPtr->msg) == NULL)
		return CWErrorRaise(CW_ERROR_WRONG_ARG, NULL);

	offsetTillMessages = msgPtr->offset;

	CWLog("Parsing Configuration Update Response...");

	/* parse message elements */
	while ((msgPtr->offset - offsetTillMessages) < len) {

		unsigned short int elemType = 0;
		unsigned short int elemLen = 0;

		CWParseFormatMsgElem(msgPtr, &elemType, &elemLen);

		switch (elemType) {
		case CW_MSG_ELEMENT_RESULT_CODE_CW_TYPE:
			*resultCode = CWProtocolRetrieve32(msgPtr);
			break;

			/*Update 2009:
			 Added case to implement conf update response with payload*/
		case CW_MSG_ELEMENT_RESULT_CODE_CW_TYPE_WITH_PAYLOAD: {
			int payloadSize = 0;
			CW_CREATE_OBJECT_ERR(*vendValues, CWProtocolVendorSpecificValues, return CWErrorRaise(CW_ERROR_OUT_OF_MEMORY, NULL););

			*resultCode = CWProtocolRetrieve32(msgPtr);

			if (CWProtocolRetrieve16(msgPtr) != CW_MSG_ELEMENT_VENDOR_SPEC_PAYLOAD_CW_TYPE)
				/*For now, we only have UCI payloads, so we will accept only vendor payloads for protocol data*/
				return CWErrorRaise(CW_ERROR_INVALID_FORMAT, "Unrecognized Message Element in Configuration Update Response");

			(*vendValues)->vendorPayloadType = CWProtocolRetrieve16(msgPtr);

			switch ((*vendValues)->vendorPayloadType) {
			case CW_MSG_ELEMENT_VENDOR_SPEC_PAYLOAD_UCI:
				payloadSize = CWProtocolRetrieve32(msgPtr);
				if (payloadSize != 0) {
					(*vendValues)->payload = (void *) CWProtocolRetrieveStr(msgPtr, payloadSize);
				} else
					(*vendValues)->payload = NULL;
				break;
			case CW_MSG_ELEMENT_VENDOR_SPEC_PAYLOAD_WUM:
				payloadSize = CWProtocolRetrieve32(msgPtr);

				if (payloadSize <= 0) {
					/* Payload can't be zero here,
					 * at least the message type must be specified */
					return CWErrorRaise(CW_ERROR_INVALID_FORMAT, "Unrecognized Message Element in Configuration Update Response");
				}
				(*vendValues)->payload = (void *) CWProtocolRetrieveRawBytes(msgPtr, payloadSize);
				break;
			default:
				return CWErrorRaise(CW_ERROR_INVALID_FORMAT, "Unrecognized Message Element in Configuration Update Response");
				break;
			}
		}
			break;
		default:
			return CWErrorRaise(CW_ERROR_INVALID_FORMAT, "Unrecognized Message Element in Configuration Update Response");
			break;
		}
	}
Пример #11
0
int main (int argc, const char * argv[]) {
	

	/* Daemon Mode */

	pid_t pid;
	
	if (argc <= 1)
		printf("Usage: WTP working_path\n");

	if ((pid = fork()) < 0)
		exit(1);
	else if (pid != 0)
		exit(0);
	else {
		setsid();
		if (chdir(argv[1]) != 0){
			printf("chdir Faile\n");
			exit(1);
		}
		fclose(stdout);
	}	

	
	CWStateTransition nextState = CW_ENTER_DISCOVERY;
	CWLogInitFile(WTP_LOG_FILE_NAME);

#ifndef CW_SINGLE_THREAD
	CWDebugLog("Use Threads");
#else
	CWDebugLog("Don't Use Threads");
#endif
	CWErrorHandlingInitLib();
	if(!CWParseSettingsFile()){
		CWLog("Can't start WTP");
		exit(1);
	}

	/* Capwap receive packets list */
	if (!CWErr(CWCreateSafeList(&gPacketReceiveList)))
	{
		CWLog("Can't start WTP");
		exit(1);
	}

	/* Capwap receive frame list */
	if (!CWErr(CWCreateSafeList(&gFrameList)))
	{
		CWLog("Can't start WTP");
		exit(1);
	}

	CWCreateThreadMutex(&gInterfaceMutex);
	CWSetMutexSafeList(gPacketReceiveList, &gInterfaceMutex);
	CWSetMutexSafeList(gFrameList, &gInterfaceMutex);
	CWCreateThreadCondition(&gInterfaceWait);
	CWSetConditionSafeList(gPacketReceiveList, &gInterfaceWait);
	CWSetConditionSafeList(gFrameList, &gInterfaceWait);

	CWLog("Starting WTP...");
	
	CWRandomInitLib();

	CWThreadSetSignals(SIG_BLOCK, 1, SIGALRM);

	if (timer_init() == 0) {
		CWLog("Can't init timer module");
		exit(1);
	}


#ifdef CW_NO_DTLS
	if( !CWErr(CWWTPLoadConfiguration()) ) {
#else
	if( !CWErr(CWSecurityInitLib())	|| !CWErr(CWWTPLoadConfiguration()) ) {
#endif
		CWLog("Can't start WTP");
		exit(1);
	}

	CWDebugLog("Init WTP Radio Info");
	if(!CWWTPInitConfiguration())
	{
		CWLog("Error Init Configuration");
		exit(1);
	}

#ifdef SOFTMAC
	CWThread thread_ipc_with_wtp_hostapd;
	if(!CWErr(CWCreateThread(&thread_ipc_with_wtp_hostapd, CWWTPThread_read_data_from_hostapd, NULL))) {
		CWLog("Error starting Thread that receive command and 802.11 frame from hostapd (WTP side)");
		exit(1);
	}
#endif


	CWThread thread_receiveFrame;
	if(!CWErr(CWCreateThread(&thread_receiveFrame, CWWTPReceiveFrame, NULL))) {
		CWLog("Error starting Thread that receive binding frame");
		exit(1);
	}


	CWThread thread_receiveStats;
	if(!CWErr(CWCreateThread(&thread_receiveStats, CWWTPReceiveStats, NULL))) {
		CWLog("Error starting Thread that receive stats on monitoring interface");
		exit(1);
	}

	/****************************************
	 * 2009 Update:							*
	 *				Spawn Frequency Stats	*
	 *				Receiver Thread			*
	 ****************************************/

	CWThread thread_receiveFreqStats;
	if(!CWErr(CWCreateThread(&thread_receiveFreqStats, CWWTPReceiveFreqStats, NULL))) {
		CWLog("Error starting Thread that receive frequency stats on monitoring interface");
		exit(1);
	}

	/* if AC address is given jump Discovery and use this address for Joining */
	if(gWTPForceACAddress != NULL)	nextState = CW_ENTER_JOIN;

	/* start CAPWAP state machine */	
	CW_REPEAT_FOREVER {
		switch(nextState) {
			case CW_ENTER_DISCOVERY:
				nextState = CWWTPEnterDiscovery();
				break;
			case CW_ENTER_SULKING:
				nextState = CWWTPEnterSulking();
				break;
			case CW_ENTER_JOIN:
				nextState = CWWTPEnterJoin();
				break;
			case CW_ENTER_CONFIGURE:
				nextState = CWWTPEnterConfigure();
				break;	
			case CW_ENTER_DATA_CHECK:
				nextState = CWWTPEnterDataCheck();
				break;	
			case CW_ENTER_RUN:
				nextState = CWWTPEnterRun();
				break;
			case CW_ENTER_RESET:
				/*
				 * CWStopHeartbeatTimer();
				 * CWStopNeighborDeadTimer();
				 * CWNetworkCloseSocket(gWTPSocket);
				 * CWSecurityDestroySession(gWTPSession);
				 * CWSecurityDestroyContext(gWTPSecurityContext);
				 * gWTPSecurityContext = NULL;
				 * gWTPSession = NULL;
				 */
				nextState = CW_ENTER_DISCOVERY;
				break;
			case CW_QUIT:
				CWWTPDestroy();
				return 0;
		}
	}
}

__inline__ unsigned int CWGetSeqNum() {
	static unsigned int seqNum = 0;
	
	if (seqNum==CW_MAX_SEQ_NUM) seqNum=0;
	else seqNum++;
	return seqNum;
}

__inline__ int CWGetFragmentID() {
	static int fragID = 0;
	return fragID++;
}


/* 
 * Parses config file and inits WTP configuration.
 */
CWBool CWWTPLoadConfiguration() {
	int i;
	
	CWLog("WTP Loads Configuration");
	
	/* get saved preferences */
	if(!CWErr(CWParseConfigFile())) {
		CWLog("Can't Read Config File");
		exit(1);
	}
	
	if(gCWACCount == 0) 
		return CWErrorRaise(CW_ERROR_NEED_RESOURCE, "No AC Configured");
	
	CW_CREATE_ARRAY_ERR(gCWACList, 
			    gCWACCount,
			    CWACDescriptor,
			    return CWErrorRaise(CW_ERROR_OUT_OF_MEMORY, NULL););

	for(i = 0; i < gCWACCount; i++) {

		CWDebugLog("Init Configuration for AC at %s", gCWACAddresses[i]);
		CW_CREATE_STRING_FROM_STRING_ERR(gCWACList[i].address, gCWACAddresses[i],
						 return CWErrorRaise(CW_ERROR_OUT_OF_MEMORY, NULL););
	}
Пример #12
0
CWBool CWWTPSendAcknowledgedPacket(int seqNum, 
				   CWList msgElemlist,
				   CWBool (assembleFunc)(CWProtocolMessage **, int *, int, int, CWList),
				   CWBool (parseFunc)(char*, int, int, void*), 
				   CWBool (saveFunc)(void*),
				   void *valuesPtr) {

	CWProtocolMessage *messages = NULL;
	CWProtocolMessage msg;
	int fragmentsNum = 0, i;

	struct timespec timewait;
	
	int gTimeToSleep = gCWRetransmitTimer;
	int gMaxTimeToSleep = CW_ECHO_INTERVAL_DEFAULT/2;

	msg.msg = NULL;
	
	if(!(assembleFunc(&messages, 
			  &fragmentsNum, 
			  gWTPPathMTU, 
			  seqNum, 
			  msgElemlist))) {

		goto cw_failure;
	}
	
	gWTPRetransmissionCount= 0;
	
	while(gWTPRetransmissionCount < gCWMaxRetransmit) 
	{
		CWDebugLog("Transmission Num:%d", gWTPRetransmissionCount);
		for(i = 0; i < fragmentsNum; i++) 
		{
#ifdef CW_NO_DTLS
			if(!CWNetworkSendUnsafeConnected(gWTPSocket, 
							 messages[i].msg,
							 messages[i].offset))
#else
			if(!CWSecuritySend(gWTPSession,
					   messages[i].msg, 
					   messages[i].offset))
#endif
			{
				CWDebugLog("Failure sending Request");
				goto cw_failure;
			}
		}
		
		timewait.tv_sec = time(0) + gTimeToSleep;
		timewait.tv_nsec = 0;

		CW_REPEAT_FOREVER 
		{
			CWThreadMutexLock(&gInterfaceMutex);

			if (CWGetCountElementFromSafeList(gPacketReceiveList) > 0)
				CWErrorRaise(CW_ERROR_SUCCESS, NULL);
			else {
				if (CWErr(CWWaitThreadConditionTimeout(&gInterfaceWait, &gInterfaceMutex, &timewait)))
					CWErrorRaise(CW_ERROR_SUCCESS, NULL);
			}

			CWThreadMutexUnlock(&gInterfaceMutex);

			switch(CWErrorGetLastErrorCode()) {

				case CW_ERROR_TIME_EXPIRED:
				{
					gWTPRetransmissionCount++;
					goto cw_continue_external_loop;
					break;
				}

				case CW_ERROR_SUCCESS:
				{
					/* there's something to read */
					if(!(CWReceiveMessage(&msg))) 
					{
						CW_FREE_PROTOCOL_MESSAGE(msg);
						CWDebugLog("Failure Receiving Response");
						goto cw_failure;
					}
					
					if(!(parseFunc(msg.msg, msg.offset, seqNum, valuesPtr))) 
					{
						if(CWErrorGetLastErrorCode() != CW_ERROR_INVALID_FORMAT) {

							CW_FREE_PROTOCOL_MESSAGE(msg);
							CWDebugLog("Failure Parsing Response");
							goto cw_failure;
						}
						else {
							CWErrorHandleLast();
							{ 
								gWTPRetransmissionCount++;
								goto cw_continue_external_loop;
							}
							break;
						}
					}
					
					if((saveFunc(valuesPtr))) {

						goto cw_success;
					} 
					else {
						if(CWErrorGetLastErrorCode() != CW_ERROR_INVALID_FORMAT) {
							CW_FREE_PROTOCOL_MESSAGE(msg);
							CWDebugLog("Failure Saving Response");
							goto cw_failure;
						} 
					}
					break;
				}

				case CW_ERROR_INTERRUPTED: 
				{
					gWTPRetransmissionCount++;
					goto cw_continue_external_loop;
					break;
				}	
				default:
				{
					CWErrorHandleLast();
					CWDebugLog("Failure");
					goto cw_failure;
					break;
				}
			}
		}
		
		cw_continue_external_loop:
			CWDebugLog("Retransmission time is over");
			
			gTimeToSleep<<=1;
			if ( gTimeToSleep > gMaxTimeToSleep ) gTimeToSleep = gMaxTimeToSleep;
	}

	/* too many retransmissions */
	return CWErrorRaise(CW_ERROR_NEED_RESOURCE, "Peer Dead");
	
cw_success:	
	for(i = 0; i < fragmentsNum; i++) {
		CW_FREE_PROTOCOL_MESSAGE(messages[i]);
	}
	
	CW_FREE_OBJECT(messages);
	CW_FREE_PROTOCOL_MESSAGE(msg);
	
	return CW_TRUE;
	
cw_failure:
	if(messages != NULL) {
		for(i = 0; i < fragmentsNum; i++) {
			CW_FREE_PROTOCOL_MESSAGE(messages[i]);
		}
		CW_FREE_OBJECT(messages);
	}
	CWDebugLog("Failure");
	return CW_FALSE;
}
Пример #13
0
void CWACInit() {
	int i;
	CWNetworkLev4Address *addresses = NULL;
	struct sockaddr_in *IPv4Addresses = NULL;
	
	CWLogInitFile(AC_LOG_FILE_NAME);
	
	#ifndef CW_SINGLE_THREAD
		CWDebugLog("Use Threads");
	#else
		CWDebugLog("Don't Use Threads");
	#endif
	
	CWErrorHandlingInitLib();
	
	if(!CWParseSettingsFile())
	{
		CWLog("Can't start AC");
		exit(1);
	}

	CWLog("Starting AC");

	CWThreadSetSignals(SIG_BLOCK, 1, SIGALRM);
	if (timer_init() == 0) {
		CWLog("Can't init timer module");
		exit(1);
	}

	if(!CWErr(CWParseConfigFile()) ||
#ifndef CW_NO_DTLS
	   !CWErr(CWSecurityInitLib()) ||
#endif
	   !CWErr(CWNetworkInitSocketServerMultiHomed(&gACSocket, CW_CONTROL_PORT, gMulticastGroups, gMulticastGroupsCount)) ||
	   !CWErr(CWNetworkGetInterfaceAddresses(&gACSocket, &addresses, &IPv4Addresses)) ||
	   !CWErr(CWCreateThreadMutex(&gWTPsMutex)) ||
	   !CWErr(CWCreateThreadMutex(&gActiveWTPsMutex))) {

		/* error starting */
		CWLog("Can't start AC");
		exit(1);
	}

#ifndef CW_NO_DTLS
	if(gACDescriptorSecurity == CW_X509_CERTIFICATE) {

		if(!CWErr(CWSecurityInitContext(&gACSecurityContext,
						"root.pem",
						"server.pem",
						"prova",
						CW_FALSE,
						CWACSemPostForOpenSSLHack))) {

			CWLog("Can't start AC");
			exit(1);
		}
	} else { /* preshared */
		if(!CWErr(CWSecurityInitContext(&gACSecurityContext,
						NULL,
						NULL,
						NULL,
						CW_FALSE,
						CWACSemPostForOpenSSLHack))) {
			CWLog("Can't start AC");
			exit(1);
		}
	}
#endif
	CW_FREE_OBJECTS_ARRAY(gMulticastGroups, gMulticastGroupsCount);

	for(i = 0; i < CW_MAX_WTP; i++) {
		gWTPs[i].isNotFree = CW_FALSE;
	}

	/* store network interface's addresses */
	gInterfacesCount = CWNetworkCountInterfaceAddresses(&gACSocket);
	CWLog("Found %d Network Interface(s)", gInterfacesCount);
	
	if (gInterfacesCount<=0){
		CWLog("Can't start AC");
		exit(1);
	}

	CW_CREATE_ARRAY_ERR(gInterfaces, 
			    gInterfacesCount,
			    CWProtocolNetworkInterface,
			    CWLog("Out of Memory"); return;);