Exemplo n.º 1
0
static void EsifDataLogFire(int isHeader)
{
	int i = 0;
	char outLine[MAX_LOG_LINE] = { 0 };
	EsifLogType logtype = ESIF_LOG_UI;
	time_t now = time(NULL);
	struct tm time = { 0 };
	esif_ccb_time_t msec = 0;

	esif_ccb_system_time(&msec);

	if (isHeader > 0) {
		esif_ccb_sprintf(MAX_LOG_LINE, outLine, "Time,Server Msec,");
	}
	else {
		if (esif_ccb_localtime(&time, &now) == 0) {
				esif_ccb_sprintf(MAX_LOG_LINE, outLine, "%04d-%02d-%02d %02d:%02d:%02d,%llu,",
					time.tm_year + 1900, time.tm_mon + 1, time.tm_mday, time.tm_hour, time.tm_min, time.tm_sec, msec);
		}
	}
	for (i = 0; i < MAX_PARTICIPANT_ENTRY; i++) {
		eEsifError rc = ESIF_OK;
		DataLogParticipant currentParticipant = g_dataLogParticipants[i];

		if (currentParticipant.participantNumFields > 0) {
			rc = EsifDataLogAddParticipant(outLine, i, isHeader);
		}
	}
	EsifLogFile_Write(logtype, "%s\n", outLine);
}
Exemplo n.º 2
0
// backwards compatibility
eEsifError EsifConfigSet (
	EsifDataPtr nameSpace,
	EsifDataPtr path,
	esif_flags_t flags,
	EsifDataPtr value
	)
{
	eEsifError rc = ESIF_OK;

	// Get the NameSpace or create it if it does not exist
	DataVaultPtr DB = DataBank_GetNameSpace(g_DataBankMgr, (StringPtr)(nameSpace->buf_ptr));
	if (!DB) {
		struct esif_ccb_file dv_file = {0};
		DB = DataBank_OpenNameSpace(g_DataBankMgr, (StringPtr)nameSpace->buf_ptr);
		if (!DB) {
			return ESIF_E_NOT_FOUND;
		}

		// esif_ccb_sprintf(MAX_PATH, dv_file.filename, "%s%s", esif_build_path(dv_file.filename, MAX_PATH, NULL, DB->name), ESIFDV_FILEEXT);
		esif_ccb_sprintf(MAX_PATH, dv_file.filename, "%s%s%s", ESIFDV_DIR, DB->name, ESIFDV_FILEEXT);
		IOStream_SetFile(DB->stream, dv_file.filename, "rb");
		rc = DataVault_ReadVault(DB);
		if (rc == ESIF_E_NOT_FOUND) {
			rc = ESIF_OK;
		}
	}
	if (rc == ESIF_OK) {
		rc = DataVault_SetValue(DB, path, value, flags);
	}
	return rc;
}
Exemplo n.º 3
0
// Automatically Load all Static DataVaults and *.dv files in the current folder into the DataBank
eEsifError DataBank_LoadDataVaults (DataBankPtr self)
{
	eEsifError rc = ESIF_OK;
	esif_ccb_file_find_handle find_handle = INVALID_HANDLE_VALUE;
	char file_path[MAX_PATH] = {0};
	char file_pattern[MAX_PATH] = {0};
	struct esif_ccb_file *ffd_ptr;
	UInt32 idx;

	ASSERT(self);

	// Import all Static DataVaults into ReadOnly DataVaults
	for (idx = 0; g_StaticDataVaults[idx].name; idx++) {
		DataVaultPtr DB = DataBank_OpenNameSpace(self, g_StaticDataVaults[idx].name);
		if (DB) {
			IOStream_SetMemory(DB->stream, g_StaticDataVaults[idx].buffer, g_StaticDataVaults[idx].buf_len);
			DB->flags |= (ESIF_SERVICE_CONFIG_READONLY | ESIF_SERVICE_CONFIG_NOCACHE);
			DataVault_ReadVault(DB);
		}
	}

	// Create DataVault Directory if it doesn't exit
	esif_build_path(file_path, sizeof(file_path), ESIF_PATHTYPE_DV, NULL, NULL);
	esif_ccb_makepath(file_path);

	// Import all matching *.dv files into ReadWrite DataVaults
	esif_ccb_sprintf(MAX_PATH, file_pattern, "*%s", ESIFDV_FILEEXT);
	ffd_ptr   = (struct esif_ccb_file*)esif_ccb_malloc(sizeof(*ffd_ptr));
	if (NULL == ffd_ptr) {
		rc = ESIF_E_NO_MEMORY;
	}

	if (rc == ESIF_OK) {
		find_handle = esif_ccb_file_enum_first(file_path, file_pattern, ffd_ptr);
	}
	if (INVALID_HANDLE_VALUE != find_handle) {
		do {
			struct esif_ccb_file dv_file = {0};
			DataVaultPtr DB = 0;

			// Read DataVault File, unless it's already been loaded as a Static DataVault
			if (esif_ccb_strlen(ffd_ptr->filename, MAX_PATH) > sizeof(ESIFDV_FILEEXT)) {
				ffd_ptr->filename[esif_ccb_strlen(ffd_ptr->filename, MAX_PATH) - (sizeof(ESIFDV_FILEEXT) - 1)] = 0;	// Truncate ".dv" extension
				if (DataBank_GetNameSpace(self, ffd_ptr->filename) == NULL) {
					DB = DataBank_OpenNameSpace(self, ffd_ptr->filename);
					if (DB) {
						esif_build_path(dv_file.filename, sizeof(dv_file.filename), ESIF_PATHTYPE_DV, DB->name, ESIFDV_FILEEXT);
						IOStream_SetFile(DB->stream, dv_file.filename, "rb");
						DataVault_ReadVault(DB);
					}
				}
			}
		} while (esif_ccb_file_enum_next(find_handle, file_pattern, ffd_ptr));
		esif_ccb_file_enum_close(find_handle);
	}
	esif_ccb_free(ffd_ptr);
	return rc;
}
Exemplo n.º 4
0
void esif_ws_server_set_ipaddr_port(const char *ipaddr, u32 portPtr, Bool restricted)
{
	if (ipaddr == NULL) {
		ipaddr = (restricted ? WEBSOCKET_RESTRICTED_IPADDR : WEBSOCKET_DEFAULT_IPADDR);
	}
	if (portPtr == 0) {
		portPtr = atoi(restricted ? WEBSOCKET_RESTRICTED_PORT : WEBSOCKET_DEFAULT_PORT);
	}
	esif_ccb_strcpy(g_ws_ipaddr, ipaddr, sizeof(g_ws_ipaddr));
	esif_ccb_sprintf(sizeof(g_ws_port), g_ws_port, "%d", portPtr);
	g_ws_restricted = restricted;
}
Exemplo n.º 5
0
void ipc_connect ()
{
	g_ipc_handle = esif_ipc_connect((char*)SESSION_ID);
	if (g_ipc_handle != ESIF_INVALID_HANDLE) {
		char *kern_str = esif_cmd_info(g_out_buf);
		ESIF_TRACE_DEBUG("ESIF IPC Kernel Device Opened\n");
		if (NULL != kern_str) {
			ESIF_TRACE_DEBUG("%s", kern_str);
			esif_ccb_sprintf(sizeof(g_esif_kernel_version), g_esif_kernel_version, "%s", kern_str);
		}
	}
}
Exemplo n.º 6
0
/* IPC OS Connect */
esif_handle_t esif_os_ipc_connect(char *session_id)
{
	int fd = 0;
	char device[MAX_PATH] = { 0 };

	esif_ccb_sprintf(sizeof(device), device, "/dev/%s", IPC_DEVICE);
	fd = open(device, O_RDWR);

	ESIF_TRACE_DEBUG("linux_%s: session_id=%s device=%s handle=%d\n",
			 __func__, session_id, device, fd);
	return fd;
}
Exemplo n.º 7
0
static void esif_ws_http_send_error_code (
	ClientRecordPtr connection,
	int error_code
	)
{
	char buffer[MAX_PATH]={0};
	char *message = (error_code==404 ? "Not Found" : "Error");

	esif_ccb_sprintf(sizeof(buffer), buffer, (char*)"HTTP/1.1 %d %s\r\n\r\n<h1>%d %s</h1>", error_code, message, error_code, message);

	send(connection->socket, buffer, (int)esif_ccb_strlen(buffer, sizeof(buffer)), ESIF_WS_SEND_FLAGS);
	esif_ws_client_close_client(connection);
}
Exemplo n.º 8
0
// Write to Transaction Log
// NOTE: This version is just a dumb text log, not a recoverable transaction log
//
static void DataVault_WriteLog (
	DataVaultPtr self,
	esif_string action,
	esif_string nameSpace,
	EsifDataPtr path,
	esif_flags_t flags,
	EsifDataPtr value
	)
{
#ifdef ESIF_CONFIG_LOG
	UNREFERENCED_PARAMETER(self);
	UNREFERENCED_PARAMETER(action);
	UNREFERENCED_PARAMETER(nameSpace);
	UNREFERENCED_PARAMETER(path);
	UNREFERENCED_PARAMETER(flags);
	UNREFERENCED_PARAMETER(value);
#else
	struct esif_ccb_file log_file = {0};
	FILE *filePtr = NULL;
	time_t now;
	char theTime[30];

	UNREFERENCED_PARAMETER(self);

	if (!flags) {
		return;
	}

	esif_ccb_sprintf(MAX_PATH, log_file.filename, "%s%s", esif_build_path(log_file.filename, MAX_PATH, ESIF_DIR_LOG, (EsifString)nameSpace), ESIFDV_LOGFILEEXT);
	esif_ccb_fopen(&filePtr, log_file.filename, "ab");
	if (NULL == filePtr) {
		return;
	}

	time(&now);
	esif_ccb_ctime(theTime, sizeof(theTime), &now);
	esif_ccb_fprintf(filePtr, "%.24s: %-6s %s flags=%d",
					 theTime,
					 action,
					 (EsifString)path->buf_ptr,
					 flags);
	if (NULL != value) {
		UInt32 ch;
		esif_ccb_fprintf(filePtr, " type=%d buf_len=%d data_len=%d buf_ptr=%s", value->type, value->buf_len, value->data_len, (value->buf_ptr ? "0x" : "NULL"));
		for (ch = 0; NULL != value->buf_ptr && ch < value->data_len; ch++)
			esif_ccb_fprintf(filePtr, "%02X", (int)((UInt8*)(value->buf_ptr))[ch]);
	}
	esif_ccb_fprintf(filePtr, "\r\n");
	fclose(filePtr);
#endif
}
Exemplo n.º 9
0
static void esif_ws_http_send_error_code (
	int fd,
	int error_code
	)
{
	char buffer[BUFFER_LENGTH];

	error_code = error_code;

	(void)esif_ccb_sprintf(BUFFER_LENGTH, buffer, (char*)"HTTP/1.1 404 Not Found\r\n\r\n");

	(void)send(fd, buffer, (int)esif_ccb_strlen(buffer, MAX_SIZE), 0);
	esif_uf_ccb_sock_close(fd);
}
Exemplo n.º 10
0
static eEsifError GetPrompt(
	EsifAppMgr *THIS,
	EsifDataPtr promptPtr
	)
{
	enum esif_rc rc = ESIF_OK;
	EsifAppPtr a_app_ptr = THIS->fSelectedAppPtr;
	if (NULL == a_app_ptr) {
		esif_ccb_sprintf(promptPtr->buf_len, (esif_string)promptPtr->buf_ptr, "esif(%u)->", g_dst);
	} else {
		ESIF_DATA(data_prompt, ESIF_DATA_STRING, promptPtr->buf_ptr, promptPtr->buf_len);
		rc = a_app_ptr->fInterface.fAppGetPromptFuncPtr(a_app_ptr->fHandle, &data_prompt);
	}
	return rc;
}
Exemplo n.º 11
0
// IPC Connect
eEsifError ipc_connect()
{
	eEsifError rc = ESIF_OK;
	int check_kernel_version = ESIF_TRUE;

	ESIF_TRACE_ENTRY_INFO();

	// Exit if IPC already connected
	if (g_ipc_handle != ESIF_INVALID_HANDLE) {
		return ESIF_OK;
	}

	// Connect to LF
	g_ipc_handle = esif_ipc_connect((char *)SESSION_ID);
	if (g_ipc_handle == ESIF_INVALID_HANDLE) {
		ESIF_TRACE_WARN("ESIF LF is not available\n");
		rc = ESIF_E_NO_LOWER_FRAMEWORK;
	}
	else {
		char *outbuf = esif_ccb_malloc(OUT_BUF_LEN);
		char *kern_str = (outbuf != NULL ? esif_cmd_info(outbuf) : NULL);
		ESIF_TRACE_DEBUG("ESIF IPC Kernel Device Opened\n");
		if (NULL != kern_str) {
			// Extract just the Kernel LF Version from the result string
			extract_kernel_version(kern_str, OUT_BUF_LEN);

			// Bypass Kernel Version check for DEBUG builds
			#if defined(ESIF_ATTR_DEBUG)
			check_kernel_version = ESIF_FALSE;
			#endif

			// Validate Kernel LF version is compatible with UF version
			if (check_kernel_version == ESIF_FALSE || esif_ccb_strcmp(kern_str, ESIF_VERSION) == 0) {
				ESIF_TRACE_INFO("Kernel Version: %s\n", kern_str);
				esif_ccb_sprintf(sizeof(g_esif_kernel_version), g_esif_kernel_version, "%s", kern_str);
			}
			else {
				ESIF_TRACE_ERROR("ESIF_LF Version (%s) Incompatible with ESIF_UF Version (%s)\n", kern_str, ESIF_VERSION);
				ipc_disconnect();
				rc = ESIF_E_NOT_SUPPORTED;
			}
		}
		esif_ccb_free(outbuf);
	}
	ESIF_TRACE_EXIT_INFO_W_STATUS(rc);
	return rc;
}
Exemplo n.º 12
0
static void esif_ws_http_send_401 (int fd)
{
	char buffer[256];
	char tmpbuffer[128];
	char *fileType = "text/html";
	FILE *file_fp  = NULL;
	int len;
	struct stat st;
	int ret;


	char *fileName = "error.html";

	printf("fileName :%s\n", fileName);
	esif_ccb_fopen(&file_fp, fileName, "r");

	if (NULL == file_fp) {
		printf("failed to open file: \n");
		return;
	}

	if (esif_ccb_stat(fileName, &st) != 0) {
		printf("Could not stat file descriptor \n");
		return;
	}

	len = (long)fseek(file_fp, (off_t)0, SEEK_END);

	(void)fseek(file_fp, (off_t)0, SEEK_SET);

	(void)esif_ccb_sprintf(256, buffer, (char*)"HTTP/1.1 401 Unauthorized\n"
											   "Server: server/%d.0\nLast-Modified: %s\nDate: %s\n"
											   "Content-Type: %s\nContent-Length: %ld\nConnection: close\n\n",
						   VERSION, esif_ws_http_time_stamp(st.st_mtime, tmpbuffer), esif_ws_http_time_stamp(time(0), tmpbuffer), fileType, (long)st.st_size);

	(void)send(fd, buffer, (int)esif_ccb_strlen(buffer), 0);

	while ((ret = (int)fread(buffer, 1, 256, file_fp)) > 0)
		(void)send(fd, buffer, ret, 0);

	fclose(file_fp);
}
Exemplo n.º 13
0
eEsifError EsifActStart (EsifActPtr actionPtr)
{
	eEsifError rc = ESIF_OK;
	GetIfaceFuncPtr iface_func_ptr = NULL;
	EsifString iface_func_name     = "GetActionInterface";

	char libPath[ESIF_LIBPATH_LEN];
	esif_lib_t lib_handle = 0;

	ESIF_TRACE_DEBUG("%s name=%s\n", ESIF_FUNC, actionPtr->fLibNamePtr);
	esif_ccb_sprintf(ESIF_LIBPATH_LEN, libPath, "%s.%s",
					 esif_build_path(libPath, ESIF_LIBPATH_LEN, ESIF_DIR_PRG, actionPtr->fLibNamePtr), ESIF_LIB_EXT);

	lib_handle = esif_ccb_library_load(libPath);

	if (0 == lib_handle) {
		rc = ESIF_E_UNSPECIFIED;
		ESIF_TRACE_DEBUG("%s esif_ccb_library_load() %s failed.\n", ESIF_FUNC, libPath);
		goto exit;
	}
	ESIF_TRACE_DEBUG("%s esif_ccb_library_load() %s completed.\n", ESIF_FUNC, libPath);

	iface_func_ptr = (GetIfaceFuncPtr)
		esif_ccb_library_get_func(lib_handle, (EsifString)iface_func_name);

	if (NULL == iface_func_ptr) {
		rc = ESIF_E_UNSPECIFIED;
		ESIF_TRACE_DEBUG("%s esif_ccb_library_get_func() %s failed.\n",
						 ESIF_FUNC, iface_func_name);
		goto exit;
	}

	ESIF_TRACE_DEBUG("%s esif_ccb_library_get_func() %s completed.\n",
					 ESIF_FUNC, iface_func_name);
	rc = ActionCreate(actionPtr, iface_func_ptr);
	ESIF_TRACE_DEBUG("%s ActionCreate completed.\n", ESIF_FUNC);
exit:
	return rc;
}
Exemplo n.º 14
0
static eEsifError EsifDataLogOpenLogFile()
{
	eEsifError rc = ESIF_OK;
	EsifLogType logtype = ESIF_LOG_UI;
	char logname[35] = { 0 };
	int append = ESIF_FALSE;
	char fullpath[MAX_PATH] = { 0 };
	time_t now = time(NULL);
	struct tm time = { 0 };

	if (esif_ccb_localtime(&time, &now) == 0) {
		esif_ccb_sprintf(sizeof(logname), logname, "data_log_%04d-%02d-%02d-%02d%02d%02d.csv",
			time.tm_year + 1900, time.tm_mon + 1, time.tm_mday, time.tm_hour, time.tm_min, time.tm_sec);
	}
	EsifLogFile_Open(logtype, logname, append);
	EsifLogFile_GetFullPath(fullpath, sizeof(fullpath), logname);
	if (!EsifLogFile_IsOpen(logtype)) {
		rc = ESIF_E_IO_ERROR;
		goto exit;
	}
exit:
	return rc;
}
Exemplo n.º 15
0
static void esif_ws_cgi_redirect_output (
    char *script,
    int fd
)
{
    int current_out;
    char buffer[BUFFER_LENGTH];
    int ret;
    FILE *dataFile = NULL;
#define MAX_SIZE 100
    printf("esif_ws_cgi_redirect_output-> full_script_name: %s\n", script);


    current_out = esif_ccb_dup(1);

    if (current_out == -1) {
        perror("_dup( 1 ) failure");
        exit(1);
    }

    esif_ccb_fopen(&dataFile, "data", "w");

    if (NULL == dataFile) {
        printf("failed to open file in writing mode \n");
        return;
    }

    if (-1 == esif_ccb_dup2(dataFile, 1)) {
        perror("Can't _dup2 stdout");
        exit(1);
    }

    printf("Execute the script\n");
    system(script);

    fflush(stdout);
    fclose(dataFile);

    esif_ccb_dup3(current_out, 1);
    esif_ccb_flushall();


    esif_ccb_fopen(&dataFile, "data", "r");
    if (NULL == dataFile) {
        printf("failed to open file in readig mode: \n");
        return;
    }

    (long)fseek(dataFile, (off_t)0, SEEK_END);
    (void)fseek(dataFile, (off_t)0, SEEK_SET);

    (void)esif_ccb_sprintf(BUFFER_LENGTH, buffer, (char*)"HTTP/1.1 200 OK\n");

    (void)send(fd, buffer, (int)esif_ccb_strlen(buffer, MAX_SIZE), 0);

    while ((ret = (int)fread(buffer, 1, BUFFER_LENGTH, dataFile)) > 0)
        (void)send(fd, buffer, ret, 0);

    fclose(dataFile);

    esif_ws_server_initialize_clients();

    esif_ws_http_set_login_requested(1);
    esif_ws_http_set_authenticated(1);
}
Exemplo n.º 16
0
EsifString EsifDspMgr_SelectDsp(
	EsifDspQuery query
	)
{
	int i = 0;							// Loop index for DSP table.
	int weight = 0;						// Total weight of DSP query
	int primaryWeight = 0;				// Weight of items sufficient for selection.
	int secondaryWeight = 0;			// Weight of items allowed to sway results, but cannot stand alone.
	int heaviest = -1;					// Heaviest Row Found.
	EsifString dspNamePtr = NULL;		// DSP Name/Code To Use.
	int best = 0;						// Best Weight Possible.
	char *defaultDsp = GetDSPFromList(query.participantName); // Default DSP based on Participant Name

	/*
	** Query table for weighted match highest score wins. It is
	** unlikely that the table would change but we lock it just
	** to be sure it can't.
	*/
	
	// LOCK
	esif_ccb_read_lock(&g_dm.lock);

	for (i = 0; i < g_dm.dme_count; i++) {
		EsifDspPtr dspPtr = g_dm.dme[i].dsp_ptr;
		char busEnum[ENUM_TO_STRING_LEN] = { 0 };

		if (dspPtr == NULL) {
			continue;
		}

		esif_ccb_sprintf(ENUM_TO_STRING_LEN, busEnum, "%d", *dspPtr->bus_enum);
		
		// Primary weight indicates items that can result in a match
		primaryWeight =
			compare_and_weight_minterm(dspPtr->device_id, query.deviceId, PCI_DEVICE_ID_WEIGHT) +
			compare_and_weight_minterm(dspPtr->acpi_device, query.hid, ACPI_HID_WEIGHT) +
			compare_and_weight_minterm(dspPtr->acpi_type, query.ptype, ACPI_PTYPE_WEIGHT) +
			compare_and_weight_minterm(dspPtr->code_ptr, defaultDsp, PARTICIPANT_NAME_WEIGHT);

		// Secondary items can contribute only if at least one primary match is found
		secondaryWeight = 
			compare_and_weight_minterm(dspPtr->acpi_uid, query.uid, ACPI_UID_WEIGHT) +
			compare_and_weight_minterm(dspPtr->vendor_id, query.vendorId, PCI_VENDOR_ID_WEIGHT) +
			compare_and_weight_minterm(busEnum, query.enumerator, ENUMERATOR_TYPE_WEIGHT);

		// Items in secondary can weigh in on the results but cannot be the sole factor
		if (primaryWeight < MIN_VIABLE_DSP_WEIGHT) {
			weight = primaryWeight;
		}
		else {
			weight = primaryWeight + secondaryWeight;
		}

		ESIF_TRACE_DEBUG("DSP: %s Weight: %d\n", (esif_string) dspPtr->code_ptr, weight);

		//Keep track of row with most weight.  
		if (weight > heaviest) {
			heaviest = weight;
			dspNamePtr = dspPtr->code_ptr;
		}
	}

	// UNLOCK
	esif_ccb_read_unlock(&g_dm.lock);

	if (dspNamePtr != NULL) {
		ESIF_TRACE_DEBUG("Selected DSP: %s Score: %d of %d\n", dspNamePtr, heaviest, best);
	}
	else {
		ESIF_TRACE_ERROR("No DSP selected for %s. \n", query.participantName);
	}

	return dspNamePtr;
}
Exemplo n.º 17
0
static int esif_ws_http_process_static_pages (
	ClientRecordPtr connection,
	char *buffer,
	char *resource,
	ssize_t ret,
	char *fileType
	)
{
	struct stat st={0};
	char tmpbuffer[128]={0};
	char file_to_open[MAX_PATH]={0};
	char content_disposition[MAX_PATH]={0};
	FILE *file_fp = NULL;

	esif_build_path(file_to_open, sizeof(file_to_open), ESIF_PATHTYPE_UI, resource, NULL);
	esif_ccb_fopen(&file_fp, (esif_string)file_to_open, (esif_string)"rb");
	
	// Log file workaround: If not found in HTML folder, look in LOG folder
	if (NULL == file_fp) {
		char logpath[MAX_PATH]={0};
		esif_build_path(logpath, sizeof(logpath), ESIF_PATHTYPE_LOG, resource, NULL);
		esif_ccb_fopen(&file_fp, (esif_string)logpath, (esif_string)"rb");
		if (NULL != file_fp) 
			esif_ccb_strcpy(file_to_open, logpath, sizeof(file_to_open));
	}
	
	ESIF_TRACE_DEBUG("HTTP: file=%s, type=%s\n", file_to_open, fileType);
	if (NULL == file_fp) {
		ESIF_TRACE_DEBUG("failed to open file: %s\n", file_to_open);
		return 404;
	}

	if (esif_ccb_stat(file_to_open, &st) != 0) {
		ESIF_TRACE_DEBUG("Could not stat file descriptor \n");
		fclose(file_fp);
		return 404;
	}

	fseek(file_fp, (off_t)0, SEEK_END);
	fseek(file_fp, (off_t)0, SEEK_SET);

	// Add Content-Disposition header to prompt user with Save-As Dialog if unknown file type
	if (esif_ccb_strcmp(fileType, UNKNOWN_MIME_TYPE) == 0) {
		esif_ccb_sprintf(sizeof(content_disposition), content_disposition,  "Content-Disposition: attachment; filename=\"%s\";\n", resource);
	}

	esif_ccb_sprintf(WS_BUFFER_LENGTH, buffer,	
					"HTTP/1.1 200 OK\n"
					"Server: ESIF_UF/%s\n"
					"Last-Modified: %s\n"
					"Date: %s\n"
					"Content-Type: %s\n"
					"Content-Length: %ld\n"
					"%s"
					"Connection: close\n"
					"\n",
				ESIF_UF_VERSION,
				esif_ws_http_time_stamp(st.st_mtime, tmpbuffer),
				esif_ws_http_time_stamp(time(0), tmpbuffer), 
				fileType, 
				(long)st.st_size, 
				content_disposition);

	send(connection->socket, buffer, (int)esif_ccb_strlen(buffer, WS_BUFFER_LENGTH), ESIF_WS_SEND_FLAGS);
	while ((ret = (int)fread(buffer, 1, WS_BUFFER_LENGTH, file_fp)) > 0) {
		send(connection->socket, buffer, (int)ret, ESIF_WS_SEND_FLAGS);
	}
	fclose(file_fp);

	return 0;
}
Exemplo n.º 18
0
int EsifTraceMessage(
	esif_tracemask_t module, 
	int level, 
	const char *func, 
	const char *file, 
	int line, 
	const char *msg, 
	...)
{
	int rc=0;
	char *appname  = "";
	char *fmtDetail= "%s%s:[<%s>%s@%s#%d]<%llu ms>: ";
	char *fmtInfo  = "%s%s:[<%s>]<%llu ms>: ";
	const char *sep=NULL;
	size_t fmtlen=esif_ccb_strlen(msg, 0x7FFFFFFF);
	int  detailed_message = (level >= DETAILED_TRACELEVEL ? ESIF_TRUE : ESIF_FALSE);
	va_list args;
	esif_ccb_time_t msec = 0;
	enum esif_tracemodule moduleid = ESIF_TRACEMODULE_DEFAULT;
	const char *module_name = NULL;

	esif_ccb_system_time(&msec);

	while (module >>= 1)
		moduleid++;
	module_name = EsifTraceModule_ToString(moduleid);

	level = esif_ccb_min(level, ESIF_TRACELEVEL_MAX);
	level = esif_ccb_max(level, ESIF_TRACELEVEL_FATAL);
	if ((sep = strrchr(file, *ESIF_PATH_SEP)) != NULL)
		file = sep+1;

	// Do not log function/file/line information for DPTF app interface messages logged from EsifSvcWriteLog
	if (moduleid == ESIF_TRACEMODULE_DPTF) {
		detailed_message = ESIF_FALSE;
	}

	if (g_traceinfo[level].routes & ESIF_TRACEROUTE_CONSOLE) {
		if (detailed_message)
			rc =  CMD_CONSOLE(fmtDetail, appname, g_traceinfo[level].label, module_name, func, file, line, msec);
		else
			rc =  CMD_CONSOLE(fmtInfo, appname, g_traceinfo[level].label, module_name, msec);
		va_start(args, msg);
		rc += EsifConsole_WriteConsole(msg, args);
		va_end(args);

		if (fmtlen && msg[fmtlen-1]!='\n')
			CMD_CONSOLE("\n");
	}

	if (g_traceinfo[level].routes & ESIF_TRACEROUTE_LOGFILE && EsifLogFile_IsOpen(ESIF_LOG_TRACE)) {
		time_t now=0;
		char timestamp[MAX_CTIME_LEN]={0};

		time(&now);
		esif_ccb_ctime(timestamp, sizeof(timestamp), &now);
		timestamp[20] = 0; // truncate year

		if (detailed_message)
			rc = EsifLogFile_Write(ESIF_LOG_TRACE, fmtDetail, timestamp + 4, g_traceinfo[level].label, module_name, func, file, line, msec);
		else
			rc =  EsifLogFile_Write(ESIF_LOG_TRACE, fmtInfo, timestamp+4, g_traceinfo[level].label, module_name, msec);
		va_start(args, msg);
		rc += EsifLogFile_WriteArgsAppend(ESIF_LOG_TRACE, "\n", msg, args);
		va_end(args);
	}

#ifdef ESIF_ATTR_OS_WINDOWS
	if (g_traceinfo[level].routes & (ESIF_TRACEROUTE_DEBUGGER)) {
		size_t  msglen=0;
		char *buffer=0;
		int  offset=0;

		va_start(args, msg);
		msglen = esif_ccb_vscprintf(msg, args) + esif_ccb_strlen(g_traceinfo[level].label, MAX_PATH) + esif_ccb_strlen(appname, MAX_PATH) + esif_ccb_strlen(func, MAX_PATH) + esif_ccb_strlen(file, MAX_PATH) + esif_ccb_strlen(module_name, MAX_PATH) + 22;
		va_end(args);
		msglen += (detailed_message ? esif_ccb_strlen(fmtDetail, MAX_PATH) : esif_ccb_strlen(fmtInfo, MAX_PATH));
		buffer = (char *)esif_ccb_malloc(msglen);

		if (NULL != buffer) {
			if (detailed_message)
				rc =  esif_ccb_sprintf(msglen, buffer, fmtDetail, appname, g_traceinfo[level].label, module_name, func, file, line, msec);
			else
				rc =  esif_ccb_sprintf(msglen, buffer, fmtInfo, appname, g_traceinfo[level].label, module_name, msec);

			offset = rc;
			va_start(args, msg);
			rc += esif_ccb_vsprintf(msglen-offset, buffer+offset, msg, args);
			va_end(args);
			if (rc && buffer[rc-1]!='\n')
				esif_ccb_strcat(buffer, "\n", msglen);

			OutputDebugStringA(buffer); 
			esif_ccb_free(buffer);
		}
	}
	if (g_traceinfo[level].routes & (ESIF_TRACEROUTE_EVENTLOG)) {
		size_t  msglen=0;
		char *buffer=0;
		char *replaced=0;
		int  offset=0;
		int  backset=0;
		WORD eventType;

		appname  = "";
		fmtInfo  = "%sESIF(%s) TYPE: %s MODULE: %s TIME %llu ms\n\n";
		fmtDetail= "%sESIF(%s) TYPE: %s MODULE: %s FUNC: %s FILE: %s LINE: %d TIME: %llu ms\n\n";
		backset  = 0;

		va_start(args, msg);
		msglen = esif_ccb_vscprintf(msg,args) + esif_ccb_strlen(g_traceinfo[level].label, MAX_PATH) + esif_ccb_strlen(appname, MAX_PATH) + esif_ccb_strlen(func, MAX_PATH) + esif_ccb_strlen(file, MAX_PATH) + esif_ccb_strlen(module_name, MAX_PATH) + 32;
		va_end(args);
		msglen += (detailed_message ? esif_ccb_strlen(fmtDetail, MAX_PATH) : esif_ccb_strlen(fmtInfo, MAX_PATH));
		buffer = (char *)esif_ccb_malloc(msglen);

		if (NULL != buffer) {
			if (detailed_message)
				rc = esif_ccb_sprintf(msglen, buffer, fmtDetail, appname, ESIF_UF_VERSION, g_traceinfo[level].label, module_name, func, file, line, msec);
			else
				rc = esif_ccb_sprintf(msglen, buffer, fmtInfo, appname, ESIF_UF_VERSION, g_traceinfo[level].label, module_name, msec);

			if (backset && backset < rc)
				buffer[rc-backset-1] = 0;
			offset = rc-backset;
			va_start(args, msg);
			rc += esif_ccb_vsprintf(msglen-(offset+backset), buffer+offset+backset, msg, args);
			va_end(args);
			if (rc && buffer[rc-1]=='\n')
				buffer[--rc] = 0;

			switch (g_traceinfo[level].level) {
			case ESIF_TRACELEVEL_FATAL:
			case ESIF_TRACELEVEL_ERROR:
				eventType = EVENTLOG_ERROR_TYPE;
				break;
			case ESIF_TRACELEVEL_WARN:
				eventType = EVENTLOG_WARNING_TYPE;
				break;
			case ESIF_TRACELEVEL_INFO:
			case ESIF_TRACELEVEL_DEBUG:
			default:
				eventType = EVENTLOG_INFORMATION_TYPE;
				break;
			}
			// Escape any "%" in message before writing to EventLog
			if ((replaced = esif_str_replace(buffer, "%", "%%")) != NULL) {
				esif_ccb_free(buffer);
				buffer = replaced;
				replaced = NULL;
			}
			report_event_to_event_log(CATEGORY_GENERAL, eventType, buffer);
			esif_ccb_free(buffer);
		}
	}
#endif
#ifdef ESIF_ATTR_OS_LINUX
	if (g_traceinfo[level].routes & (ESIF_TRACEROUTE_EVENTLOG|ESIF_TRACEROUTE_DEBUGGER)) {
		size_t  msglen=0;
		char *buffer=0;
		int  offset=0;
		int priority;

		fmtDetail= "%s:[<%s>%s@%s#%d]<%llu ms>: ";
		fmtInfo  = "%s:[<%s>]<%llu ms>: ";

		va_start(args, msg);
		msglen = esif_ccb_vscprintf(msg,args) + esif_ccb_strlen(g_traceinfo[level].label, MAX_PATH) + esif_ccb_strlen(func, MAX_PATH) + esif_ccb_strlen(file, MAX_PATH) + esif_ccb_strlen(module_name, MAX_PATH) + 22;
		va_end(args);
		msglen += (detailed_message ? esif_ccb_strlen(fmtDetail, MAX_PATH) : esif_ccb_strlen(fmtInfo, MAX_PATH));
		buffer = (char *)esif_ccb_malloc(msglen);

		if (NULL != buffer) {
			char *lf;
			if (detailed_message)
				rc =  esif_ccb_sprintf(msglen, buffer, fmtDetail, g_traceinfo[level].label, module_name, func, file, line, msec);
			else
				rc =  esif_ccb_sprintf(msglen, buffer, fmtInfo, g_traceinfo[level].label, module_name, msec);

			offset = rc;
			va_start(args, msg);
			rc += esif_ccb_vsprintf(msglen-offset, buffer+offset, msg, args);
			va_end(args);
			if (rc && buffer[rc-1]=='\n')
				buffer[--rc] = 0;

			while ((lf = esif_ccb_strchr(buffer, '\n')) != NULL)
				*lf = '\t';

			switch (g_traceinfo[level].level) {
			case ESIF_TRACELEVEL_FATAL:
				priority = ESIF_PRIORITY_FATAL;
				break;
			case ESIF_TRACELEVEL_ERROR:
				priority = ESIF_PRIORITY_ERROR;
				break;
			case ESIF_TRACELEVEL_WARN:
				priority = ESIF_PRIORITY_WARNING;
				break;
			case ESIF_TRACELEVEL_INFO:
				priority = ESIF_PRIORITY_INFO;
				break;
			case ESIF_TRACELEVEL_DEBUG:
			default:
				priority = ESIF_PRIORITY_DEBUG;
				break;
			}
		#ifdef ESIF_ATTR_OS_ANDROID
			__android_log_write(priority, IDENT, buffer);
		#else
			openlog(IDENT, OPTION, FACILITY);
			syslog(priority, "%s", buffer);
			closelog();
		#endif
			esif_ccb_free(buffer);
		}
	}
#endif
	return rc;
}
Exemplo n.º 19
0
//
// PUBLIC INTERFACE---------------------------------------------------------------------
//
char *EsifShellCmdDataLog(EsifShellCmdPtr shell)
{
	eEsifError rc = ESIF_OK;
	int argc = shell->argc;
	char **argv = shell->argv;
	char *output = shell->outbuf;
	char participantList[MAX_LOG_LINE] = { 0 };

	/*
	 * Serialize access to the datalog state.
	 */
	while (atomic_set(&g_dataLogLock, ESIF_TRUE)) {
		esif_ccb_sleep_msec(ESIF_DATALOG_LOCK_SLEEP_MS);
	}

	if (argc < 2) {
		esif_ccb_sprintf(OUT_BUF_LEN, output, "Data logging is: %s\n", (EsifDataIsLogStarted() ? "started" : "stopped"));
	}
	else if (esif_ccb_stricmp(argv[1], "start") == 0) {

		if (EsifDataIsLogStarted()){
			esif_ccb_sprintf(OUT_BUF_LEN, output, "Data logging is already started.\n");
			goto exit;
		}

		g_dataLogInterval = DEFAULT_STATUS_LOG_INTERVAL;
		if (argc > 2) {
			if ((int)esif_atoi(argv[2]) >= MIN_STATUS_LOG_INTERVAL) {
				g_dataLogInterval = (esif_ccb_time_t)esif_atoi(argv[2]);
			}
			else {
				esif_ccb_sprintf(OUT_BUF_LEN, output, "Invalid sampling period specified (minimum is %d ms).\n", MIN_STATUS_LOG_INTERVAL);
				goto exit;
			}
		}
		if (argc > 3) {
			esif_ccb_sprintf(sizeof(participantList), participantList, "%s", argv[3]);
		}

		rc = EsifDataLogValidateParticipantList(participantList);
		if (rc != ESIF_OK) {
			esif_ccb_sprintf(OUT_BUF_LEN, output, "There was a problem with your participant list. You may have selected invalid participants, or too many participants. \n");
			goto exit;
		}
		rc = EsifDataLogOpenLogFile();
		if (rc != ESIF_OK) {
			esif_ccb_sprintf(OUT_BUF_LEN, output, "Error opening log file... \n");
			goto exit;
		}
		esif_ccb_sprintf(OUT_BUF_LEN, output, "Data logging starting... \n");

		EsifDataLogStart();
	}
	else if (esif_ccb_stricmp(argv[1], "schedule") == 0) {
		UInt32 startTime = 1000;

		/* initialize */
		if (dataLogContextPtr == NULL) {
			dataLogContextPtr = (struct dataLogContext *)esif_ccb_malloc(sizeof(struct dataLogContext));
			if (dataLogContextPtr == NULL) {
				rc = ESIF_E_NO_MEMORY;
				goto exit;
			}
			dataLogContextPtr->dataLogScheduleTimer = (esif_ccb_timer_t *) esif_ccb_malloc(sizeof(esif_ccb_timer_t));
			if (dataLogContextPtr->dataLogScheduleTimer == NULL) {
				rc = ESIF_E_NO_MEMORY;
				goto exit;
			}
			dataLogContextPtr->dataLogParticipantList = NULL;
		}

		dataLogContextPtr->dataLogInterval = DEFAULT_STATUS_LOG_INTERVAL;
		/* start time (in ms from now) */
		if (argc > 2) {
			if ((int) esif_atoi(argv[2]) >= MIN_STATUS_LOG_SCHEDULE) {
				startTime = (esif_ccb_time_t) esif_atoi(argv[2]);
			}
			else {
				esif_ccb_sprintf(OUT_BUF_LEN, output, "Invalid schedule time specified (minimum is %d ms).\n", MIN_STATUS_LOG_INTERVAL);
				goto exit;
			}
		}
		/* log interval */
		if (argc > 3) {
			if ((int) esif_atoi(argv[3]) >= MIN_STATUS_LOG_INTERVAL) {
				dataLogContextPtr->dataLogInterval = (esif_ccb_time_t) esif_atoi(argv[3]);
			}
			else {
				esif_ccb_sprintf(OUT_BUF_LEN, output, "Invalid sampling period specified (minimum is %d ms).\n", MIN_STATUS_LOG_INTERVAL);
				goto exit;
			}
		}
		if (argc > 4) {
			dataLogContextPtr->dataLogParticipantList = esif_ccb_strdup(argv[4]);
			if (dataLogContextPtr->dataLogParticipantList == NULL) {
				rc = ESIF_E_NO_MEMORY;
				goto exit;
			}
		}

		rc = esif_ccb_timer_init(dataLogContextPtr->dataLogScheduleTimer, (esif_ccb_timer_cb) EsifDataLogSchedule, NULL);
		if (ESIF_OK != rc) {
			esif_ccb_sprintf(OUT_BUF_LEN, output, "Error starting timer... \n");
			goto exit;
		}
		rc = esif_ccb_timer_set_msec(dataLogContextPtr->dataLogScheduleTimer, startTime);
		esif_ccb_sprintf(OUT_BUF_LEN, output, "Data logging scheduled for start in %d ms at an interval of %d... \n", startTime, dataLogContextPtr->dataLogInterval);
		
	}
	else if (esif_ccb_stricmp(argv[1], "stop") == 0) {
		EsifDataLogStop();
		esif_ccb_sprintf(OUT_BUF_LEN, output, "Data logging stopped...\n");
		g_dataLogActive = ESIF_FALSE;
	}
	else {
		esif_ccb_sprintf(OUT_BUF_LEN, output, "Invalid parameter specified\n");
	}
exit:
	atomic_set(&g_dataLogLock, ESIF_FALSE);
	return output;
}
Exemplo n.º 20
0
static int esif_ws_http_server_static_pages (
	char *buffer,
	char *resource,
	int fd,
	ssize_t ret,
	char *fileType
	)
{
	struct stat st;
	char tmpbuffer[128];
	char file_to_open[1000];
	FILE *file_fp = NULL;
	#define MAX_SIZE 200


	esif_ccb_memcpy(file_to_open, g_server_root, esif_ccb_strlen(g_server_root, MAX_SIZE));
	file_to_open[esif_ccb_strlen(g_server_root, MAX_SIZE)] = '\0';
	// printf("file to open after esif_ccb_memcpy: %s\n", file_to_open);
	// printf("resource : %s\n", resource);

#ifdef ESIF_ATTR_OS_WINDOWS

	strcat_s((esif_string)file_to_open, 1000, resource);
	esif_ccb_fopen(&file_fp, (esif_string)file_to_open, (esif_string)"rb");
#else
	strcat((esif_string)file_to_open, resource);
	esif_ccb_fopen(&file_fp, (esif_string)file_to_open, (esif_string)"r");
#endif
	printf("file to open: %s\n", file_to_open);
	printf("file type: %s\n", fileType);


	if (NULL == file_fp) {
		printf("failed to open file: %s\n", file_to_open);
		return 404;
	}

	if (esif_ccb_stat(file_to_open, &st) != 0) {
		printf("Could not stat file descriptor \n");
		fclose(file_fp);
		return 404;
	}


	(long)fseek(file_fp, (off_t)0, SEEK_END);
	(void)fseek(file_fp, (off_t)0, SEEK_SET);

	if (!strcmp(fileType, "text/xml")) {
		(void)esif_ccb_sprintf(BUFFER_LENGTH, buffer, (char*)"HTTP/1.1 200 OK\n<?xml version==\"1.0\" encoding=\"utf-8\"?>\n"
															 "Server: server/%d.0\n"
															 "Content-Type: %s\nContent-Length: %ld\nConnection: close\n\n",
							   VERSION, fileType, (long)st.st_size);
	} else {
		(void)esif_ccb_sprintf(BUFFER_LENGTH, buffer, (char*)"HTTP/1.1 200 OK\n"
															 "Server: server/%d.0\nLast-Modified: %s\nDate: %s\n"
															 "Content-Type: %s\nContent-Length: %ld\nConnection: close\n\n",
							   VERSION,
							   esif_ws_http_time_stamp(st.st_mtime, tmpbuffer), esif_ws_http_time_stamp(time(0), tmpbuffer), fileType, (long)st.st_size);
	}

	(void)send(fd, buffer, (int)esif_ccb_strlen(buffer, MAX_SIZE), 0);
	while ((ret = (int)fread(buffer, 1, BUFFER_LENGTH, file_fp)) > 0)

		(void)send(fd, buffer, ret, 0);
	fclose(file_fp);

	return 0;
}
Exemplo n.º 21
0
/*
 * This function processes the socket when it is in the "opening" state
 */
