Ejemplo n.º 1
0
std::shared_ptr<Image> Data::load_image(const UString &path)
{
	// Use an uppercase version of the path for the cache key
	UString cacheKey = path.toUpper();
	std::shared_ptr<Image> img = this->imageCache[cacheKey].lock();
	if (img)
	{
		return img;
	}

	if (path.substr(0, 4) == "RAW:")
	{
		auto splitString = path.split(':');
		// RAW:PATH:WIDTH:HEIGHT
		if (splitString.size() != 4 && splitString.size() != 5)
		{
			LogError("Invalid RAW resource string: \"%s\"", path.c_str());
			return nullptr;
		}

		auto pImg =
		    RawImage::load(*this, splitString[1], Vec2<int>{Strings::ToInteger(splitString[2]),
		                                                    Strings::ToInteger(splitString[3])});
		if (!pImg)
		{
			LogError("Failed to load RAW image: \"%s\"", path.c_str());
			return nullptr;
		}
		if (splitString.size() == 5)
		{
			auto pal = this->load_palette(splitString[4]);
			if (!pal)
			{
				LogError("Failed to load palette for RAW image: \"%s\"", path.c_str());
				return nullptr;
			}
			img = pImg->toRGBImage(pal);
		}
		else
		{
			img = pImg;
		}
	}
	else if (path.substr(0, 4) == "PCK:")
	{
		auto splitString = path.split(':');
		if (splitString.size() != 3 && splitString.size() != 4 && splitString.size() != 5)
		{
			LogError("Invalid PCK resource string: \"%s\"", path.c_str());
			return nullptr;
		}
		auto imageSet =
		    this->load_image_set(splitString[0] + ":" + splitString[1] + ":" + splitString[2]);
		if (!imageSet)
		{
			return nullptr;
		}
		// PCK resources come in the format:
		//"PCK:PCKFILE:TABFILE:INDEX"
		// or
		//"PCK:PCKFILE:TABFILE:INDEX:PALETTE" if we want them already in rgb space
		switch (splitString.size())
		{
			case 4:
			{
				img = imageSet->images[Strings::ToInteger(splitString[3])];
				break;
			}
			case 5:
			{
				std::shared_ptr<PaletteImage> pImg =
				    std::dynamic_pointer_cast<PaletteImage>(this->load_image(
				        "PCK:" + splitString[1] + ":" + splitString[2] + ":" + splitString[3]));
				assert(pImg);
				auto pal = this->load_palette(splitString[4]);
				assert(pal);
				img = pImg->toRGBImage(pal);
				break;
			}
			default:
				LogError("Invalid PCK resource string \"%s\"", path.c_str());
				return nullptr;
		}
	}
	else if (path.substr(0, 9) == "PCKSTRAT:")
	{
		auto splitString = path.split(':');
		if (splitString.size() != 3 && splitString.size() != 4 && splitString.size() != 5)
		{
			LogError("Invalid PCKSTRAT resource string: \"%s\"", path.c_str());
			return nullptr;
		}
		auto imageSet =
		    this->load_image_set(splitString[0] + ":" + splitString[1] + ":" + splitString[2]);
		if (!imageSet)
		{
			return nullptr;
		}
		// PCK resources come in the format:
		//"PCK:PCKFILE:TABFILE:INDEX"
		// or
		//"PCK:PCKFILE:TABFILE:INDEX:PALETTE" if we want them already in rgb space
		switch (splitString.size())
		{
			case 4:
			{
				img = imageSet->images[Strings::ToInteger(splitString[3])];
				break;
			}
			case 5:
			{
				std::shared_ptr<PaletteImage> pImg = std::dynamic_pointer_cast<PaletteImage>(
				    this->load_image("PCKSTRAT:" + splitString[1] + ":" + splitString[2] + ":" +
				                     splitString[3]));
				assert(pImg);
				auto pal = this->load_palette(splitString[4]);
				assert(pal);
				img = pImg->toRGBImage(pal);
				break;
			}
			default:
				LogError("Invalid PCKSTRAT resource string \"%s\"", path.c_str());
				return nullptr;
		}
	}
	else
	{
		for (auto &loader : imageLoaders)
		{
			img = loader->loadImage(GetCorrectCaseFilename(path));
			if (img)
			{
				break;
			}
		}
		if (!img)
		{
			LogInfo("Failed to load image \"%s\"", path.c_str());
			return nullptr;
		}
	}

	this->pinnedImages.push(img);
	this->pinnedImages.pop();

	this->imageCache[cacheKey] = img;
	return img;
}
Ejemplo n.º 2
0
_Use_decl_annotations_
NDIS_STATUS
FilterRestart(
    NDIS_HANDLE                     FilterModuleContext,
    PNDIS_FILTER_RESTART_PARAMETERS RestartParameters
    )
/*++

Routine Description:

    Filter restart routine.
    Start the datapath - begin sending and receiving NBLs.

Arguments:

    FilterModuleContext - pointer to the filter context stucture.
    RestartParameters   - additional information about the restart operation.

Return Value:

    NDIS_STATUS_SUCCESS: if filter restarts successfully
    NDIS_STATUS_XXX: Otherwise.

--*/
{
    NTSTATUS            NtStatus = STATUS_SUCCESS;
    NDIS_STATUS         NdisStatus = NDIS_STATUS_SUCCESS;
    PMS_FILTER          pFilter = (PMS_FILTER)FilterModuleContext;
    PVOID               SpinelCapsDataBuffer = NULL;
    const uint8_t*      SpinelCapsPtr = NULL;
    spinel_size_t       SpinelCapsLen = 0;
    NL_INTERFACE_KEY    key = {0};
    NL_INTERFACE_RW     interfaceRw;
    ULONG               ThreadOnHost = TRUE;

    PNDIS_RESTART_GENERAL_ATTRIBUTES NdisGeneralAttributes;
    PNDIS_RESTART_ATTRIBUTES         NdisRestartAttributes;

    LogFuncEntryMsg(DRIVER_DEFAULT, "Filter: %p", FilterModuleContext);

    NT_ASSERT(pFilter->State == FilterPaused);

    NdisRestartAttributes = RestartParameters->RestartAttributes;

    //
    // If NdisRestartAttributes is not NULL, then the filter can modify generic 
    // attributes and add new media specific info attributes at the end. 
    // Otherwise, if NdisRestartAttributes is NULL, the filter should not try to 
    // modify/add attributes.
    //
    if (NdisRestartAttributes != NULL)
    {
        ASSERT(NdisRestartAttributes->Oid == OID_GEN_MINIPORT_RESTART_ATTRIBUTES);

        NdisGeneralAttributes = (PNDIS_RESTART_GENERAL_ATTRIBUTES)NdisRestartAttributes->Data;

        //
        // Check to see if we need to change any attributes. For example, the
        // driver can change the current MAC address here. Or the driver can add
        // media specific info attributes.
        //
        NdisGeneralAttributes->LookaheadSize = 128;
    }

    // Initialize the Spinel command processing
    NdisStatus = otLwfCmdInitialize(pFilter);
    if (NdisStatus != NDIS_STATUS_SUCCESS)
    {
        LogError(DRIVER_DEFAULT, "otLwfCmdInitialize failed, %!NDIS_STATUS!", NdisStatus);
        goto exit;
    }

    // Query the device capabilities
    NtStatus = otLwfCmdGetProp(pFilter, SpinelCapsDataBuffer, SPINEL_PROP_CAPS, SPINEL_DATATYPE_DATA_S, &SpinelCapsPtr, &SpinelCapsLen);
    if (!NT_SUCCESS(NtStatus))
    {
        NdisStatus = NDIS_STATUS_NOT_SUPPORTED;
        LogError(DRIVER_DEFAULT, "Failed to query SPINEL_PROP_CAPS, %!STATUS!", NtStatus);
        goto exit;
    }

    // Iterate and process returned capabilities
    while (SpinelCapsLen > 0)
    {
        ULONG SpinelCap = 0;
        spinel_ssize_t len = spinel_datatype_unpack(SpinelCapsPtr, SpinelCapsLen, SPINEL_DATATYPE_UINT_PACKED_S, &SpinelCap);
        if (len < 1) break;
        SpinelCapsLen -= (spinel_size_t)len;

        switch (SpinelCap)
        {
        case SPINEL_CAP_MAC_RAW:
            pFilter->DeviceCapabilities |= OTLWF_DEVICE_CAP_RADIO;
            pFilter->DeviceCapabilities |= OTLWF_DEVICE_CAP_RADIO_ACK_TIMEOUT;
            pFilter->DeviceCapabilities |= OTLWF_DEVICE_CAP_RADIO_ENERGY_SCAN;
            break;
        case SPINEL_CAP_NET_THREAD_1_0:
            pFilter->DeviceCapabilities |= OTLWF_DEVICE_CAP_THREAD_1_0;
            break;
        default:
            break;
        }
    }

    // Set the state indicating where we should be running the Thread logic (Host or Device).
    if (!NT_SUCCESS(GetRegDWORDValue(pFilter, L"RunOnHost", &ThreadOnHost)))
    {
        // Default to running on the host if the key isn't present
        ThreadOnHost = TRUE;
        SetRegDWORDValue(pFilter, L"RunOnHost", ThreadOnHost);
    }

    LogInfo(DRIVER_DEFAULT, "Filter: %p initializing ThreadOnHost=%d", FilterModuleContext, ThreadOnHost);

    // Initialize the processing logic
    if (ThreadOnHost)
    {
        // Ensure the device has the capabilities to support raw radio commands
        if ((pFilter->DeviceCapabilities & OTLWF_DEVICE_CAP_RADIO) == 0)
        {
            LogError(DRIVER_DEFAULT, "Failed to start because device doesn't support raw radio commands");
            NdisStatus = NDIS_STATUS_NOT_SUPPORTED;
            goto exit;
        }

        pFilter->DeviceStatus = OTLWF_DEVICE_STATUS_RADIO_MODE;
        NtStatus = otLwfInitializeThreadMode(pFilter);
        if (!NT_SUCCESS(NtStatus))
        {
            LogError(DRIVER_DEFAULT, "otLwfInitializeThreadMode failed, %!STATUS!", NtStatus);
            NdisStatus = NDIS_STATUS_FAILURE;
            pFilter->DeviceStatus = OTLWF_DEVICE_STATUS_UNINTIALIZED;
            goto exit;
        }
    }
    else
    {
        // Ensure the device has the capabilities to support Thread commands
        if ((pFilter->DeviceCapabilities & OTLWF_DEVICE_CAP_THREAD_1_0) == 0)
        {
            LogError(DRIVER_DEFAULT, "Failed to start because device doesn't support thread commands");
            NdisStatus = NDIS_STATUS_NOT_SUPPORTED;
            goto exit;
        }

        pFilter->DeviceStatus = OTLWF_DEVICE_STATUS_THREAD_MODE;
        NtStatus = otLwfTunInitialize(pFilter);
        if (!NT_SUCCESS(NtStatus))
        {
            LogError(DRIVER_DEFAULT, "otLwfInitializeTunnelMode failed, %!STATUS!", NtStatus);
            NdisStatus = NDIS_STATUS_FAILURE;
            pFilter->DeviceStatus = OTLWF_DEVICE_STATUS_UNINTIALIZED;
            goto exit;
        }
    }

    //
    // Disable DAD and Neighbor advertisements
    //
    key.Luid = pFilter->InterfaceLuid;
    NlInitializeInterfaceRw(&interfaceRw);
    interfaceRw.DadTransmits = 0;
    interfaceRw.SendUnsolicitedNeighborAdvertisementOnDad = FALSE;
  
    NtStatus =
        NsiSetAllParameters(
            NsiActive,
            NsiSetDefault,
            &NPI_MS_IPV6_MODULEID,
            NlInterfaceObject,
            &key,
            sizeof(key),
            &interfaceRw,
            sizeof(interfaceRw));
    if (!NT_SUCCESS(NtStatus))
    {
        LogError(DRIVER_DEFAULT, "NsiSetAllParameters (NlInterfaceObject) failed, %!STATUS!", NtStatus);
        NdisStatus = NDIS_STATUS_FAILURE;
        goto exit;
    }

    //
    // Enable the external references to the filter
    //
    ExReInitializeRundownProtection(&pFilter->ExternalRefs);

    //
    // If everything is OK, set the filter in running state.
    //
    pFilter->State = FilterRunning; // when successful
    otLwfNotifyDeviceAvailabilityChange(pFilter, TRUE);
    LogInfo(DRIVER_DEFAULT, "Interface %!GUID! arrival, Filter=%p", &pFilter->InterfaceGuid, pFilter);

exit:

    //
    // Ensure the state is Paused if restart failed.
    //
    if (NdisStatus != NDIS_STATUS_SUCCESS)
    {
        pFilter->State = FilterPaused;

        if (pFilter->DeviceStatus == OTLWF_DEVICE_STATUS_RADIO_MODE)
        {
            otLwfUninitializeThreadMode(pFilter);
        }
        else if (pFilter->DeviceStatus == OTLWF_DEVICE_STATUS_THREAD_MODE)
        {
            otLwfTunUninitialize(pFilter);
        }

        pFilter->DeviceStatus = OTLWF_DEVICE_STATUS_UNINTIALIZED;

        // Clean up Spinel command processing
        otLwfCmdUninitialize(pFilter);
    }

    // Free the buffer for the capabilities we queried
    if (SpinelCapsDataBuffer != NULL)
    {
        FILTER_FREE_MEM(SpinelCapsDataBuffer);
    }

    LogFuncExitNDIS(DRIVER_DEFAULT, NdisStatus);
    return NdisStatus;
}
Ejemplo n.º 3
0
/**
 * _9p_dispatcher_thread: thread used for RPC dispatching.
 *
 * This function is the main loop for the 9p dispatcher.
 * It never returns because it is an infinite loop.
 *
 * @param Arg (unused)
 *
 * @return Pointer to the result (but this function will mostly loop forever).
 *
 */