static eEsifError esif_ws_client_open_client(
	ClientRecordPtr clientPtr,
	char *bufferPtr,
	size_t bufferSize,
	size_t messageLength
	)
{
	eEsifError result = ESIF_OK;
	FrameType frameType;
	size_t frameSize = 0;

	ESIF_ASSERT(clientPtr->state == STATE_OPENING);
	ESIF_ASSERT(messageLength > 0);

	ESIF_TRACE_DEBUG("Socket in its opening state\n");
	/*Determine the initial frame type:  http frame type or websocket frame type */
	frameType = esif_ws_socket_get_initial_frame_type(bufferPtr, messageLength, &clientPtr->prot);

	if ((INCOMPLETE_FRAME == frameType) ||  (ERROR_FRAME == frameType)) {
		if (INCOMPLETE_FRAME == frameType) {
			ESIF_TRACE_DEBUG("Incomplete frame received\n");
		} else {
			ESIF_TRACE_DEBUG("Improper format for frame\n");
		}

		/*
		 * If the socket frame type is in error or is incomplete and happens to
		 * be in its opening state, send a message to the client that the request is bad
		 */
		frameSize = esif_ccb_sprintf(bufferSize,
			(char*)bufferPtr,
			"HTTP/1.1 400 Bad Request\r\n"
			"Content-Type: text/html\r\n\r\n"
			"<html>"
			"<head></head>"
			"  <body>"
			"    ERROR: HTTP/1.1 400 Bad Request"
			"  </body>"
			"</html>");
		
		esif_ws_client_write_to_socket(clientPtr, bufferPtr, frameSize);
		result =  ESIF_E_WS_DISC;
		goto exit;
	}

	if (OPENING_FRAME == frameType) {
		if (esif_ws_socket_build_protocol_change_response(&clientPtr->prot, bufferPtr, bufferSize, &frameSize) != 0)	{
			ESIF_TRACE_DEBUG("Unable to build response header\n");
			result =   ESIF_E_WS_DISC;
			goto exit;
		}

		if (esif_ws_client_write_to_socket(clientPtr, bufferPtr, frameSize) == EXIT_FAILURE) {
			result =   ESIF_E_WS_DISC;
			goto exit;
		}

		/**************************** This is a now a websocket connection ****************************/
		clientPtr->state = STATE_NORMAL;
	}

	if (HTTP_FRAME == frameType) {				
		result = esif_ws_http_process_reqs(clientPtr, g_ws_http_buffer, messageLength);
	}
exit:
	return result;
}
Exemplo n.º 22
0
// Write DataVault to Disk
eEsifError DataVault_WriteVault (DataVaultPtr self)
{
	eEsifError rc = ESIF_E_NOT_FOUND;
	DataVaultHeader header;
	struct esif_ccb_file dv_file    = {0};
	struct esif_ccb_file dv_filebak = {0};
	IOStreamPtr vault    = 0;
	IOStreamPtr vaultBak = 0;
	u32 idx;

	if (FLAGS_TEST(self->flags, ESIF_SERVICE_CONFIG_STATIC | ESIF_SERVICE_CONFIG_READONLY)) {
		return ESIF_E_READONLY;
	}

	// TODO: Locking
	vault = IOStream_Create();
	if (!vault) {
		return ESIF_E_NO_MEMORY;
	}

	// If any rows contain NOCACHE PERSIST values, we need to make a copy the original DataVault while creating the new one
	// esif_ccb_sprintf(MAX_PATH, dv_file.filename, "%s%s", esif_build_path(dv_file.filename, MAX_PATH, NULL, self->name), ESIFDV_FILEEXT);
	esif_ccb_sprintf(MAX_PATH, dv_file.filename, "%s%s%s", ESIFDV_DIR, self->name, ESIFDV_FILEEXT);

	for (idx = 0; idx < self->cache->size; idx++)
		if (FLAGS_TESTALL(self->cache->elements[idx].flags, ESIF_SERVICE_CONFIG_NOCACHE | ESIF_SERVICE_CONFIG_PERSIST) &&
			self->cache->elements[idx].value.buf_len == 0) {
			struct stat filebak_stat = {0};
            esif_ccb_sprintf(MAX_PATH, dv_filebak.filename, "%s%s%s", ESIFDV_DIR, self->name, ESIFDV_BAKFILEEXT);

			// Delete BAK file if it exists
			if (esif_ccb_stat(dv_filebak.filename, &filebak_stat) == 0) {
				esif_ccb_unlink(dv_filebak.filename);
			}
			if (esif_ccb_rename(dv_file.filename, dv_filebak.filename) == 0) {
				if ((vaultBak = IOStream_Create()) == NULL) {
					rc = ESIF_E_NO_MEMORY;
				}
				if (!vaultBak || IOStream_OpenFile(vaultBak, dv_filebak.filename, "rb") != 0) {
					IOStream_Destroy(vault);
					IOStream_Destroy(vaultBak);
					return rc;
				}
			}
			break;
		}

	// Create DataVault, Overwrite if necessary
	IOStream_SetFile(vault, self->stream->file.name, "wb");
	if (IOStream_Open(vault) != 0) {
		if (vaultBak) {
			IOStream_Destroy(vaultBak);
			esif_ccb_unlink(dv_filebak.filename);
		}
		IOStream_Destroy(vault);
		return rc;
	}

	// Create File Header
	memset(&header, 0, sizeof(header));
	esif_ccb_memcpy(&header.signature, ESIFDV_SIGNATURE, sizeof(header.signature));
	header.headersize = sizeof(header);
	header.version    = ESIFDV_VERSION(ESIFDV_MAJOR_VERSION, ESIFDV_MINOR_VERSION, ESIFDV_REVISION);
	header.flags = 0;	// TODO: get from self->flags

	// Write File Header
	IOStream_Seek(vault, 0, SEEK_SET);
	IOStream_Write(vault, &header, sizeof(header));
	rc = ESIF_OK;

	// Write All Persisted Rows from Sorted List to DataVault
	for (idx = 0; idx < self->cache->size; idx++) {
		DataCacheEntryPtr keypair = &self->cache->elements[idx];
		if (keypair->flags & ESIF_SERVICE_CONFIG_PERSIST) {
			UInt8 *buffer     = 0;
			UInt32 buffer_len = 0;
			UInt32 byte = 0;

			IOStream_Write(vault, &keypair->flags, sizeof(keypair->flags));
			IOStream_Write(vault, &keypair->key.data_len, sizeof(keypair->key.data_len));
			IOStream_Write(vault, keypair->key.buf_ptr, keypair->key.data_len);

			IOStream_Write(vault, &keypair->value.type, sizeof(keypair->value.type));
			IOStream_Write(vault, &keypair->value.data_len, sizeof(keypair->value.data_len));

			// Read NOCACHE Entries from Backup file
			if (keypair->flags & ESIF_SERVICE_CONFIG_NOCACHE) {
				size_t offset = IOStream_GetOffset(vault);

				// Read Block from BAK file
				if (keypair->value.buf_len == 0) {
					size_t bakoffset = (size_t)keypair->value.buf_ptr;
					buffer     = (UInt8*)esif_ccb_malloc(keypair->value.data_len);
					buffer_len = keypair->value.data_len;
					if (!buffer) {
						rc = ESIF_E_NO_MEMORY;
						break;
					}
					if (IOStream_Seek(vaultBak, bakoffset, SEEK_SET) != 0 || IOStream_Read(vaultBak, buffer, buffer_len) != buffer_len) {
						esif_ccb_free(buffer);
						rc = ESIF_E_UNSPECIFIED;// TODO: ESIF_E_IOERROR;
						break;
					}
					keypair->value.buf_ptr = (void*)offset;
				}
				// Convert internal storage to NOCACHE
				else {
					buffer     = (UInt8*)keypair->value.buf_ptr;
					buffer_len = keypair->value.data_len;
					keypair->value.buf_ptr = (void*)offset;
					keypair->value.buf_len = 0;
				}
			}

			// Encrypt Data?
			if (keypair->flags & ESIF_SERVICE_CONFIG_ENCRYPT) {
				if (!buffer) {
					buffer     = (UInt8*)esif_ccb_malloc(keypair->value.data_len);
					buffer_len = keypair->value.data_len;
					if (!buffer) {
						rc = ESIF_E_NO_MEMORY;
						break;
					}
				}
				for (byte = 0; byte < keypair->value.data_len; byte++)
					buffer[byte] = ~((UInt8*)(keypair->value.buf_ptr))[byte];
			}

			if (buffer) {
				IOStream_Write(vault, buffer, buffer_len);
				esif_ccb_free(buffer);
			} else {
				IOStream_Write(vault, keypair->value.buf_ptr, keypair->value.data_len);
			}
		}
	}

	// Rollback on Error
	if (rc != ESIF_OK) {
		IOStream_Destroy(vaultBak);
		IOStream_Destroy(vault);
		esif_ccb_unlink(dv_file.filename);
		IGNORE_RESULT(esif_ccb_rename(dv_filebak.filename, dv_file.filename));
		return rc;
	}
	// Remove BAK file and Commit
	if (vaultBak) {
		IOStream_Close(vaultBak);
		esif_ccb_unlink(dv_filebak.filename);
		IOStream_Destroy(vaultBak);
	}
	IOStream_Close(vault);
	IOStream_Destroy(vault);
	return rc;
}
Exemplo n.º 23
0
void esif_ws_server_execute_rest_cmd(
	const char *dataPtr,
	const size_t dataSize
	)
{
	char *command_buf = NULL;

	if (atomic_read(&g_ws_quit))
		return;

	command_buf = strchr(dataPtr, ':');
	if (NULL != command_buf) {
		u32 msg_id = atoi(dataPtr);
		*command_buf = 0;
		command_buf++;

		// Ad-Hoc UI Shell commands begin with "0:", so verify ESIF shell is enabled and command is valid
		if (msg_id == 0 || g_ws_restricted) {
			char *response = NULL;
			if (msg_id == 0 && !g_shell_enabled) {
				response = "Shell Disabled";
			}
			else {
				static char *whitelist[] = { "status", "participants", NULL };
				static char *blacklist[] = { "shell", "web", "exit", "quit", NULL };
				Bool blocked = ESIF_FALSE;
				int j = 0;
				if (g_ws_restricted) {
					for (j = 0; whitelist[j] != NULL; j++) {
						if (esif_ccb_strnicmp(command_buf, whitelist[j], esif_ccb_strlen(whitelist[j], MAX_PATH)) == 0) {
							break;
						}
					}
					if (whitelist[j] == NULL) {
						blocked = ESIF_TRUE;
					}
				}
				else {
					for (j = 0; blacklist[j] != NULL; j++) {
						if (esif_ccb_strnicmp(command_buf, blacklist[j], esif_ccb_strlen(blacklist[j], MAX_PATH)) == 0) {
							blocked = ESIF_TRUE;
							break;
						}
					}
				}
				if (blocked) {
					response = "Unsupported Command";
				}
			}
			// Exit if shell or command unavailable
			if (response) {
				char buffer[MAX_PATH] = { 0 };
				esif_ccb_sprintf(sizeof(buffer), buffer, "%d:%s", msg_id, response);
				esif_ccb_free(g_rest_out);
				g_rest_out = esif_ccb_strdup(buffer);
				goto exit;
			}
		}

		// Lock Shell so we can capture output before another thread executes another command
#ifdef ESIF_ATTR_SHELL_LOCK
		esif_ccb_mutex_lock(&g_shellLock);
#endif
		if (!atomic_read(&g_ws_quit)) {
			EsifString cmd_results = esif_shell_exec_command(command_buf, dataSize, ESIF_TRUE);
			if (NULL != cmd_results) {
				size_t out_len = esif_ccb_strlen(cmd_results, OUT_BUF_LEN) + 12;
				esif_ccb_free(g_rest_out);
				g_rest_out = (EsifString) esif_ccb_malloc(out_len);
				if (g_rest_out) {
					esif_ccb_sprintf(out_len, g_rest_out, "%u:%s", msg_id, cmd_results);
				}
			}
		}
#ifdef ESIF_ATTR_SHELL_LOCK
		esif_ccb_mutex_unlock(&g_shellLock);
#endif
	}

exit:
	return;
}
Exemplo n.º 24
0
// Automatically Load all Static DataVaults and *.dv files in the current folder into the DataBank
eEsifError DataBank_LoadDataVaults (DataBankPtr self)
{
	eEsifError rc = ESIF_OK;
	esif_ccb_file_find_handle find_handle;
	esif_string file_path = 0;
	char file_pattern[MAX_PATH];
	char file_path_buf[MAX_PATH] = {0};
	struct esif_ccb_file *ffd_ptr;
	UInt32 idx;

	ASSERT(self);
	esif_ccb_lock_init(&self->lock);

	// TODO: Locking

	// Import all Static DataVaults into ReadOnly DataVaults
	for (idx = 0; g_StaticDataVaults[idx].name; idx++) {
		DataVaultPtr DB = DataBank_OpenNameSpace(self, g_StaticDataVaults[idx].name);
		if (DB) {
			IOStream_SetMemory(DB->stream, g_StaticDataVaults[idx].buffer, g_StaticDataVaults[idx].buf_len);
			DB->flags |= (ESIF_SERVICE_CONFIG_READONLY | ESIF_SERVICE_CONFIG_NOCACHE);
			DataVault_ReadVault(DB);
		}
	}

	// Create ESIFDV_DIR if it doesn't exit (only 1 level deep for now)
	esif_ccb_makepath(ESIFDV_DIR);

	// Import all matching *.dv files into ReadWrite DataVaults
	esif_ccb_strcpy(file_path_buf, ESIFDV_DIR, sizeof(file_path_buf));
	file_path = file_path_buf;
	esif_ccb_sprintf(MAX_PATH, file_pattern, "*%s", ESIFDV_FILEEXT);
	ffd_ptr   = (struct esif_ccb_file*)esif_ccb_malloc(sizeof(*ffd_ptr));
	if (NULL == ffd_ptr) {
		return ESIF_E_NO_MEMORY;
	}

	find_handle = esif_ccb_file_enum_first(file_path, file_pattern, ffd_ptr);
	if (INVALID_HANDLE_VALUE == find_handle) {
		rc = ESIF_OK;	// No Persisted DataVaults found
	} else {
		do {
			struct esif_ccb_file dv_file = {0};
			DataVaultPtr DB = 0;

			// Read DataVault File, unless it's already been loaded as a Static DataVault
			if (esif_ccb_strlen(ffd_ptr->filename, MAX_PATH) > sizeof(ESIFDV_FILEEXT)) {
				ffd_ptr->filename[esif_ccb_strlen(ffd_ptr->filename, MAX_PATH) - (sizeof(ESIFDV_FILEEXT) - 1)] = 0;	// Truncate ".dv" extension
				if (DataBank_GetNameSpace(self, ffd_ptr->filename) == NULL) {
					DB = DataBank_OpenNameSpace(self, ffd_ptr->filename);
					if (DB) {
						esif_ccb_sprintf(MAX_PATH, dv_file.filename, "%s%s%s", file_path, DB->name, ESIFDV_FILEEXT);
						IOStream_SetFile(DB->stream, dv_file.filename, "rb");
						DataVault_ReadVault(DB);
					}
				}
			}
		} while (esif_ccb_file_enum_next(find_handle, file_pattern, ffd_ptr));
		esif_ccb_file_enum_close(find_handle);
	}
	esif_ccb_free(ffd_ptr);
	return rc;
}