void *_9p_dispatcher_thread(void *Arg)
{
	int _9p_socket;
	int rc = 0;
	long int newsock = -1;
	pthread_attr_t attr_thr;
	pthread_t tcp_thrid;

	SetNameFunction("_9p_disp");

	/* Calling dispatcher main loop */
	LogInfo(COMPONENT_9P_DISPATCH, "Entering nfs/rpc dispatcher");

	LogDebug(COMPONENT_9P_DISPATCH, "My pthread id is %p",
		 (caddr_t) pthread_self());

	/* Set up the _9p_socket (trying V6 first, will fall back to V4
	 * if V6 fails).
	 */
	_9p_socket = _9p_create_socket_V6();

	if (_9p_socket == -1) {
		LogFatal(COMPONENT_9P_DISPATCH,
			 "Can't get socket for 9p dispatcher");
	}

	/* Init for thread parameter (mostly for scheduling) */
	if (pthread_attr_init(&attr_thr) != 0)
		LogDebug(COMPONENT_9P_DISPATCH,
			 "can't init pthread's attributes");

	if (pthread_attr_setscope(&attr_thr, PTHREAD_SCOPE_SYSTEM) != 0)
		LogDebug(COMPONENT_9P_DISPATCH, "can't set pthread's scope");

	if (pthread_attr_setdetachstate(&attr_thr,
					PTHREAD_CREATE_DETACHED) != 0)
		LogDebug(COMPONENT_9P_DISPATCH,
			 "can't set pthread's join state");

	LogEvent(COMPONENT_9P_DISPATCH, "9P dispatcher started");

	while (true) {
		newsock = accept(_9p_socket, NULL, NULL);

		if (newsock < 0) {
			LogCrit(COMPONENT_9P_DISPATCH, "accept failed: %d",
				errno);
			continue;
		}

		/* Starting the thread dedicated to signal handling */
		rc = pthread_create(&tcp_thrid, &attr_thr,
				    _9p_socket_thread, (void *)newsock);
		if (rc != 0) {
			LogFatal(COMPONENT_THREAD,
				 "Could not create 9p socket manager thread, error = %d (%s)",
				 errno, strerror(errno));
		}
	}			/* while */

	close(_9p_socket);

	return NULL;
}				/* _9p_dispatcher_thread */
static void printReceiveStatistics(LONGHAUL_RECEIVE_STATISTICS* stats)
{
	LogInfo("Number of Messages: Sent=%lu, Received=%lu; Travel Time (secs): Min=%f, Max=%f, Average=%f",
		stats->numberOfMessagesReceivedByClient, stats->numberOfMessagesReceivedByClient, stats->minMessageTravelTime, stats->maxMessageTravelTime, stats->avgMessageTravelTime);
}
static int sendEventLoop(IOTHUB_CLIENT_HANDLE iotHubClientHandle, LONGHAUL_SEND_TEST_STATE* test_state)
{
	int result = 0;

#ifndef MBED_BUILD_TIMESTAMP
	IOTHUB_TEST_HANDLE iotHubTestHandle;

	if ((iotHubTestHandle = IoTHubTest_Initialize(IoTHubAccount_GetEventHubConnectionString(g_iothubAcctInfo), IoTHubAccount_GetIoTHubConnString(g_iothubAcctInfo), IoTHubAccount_GetDeviceId(g_iothubAcctInfo), IoTHubAccount_GetDeviceKey(g_iothubAcctInfo), IoTHubAccount_GetEventhubListenName(g_iothubAcctInfo), IoTHubAccount_GetEventhubAccessKey(g_iothubAcctInfo), IoTHubAccount_GetSharedAccessSignature(g_iothubAcctInfo), IoTHubAccount_GetEventhubConsumerGroup(g_iothubAcctInfo))) == NULL)
	{
		LogError("Failed initializing the Event Hub test client.");
		result = __LINE__;
	}
	else
	{
		initializeSendStatistics(&test_state->statistics);
#endif
		time_t testInitialTime;

		if ((testInitialTime = time(NULL)) == INDEFINITE_TIME)
		{
			LogError("Failed setting the initial time of the test (time(NULL) failed).");
			result = __LINE__;
		}
		else
		{
			time_t loopIterationStartTimeInSeconds, loopIterationEndTimeInSeconds;
			double loopIterationTotalTime;
			time_t testCurrentTime;

			while (result == 0)
			{
				if ((testCurrentTime = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the current time of the test (time(NULL) failed)");
					result = __LINE__;
					break;
				}
				else if (difftime(testCurrentTime, testInitialTime) > test_state->profile->totalRunTimeInSeconds)
				{
					LogInfo("Test run for the expected duration (%d seconds)", test_state->profile->totalRunTimeInSeconds);
					break;
				}

				if ((loopIterationStartTimeInSeconds = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the initial time of the send/receive loop (time(NULL) failed)");
					result = __LINE__;
					break;
				}

				if (test_state->timeUntilNextSendEventInSeconds <= 0.0)
				{
					EXPECTED_SEND_DATA* sendData;
					IOTHUB_MESSAGE_HANDLE msgHandle;

					if ((sendData = EventData_Create()) == NULL)
					{
						LogError("Failed creating EXPECTED_SEND_DATA.");
						result = __LINE__;
					}
					else
					{
						if ((msgHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)sendData->expectedString, strlen(sendData->expectedString))) == NULL)
						{
							LogError("Failed creating IOTHUB_MESSAGE_HANDLE.");
							result = __LINE__;
						}
						else
						{
							if (IoTHubClient_SendEventAsync(iotHubClientHandle, msgHandle, SendConfirmationCallback, sendData) != IOTHUB_CLIENT_OK)
							{
								LogError("Call to IoTHubClient_SendEventAsync failed.");
								result = __LINE__;
							}
							else
							{
								bool dataWasSent = false;
								time_t beginOperation, nowTime;

								if ((beginOperation = time(NULL)) == INDEFINITE_TIME)
								{
									LogError("Failed setting beginOperation (time(NULL) failed).");
									result = __LINE__;
								}
								else
								{
									do
									{
										if (Lock(sendData->lock) != LOCK_OK)
										{
											LogError("Unable to lock to flag event sent.");
											break;
										}
										else
										{
											if (sendData->dataWasSent)
											{
												dataWasSent = true;
												Unlock(sendData->lock);
												break;
											}
											Unlock(sendData->lock);
										}
										ThreadAPI_Sleep(100);

										if ((nowTime = time(NULL)) == INDEFINITE_TIME)
										{
											LogError("Failed setting nowTime (time(NULL) failed).");
											result = __LINE__;
											break;
										}
									} while (difftime(nowTime, beginOperation) < MAX_CLOUD_TRAVEL_TIME);

									if (!dataWasSent)
									{
										LogError("Failure sending data to IotHub");
										result = __LINE__;
									}
									else
									{
#ifdef MBED_BUILD_TIMESTAMP
										if (verifyEventReceivedByHub(sendData) != 0)
										{
											result = __LINE__;
										}
										else
										{
#else
										if (verifyEventReceivedByHub(sendData, iotHubTestHandle) != 0)
										{
											result = __LINE__;
										}
										else
										{
											computeSendStatistics(&test_state->statistics, sendData);
#endif
											test_state->timeUntilNextSendEventInSeconds = test_state->profile->eventFrequencyInSecs[test_state->sendFrequencyIndex];

											if ((test_state->sendFrequencyIndex + 1) < test_state->profile->numberOfEventFrequencyVariations) test_state->sendFrequencyIndex++;
										}
									}
								}
							}

							IoTHubMessage_Destroy(msgHandle);
						}

						EventData_Destroy(sendData);
					}
				}

				ThreadAPI_Sleep(500);

				if ((loopIterationEndTimeInSeconds = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the end time of the send loop iteration (time(NULL) failed)");
					result = __LINE__;
				}
				else
				{
					loopIterationTotalTime = difftime(loopIterationEndTimeInSeconds, loopIterationStartTimeInSeconds);
					test_state->timeUntilNextSendEventInSeconds -= loopIterationTotalTime;
				}
			} // While loop
		}
			
#ifndef MBED_BUILD_TIMESTAMP
		printSendStatistics(&test_state->statistics);

		IoTHubTest_Deinit(iotHubTestHandle);
	}
#endif

	return result;
}

static int receiveMessageLoop(IOTHUB_CLIENT_HANDLE iotHubClientHandle, LONGHAUL_RECEIVE_TEST_STATE* test_state)
{
	int result = 0;

#ifndef MBED_BUILD_TIMESTAMP
	IOTHUB_TEST_HANDLE iotHubTestHandle;

	if ((iotHubTestHandle = IoTHubTest_Initialize(IoTHubAccount_GetEventHubConnectionString(g_iothubAcctInfo), IoTHubAccount_GetIoTHubConnString(g_iothubAcctInfo), IoTHubAccount_GetDeviceId(g_iothubAcctInfo), IoTHubAccount_GetDeviceKey(g_iothubAcctInfo), IoTHubAccount_GetEventhubListenName(g_iothubAcctInfo), IoTHubAccount_GetEventhubAccessKey(g_iothubAcctInfo), IoTHubAccount_GetSharedAccessSignature(g_iothubAcctInfo), IoTHubAccount_GetEventhubConsumerGroup(g_iothubAcctInfo))) == NULL)
	{
		LogError("Failed initializing the Event Hub test client.");
		result = __LINE__;
	}
	else
	{
		initializeReceiveStatistics(&test_state->statistics);
#endif
		time_t testInitialTime;

		if ((testInitialTime = time(NULL)) == INDEFINITE_TIME)
		{
			LogError("Failed setting the initial time of the test (time(NULL) failed).");
			result = __LINE__;
		}
		else
		{
			time_t loopIterationStartTimeInSeconds, loopIterationEndTimeInSeconds;
			double loopIterationTotalTime;
			time_t testCurrentTime;

			while (result == 0)
			{
				if ((testCurrentTime = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the current time of the test (time(NULL) failed)");
					result = __LINE__;
					break;
				}
				else if (difftime(testCurrentTime, testInitialTime) > test_state->profile->totalRunTimeInSeconds)
				{
					LogInfo("Test run for the expected duration (%d seconds)", test_state->profile->totalRunTimeInSeconds);
					break;
				}

				if ((loopIterationStartTimeInSeconds = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the initial time of the receive loop iteration (time(NULL) failed)");
					result = __LINE__;
					break;
				}

				if (test_state->timeUntilNextReceiveMessageInSeconds <= 0.0)
				{
					EXPECTED_RECEIVE_DATA* receiveData;

					if ((receiveData = MessageData_Create()) == NULL)
					{
						LogError("Failed creating EXPECTED_RECEIVE_DATA.");
						result = __LINE__;
					}
					else
					{
						IOTHUB_TEST_CLIENT_RESULT sendResult;

						if (IoTHubClient_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, receiveData) != IOTHUB_CLIENT_OK)
						{
							LogError("Call to IoTHubClient_SetMessageCallback failed.");
							result = __LINE__;
						}
						else if ((sendResult = IoTHubTest_SendMessage(iotHubTestHandle, (const unsigned char*)receiveData->data, receiveData->dataSize)) != IOTHUB_TEST_CLIENT_OK)
						{
							LogError("Call to IoTHubTest_SendMessage failed (%i).", sendResult);
							result = __LINE__;
						}
						else
						{
							if ((receiveData->timeSent = time(NULL)) == INDEFINITE_TIME)
							{
								LogError("Failed setting receiveData->timeSent (time(NULL) failed)");
							}

							time_t beginOperation, nowTime;
							
							if ((beginOperation = time(NULL)) == INDEFINITE_TIME)
							{
								LogError("Failed setting beginOperation (time(NULL) failed).");
								result = __LINE__;
							}
							else
							{
								do
								{
									if (Lock(receiveData->lock) != LOCK_OK)
									{
										LogError("Unable to lock to verify if C2D message has been received.");
										result = __LINE__;
										break;
									}
									else
									{
										if (receiveData->receivedByClient)
										{
											(void)Unlock(receiveData->lock);
											break;
										}
										(void)Unlock(receiveData->lock);
									}
									ThreadAPI_Sleep(100);

									if ((nowTime = time(NULL)) == INDEFINITE_TIME)
									{
										LogError("Failed setting nowTime (time(NULL) failed).");
										result = __LINE__;
										break;
									}
								} while (difftime(nowTime, beginOperation) < MAX_CLOUD_TRAVEL_TIME);

								if (result == 0)
								{
									if (!receiveData->receivedByClient)
									{
										LogError("Failure retrieving data from C2D");
										result = __LINE__;
									}
									else
									{
#ifndef MBED_BUILD_TIMESTAMP
										computeReceiveStatistics(&test_state->statistics, receiveData);
#endif
										test_state->timeUntilNextReceiveMessageInSeconds = test_state->profile->messageFrequencyInSecs[test_state->receiveFrequencyIndex];

										if ((test_state->receiveFrequencyIndex + 1) < test_state->profile->numberOfMessageFrequencyVariations) test_state->receiveFrequencyIndex++;
									}
								}
							}
						}

						MessageData_Destroy(receiveData);
					}
				}

				ThreadAPI_Sleep(500);

				if ((loopIterationEndTimeInSeconds = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the end time of the receive loop iteration (time(NULL) failed)");
					result = __LINE__;
				}
				else
				{
					loopIterationTotalTime = difftime(loopIterationEndTimeInSeconds, loopIterationStartTimeInSeconds);
					test_state->timeUntilNextReceiveMessageInSeconds -= loopIterationTotalTime;
				}
			} // While loop
		}

#ifndef MBED_BUILD_TIMESTAMP
		printReceiveStatistics(&test_state->statistics);

		IoTHubTest_Deinit(iotHubTestHandle);
		}
#endif

	return result;
}
Ejemplo n.º 6
0
TSS_RESULT
conf_file_init(struct tcsd_config *conf)
{
	FILE *f = NULL;
	struct stat stat_buf;
#ifndef SOLARIS
	struct group *grp;
	struct passwd *pw;
	mode_t mode = (S_IRUSR|S_IWUSR);
#endif /* SOLARIS */
	TSS_RESULT result;

	init_tcsd_config(conf);

#ifdef SOLARIS
       /*
	* Solaris runs as root:sys but with reduced privileges
	* so we don't need to create a new user/group and also so
	* we can have auditing support.  The permissions on
	* the tcsd configuration file are not checked on Solaris.
	*/
#endif
	/* look for a config file, create if it doesn't exist */
	if (stat(TCSD_CONFIG_FILE, &stat_buf) == -1) {
		if (errno == ENOENT) {
			/* no config file? use defaults */
			config_set_defaults(conf);
			LogInfo("Config file %s not found, using defaults.", TCSD_CONFIG_FILE);
			return TSS_SUCCESS;
		} else {
			LogError("stat(%s): %s", TCSD_CONFIG_FILE, strerror(errno));
			return TCSERR(TSS_E_INTERNAL_ERROR);
		}
	}

#ifndef SOLARIS
	/* find the gid that owns the conf file */
	errno = 0;
	grp = getgrnam(TSS_GROUP_NAME);
	if (grp == NULL) {
		if (errno == 0) {
			LogError("Group \"%s\" not found, please add this group"
					" manually.", TSS_GROUP_NAME);
		} else {
			LogError("getgrnam(%s): %s", TSS_GROUP_NAME, strerror(errno));
		}
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}

	errno = 0;
	pw = getpwnam(TSS_USER_NAME);
	if (pw == NULL) {
		if (errno == 0) {
			LogError("User \"%s\" not found, please add this user"
					" manually.", TSS_USER_NAME);
		} else {
			LogError("getpwnam(%s): %s", TSS_USER_NAME, strerror(errno));
		}
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}

	/* make sure user/group TSS owns the conf file */
	if (pw->pw_uid != stat_buf.st_uid || grp->gr_gid != stat_buf.st_gid) {
		LogError("TCSD config file (%s) must be user/group %s/%s", TCSD_CONFIG_FILE,
				TSS_USER_NAME, TSS_GROUP_NAME);
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}

	/* make sure only the tss user can manipulate the config file */
	if (((stat_buf.st_mode & 0777) ^ mode) != 0) {
		LogError("TCSD config file (%s) must be mode 0600", TCSD_CONFIG_FILE);
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}
#endif /* SOLARIS */

	if ((f = fopen(TCSD_CONFIG_FILE, "r")) == NULL) {
		LogError("fopen(%s): %s", TCSD_CONFIG_FILE, strerror(errno));
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}

	result = read_conf_file(f, conf);
	fclose(f);

	/* fill out any uninitialized options */
	config_set_defaults(conf);

#ifdef SOLARIS
	/*
	* The SMF value for "local_only" overrides the config file and
	* disables all remote operations.
	*/
if (get_smf_prop("local_only", B_TRUE)) {
		(void) memset(conf->remote_ops, 0, sizeof(conf->remote_ops));
		conf->unset |= TCSD_OPTION_REMOTE_OPS;
	
	}
#endif
	return result;
}
Ejemplo n.º 7
0
/**
 *
 * Print_param_in_log : prints the nfs worker parameter structure into the logfile
 *
 * prints the nfs worker parameter structure into the logfile
 *
 * @param pparam Pointer to the nfs worker parameter
 *
 * @return none (void function)
 *
 */
void Print_param_worker_in_log(nfs_worker_parameter_t * pparam)
{
  LogInfo(COMPONENT_INIT,
          "NFS PARAM : worker_param.nb_before_gc = %d",
          pparam->nb_before_gc);
}                               /* Print_param_worker_in_log */
Ejemplo n.º 8
0
Launch::Launch()
{
	successfullRead = GL_FALSE;

	std::string nameOfFile = "launch";

	// Read XML from file
	std::ifstream in(std::string(nameOfFile + ".xml").c_str());

	// Check whether file exisits
	if(!in.is_open())
	{
		LogWarning("'launch.xml' was not found!");
		createNewLaunchFile();
		LogInfo("New 'launch.xml' was created! 'None' warnings will follow ;)");
		in.open(std::string(nameOfFile + ".xml").c_str());
	}

	// File exisits, lets hope the best
	std::stringstream buffer;
	buffer << in.rdbuf();
	in.close();
	std::string content(buffer.str());
	std::vector<GLchar> xml(content.begin(), content.end());
    xml.push_back('\0');

	// Parse it to a doc
	rapidxml::xml_document<> doc;
	doc.parse<rapidxml::parse_declaration_node | rapidxml::parse_no_data_nodes>(&xml[0]);

	// Launch (jump over declaration)
	rapidxml::xml_node<>* pRootNode = doc.first_node()->next_sibling();
	checkValue(std::string(pRootNode->name()), "launch", nameOfFile);

	// Get Version
	rapidxml::xml_attribute<>* pRootNodeCurrentAttribute = pRootNode->first_attribute();
	checkValue(std::string(pRootNodeCurrentAttribute->name()), "version", nameOfFile);
	GLfloat version = convertCharToFloat(pRootNodeCurrentAttribute->value());

	// Preparation of reading
	rapidxml::xml_node<>* pChildNode;
	rapidxml::xml_attribute<>* pNodeCurrentAttribute;
	GLuint errorCounter = 0;

	// Window width
	pChildNode = pRootNode->first_node();
	errorCounter += checkValue(std::string(pChildNode->name()), "windowWidth", nameOfFile);
	pNodeCurrentAttribute = pChildNode->first_attribute();
	errorCounter += checkValue(std::string(pNodeCurrentAttribute->name()), "value", nameOfFile);
	windowWidth = static_cast<GLuint>(convertCharToFloat(pNodeCurrentAttribute->value()));

	// Window height
	pChildNode = pChildNode->next_sibling();
	errorCounter += checkValue(std::string(pChildNode->name()), "windowHeight", nameOfFile);
	pNodeCurrentAttribute = pChildNode->first_attribute();
	errorCounter += checkValue(std::string(pNodeCurrentAttribute->name()), "value", nameOfFile);
	windowHeight = static_cast<GLuint>(convertCharToFloat(pNodeCurrentAttribute->value()));

	// Fullscreen
	pChildNode = pChildNode->next_sibling();
	errorCounter += checkValue(std::string(pChildNode->name()), "fullscreen", nameOfFile);
	pNodeCurrentAttribute = pChildNode->first_attribute();
	errorCounter += checkValue(std::string(pNodeCurrentAttribute->name()), "value", nameOfFile);
	fullscreen = convertCharToBool(pNodeCurrentAttribute->value());

	// Volume
	pChildNode = pChildNode->next_sibling();
	errorCounter += checkValue(std::string(pChildNode->name()), "volume", nameOfFile);
	pNodeCurrentAttribute = pChildNode->first_attribute();
	errorCounter += checkValue(std::string(pNodeCurrentAttribute->name()), "value", nameOfFile);
	volume = convertCharToString(pNodeCurrentAttribute->value());

	// Transferfunction
	pChildNode = pChildNode->next_sibling();
	errorCounter += checkValue(std::string(pChildNode->name()), "transferfunction", nameOfFile);
	pNodeCurrentAttribute = pChildNode->first_attribute();
	errorCounter += checkValue(std::string(pNodeCurrentAttribute->name()), "value", nameOfFile);
	transferfunction = convertCharToString(pNodeCurrentAttribute->value());

	// Raycaster
	pChildNode = pChildNode->next_sibling();
	errorCounter += checkValue(std::string(pChildNode->name()), "raycaster", nameOfFile);
	pNodeCurrentAttribute = pChildNode->first_attribute();
	errorCounter += checkValue(std::string(pNodeCurrentAttribute->name()), "value", nameOfFile);
	raycaster = convertCharToString(pNodeCurrentAttribute->value());

	// Check whether everything was read successfully
	successfullRead = (errorCounter == 0);
}
Ejemplo n.º 9
0
int Multicast_receive_socket (const char *hostname, const char *listenport, int family, int sockbuflen)
{
	struct addrinfo hints, *res, *ressave;
	socklen_t optlen;
	int p, error, sockfd;

	if (!listenport) {
		fprintf (stderr, "listen port required!\n");
		LogError ("listen port required!");
		return -1;
	}

	memset (&hints, 0, sizeof (struct addrinfo));
	hints.ai_family = family;
	hints.ai_socktype = SOCK_DGRAM;

	error = getaddrinfo (hostname, listenport, &hints, &res);

	if (error) {
		fprintf (stderr, "getaddrinfo error:: [%s]\n", gai_strerror (error));
		LogError ("getaddrinfo error:: [%s]", gai_strerror (error));
		return -1;
	}


	/*
	   Try open socket with each address getaddrinfo returned,
	   until we get a valid listening socket.
	*/

	sockfd = -1;
	ressave = res;
	while (res) {
		sockfd = socket (res->ai_family, res->ai_socktype, res->ai_protocol);
		if (sockfd < 0) {
			res = res->ai_next;
			continue;
		}

		// we found a valid socket and are done in this loop
		break;
	}

	if (sockfd < 0) {
		// nothing found - bye bye
		fprintf (stderr, "Could not create a socket for [%s:%s]\n", hostname, listenport);
		LogError ("Could not create a socket for [%s:%s]", hostname, listenport);
		freeaddrinfo (ressave);
		return -1;
	}


	if (isMulticast ( (struct sockaddr_storage *) res->ai_addr) < 0) {
		fprintf (stderr, "Not a multicast address [%s]\n", hostname);
		LogError ("Not a multicast address [%s]", hostname);
		freeaddrinfo (ressave);
		return -1;
	}

	close (sockfd);


	sockfd = socket (res->ai_family, SOCK_DGRAM, 0);
	if (bind (sockfd, res->ai_addr, res->ai_addrlen) < 0) {
		fprintf (stderr, "bind: %s\n", strerror (errno));
		LogError ("bind: %s", strerror (errno));
		close (sockfd);
		freeaddrinfo (ressave);
		return -1;
	}

	if (joinGroup (sockfd, 1 , 1, (struct sockaddr_storage *) res->ai_addr) < 0) {
		close (sockfd);
		freeaddrinfo (ressave);
		return -1;
	}

	if (res->ai_family == AF_INET)
		LogInfo ("Joined IPv4 multicast group: %s Port: %s", hostname, listenport);
	if (res->ai_family == AF_INET6)
		LogInfo ("Joined IPv6 multicat group: %s Port: %s", hostname, listenport);


	freeaddrinfo (ressave);

	if (sockbuflen) {
		if (sockbuflen < Min_SOCKBUFF_LEN) {
			sockbuflen = Min_SOCKBUFF_LEN;
			LogInfo ("I want at least %i bytes as socket buffer", sockbuflen);
		}
		optlen = sizeof (p);
		getsockopt (sockfd, SOL_SOCKET, SO_RCVBUF, &p, &optlen);
		LogInfo ("Standard setsockopt, SO_RCVBUF is %i Requested length is %i bytes", p, sockbuflen);
		if ( (setsockopt (sockfd, SOL_SOCKET, SO_RCVBUF, &sockbuflen, sizeof (sockbuflen)) != 0)) {
			fprintf (stderr, "setsockopt(SO_RCVBUF,%d): %s\n", sockbuflen, strerror (errno));
			LogError ("setsockopt(SO_RCVBUF,%d): %s", sockbuflen, strerror (errno));
			close (sockfd);
			return -1;
		} else {
			getsockopt (sockfd, SOL_SOCKET, SO_RCVBUF, &p, &optlen);
			LogInfo ("System set setsockopt, SO_RCVBUF to %d bytes", p);
		}
	}

	return sockfd;

} // End of Multicast_receive_socket
Ejemplo n.º 10
0
bool Controller::Initialize(const char* server_name, const char* configure_file)
{
    _server_name = server_name;
    _configure_file = configure_file;

    // 加载配置
    if (!gConfigureMap.Load(configure_file))
    {
        printf("error: %s\n", gConfigureMap.GetErrMsg().c_str());
        return false;
    }
    gConfigureMap.Print();

    // 初始化日志
    std::string log_path = JoinPath(gConfigureMap["log"]["log_path"].str(), server_name);
    if (!Logger::Initialize(log_path.c_str(),
                           gConfigureMap["log"]["max_file_size"].as<uint32_t>(DefaultConf::kMaxLogFileSize),
                           gConfigureMap["log"]["max_file_num"].as<uint32_t>(DefaultConf::kMaxLogFileNum),
                           gConfigureMap["log"]["log_level"].c_str())) {
        printf("logger initialize failed, errmsg: %s\n", Logger::GetErrMsg().c_str());
    }

    LogInfo("Logger initialize succeed\n");

    int poller_max_event = gConfigureMap["poller_max_event"].as<int>(DefaultConf::kPollerMaxEventNum);
    assert(poller_max_event > 0);
    _poller = new Poller(poller_max_event);
    assert(_poller);

    LogInfo("Poller initialize succeed\n");

    // 初始化监听端口

    // TODO different port bind different protocol(unpack function)
    // 每个监听端口最好能独立的包完整性检查,每个访问外部server的端口,最好也能绑定独立协议
    const Value & val = gConfigureMap["listen"];
    _listen_size = val.size() + 128;
    _listen_sockets = new ListenFdInfo[_listen_size];
    for (uint32_t i=0; i<_listen_size; ++i)
    {
        unsigned int port = val[i]["port"].as<unsigned>(0);
        int fd = ListenTcpV4(port);
        if (fd < 0) {
            FillErrmsg("listen failed: ", errno);
            return false;
        }

        _listen_sockets[fd].port = port;
        _listen_sockets[fd].fd = fd;

        if (_poller->Add(fd, (uint64_t)fd, EPOLLIN)) {
            FillErrmsg("listen fd add to poller failed: ", errno);
            return false;
        }
    }

    _io_handler_num = gConfigureMap["server"]["io_handler_num"].as<uint32_t>(DefaultConf::kIoHandlerNum);
    _io_handers = new IoHandler[_io_handler_num];
    assert(_io_handers);
    for (uint32_t i=0; i<_io_handler_num; ++i) {
        if(!_io_handers[i].Initialize()) {
            _errmsg = "io handler initialize failed";
            return false;
        }
    }

    _worker_num = gConfigureMap["server"]["worker_num"].as<uint32_t>(DefaultConf::kWorkerNum);
    _workers = new Worker[_worker_num];
    assert(_workers);
    for (uint32_t i=0; i<_worker_num; ++i) {
        if(!_workers[i].Initialize()) {
            _errmsg = "initialize workers failed";
            return false;
        }
    }

    int pool_size = _io_handler_num + _worker_num;
    int queue_size = gConfigureMap["server"]["queue_size"].as<uint32_t>(DefaultConf::kQueueSize);
    _task_pool = new TaskPool();
    assert(_task_pool);
    if (!_task_pool->Initialize(pool_size, queue_size)) {
        LogErr("task poll initialize failed");
        return false;
    }

    return true;
}
Ejemplo n.º 11
0
//校验请求是否正确
int CLogin4399::check_login(const char* plat_name, const char* pszReq, string& strAccountGot)
{  	
// 	if ( m_str_plat_name !=  (string)plat_name)
// 	{
// 		LogWarning("check_login", "plat :%s != %s", plat_name, m_str_plat_name.c_str());
// 		return ENUM_LOGIN_PLAT_NAME_ERROR;
// 	}

	//port=123&suid=xxx&timestamp=12345&sign=xxx&platid=111&plataccount=xxx&token=xxx

	//解析登录是否合法
	map<string, string> dictParams;
	SplitStringToMap(pszReq, '&', '=', dictParams);

	//校验客户端发来的loginapp端口是否在合法
	//uLoginappPort = (uint16_t)atoi(get_dict_field(dictParams, "port").c_str());
	//if(uLoginappPort < LOGINAPP_MIN_PORT || uLoginappPort > LOGINAPP_MAX_PORT)
	//{
	//    LogError("login_porterr", "req=%s", pszReq);
	//    return ENUM_LOGIN_INNER_ERR;
	//}
	//loginapp端口改为读配置
	//uint16_t unPortFromClient = (uint16_t)atoi(get_dict_field(dictParams, "port").c_str());

	//平台的时间戳
	const string&  strTime = get_dict_field(dictParams, "timestamp");	
	int nTimestamp = atoi(strTime.c_str());
	int nTimeNow = time(NULL);
	//比服务器时间滞后超过20分钟,或者超前多于5分钟算时间无效
	if(nTimeNow > nTimestamp + 1200 || nTimestamp > nTimeNow + 300)
	{
		LogError("login_timeout", "req=%s", pszReq);
		return ENUM_LOGIN_TIME_ILLEGAL;		
	}

	const string& strSuid = get_dict_field(dictParams, "suid");
	const string& strSign = get_dict_field(dictParams, "sign");
	//检查md5是否匹配
	//flag=md5("$suid&$timestamp&%key")
	{
		std::ostringstream oss;
		oss << strSuid << '&' << strTime << '&' << this->get_cfg_value("key", sg_szLoginKey);		
		const string& strOss = oss.str();
		
		string __md5 = getmd5(strOss);		

		if(strcasecmp(__md5.c_str(), strSign.c_str()) != 0 )
		{
			//md5签名不匹配,错误的请求
			return ENUM_LOGIN_SIGN_ILLEGAL;
		}
	}

	//到平台验证tocken是否正确
	const string& strTocken = get_dict_field(dictParams, "tocken");
	const string& strAccount = get_dict_field(dictParams, "plataccount");
	{
		string resp = "";
		string strUrl = this->get_cfg_value("url", sg_szVerifyUrl).append(strTocken);
		int ret = GetUrl_new(strUrl.c_str(), resp);
		if (ret != CURLE_OK)
		{
			LogWarning("login_urlerr", "ret=%d;req=%s", ret, pszReq);
			return ENUM_LOGIN_SERVER_BUSY;
		}
		Trim(resp);


		JsonHelper jsonhp(resp);

		int rst = 0;
		if (!jsonhp.GetJsonItem("code", rst))
		{
			//平台返回字符串解析失败
			LogWarning("login_jsonfailed", "json=%s", resp.c_str());
			return ENUM_LOGIN_SDK_VERIFY_FAILED;
		}

		if (rst != 1)
		{
			//结果码为1表示验证成功,其他值都是失败
			LogWarning("login_verifyfailed", "rst=%d;req=%s", rst, pszReq);
			return ENUM_LOGIN_SDK_VERIFY_FAILED;            
		}
	}

	//需要返回的参数值
	strAccountGot.assign(strSuid);

	LogInfo("login_req", "%s", pszReq);
	return ENUM_LOGIN_SUCCESS;
}
Ejemplo n.º 12
0
bool ethernet_init(
    char *if_name)
{
    PPACKET_OID_DATA pOidData;
    LPADAPTER lpAdapter;
    pcap_if_t *pcap_all_if;
    pcap_if_t *dev;
    BOOLEAN result;
    CHAR str[sizeof(PACKET_OID_DATA) + 128];
    int i;
    char msgBuf[200];

    if (ethernet_valid())
        ethernet_cleanup();

    /**
     * Find the interface user specified
     */
    /* Retrieve the device list */
    if (pcap_findalldevs(&pcap_all_if, pcap_errbuf) == -1) {
        sprintf(msgBuf, "ethernet.c: error in pcap_findalldevs: %s\n",
            pcap_errbuf);
        LogError(msgBuf);
        return false;
    }
    /* Scan the list printing every entry */
    for (dev = pcap_all_if; dev; dev = dev->next) {
        if (strcmp(if_name, dev->name) == 0)
            break;
    }
    pcap_freealldevs(pcap_all_if);      /* we don't need it anymore */
    if (dev == NULL) {
        sprintf(msgBuf, "ethernet.c: specified interface not found: %s\n",
            if_name);
        LogError(msgBuf);
        return false;
    }

    /**
     * Get local MAC address
     */
    ZeroMemory(str, sizeof(PACKET_OID_DATA) + 128);
    lpAdapter = PacketOpenAdapter(if_name);
    if (lpAdapter == NULL) {
        ethernet_cleanup();
        sprintf(msgBuf, "ethernet.c: error in PacketOpenAdapter(\"%s\")\n",
            if_name);
        LogError(msgBuf);
        return false;
    }
    pOidData = (PPACKET_OID_DATA) str;
    pOidData->Oid = OID_802_3_CURRENT_ADDRESS;
    pOidData->Length = 6;
    result = PacketRequest(lpAdapter, FALSE, pOidData);
    if (!result) {
        PacketCloseAdapter(lpAdapter);
        ethernet_cleanup();
        LogError("ethernet.c: error in PacketRequest()\n");
        return false;
    }
    for (i = 0; i < 6; ++i)
        Ethernet_MAC_Address[i] = pOidData->Data[i];
    PacketCloseAdapter(lpAdapter);

    /**
     * Open interface for subsequent sending and receiving
     */
    /* Open the output device */
    pcap_eth802_fp = pcap_open(if_name, /* name of the device */
        MAX_MPDU,       /* portion of the packet to capture */
        PCAP_OPENFLAG_PROMISCUOUS,      /* promiscuous mode */
        eth_timeout,    /* read timeout */
        NULL,   /* authentication on the remote machine */
        pcap_errbuf     /* error buffer */
        );
    if (pcap_eth802_fp == NULL) {
        PacketCloseAdapter(lpAdapter);
        ethernet_cleanup();
        sprintf(msgBuf,
            "ethernet.c: unable to open the adapter. %s is not supported by WinPcap\n",
            if_name);
        LogError(msgBuf);
        return false;
    }

    LogInfo("ethernet.c: ethernet_init() ok.\n");

    atexit(ethernet_cleanup);

    return ethernet_valid();
}
Ejemplo n.º 13
0
int main(int argc, char **argv) {
 
//Set timezone to UTC f or standarization.
setenv("TZ","UTC",1);
tzset();

char	*bindhost, *filter, *datadir, pidstr[32], *launch_process;
char	*userid, *groupid, *checkptr, *listenport, *mcastgroup, *extension_tags;
char	*Ident, *dynsrcdir, pidfile[MAXPATHLEN];
struct stat fstat;
packet_function_t receive_packet;
send_peer_t  peer;
FlowSource_t *fs;
struct sigaction act;
int		family, bufflen;
time_t 	twin, t_start;
int		sock, synctime, do_daemonize, expire, report_sequence, do_xstat;
int		subdir_index, sampling_rate, compress;
int		c;
#ifdef PCAP
char	*pcap_file;
 
	pcap_file		= NULL;
#endif

	receive_packet 	= recvfrom;
	verbose = synctime = do_daemonize = 0;
	bufflen  		= 0;
	family			= AF_UNSPEC;
	launcher_pid	= 0;
	launcher_alive	= 0;
	report_sequence	= 0;
	listenport		= DEFAULTCISCOPORT;
	bindhost 		= NULL;
	mcastgroup		= NULL;
	pidfile[0]		= 0;
	filter   		= NULL;
	launch_process	= NULL;
	userid 			= groupid = NULL;
	twin	 		= TIME_WINDOW;
	datadir	 		= NULL;
	subdir_index	= 0;
	expire			= 0;
	sampling_rate	= 1;
	compress		= 0;
	do_xstat		= 0;
	memset((void *)&peer, 0, sizeof(send_peer_t));
	peer.family		= AF_UNSPEC;
	Ident			= "none";
	FlowSource		= NULL;
	extension_tags	= DefaultExtensions;
	dynsrcdir		= NULL;

	while ((c = getopt(argc, argv, "46ef:whEVI:DB:b:j:l:M:n:p:P:R:S:s:T:t:x:Xru:g:z")) != EOF) {
		switch (c) {
			case 'h':
				usage(argv[0]);
				exit(0);
				break;
			case 'u':
				userid  = optarg;
				break;
			case 'g':
				groupid  = optarg;
				break;
			case 'e':
				expire = 1;
				break;
			case 'f': {
#ifdef PCAP
				struct stat	fstat;
				pcap_file = optarg;
				stat(pcap_file, &fstat);
				if ( !S_ISREG(fstat.st_mode) ) {
					fprintf(stderr, "Not a regular file: %s\n", pcap_file);
					exit(254);
				}
#else
				fprintf(stderr, "PCAP reader not compiled! Option ignored!\n");
#endif
				} break;
			case 'E':
				verbose = 1;
				Setv6Mode(1);
				break;
			case 'V':
				printf("%s: Version: %s\n",argv[0], nfdump_version);
				exit(0);
				break;
			case 'X':
				do_xstat = 1;
				break;
			case 'D':
				do_daemonize = 1;
				break;
			case 'I':
				Ident = strdup(optarg);
				break;
			case 'M':
				dynsrcdir = strdup(optarg);
				if ( strlen(dynsrcdir) > MAXPATHLEN ) {
					fprintf(stderr, "ERROR: Path too long!\n");
					exit(255);
				}
				if ( stat(dynsrcdir, &fstat) < 0 ) {
					fprintf(stderr, "stat() failed on %s: %s\n", dynsrcdir, strerror(errno));
					exit(255);
				}
				if ( !(fstat.st_mode & S_IFDIR) ) {
					fprintf(stderr, "No such directory: %s\n", dynsrcdir);
					break;
				}
				if ( !SetDynamicSourcesDir(&FlowSource, dynsrcdir) ) {
					fprintf(stderr, "-l, -M and -n are mutually exclusive\n");
					break;
				}
				break;
			case 'n':
				if ( AddFlowSource(&FlowSource, optarg) != 1 ) 
					exit(255);
				break;
			case 'w':
				synctime = 1;
				break;
			case 'B':
				bufflen = strtol(optarg, &checkptr, 10);
				if ( (checkptr != NULL && *checkptr == 0) && bufflen > 0 )
					break;
				fprintf(stderr,"Argument error for -B\n");
				exit(255);
			case 'b':
				bindhost = optarg;
				break;
			case 'j':
				mcastgroup = optarg;
				break;
			case 'p':
				listenport = optarg;
				break;
			case 'P':
				if ( optarg[0] == '/' ) { 	// absolute path given
					strncpy(pidfile, optarg, MAXPATHLEN-1);
				} else {					// path relative to current working directory
					char tmp[MAXPATHLEN];
					if ( !getcwd(tmp, MAXPATHLEN-1) ) {
						fprintf(stderr, "Failed to get current working directory: %s\n", strerror(errno));
						exit(255);
					}
					tmp[MAXPATHLEN-1] = 0;
					snprintf(pidfile, MAXPATHLEN - 1 - strlen(tmp), "%s/%s", tmp, optarg);
				}
				// pidfile now absolute path
				pidfile[MAXPATHLEN-1] = 0;
				break;
			case 'R': {
				char *p = strchr(optarg, '/');
				if ( p ) { 
					*p++ = '\0';
					peer.port = strdup(p);
				} else {
					peer.port = DEFAULTCISCOPORT;
				}
				peer.hostname = strdup(optarg);

				break; }
			case 'r':
				report_sequence = 1;
				break;
			case 's':
				// a negative sampling rate is set as the overwrite sampling rate
				sampling_rate = (int)strtol(optarg, (char **)NULL, 10);
				if ( (sampling_rate == 0 ) ||
					 (sampling_rate < 0 && sampling_rate < -10000000) ||
					 (sampling_rate > 0 && sampling_rate > 10000000) ) {
					fprintf(stderr, "Invalid sampling rate: %s\n", optarg);
					exit(255);
				} 
				break;
			case 'T': {
				size_t len = strlen(optarg);
				extension_tags = optarg;
				if ( len == 0 || len > 128 ) {
					fprintf(stderr, "Extension length error. Unexpected option '%s'\n", extension_tags);
					exit(255);
				}
				break; }
			case 'l':
				datadir = optarg;
				if ( strlen(datadir) > MAXPATHLEN ) {
					fprintf(stderr, "ERROR: Path too long!\n");
					exit(255);
				}
				if ( stat(datadir, &fstat) < 0 ) {
					fprintf(stderr, "stat() failed on %s: %s\n", datadir, strerror(errno));
					exit(255);
				}
				if ( !(fstat.st_mode & S_IFDIR) ) {
					fprintf(stderr, "No such directory: %s\n", datadir);
					break;
				}
				break;
			case 'S':
				subdir_index = atoi(optarg);
				break;
			case 't':
				twin = atoi(optarg);
				if ( twin <= 0 ) {
					fprintf(stderr, "ERROR: time frame <= 0\n");
					exit(255);
				}
				if (twin < 10) {
					fprintf(stderr, "WARNING, Very small time frame - < 10s!\n");
				}
				break;
			case 'x':
				launch_process = optarg;
				break;
			case 'z':
				compress = 1;
				break;
			case '4':
				if ( family == AF_UNSPEC )
					family = AF_INET;
				else {
					fprintf(stderr, "ERROR, Accepts only one protocol IPv4 or IPv6!\n");
					exit(255);
				}
				break;
			case '6':
				if ( family == AF_UNSPEC )
					family = AF_INET6;
				else {
					fprintf(stderr, "ERROR, Accepts only one protocol IPv4 or IPv6!\n");
					exit(255);
				}
				break;
			default:
				usage(argv[0]);
				exit(255);
		}
	}
	
	if ( FlowSource == NULL && datadir == NULL && dynsrcdir == NULL ) {
		fprintf(stderr, "ERROR, Missing -n (-l/-I) or -M source definitions\n");
		exit(255);
	}
	if ( FlowSource == NULL && datadir != NULL && !AddDefaultFlowSource(&FlowSource, Ident, datadir) ) {
		fprintf(stderr, "Failed to add default data collector directory\n");
		exit(255);
	}

	if ( bindhost && mcastgroup ) {
		fprintf(stderr, "ERROR, -b and -j are mutually exclusive!!\n");
		exit(255);
	}

	if ( do_daemonize && !InitLog(argv[0], SYSLOG_FACILITY)) {
		exit(255);
	}

	InitExtensionMaps(NO_EXTENSION_LIST);
	SetupExtensionDescriptors(strdup(extension_tags));

	// Debug code to read from pcap file
#ifdef PCAP
	sock = 0;
	if ( pcap_file ) {
		printf("Setup pcap reader\n");
		setup_packethandler(pcap_file, NULL);
		receive_packet 	= NextPacket;
	} else 
#endif
	if ( mcastgroup ) 
		sock = Multicast_receive_socket (mcastgroup, listenport, family, bufflen);
	else 
		sock = Unicast_receive_socket(bindhost, listenport, family, bufflen );

	if ( sock == -1 ) {
		fprintf(stderr,"Terminated due to errors.\n");
		exit(255);
	}

	if ( peer.hostname ) {
		peer.sockfd = Unicast_send_socket (peer.hostname, peer.port, peer.family, bufflen, 
											&peer.addr, &peer.addrlen );
		if ( peer.sockfd <= 0 )
			exit(255);
		LogInfo("Replay flows to host: %s port: %s", peer.hostname, peer.port);
	}

	if ( sampling_rate < 0 ) {
		default_sampling = -sampling_rate;
		overwrite_sampling = default_sampling;
	} else {
		default_sampling = sampling_rate;
	}

	SetPriv(userid, groupid);

	if ( subdir_index && !InitHierPath(subdir_index) ) {
		close(sock);
		exit(255);
	}

	// check if pid file exists and if so, if a process with registered pid is running
	if ( strlen(pidfile) ) {
		int pidf;
		pidf = open(pidfile, O_RDONLY, 0);
		if ( pidf > 0 ) {
			// pid file exists
			char s[32];
			ssize_t len;
			len = read(pidf, (void *)s, 31);
			close(pidf);
			s[31] = '\0';
			if ( len < 0 ) {
				fprintf(stderr, "read() error existing pid file: %s\n", strerror(errno));
				exit(255);
			} else {
				unsigned long pid = atol(s);
				if ( pid == 0 ) {
					// garbage - use this file
					unlink(pidfile);
				} else {
					if ( kill(pid, 0) == 0 ) {
						// process exists
						fprintf(stderr, "A process with pid %lu registered in pidfile %s is already running!\n", 
							pid, strerror(errno));
						exit(255);
					} else {
						// no such process - use this file
						unlink(pidfile);
					}
				}
			}
		} else {
			if ( errno != ENOENT ) {
				fprintf(stderr, "open() error existing pid file: %s\n", strerror(errno));
				exit(255);
			} // else errno == ENOENT - no file - this is fine
		}
	}

	if (argc - optind > 1) {
		usage(argv[0]);
		close(sock);
		exit(255);
	} else {
		/* user specified a pcap filter */
		filter = argv[optind];
	}


	t_start = time(NULL);
	if ( synctime )
		t_start = t_start - ( t_start % twin);

	if ( do_daemonize ) {
		verbose = 0;
		daemonize();
	}
	if (strlen(pidfile)) {
		pid_t pid = getpid();
		int pidf  = open(pidfile, O_RDWR|O_TRUNC|O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
		if ( pidf == -1 ) {
			LogError("Error opening pid file: '%s' %s", pidfile, strerror(errno));
			close(sock);
			exit(255);
		}
		snprintf(pidstr,31,"%lu\n", (unsigned long)pid);
		if ( write(pidf, pidstr, strlen(pidstr)) <= 0 ) {
			LogError("Error write pid file: '%s' %s", pidfile, strerror(errno));
		}
		close(pidf);
	}

	done = 0;
	if ( launch_process || expire ) {
		// for efficiency reason, the process collecting the data
		// and the process launching processes, when a new file becomes
		// available are separated. Communication is done using signals
		// as well as shared memory
		// prepare shared memory
		shmem = mmap(0, sizeof(srecord_t), PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0);
		if ( shmem == (caddr_t)-1 ) {
			LogError("mmap() error: %s", strerror(errno));
			close(sock);
			exit(255);
		}

		launcher_pid = fork();
		switch (launcher_pid) {
			case 0:
				// child
				close(sock);
				launcher((char *)shmem, FlowSource, launch_process, expire);
				_exit(0);
				break;
			case -1:
				LogError("fork() error: %s", strerror(errno));
				if ( strlen(pidfile) )
					unlink(pidfile);
				exit(255);
				break;
			default:
				// parent
			launcher_alive = 1;
			LogInfo("Launcher[%i] forked", launcher_pid);
		}
	}

	fs = FlowSource;
	while ( fs ) {
		if ( InitBookkeeper(&fs->bookkeeper, fs->datadir, getpid(), launcher_pid) != BOOKKEEPER_OK ) {
			LogError("initialize bookkeeper failed.");

			// release all already allocated bookkeepers
			fs = FlowSource;
			while ( fs && fs->bookkeeper ) {
				ReleaseBookkeeper(fs->bookkeeper, DESTROY_BOOKKEEPER);
				fs = fs->next;
			}
			close(sock);
			if ( launcher_pid )
				kill_launcher(launcher_pid);
			if ( strlen(pidfile) )
				unlink(pidfile);
			exit(255);
		}

		// Init the extension map list
		if ( !InitExtensionMapList(fs) ) {
			// error message goes to syslog
			exit(255);
		}

		fs = fs->next;
	}

	/* Signal handling */
	memset((void *)&act,0,sizeof(struct sigaction));
	act.sa_handler = IntHandler;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	sigaction(SIGTERM, &act, NULL);
	sigaction(SIGINT, &act, NULL);
	sigaction(SIGHUP, &act, NULL);
	sigaction(SIGALRM, &act, NULL);
	sigaction(SIGCHLD, &act, NULL);

	LogInfo("Startup.");
	run(receive_packet, sock, peer, twin, t_start, report_sequence, subdir_index, compress, do_xstat);
	close(sock);
	kill_launcher(launcher_pid);

	fs = FlowSource;
	while ( fs && fs->bookkeeper ) {
		dirstat_t 	*dirstat;
		// if we do not auto expire and there is a stat file, update the stats before we leave
		if ( expire == 0 && ReadStatInfo(fs->datadir, &dirstat, LOCK_IF_EXISTS) == STATFILE_OK ) {
			UpdateBookStat(dirstat, fs->bookkeeper);
			WriteStatInfo(dirstat);
			LogInfo("Updating statinfo in directory '%s'", datadir);
		}

		ReleaseBookkeeper(fs->bookkeeper, DESTROY_BOOKKEEPER);
		fs = fs->next;
	}

	LogInfo("Terminating nfcapd.");
	EndLog();

	if ( strlen(pidfile) )
		unlink(pidfile);

	return 0;

} /* End of main */
Ejemplo n.º 14
0
static void run(packet_function_t receive_packet, int socket, send_peer_t peer, 
	time_t twin, time_t t_begin, int report_seq, int use_subdirs, int compress, int do_xstat) {
common_flow_header_t	*nf_header;
FlowSource_t			*fs;
struct sockaddr_storage nf_sender;
socklen_t 	nf_sender_size = sizeof(nf_sender);
time_t 		t_start, t_now;
uint64_t	export_packets;
uint32_t	blast_cnt, blast_failures, ignored_packets;
uint16_t	version;
ssize_t		cnt;
void 		*in_buff;
int 		err;
char 		*string;
srecord_t	*commbuff;

	if ( !Init_v1() || !Init_v5_v7_input() || !Init_v9() || !Init_IPFIX() )
		return;

	in_buff  = malloc(NETWORK_INPUT_BUFF_SIZE);
	if ( !in_buff ) {
		LogError("malloc() allocation error in %s line %d: %s\n", __FILE__, __LINE__, strerror(errno) );
		return;
	}

	// init vars
	commbuff = (srecord_t *)shmem;
	nf_header = (common_flow_header_t *)in_buff;

	// Init each netflow source output data buffer
	fs = FlowSource;
	while ( fs ) {

		// prepare file
		fs->nffile = OpenNewFile(fs->current, NULL, compress, 0, NULL);
		if ( !fs->nffile ) {
			return;
		}
		if ( do_xstat ) {
			fs->xstat = InitXStat(fs->nffile);
			if ( !fs->xstat ) 
				return;
		}
		// init vars
		fs->bad_packets		= 0;
		fs->first_seen      = 0xffffffffffffLL;
		fs->last_seen 		= 0;

		// next source
		fs = fs->next;
	}

	export_packets = blast_cnt = blast_failures = 0;
	t_start = t_begin;

	cnt = 0;
	periodic_trigger = 0;
	ignored_packets  = 0;

	// wake up at least at next time slot (twin) + some Overdue time
	alarm(t_start + twin + OVERDUE_TIME - time(NULL));
	/*
	 * Main processing loop:
	 * this loop, continues until done = 1, set by the signal handler
	 * The while loop will be breaked by the periodic file renaming code
	 * for proper cleanup 
	 */
	while ( 1 ) {
		struct timeval tv;

		/* read next bunch of data into beginn of input buffer */
		if ( !done) {
#ifdef PCAP
			// Debug code to read from pcap file, or from socket 
			cnt = receive_packet(socket, in_buff, NETWORK_INPUT_BUFF_SIZE , 0, 
						(struct sockaddr *)&nf_sender, &nf_sender_size);
						
			// in case of reading from file EOF => -2
			if ( cnt == -2 ) 
				done = 1;
#else
			cnt = recvfrom (socket, in_buff, NETWORK_INPUT_BUFF_SIZE , 0, 
						(struct sockaddr *)&nf_sender, &nf_sender_size);
#endif

			if ( cnt == -1 && errno != EINTR ) {
				LogError("ERROR: recvfrom: %s", strerror(errno));
				continue;
			}

			if ( peer.hostname ) {
				ssize_t len;
				len = sendto(peer.sockfd, in_buff, cnt, 0, (struct sockaddr *)&(peer.addr), peer.addrlen);
				if ( len < 0 ) {
					LogError("ERROR: sendto(): %s", strerror(errno));
				}
			}
		}

		/* Periodic file renaming, if time limit reached or if we are done.  */
		// t_now = time(NULL);
		gettimeofday(&tv, NULL);
		t_now = tv.tv_sec;

		if ( ((t_now - t_start) >= twin) || done ) {
			char subfilename[64];
			struct  tm *now;
			char	*subdir;

			alarm(0);
			now = localtime(&t_start);

			// prepare sub dir hierarchy
			if ( use_subdirs ) {
				subdir = GetSubDir(now);
				if ( !subdir ) {
					// failed to generate subdir path - put flows into base directory
					LogError("Failed to create subdir path!");
			
					// failed to generate subdir path - put flows into base directory
					subdir = NULL;
					snprintf(subfilename, 63, "nfcapd.%i%02i%02i%02i%02i%02i",
						now->tm_year + 1900, now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
				} else {
					snprintf(subfilename, 63, "%s/nfcapd.%i%02i%02i%02i%02i%02i", subdir,
						now->tm_year + 1900, now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
				}
			} else {
				subdir = NULL;
				snprintf(subfilename, 63, "nfcapd.%i%02i%02i%02i%02i%02i",
					now->tm_year + 1900, now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
			}
			subfilename[63] = '\0';

			// for each flow source update the stats, close the file and re-initialize the new file
			fs = FlowSource;
			while ( fs ) {
				char nfcapd_filename[MAXPATHLEN];
				char error[255];
				nffile_t *nffile = fs->nffile;

				if ( verbose ) {
					// Dump to stdout
					format_file_block_header(nffile->block_header, &string, 0);
					printf("%s\n", string);
				}

				if ( nffile->block_header->NumRecords ) {
					// flush current buffer to disc
					if ( WriteBlock(nffile) <= 0 )
						LogError("Ident: %s, failed to write output buffer to disk: '%s'" , fs->Ident, strerror(errno));
				} // else - no new records in current block

	
				// prepare filename
				snprintf(nfcapd_filename, MAXPATHLEN-1, "%s/%s", fs->datadir, subfilename);
				nfcapd_filename[MAXPATHLEN-1] = '\0';
	
				// update stat record
				// if no flows were collected, fs->last_seen is still 0
				// set first_seen to start of this time slot, with twin window size.
				if ( fs->last_seen == 0 ) {
					fs->first_seen = (uint64_t)1000 * (uint64_t)t_start;
					fs->last_seen  = (uint64_t)1000 * (uint64_t)(t_start + twin);
				}
				nffile->stat_record->first_seen = fs->first_seen/1000;
				nffile->stat_record->msec_first	= fs->first_seen - nffile->stat_record->first_seen*1000;
				nffile->stat_record->last_seen 	= fs->last_seen/1000;
				nffile->stat_record->msec_last	= fs->last_seen - nffile->stat_record->last_seen*1000;

				if ( fs->xstat ) {
					if ( WriteExtraBlock(nffile, fs->xstat->block_header ) <= 0 ) 
						LogError("Ident: %s, failed to write xstat buffer to disk: '%s'" , fs->Ident, strerror(errno));

					ResetPortHistogram(fs->xstat->port_histogram);
					ResetBppHistogram(fs->xstat->bpp_histogram);
				}

				// Flush Exporter Stat to file
				FlushExporterStats(fs);
				// Close file
				CloseUpdateFile(nffile, fs->Ident);

				if ( subdir && !SetupSubDir(fs->datadir, subdir, error, 255) ) {
					// in this case the flows get lost! - the rename will fail
					// but this should not happen anyway, unless i/o problems, inode problems etc.
					LogError("Ident: %s, Failed to create sub hier directories: %s", fs->Ident, error );
				}

				// if rename fails, we are in big trouble, as we need to get rid of the old .current file
				// otherwise, we will loose flows and can not continue collecting new flows
				err = rename(fs->current, nfcapd_filename);
				if ( err ) {
					LogError("Ident: %s, Can't rename dump file: %s", fs->Ident,  strerror(errno));
					LogError("Ident: %s, Serious Problem! Fix manually", fs->Ident);
					if ( launcher_pid )
						commbuff->failed = 1;

					// we do not update the books here, as the file failed to rename properly
					// otherwise the books may be wrong
				} else {
					struct stat	fstat;
					if ( launcher_pid )
						commbuff->failed = 0;

					// Update books
					stat(nfcapd_filename, &fstat);
					UpdateBooks(fs->bookkeeper, t_start, 512*fstat.st_blocks);
				}

				// log stats
				LogInfo("Ident: '%s' Flows: %llu, Packets: %llu, Bytes: %llu, Sequence Errors: %u, Bad Packets: %u", 
					fs->Ident, (unsigned long long)nffile->stat_record->numflows, (unsigned long long)nffile->stat_record->numpackets, 
					(unsigned long long)nffile->stat_record->numbytes, nffile->stat_record->sequence_failure, fs->bad_packets);

				// reset stats
				fs->bad_packets = 0;
				fs->first_seen  = 0xffffffffffffLL;
				fs->last_seen 	= 0;

				if ( !done ) {
					nffile = OpenNewFile(fs->current, nffile, compress, 0, NULL);
					if ( !nffile ) {
						LogError("killed due to fatal error: ident: %s", fs->Ident);
						break;
					}
					/* XXX needs fixing */
					if ( fs->xstat ) {
						// to be implemented
					}
				}

				// Dump all extension maps and exporters to the buffer
				FlushStdRecords(fs);

				// next flow source
				fs = fs->next;
			} // end of while (fs)

			// All flow sources updated - signal launcher if required
			if ( launcher_pid ) {
				// Signal launcher
		
				// prepare filename for %f expansion
				strncpy(commbuff->fname, subfilename, FNAME_SIZE-1);
				commbuff->fname[FNAME_SIZE-1] = 0;
				snprintf(commbuff->tstring, 16, "%i%02i%02i%02i%02i", 
					now->tm_year + 1900, now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min);
				commbuff->tstring[15] = 0;
				commbuff->tstamp = t_start;
				if ( subdir ) 
					strncpy(commbuff->subdir, subdir, FNAME_SIZE);
				else
					commbuff->subdir[0] = '\0';

				if ( launcher_alive ) {
					LogInfo("Signal launcher");
					kill(launcher_pid, SIGHUP);
				} else 
					LogError("ERROR: Launcher did unexpectedly!");

			}
			
			LogInfo("Total ignored packets: %u", ignored_packets);
			ignored_packets = 0;

			if ( done )
				break;

			// update alarm for next cycle
			t_start += twin;
			/* t_start = filename time stamp: begin of slot
		 	* + twin = end of next time interval
		 	* + OVERDUE_TIME = if no data is collected, this is at latest to act
		 	* - , now->tm_sect_now = difference value to now
		 	*/
			alarm(t_start + twin + OVERDUE_TIME - t_now);

		}

		/* check for error condition or done . errno may only be EINTR */
		if ( cnt < 0 ) {
			if ( periodic_trigger ) {	
				// alarm triggered, no new flow data 
				periodic_trigger = 0;
				continue;
			}
			if ( done ) 
				// signaled to terminate - exit from loop
				break;
			else {
				/* this should never be executed as it should be caught in other places */
				LogError("error condition in '%s', line '%d', cnt: %i", __FILE__, __LINE__ ,(int)cnt);
				continue;
			}
		}

		/* enough data? */
		if ( cnt == 0 )
			continue;

		// get flow source record for current packet, identified by sender IP address
		fs = GetFlowSource(&nf_sender);
		if ( fs == NULL ) {
			fs = AddDynamicSource(&FlowSource, &nf_sender);
			if ( fs == NULL ) {
				LogError("Skip UDP packet. Ignored packets so far %u packets", ignored_packets);
				ignored_packets++;
				continue;
			}
			if ( InitBookkeeper(&fs->bookkeeper, fs->datadir, getpid(), launcher_pid) != BOOKKEEPER_OK ) {
				LogError("Failed to initialise bookkeeper for new source");
				// fatal error
				return;
			}
			fs->nffile = OpenNewFile(fs->current, NULL, compress, 0, NULL);
			if ( !fs->nffile ) {
				LogError("Failed to open new collector file");
				return;
			}
		}

		/* check for too little data - cnt must be > 0 at this point */
		if ( cnt < sizeof(common_flow_header_t) ) {
			LogError("Ident: %s, Data length error: too little data for common netflow header. cnt: %i",fs->Ident, (int)cnt);
			fs->bad_packets++;
			continue;
		}

		fs->received = tv;
		/* Process data - have a look at the common header */
		version = ntohs(nf_header->version);
		switch (version) {
			case 1: 
				Process_v1(in_buff, cnt, fs);
				break;
			case 5: // fall through
			case 7: 
				Process_v5_v7(in_buff, cnt, fs);
				break;
			case 9: 
				Process_v9(in_buff, cnt, fs);
				break;
			case 10: 
				Process_IPFIX(in_buff, cnt, fs);
				break;
			case 255:
				// blast test header
				if ( verbose ) {
					uint16_t count = ntohs(nf_header->count);
					if ( blast_cnt != count ) {
							// LogError("Missmatch blast check: Expected %u got %u\n", blast_cnt, count);
						blast_cnt = count;
						blast_failures++;
					} else {
						blast_cnt++;
					}
					if ( blast_cnt == 65535 ) {
						fprintf(stderr, "Total missed packets: %u\n", blast_failures);
						done = 1;
					}
					break;
				}
			default:
				// data error, while reading data from socket
				LogError("Ident: %s, Error reading netflow header: Unexpected netflow version %i", fs->Ident, version);
				fs->bad_packets++;
				continue;

				// not reached
				break;
		}
		// each Process_xx function has to process the entire input buffer, therefore it's empty now.
		export_packets++;

		// flush current buffer to disc
		if ( fs->nffile->block_header->size > BUFFSIZE ) {
			// fishy! - we already wrote into someone elses memory! - I'm sorry
			// reset output buffer - data may be lost, as we don not know, where it happen
			fs->nffile->block_header->size 		 = 0;
			fs->nffile->block_header->NumRecords = 0;
			fs->nffile->buff_ptr = (void *)((pointer_addr_t)fs->nffile->block_header + sizeof(data_block_header_t) );
			LogError("### Software bug ### Ident: %s, output buffer overflow: expect memory inconsitency", fs->Ident);
		}
	}

	if ( verbose && blast_failures ) {
		fprintf(stderr, "Total missed packets: %u\n", blast_failures);
	}
	free(in_buff);

	fs = FlowSource;
	while ( fs ) {
		DisposeFile(fs->nffile);
		fs = fs->next;
	}

} /* End of run */
Ejemplo n.º 15
0
int doParallelSuperPMI(CommandLine::Options& o)
{
    HRESULT     hr = E_FAIL;
    SimpleTimer st;
    st.Start();

#ifndef FEATURE_PAL // TODO-Porting: handle Ctrl-C signals gracefully on Unix
    // Register a ConsoleCtrlHandler
    if (!SetConsoleCtrlHandler(CtrlHandler, TRUE))
    {
        LogError("Failed to set control handler.");
        return 1;
    }
#endif // !FEATURE_PAL

    char tempPath[MAX_PATH];
    if (!GetTempPath(MAX_PATH, tempPath))
    {
        LogError("Failed to get path to temp folder.");
        return 1;
    }

    if (o.workerCount <= 0)
    {
        // Use the default value which is the number of processors on the machine.
        SYSTEM_INFO sysinfo;
        GetSystemInfo(&sysinfo);

        o.workerCount = sysinfo.dwNumberOfProcessors;

        // If we ever execute on a machine which has more than MAXIMUM_WAIT_OBJECTS(64) CPU cores
        // we still can't spawn more than the max supported by WaitForMultipleObjects()
        if (o.workerCount > MAXIMUM_WAIT_OBJECTS)
            o.workerCount = MAXIMUM_WAIT_OBJECTS;
    }

    // Obtain the folder path of the current executable, which we will use to spawn ourself.
    char* spmiFilename = new char[MAX_PATH];
    if (!GetModuleFileName(NULL, spmiFilename, MAX_PATH))
    {
        LogError("Failed to get current exe path.");
        return 1;
    }

    char* spmiArgs = ConstructChildProcessArgs(o);

    // TODO: merge all this output to a single call to LogVerbose to avoid all the newlines.
    LogVerbose("Using child (%s) with args (%s)", spmiFilename, spmiArgs);
    if (o.mclFilename != nullptr)
        LogVerbose(" failingMCList=%s", o.mclFilename);
    if (o.diffMCLFilename != nullptr)
        LogVerbose(" diffMCLFilename=%s", o.diffMCLFilename);
    LogVerbose(" workerCount=%d, skipCleanup=%d.", o.workerCount, o.skipCleanup);

    HANDLE* hProcesses = new HANDLE[o.workerCount];
    HANDLE* hStdOutput = new HANDLE[o.workerCount];
    HANDLE* hStdError  = new HANDLE[o.workerCount];

    char** arrFailingMCListPath = new char*[o.workerCount];
    char** arrDiffMCListPath    = new char*[o.workerCount];
    char** arrStdOutputPath     = new char*[o.workerCount];
    char** arrStdErrorPath      = new char*[o.workerCount];

    // Add a random number to the temporary file names to allow multiple parallel SuperPMI to happen at once.
    unsigned int randNumber = 0;
#ifdef FEATURE_PAL
    PAL_Random(&randNumber, sizeof(randNumber));
#else  // !FEATURE_PAL
    rand_s(&randNumber);
#endif // !FEATURE_PAL

    for (int i = 0; i < o.workerCount; i++)
    {
        if (o.mclFilename != nullptr)
        {
            arrFailingMCListPath[i] = new char[MAX_PATH];
            sprintf_s(arrFailingMCListPath[i], MAX_PATH, "%sParallelSuperPMI-%u-%d.mcl", tempPath, randNumber, i);
        }
        else
        {
            arrFailingMCListPath[i] = nullptr;
        }

        if (o.diffMCLFilename != nullptr)
        {
            arrDiffMCListPath[i] = new char[MAX_PATH];
            sprintf_s(arrDiffMCListPath[i], MAX_PATH, "%sParallelSuperPMI-Diff-%u-%d.mcl", tempPath, randNumber, i);
        }
        else
        {
            arrDiffMCListPath[i] = nullptr;
        }

        arrStdOutputPath[i] = new char[MAX_PATH];
        arrStdErrorPath[i]  = new char[MAX_PATH];

        sprintf_s(arrStdOutputPath[i], MAX_PATH, "%sParallelSuperPMI-stdout-%u-%d.txt", tempPath, randNumber, i);
        sprintf_s(arrStdErrorPath[i], MAX_PATH, "%sParallelSuperPMI-stderr-%u-%d.txt", tempPath, randNumber, i);
    }

    char cmdLine[MAX_CMDLINE_SIZE];
    cmdLine[0] = '\0';
    int bytesWritten;

    for (int i = 0; i < o.workerCount; i++)
    {
        bytesWritten = sprintf_s(cmdLine, MAX_CMDLINE_SIZE, "%s -stride %d %d", spmiFilename, i + 1, o.workerCount);

        if (o.mclFilename != nullptr)
        {
            bytesWritten += sprintf_s(cmdLine + bytesWritten, MAX_CMDLINE_SIZE - bytesWritten, " -failingMCList %s",
                                      arrFailingMCListPath[i]);
        }

        if (o.diffMCLFilename != nullptr)
        {
            bytesWritten += sprintf_s(cmdLine + bytesWritten, MAX_CMDLINE_SIZE - bytesWritten, " -diffMCList %s",
                                      arrDiffMCListPath[i]);
        }

        bytesWritten += sprintf_s(cmdLine + bytesWritten, MAX_CMDLINE_SIZE - bytesWritten, " -v ewmin %s", spmiArgs);

        SECURITY_ATTRIBUTES sa;
        sa.nLength              = sizeof(sa);
        sa.lpSecurityDescriptor = NULL;
        sa.bInheritHandle       = TRUE; // Let newly created stdout/stderr handles be inherited.

        LogDebug("stdout %i=%s", i, arrStdOutputPath[i]);
        hStdOutput[i] = CreateFileA(arrStdOutputPath[i], GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS,
                                    FILE_ATTRIBUTE_NORMAL, NULL);
        if (hStdOutput[i] == INVALID_HANDLE_VALUE)
        {
            LogError("Unable to open '%s'. GetLastError()=%u", arrStdOutputPath[i], GetLastError());
            return -1;
        }

        LogDebug("stderr %i=%s", i, arrStdErrorPath[i]);
        hStdError[i] = CreateFileA(arrStdErrorPath[i], GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS,
                                   FILE_ATTRIBUTE_NORMAL, NULL);
        if (hStdError[i] == INVALID_HANDLE_VALUE)
        {
            LogError("Unable to open '%s'. GetLastError()=%u", arrStdErrorPath[i], GetLastError());
            return -1;
        }

        // Create a SuperPMI worker process and redirect its output to file
        if (!StartProcess(cmdLine, hStdOutput[i], hStdError[i], &hProcesses[i]))
        {
            return -1;
        }
    }

    WaitForMultipleObjects(o.workerCount, hProcesses, true, INFINITE);

    // Close stdout/stderr
    for (int i = 0; i < o.workerCount; i++)
    {
        CloseHandle(hStdOutput[i]);
        CloseHandle(hStdError[i]);
    }

    SpmiResult result = SpmiResult::Success;

    if (!closeRequested)
    {
        // Figure out the error code to use.
        // Mainly, if any child returns non-zero, we want to return non-zero, to indicate failure.
        for (int i = 0; i < o.workerCount; i++)
        {
            DWORD      exitCodeTmp;
            BOOL       ok          = GetExitCodeProcess(hProcesses[i], &exitCodeTmp);
            SpmiResult childResult = (SpmiResult)exitCodeTmp;
            if (ok && (childResult != result))
            {
                if (result == SpmiResult::Error || childResult == SpmiResult::Error)
                {
                    result = SpmiResult::Error;
                }
                else if (result == SpmiResult::Diffs || childResult == SpmiResult::Diffs)
                {
                    result = SpmiResult::Diffs;
                }
                else if (result == SpmiResult::Misses || childResult == SpmiResult::Misses)
                {
                    result = SpmiResult::Misses;
                }
                else if (result == SpmiResult::JitFailedToInit || childResult == SpmiResult::JitFailedToInit)
                {
                    result = SpmiResult::JitFailedToInit;
                }
                else
                {
                    result = SpmiResult::GeneralFailure;
                }
            }
        }

        bool usageError = false; // variable to flag if we hit a usage error in SuperPMI

        int loaded = 0, jitted = 0, failed = 0, excluded = 0, diffs = 0;

        // Read the stderr files and log them as errors
        // Read the stdout files and parse them for counts and log any MISSING or ISSUE errors
        for (int i = 0; i < o.workerCount; i++)
        {
            ProcessChildStdErr(arrStdErrorPath[i]);
            ProcessChildStdOut(o, arrStdOutputPath[i], &loaded, &jitted, &failed, &excluded, &diffs, &usageError);
            if (usageError)
                break;
        }

        if (o.mclFilename != nullptr && !usageError)
        {
            // Concat the resulting .mcl files
            MergeWorkerMCLs(o.mclFilename, arrFailingMCListPath, o.workerCount);
        }

        if (o.diffMCLFilename != nullptr && !usageError)
        {
            // Concat the resulting diff .mcl files
            MergeWorkerMCLs(o.diffMCLFilename, arrDiffMCListPath, o.workerCount);
        }

        if (!usageError)
        {
            if (o.applyDiff)
            {
                LogInfo(g_AsmDiffsSummaryFormatString, loaded, jitted, failed, excluded, diffs);
            }
            else
            {
                LogInfo(g_SummaryFormatString, loaded, jitted, failed, excluded);
            }
        }

        st.Stop();
        LogVerbose("Total time: %fms", st.GetMilliseconds());
    }

    if (!o.skipCleanup)
    {
        // Delete all temporary files generated
        for (int i = 0; i < o.workerCount; i++)
        {
            if (arrFailingMCListPath[i] != nullptr)
            {
                DeleteFile(arrFailingMCListPath[i]);
            }
            if (arrDiffMCListPath[i] != nullptr)
            {
                DeleteFile(arrDiffMCListPath[i]);
            }
            DeleteFile(arrStdOutputPath[i]);
            DeleteFile(arrStdErrorPath[i]);
        }
    }

    return (int)result;
}
Ejemplo n.º 16
0
int Unicast_receive_socket (const char *bindhost, const char *listenport, int family, int sockbuflen)
{
	struct addrinfo hints, *res, *ressave;
	socklen_t optlen;
	int error, p, sockfd;


	if (!listenport) {
		fprintf (stderr, "listen port required!\n");
		LogError ("listen port required!");
		return -1;
	}

	// if nothing specified on command line, prefer IPv4 over IPv6, for compatibility
	if (bindhost == NULL && family == AF_UNSPEC)
		family = AF_INET;

	memset (&hints, 0, sizeof (struct addrinfo));

	/*
	   AI_PASSIVE flag: we use the resulting address to bind
	   to a socket for accepting incoming connections.
	   So, when the hostname==NULL, getaddrinfo function will
	   return one entry per allowed protocol family containing
	   the unspecified address for that family.
	*/

	hints.ai_flags = AI_PASSIVE;
	hints.ai_family = family;
	hints.ai_socktype = SOCK_DGRAM;

	error = getaddrinfo (bindhost, listenport, &hints, &res);
	if (error) {
		fprintf (stderr, "getaddrinfo error: [%s]\n", gai_strerror (error));
		LogError ("getaddrinfo error: [%s]", gai_strerror (error));
		return -1;
	}

	/*
	   Try open socket with each address getaddrinfo returned,
	   until we get a valid listening socket.
	*/
	ressave = res;
	sockfd = -1;
	while (res) {
		// we listen only on IPv4 or IPv6
		if (res->ai_family != AF_INET && res->ai_family != AF_INET6)
			continue;

		sockfd = socket (res->ai_family, res->ai_socktype, res->ai_protocol);

		if (! (sockfd < 0)) {
			// socket call was successfull

			if (bind (sockfd, res->ai_addr, res->ai_addrlen) == 0) {
				if (res->ai_family == AF_INET)
					LogInfo ("Bound to IPv4 host/IP: %s, Port: %s",
					         bindhost == NULL ? "any" : bindhost, listenport);
				if (res->ai_family == AF_INET6)
					LogInfo ("Bound to IPv6 host/IP: %s, Port: %s",
					         bindhost == NULL ? "any" : bindhost, listenport);

				// we are done
				break;
			}

			// bind was unsuccessful :(
			close (sockfd);
			sockfd = -1;
		}
		res = res->ai_next;
	}

	if (sockfd < 0) {
		freeaddrinfo (ressave);
		fprintf (stderr, "Could not open the requested socket: %s\n", strerror (errno));
		LogError ("Receive socket error: could not open the requested socket", strerror (errno));
		return -1;
	}

	listen (sockfd, LISTEN_QUEUE);

	freeaddrinfo (ressave);

	if (sockbuflen) {
		if (sockbuflen < Min_SOCKBUFF_LEN) {
			sockbuflen = Min_SOCKBUFF_LEN;
			LogInfo ("I want at least %i bytes as socket buffer", sockbuflen);
		}
		optlen = sizeof (p);
		getsockopt (sockfd, SOL_SOCKET, SO_RCVBUF, &p, &optlen);
		LogInfo ("Standard setsockopt, SO_RCVBUF is %i Requested length is %i bytes", p, sockbuflen);
		if ( (setsockopt (sockfd, SOL_SOCKET, SO_RCVBUF, &sockbuflen, sizeof (sockbuflen)) != 0)) {
			fprintf (stderr, "setsockopt(SO_RCVBUF,%d): %s\n", sockbuflen, strerror (errno));
			LogError ("setsockopt(SO_RCVBUF,%d): %s", sockbuflen, strerror (errno));
			close (sockfd);
			return -1;
		} else {
			getsockopt (sockfd, SOL_SOCKET, SO_RCVBUF, &p, &optlen);
			LogInfo ("System set setsockopt, SO_RCVBUF to %d bytes", p);
		}
	}

	return sockfd;

} // End of Unicast_receive_socket
Ejemplo n.º 17
0
static nfsstat4 make_ds_handle(struct fsal_pnfs_ds *const pds,
			       const struct gsh_buffdesc *const desc,
			       struct fsal_ds_handle **const handle,
			       int flags)
{
	struct gpfs_file_handle *fh = (struct gpfs_file_handle *)desc->addr;
	struct gpfs_ds *ds;		/* Handle to be created */
	struct fsal_filesystem *fs;
	struct fsal_fsid__ fsid;

	*handle = NULL;

	if (desc->len != sizeof(struct gpfs_file_handle))
		return NFS4ERR_BADHANDLE;

	if (flags & FH_FSAL_BIG_ENDIAN) {
#if (BYTE_ORDER != BIG_ENDIAN)
		fh->handle_size = bswap_16(fh->handle_size);
		fh->handle_type = bswap_16(fh->handle_type);
		fh->handle_version = bswap_16(fh->handle_version);
		fh->handle_key_size = bswap_16(fh->handle_key_size);
#endif
	} else {
#if (BYTE_ORDER == BIG_ENDIAN)
		fh->handle_size = bswap_16(fh->handle_size);
		fh->handle_type = bswap_16(fh->handle_type);
		fh->handle_version = bswap_16(fh->handle_version);
		fh->handle_key_size = bswap_16(fh->handle_key_size);
#endif
	}
	LogFullDebug(COMPONENT_FSAL,
	  "flags 0x%X size %d type %d ver %d key_size %d FSID 0x%X:%X",
	   flags, fh->handle_size, fh->handle_type, fh->handle_version,
	   fh->handle_key_size, fh->handle_fsid[0], fh->handle_fsid[1]);

	gpfs_extract_fsid(fh, &fsid);

	fs = lookup_fsid(&fsid, GPFS_FSID_TYPE);
	if (fs == NULL) {
		LogInfo(COMPONENT_FSAL,
			"Could not find filesystem for fsid=0x%016"PRIx64
			".0x%016"PRIx64" from handle",
			fsid.major, fsid.minor);
		return NFS4ERR_STALE;
	}

	if (fs->fsal != pds->fsal) {
		LogInfo(COMPONENT_FSAL,
			"Non GPFS filesystem fsid=0x%016"PRIx64".0x%016"PRIx64
			" from handle",
			fsid.major, fsid.minor);
		return NFS4ERR_STALE;
	}

	ds = gsh_calloc(1, sizeof(struct gpfs_ds));

	*handle = &ds->ds;
	fsal_ds_handle_init(*handle, pds);

	/* Connect lazily when a FILE_SYNC4 write forces us to, not
	   here. */

	ds->connected = false;

	ds->gpfs_fs = fs->private_data;

	memcpy(&ds->wire, desc->addr, desc->len);
	return NFS4_OK;
}
Ejemplo n.º 18
0
    PetAI::PetAI(CMoveShape *owner) : BaseAI(owner)
    {
		LogInfo(AI_MODULE, "Create PetAI object, its owner\'s id is %s",
			owner->GetExID().tostring());
        m_Host = NULL;
    }
Ejemplo n.º 19
0
int CRedisUtil::UpdateEntity(const string& strEntity, const map<string, VOBJECT*>& props, TDBID dbid)
{
	int nPropsSize = 2 * (int)props.size() + 4;

	char** argv = new char*[nPropsSize];
	size_t* argvlen = new size_t[nPropsSize];

	//设置命令头
	{
		string s1("hmset");
		_CopyStringToRedisCmd2(0, s1, argv, argvlen);

		enum { _cmd_size = 64 };
		char* s = new char[_cmd_size];
		memset(s, 0, _cmd_size);
		snprintf(s, _cmd_size, "%s:%lld", strEntity.c_str(), dbid);

		argv[1] = s;
		argvlen[1] = strlen(s);

		_CopyStringToRedisCmd2(2, "timestamp", argv, argvlen);

		char szTime[32];
		memset(szTime, 0, sizeof(szTime));
		snprintf(szTime, sizeof(szTime), "%d", (int)time(NULL));
		_CopyStringToRedisCmd2(3, szTime, argv, argvlen);
	}

	//设置其他参数
	int i = 4;
	map<string, VOBJECT*>::const_iterator iter = props.begin();
	for (; iter != props.end(); ++iter)
	{
		VOBJECT* p = iter->second;
		PushVObjectToRedisCmd(i, iter->first, *(iter->second), argv, argvlen);
		i += 2;
	}

	//for(int i=0;i<nPropsSize; ++i)
	//{
	//  printf("--- %s %d\n", argv[i], argvlen[i]);
	//}

	redisReply* reply = (redisReply*)redisCommandArgv(m_redis, nPropsSize, (const char**)argv, (const size_t*)argvlen);
	if (reply && reply->str)
	{
		LogInfo("redis_UpdateEntity", "type=%s;dbid=%lld;ret=%s", strEntity.c_str(), dbid, reply->str);
	}
	else
	{
		LogError("redis_UpdateEntity_err", "dbid=%lld;err=%s", dbid, m_redis->errstr);
	}
	if (reply)
	{
		//LogDebug("freeReplyObject", "%s : %d", __FILE__, __LINE__);
		freeReplyObject(reply);
	}

	//释放argv, argvlen
	for (int i = 0; i < nPropsSize; ++i)
	{
		delete[] argv[i];
	}
	delete[] argv;
	delete[] argvlen;

	return 0;
}
Ejemplo n.º 20
0
    void PetAI::SetHost(CMoveShape *host)
    {
		LogInfo(AI_MODULE, "set host for PetAI(host=%s)",
			host->GetExID().tostring());
        m_Host = host;
    }
static void printSendStatistics(LONGHAUL_SEND_STATISTICS* stats)
{
	LogInfo("Number of Events: Sent=%lu, Received=%lu; Travel Time (secs): Min=%f, Max=%f, Average=%f",
		stats->numberOfEventsReceivedByHub, stats->numberOfEventsReceivedByHub, stats->minEventTravelTime, stats->maxEventTravelTime, stats->avgEventTravelTime);
}
void InitialGameStateExtractor::readBattleMapParts(GameState &state, const TACP &data_t,
                                                   sp<BattleMapTileset> t,
                                                   BattleMapPartType::Type type,
                                                   const UString &idPrefix, const UString &dirName,
                                                   const UString &datName, const UString &pckName,
                                                   const UString &stratPckName) const
{
	const UString loftempsFile = "xcom3/tacdata/loftemps.dat";
	const UString loftempsTab = "xcom3/tacdata/loftemps.tab";

	auto datFileName = dirName + "/" + datName + ".dat";
	auto inFile = fw().data->fs.open(datFileName);
	if (!inFile)
	{
		LogError("Failed to open mapunits DAT file at \"%s\"", datFileName);
		return;
	}
	auto fileSize = inFile.size();
	auto objectCount = fileSize / sizeof(struct BattleMapPartEntry);
	auto firstExitIdx = objectCount - 4;

	auto strategySpriteTabFileName = dirName + "/" + stratPckName + ".tab";
	auto strategySpriteTabFile = fw().data->fs.open(strategySpriteTabFileName);
	if (!strategySpriteTabFile)
	{
		LogError("Failed to open strategy sprite TAB file \"%s\"", strategySpriteTabFileName);
		return;
	}
	size_t strategySpriteCount = strategySpriteTabFile.size() / 4;

	LogInfo("Loading %zu entries from \"%s\"", objectCount, datFileName);

	for (size_t i = 0; i < objectCount; i++)
	{

		struct BattleMapPartEntry entry;
		inFile.read((char *)&entry, sizeof(entry));
		if (!inFile)
		{
			LogError("Failed to read entry %zu in \"%s\"", i, datFileName);
			return;
		}

		UString id = format("%s%u", idPrefix, i);
		auto object = mksp<BattleMapPartType>();
		if (entry.alternative_object_idx != 0)
		{
			object->alternative_map_part = {&state,
			                                format("%s%u", idPrefix, entry.alternative_object_idx)};
		}
		object->type = type;
		object->constitution = entry.constitution;
		object->explosion_power = entry.explosion_power;
		object->explosion_depletion_rate = entry.explosion_depletion_rate;
		object->explosion_type = {&state, data_t.getDTypeId(entry.explosion_type)};

		object->fire_resist = entry.fire_resist;
		object->fire_burn_time = entry.fire_burn_time;
		object->block[DamageType::BlockType::Physical] = entry.block_physical;
		object->block[DamageType::BlockType::Gas] = entry.block_gas;
		object->block[DamageType::BlockType::Fire] = entry.block_fire;
		object->block[DamageType::BlockType::Psionic] = entry.block_psionic;
		object->size = entry.size;

		object->voxelMapLOF = mksp<VoxelMap>(Vec3<int>{24, 24, 20});
		for (int slice = 0; slice < 20; slice++)
		{
			if ((unsigned int)entry.loftemps_lof[slice] == 0)
				continue;
			auto lofString = format("LOFTEMPS:%s:%s:%u", loftempsFile, loftempsTab,
			                        (unsigned int)entry.loftemps_lof[slice]);
			object->voxelMapLOF->slices[slice] = fw().data->loadVoxelSlice(lofString);
		}
		object->voxelMapLOS = mksp<VoxelMap>(Vec3<int>{24, 24, 20});
		for (int slice = 0; slice < 20; slice++)
		{
			if ((unsigned int)entry.loftemps_los[slice] == 0)
				continue;
			auto lofString = format("LOFTEMPS:%s:%s:%u", loftempsFile, loftempsTab,
			                        (unsigned int)entry.loftemps_los[slice]);
			object->voxelMapLOS->slices[slice] = fw().data->loadVoxelSlice(lofString);
		}
		if (entry.damaged_idx)
		{
			object->damaged_map_part = {&state, format("%s%u", idPrefix, entry.damaged_idx)};
		}

		// So far haven't seen an animated object with only 1 frame, but seen objects with 1 in this
		// field that are not actually animated via animated frames, therefore, ignore them
		if (entry.animation_length > 1)
		{
			auto animateTabFileName = dirName + "/" + "animate.tab";
			auto animateTabFile = fw().data->fs.open(animateTabFileName);
			if (!animateTabFile)
			{
				LogError("Failed to open animate sprite TAB file \"%s\"", animateTabFileName);
				return;
			}
			size_t animateSpriteCount = animateTabFile.size() / 4;

			if (animateSpriteCount < entry.animation_idx + entry.animation_length)
			{
				LogWarning("Bogus animation value, animation frames not present for ID %s", id);
			}
			else
			{
				for (int j = 0; j < entry.animation_length; j++)
				{
					auto animateString = format("PCK:%s%s.pck:%s%s.tab:%u", dirName, "animate",
					                            dirName, "animate", entry.animation_idx + j);
					object->animation_frames.push_back(fw().data->loadImage(animateString));
				}
			}
		}

		auto imageString =
		    format("PCK:%s%s.pck:%s%s.tab:%u", dirName, pckName, dirName, pckName, i);
		object->sprite = fw().data->loadImage(imageString);
		if (i < strategySpriteCount)
		{
			auto stratImageString = format("PCKSTRAT:%s%s.pck:%s%s.tab:%u", dirName, stratPckName,
			                               dirName, stratPckName, i);
			object->strategySprite = fw().data->loadImage(stratImageString);
		}
		// It should be {24,34} I guess, since 48/2=24, but 23 gives a little better visual
		// corellation with the sprites
		object->imageOffset = BATTLE_IMAGE_OFFSET;

		object->transparent = entry.transparent == 1;
		object->sfxIndex = entry.sfx - 1;
		object->door = entry.is_door == 1 && entry.is_door_closed == 1;
		// Unused in vanilla
		// object->los_through_terrain = entry.los_through_terrain == 1;
		// Instead we mark objects based on wether they block los or not
		// For now, we simply cheat and check several voxels
		switch (type)
		{
			case BattleMapPartType::Type::Ground:
				// Ground blocks LOS if there's something in the middle column
				for (int i = 0; i < 20; i++)
				{
					if (object->voxelMapLOS->getBit({12, 12, i}))
					{
						object->blocksLOS = true;
						break;
					}
				}
				break;
			case BattleMapPartType::Type::LeftWall:
				// Wall blocks LOS if there's something in the middle line
				for (int i = 0; i < 24; i++)
				{
					if (object->voxelMapLOS->getBit({i, 12, 10}))
					{
						object->blocksLOS = true;
						break;
					}
				}
				break;
			case BattleMapPartType::Type::RightWall:
				// Wall blocks LOS if there's something in the middle line
				for (int i = 0; i < 24; i++)
				{
					if (object->voxelMapLOS->getBit({12, i, 10}))
					{
						object->blocksLOS = true;
						break;
					}
				}
				break;
			case BattleMapPartType::Type::Feature:
				// Feature blocks LOS if there's something in the middle cross
				for (int i = 0; i < 24; i++)
				{
					if (object->voxelMapLOS->getBit({12, i, 10}) ||
					    object->voxelMapLOS->getBit({i, 12, 10}))
					{
						object->blocksLOS = true;
						break;
					}
				}
				break;
		}
		object->floor = entry.is_floor == 1;
		object->gravlift = entry.is_gravlift == 1;
		object->movement_cost = entry.movement_cost;
		object->height = entry.height;
		object->floating = entry.is_floating;
		object->provides_support = entry.provides_support;

		int gets_support_from = 0;
		switch (entry.gets_support_from)
		{
			// 32 is a mistake, it should read "0"
			case 32:
			case 0:
				break;
			case 7:
			case 20:
				object->vanillaSupportedById = entry.gets_support_from;
				break;
			// 30 is a mistake, it should read "1"
			case 30:
				gets_support_from = 1;
				break;
			default:
				gets_support_from = entry.gets_support_from;
		}
		if (gets_support_from == 36)
		{
			object->supportedByDirections.insert(MapDirection::North);
			object->supportedByDirections.insert(MapDirection::West);
			object->supportedByTypes.insert(BattleMapPartType::Type::LeftWall);
			object->supportedByTypes.insert(BattleMapPartType::Type::RightWall);
			object->supportedByTypes.insert(BattleMapPartType::Type::Feature);
		}
		else if (gets_support_from == 5)
		{
			object->supportedByAbove = true;
		}
		else if (gets_support_from)
		{
			if (gets_support_from % 10 < 1 || gets_support_from % 10 > 4)
			{
				LogError("Unrecognized support by id %d", (int)entry.gets_support_from);
				return;
			}
			object->supportedByDirections.insert((MapDirection)(gets_support_from % 10));
			switch (gets_support_from / 10)
			{
				case 0:
					break;
				case 1:
					object->supportedByTypes.insert(BattleMapPartType::Type::Ground);
					break;
				case 2:
					object->supportedByTypes.insert(BattleMapPartType::Type::Feature);
					break;
				case 4:
					object->supportedByTypes.insert(object->type);
					if (object->type != BattleMapPartType::Type::Ground)
					{
						object->supportedByTypes.insert(BattleMapPartType::Type::Ground);
					}
					break;
				case 5:
					object->supportedByTypes.insert(BattleMapPartType::Type::Ground);
					object->supportedByTypes.insert(BattleMapPartType::Type::Feature);
					break;
				default:
					LogError("Unrecognized support by id %d", (int)entry.gets_support_from);
					return;
			}
		}

		object->independent_structure = entry.independent_structure;

		if (type == BattleMapPartType::Type::Ground && i >= firstExitIdx)
			object->exit = true;

		t->map_part_types[id] = object;
	}
}
static IOTHUBMESSAGE_DISPOSITION_RESULT ReceiveMessageCallback(IOTHUB_MESSAGE_HANDLE msg, void* userContextCallback)
{
	if (userContextCallback != NULL)
	{
		EXPECTED_RECEIVE_DATA* notifyData = (EXPECTED_RECEIVE_DATA*)userContextCallback;

		if (Lock(notifyData->lock) != LOCK_OK)
		{
			LogError("Unable to lock on ReceiveMessageCallback"); /*because the test must absolutely be terminated*/
		}
		else
		{
			const char* messageId;
			const char* correlationId;
			
			const char* buffer;
			size_t size;

			if ((messageId = IoTHubMessage_GetMessageId(msg)) == NULL)
			{
				messageId = "<null>";
			}

			if ((correlationId = IoTHubMessage_GetCorrelationId(msg)) == NULL)
			{
				correlationId = "<null>";
			}

			LogInfo("Received new message from IoT Hub (message-id: %s, correlation-id: %s)", messageId, correlationId);

			if (IoTHubMessage_GetByteArray(msg, (const unsigned char**)&buffer, &size) != IOTHUB_CLIENT_OK)
			{
				LogInfo("Failed calling IoTHubMessage_GetByteArray() for new message received.");
			}
			else
			{
				if (notifyData->data == NULL)
				{
					if (size == 0)
					{
						notifyData->receivedByClient = true;

						if ((notifyData->timeReceived = time(NULL)) == INDEFINITE_TIME)
						{
							LogError("Failed setting notifyData->timeReceived (time(NULL) failed)");
						}
					}
					else
					{
						notifyData->receivedByClient = false;
					}
				}
				else
				{
					if (buffer == NULL)
					{
						notifyData->receivedByClient = false;
					}
					else
					{
						if ((size == notifyData->dataSize) && (memcmp(notifyData->data, buffer, size) == 0))
						{
							notifyData->receivedByClient = true;

							if ((notifyData->timeReceived = time(NULL)) == INDEFINITE_TIME)
							{
								LogError("Failed setting notifyData->timeReceived (time(NULL) failed)");
							}
						}
						else
						{
							notifyData->receivedByClient = false;
						}
					}
				}
			}

			Unlock(notifyData->lock);
		}
	}

	return IOTHUBMESSAGE_ACCEPTED;
}
Ejemplo n.º 24
0
bool CMMDVMHost::createDMRNetwork()
{
	if (!m_conf.getDMRNetworkEnabled())
		return false;

	std::string address  = m_conf.getDMRNetworkAddress();
	unsigned int port    = m_conf.getDMRNetworkPort();
	unsigned int id      = m_conf.getDMRId();
	std::string password = m_conf.getDMRNetworkPassword();
	bool debug           = m_conf.getDMRNetworkDebug();

	LogInfo("DMR Network Parameters");
	LogInfo("    Address: %s", address.c_str());
	LogInfo("    Port: %u", port);

	m_dmrNetwork = new CHomebrewDMRIPSC(address, port, id, password, VERSION, "MMDVMHost", debug);

	std::string callsign     = m_conf.getCallsign();
	unsigned int rxFrequency = m_conf.getRxFrequency();
	unsigned int txFrequency = m_conf.getTxFrequency();
	unsigned int power       = m_conf.getPower();
	unsigned int colorCode   = m_conf.getDMRColorCode();
	float latitude           = m_conf.getLatitude();
	float longitude          = m_conf.getLongitude();
	int height               = m_conf.getHeight();
	std::string location     = m_conf.getLocation();
	std::string description  = m_conf.getDescription();
	std::string url          = m_conf.getURL();

	LogInfo("Info Parameters");
	LogInfo("    Callsign: %s", callsign.c_str());
	LogInfo("    RX Frequency: %uHz", rxFrequency);
	LogInfo("    TX Frequency: %uHz", txFrequency);
	LogInfo("    Power: %uW", power);
	LogInfo("    Latitude: %fdeg N", latitude);
	LogInfo("    Longitude: %fdeg E", longitude);
	LogInfo("    Height: %um", height);
	LogInfo("    Location: \"%s\"", location.c_str());
	LogInfo("    Description: \"%s\"", description.c_str());
	LogInfo("    URL: \"%s\"", url.c_str());

	m_dmrNetwork->setConfig(callsign, rxFrequency, txFrequency, power, colorCode, latitude, longitude, height, location, description, url);

	bool ret = m_dmrNetwork->open();
	if (!ret) {
		delete m_dmrNetwork;
		m_dmrNetwork = NULL;
		return false;
	}

	return true;
}
Ejemplo n.º 25
0
bool PluginAuth::FullAuth(XmppHandler * xmpp, QByteArray const& data, Bunny ** pBunny, QByteArray & answer)
{
	switch(xmpp->currentAuthStep)
	{
		case 0:
			// We should receive <?xml version='1.0' encoding='UTF-8'?><stream:stream to='ojn.soete.org' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>"
			if(data.startsWith("<?xml version='1.0' encoding='UTF-8'?>"))
			{
				// Send an auth Request
				answer.append("<?xml version='1.0'?><stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='2173750751' from='xmpp.nabaztag.com' version='1.0' xml:lang='en'>");
				answer.append("<stream:features><mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><mechanism>DIGEST-MD5</mechanism><mechanism>PLAIN</mechanism></mechanisms><register xmlns='http://violet.net/features/violet-register'/></stream:features>");
				xmpp->currentAuthStep = 1;
				return true;
			}
			LogError("Bad Auth Step 0, disconnect");
			return false;
			
		case 1:
			{
				// Bunny request a register <iq type='get' id='1'><query xmlns='violet:iq:register'/></iq>
				IQ iq(data);
				if(iq.IsValid() && iq.Type() == IQ::Iq_Get && iq.Content() == "<query xmlns='violet:iq:register'/>")
				{
					// Send the request
					answer = iq.Reply(IQ::Iq_Result, "from='" + xmpp->GetXmppDomain() + "' %1 %4", "<query xmlns='violet:iq:register'><instructions>Choose a username and password to register with this server</instructions><username/><password/></query>");
					xmpp->currentAuthStep = 100;
					return true;
				}
				// Bunny request an auth <auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>
				if(data.startsWith("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>"))
				{
					// Send a challenge
					// <challenge xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>...</challenge>
					// <challenge xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>nonce="random_number",qop="auth",charset=utf-8,algorithm=md5-sess</challenge>
					QByteArray nonce = QByteArray::number((unsigned int)qrand());
					QByteArray challenge = "nonce=\"" + nonce + "\",qop=\"auth\",charset=utf-8,algorithm=md5-sess";
					answer.append("<challenge xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>" + challenge.toBase64() + "</challenge>");
					xmpp->currentAuthStep = 2;
					return true;
				}
				LogError("Bad Auth Step 1, disconnect");
				return false;
			}
			
		case 2:
			{
				// We should receive <response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>...</response>
				QRegExp rx("<response[^>]*>(.*)</response>");
				if (rx.indexIn(data) != -1)
				{
					QByteArray authString = QByteArray::fromBase64(rx.cap(1).toAscii()).replace((char)0, "");
					// authString is like : username="",nonce="",cnonce="",nc=,qop=auth,digest-uri="",response=,charset=utf-8
					// Parse values
					rx.setPattern("username=\"([^\"]*)\",nonce=\"([^\"]*)\",cnonce=\"([^\"]*)\",nc=([^,]*),qop=auth,digest-uri=\"([^\"]*)\",response=([^,]*),charset=utf-8");
					if(rx.indexIn(authString) != -1)
					{
						QByteArray const username = rx.cap(1).toAscii();
						Bunny * bunny = BunnyManager::GetBunny(username);

						// Check if we want to bypass auth for this bunny
						if((GlobalSettings::Get("Config/StandAloneAuthBypass", false)) == true && (username == GlobalSettings::GetString("Config/StandAloneAuthBypassBunny")))
						{
							// Send success
							LogInfo("Sending success instead of password verification");
							answer.append("<success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>");

							bunny->Authenticating();
							*pBunny = bunny; // Auth OK, set current bunny

							xmpp->currentAuthStep = 4;
							return true;
						}


						QByteArray const password = bunny->GetBunnyPassword();
						QByteArray const nonce = rx.cap(2).toAscii();
						QByteArray const cnonce = rx.cap(3).toAscii().append((char)0); // cnonce have a dummy \0 at his end :(
						QByteArray const nc = rx.cap(4).toAscii();
						QByteArray const digest_uri = rx.cap(5).toAscii();
						QByteArray const bunnyResponse = rx.cap(6).toAscii();
						if(bunnyResponse == ComputeResponse(username, password, nonce, cnonce, nc, digest_uri, "AUTHENTICATE"))
						{
							// Send challenge back
							// <challenge xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>...</challenge>
							// rspauth=...
							QByteArray const rspAuth = "rspauth=" + ComputeResponse(username, password, nonce, cnonce, nc, digest_uri, "");
							answer.append("<challenge xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>" + rspAuth.toBase64() + "</challenge>");

							bunny->Authenticating();
							*pBunny = bunny; // Auth OK, set current bunny

							xmpp->currentAuthStep = 3;
							return true;
						}

						LogError("Authentication failure for bunny");
						// Bad password, send failure and restart auth
						answer.append("<failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><not-authorized/></failure>");
						xmpp->currentAuthStep = 0;
						return true;
					}
				}
				LogError("Bad Auth Step 2, disconnect");
				return false;
			}
			
		case 3:
			// We should receive <response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>
			if(data.startsWith("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>"))
			{
				// Send success
				answer.append("<success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>");
				xmpp->currentAuthStep = 4;
				return true;
			}
			LogError("Bad Auth Step 3, disconnect");
			return false;
			
		case 4:
			// We should receive <?xml version='1.0' encoding='UTF-8'?>
			if(data.startsWith("<?xml version='1.0' encoding='UTF-8'?>"))
			{
				// Send success
				answer.append("<?xml version='1.0'?><stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='1331400675' from='xmpp.nabaztag.com' version='1.0' xml:lang='en'>");
				answer.append("<stream:features><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><required/></bind><unbind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/><session xmlns='urn:ietf:params:xml:ns:xmpp-session'/></stream:features>");
				xmpp->currentAuthStep = 0;
				(*pBunny)->Authenticated();
				(*pBunny)->SetXmppHandler(xmpp);
				// Bunny is now authenticated
				return true;
			}
			LogError("Bad Auth Step 4, disconnect");
			return false;


		case 100: // Register Bunny
			{
				// We should receive <iq to='xmpp.nabaztag.com' type='set' id='2'><query xmlns="violet:iq:register"><username>0019db01dbd7</username><password>208e6d83bfb2</password></query></iq>
				IQ iqAuth(data);
				if(iqAuth.IsValid() && iqAuth.Type() == IQ::Iq_Set)
				{
					QByteArray content = iqAuth.Content();
					QRegExp rx("<query xmlns=\"violet:iq:register\"><username>([0-9a-f]*)</username><password>([0-9a-f]*)</password></query>");
					if(rx.indexIn(content) != -1)
					{
						QByteArray user = rx.cap(1).toAscii();
						QByteArray password = rx.cap(2).toAscii();
						Bunny * bunny = BunnyManager::GetBunny(user);
						if(bunny->SetBunnyPassword(ComputeXor(user,password)))
						{
							answer.append(iqAuth.Reply(IQ::Iq_Result, "%1 %2 %3 %4", content));
							xmpp->currentAuthStep = 1;
							return true;
						}
						LogError(QString("Password already set for bunny : ").append(QString(user)));
						return false;
					}
				}
				LogError("Bad Register, disconnect");
				return false;
			}
			
		default:
			LogError("Unknown Auth Step, disconnect");
			return false;
	}
}
Ejemplo n.º 26
0
int CMMDVMHost::run()
{
	bool ret = m_conf.read();
	if (!ret) {
		::fprintf(stderr, "MMDVMHost: cannot read the .ini file\n");
		return 1;
	}

	ret = ::LogInitialise(m_conf.getLogPath(), m_conf.getLogRoot(), m_conf.getLogDisplay());
	if (!ret) {
		::fprintf(stderr, "MMDVMHost: unable to open the log file\n");
		return 1;
	}

	::LogSetLevel(m_conf.getLogLevel());

	LogInfo(HEADER1);
	LogInfo(HEADER2);
	LogInfo(HEADER3);

	LogMessage("MMDVMHost-%s is starting", VERSION);

	readParams();

	ret = createModem();
	if (!ret)
		return 1;

	createDisplay();

	if (m_dmrEnabled) {
		ret = createDMRNetwork();
		if (!ret)
			return 1;
	}

	CTimer dmrBeaconTimer(1000U, 4U);
	bool dmrBeaconsEnabled = m_dmrEnabled && m_conf.getDMRBeacons();

	CStopWatch stopWatch;
	stopWatch.start();

	CDStarEcho* dstar = NULL;
	if (m_dstarEnabled)
		dstar = new CDStarEcho(2U, 10000U);

	CDMRControl* dmr = NULL;
	if (m_dmrEnabled) {
		unsigned int id        = m_conf.getDMRId();
		unsigned int colorCode = m_conf.getDMRColorCode();
		unsigned int timeout   = m_conf.getTimeout();

		LogInfo("DMR Parameters");
		LogInfo("    Id: %u", id);
		LogInfo("    Color Code: %u", colorCode);
		LogInfo("    Timeout: %us", timeout);

		dmr = new CDMRControl(id, colorCode, timeout, m_modem, m_dmrNetwork, m_display);
	}

	CYSFEcho* ysf = NULL;
	if (m_ysfEnabled)
		ysf = new CYSFEcho(2U, 10000U);

	unsigned char mode = MODE_IDLE;
	CTimer modeTimer(1000U, m_conf.getModeHang());

	m_display->setIdle();

	while (!m_killed) {
		unsigned char data[200U];
		unsigned int len;
		bool ret;

		len = m_modem->readDStarData(data);
		if (dstar != NULL && len > 0U) {
			if (mode == MODE_IDLE && (data[0U] == TAG_HEADER || data[0U] == TAG_DATA)) {
				LogMessage("Mode set to D-Star");
				mode = MODE_DSTAR;
				m_display->setDStar();
				m_modem->setMode(MODE_DSTAR);
				modeTimer.start();
			}
			if (mode != MODE_DSTAR) {
				LogWarning("D-Star data received when in mode %u", mode);
			} else {
				if (data[0U] == TAG_HEADER || data[0U] == TAG_DATA || data[0U] == TAG_EOT) {
					dstar->writeData(data, len);
					modeTimer.start();
				}
			}
		}

		len = m_modem->readDMRData1(data);
		if (dmr != NULL && len > 0U) {
			if (mode == MODE_IDLE) {
				bool ret = dmr->processWakeup(data);
				if (ret) {
					LogMessage("Mode set to DMR");
					mode = MODE_DMR;
					m_display->setDMR();
					// This sets the mode to DMR within the modem
					m_modem->writeDMRStart(true);
					modeTimer.start();
				}
			} else if (mode == MODE_DMR) {
				dmr->writeModemSlot1(data);
				dmrBeaconTimer.stop();
				modeTimer.start();
			} else {
				LogWarning("DMR data received when in mode %u", mode);
			}
		}

		len = m_modem->readDMRData2(data);
		if (dmr != NULL && len > 0U) {
			if (mode == MODE_IDLE) {
				bool ret = dmr->processWakeup(data);
				if (ret) {
					LogMessage("Mode set to DMR");
					mode = MODE_DMR;
					m_display->setDMR();
					// This sets the mode to DMR within the modem
					m_modem->writeDMRStart(true);
					modeTimer.start();
				}
			} else if (mode == MODE_DMR) {
				dmr->writeModemSlot2(data);
				dmrBeaconTimer.stop();
				modeTimer.start();
			} else {
				LogWarning("DMR data received when in mode %u", mode);
			}
		}

		len = m_modem->readYSFData(data);
		if (ysf != NULL && len > 0U) {
			if (mode == MODE_IDLE && data[0U] == TAG_DATA) {
				LogMessage("Mode set to System Fusion");
				mode = MODE_YSF;
				m_display->setFusion();
				m_modem->setMode(MODE_YSF);
				modeTimer.start();
			}
			if (mode != MODE_YSF) {
				LogWarning("System Fusion data received when in mode %u", mode);
			} else {
				if (data[0U] == TAG_DATA) {
					data[1U] = 0x00U;		// FICH digest
					ysf->writeData(data, len);
					modeTimer.start();
				}
			}
		}

		if (modeTimer.isRunning() && modeTimer.hasExpired()) {
			LogMessage("Mode set to Idle");

			if (mode == MODE_DMR)
				m_modem->writeDMRStart(false);

			mode = MODE_IDLE;
			m_display->setIdle();
			m_modem->setMode(MODE_IDLE);
			modeTimer.stop();
		}

		if (dstar != NULL) {
			ret = dstar->hasData();
			if (ret) {
				ret = m_modem->hasDStarSpace();
				if (ret) {
					len = dstar->readData(data);
					if (mode != MODE_DSTAR) {
						LogWarning("D-Star echo data received when in mode %u", mode);
					} else {
						m_modem->writeDStarData(data, len);
						modeTimer.start();
					}
				}
			}
		}

		if (dmr != NULL) {
			ret = m_modem->hasDMRSpace1();
			if (ret) {
				len = dmr->readModemSlot1(data);
				if (len > 0U && mode == MODE_IDLE) {
					m_display->setDMR();
					mode = MODE_DMR;
				}
				if (len > 0U && mode == MODE_DMR) {
					m_modem->writeDMRData1(data, len);
					dmrBeaconTimer.stop();
					modeTimer.start();
				}
			}

			ret = m_modem->hasDMRSpace2();
			if (ret) {
				len = dmr->readModemSlot2(data);
				if (len > 0U && mode == MODE_IDLE) {
					m_display->setDMR();
					mode = MODE_DMR;
				}
				if (len > 0U && mode == MODE_DMR) {
					m_modem->writeDMRData2(data, len);
					dmrBeaconTimer.stop();
					modeTimer.start();
				}
			}
		}

		if (ysf != NULL) {
			ret = ysf->hasData();
			if (ret) {
				ret = m_modem->hasYSFSpace();
				if (ret) {
					len = ysf->readData(data);
					if (mode != MODE_YSF) {
						LogWarning("System Fusion echo data received when in mode %u", mode);
					} else {
						m_modem->writeYSFData(data, len);
						modeTimer.start();
					}
				}
			}
		}

		if (m_dmrNetwork != NULL) {
			bool run = m_dmrNetwork->wantsBeacon();

			if (dmrBeaconsEnabled && run && mode == MODE_IDLE) {
				mode = MODE_DMR;
				m_modem->writeDMRStart(true);
				dmrBeaconTimer.start();
			}
		}

		unsigned int ms = stopWatch.elapsed();
		m_modem->clock(ms);
		modeTimer.clock(ms);
		if (dstar != NULL)
			dstar->clock(ms);
		if (dmr != NULL)
			dmr->clock(ms);
		if (ysf != NULL)
			ysf->clock(ms);
		stopWatch.start();

		dmrBeaconTimer.clock(ms);
		if (dmrBeaconTimer.isRunning() && dmrBeaconTimer.hasExpired()) {
			dmrBeaconTimer.stop();
			m_modem->writeDMRStart(false);
			mode = MODE_IDLE;
		}

		if (ms < 5U) {
#if defined(_WIN32) || defined(_WIN64)
			::Sleep(5UL);		// 5ms
#else
			::usleep(5000);		// 5ms
#endif
		}
	}

	LogMessage("MMDVMHost is exiting on receipt of SIGHUP1");

	m_display->setIdle();

	m_modem->close();
	delete m_modem;

	m_display->close();
	delete m_display;

	if (m_dmrNetwork != NULL) {
		m_dmrNetwork->close();
		delete m_dmrNetwork;
	}

	delete dstar;
	delete dmr;
	delete ysf;

	return 0;
}
Ejemplo n.º 27
0
_Use_decl_annotations_
NDIS_STATUS
FilterPause(
    NDIS_HANDLE                     FilterModuleContext,
    PNDIS_FILTER_PAUSE_PARAMETERS   PauseParameters
    )
/*++

Routine Description:

    Filter pause routine.
    Complete all the outstanding sends and queued sends,
    wait for all the outstanding recvs to be returned
    and return all the queued receives.

Arguments:

    FilterModuleContext - pointer to the filter context stucture
    PauseParameters     - additional information about the pause

Return Value:

    NDIS_STATUS_SUCCESS if filter pauses successfully, NDIS_STATUS_PENDING
    if not.  No other return value is allowed (pause must succeed, eventually).

N.B.: When the filter is in Pausing state, it can still process OID requests, 
    complete sending, and returning packets to NDIS, and also indicate status.
    After this function completes, the filter must not attempt to send or 
    receive packets, but it may still process OID requests and status 
    indications.

--*/
{
    PMS_FILTER      pFilter = (PMS_FILTER)(FilterModuleContext);
    NDIS_STATUS     Status = STATUS_SUCCESS;

    UNREFERENCED_PARAMETER(PauseParameters);

    LogFuncEntryMsg(DRIVER_DEFAULT, "Filter: %p", FilterModuleContext);

    //
    // Set the flag that the filter is going to pause
    //
    NT_ASSERT(pFilter->State == FilterRunning);
    NdisAcquireSpinLock(&FilterListLock);
    pFilter->State = FilterPausing;
    NdisReleaseSpinLock(&FilterListLock);

    //
    // Send final notification of interface removal
    //
    otLwfNotifyDeviceAvailabilityChange(pFilter, FALSE);
    LogInfo(DRIVER_DEFAULT, "Interface %!GUID! removal.", &pFilter->InterfaceGuid);

    //
    // Disable external references and wait for existing calls to complete
    //
    LogInfo(DRIVER_DEFAULT, "Disabling and waiting for external references to release");
    ExWaitForRundownProtectionRelease(&pFilter->ExternalRefs);
    LogInfo(DRIVER_DEFAULT, "External references released.");

    //
    // Clean up based on the device mode
    //
    if (pFilter->DeviceStatus == OTLWF_DEVICE_STATUS_RADIO_MODE)
    {
        otLwfUninitializeThreadMode(pFilter);
    }
    else if (pFilter->DeviceStatus == OTLWF_DEVICE_STATUS_THREAD_MODE)
    {
        otLwfTunUninitialize(pFilter);
    }

    pFilter->DeviceStatus = OTLWF_DEVICE_STATUS_UNINTIALIZED;

    //
    // Clean up the Spinel command processing
    //
    otLwfCmdUninitialize(pFilter);

    //
    // Set the state back to Paused now that we are done
    //
    pFilter->State = FilterPaused;

    LogFuncExitNDIS(DRIVER_DEFAULT, Status);
    return Status;
}
Ejemplo n.º 28
0
void CPaiJiuPeerCard::SetPeerCardCompsiteNumber( unsigned char nA , unsigned char nB )
{
	m_Card[0].RsetCardByCompositeNum(nA);
	m_Card[1].RsetCardByCompositeNum(nB);

	// comfir type ;
	m_nSelftWeight = 0 ;
	unsigned char AFaceN = m_Card[0].GetCardFaceNum();
	unsigned char BFaceN = m_Card[1].GetCardFaceNum() ;
	CCard::eCardType AType = m_Card[0].GetType();
	CCard::eCardType BType = m_Card[1].GetType();
	if ( SPECAIL_PAIR_RED(12))
	{
		m_nSelftWeight = 100 ;
		m_strName = "双天";
	}
	else if ( SPECAIL_PAIR_RED(2))
	{
		m_nSelftWeight = 99 ;
		m_strName = "双地";
	}
	else if ( CAN_PAIR(AFaceN,BFaceN,1,3) && CAN_PAIR(AType,BType,CCard::eCard_Sword,CCard::eCard_Sword) )
	{
		m_nSelftWeight =98;
		m_strName = "至尊";
	}
	else if ( SPECAIL_PAIR_RED(8))
	{
		m_nSelftWeight = 97 ;
		m_strName = "双人";
	}
	else if ( SPECAIL_PAIR_RED(4) )
	{
		m_nSelftWeight = 96 ;
		m_strName = "双鹅";
	}
	else if ( SPECAIL_PAIR_RED(6) || SPECAIL_PAIR_RED(10) || SPECAIL_PAIR_BLACK(4) )
	{
		m_nSelftWeight = 95;
		if ( BFaceN == 6 )
		{
			m_strName = "双零霖六" ;
		}
		else if ( BFaceN == 10 )
		{
			m_strName = "双红头十" ;
		}
		else if ( BFaceN == 4 )
		{
			m_strName = "双板凳" ;
		}
	}
	else if ( SPECAIL_PAIR_BLACK(6) || SPECAIL_PAIR_RED(7) || SPECAIL_PAIR_BLACK(10) || SPECAIL_PAIR_BLACK(11))
	{
		m_nSelftWeight = 94;
		
		if ( AFaceN == 6 )
		{
			m_strName = "双长三";
		}
		else if ( 7 == AFaceN )
		{
			m_strName = "双高脚七";
		}
		else if ( 10 == AFaceN )
		{
			m_strName = "双梅花";
		}
		else if ( 11 == AFaceN )
		{
			m_strName = "斧头";
		}
	}

	else if ( SPECAIL_PAIR_RED(5) || SPECAIL_PAIR_BLACK(7) || SPECAIL_PAIR_BLACK(8) || SPECAIL_PAIR_RED(9))
	{
		m_nSelftWeight = 93;
		
		if ( 5 == AFaceN )
		{
			m_strName = "双杂五";
		}
		else if ( 7 == AFaceN) 
		{
			m_strName = "双杂七";
		}
		else if ( 8 == AFaceN )
		{
			m_strName = "双杂八";
		}
		else if ( 9 == AFaceN )
		{
			m_strName = "双杂九";
		}
	}
	else if ( CAN_PAIR(AFaceN,BFaceN,12,9))
	{
		m_nSelftWeight = 92 ;
		m_strName = "天九王";
	}
	else if ( CAN_PAIR(AFaceN,BFaceN,12,8 ) )
	{
		m_nSelftWeight = 91 ;
		m_strName = "天杠";
	}
	else if ( CAN_PAIR(AFaceN,BFaceN,2,8))
	{
		m_nSelftWeight = 90 ;
		m_strName = "地杠";
	}
	else
	{
		if ( AFaceN == 1 )
		{
			AFaceN = 6 ;
		}

		if ( BFaceN == 1 )
		{
			BFaceN = 6 ;
		}
		m_nSelftWeight = (AFaceN + BFaceN )%10;
		
		if ( CAN_PAIR(AFaceN,BFaceN,12,7))
		{
			m_strName = "天九" ;
		}
		else if ( CAN_PAIR(AFaceN,BFaceN,2,7))
		{
			m_strName = "地九" ;
		}
		else
		{
			char pBuffer[10] = { 0 } ;
			sprintf(pBuffer, "%d点",m_nSelftWeight ) ;
			m_strName = pBuffer ;
		}
	}

#ifdef _DEBUG
	LogInfo();
#endif
} 
Ejemplo n.º 29
0
void JavaScriptEngine::ReportError(JSContext *cx, const char *message,
		JSErrorReport *report) {
	LogInfo(TAG, "file is %s,line number is %u, message is :%s\n",
			report->filename ? report->filename : "",
			(unsigned int) report->lineno, message);
}
Ejemplo n.º 30
0
Data::Data(Framework &fw, std::vector<UString> paths, int imageCacheSize, int imageSetCacheSize,
           int voxelCacheSize)
{
	for (auto &imageBackend : *registeredImageBackends)
	{
		auto t = imageBackend.first;
		ImageLoader *l = imageBackend.second->create();
		if (l)
		{
			this->imageLoaders.emplace_back(l);
			LogInfo("Initialised image loader %s", t.c_str());
		}
		else
			LogWarning("Failed to load image loader %s", t.c_str());
	}

	for (auto &sampleBackend : *registeredSampleLoaders)
	{
		auto t = sampleBackend.first;
		SampleLoader *s = sampleBackend.second->create(fw);
		if (s)
		{
			this->sampleLoaders.emplace_back(s);
			LogInfo("Initialised sample loader %s", t.c_str());
		}
		else
			LogWarning("Failed to load sample loader %s", t.c_str());
	}

	for (auto &musicLoader : *registeredMusicLoaders)
	{
		auto t = musicLoader.first;
		MusicLoader *m = musicLoader.second->create(fw);
		if (m)
		{
			this->musicLoaders.emplace_back(m);
			LogInfo("Initialised music loader %s", t.c_str());
		}
		else
			LogWarning("Failed to load music loader %s", t.c_str());
	}
	this->writeDir = PHYSFS_getPrefDir(PROGRAM_ORGANISATION, PROGRAM_NAME);
	LogInfo("Setting write directory to \"%s\"", this->writeDir.c_str());
	PHYSFS_setWriteDir(this->writeDir.c_str());
	for (int i = 0; i < imageCacheSize; i++)
		pinnedImages.push(nullptr);
	for (int i = 0; i < imageSetCacheSize; i++)
		pinnedImageSets.push(nullptr);
	for (int i = 0; i < voxelCacheSize; i++)
		pinnedLOFVoxels.push(nullptr);

	// Paths are supplied in inverse-search order (IE the last in 'paths' should be the first
	// searched)
	for (auto &p : paths)
	{
		if (!PHYSFS_mount(p.c_str(), "/", 0))
		{
			LogWarning("Failed to add resource dir \"%s\"", p.c_str());
			continue;
		}
		else
			LogInfo("Resource dir \"%s\" mounted to \"%s\"", p.c_str(),
			        PHYSFS_getMountPoint(p.c_str()));
	}
	// Finally, the write directory trumps all
	PHYSFS_mount(this->writeDir.c_str(), "/", 0);
}